title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C++ Library - <list>
List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data. List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time. Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator. Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined. Below is definition of std::list from <list> header file template < class T, class Alloc = allocator<T> > class list; T − Type of the element contained. T may be substituted by any other data type including user-defined type. T − Type of the element contained. T may be substituted by any other data type including user-defined type. Alloc − Type of allocator object. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent. Alloc − Type of allocator object. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent. Following member types can be used as parameters or return type by member functions. Below is list of all methods from <list> header. Constructs an empty list with zero elements. Constructs a new list with n elements and assigns val to each element of list. Constructs a new list with n elements and assign zero value to each element of list. Constructs a list with as many elements as in range of first to last. Constructs a list with copy of each elements present in existing list. Constructs a list with the contents of other using move semantics. Constructs a list with the contents of other using move semantics. Destroys list object by deallocating it's memory. Assigns new value to list by replacing old ones. Assigns new values to list by replacing old ones. Assigns new values to list by replacing old ones. Returns a reference to the last element of the list. Returns a random access iterator which points to the first element of the list. Returns a constant random access iterator which points to the beginning of the list. Returns a constant random access iterator which points to the end of the list. Destroys the list by removing all elements from the list and sets size of list to zero. Returns a constant reverse iterator which points to the last element of the list. Returns a constant reverse iterator which points to the theoretical element preceding the first element in the list. Extends list by inserting new element at a given position. Inserts new element at the end of list and increases size of list by one. Inserts new element at the beginning of the list and increases size of list by one. Tests whether list is empty or not. Returns a random access iterator which points to the last element of the list. Removes single element from the the list. Removes range of element from the the list. Returns a reference to the first element of the list. Returns an allocator associated with list Extends iterator by inserting new element at position in list. Extends list by inserting new elements in the container. Extends list by inserting new elements in the container. Extends list by inserting new element in the container. Extends list by inserting new elements in the container Returns the maximum number of elements can be held by list. Merges two sorted lists into one. Merges two sorted lists into one. Merges two sorted lists into one by using move semantics. Merges two sorted lists into one by using move semantics. Assigns new contents to the list by replacing old ones. Assign new contents to the list by replacing old ones. Assign new contents to the list by replacing old ones. Removes last element from list. Removes first element from list. Inserts new element at the end of list. Inserts new element at the end of list. Inserts new element at the beginning of list. Inserts new element at the beginning of list. Returns a reverse iterator which points to the last element of the list. removes element(s) from the list that matches the value. removes elements from the list that fulfills the condition. Returns a reverse iterator which points to the reverse end of the list. Changes the size of list. Changes the size of list. Reverses the order of the elements present in the list. Returns the number of elements present in the list. Sorts the elements of the list. Sorts the elements of the list. Transfers all elements from list to *this. Transfers a element pointed to by iterator i from list x into *this. Transfers all elements from list x to *this by using move semantics. Transfers the elements in the range of first to last from x to *this. Transfers the element pointed to by iterator i from list x into *this by using move semantics. Transfers the elements in the range of first to last from x to *this by using move semantics. Exchanges the content of list with contents of another list x. Removes all consecutive duplicate elements from the list. Removes all consecutive duplicate elements from the list. Tests whether two lists are equal or not. Tests whether two lists are equal or not. Tests whether first list is less than other or not. Tests whether first list is less than or equal to other or not. Tests whether first list is greater than other or not. Tests whether first list is greater than or equal to other or not. Exchanges the contents of two list. Print Add Notes Bookmark this page
[ { "code": null, "e": 2818, "s": 2603, "text": "List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data." }, { "code": null, "e": 3004, "s": 2818, "text": "List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time." }, { "code": null, "e": 3288, "s": 3004, "text": "Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator." }, { "code": null, "e": 3443, "s": 3288, "text": "Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined." }, { "code": null, "e": 3500, "s": 3443, "text": "Below is definition of std::list from <list> header file" }, { "code": null, "e": 3562, "s": 3500, "text": "template < class T, class Alloc = allocator<T> > class list;\n" }, { "code": null, "e": 3670, "s": 3562, "text": "T − Type of the element contained.\nT may be substituted by any other data type including user-defined type." }, { "code": null, "e": 3705, "s": 3670, "text": "T − Type of the element contained." }, { "code": null, "e": 3778, "s": 3705, "text": "T may be substituted by any other data type including user-defined type." }, { "code": null, "e": 3939, "s": 3778, "text": "Alloc − Type of allocator object.\nBy default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent." }, { "code": null, "e": 3973, "s": 3939, "text": "Alloc − Type of allocator object." }, { "code": null, "e": 4100, "s": 3973, "text": "By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent." }, { "code": null, "e": 4185, "s": 4100, "text": "Following member types can be used as parameters or return type by member functions." }, { "code": null, "e": 4234, "s": 4185, "text": "Below is list of all methods from <list> header." }, { "code": null, "e": 4279, "s": 4234, "text": "Constructs an empty list with zero elements." }, { "code": null, "e": 4358, "s": 4279, "text": "Constructs a new list with n elements and assigns val to each element of list." }, { "code": null, "e": 4443, "s": 4358, "text": "Constructs a new list with n elements and assign zero value to each element of list." }, { "code": null, "e": 4513, "s": 4443, "text": "Constructs a list with as many elements as in range of first to last." }, { "code": null, "e": 4584, "s": 4513, "text": "Constructs a list with copy of each elements present in existing list." }, { "code": null, "e": 4651, "s": 4584, "text": "Constructs a list with the contents of other using move semantics." }, { "code": null, "e": 4718, "s": 4651, "text": "Constructs a list with the contents of other using move semantics." }, { "code": null, "e": 4768, "s": 4718, "text": "Destroys list object by deallocating it's memory." }, { "code": null, "e": 4817, "s": 4768, "text": "Assigns new value to list by replacing old ones." }, { "code": null, "e": 4867, "s": 4817, "text": "Assigns new values to list by replacing old ones." }, { "code": null, "e": 4917, "s": 4867, "text": "Assigns new values to list by replacing old ones." }, { "code": null, "e": 4970, "s": 4917, "text": "Returns a reference to the last element of the list." }, { "code": null, "e": 5050, "s": 4970, "text": "Returns a random access iterator which points to the first element of the list." }, { "code": null, "e": 5135, "s": 5050, "text": "Returns a constant random access iterator which points to the beginning of the list." }, { "code": null, "e": 5214, "s": 5135, "text": "Returns a constant random access iterator which points to the end of the list." }, { "code": null, "e": 5302, "s": 5214, "text": "Destroys the list by removing all elements from the list and sets size of list to zero." }, { "code": null, "e": 5384, "s": 5302, "text": "Returns a constant reverse iterator which points to the last element of the list." }, { "code": null, "e": 5501, "s": 5384, "text": "Returns a constant reverse iterator which points to the theoretical element preceding the first element in the list." }, { "code": null, "e": 5560, "s": 5501, "text": "Extends list by inserting new element at a given position." }, { "code": null, "e": 5634, "s": 5560, "text": "Inserts new element at the end of list and increases size of list by one." }, { "code": null, "e": 5718, "s": 5634, "text": "Inserts new element at the beginning of the list and increases size of list by one." }, { "code": null, "e": 5754, "s": 5718, "text": "Tests whether list is empty or not." }, { "code": null, "e": 5833, "s": 5754, "text": "Returns a random access iterator which points to the last element of the list." }, { "code": null, "e": 5875, "s": 5833, "text": "Removes single element from the the list." }, { "code": null, "e": 5919, "s": 5875, "text": "Removes range of element from the the list." }, { "code": null, "e": 5973, "s": 5919, "text": "Returns a reference to the first element of the list." }, { "code": null, "e": 6015, "s": 5973, "text": "Returns an allocator associated with list" }, { "code": null, "e": 6078, "s": 6015, "text": "Extends iterator by inserting new element at position in list." }, { "code": null, "e": 6135, "s": 6078, "text": "Extends list by inserting new elements in the container." }, { "code": null, "e": 6192, "s": 6135, "text": "Extends list by inserting new elements in the container." }, { "code": null, "e": 6248, "s": 6192, "text": "Extends list by inserting new element in the container." }, { "code": null, "e": 6304, "s": 6248, "text": "Extends list by inserting new elements in the container" }, { "code": null, "e": 6364, "s": 6304, "text": "Returns the maximum number of elements can be held by list." }, { "code": null, "e": 6398, "s": 6364, "text": "Merges two sorted lists into one." }, { "code": null, "e": 6432, "s": 6398, "text": "Merges two sorted lists into one." }, { "code": null, "e": 6490, "s": 6432, "text": "Merges two sorted lists into one by using move semantics." }, { "code": null, "e": 6548, "s": 6490, "text": "Merges two sorted lists into one by using move semantics." }, { "code": null, "e": 6604, "s": 6548, "text": "Assigns new contents to the list by replacing old ones." }, { "code": null, "e": 6659, "s": 6604, "text": "Assign new contents to the list by replacing old ones." }, { "code": null, "e": 6714, "s": 6659, "text": "Assign new contents to the list by replacing old ones." }, { "code": null, "e": 6746, "s": 6714, "text": "Removes last element from list." }, { "code": null, "e": 6779, "s": 6746, "text": "Removes first element from list." }, { "code": null, "e": 6819, "s": 6779, "text": "Inserts new element at the end of list." }, { "code": null, "e": 6859, "s": 6819, "text": "Inserts new element at the end of list." }, { "code": null, "e": 6905, "s": 6859, "text": "Inserts new element at the beginning of list." }, { "code": null, "e": 6951, "s": 6905, "text": "Inserts new element at the beginning of list." }, { "code": null, "e": 7024, "s": 6951, "text": "Returns a reverse iterator which points to the last element of the list." }, { "code": null, "e": 7081, "s": 7024, "text": "removes element(s) from the list that matches the value." }, { "code": null, "e": 7141, "s": 7081, "text": "removes elements from the list that fulfills the condition." }, { "code": null, "e": 7213, "s": 7141, "text": "Returns a reverse iterator which points to the reverse end of the list." }, { "code": null, "e": 7239, "s": 7213, "text": "Changes the size of list." }, { "code": null, "e": 7265, "s": 7239, "text": "Changes the size of list." }, { "code": null, "e": 7321, "s": 7265, "text": "Reverses the order of the elements present in the list." }, { "code": null, "e": 7373, "s": 7321, "text": "Returns the number of elements present in the list." }, { "code": null, "e": 7405, "s": 7373, "text": "Sorts the elements of the list." }, { "code": null, "e": 7437, "s": 7405, "text": "Sorts the elements of the list." }, { "code": null, "e": 7480, "s": 7437, "text": "Transfers all elements from list to *this." }, { "code": null, "e": 7549, "s": 7480, "text": "Transfers a element pointed to by iterator i from list x into *this." }, { "code": null, "e": 7618, "s": 7549, "text": "Transfers all elements from list x to *this by using move semantics." }, { "code": null, "e": 7688, "s": 7618, "text": "Transfers the elements in the range of first to last from x to *this." }, { "code": null, "e": 7783, "s": 7688, "text": "Transfers the element pointed to by iterator i from list x into *this by using move semantics." }, { "code": null, "e": 7877, "s": 7783, "text": "Transfers the elements in the range of first to last from x to *this by using move semantics." }, { "code": null, "e": 7940, "s": 7877, "text": "Exchanges the content of list with contents of another list x." }, { "code": null, "e": 7998, "s": 7940, "text": "Removes all consecutive duplicate elements from the list." }, { "code": null, "e": 8056, "s": 7998, "text": "Removes all consecutive duplicate elements from the list." }, { "code": null, "e": 8098, "s": 8056, "text": "Tests whether two lists are equal or not." }, { "code": null, "e": 8140, "s": 8098, "text": "Tests whether two lists are equal or not." }, { "code": null, "e": 8192, "s": 8140, "text": "Tests whether first list is less than other or not." }, { "code": null, "e": 8256, "s": 8192, "text": "Tests whether first list is less than or equal to other or not." }, { "code": null, "e": 8311, "s": 8256, "text": "Tests whether first list is greater than other or not." }, { "code": null, "e": 8378, "s": 8311, "text": "Tests whether first list is greater than or equal to other or not." }, { "code": null, "e": 8414, "s": 8378, "text": "Exchanges the contents of two list." }, { "code": null, "e": 8421, "s": 8414, "text": " Print" }, { "code": null, "e": 8432, "s": 8421, "text": " Add Notes" } ]
wxPython - Dialog Class
Although a Dialog class object appears like a Frame, it is normally used as a pop-up window on top of a parent frame. The objective of a Dialog is to collect some data from the user and send it to the parent frame. Dialog frame can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed). ShowModal() method displays dialog frame in the modal manner, while Show() makes it modeless. wxPython has a number of preconfigured Dialog widgets such as MessageDialog, FileDialog, FontDialog, etc. wx.Dialog supports the use of Sizers just as a wx.Frame object. Hence, a custom Dialog can be designed. Wx.Dialog class constructor takes the following usual parameters − wx.Dialog(parent, id, title, pos, size, style) Default appearance of Dialog widget shows only Close box in the title bar. However, it can be customized using a combination of the following style parameters − wx.CAPTION Puts a caption on the dialog box wx.DEFAULT_DIALOG_STYLE Equivalent to a combination of wxCAPTION, wxCLOSE_BOX and wxSYSTEM_MENU wx.RESIZE_BORDER Displays a resizable frame around the window wxSYSTEM_MENU Displays a system menu wx.CLOSE_BOX Displays a close box on the frame wx.MAXIMIZE_BOX Displays a maximize box on the dialog wx.MINIMIZE_BOX Displays a minimize box on the dialog wx.STAY_ON_TOP Ensures the dialog stays on top of all other windows wx.DIALOG_NO_PARENT Prevents creating orphan dialog. Not recommended for modal dialogs Two even binders are defined for this class − EVT_CLOSE When the dialog is being closed by the user or programmatically EVT_INIT_DIALOG When the dialog is being initialized As mentioned above, the objective of Dialog is to collect data and return to the parent window. However, some useful methods are available for Dialog class. DoOK() Called when OK button on the dialog is pressed ShowModal() Shows the dialog in application modal fashion ShowWindowModal() Dialog is modal to top level parent window only EndModal() Ends a modal dialog passing the value from ShowModal invocation One of the preconfigured dialogs is MessageDialog. It is used to display a message of one or more lines with buttons having standard IDs. Here is a select list of standard buttons on MessageDialog. wx.OK Shows OK button wx.CANCEL Shows Cancel button wx.YES_NO Shows Yes, No buttons wx.YES_DEFAULT Makes Yes button as default wx.NO_DEFAULT Makes No button as default wx.ICON_EXCLAMATION Shows an alert icon wx.ICON_ERROR Shows an error icon wx.ICON_HAND Same as wx.ICON_ERROR wx.ICON_INFORMATION Show an info icon wx.ICON_QUESTION Shows a question icon This is declared with the following constructor − wx.MessageDialog(parent, message, caption, style, pos) One or more lines of the text to be displayed is the message parameter, while the caption is displayed on the title bar. Default style parameter is wx.OK|wx.ECNRE. Other style parameters allow the message box to be customized. wx.MessageBox is a convenience function to construct a message box instead of using MessageDialog. Given below is a simple demonstration of modal and modeless behavior of Dialog. The parent window is a wx.Frame object with two buttons. Click event on the first button displays a dialog in modal fashion. Hence, any operation on the parent window is prevented till the dialog is closed. The second button displays a modeless dialog, which doesn’t obstruct access to parent window. The third button displays a MessageBox. The entire code is as follows − import wx class MyDialog(wx.Dialog): def __init__(self, parent, title): super(MyDialog, self).__init__(parent, title = title, size = (250,150)) panel = wx.Panel(self) self.btn = wx.Button(panel, wx.ID_OK, label = "ok", size = (50,20), pos = (75,50)) class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title, size = (250,150)) self.InitUI() def InitUI(self): panel = wx.Panel(self) btn = wx.Button(panel, label = "Modal Dialog", pos = (75,10)) btn1 = wx.Button(panel, label = "Modeless Dialog", pos = (75,40)) btn2 = wx.Button(panel, label = "MessageBox", pos = (75,70)) btn.Bind(wx.EVT_BUTTON, self.OnModal) a = btn1.Bind(wx.EVT_BUTTON, self.OnModeless) print a btn2.Bind(wx.EVT_BUTTON, self.Onmsgbox) self.Centre() self.Show(True) def OnModal(self, event): a = MyDialog(self, "Dialog").ShowModal() print a def OnModeless(self, event): a = MyDialog(self, "Dialog").Show() def Onmsgbox(self, event): wx.MessageBox("This is a Message Box", "Message" ,wx.OK | wx.ICON_INFORMATION) ex = wx.App() Mywin(None,'MenuBar demo') ex.MainLoop() The above code produces the following output − Object of this class displays a dialog with one text field, a customizable label prompting the user to input and two buttons with predefined styles. Although this dialog requests a one line input, the text box can be customized by using TextCtrl styles like password and multiline. Contents of the text field are collected as return value when the user clicks OK button. TextEntryDialog constructor is as follows − wx.TextEntryDialog(parent, id, message, caption, value, style, pos) The text to be displayed on the Dialog window is passed as the message parameter. The caption parameter is the string to be displayed in the title bar. Default string in the text box is vthe alue parameter. TextCtrl in dialog can be configured to display password characters (wx.TE_PASSWORD) and/or multiline (wx.TE_MULTILINE). Other methods of TextEntry class are as listed in the following table − SetMaxLength() Sets the maximum number of characters the user can enter into the text box SetValue() Sets the text box value programmatically GetValue() Returns the contents of the text box ShowModal() Shows dialog modally. Returns wx.ID_OK if the user confirms input, and wx.ID_CANCEL if the dialog is rejected Top level frame in the following example shows a button and a read-only TextCtrl widget. self.text = wx.TextCtrl(pnl, size = (250, 25),style = wx.TE_READONLY) self.btn1 = wx.Button(pnl, label = "Enter Text") The button responds to click and invokes the OnClick() function. self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) OnClick() function displays a TextEntryDialog. dlg = wx.TextEntryDialog(self, 'Enter Your Name','Text Entry Dialog') Return value of the dialog is fetched by GetValue() function and displayed in the TextCtrl object of top level frame. if dlg.ShowModal() == wx.ID_OK: self.text.SetValue("Name entered:"+dlg.GetValue()) The complete code is as follows − import wx class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title,size = (300,200)) self.InitUI() def InitUI(self): self.count = 0 pnl = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.TextCtrl(pnl, size = (250, 25),style = wx.TE_READONLY) self.btn1 = wx.Button(pnl, label = "Enter Text") self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) hbox2.Add(self.btn1, proportion = 1, flag = wx.RIGHT, border = 10) vbox.Add((0, 30)) vbox.Add(hbox1, flag = wx.ALIGN_CENTRE) vbox.Add((0, 20)) vbox.Add(hbox2, proportion = 1, flag = wx.ALIGN_CENTRE) pnl.SetSizer(vbox) self.Centre() self.Show(True) def OnClick(self, e): dlg = wx.TextEntryDialog(self, 'Enter Your Name','Text Entry Dialog') if dlg.ShowModal() == wx.ID_OK: self.text.SetValue("Name entered:"+dlg.GetValue()) dlg.Destroy() ex = wx.App() Mywin(None,'TextEntry Demo') ex.MainLoop() The above code produces the following output − This class represents a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. Appearance of the dialog is OS specific. A file filter can also be applied to display the files of specified extensions only. Starting directory and default file name can also be set. FileDialog constructor’s prototype looks like this − wx.FileDialog(parent, message, DefaultDir, DefaultFile, wildcard, style, pos, size) The message represents text to be displayed. DefaultDir is the initial directory. One or more types of files can be set as file filter represented by wildcard parameter. Style parameters defined for FileDialog are − wx.FD_DEFAULT_STYLE Equivalent to wxFD_OPEN wx.FD_OPEN This is an open dialog; default button's label of the dialog is "Open" wx.FD_SAVE This is a save dialog; default button's label of the dialog is "Save" wx.FD_OVERWRITE_PROMPT For save dialog only: prompts for a confirmation if a file will be overwritten wx.FD_MULTIPLE For open dialog only: allows selecting multiple files wx.FD_CHANGE_DIR Changes the current working directory to the directory where the file(s) chosen by the user are Member functions of wx.FileDialog class − GetDirectory() Returns default directory GetFileName() Returns default file name GetPath() Returns full path of selected file SetDirectory() Sets default directory SetFilename() Sets default file SetPath() Sets full path ShowModal() Displays dialog, returns wx.ID_OK if the user clicks OK button and wx.ID_CANCEL otherwise In the following example, the top level frame shows a button and a multiline TextCtrl. self.text = wx.TextCtrl(pnl, size = (-1,200), style = wx.TE_MULTILINE) self.btn1 = wx.Button(pnl, label = "Open a File") EVT_BUTTON event binder registers OnClick() function with the button. self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) OnClick() function displays a FileDialog in open mode. Its selection is returned as dlg. The selected file is obtained by GetPath() function and its contents are displayed in TextCtrl box on parent window. def OnClick(self, e): wildcard = "Text Files (*.txt)|*.txt" dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: f = open(dlg.GetPath(), 'r') with f: data = f.read() self.text.SetValue(data) The complete code is as follows − import wx import os class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title) self.InitUI() def InitUI(self): self.count = 0 pnl = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.TextCtrl(pnl, size = (-1,200),style = wx.TE_MULTILINE) self.btn1 = wx.Button(pnl, label = "Open a File") self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) hbox2.Add(self.btn1, proportion = 1, flag = wx.RIGHT, border = 10) vbox.Add(hbox2, proportion = 1, flag = wx.ALIGN_CENTRE) vbox.Add(hbox1, proportion = 1, flag = wx.EXPAND|wx.ALIGN_CENTRE) pnl.SetSizer(vbox) self.Centre() self.Show(True) def OnClick(self, e): wildcard = "Text Files (*.txt)|*.txt" dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: f = open(dlg.GetPath(), 'r') with f: data = f.read() self.text.SetValue(data) dlg.Destroy() ex = wx.App() Mywin(None, 'FileDialog Demo') ex.MainLoop() The above code produces the following output − The object of this class is a font chooser dialog. Appearance of this dialog too is OS specific. Attributes, such as name, size, weight, etc. of the selected font are returned as the return value of this dialog. Fontdata parameter required for this class constructor is used to initialize these attributes. wx.FontDialog(parent, data) GetFontData() method of this class contains the parameters of the selected font. The following code demonstrating the use of FontDialog has a button and a label (StaticText object). self.text = wx.StaticText(pnl, label = "hello") self.btn1 = wx.Button(pnl, label = "Choose Font") The button when clicked triggers OnClick() event handler function. def OnClick(self, e): dlg = wx.FontDialog(self,wx.FontData()) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetFontData() font = data.GetChosenFont() self.text.SetFont(font) dlg.Destroy() The chosen font is then applied to label’s text. The complete code is as follows − import wx import os class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title, size = (250,200)) self.InitUI() def InitUI(self): self.count = 0 pnl = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.text = wx.StaticText(pnl, label = "hello") self.btn1 = wx.Button(pnl, label = "Choose Font") self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) hbox2.Add(self.btn1, proportion = 1, flag = wx.ALIGN_CENTRE, border = 10) vbox.Add(hbox2, flag = wx.ALIGN_CENTRE) vbox.Add(hbox1, proportion = 1, flag = wx.ALIGN_CENTRE) pnl.SetSizer(vbox) self.Centre() self.Show(True) def OnClick(self, e): dlg = wx.FontDialog(self,wx.FontData()) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetFontData() font = data.GetChosenFont() self.text.SetFont(font) dlg.Destroy() ex = wx.App() Mywin(None,'FileDialog Demo') ex.MainLoop() The above code produces the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2296, "s": 1882, "text": "Although a Dialog class object appears like a Frame, it is normally used as a pop-up window on top of a parent frame. The objective of a Dialog is to collect some data from the user and send it to the parent frame. Dialog frame can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed). ShowModal() method displays dialog frame in the modal manner, while Show() makes it modeless." }, { "code": null, "e": 2402, "s": 2296, "text": "wxPython has a number of preconfigured Dialog widgets such as MessageDialog, FileDialog, FontDialog, etc." }, { "code": null, "e": 2506, "s": 2402, "text": "wx.Dialog supports the use of Sizers just as a wx.Frame object. Hence, a custom Dialog can be designed." }, { "code": null, "e": 2573, "s": 2506, "text": "Wx.Dialog class constructor takes the following usual parameters −" }, { "code": null, "e": 2621, "s": 2573, "text": "wx.Dialog(parent, id, title, pos, size, style)\n" }, { "code": null, "e": 2782, "s": 2621, "text": "Default appearance of Dialog widget shows only Close box in the title bar. However, it can be customized using a combination of the following style parameters −" }, { "code": null, "e": 2793, "s": 2782, "text": "wx.CAPTION" }, { "code": null, "e": 2826, "s": 2793, "text": "Puts a caption on the dialog box" }, { "code": null, "e": 2850, "s": 2826, "text": "wx.DEFAULT_DIALOG_STYLE" }, { "code": null, "e": 2922, "s": 2850, "text": "Equivalent to a combination of wxCAPTION, wxCLOSE_BOX and wxSYSTEM_MENU" }, { "code": null, "e": 2939, "s": 2922, "text": "wx.RESIZE_BORDER" }, { "code": null, "e": 2984, "s": 2939, "text": "Displays a resizable frame around the window" }, { "code": null, "e": 2998, "s": 2984, "text": "wxSYSTEM_MENU" }, { "code": null, "e": 3021, "s": 2998, "text": "Displays a system menu" }, { "code": null, "e": 3034, "s": 3021, "text": "wx.CLOSE_BOX" }, { "code": null, "e": 3068, "s": 3034, "text": "Displays a close box on the frame" }, { "code": null, "e": 3084, "s": 3068, "text": "wx.MAXIMIZE_BOX" }, { "code": null, "e": 3122, "s": 3084, "text": "Displays a maximize box on the dialog" }, { "code": null, "e": 3138, "s": 3122, "text": "wx.MINIMIZE_BOX" }, { "code": null, "e": 3176, "s": 3138, "text": "Displays a minimize box on the dialog" }, { "code": null, "e": 3191, "s": 3176, "text": "wx.STAY_ON_TOP" }, { "code": null, "e": 3244, "s": 3191, "text": "Ensures the dialog stays on top of all other windows" }, { "code": null, "e": 3264, "s": 3244, "text": "wx.DIALOG_NO_PARENT" }, { "code": null, "e": 3331, "s": 3264, "text": "Prevents creating orphan dialog. Not recommended for modal dialogs" }, { "code": null, "e": 3377, "s": 3331, "text": "Two even binders are defined for this class −" }, { "code": null, "e": 3387, "s": 3377, "text": "EVT_CLOSE" }, { "code": null, "e": 3451, "s": 3387, "text": "When the dialog is being closed by the user or programmatically" }, { "code": null, "e": 3467, "s": 3451, "text": "EVT_INIT_DIALOG" }, { "code": null, "e": 3504, "s": 3467, "text": "When the dialog is being initialized" }, { "code": null, "e": 3661, "s": 3504, "text": "As mentioned above, the objective of Dialog is to collect data and return to the parent window. However, some useful methods are available for Dialog class." }, { "code": null, "e": 3668, "s": 3661, "text": "DoOK()" }, { "code": null, "e": 3715, "s": 3668, "text": "Called when OK button on the dialog is pressed" }, { "code": null, "e": 3727, "s": 3715, "text": "ShowModal()" }, { "code": null, "e": 3773, "s": 3727, "text": "Shows the dialog in application modal fashion" }, { "code": null, "e": 3791, "s": 3773, "text": "ShowWindowModal()" }, { "code": null, "e": 3839, "s": 3791, "text": "Dialog is modal to top level parent window only" }, { "code": null, "e": 3850, "s": 3839, "text": "EndModal()" }, { "code": null, "e": 3914, "s": 3850, "text": "Ends a modal dialog passing the value from ShowModal invocation" }, { "code": null, "e": 4112, "s": 3914, "text": "One of the preconfigured dialogs is MessageDialog. It is used to display a message of one or more lines with buttons having standard IDs. Here is a select list of standard buttons on MessageDialog." }, { "code": null, "e": 4118, "s": 4112, "text": "wx.OK" }, { "code": null, "e": 4134, "s": 4118, "text": "Shows OK button" }, { "code": null, "e": 4144, "s": 4134, "text": "wx.CANCEL" }, { "code": null, "e": 4164, "s": 4144, "text": "Shows Cancel button" }, { "code": null, "e": 4174, "s": 4164, "text": "wx.YES_NO" }, { "code": null, "e": 4196, "s": 4174, "text": "Shows Yes, No buttons" }, { "code": null, "e": 4211, "s": 4196, "text": "wx.YES_DEFAULT" }, { "code": null, "e": 4239, "s": 4211, "text": "Makes Yes button as default" }, { "code": null, "e": 4253, "s": 4239, "text": "wx.NO_DEFAULT" }, { "code": null, "e": 4280, "s": 4253, "text": "Makes No button as default" }, { "code": null, "e": 4300, "s": 4280, "text": "wx.ICON_EXCLAMATION" }, { "code": null, "e": 4320, "s": 4300, "text": "Shows an alert icon" }, { "code": null, "e": 4334, "s": 4320, "text": "wx.ICON_ERROR" }, { "code": null, "e": 4354, "s": 4334, "text": "Shows an error icon" }, { "code": null, "e": 4367, "s": 4354, "text": "wx.ICON_HAND" }, { "code": null, "e": 4389, "s": 4367, "text": "Same as wx.ICON_ERROR" }, { "code": null, "e": 4409, "s": 4389, "text": "wx.ICON_INFORMATION" }, { "code": null, "e": 4427, "s": 4409, "text": "Show an info icon" }, { "code": null, "e": 4444, "s": 4427, "text": "wx.ICON_QUESTION" }, { "code": null, "e": 4466, "s": 4444, "text": "Shows a question icon" }, { "code": null, "e": 4516, "s": 4466, "text": "This is declared with the following constructor −" }, { "code": null, "e": 4572, "s": 4516, "text": "wx.MessageDialog(parent, message, caption, style, pos)\n" }, { "code": null, "e": 4799, "s": 4572, "text": "One or more lines of the text to be displayed is the message parameter, while the caption is displayed on the title bar. Default style parameter is wx.OK|wx.ECNRE. Other style parameters allow the message box to be customized." }, { "code": null, "e": 4898, "s": 4799, "text": "wx.MessageBox is a convenience function to construct a message box instead of using MessageDialog." }, { "code": null, "e": 5319, "s": 4898, "text": "Given below is a simple demonstration of modal and modeless behavior of Dialog. The parent window is a wx.Frame object with two buttons. Click event on the first button displays a dialog in modal fashion. Hence, any operation on the parent window is prevented till the dialog is closed. The second button displays a modeless dialog, which doesn’t obstruct access to parent window. The third button displays a MessageBox." }, { "code": null, "e": 5351, "s": 5319, "text": "The entire code is as follows −" }, { "code": null, "e": 6644, "s": 5351, "text": "import wx\n \nclass MyDialog(wx.Dialog): \n def __init__(self, parent, title): \n super(MyDialog, self).__init__(parent, title = title, size = (250,150)) \n panel = wx.Panel(self) \n self.btn = wx.Button(panel, wx.ID_OK, label = \"ok\", size = (50,20), pos = (75,50))\n\t\t\nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title, size = (250,150)) \n self.InitUI() \n \n def InitUI(self): \n panel = wx.Panel(self) \n btn = wx.Button(panel, label = \"Modal Dialog\", pos = (75,10)) \n btn1 = wx.Button(panel, label = \"Modeless Dialog\", pos = (75,40)) \n btn2 = wx.Button(panel, label = \"MessageBox\", pos = (75,70)) \n btn.Bind(wx.EVT_BUTTON, self.OnModal)\n\t\t\n a = btn1.Bind(wx.EVT_BUTTON, self.OnModeless) \n print a \n btn2.Bind(wx.EVT_BUTTON, self.Onmsgbox) \n self.Centre() \n self.Show(True) \n\t\t\n def OnModal(self, event): \n a = MyDialog(self, \"Dialog\").ShowModal() \n print a \n\t\t\n def OnModeless(self, event): \n a = MyDialog(self, \"Dialog\").Show()\n\t\t\n def Onmsgbox(self, event): \n wx.MessageBox(\"This is a Message Box\", \"Message\" ,wx.OK | wx.ICON_INFORMATION) \n\t\t\nex = wx.App() \nMywin(None,'MenuBar demo') \nex.MainLoop()" }, { "code": null, "e": 6691, "s": 6644, "text": "The above code produces the following output −" }, { "code": null, "e": 6840, "s": 6691, "text": "Object of this class displays a dialog with one text field, a customizable label prompting the user to input and two buttons with predefined styles." }, { "code": null, "e": 6973, "s": 6840, "text": "Although this dialog requests a one line input, the text box can be customized by using TextCtrl styles like password and multiline." }, { "code": null, "e": 7062, "s": 6973, "text": "Contents of the text field are collected as return value when the user clicks OK button." }, { "code": null, "e": 7106, "s": 7062, "text": "TextEntryDialog constructor is as follows −" }, { "code": null, "e": 7175, "s": 7106, "text": "wx.TextEntryDialog(parent, id, message, caption, value, style, pos)\n" }, { "code": null, "e": 7503, "s": 7175, "text": "The text to be displayed on the Dialog window is passed as the message parameter. The caption parameter is the string to be displayed in the title bar. Default string in the text box is vthe alue parameter. TextCtrl in dialog can be configured to display password characters (wx.TE_PASSWORD) and/or multiline (wx.TE_MULTILINE)." }, { "code": null, "e": 7575, "s": 7503, "text": "Other methods of TextEntry class are as listed in the following table −" }, { "code": null, "e": 7590, "s": 7575, "text": "SetMaxLength()" }, { "code": null, "e": 7665, "s": 7590, "text": "Sets the maximum number of characters the user can enter into the text box" }, { "code": null, "e": 7676, "s": 7665, "text": "SetValue()" }, { "code": null, "e": 7717, "s": 7676, "text": "Sets the text box value programmatically" }, { "code": null, "e": 7728, "s": 7717, "text": "GetValue()" }, { "code": null, "e": 7765, "s": 7728, "text": "Returns the contents of the text box" }, { "code": null, "e": 7777, "s": 7765, "text": "ShowModal()" }, { "code": null, "e": 7887, "s": 7777, "text": "Shows dialog modally. Returns wx.ID_OK if the user confirms input, and wx.ID_CANCEL if the dialog is rejected" }, { "code": null, "e": 7976, "s": 7887, "text": "Top level frame in the following example shows a button and a read-only TextCtrl widget." }, { "code": null, "e": 8097, "s": 7976, "text": "self.text = wx.TextCtrl(pnl, size = (250, 25),style = wx.TE_READONLY) \nself.btn1 = wx.Button(pnl, label = \"Enter Text\")\n" }, { "code": null, "e": 8162, "s": 8097, "text": "The button responds to click and invokes the OnClick() function." }, { "code": null, "e": 8213, "s": 8162, "text": "self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1)\n" }, { "code": null, "e": 8260, "s": 8213, "text": "OnClick() function displays a TextEntryDialog." }, { "code": null, "e": 8331, "s": 8260, "text": "dlg = wx.TextEntryDialog(self, 'Enter Your Name','Text Entry Dialog')\n" }, { "code": null, "e": 8449, "s": 8331, "text": "Return value of the dialog is fetched by GetValue() function and displayed in the TextCtrl object of top level frame." }, { "code": null, "e": 8536, "s": 8449, "text": "if dlg.ShowModal() == wx.ID_OK: \n self.text.SetValue(\"Name entered:\"+dlg.GetValue())" }, { "code": null, "e": 8570, "s": 8536, "text": "The complete code is as follows −" }, { "code": null, "e": 9875, "s": 8570, "text": "import wx \n \nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (300,200)) \n \n self.InitUI() \n \n def InitUI(self): \n self.count = 0 \n pnl = wx.Panel(self) \n vbox = wx.BoxSizer(wx.VERTICAL) \n\t\t\n hbox1 = wx.BoxSizer(wx.HORIZONTAL) \n hbox2 = wx.BoxSizer(wx.HORIZONTAL) \n\t\t\n self.text = wx.TextCtrl(pnl, size = (250, 25),style = wx.TE_READONLY) \n self.btn1 = wx.Button(pnl, label = \"Enter Text\") \n self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) \n\t\t\n hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) \n hbox2.Add(self.btn1, proportion = 1, flag = wx.RIGHT, border = 10)\n\t\t\n vbox.Add((0, 30)) \n vbox.Add(hbox1, flag = wx.ALIGN_CENTRE) \n vbox.Add((0, 20)) \n vbox.Add(hbox2, proportion = 1, flag = wx.ALIGN_CENTRE) \n\t\t\n pnl.SetSizer(vbox) \n self.Centre() \n self.Show(True)\n\t\t\n def OnClick(self, e): \n dlg = wx.TextEntryDialog(self, 'Enter Your Name','Text Entry Dialog') \n\t\t\n if dlg.ShowModal() == wx.ID_OK: \n self.text.SetValue(\"Name entered:\"+dlg.GetValue()) \n dlg.Destroy() \n \nex = wx.App() \nMywin(None,'TextEntry Demo') \nex.MainLoop()" }, { "code": null, "e": 9922, "s": 9875, "text": "The above code produces the following output −" }, { "code": null, "e": 10100, "s": 9922, "text": "This class represents a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. Appearance of the dialog is OS specific." }, { "code": null, "e": 10244, "s": 10100, "text": "A file filter can also be applied to display the files of specified extensions only. Starting directory and default file name can also be set." }, { "code": null, "e": 10297, "s": 10244, "text": "FileDialog constructor’s prototype looks like this −" }, { "code": null, "e": 10382, "s": 10297, "text": "wx.FileDialog(parent, message, DefaultDir, DefaultFile, wildcard, style, pos, size)\n" }, { "code": null, "e": 10552, "s": 10382, "text": "The message represents text to be displayed. DefaultDir is the initial directory. One or more types of files can be set as file filter represented by wildcard parameter." }, { "code": null, "e": 10598, "s": 10552, "text": "Style parameters defined for FileDialog are −" }, { "code": null, "e": 10618, "s": 10598, "text": "wx.FD_DEFAULT_STYLE" }, { "code": null, "e": 10642, "s": 10618, "text": "Equivalent to wxFD_OPEN" }, { "code": null, "e": 10653, "s": 10642, "text": "wx.FD_OPEN" }, { "code": null, "e": 10724, "s": 10653, "text": "This is an open dialog; default button's label of the dialog is \"Open\"" }, { "code": null, "e": 10735, "s": 10724, "text": "wx.FD_SAVE" }, { "code": null, "e": 10805, "s": 10735, "text": "This is a save dialog; default button's label of the dialog is \"Save\"" }, { "code": null, "e": 10828, "s": 10805, "text": "wx.FD_OVERWRITE_PROMPT" }, { "code": null, "e": 10907, "s": 10828, "text": "For save dialog only: prompts for a confirmation if a file will be overwritten" }, { "code": null, "e": 10922, "s": 10907, "text": "wx.FD_MULTIPLE" }, { "code": null, "e": 10976, "s": 10922, "text": "For open dialog only: allows selecting multiple files" }, { "code": null, "e": 10993, "s": 10976, "text": "wx.FD_CHANGE_DIR" }, { "code": null, "e": 11089, "s": 10993, "text": "Changes the current working directory to the directory where the file(s) chosen by the user are" }, { "code": null, "e": 11131, "s": 11089, "text": "Member functions of wx.FileDialog class −" }, { "code": null, "e": 11146, "s": 11131, "text": "GetDirectory()" }, { "code": null, "e": 11172, "s": 11146, "text": "Returns default directory" }, { "code": null, "e": 11186, "s": 11172, "text": "GetFileName()" }, { "code": null, "e": 11212, "s": 11186, "text": "Returns default file name" }, { "code": null, "e": 11222, "s": 11212, "text": "GetPath()" }, { "code": null, "e": 11257, "s": 11222, "text": "Returns full path of selected file" }, { "code": null, "e": 11272, "s": 11257, "text": "SetDirectory()" }, { "code": null, "e": 11295, "s": 11272, "text": "Sets default directory" }, { "code": null, "e": 11309, "s": 11295, "text": "SetFilename()" }, { "code": null, "e": 11327, "s": 11309, "text": "Sets default file" }, { "code": null, "e": 11337, "s": 11327, "text": "SetPath()" }, { "code": null, "e": 11352, "s": 11337, "text": "Sets full path" }, { "code": null, "e": 11364, "s": 11352, "text": "ShowModal()" }, { "code": null, "e": 11454, "s": 11364, "text": "Displays dialog, returns wx.ID_OK if the user clicks OK button and wx.ID_CANCEL otherwise" }, { "code": null, "e": 11541, "s": 11454, "text": "In the following example, the top level frame shows a button and a multiline TextCtrl." }, { "code": null, "e": 11664, "s": 11541, "text": "self.text = wx.TextCtrl(pnl, size = (-1,200), style = wx.TE_MULTILINE) \nself.btn1 = wx.Button(pnl, label = \"Open a File\")\n" }, { "code": null, "e": 11734, "s": 11664, "text": "EVT_BUTTON event binder registers OnClick() function with the button." }, { "code": null, "e": 11785, "s": 11734, "text": "self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1)\n" }, { "code": null, "e": 11991, "s": 11785, "text": "OnClick() function displays a FileDialog in open mode. Its selection is returned as dlg. The selected file is obtained by GetPath() function and its contents are displayed in TextCtrl box on parent window." }, { "code": null, "e": 12288, "s": 11991, "text": "def OnClick(self, e): \n wildcard = \"Text Files (*.txt)|*.txt\" \n dlg = wx.FileDialog(self, \"Choose a file\", os.getcwd(), \"\", wildcard, wx.OPEN) \n\t\n if dlg.ShowModal() == wx.ID_OK:\n f = open(dlg.GetPath(), 'r') \n with f: \n data = f.read() \n self.text.SetValue(data) " }, { "code": null, "e": 12322, "s": 12288, "text": "The complete code is as follows −" }, { "code": null, "e": 13738, "s": 12322, "text": "import wx \nimport os \n\nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title) \n \n self.InitUI() \n \n def InitUI(self): \n self.count = 0 \n pnl = wx.Panel(self) \n vbox = wx.BoxSizer(wx.VERTICAL) \n hbox1 = wx.BoxSizer(wx.HORIZONTAL) \n hbox2 = wx.BoxSizer(wx.HORIZONTAL) \n\t\t\n self.text = wx.TextCtrl(pnl, size = (-1,200),style = wx.TE_MULTILINE) \n self.btn1 = wx.Button(pnl, label = \"Open a File\") \n self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) \n\t\t\n hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) \n hbox2.Add(self.btn1, proportion = 1, flag = wx.RIGHT, border = 10) \n\t\t\n vbox.Add(hbox2, proportion = 1, flag = wx.ALIGN_CENTRE) \n \n vbox.Add(hbox1, proportion = 1, flag = wx.EXPAND|wx.ALIGN_CENTRE) \n \n pnl.SetSizer(vbox) \n self.Centre() \n self.Show(True) \n\t\t\n def OnClick(self, e): \n wildcard = \"Text Files (*.txt)|*.txt\" \n dlg = wx.FileDialog(self, \"Choose a file\", os.getcwd(), \"\", wildcard, wx.OPEN)\n\t\t\n if dlg.ShowModal() == wx.ID_OK: \n f = open(dlg.GetPath(), 'r') \n\t\t\t\n with f: \n data = f.read() \n self.text.SetValue(data) \n dlg.Destroy() \n \nex = wx.App() \nMywin(None, 'FileDialog Demo') \nex.MainLoop()" }, { "code": null, "e": 13785, "s": 13738, "text": "The above code produces the following output −" }, { "code": null, "e": 13997, "s": 13785, "text": "The object of this class is a font chooser dialog. Appearance of this dialog too is OS specific. Attributes, such as name, size, weight, etc. of the selected font are returned as the return value of this dialog." }, { "code": null, "e": 14092, "s": 13997, "text": "Fontdata parameter required for this class constructor is used to initialize these attributes." }, { "code": null, "e": 14121, "s": 14092, "text": "wx.FontDialog(parent, data)\n" }, { "code": null, "e": 14202, "s": 14121, "text": "GetFontData() method of this class contains the parameters of the selected font." }, { "code": null, "e": 14303, "s": 14202, "text": "The following code demonstrating the use of FontDialog has a button and a label (StaticText object)." }, { "code": null, "e": 14403, "s": 14303, "text": "self.text = wx.StaticText(pnl, label = \"hello\") \nself.btn1 = wx.Button(pnl, label = \"Choose Font\")\n" }, { "code": null, "e": 14470, "s": 14403, "text": "The button when clicked triggers OnClick() event handler function." }, { "code": null, "e": 14693, "s": 14470, "text": "def OnClick(self, e): \n dlg = wx.FontDialog(self,wx.FontData()) \n\t\n if dlg.ShowModal() == wx.ID_OK: \n data = dlg.GetFontData() \n font = data.GetChosenFont() \n self.text.SetFont(font) \n\t\t\n dlg.Destroy()" }, { "code": null, "e": 14742, "s": 14693, "text": "The chosen font is then applied to label’s text." }, { "code": null, "e": 14776, "s": 14742, "text": "The complete code is as follows −" }, { "code": null, "e": 16035, "s": 14776, "text": "import wx \nimport os \n\nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title, size = (250,200)) \n \n self.InitUI() \n \n def InitUI(self): \n self.count = 0 \n pnl = wx.Panel(self) \n\t\t\n vbox = wx.BoxSizer(wx.VERTICAL) \n hbox1 = wx.BoxSizer(wx.HORIZONTAL) \n hbox2 = wx.BoxSizer(wx.HORIZONTAL)\n\t\t\n self.text = wx.StaticText(pnl, label = \"hello\") \n self.btn1 = wx.Button(pnl, label = \"Choose Font\")\n self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) \n\t\t\n hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) \n hbox2.Add(self.btn1, proportion = 1, flag = wx.ALIGN_CENTRE, border = 10) \n\t\t\n vbox.Add(hbox2, flag = wx.ALIGN_CENTRE) \n \n vbox.Add(hbox1, proportion = 1, flag = wx.ALIGN_CENTRE) \n \n pnl.SetSizer(vbox) \n self.Centre() \n self.Show(True) \n \n def OnClick(self, e): \n dlg = wx.FontDialog(self,wx.FontData()) \n\t\t\n if dlg.ShowModal() == wx.ID_OK: \n data = dlg.GetFontData() \n font = data.GetChosenFont() \n self.text.SetFont(font)\n\t\t\t\n dlg.Destroy() \n\t\t\nex = wx.App() \nMywin(None,'FileDialog Demo') \nex.MainLoop()" }, { "code": null, "e": 16082, "s": 16035, "text": "The above code produces the following output −" }, { "code": null, "e": 16089, "s": 16082, "text": " Print" }, { "code": null, "e": 16100, "s": 16089, "text": " Add Notes" } ]
Casting value or an expression from one data type to another in SQL server - GeeksforGeeks
28 Dec, 2020 SQL Server uses the CAST() function to cast or convert a value or an expression from one data type to another. Syntax : CAST ( value AS targettype [ ( length ) ] ) Parameters used : value –value can be any value of any type that will be converted. targettype –targettype is the target data type to which the value will be converted. e.g. INT, BIT, SQL_VARIANT, etc. length –length is an optional parameter that specifies the length of the targettype, default length is 30. For better understanding, let us run the below query as follows. SELECT 3 + '3' AS Result; Output : Its result is 6 as a number. In above statement, SQL Server implicitly converts the character string ‘3’ to the number 3. Note –When two values with different data types are used in SQL Server, it will convert the lower to higher data type before it process if further. This is known as implicit conversion. On the other hand, SQL server could use explicit conversions where the CAST() function is used explicitly to convert a value of one type to another as follows. SELECT 3 + CAST('3' AS INT) AS Result; Output : To cast a value of the data types in different scenarios, SQL Server will return a truncated value or a rounded value based on the following rules as follows. Examples – Example-1 :Below example uses the CAST() function to convert the decimal type value to an integer type value.SELECT CAST(5.95 AS INT) AS Result;Output :Result5 SELECT CAST(5.95 AS INT) AS Result; Output : Example-2 :Below example uses the CAST() function to convert the decimal type value to another decimal type value number with the zero scale.SELECT CAST(5.95 AS DEC(3, 0)) Result;Output :Result6 SELECT CAST(5.95 AS DEC(3, 0)) Result; Output : Example-3 :Using the CAST() function to convert a string to a datetime value example.The below example uses the CAST() function to convert the string to a datetime.SELECT CAST('2020-09-14' AS DATETIME) AS Result;Output :Result2020-09-14 00:00:00.000 SELECT CAST('2020-09-14' AS DATETIME) AS Result; Output : DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? How to Alter Multiple Columns at Once in SQL Server? What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL | Subquery SQL Query to Convert VARCHAR to INT SQL - SELECT from Multiple Tables with MS SQL Server SQL | Date functions SQL Query to Insert Multiple Rows
[ { "code": null, "e": 24268, "s": 24240, "text": "\n28 Dec, 2020" }, { "code": null, "e": 24379, "s": 24268, "text": "SQL Server uses the CAST() function to cast or convert a value or an expression from one data type to another." }, { "code": null, "e": 24388, "s": 24379, "text": "Syntax :" }, { "code": null, "e": 24433, "s": 24388, "text": "CAST ( value AS targettype [ ( length ) ] )\n" }, { "code": null, "e": 24451, "s": 24433, "text": "Parameters used :" }, { "code": null, "e": 24517, "s": 24451, "text": "value –value can be any value of any type that will be converted." }, { "code": null, "e": 24635, "s": 24517, "text": "targettype –targettype is the target data type to which the value will be converted. e.g. INT, BIT, SQL_VARIANT, etc." }, { "code": null, "e": 24742, "s": 24635, "text": "length –length is an optional parameter that specifies the length of the targettype, default length is 30." }, { "code": null, "e": 24807, "s": 24742, "text": "For better understanding, let us run the below query as follows." }, { "code": null, "e": 24833, "s": 24807, "text": "SELECT 3 + '3' AS Result;" }, { "code": null, "e": 24842, "s": 24833, "text": "Output :" }, { "code": null, "e": 24964, "s": 24842, "text": "Its result is 6 as a number. In above statement, SQL Server implicitly converts the character string ‘3’ to the number 3." }, { "code": null, "e": 25150, "s": 24964, "text": "Note –When two values with different data types are used in SQL Server, it will convert the lower to higher data type before it process if further. This is known as implicit conversion." }, { "code": null, "e": 25310, "s": 25150, "text": "On the other hand, SQL server could use explicit conversions where the CAST() function is used explicitly to convert a value of one type to another as follows." }, { "code": null, "e": 25349, "s": 25310, "text": "SELECT 3 + CAST('3' AS INT) AS Result;" }, { "code": null, "e": 25358, "s": 25349, "text": "Output :" }, { "code": null, "e": 25517, "s": 25358, "text": "To cast a value of the data types in different scenarios, SQL Server will return a truncated value or a rounded value based on the following rules as follows." }, { "code": null, "e": 25528, "s": 25517, "text": "Examples –" }, { "code": null, "e": 25688, "s": 25528, "text": "Example-1 :Below example uses the CAST() function to convert the decimal type value to an integer type value.SELECT CAST(5.95 AS INT) AS Result;Output :Result5" }, { "code": null, "e": 25724, "s": 25688, "text": "SELECT CAST(5.95 AS INT) AS Result;" }, { "code": null, "e": 25733, "s": 25724, "text": "Output :" }, { "code": null, "e": 25928, "s": 25733, "text": "Example-2 :Below example uses the CAST() function to convert the decimal type value to another decimal type value number with the zero scale.SELECT CAST(5.95 AS DEC(3, 0)) Result;Output :Result6" }, { "code": null, "e": 25967, "s": 25928, "text": "SELECT CAST(5.95 AS DEC(3, 0)) Result;" }, { "code": null, "e": 25976, "s": 25967, "text": "Output :" }, { "code": null, "e": 26227, "s": 25976, "text": "Example-3 :Using the CAST() function to convert a string to a datetime value example.The below example uses the CAST() function to convert the string to a datetime.SELECT CAST('2020-09-14' AS DATETIME) \nAS Result;Output :Result2020-09-14 00:00:00.000" }, { "code": null, "e": 26277, "s": 26227, "text": "SELECT CAST('2020-09-14' AS DATETIME) \nAS Result;" }, { "code": null, "e": 26286, "s": 26277, "text": "Output :" }, { "code": null, "e": 26295, "s": 26286, "text": "DBMS-SQL" }, { "code": null, "e": 26306, "s": 26295, "text": "SQL-Server" }, { "code": null, "e": 26310, "s": 26306, "text": "SQL" }, { "code": null, "e": 26314, "s": 26310, "text": "SQL" }, { "code": null, "e": 26412, "s": 26314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26421, "s": 26412, "text": "Comments" }, { "code": null, "e": 26434, "s": 26421, "text": "Old Comments" }, { "code": null, "e": 26500, "s": 26434, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26553, "s": 26500, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 26585, "s": 26553, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26602, "s": 26585, "text": "SQL using Python" }, { "code": null, "e": 26680, "s": 26602, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26695, "s": 26680, "text": "SQL | Subquery" }, { "code": null, "e": 26731, "s": 26695, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 26784, "s": 26731, "text": "SQL - SELECT from Multiple Tables with MS SQL Server" }, { "code": null, "e": 26805, "s": 26784, "text": "SQL | Date functions" } ]
Explain about the Time stamp ordering protocol in DBMS
The timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions. A conflict occurs when an older transaction tries to read/write a value already read or written by a younger transaction. Read or write proceeds only if the last update on that data item was carried out by an older transaction. Otherwise, the transaction requesting read/write is restarted and gives a new timestamp. Here no locks are used so no deadlock. The timestamp of transaction Ti is denoted as TS(Ti). The timestamp of transaction Ti is denoted as TS(Ti). Read time-stamp of data-item X is denoted by R-timestamp(X). Read time-stamp of data-item X is denoted by R-timestamp(X). Write time-stamp of data-item X is denoted by W-timestamp(X). Write time-stamp of data-item X is denoted by W-timestamp(X). These timestamps are updated after a successful read/write operation on data item X. Older transactions get priority over younger transactions in the event of conflict operation. Conflict is resolved by rolling back and restarting transactions. To ensure serializability following rules are used − Rule 1 − If a transaction Ti issues a read(X) operation. If TS(Ti) < W-timestamp(X) Operation rejected. If TS(Ti) >= W-timestamp(X) Operation executed. All data-item timestamps updated. Rule 2 − If a transaction Ti issues a write(X) operation. If TS(Ti) < R-timestamp(X) Operation rejected. If TS(Ti) < W-timestamp(X) Operation rejected and Ti rolled back. Otherwise, the operation is executed. This rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back. Time-stamp ordering rules can be modified to make the schedule view serializable. Instead of making Ti rolled back, the 'write' operation itself is ignored. EFFECT − Thomas Write Rule allows such operations and is a modification on the Basic Timestamp Ordering protocol. In Thomas Write Rule users ignore outdated writes. S: f1(X) W2(X) W1(X) Check whether timestamp ordering protocol allows schedule S. X-----------------RTS------3 X----------------WTS------4 For f1(X) : TS(Ti) <WTS(X) i.e TS(T1)<WTS(X) 3<0 (FALSE) GOTO else and perform write operation W2(X) AND WTS(X)=4 For W1(X): TS(Ti)<RTS(X) i.e TS(T1)<RTS(X) 3<3 (FALSE) TS(T1)<WTS(X) 3<4 (TRUE) ROLLBACK
[ { "code": null, "e": 1344, "s": 1062, "text": "The timestamp-ordering protocol ensures serializability among transactions in their conflicting read and write operations. This is the responsibility of the protocol system that the conflicting pair of tasks should be executed according to the timestamp values of the transactions." }, { "code": null, "e": 1572, "s": 1344, "text": "A conflict occurs when an older transaction tries to read/write a value already read or written by a younger transaction. Read or write proceeds only if the last update on that data item was carried out by an older transaction." }, { "code": null, "e": 1700, "s": 1572, "text": "Otherwise, the transaction requesting read/write is restarted and gives a new timestamp. Here no locks are used so no deadlock." }, { "code": null, "e": 1754, "s": 1700, "text": "The timestamp of transaction Ti is denoted as TS(Ti)." }, { "code": null, "e": 1808, "s": 1754, "text": "The timestamp of transaction Ti is denoted as TS(Ti)." }, { "code": null, "e": 1869, "s": 1808, "text": "Read time-stamp of data-item X is denoted by R-timestamp(X)." }, { "code": null, "e": 1930, "s": 1869, "text": "Read time-stamp of data-item X is denoted by R-timestamp(X)." }, { "code": null, "e": 1992, "s": 1930, "text": "Write time-stamp of data-item X is denoted by W-timestamp(X)." }, { "code": null, "e": 2054, "s": 1992, "text": "Write time-stamp of data-item X is denoted by W-timestamp(X)." }, { "code": null, "e": 2139, "s": 2054, "text": "These timestamps are updated after a successful read/write operation on data item X." }, { "code": null, "e": 2299, "s": 2139, "text": "Older transactions get priority over younger transactions in the event of conflict operation. Conflict is resolved by rolling back and restarting transactions." }, { "code": null, "e": 2352, "s": 2299, "text": "To ensure serializability following rules are used −" }, { "code": null, "e": 2409, "s": 2352, "text": "Rule 1 − If a transaction Ti issues a read(X) operation." }, { "code": null, "e": 2436, "s": 2409, "text": "If TS(Ti) < W-timestamp(X)" }, { "code": null, "e": 2456, "s": 2436, "text": "Operation rejected." }, { "code": null, "e": 2484, "s": 2456, "text": "If TS(Ti) >= W-timestamp(X)" }, { "code": null, "e": 2504, "s": 2484, "text": "Operation executed." }, { "code": null, "e": 2538, "s": 2504, "text": "All data-item timestamps updated." }, { "code": null, "e": 2596, "s": 2538, "text": "Rule 2 − If a transaction Ti issues a write(X) operation." }, { "code": null, "e": 2623, "s": 2596, "text": "If TS(Ti) < R-timestamp(X)" }, { "code": null, "e": 2643, "s": 2623, "text": "Operation rejected." }, { "code": null, "e": 2670, "s": 2643, "text": "If TS(Ti) < W-timestamp(X)" }, { "code": null, "e": 2709, "s": 2670, "text": "Operation rejected and Ti rolled back." }, { "code": null, "e": 2747, "s": 2709, "text": "Otherwise, the operation is executed." }, { "code": null, "e": 2846, "s": 2747, "text": "This rule states if TS(Ti) < W-timestamp(X), then the operation is rejected and Ti is rolled back." }, { "code": null, "e": 2928, "s": 2846, "text": "Time-stamp ordering rules can be modified to make the schedule view serializable." }, { "code": null, "e": 3003, "s": 2928, "text": "Instead of making Ti rolled back, the 'write' operation itself is ignored." }, { "code": null, "e": 3168, "s": 3003, "text": "EFFECT − Thomas Write Rule allows such operations and is a modification on the Basic Timestamp Ordering protocol. In Thomas Write Rule users ignore outdated writes." }, { "code": null, "e": 3189, "s": 3168, "text": "S: f1(X) W2(X) W1(X)" }, { "code": null, "e": 3250, "s": 3189, "text": "Check whether timestamp ordering protocol allows schedule S." }, { "code": null, "e": 3367, "s": 3250, "text": "X-----------------RTS------3\nX----------------WTS------4\nFor f1(X) : TS(Ti) <WTS(X) i.e TS(T1)<WTS(X)\n 3<0 (FALSE)" }, { "code": null, "e": 3424, "s": 3367, "text": "GOTO else and perform write operation W2(X) AND WTS(X)=4" }, { "code": null, "e": 3528, "s": 3424, "text": "For W1(X): TS(Ti)<RTS(X) i.e TS(T1)<RTS(X)\n 3<3 (FALSE)\n TS(T1)<WTS(X)\n 3<4 (TRUE)\nROLLBACK" } ]
Return array from function in C
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index. If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example − int * myFunction() { . . . } Second point to remember is that C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable. Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows − #include <stdio.h> /* function to generate and return random numbers */ int * getRandom( ) { static int r[10]; int i; /* set the seed */ srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf( "r[%d] = %d\n", i, r[i]); } return r; } /* main function to call above defined function */ int main () { /* a pointer to an int */ int *p; int i; p = getRandom(); for ( i = 0; i < 10; i++ ) { printf( "*(p + %d) : %d\n", i, *(p + i)); } return 0; } When the above code is compiled together and executed, it produces the following result − r[0] = 313959809 r[1] = 1759055877 r[2] = 1113101911 r[3] = 2133832223 r[4] = 2073354073 r[5] = 167288147 r[6] = 1827471542 r[7] = 834791014 r[8] = 1901409888 r[9] = 1990469526 *(p + 0) : 313959809 *(p + 1) : 1759055877 *(p + 2) : 1113101911 *(p + 3) : 2133832223 *(p + 4) : 2073354073 *(p + 5) : 167288147 *(p + 6) : 1827471542 *(p + 7) : 834791014 *(p + 8) : 1901409888 *(p + 9) : 1990469526 Print Add Notes Bookmark this page
[ { "code": null, "e": 2264, "s": 2084, "text": "C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index." }, { "code": null, "e": 2415, "s": 2264, "text": "If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example −" }, { "code": null, "e": 2453, "s": 2415, "text": "int * myFunction() {\n .\n .\n .\n}" }, { "code": null, "e": 2643, "s": 2453, "text": "Second point to remember is that C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable." }, { "code": null, "e": 2785, "s": 2643, "text": "Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows −" }, { "code": null, "e": 3328, "s": 2785, "text": "#include <stdio.h>\n\n/* function to generate and return random numbers */\nint * getRandom( ) {\n\n static int r[10];\n int i;\n\n /* set the seed */\n srand( (unsigned)time( NULL ) );\n \n for ( i = 0; i < 10; ++i) {\n r[i] = rand();\n printf( \"r[%d] = %d\\n\", i, r[i]);\n }\n\n return r;\n}\n\n/* main function to call above defined function */\nint main () {\n\n /* a pointer to an int */\n int *p;\n int i;\n\n p = getRandom();\n\t\n for ( i = 0; i < 10; i++ ) {\n printf( \"*(p + %d) : %d\\n\", i, *(p + i));\n }\n\n return 0;\n}" }, { "code": null, "e": 3418, "s": 3328, "text": "When the above code is compiled together and executed, it produces the following result −" }, { "code": null, "e": 3813, "s": 3418, "text": "r[0] = 313959809\nr[1] = 1759055877\nr[2] = 1113101911\nr[3] = 2133832223\nr[4] = 2073354073\nr[5] = 167288147\nr[6] = 1827471542\nr[7] = 834791014\nr[8] = 1901409888\nr[9] = 1990469526\n*(p + 0) : 313959809\n*(p + 1) : 1759055877\n*(p + 2) : 1113101911\n*(p + 3) : 2133832223\n*(p + 4) : 2073354073\n*(p + 5) : 167288147\n*(p + 6) : 1827471542\n*(p + 7) : 834791014\n*(p + 8) : 1901409888\n*(p + 9) : 1990469526\n" }, { "code": null, "e": 3820, "s": 3813, "text": " Print" }, { "code": null, "e": 3831, "s": 3820, "text": " Add Notes" } ]
Print first letter of every word in the string | Practice | GeeksforGeeks
Given a string S, the task is to create a string with the first letter of every word in the string. Example 1: Input: S = "geeks for geeks" Output: gfg Example 2: Input: S = "bad is good" Output: big Your Task: You don't need to read input or print anything. Your task is to complete the function firstAlphabet() which takes string S as input parameter and returns a string that contains the first letter of every word in S. Expected Time Complexity: O(|S|) Expected Auxiliary Space: O(|S|) Constraints: 1 <= |S| <= 105 S contains lower case English alphabets Words have a single space between them. 0 radhikamendiratta199411 hours ago python solution def firstAlphabet(self, S): if S[0] != ' ': output = S[0] for i in range(len(S)): if S[i] ==' ': output += S[i+1] return output +1 sharvilpatil1312 hours ago JAVA CODE class Solution { String firstAlphabet(String S) { String res=""+S.charAt(0); for(int i=0; i<S.length()-1; i++) { if(S.charAt(i)==' ' && S.charAt(i+1)!=' ') res=res+S.charAt(i+1); } return res; }}; 0 criticaugen3 days ago #Python Code: #changing the string into list and checking the values #code : def firstAlphabet(self, S): # code here S=list(S) output="" for i in range(len(S)): if i==0 and S[i].isalpha(): output+=S[i] elif S[i].isalpha() and S[i-1]==" ": output+=S[i] return output 0 shykatroybdku1994 days ago String firstAlphabet(String S) { String string=""; for(int i=0; i<S.length(); i++){ if(S.charAt(i)!=' '){ if(i==0){ string+=(S.charAt(i)); }else if(S.charAt(i-1)== ' '){ string+=(S.charAt(i)); } } } return string; 0 abhilaygude1 week ago class Solution:def firstAlphabet(self, S): l=[] if len(S)>0: l.append(S[0]) for i in range(len(S)): if S[i]==' ': l.append(S[i+1]) c='' for i in l: c+=i return c 0 deeplakhotia8761 week ago Simple Python solution x="" s=S.split(" ") for i in s: x+=i[0] return x Upvote if it helped you 0 mayank180919991 week ago string firstAlphabet(string S) { // Your code goes here string str; str.push_back(S[0]); for(int i=1;i<S.length();i++){ if(S[i]==' '){ str.push_back(S[i+1]); } } return str; } 0 gurankitbehal781141 week ago class Solution{public: string firstAlphabet(string S){ string s=""; s.push_back(S[0]); for(int i=0;i<S.length();i++){ if(S[i]==' '){ s.push_back(S[i+1]); } } return s;}}; 0 manavkanjiyanijobupdate3 weeks ago JAVA SOLUTION – ALL TEST CASE PASS class Solution { String firstAlphabet(String S) { String s = ""; s = String.valueOf(S.charAt(0)); for(int i = 0; i < S.length()-1;i++) { if(String.valueOf(S.charAt(i)).equals(" ")) { s = s + S.charAt(i+1); } } return s; }}; 0 sanyasi13104 weeks ago ##JAVA##### String[] ab = S.split(" "); StringBuilder sb = new StringBuilder(); for(String str: ab){ sb.append(str.charAt(0)); } return sb.toString(); 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": 340, "s": 238, "text": "Given a string S, the task is to create a string with the first letter of every word in the string.\n " }, { "code": null, "e": 351, "s": 340, "text": "Example 1:" }, { "code": null, "e": 395, "s": 351, "text": "Input: \nS = \"geeks for geeks\"\nOutput: gfg\n\n" }, { "code": null, "e": 406, "s": 395, "text": "Example 2:" }, { "code": null, "e": 446, "s": 406, "text": "Input: \nS = \"bad is good\"\nOutput: big\n\n" }, { "code": null, "e": 671, "s": 446, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function firstAlphabet() which takes string S as input parameter and returns a string that contains the first letter of every word in S." }, { "code": null, "e": 738, "s": 671, "text": "\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(|S|)" }, { "code": null, "e": 849, "s": 738, "text": "\nConstraints:\n1 <= |S| <= 105\nS contains lower case English alphabets\nWords have a single space between them. " }, { "code": null, "e": 851, "s": 849, "text": "0" }, { "code": null, "e": 885, "s": 851, "text": "radhikamendiratta199411 hours ago" }, { "code": null, "e": 901, "s": 885, "text": "python solution" }, { "code": null, "e": 1060, "s": 901, "text": "def firstAlphabet(self, S):\n\t if S[0] != ' ':\n\t\t output = S[0]\n\t\tfor i in range(len(S)):\n\t\t if S[i] ==' ':\n\t\t output += S[i+1]\n\t\treturn output" }, { "code": null, "e": 1063, "s": 1060, "text": "+1" }, { "code": null, "e": 1090, "s": 1063, "text": "sharvilpatil1312 hours ago" }, { "code": null, "e": 1100, "s": 1090, "text": "JAVA CODE" }, { "code": null, "e": 1344, "s": 1100, "text": "class Solution { String firstAlphabet(String S) { String res=\"\"+S.charAt(0); for(int i=0; i<S.length()-1; i++) { if(S.charAt(i)==' ' && S.charAt(i+1)!=' ') res=res+S.charAt(i+1); } return res; }};" }, { "code": null, "e": 1346, "s": 1344, "text": "0" }, { "code": null, "e": 1368, "s": 1346, "text": "criticaugen3 days ago" }, { "code": null, "e": 1382, "s": 1368, "text": "#Python Code:" }, { "code": null, "e": 1437, "s": 1382, "text": "#changing the string into list and checking the values" }, { "code": null, "e": 1445, "s": 1437, "text": "#code :" }, { "code": null, "e": 1503, "s": 1447, "text": "def firstAlphabet(self, S): # code here S=list(S)" }, { "code": null, "e": 1517, "s": 1503, "text": " output=\"\"" }, { "code": null, "e": 1545, "s": 1517, "text": " for i in range(len(S)):" }, { "code": null, "e": 1581, "s": 1545, "text": " if i==0 and S[i].isalpha():" }, { "code": null, "e": 1606, "s": 1581, "text": " output+=S[i]" }, { "code": null, "e": 1651, "s": 1606, "text": " elif S[i].isalpha() and S[i-1]==\" \":" }, { "code": null, "e": 1676, "s": 1651, "text": " output+=S[i]" }, { "code": null, "e": 1694, "s": 1676, "text": " return output" }, { "code": null, "e": 1696, "s": 1694, "text": "0" }, { "code": null, "e": 1723, "s": 1696, "text": "shykatroybdku1994 days ago" }, { "code": null, "e": 2059, "s": 1723, "text": "String firstAlphabet(String S) { String string=\"\"; for(int i=0; i<S.length(); i++){ if(S.charAt(i)!=' '){ if(i==0){ string+=(S.charAt(i)); }else if(S.charAt(i-1)== ' '){ string+=(S.charAt(i)); } } } return string;" }, { "code": null, "e": 2061, "s": 2059, "text": "0" }, { "code": null, "e": 2083, "s": 2061, "text": "abhilaygude1 week ago" }, { "code": null, "e": 2270, "s": 2083, "text": "class Solution:def firstAlphabet(self, S): l=[] if len(S)>0: l.append(S[0]) for i in range(len(S)): if S[i]==' ': l.append(S[i+1]) c='' for i in l: c+=i return c " }, { "code": null, "e": 2278, "s": 2276, "text": "0" }, { "code": null, "e": 2304, "s": 2278, "text": "deeplakhotia8761 week ago" }, { "code": null, "e": 2327, "s": 2304, "text": "Simple Python solution" }, { "code": null, "e": 2383, "s": 2329, "text": "x=\"\" s=S.split(\" \") for i in s: x+=i[0] return x " }, { "code": null, "e": 2409, "s": 2385, "text": "Upvote if it helped you" }, { "code": null, "e": 2411, "s": 2409, "text": "0" }, { "code": null, "e": 2436, "s": 2411, "text": "mayank180919991 week ago" }, { "code": null, "e": 2676, "s": 2436, "text": "\tstring firstAlphabet(string S)\n\t{\n\t // Your code goes here\n\t string str;\n\t str.push_back(S[0]);\n\t for(int i=1;i<S.length();i++){\n\t if(S[i]==' '){\n\t str.push_back(S[i+1]);\n\t }\n\t }\n\t return str;\n\t}" }, { "code": null, "e": 2678, "s": 2676, "text": "0" }, { "code": null, "e": 2707, "s": 2678, "text": "gurankitbehal781141 week ago" }, { "code": null, "e": 2916, "s": 2707, "text": "class Solution{public: string firstAlphabet(string S){ string s=\"\"; s.push_back(S[0]); for(int i=0;i<S.length();i++){ if(S[i]==' '){ s.push_back(S[i+1]); } } return s;}};" }, { "code": null, "e": 2918, "s": 2916, "text": "0" }, { "code": null, "e": 2953, "s": 2918, "text": "manavkanjiyanijobupdate3 weeks ago" }, { "code": null, "e": 2988, "s": 2953, "text": "JAVA SOLUTION – ALL TEST CASE PASS" }, { "code": null, "e": 3332, "s": 2988, "text": "class Solution { String firstAlphabet(String S) { String s = \"\"; s = String.valueOf(S.charAt(0)); for(int i = 0; i < S.length()-1;i++) { if(String.valueOf(S.charAt(i)).equals(\" \")) { s = s + S.charAt(i+1); } } return s; }};" }, { "code": null, "e": 3334, "s": 3332, "text": "0" }, { "code": null, "e": 3357, "s": 3334, "text": "sanyasi13104 weeks ago" }, { "code": null, "e": 3369, "s": 3357, "text": "##JAVA#####" }, { "code": null, "e": 3553, "s": 3369, "text": "String[] ab = S.split(\" \"); StringBuilder sb = new StringBuilder(); for(String str: ab){ sb.append(str.charAt(0)); } return sb.toString();" }, { "code": null, "e": 3699, "s": 3553, "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": 3735, "s": 3699, "text": " Login to access your submissions. " }, { "code": null, "e": 3745, "s": 3735, "text": "\nProblem\n" }, { "code": null, "e": 3755, "s": 3745, "text": "\nContest\n" }, { "code": null, "e": 3818, "s": 3755, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3966, "s": 3818, "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": 4174, "s": 3966, "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": 4280, "s": 4174, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Concatenation of two strings in PHP
16 Jun, 2022 There are two string operators. The first is the concatenation operator (‘.‘), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (‘.=‘), which appends the argument on the right side to the argument on the left side. Examples : Input : string1: Hello string2 : World! Output : HelloWorld! Input : string1: geeksfor string2: geeks Output : geeksforgeeks Code #1: PHP <?php // First String$a = 'Hello'; // Second String$b = 'World!'; // Concatenation Of String$c = $a.$b; // print Concatenate Stringecho " $c \n";?> Output : HelloWorld! Time complexity : O(n) Auxiliary Space : O(n) Code #2 : PHP <?php // First String$fname = 'John'; // Second String$lname = 'Carter!'; // Concatenation Of String$c = $fname." ".$lname; // print Concatenate Stringecho " $c \n";?> Output : John Carter! Time complexity : O(n) Auxiliary Space : O(n) Code #3 : PHP <?php // First String$a = 'Hello'; // now $a contains "HelloWorld!"$a. = "World!"; // Print The String $aecho " $a \n";?> Output : HelloWorld! Time complexity : O(n) Auxiliary Space : O(n) 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. mahendrabagul569 PHP-string PHP Strings Web Technologies Strings PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Jun, 2022" }, { "code": null, "e": 347, "s": 53, "text": "There are two string operators. The first is the concatenation operator (‘.‘), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (‘.=‘), which appends the argument on the right side to the argument on the left side. Examples :" }, { "code": null, "e": 492, "s": 347, "text": "Input : string1: Hello\n string2 : World! \nOutput : HelloWorld!\n\n\nInput : string1: geeksfor\n string2: geeks\nOutput : geeksforgeeks" }, { "code": null, "e": 502, "s": 492, "text": "Code #1: " }, { "code": null, "e": 506, "s": 502, "text": "PHP" }, { "code": "<?php // First String$a = 'Hello'; // Second String$b = 'World!'; // Concatenation Of String$c = $a.$b; // print Concatenate Stringecho \" $c \\n\";?>", "e": 654, "s": 506, "text": null }, { "code": null, "e": 663, "s": 654, "text": "Output :" }, { "code": null, "e": 676, "s": 663, "text": " HelloWorld!" }, { "code": null, "e": 722, "s": 676, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 735, "s": 722, "text": " Code #2 : " }, { "code": null, "e": 739, "s": 735, "text": "PHP" }, { "code": "<?php // First String$fname = 'John'; // Second String$lname = 'Carter!'; // Concatenation Of String$c = $fname.\" \".$lname; // print Concatenate Stringecho \" $c \\n\";?>", "e": 907, "s": 739, "text": null }, { "code": null, "e": 916, "s": 907, "text": "Output :" }, { "code": null, "e": 929, "s": 916, "text": "John Carter!" }, { "code": null, "e": 975, "s": 929, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 988, "s": 975, "text": " Code #3 : " }, { "code": null, "e": 992, "s": 988, "text": "PHP" }, { "code": "<?php // First String$a = 'Hello'; // now $a contains \"HelloWorld!\"$a. = \"World!\"; // Print The String $aecho \" $a \\n\";?>", "e": 1114, "s": 992, "text": null }, { "code": null, "e": 1123, "s": 1114, "text": "Output :" }, { "code": null, "e": 1136, "s": 1123, "text": " HelloWorld!" }, { "code": null, "e": 1182, "s": 1136, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 1351, "s": 1182, "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": 1368, "s": 1351, "text": "mahendrabagul569" }, { "code": null, "e": 1379, "s": 1368, "text": "PHP-string" }, { "code": null, "e": 1383, "s": 1379, "text": "PHP" }, { "code": null, "e": 1391, "s": 1383, "text": "Strings" }, { "code": null, "e": 1408, "s": 1391, "text": "Web Technologies" }, { "code": null, "e": 1416, "s": 1408, "text": "Strings" }, { "code": null, "e": 1420, "s": 1416, "text": "PHP" } ]
MySQL | Deleting rows when there is a foreign key
08 Apr, 2021 In this article, let us discuss the overview of the foreign key in SQL and the main focus will be on how to delete a foreign key in MySQL.Let’s discuss it step-by-step. Foreign key : In Foreign key, when an attribute in one table which is a non-primary key references the same attribute which is the primary key in another table then the non-prime key is called the foreign key. We use the foreign key references in order to make the links between the tables and whatever action is done in any of the tables. Steps for deleting rows when there is a foreign key in MySQL :Here, we will discuss the required steps to implement deleting rows when there is a foreign key in MySQL with the help of examples for better understanding. Step-1: Creating a database :Creating a database student by using the following SQL query as follows. CREATE DATABASE student; Output : Step-2: Using the database :Using the database student using the following SQL query as follows. USE student; Output : Step-3: Creating two tables :Table1 –Creating a table student_details with 3 columns using the following SQL query as follows. CREATE TABLE student_details ( student_id INT PRIMARY KEY, Student_name varchar(8), student_year varchar(8) ); Output : Table2 –Creating a table student_exam with 3 columns using the following SQL query as follows. CREATE TABLE student_exam ( exam_id INT PRIMARY KEY, exam_name varchar(8), student_id INT, FOREIGN KEY(student_id) REFERENCES student_details(student_id) ON DELETE CASCADE ); Output :Table student_exam has foreign key student_id referencing student_id in student_details table. Here, ON DELETE CASCADE is added because when any row is deleted in one table the same gets deleted in the foreign referenced tables that are referencing the primary key in that table. Step-4: Verifying the database :To view the description of the tables in the database using the following SQL query as follows. DESCRIBE student_details; Output : DESCRIBE student_exam; Output :Here, we can see MUL for the foreign key in the key column. Step-5: Inserting data into the table :Inserting rows into student_details table using the following SQL query as follows. INSERT INTO student_details VALUES(19102047,'PRADEEP','1st'); INSERT INTO student_details VALUES(19102048,'KOUSHIK','1st'); INSERT INTO student_details VALUES(19102049,'SATWIK','2st'); INSERT INTO student_details VALUES(19102050,'VAMSI','2nd'); Output : Inserting rows into student_exam table using the following SQL query as follows. INSERT INTO student_exam VALUES(9001,'DBMS','19102047'); INSERT INTO student_exam VALUES(9002,'C.N','19102048'); INSERT INTO student_exam VALUES(9003,'O.S','19102049'); INSERT INTO student_exam VALUES(9004,'O.S','19102050'); Output : Step-6: Verifying the inserted data :Viewing the table student_details after inserting rows by using the following SQL query as follows. SELECT * FROM student_details; Output : Viewing the table student_exam after inserting rows by using the following SQL query as follows. SELECT* FROM student_exam; Output : Note – If ON DELETE CASCADE constraint is not used then referencing error occurs. Step-7: Deleting rows when there is a foreign key :Query to delete a student with id 19102048 from student_exam table where referenced tables are student_details.Syntax – DELETE FROM table_name WHERE constraint; Query – DELETE FROM student_details WHERE student_id=19102048; Output: Before Deleting – Output: After Deleting –The rows with student id 19102048 are deleted in both tables. DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Apr, 2021" }, { "code": null, "e": 223, "s": 54, "text": "In this article, let us discuss the overview of the foreign key in SQL and the main focus will be on how to delete a foreign key in MySQL.Let’s discuss it step-by-step." }, { "code": null, "e": 563, "s": 223, "text": "Foreign key : In Foreign key, when an attribute in one table which is a non-primary key references the same attribute which is the primary key in another table then the non-prime key is called the foreign key. We use the foreign key references in order to make the links between the tables and whatever action is done in any of the tables." }, { "code": null, "e": 782, "s": 563, "text": "Steps for deleting rows when there is a foreign key in MySQL :Here, we will discuss the required steps to implement deleting rows when there is a foreign key in MySQL with the help of examples for better understanding." }, { "code": null, "e": 884, "s": 782, "text": "Step-1: Creating a database :Creating a database student by using the following SQL query as follows." }, { "code": null, "e": 909, "s": 884, "text": "CREATE DATABASE student;" }, { "code": null, "e": 918, "s": 909, "text": "Output :" }, { "code": null, "e": 1015, "s": 918, "text": "Step-2: Using the database :Using the database student using the following SQL query as follows." }, { "code": null, "e": 1028, "s": 1015, "text": "USE student;" }, { "code": null, "e": 1037, "s": 1028, "text": "Output :" }, { "code": null, "e": 1165, "s": 1037, "text": "Step-3: Creating two tables :Table1 –Creating a table student_details with 3 columns using the following SQL query as follows." }, { "code": null, "e": 1291, "s": 1165, "text": "CREATE TABLE student_details\n(\n student_id INT PRIMARY KEY,\n Student_name varchar(8),\n student_year varchar(8)\n);" }, { "code": null, "e": 1300, "s": 1291, "text": "Output :" }, { "code": null, "e": 1395, "s": 1300, "text": "Table2 –Creating a table student_exam with 3 columns using the following SQL query as follows." }, { "code": null, "e": 1584, "s": 1395, "text": "CREATE TABLE student_exam\n(\n exam_id INT PRIMARY KEY,\n exam_name varchar(8),\n student_id INT,\n FOREIGN KEY(student_id) \n REFERENCES student_details(student_id) \n ON DELETE CASCADE\n);" }, { "code": null, "e": 1872, "s": 1584, "text": "Output :Table student_exam has foreign key student_id referencing student_id in student_details table. Here, ON DELETE CASCADE is added because when any row is deleted in one table the same gets deleted in the foreign referenced tables that are referencing the primary key in that table." }, { "code": null, "e": 2000, "s": 1872, "text": "Step-4: Verifying the database :To view the description of the tables in the database using the following SQL query as follows." }, { "code": null, "e": 2026, "s": 2000, "text": "DESCRIBE student_details;" }, { "code": null, "e": 2035, "s": 2026, "text": "Output :" }, { "code": null, "e": 2058, "s": 2035, "text": "DESCRIBE student_exam;" }, { "code": null, "e": 2126, "s": 2058, "text": "Output :Here, we can see MUL for the foreign key in the key column." }, { "code": null, "e": 2249, "s": 2126, "text": "Step-5: Inserting data into the table :Inserting rows into student_details table using the following SQL query as follows." }, { "code": null, "e": 2494, "s": 2249, "text": "INSERT INTO student_details VALUES(19102047,'PRADEEP','1st');\nINSERT INTO student_details VALUES(19102048,'KOUSHIK','1st');\nINSERT INTO student_details VALUES(19102049,'SATWIK','2st');\nINSERT INTO student_details VALUES(19102050,'VAMSI','2nd');" }, { "code": null, "e": 2503, "s": 2494, "text": "Output :" }, { "code": null, "e": 2584, "s": 2503, "text": "Inserting rows into student_exam table using the following SQL query as follows." }, { "code": null, "e": 2809, "s": 2584, "text": "INSERT INTO student_exam VALUES(9001,'DBMS','19102047');\nINSERT INTO student_exam VALUES(9002,'C.N','19102048');\nINSERT INTO student_exam VALUES(9003,'O.S','19102049');\nINSERT INTO student_exam VALUES(9004,'O.S','19102050');" }, { "code": null, "e": 2818, "s": 2809, "text": "Output :" }, { "code": null, "e": 2955, "s": 2818, "text": "Step-6: Verifying the inserted data :Viewing the table student_details after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 2986, "s": 2955, "text": "SELECT * FROM student_details;" }, { "code": null, "e": 2995, "s": 2986, "text": "Output :" }, { "code": null, "e": 3092, "s": 2995, "text": "Viewing the table student_exam after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 3119, "s": 3092, "text": "SELECT* FROM student_exam;" }, { "code": null, "e": 3128, "s": 3119, "text": "Output :" }, { "code": null, "e": 3210, "s": 3128, "text": "Note – If ON DELETE CASCADE constraint is not used then referencing error occurs." }, { "code": null, "e": 3381, "s": 3210, "text": "Step-7: Deleting rows when there is a foreign key :Query to delete a student with id 19102048 from student_exam table where referenced tables are student_details.Syntax –" }, { "code": null, "e": 3424, "s": 3381, "text": " DELETE FROM table_name\n WHERE constraint;" }, { "code": null, "e": 3432, "s": 3424, "text": "Query –" }, { "code": null, "e": 3489, "s": 3432, "text": " DELETE FROM student_details\n WHERE student_id=19102048;" }, { "code": null, "e": 3515, "s": 3489, "text": "Output: Before Deleting –" }, { "code": null, "e": 3601, "s": 3515, "text": "Output: After Deleting –The rows with student id 19102048 are deleted in both tables." }, { "code": null, "e": 3610, "s": 3601, "text": "DBMS-SQL" }, { "code": null, "e": 3616, "s": 3610, "text": "mysql" }, { "code": null, "e": 3620, "s": 3616, "text": "SQL" }, { "code": null, "e": 3624, "s": 3620, "text": "SQL" } ]
SQL Right Join
26 Apr, 2021 The RIGHT JOIN keyword in SQL returns the all matching records(or rows) and the records(or rows) which are present in the right table but not in the left table .That means that, if a certain row is present in the right table but not in the left, the result will include this row but with a NULL value in each column from the left . If a record from the left table is not in the right, it will not be included in the result. RIGHT JOIN The syntax for a RIGHT JOIN is :- SELECT column_name(s) FROM tableA RIGHT JOIN tableB ON tableA.column_name = tableB.column_name; SQL RIGHT JOIN EXAMPLE : In this example we will consider two tables employee table containing details of the employees working in the particular department the and department table containing the details of the department employee table : department table : To perform right- join on these two tables we will use the following SQL query: select emp_no , emp_name ,d_name, location from employee right join dept on employee.dept_no = department.dept_no; The output that we will get is as follows : As right join gives the matching rows and the rows that are present in the left table but not in the right table .Here in this example ,we see that the department that contains no employee contains [NULL] values of emp_no and emp_name after performing the right join. DBMS-SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Apr, 2021" }, { "code": null, "e": 452, "s": 28, "text": "The RIGHT JOIN keyword in SQL returns the all matching records(or rows) and the records(or rows) which are present in the right table but not in the left table .That means that, if a certain row is present in the right table but not in the left, the result will include this row but with a NULL value in each column from the left . If a record from the left table is not in the right, it will not be included in the result." }, { "code": null, "e": 463, "s": 452, "text": "RIGHT JOIN" }, { "code": null, "e": 497, "s": 463, "text": "The syntax for a RIGHT JOIN is :-" }, { "code": null, "e": 595, "s": 497, "text": "SELECT column_name(s) \nFROM tableA \nRIGHT JOIN tableB ON tableA.column_name = tableB.column_name;" }, { "code": null, "e": 621, "s": 595, "text": "SQL RIGHT JOIN EXAMPLE :" }, { "code": null, "e": 819, "s": 621, "text": "In this example we will consider two tables employee table containing details of the employees working in the particular department the and department table containing the details of the department" }, { "code": null, "e": 836, "s": 819, "text": "employee table :" }, { "code": null, "e": 855, "s": 836, "text": "department table :" }, { "code": null, "e": 935, "s": 855, "text": "To perform right- join on these two tables we will use the following SQL query:" }, { "code": null, "e": 1052, "s": 935, "text": "select emp_no , emp_name ,d_name, location \nfrom employee \nright join dept on employee.dept_no = department.dept_no;" }, { "code": null, "e": 1097, "s": 1052, "text": "The output that we will get is as follows : " }, { "code": null, "e": 1366, "s": 1097, "text": "As right join gives the matching rows and the rows that are present in the left table but not in the right table .Here in this example ,we see that the department that contains no employee contains [NULL] values of emp_no and emp_name after performing the right join." }, { "code": null, "e": 1375, "s": 1366, "text": "DBMS-SQL" }, { "code": null, "e": 1380, "s": 1375, "text": "DBMS" }, { "code": null, "e": 1384, "s": 1380, "text": "SQL" }, { "code": null, "e": 1389, "s": 1384, "text": "DBMS" }, { "code": null, "e": 1393, "s": 1389, "text": "SQL" } ]
Python | Truncate a list
04 Jan, 2019 Sometimes there is a requirement to restrict the list size to a particular number and remove all the elements from list which occur after a certain number as decided as list size. This is a useful utility for web development using Python. Let’s discuss certain ways in which this can be performed. Method #1 : Using pop()pop function can be repeated a number of times till size of the list reaches the threshold required as the size of the list. This uses a whole loop and hence is comparatively tedious. # Python3 code to demonstrate # to truncate list using pop() # initializing list test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10] # printing original listprint ("The original list is : " + str(test_list)) # size desiredk = 5 # using pop()# to truncate list n = len(test_list)for i in range(0, n - k ): test_list.pop() # printing resultprint ("The truncated list is : " + str(test_list)) The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10] The truncated list is : [1, 4, 5, 6, 7] Method #2 : Using del + list slicedel operator can be used to delete all the elements that appear after the specific index, which is handled by the list slicing technique. # Python3 code to demonstrate # to truncate list # using del + list slicing # initializing list test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10] # printing original listprint ("The original list is : " + str(test_list)) # size desiredk = 5 # using del + list slicing# to truncate list del test_list[5:] # printing resultprint ("The truncated list is : " + str(test_list)) The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10] The truncated list is : [1, 4, 5, 6, 7] Method #3 : Using list slicingIn this method, we just slice the first K elements and ignore all the elements that occur after K elements. This is most pythonic and recommended method to perform this task. # Python3 code to demonstrate # to truncate list # using list slicing # initializing list test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10] # printing original listprint ("The original list is : " + str(test_list)) # size desiredk = 5 # using list slicing# to truncate list res = test_list[0 : 5] # printing resultprint ("The truncated list is : " + str(res)) The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10] The truncated list is : [1, 4, 5, 6, 7] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2019" }, { "code": null, "e": 326, "s": 28, "text": "Sometimes there is a requirement to restrict the list size to a particular number and remove all the elements from list which occur after a certain number as decided as list size. This is a useful utility for web development using Python. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 533, "s": 326, "text": "Method #1 : Using pop()pop function can be repeated a number of times till size of the list reaches the threshold required as the size of the list. This uses a whole loop and hence is comparatively tedious." }, { "code": "# Python3 code to demonstrate # to truncate list using pop() # initializing list test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10] # printing original listprint (\"The original list is : \" + str(test_list)) # size desiredk = 5 # using pop()# to truncate list n = len(test_list)for i in range(0, n - k ): test_list.pop() # printing resultprint (\"The truncated list is : \" + str(test_list))", "e": 922, "s": 533, "text": null }, { "code": null, "e": 1015, "s": 922, "text": "The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]\nThe truncated list is : [1, 4, 5, 6, 7]\n" }, { "code": null, "e": 1188, "s": 1015, "text": " Method #2 : Using del + list slicedel operator can be used to delete all the elements that appear after the specific index, which is handled by the list slicing technique." }, { "code": "# Python3 code to demonstrate # to truncate list # using del + list slicing # initializing list test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10] # printing original listprint (\"The original list is : \" + str(test_list)) # size desiredk = 5 # using del + list slicing# to truncate list del test_list[5:] # printing resultprint (\"The truncated list is : \" + str(test_list))", "e": 1559, "s": 1188, "text": null }, { "code": null, "e": 1652, "s": 1559, "text": "The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]\nThe truncated list is : [1, 4, 5, 6, 7]\n" }, { "code": null, "e": 1858, "s": 1652, "text": " Method #3 : Using list slicingIn this method, we just slice the first K elements and ignore all the elements that occur after K elements. This is most pythonic and recommended method to perform this task." }, { "code": "# Python3 code to demonstrate # to truncate list # using list slicing # initializing list test_list = [1, 4, 5, 6, 7, 3, 8, 9, 10] # printing original listprint (\"The original list is : \" + str(test_list)) # size desiredk = 5 # using list slicing# to truncate list res = test_list[0 : 5] # printing resultprint (\"The truncated list is : \" + str(res))", "e": 2216, "s": 1858, "text": null }, { "code": null, "e": 2309, "s": 2216, "text": "The original list is : [1, 4, 5, 6, 7, 3, 8, 9, 10]\nThe truncated list is : [1, 4, 5, 6, 7]\n" }, { "code": null, "e": 2330, "s": 2309, "text": "Python list-programs" }, { "code": null, "e": 2337, "s": 2330, "text": "Python" }, { "code": null, "e": 2353, "s": 2337, "text": "Python Programs" } ]
Hashmap methods in Java with Examples | Set 2 (keySet(), values(), containsKey()..)
14 Oct, 2019 HashMap Class Methods in Java with Examples | Set 1 (put(), get(), isEmpty() and size()) In this post more methods are discussed. keySet(): java.util.HashMap.keySet() It returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.Syntax: public Set keySet() Return: a set view of the keys contained in this map Syntax: public Set keySet() Return: a set view of the keys contained in this map values(): java.util.HashMap.values() It returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.Syntax: public Collection values() Return: a collection view of the values contained in this map Syntax: public Collection values() Return: a collection view of the values contained in this map containsKey(): java.util.HashMap.containsKey() It returns true if this map maps one or more keys to the specified value.Syntax: public boolean containsValue(Object value) Parameters: value - value whose presence in this map is to be tested Return: true if this map maps one or more keys to the specified value Syntax: public boolean containsValue(Object value) Parameters: value - value whose presence in this map is to be tested Return: true if this map maps one or more keys to the specified value Implementation: // Java program illustrating usage of HashMap class methods// keySet(), values(), containsKey()import java.util.*;public class NewClass{ public static void main(String args[]) { // 1 Creation of HashMap HashMap<String, String> Geeks = new HashMap<>(); // 2 Adding values to HashMap as ("keys", "values") Geeks.put("Language", "Java"); Geeks.put("Platform", "Geeks For geeks"); Geeks.put("Code", "HashMap"); Geeks.put("Learn", "More"); // 3 containsKey() method is to check the presence // of a particluar key // Since 'Code' key present here, the condition is true if (Geeks.containsKey("Code")) System.out.println("Testing .containsKey : " + Geeks.get("Code")); // 4 keySet() method returns all the keys in HashMap Set<String> Geekskeys = Geeks.keySet(); System.out.println("Initial keys : " + Geekskeys); // 5 values() method return all the values in HashMap Collection<String> Geeksvalues = Geeks.values(); System.out.println("Initial values : " + Geeksvalues); // Adding new set of key-value Geeks.put("Search", "JavaArticle"); // Again using .keySet() and .values() methods System.out.println("New Keys : " + Geekskeys); System.out.println("New Values: " + Geeksvalues); }} Output: Testing .containsKey : HashMap Initial keys : [Language, Platform, Learn, Code] Initial values : [Java, Geeks For geeks, More, HashMap] New Keys : [Language, Platform, Search, Learn, Code] New Values: [Java, Geeks For geeks, JavaArticle, More, HashMap] .entrySet() : java.util.HashMap.entrySet() method returns a complete set of keys and values present in the HashMap.Syntax: public Set<Map.Entry> entrySet() Return: complete set of keys and values Syntax: public Set<Map.Entry> entrySet() Return: complete set of keys and values .getOrDefault : java.util.HashMap.getOrDefault() method returns a default value if there is no value find using the key we passed as an argument in HashMap. If the value for key if present already in the HashMap, it won’t do anything to it.It is very nice way to assign values to the keys that are not yet mapped, without interfering with the already present set of keys and values.Syntax: default V getOrDefault(Object key,V defaultValue) Parameters: key - the key whose mapped value we need to return defaultValue - the default for the keys present in HashMap Return: mapping the unmapped keys with the default value. Syntax: default V getOrDefault(Object key,V defaultValue) Parameters: key - the key whose mapped value we need to return defaultValue - the default for the keys present in HashMap Return: mapping the unmapped keys with the default value. .replace() : java.util.HashMap.replace(key, value) or java.util.HashMap.replace(key, oldvalue, newvalue) method is a java.util.HashMap class method.1st method accepts set of key and value which will replace the already present value of the key with the new value passed in the argument. If no such set is present replace() method will do nothing.Meanwhile 2nd method will only replace the already present set of key-old_value if the key and old_Value are found in the HashMap.Syntax: replace(k key, v value) or replace(k key, v oldvalue, newvalue) Parameters: key - key in set with the old value. value - new value we want to be with the specified key oldvalue - old value in set with the specified key newvalue - new value we want to be with the specified key Return: True - if the value is replaced Null - if there is no such set present Syntax: replace(k key, v value) or replace(k key, v oldvalue, newvalue) Parameters: key - key in set with the old value. value - new value we want to be with the specified key oldvalue - old value in set with the specified key newvalue - new value we want to be with the specified key Return: True - if the value is replaced Null - if there is no such set present .putIfAbsent java.util.HashMap.putIfAbsent(key, value) method is being used to insert a new key-value set to the HashMap if the respective set is present. Null value is returned if such key-value set is already present in the HashMap.Syntax: public V putIfAbsent(key, value) Parameters: key - key with which the specified value is associates. value - value to associates with the specified key. Syntax: public V putIfAbsent(key, value) Parameters: key - key with which the specified value is associates. value - value to associates with the specified key. // Java Program illustrating HashMap class methods(). // entrySet(), getOrDefault(), replace(), putIfAbsentimport java.util.*;public class NewClass{ public static void main(String args[]) { // Creation of HashMap HashMap<String, String> Geeks = new HashMap<>(); // Adding values to HashMap as ("keys", "values") Geeks.put("Language", "Java"); Geeks.put("Code", "HashMap"); Geeks.put("Learn", "More"); // .entrySet() returns all the keys with their values present in Hashmap Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet(); System.out.println("Set of Keys and Values using entrySet() : "+mappingGeeks); System.out.println(); // Using .getOrDefault to access value // Here it is Showing Default value as key - "Code" was already present System.out.println("Using .getorDefault : " + Geeks.getOrDefault("Code","javaArticle")); // Here it is Showing set value as key - "Search" was not present System.out.println("Using .getorDefault : " + Geeks.getOrDefault("Search","javaArticle")); System.out.println(); // .replace() method replacing value of key "Learn" Geeks.replace("Learn", "Methods"); System.out.println("working of .replace() : "+mappingGeeks); System.out.println(); /* .putIfAbsent() method is placing a new key-value as they were not present initially*/ Geeks.putIfAbsent("cool", "HashMap methods"); System.out.println("working of .putIfAbsent() : "+mappingGeeks); /* .putIfAbsent() method is not doing anything as key-value were already present */ Geeks.putIfAbsent("Code", "With_JAVA"); System.out.println("working of .putIfAbsent() : "+mappingGeeks); }} Output: Set of Keys and Values using entrySet() : [Language=Java, Learn=More, Code=HashMap] Using .getorDefault : HashMap Using .getorDefault : javaArticle working of .replace() : [Language=Java, Learn=Methods, Code=HashMap] working of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap] working of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap] remove(Object key): Removes the mapping for this key from this map if present. // Java Program illustrating remove() method using Iterator. import java.util.*;public class NewClass{ public static void main(String args[]) { // Creation of HashMap HashMap<String, String> Geeks = new HashMap<>(); // Adding values to HashMap as ("keys", "values") Geeks.put("Language", "Java"); Geeks.put("Platform", "Geeks For geeks"); Geeks.put("Code", "HashMap"); // .entrySet() returns all the keys with their values present in Hashmap Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet(); System.out.println("Set of Keys and Values : "+mappingGeeks); System.out.println(); // Creating an iterator System.out.println("Use of Iterator to remove the sets."); Iterator<Map.Entry<String, String>> geeks_iterator = Geeks.entrySet().iterator(); while(geeks_iterator.hasNext()) { Map.Entry<String, String> entry = geeks_iterator.next(); // Removing a set one by one using iterator geeks_iterator.remove(); // right way to remove entries from Map, // avoids ConcurrentModificationException System.out.println("Set of Keys and Values : "+mappingGeeks); } }} Output: Set of Keys and Values : [Language=Java, Platform=Geeks For geeks, Code=HashMap] Use of Iterator to remove the sets. Set of Keys and Values : [Platform=Geeks For geeks, Code=HashMap] Set of Keys and Values : [Code=HashMap] Set of Keys and Values : [] Advantage:If we use for loop, it get translated to Iterator internally but without using Iterator explicitly we can’t remove any entry during Iteration.On doing so, Iterator may throw ConcurrentModificationException. So, we use explicit Iterator and while loop to traverse. Reference:https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html This article is contributed by Mohit Gupta. 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. Akanksha_Rai Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Singleton Class in Java Initializing a List in Java Stack Class in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Oct, 2019" }, { "code": null, "e": 143, "s": 54, "text": "HashMap Class Methods in Java with Examples | Set 1 (put(), get(), isEmpty() and size())" }, { "code": null, "e": 184, "s": 143, "text": "In this post more methods are discussed." }, { "code": null, "e": 453, "s": 184, "text": "keySet(): java.util.HashMap.keySet() It returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.Syntax:\npublic Set keySet()\nReturn: a set view of the keys contained in this map\n" }, { "code": null, "e": 535, "s": 453, "text": "Syntax:\npublic Set keySet()\nReturn: a set view of the keys contained in this map\n" }, { "code": null, "e": 844, "s": 535, "text": "values(): java.util.HashMap.values() It returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.Syntax:\npublic Collection values()\nReturn: a collection view of the values contained in \nthis map\n" }, { "code": null, "e": 943, "s": 844, "text": "Syntax:\npublic Collection values()\nReturn: a collection view of the values contained in \nthis map\n" }, { "code": null, "e": 1255, "s": 943, "text": "containsKey(): java.util.HashMap.containsKey() It returns true if this map maps one or more keys to the specified value.Syntax:\npublic boolean containsValue(Object value)\nParameters:\nvalue - value whose presence in this map is to be tested\nReturn: true if this map maps one or more keys to \nthe specified value\n" }, { "code": null, "e": 1447, "s": 1255, "text": "Syntax:\npublic boolean containsValue(Object value)\nParameters:\nvalue - value whose presence in this map is to be tested\nReturn: true if this map maps one or more keys to \nthe specified value\n" }, { "code": null, "e": 1463, "s": 1447, "text": "Implementation:" }, { "code": "// Java program illustrating usage of HashMap class methods// keySet(), values(), containsKey()import java.util.*;public class NewClass{ public static void main(String args[]) { // 1 Creation of HashMap HashMap<String, String> Geeks = new HashMap<>(); // 2 Adding values to HashMap as (\"keys\", \"values\") Geeks.put(\"Language\", \"Java\"); Geeks.put(\"Platform\", \"Geeks For geeks\"); Geeks.put(\"Code\", \"HashMap\"); Geeks.put(\"Learn\", \"More\"); // 3 containsKey() method is to check the presence // of a particluar key // Since 'Code' key present here, the condition is true if (Geeks.containsKey(\"Code\")) System.out.println(\"Testing .containsKey : \" + Geeks.get(\"Code\")); // 4 keySet() method returns all the keys in HashMap Set<String> Geekskeys = Geeks.keySet(); System.out.println(\"Initial keys : \" + Geekskeys); // 5 values() method return all the values in HashMap Collection<String> Geeksvalues = Geeks.values(); System.out.println(\"Initial values : \" + Geeksvalues); // Adding new set of key-value Geeks.put(\"Search\", \"JavaArticle\"); // Again using .keySet() and .values() methods System.out.println(\"New Keys : \" + Geekskeys); System.out.println(\"New Values: \" + Geeksvalues); }}", "e": 2882, "s": 1463, "text": null }, { "code": null, "e": 2890, "s": 2882, "text": "Output:" }, { "code": null, "e": 3145, "s": 2890, "text": "Testing .containsKey : HashMap\nInitial keys : [Language, Platform, Learn, Code]\nInitial values : [Java, Geeks For geeks, More, HashMap]\nNew Keys : [Language, Platform, Search, Learn, Code]\nNew Values: [Java, Geeks For geeks, JavaArticle, More, HashMap]\n" }, { "code": null, "e": 3342, "s": 3145, "text": ".entrySet() : java.util.HashMap.entrySet() method returns a complete set of keys and values present in the HashMap.Syntax:\npublic Set<Map.Entry> entrySet()\nReturn:\ncomplete set of keys and values\n" }, { "code": null, "e": 3424, "s": 3342, "text": "Syntax:\npublic Set<Map.Entry> entrySet()\nReturn:\ncomplete set of keys and values\n" }, { "code": null, "e": 4045, "s": 3424, "text": ".getOrDefault : java.util.HashMap.getOrDefault() method returns a default value if there is no value find using the key we passed as an argument in HashMap. If the value for key if present already in the HashMap, it won’t do anything to it.It is very nice way to assign values to the keys that are not yet mapped, without interfering with the already present set of keys and values.Syntax:\ndefault V getOrDefault(Object key,V defaultValue)\nParameters:\nkey - the key whose mapped value we need to return\ndefaultValue - the default for the keys present in HashMap\nReturn:\nmapping the unmapped keys with the default value.\n" }, { "code": null, "e": 4284, "s": 4045, "text": "Syntax:\ndefault V getOrDefault(Object key,V defaultValue)\nParameters:\nkey - the key whose mapped value we need to return\ndefaultValue - the default for the keys present in HashMap\nReturn:\nmapping the unmapped keys with the default value.\n" }, { "code": null, "e": 5143, "s": 4284, "text": ".replace() : java.util.HashMap.replace(key, value) or java.util.HashMap.replace(key, oldvalue, newvalue) method is a java.util.HashMap class method.1st method accepts set of key and value which will replace the already present value of the key with the new value passed in the argument. If no such set is present replace() method will do nothing.Meanwhile 2nd method will only replace the already present set of key-old_value if the key and old_Value are found in the HashMap.Syntax:\nreplace(k key, v value)\n or\nreplace(k key, v oldvalue, newvalue)\nParameters:\nkey - key in set with the old value.\nvalue - new value we want to be with the specified key\noldvalue - old value in set with the specified key\nnewvalue - new value we want to be with the specified key\nReturn:\nTrue - if the value is replaced\nNull - if there is no such set present\n" }, { "code": null, "e": 5526, "s": 5143, "text": "Syntax:\nreplace(k key, v value)\n or\nreplace(k key, v oldvalue, newvalue)\nParameters:\nkey - key in set with the old value.\nvalue - new value we want to be with the specified key\noldvalue - old value in set with the specified key\nnewvalue - new value we want to be with the specified key\nReturn:\nTrue - if the value is replaced\nNull - if there is no such set present\n" }, { "code": null, "e": 5930, "s": 5526, "text": ".putIfAbsent java.util.HashMap.putIfAbsent(key, value) method is being used to insert a new key-value set to the HashMap if the respective set is present. Null value is returned if such key-value set is already present in the HashMap.Syntax:\npublic V putIfAbsent(key, value)\nParameters:\nkey - key with which the specified value is associates.\nvalue - value to associates with the specified key.\n" }, { "code": null, "e": 6100, "s": 5930, "text": "Syntax:\npublic V putIfAbsent(key, value)\nParameters:\nkey - key with which the specified value is associates.\nvalue - value to associates with the specified key.\n" }, { "code": "// Java Program illustrating HashMap class methods(). // entrySet(), getOrDefault(), replace(), putIfAbsentimport java.util.*;public class NewClass{ public static void main(String args[]) { // Creation of HashMap HashMap<String, String> Geeks = new HashMap<>(); // Adding values to HashMap as (\"keys\", \"values\") Geeks.put(\"Language\", \"Java\"); Geeks.put(\"Code\", \"HashMap\"); Geeks.put(\"Learn\", \"More\"); // .entrySet() returns all the keys with their values present in Hashmap Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet(); System.out.println(\"Set of Keys and Values using entrySet() : \"+mappingGeeks); System.out.println(); // Using .getOrDefault to access value // Here it is Showing Default value as key - \"Code\" was already present System.out.println(\"Using .getorDefault : \" + Geeks.getOrDefault(\"Code\",\"javaArticle\")); // Here it is Showing set value as key - \"Search\" was not present System.out.println(\"Using .getorDefault : \" + Geeks.getOrDefault(\"Search\",\"javaArticle\")); System.out.println(); // .replace() method replacing value of key \"Learn\" Geeks.replace(\"Learn\", \"Methods\"); System.out.println(\"working of .replace() : \"+mappingGeeks); System.out.println(); /* .putIfAbsent() method is placing a new key-value as they were not present initially*/ Geeks.putIfAbsent(\"cool\", \"HashMap methods\"); System.out.println(\"working of .putIfAbsent() : \"+mappingGeeks); /* .putIfAbsent() method is not doing anything as key-value were already present */ Geeks.putIfAbsent(\"Code\", \"With_JAVA\"); System.out.println(\"working of .putIfAbsent() : \"+mappingGeeks); }}", "e": 7984, "s": 6100, "text": null }, { "code": null, "e": 7992, "s": 7984, "text": "Output:" }, { "code": null, "e": 8407, "s": 7992, "text": "Set of Keys and Values using entrySet() : [Language=Java, Learn=More, Code=HashMap]\n\nUsing .getorDefault : HashMap\nUsing .getorDefault : javaArticle\n\nworking of .replace() : [Language=Java, Learn=Methods, Code=HashMap]\n\nworking of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap]\nworking of .putIfAbsent() : [Language=Java, cool=HashMap methods, Learn=Methods, Code=HashMap]\n" }, { "code": null, "e": 8486, "s": 8407, "text": "remove(Object key): Removes the mapping for this key from this map if present." }, { "code": "// Java Program illustrating remove() method using Iterator. import java.util.*;public class NewClass{ public static void main(String args[]) { // Creation of HashMap HashMap<String, String> Geeks = new HashMap<>(); // Adding values to HashMap as (\"keys\", \"values\") Geeks.put(\"Language\", \"Java\"); Geeks.put(\"Platform\", \"Geeks For geeks\"); Geeks.put(\"Code\", \"HashMap\"); // .entrySet() returns all the keys with their values present in Hashmap Set<Map.Entry<String, String>> mappingGeeks = Geeks.entrySet(); System.out.println(\"Set of Keys and Values : \"+mappingGeeks); System.out.println(); // Creating an iterator System.out.println(\"Use of Iterator to remove the sets.\"); Iterator<Map.Entry<String, String>> geeks_iterator = Geeks.entrySet().iterator(); while(geeks_iterator.hasNext()) { Map.Entry<String, String> entry = geeks_iterator.next(); // Removing a set one by one using iterator geeks_iterator.remove(); // right way to remove entries from Map, // avoids ConcurrentModificationException System.out.println(\"Set of Keys and Values : \"+mappingGeeks); } }}", "e": 9743, "s": 8486, "text": null }, { "code": null, "e": 9751, "s": 9743, "text": "Output:" }, { "code": null, "e": 10004, "s": 9751, "text": "Set of Keys and Values : [Language=Java, Platform=Geeks For geeks, Code=HashMap]\n\nUse of Iterator to remove the sets.\nSet of Keys and Values : [Platform=Geeks For geeks, Code=HashMap]\nSet of Keys and Values : [Code=HashMap]\nSet of Keys and Values : []\n" }, { "code": null, "e": 10278, "s": 10004, "text": "Advantage:If we use for loop, it get translated to Iterator internally but without using Iterator explicitly we can’t remove any entry during Iteration.On doing so, Iterator may throw ConcurrentModificationException. So, we use explicit Iterator and while loop to traverse." }, { "code": null, "e": 10353, "s": 10278, "text": "Reference:https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html" }, { "code": null, "e": 10652, "s": 10353, "text": "This article is contributed by Mohit Gupta. 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": 10665, "s": 10652, "text": "Akanksha_Rai" }, { "code": null, "e": 10682, "s": 10665, "text": "Java-Collections" }, { "code": null, "e": 10687, "s": 10682, "text": "Java" }, { "code": null, "e": 10692, "s": 10687, "text": "Java" }, { "code": null, "e": 10709, "s": 10692, "text": "Java-Collections" }, { "code": null, "e": 10807, "s": 10709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10826, "s": 10807, "text": "Interfaces in Java" }, { "code": null, "e": 10844, "s": 10826, "text": "ArrayList in Java" }, { "code": null, "e": 10864, "s": 10844, "text": "Collections in Java" }, { "code": null, "e": 10896, "s": 10864, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 10911, "s": 10896, "text": "Stream In Java" }, { "code": null, "e": 10935, "s": 10911, "text": "Singleton Class in Java" }, { "code": null, "e": 10963, "s": 10935, "text": "Initializing a List in Java" }, { "code": null, "e": 10983, "s": 10963, "text": "Stack Class in Java" }, { "code": null, "e": 11004, "s": 10983, "text": "Introduction to Java" } ]
Number of recycled pairs in an array
12 Feb, 2020 Given an array of integers arr[], find the number of recycled pairs in the array. A recycled pair of two numbers {a, b} has the following properties : A should be smaller than B.Number of digits should be same.By rotating A any number of times in one direction, we should get B. A should be smaller than B. Number of digits should be same. By rotating A any number of times in one direction, we should get B. Examples: Input : arr[] = {32, 42, 13, 23, 9, 5, 31} Output : 2 Explanation : Since there are two pairs {13, 31} and {23, 32}. By rotating 13 for first time, output is 31 and by rotating 23 once output is 32. Both of these pairs satisfy our criteria. Input : arr[] = {1212, 2121} Output : 1 Explanation : Since there are two pairs {1212, 2121}. By rotating 1212 for first time, output is 2121. This pair satisfies our criteria. Note that if rotation id done further, rotating 1212 again output is 1212 which is given number and 2121 which has been already counted. So discard both of these results. Below is the step by step algorithm to solve the above problem: Sort the array.Create a new array ‘temp’ of size n where n is the length of original array.Remove duplicates from the array by copying unique values to new array ‘temp’.Find the number of elements copied from original array and let this number be the size of array.Create a HashSet to store only unique rotations of the current number.Initialize a counter with value = 0.Traverse ‘temp’ and for every number do the following steps –Find the number of digits. Let it be ‘d1’.Rotate the number for d-1 times and store every number formed by each rotation in a HashSet.If formed number is found in HashSet, ignore it.For every rotated number, do a binary search for its presence in rest of the array.If it is present, increment counter. Sort the array. Create a new array ‘temp’ of size n where n is the length of original array. Remove duplicates from the array by copying unique values to new array ‘temp’. Find the number of elements copied from original array and let this number be the size of array. Create a HashSet to store only unique rotations of the current number. Initialize a counter with value = 0. Traverse ‘temp’ and for every number do the following steps –Find the number of digits. Let it be ‘d1’.Rotate the number for d-1 times and store every number formed by each rotation in a HashSet.If formed number is found in HashSet, ignore it.For every rotated number, do a binary search for its presence in rest of the array.If it is present, increment counter. Find the number of digits. Let it be ‘d1’. Rotate the number for d-1 times and store every number formed by each rotation in a HashSet. If formed number is found in HashSet, ignore it. For every rotated number, do a binary search for its presence in rest of the array. If it is present, increment counter. C++ Java C# // C++ code for Recycled Pairs in array.#include<bits/stdc++.h>using namespace std; // Function to find recycled pairsint recycledPairs(int a[], int n){ int count = 0; // Sorting array sort(a, a + n); // Removing duplicates by creating new array temp. int temp[n]; memset(temp, -1, n); int j = 0; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1]) temp[j++] = a[i]; temp[j++] = a[n - 1]; int size = n; // Finding number of locations in temp // which are occupied from copying. for (int i = n - 1; i >= 0; i--) if (temp[i] != -1) { size = i; break; } // Hashset to store new Rotations set<int>hs; for (int i = 0; i < size + 1; i++) { // Clearing hashset for each number in temp. hs.clear(); int x = temp[i]; // Finding number of digits of taken number int d1 = (int)log10(temp[i]) + 1; int f = (int)pow(10, d1 - 1); for (j = 1; j <= d1 - 1; j++) { // Remainder int r = x % 10; // Quotient int q = x / 10; // Forming new number by rotating. x = r * f + q; // Number of digits of newly formed rotated number // to avoid duplicate numbers. int d2 = (int)log10(x) + 1; set<int>::iterator it = hs.find(x); // Inserting formed rotated number to set s if (it == hs.end()) { hs.insert(x); // Checking for number of digits of new number. if ((d1 == d2)) { // Searching for the formed element in rest of array. int position = lower_bound(temp + i, temp + size + 1 , x)-(temp + i + 1); // If position found if(position >= 0) { // Increment counter. count++; } } } } } // Return counter return count;} // Driver functionint main(){ int a[] = { 32, 42, 13, 23, 9, 5, 31 }; int n = sizeof(a)/sizeof(a[0]); int result = recycledPairs(a,n); cout << (result); return 0;} // This code is contributed by Rajput-Ji // Java code for Recycled Pairs in array.import java.util.*; class GFG { // Function to find recycled pairs static int recycledPairs(int[] a) { int count = 0; // Sorting array Arrays.sort(a); int n = a.length; // Removing duplicates by creating new array temp. int[] temp = new int[n]; Arrays.fill(temp, -1); int j = 0; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1]) temp[j++] = a[i]; temp[j++] = a[n - 1]; int size = n; // Finding number of locations in temp which are occupied from copying. for (int i = n - 1; i >= 0; i--) if (temp[i] != -1) { size = i; break; } // Hashset to store new Rotations HashSet<Integer> hs = new HashSet<Integer>(); for (int i = 0; i < size + 1; i++) { // Clearing hashset for each number in temp. hs.clear(); int x = temp[i]; // Finding number of digits of taken number int d1 = (int)Math.log10(temp[i]) + 1; int f = (int)Math.pow(10, d1 - 1); for (j = 1; j <= d1 - 1; j++) { // Remainder int r = x % 10; // Quotient int q = x / 10; // Forming new number by rotating. x = r * f + q; // Number of digits of newly formed rotated number // to avoid duplicate numbers. int d2 = (int)Math.log10(x) + 1; // Inserting formed rotated number to set s if (!hs.contains(x)) { hs.add(x); // Checking for number of digits of new number. if ((d1 == d2)) { // Searching for the formed element in rest of array. int position = Arrays.binarySearch(temp, i + 1, size + 1, x); // If position found if(position >= 0) { // Increment counter. count++; } } } } } // Return counter return count; } // Driver function public static void main(String[] args) { int a[] = { 32, 42, 13, 23, 9, 5, 31 }; int result = recycledPairs(a); System.out.println(result); }} // C# code for Recycled Pairs in array.using System;using System.Collections.Generic; class GFG { // Function to find recycled pairs static int recycledPairs(int[] a) { int count = 0; // Sorting array Array.Sort(a); int n = a.Length; // Removing duplicates by // creating new array temp. int[] temp = new int[n]; for (int i = 0; i < n; i++) temp[i] = -1; int j = 0; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1]) temp[j++] = a[i]; temp[j++] = a[n - 1]; int size = n; // Finding number of locations in temp // which are occupied from copying. for (int i = n - 1; i >= 0; i--) if (temp[i] != -1) { size = i; break; } // Hashset to store new Rotations HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < size + 1; i++) { // Clearing hashset for each number in temp. hs.Clear(); int x = temp[i]; // Finding number of digits of taken number int d1 = (int)Math.Log10(temp[i]) + 1; int f = (int)Math.Pow(10, d1 - 1); for (j = 1; j <= d1 - 1; j++) { // Remainder int r = x % 10; // Quotient int q = x / 10; // Forming new number by rotating. x = r * f + q; // Number of digits of newly formed rotated number // to avoid duplicate numbers. int d2 = (int)Math.Log10(x) + 1; // Inserting formed rotated number to set s if (!hs.Contains(x)) { hs.Add(x); // Checking for number of digits of new number. if ((d1 == d2)) { // Searching for the formed element in rest of array. int position = Array.BinarySearch(temp, i + 1, size - i, x); // If position found if(position >= 0) { // Increment counter. count++; } } } } } // Return counter return count; } // Driver Code public static void Main(String[] args) { int []a = { 32, 42, 13, 23, 9, 5, 31 }; int result = recycledPairs(a); Console.WriteLine(result); }} // This code is contributed by 29AjayKumar 2 Time Complexity : O(n*log(n)). Note: For any given integer, the maximum number of rotations to form new numbers are fixed that is (no_of_digits-1). Hence, this operation is constant time that is O(1). 29AjayKumar Rajput-Ji Arrays Google Java-Arrays java-hashset Arrays Google Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Feb, 2020" }, { "code": null, "e": 203, "s": 52, "text": "Given an array of integers arr[], find the number of recycled pairs in the array. A recycled pair of two numbers {a, b} has the following properties :" }, { "code": null, "e": 331, "s": 203, "text": "A should be smaller than B.Number of digits should be same.By rotating A any number of times in one direction, we should get B." }, { "code": null, "e": 359, "s": 331, "text": "A should be smaller than B." }, { "code": null, "e": 392, "s": 359, "text": "Number of digits should be same." }, { "code": null, "e": 461, "s": 392, "text": "By rotating A any number of times in one direction, we should get B." }, { "code": null, "e": 471, "s": 461, "text": "Examples:" }, { "code": null, "e": 1066, "s": 471, "text": "Input : arr[] = {32, 42, 13, 23, 9, 5, 31}\nOutput : 2\nExplanation : Since there are two pairs {13, 31} and {23, 32}. \nBy rotating 13 for first time, output is 31 and by rotating 23 once output is 32. \nBoth of these pairs satisfy our criteria.\n\nInput : arr[] = {1212, 2121}\nOutput : 1\nExplanation : Since there are two pairs {1212, 2121}. By rotating 1212\nfor first time, output is 2121. This pair satisfies our criteria.\nNote that if rotation id done further, rotating 1212 again output is 1212 \nwhich is given number and 2121 which has been already counted.\nSo discard both of these results. \n" }, { "code": null, "e": 1130, "s": 1066, "text": "Below is the step by step algorithm to solve the above problem:" }, { "code": null, "e": 1864, "s": 1130, "text": "Sort the array.Create a new array ‘temp’ of size n where n is the length of original array.Remove duplicates from the array by copying unique values to new array ‘temp’.Find the number of elements copied from original array and let this number be the size of array.Create a HashSet to store only unique rotations of the current number.Initialize a counter with value = 0.Traverse ‘temp’ and for every number do the following steps –Find the number of digits. Let it be ‘d1’.Rotate the number for d-1 times and store every number formed by each rotation in a HashSet.If formed number is found in HashSet, ignore it.For every rotated number, do a binary search for its presence in rest of the array.If it is present, increment counter." }, { "code": null, "e": 1880, "s": 1864, "text": "Sort the array." }, { "code": null, "e": 1957, "s": 1880, "text": "Create a new array ‘temp’ of size n where n is the length of original array." }, { "code": null, "e": 2036, "s": 1957, "text": "Remove duplicates from the array by copying unique values to new array ‘temp’." }, { "code": null, "e": 2133, "s": 2036, "text": "Find the number of elements copied from original array and let this number be the size of array." }, { "code": null, "e": 2204, "s": 2133, "text": "Create a HashSet to store only unique rotations of the current number." }, { "code": null, "e": 2241, "s": 2204, "text": "Initialize a counter with value = 0." }, { "code": null, "e": 2604, "s": 2241, "text": "Traverse ‘temp’ and for every number do the following steps –Find the number of digits. Let it be ‘d1’.Rotate the number for d-1 times and store every number formed by each rotation in a HashSet.If formed number is found in HashSet, ignore it.For every rotated number, do a binary search for its presence in rest of the array.If it is present, increment counter." }, { "code": null, "e": 2647, "s": 2604, "text": "Find the number of digits. Let it be ‘d1’." }, { "code": null, "e": 2740, "s": 2647, "text": "Rotate the number for d-1 times and store every number formed by each rotation in a HashSet." }, { "code": null, "e": 2789, "s": 2740, "text": "If formed number is found in HashSet, ignore it." }, { "code": null, "e": 2873, "s": 2789, "text": "For every rotated number, do a binary search for its presence in rest of the array." }, { "code": null, "e": 2910, "s": 2873, "text": "If it is present, increment counter." }, { "code": null, "e": 2914, "s": 2910, "text": "C++" }, { "code": null, "e": 2919, "s": 2914, "text": "Java" }, { "code": null, "e": 2922, "s": 2919, "text": "C#" }, { "code": "// C++ code for Recycled Pairs in array.#include<bits/stdc++.h>using namespace std; // Function to find recycled pairsint recycledPairs(int a[], int n){ int count = 0; // Sorting array sort(a, a + n); // Removing duplicates by creating new array temp. int temp[n]; memset(temp, -1, n); int j = 0; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1]) temp[j++] = a[i]; temp[j++] = a[n - 1]; int size = n; // Finding number of locations in temp // which are occupied from copying. for (int i = n - 1; i >= 0; i--) if (temp[i] != -1) { size = i; break; } // Hashset to store new Rotations set<int>hs; for (int i = 0; i < size + 1; i++) { // Clearing hashset for each number in temp. hs.clear(); int x = temp[i]; // Finding number of digits of taken number int d1 = (int)log10(temp[i]) + 1; int f = (int)pow(10, d1 - 1); for (j = 1; j <= d1 - 1; j++) { // Remainder int r = x % 10; // Quotient int q = x / 10; // Forming new number by rotating. x = r * f + q; // Number of digits of newly formed rotated number // to avoid duplicate numbers. int d2 = (int)log10(x) + 1; set<int>::iterator it = hs.find(x); // Inserting formed rotated number to set s if (it == hs.end()) { hs.insert(x); // Checking for number of digits of new number. if ((d1 == d2)) { // Searching for the formed element in rest of array. int position = lower_bound(temp + i, temp + size + 1 , x)-(temp + i + 1); // If position found if(position >= 0) { // Increment counter. count++; } } } } } // Return counter return count;} // Driver functionint main(){ int a[] = { 32, 42, 13, 23, 9, 5, 31 }; int n = sizeof(a)/sizeof(a[0]); int result = recycledPairs(a,n); cout << (result); return 0;} // This code is contributed by Rajput-Ji", "e": 5467, "s": 2922, "text": null }, { "code": "// Java code for Recycled Pairs in array.import java.util.*; class GFG { // Function to find recycled pairs static int recycledPairs(int[] a) { int count = 0; // Sorting array Arrays.sort(a); int n = a.length; // Removing duplicates by creating new array temp. int[] temp = new int[n]; Arrays.fill(temp, -1); int j = 0; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1]) temp[j++] = a[i]; temp[j++] = a[n - 1]; int size = n; // Finding number of locations in temp which are occupied from copying. for (int i = n - 1; i >= 0; i--) if (temp[i] != -1) { size = i; break; } // Hashset to store new Rotations HashSet<Integer> hs = new HashSet<Integer>(); for (int i = 0; i < size + 1; i++) { // Clearing hashset for each number in temp. hs.clear(); int x = temp[i]; // Finding number of digits of taken number int d1 = (int)Math.log10(temp[i]) + 1; int f = (int)Math.pow(10, d1 - 1); for (j = 1; j <= d1 - 1; j++) { // Remainder int r = x % 10; // Quotient int q = x / 10; // Forming new number by rotating. x = r * f + q; // Number of digits of newly formed rotated number // to avoid duplicate numbers. int d2 = (int)Math.log10(x) + 1; // Inserting formed rotated number to set s if (!hs.contains(x)) { hs.add(x); // Checking for number of digits of new number. if ((d1 == d2)) { // Searching for the formed element in rest of array. int position = Arrays.binarySearch(temp, i + 1, size + 1, x); // If position found if(position >= 0) { // Increment counter. count++; } } } } } // Return counter return count; } // Driver function public static void main(String[] args) { int a[] = { 32, 42, 13, 23, 9, 5, 31 }; int result = recycledPairs(a); System.out.println(result); }}", "e": 8199, "s": 5467, "text": null }, { "code": "// C# code for Recycled Pairs in array.using System;using System.Collections.Generic; class GFG { // Function to find recycled pairs static int recycledPairs(int[] a) { int count = 0; // Sorting array Array.Sort(a); int n = a.Length; // Removing duplicates by // creating new array temp. int[] temp = new int[n]; for (int i = 0; i < n; i++) temp[i] = -1; int j = 0; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1]) temp[j++] = a[i]; temp[j++] = a[n - 1]; int size = n; // Finding number of locations in temp // which are occupied from copying. for (int i = n - 1; i >= 0; i--) if (temp[i] != -1) { size = i; break; } // Hashset to store new Rotations HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < size + 1; i++) { // Clearing hashset for each number in temp. hs.Clear(); int x = temp[i]; // Finding number of digits of taken number int d1 = (int)Math.Log10(temp[i]) + 1; int f = (int)Math.Pow(10, d1 - 1); for (j = 1; j <= d1 - 1; j++) { // Remainder int r = x % 10; // Quotient int q = x / 10; // Forming new number by rotating. x = r * f + q; // Number of digits of newly formed rotated number // to avoid duplicate numbers. int d2 = (int)Math.Log10(x) + 1; // Inserting formed rotated number to set s if (!hs.Contains(x)) { hs.Add(x); // Checking for number of digits of new number. if ((d1 == d2)) { // Searching for the formed element in rest of array. int position = Array.BinarySearch(temp, i + 1, size - i, x); // If position found if(position >= 0) { // Increment counter. count++; } } } } } // Return counter return count; } // Driver Code public static void Main(String[] args) { int []a = { 32, 42, 13, 23, 9, 5, 31 }; int result = recycledPairs(a); Console.WriteLine(result); }} // This code is contributed by 29AjayKumar", "e": 11148, "s": 8199, "text": null }, { "code": null, "e": 11151, "s": 11148, "text": "2\n" }, { "code": null, "e": 11182, "s": 11151, "text": "Time Complexity : O(n*log(n))." }, { "code": null, "e": 11352, "s": 11182, "text": "Note: For any given integer, the maximum number of rotations to form new numbers are fixed that is (no_of_digits-1). Hence, this operation is constant time that is O(1)." }, { "code": null, "e": 11364, "s": 11352, "text": "29AjayKumar" }, { "code": null, "e": 11374, "s": 11364, "text": "Rajput-Ji" }, { "code": null, "e": 11381, "s": 11374, "text": "Arrays" }, { "code": null, "e": 11388, "s": 11381, "text": "Google" }, { "code": null, "e": 11400, "s": 11388, "text": "Java-Arrays" }, { "code": null, "e": 11413, "s": 11400, "text": "java-hashset" }, { "code": null, "e": 11420, "s": 11413, "text": "Arrays" }, { "code": null, "e": 11427, "s": 11420, "text": "Google" }, { "code": null, "e": 11434, "s": 11427, "text": "Arrays" } ]
Program to convert set of String to set of Integer in Java
11 Dec, 2018 Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to Set. Algorithm: Get the set of String.Convert Set of String to Stream of String. This is done using Set.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into Set of Integer. This is done using Collectors.toSet().Return/Print the set of String. Get the set of String. Convert Set of String to Stream of String. This is done using Set.stream(). Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression. Collect Stream of Integer into Set of Integer. This is done using Collectors.toSet(). Return/Print the set of String. Program 1: Using direct conversion. // Java Program to convert// Set<String> to Set<Integer> in Java 8 import java.util.*;import java.util.stream.*; class GFG { public static void main(String args[]) { // Create a set of String Set<String> setOfString = new HashSet<>( Arrays.asList("1", "2", "3", "4", "5")); // Print the set of String System.out.println("Set of String: " + setOfString); // Convert Set of String to set of Integer Set<Integer> setOfInteger = setOfString.stream() .map(s -> Integer.parseInt(s)) .collect(Collectors.toSet()); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); }} Set of String: [1, 2, 3, 4, 5] Set of Integer: [1, 2, 3, 4, 5] Program 2: Using generic function. // Java Program to convert// Set<String> to Set<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Generic function to convert Set of // String to Set of Integer public static <T, U> Set<U> convertStringSetToIntSet(Set<T> setOfString, Function<T, U> function) { return setOfString.stream() .map(function) .collect(Collectors.toSet()); } public static void main(String args[]) { // Create a set of String Set<String> setOfString = new HashSet<>( Arrays.asList("1", "2", "3", "4", "5")); // Print the set of String System.out.println("Set of String: " + setOfString); // Convert Set of String to set of Integer Set<Integer> setOfInteger = convertStringSetToIntSet( setOfString, Integer::parseInt); // Print the set of Integer System.out.println("Set of Integer: " + setOfInteger); }} Set of String: [1, 2, 3, 4, 5] Set of Integer: [1, 2, 3, 4, 5] Java-Integer java-set Java-Set-Programs Java-String-Programs Java-Strings Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 210, "s": 28, "text": "Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element." }, { "code": null, "e": 381, "s": 210, "text": "A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Java 8 Stream API can be used to convert Set to Set." }, { "code": null, "e": 392, "s": 381, "text": "Algorithm:" }, { "code": null, "e": 744, "s": 392, "text": "Get the set of String.Convert Set of String to Stream of String. This is done using Set.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into Set of Integer. This is done using Collectors.toSet().Return/Print the set of String." }, { "code": null, "e": 767, "s": 744, "text": "Get the set of String." }, { "code": null, "e": 843, "s": 767, "text": "Convert Set of String to Stream of String. This is done using Set.stream()." }, { "code": null, "e": 982, "s": 843, "text": "Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression." }, { "code": null, "e": 1068, "s": 982, "text": "Collect Stream of Integer into Set of Integer. This is done using Collectors.toSet()." }, { "code": null, "e": 1100, "s": 1068, "text": "Return/Print the set of String." }, { "code": null, "e": 1136, "s": 1100, "text": "Program 1: Using direct conversion." }, { "code": "// Java Program to convert// Set<String> to Set<Integer> in Java 8 import java.util.*;import java.util.stream.*; class GFG { public static void main(String args[]) { // Create a set of String Set<String> setOfString = new HashSet<>( Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\")); // Print the set of String System.out.println(\"Set of String: \" + setOfString); // Convert Set of String to set of Integer Set<Integer> setOfInteger = setOfString.stream() .map(s -> Integer.parseInt(s)) .collect(Collectors.toSet()); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); }}", "e": 1893, "s": 1136, "text": null }, { "code": null, "e": 1957, "s": 1893, "text": "Set of String: [1, 2, 3, 4, 5]\nSet of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 1992, "s": 1957, "text": "Program 2: Using generic function." }, { "code": "// Java Program to convert// Set<String> to Set<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.Function; class GFG { // Generic function to convert Set of // String to Set of Integer public static <T, U> Set<U> convertStringSetToIntSet(Set<T> setOfString, Function<T, U> function) { return setOfString.stream() .map(function) .collect(Collectors.toSet()); } public static void main(String args[]) { // Create a set of String Set<String> setOfString = new HashSet<>( Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\")); // Print the set of String System.out.println(\"Set of String: \" + setOfString); // Convert Set of String to set of Integer Set<Integer> setOfInteger = convertStringSetToIntSet( setOfString, Integer::parseInt); // Print the set of Integer System.out.println(\"Set of Integer: \" + setOfInteger); }}", "e": 3025, "s": 1992, "text": null }, { "code": null, "e": 3089, "s": 3025, "text": "Set of String: [1, 2, 3, 4, 5]\nSet of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 3102, "s": 3089, "text": "Java-Integer" }, { "code": null, "e": 3111, "s": 3102, "text": "java-set" }, { "code": null, "e": 3129, "s": 3111, "text": "Java-Set-Programs" }, { "code": null, "e": 3150, "s": 3129, "text": "Java-String-Programs" }, { "code": null, "e": 3163, "s": 3150, "text": "Java-Strings" }, { "code": null, "e": 3168, "s": 3163, "text": "Java" }, { "code": null, "e": 3182, "s": 3168, "text": "Java Programs" }, { "code": null, "e": 3195, "s": 3182, "text": "Java-Strings" }, { "code": null, "e": 3200, "s": 3195, "text": "Java" } ]
HTML <head> Tag
17 Mar, 2022 The <head> tag in HTML is used to define the head portion of the document which contains information related to the document. The <head> tag contains other head elements such as <title>, <meta>, <link>, <style> <link> etc. In HTML 4.01 the <head> element was mandatory but in HTML5, the <head> element can be omitted.Tag Specific Attributes:The below-mentioned layout-attributes of the <hr> tag have been removed from HTML5. Attribute: profile: It is used to specify the URL to a document that contains one or more metadata profiles for browsers to clearly understand the information. Syntax : <head> <title>Title of the document</title> </head> Below program illustrates the <head> element: Program 1: HTML <!DOCTYPE html><html lang="en"> <head> <title>HTML Head Tag </title></head> <body> <p>GeeksforGeeks is a portal for geeks.</p> <hr></body> </html> Output: Program 2(Using style tag inside head tag) HTML <!DOCTYPE html> <html> <head> <style> body { background: skyblue; } h1 { color: red; } p { color: blue; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>It is a portal for geeks.</p> </body> </html> Output: Program 3(Using link tag inside head tag): HTML <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="mystyle.css"></head> <body> <h1>GeeksforGeeks</h1> <p>It is a portal for geeks.</p> </body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari shubhamyadav4 HTML-Tags HTML5 HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Mar, 2022" }, { "code": null, "e": 478, "s": 52, "text": "The <head> tag in HTML is used to define the head portion of the document which contains information related to the document. The <head> tag contains other head elements such as <title>, <meta>, <link>, <style> <link> etc. In HTML 4.01 the <head> element was mandatory but in HTML5, the <head> element can be omitted.Tag Specific Attributes:The below-mentioned layout-attributes of the <hr> tag have been removed from HTML5. " }, { "code": null, "e": 490, "s": 478, "text": "Attribute: " }, { "code": null, "e": 639, "s": 490, "text": "profile: It is used to specify the URL to a document that contains one or more metadata profiles for browsers to clearly understand the information." }, { "code": null, "e": 649, "s": 639, "text": "Syntax : " }, { "code": null, "e": 701, "s": 649, "text": "<head>\n<title>Title of the document</title>\n</head>" }, { "code": null, "e": 747, "s": 701, "text": "Below program illustrates the <head> element:" }, { "code": null, "e": 758, "s": 747, "text": "Program 1:" }, { "code": null, "e": 763, "s": 758, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>HTML Head Tag </title></head> <body> <p>GeeksforGeeks is a portal for geeks.</p> <hr></body> </html>", "e": 921, "s": 763, "text": null }, { "code": null, "e": 931, "s": 921, "text": "Output: " }, { "code": null, "e": 974, "s": 931, "text": "Program 2(Using style tag inside head tag)" }, { "code": null, "e": 979, "s": 974, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <style> body { background: skyblue; } h1 { color: red; } p { color: blue; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>It is a portal for geeks.</p> </body> </html>", "e": 1288, "s": 979, "text": null }, { "code": null, "e": 1298, "s": 1288, "text": "Output: " }, { "code": null, "e": 1341, "s": 1298, "text": "Program 3(Using link tag inside head tag):" }, { "code": null, "e": 1346, "s": 1341, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyle.css\"></head> <body> <h1>GeeksforGeeks</h1> <p>It is a portal for geeks.</p> </body> </html>", "e": 1533, "s": 1346, "text": null }, { "code": null, "e": 1543, "s": 1533, "text": "Output: " }, { "code": null, "e": 1564, "s": 1543, "text": "Supported Browsers: " }, { "code": null, "e": 1578, "s": 1564, "text": "Google Chrome" }, { "code": null, "e": 1596, "s": 1578, "text": "Internet Explorer" }, { "code": null, "e": 1604, "s": 1596, "text": "Firefox" }, { "code": null, "e": 1610, "s": 1604, "text": "Opera" }, { "code": null, "e": 1617, "s": 1610, "text": "Safari" }, { "code": null, "e": 1633, "s": 1619, "text": "shubhamyadav4" }, { "code": null, "e": 1643, "s": 1633, "text": "HTML-Tags" }, { "code": null, "e": 1649, "s": 1643, "text": "HTML5" }, { "code": null, "e": 1654, "s": 1649, "text": "HTML" }, { "code": null, "e": 1659, "s": 1654, "text": "HTML" } ]
How to Replace a Substring of a String in Dart?
11 Jun, 2020 To replace all the substring of a string we make use of replaceAll method in Dart. This method replaces all the substring in the given string to the desired substring. Returns a new string in which the non-overlapping substrings matching from (the ones iterated by from.allMatches(this String)) are replaced by the literal string replace. Syntax: String_name.replaceAll (Old_String_Pattern, New_String_Pattern); In the above sequence: String_name is the name of the string in which operation is to be done. It could be the string itself. Old_String_Pattern is the pattern present in the given string. New_String_Pattern is the new pattern that is to be replaced with the old pattern. Example 1: Replacing the substring in the given string. Dart // Main functionmain() { String gfg = "Welcome GeeksForGeeks"; //replace substring of the given string String result = gfg.replaceAll("GeeksForGeeks", "Geek!"); print(result);} Output: Welcome Geek! In the above example the substring “GeeksForGeeks” is replaced by another string “Geek!”. Example 2: Using chain of replaceAll() method to change the string in dart. Dart // Main functionmain() { String gfg = "Welcome GeeksForGeeks"; //replace substring of the given string String result = gfg.replaceAll("GeeksForGeeks", "Geek!").replaceAll("!", " :)"); print(result);} Output: Welcome Geek :) In the above example the substring “GeeksForGeeks” is replaced by another string “Geek!” and then “!” is replaced by ” : )”. Dart-String Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jun, 2020" }, { "code": null, "e": 393, "s": 53, "text": "To replace all the substring of a string we make use of replaceAll method in Dart. This method replaces all the substring in the given string to the desired substring. Returns a new string in which the non-overlapping substrings matching from (the ones iterated by from.allMatches(this String)) are replaced by the literal string replace." }, { "code": null, "e": 467, "s": 393, "text": "Syntax: String_name.replaceAll (Old_String_Pattern, New_String_Pattern);\n" }, { "code": null, "e": 490, "s": 467, "text": "In the above sequence:" }, { "code": null, "e": 593, "s": 490, "text": "String_name is the name of the string in which operation is to be done. It could be the string itself." }, { "code": null, "e": 656, "s": 593, "text": "Old_String_Pattern is the pattern present in the given string." }, { "code": null, "e": 739, "s": 656, "text": "New_String_Pattern is the new pattern that is to be replaced with the old pattern." }, { "code": null, "e": 751, "s": 739, "text": "Example 1: " }, { "code": null, "e": 796, "s": 751, "text": "Replacing the substring in the given string." }, { "code": null, "e": 801, "s": 796, "text": "Dart" }, { "code": "// Main functionmain() { String gfg = \"Welcome GeeksForGeeks\"; //replace substring of the given string String result = gfg.replaceAll(\"GeeksForGeeks\", \"Geek!\"); print(result);}", "e": 1002, "s": 801, "text": null }, { "code": null, "e": 1010, "s": 1002, "text": "Output:" }, { "code": null, "e": 1025, "s": 1010, "text": "Welcome Geek!\n" }, { "code": null, "e": 1115, "s": 1025, "text": "In the above example the substring “GeeksForGeeks” is replaced by another string “Geek!”." }, { "code": null, "e": 1126, "s": 1115, "text": "Example 2:" }, { "code": null, "e": 1191, "s": 1126, "text": "Using chain of replaceAll() method to change the string in dart." }, { "code": null, "e": 1196, "s": 1191, "text": "Dart" }, { "code": "// Main functionmain() { String gfg = \"Welcome GeeksForGeeks\"; //replace substring of the given string String result = gfg.replaceAll(\"GeeksForGeeks\", \"Geek!\").replaceAll(\"!\", \" :)\"); print(result);}", "e": 1420, "s": 1196, "text": null }, { "code": null, "e": 1428, "s": 1420, "text": "Output:" }, { "code": null, "e": 1445, "s": 1428, "text": "Welcome Geek :)\n" }, { "code": null, "e": 1570, "s": 1445, "text": "In the above example the substring “GeeksForGeeks” is replaced by another string “Geek!” and then “!” is replaced by ” : )”." }, { "code": null, "e": 1582, "s": 1570, "text": "Dart-String" }, { "code": null, "e": 1587, "s": 1582, "text": "Dart" } ]
Amazon Interview Experience for Devops/Support Engineer (5 Years Experienced)
17 Feb, 2021 Applied through Referral for Bangalore location. All rounds happened over amazon chime(virtually) due to covid-19. The entire process took 2months-1month to get a call and then next month interviews+offer rollout. Was interviewed in December 2020. Round 1(Hiring Manager round): Supposed to be second round but was rescheduled. Brief introduction followed by behavioral questions(on leadership principles. Tell me a situation where you had to convince your client and how did you persuade him to agree to you.What do you think of operational excellence?What would you do if the delivery cannot be done before the deadline due to incomplete features?Tell me a situation where you had a conflict of interests with your co-worker and how you dealt with itTell me of a situation where you achieved a way beyond your bar. How you can improve that task further? Tell me a situation where you had to convince your client and how did you persuade him to agree to you. What do you think of operational excellence? What would you do if the delivery cannot be done before the deadline due to incomplete features? Tell me a situation where you had a conflict of interests with your co-worker and how you dealt with it Tell me of a situation where you achieved a way beyond your bar. How you can improve that task further? And few more scenario-based questions. Tip for this Round: Don’t bluff. Relate each leadership principle to your past work and answer. Think of how your work could impact the company/customer and answer from that perspective. Only if you have really worked/shown those leadership principles in the past, you can crack this round. Round 2 (Mostly on Linux fundamentals): Brief introduction followed by a question on one of my previous tasks Explain your latest automation. Entire task and how you contributed to it from scratch.How can you improve that automation now?Few Linux questions-processing a log file and fetching for few error codes from debugging prints. Can be solved using cat and sed.Write a shell script for tasks performed in (c) —> I wrote a simple for loop command. The interviewer was impressed.Discussion on how to debug disk space issue in LinuxWrite a shell script to generate a report on 10 top space-consuming workspaces (folders) with consumption details—> again a simple for loop with df & du commands. Explain your latest automation. Entire task and how you contributed to it from scratch. How can you improve that automation now? Few Linux questions-processing a log file and fetching for few error codes from debugging prints. Can be solved using cat and sed. Write a shell script for tasks performed in (c) —> I wrote a simple for loop command. The interviewer was impressed. Discussion on how to debug disk space issue in Linux Write a shell script to generate a report on 10 top space-consuming workspaces (folders) with consumption details—> again a simple for loop with df & du commands. Round 3 (Python coding- Any language you can choose): Brief introduction followed by questions Array of numbers could be either in increasing order or decreasing order or increasing then decreasing order or vice-versa. Print the type of array based on this order. Example-if array is [1,2,3,4,3,2,1] output should be "increasing-decreasing" Expected time complexity-O(1) Solution: Compare first and second elements. The same way compares the last 2 numbers in an array. Then decide what type of array it is based on these 2 results. Few leadership questions like what were previous achievements and how it impacted business etc. Round 4 (Debugging Round Mostly on Linux): Brief introduction followed by questions Questions on file processing, solutions involved a cat, sed, awk, tail, head, grep -B, sort, unique, etc How would you debug if there is an issue with API output -> Discuss all the scenarios ranging from network connectivity to data in DB from where API fetches its data. Round 5 (Bar Raiser round): Final round which will be scheduled only if you clear the previous 4 rounds. Brief introduction followed by following behavioral questions How have you dealt with ambiguous data in your tasks. Failure in your task and what you have learned out of it. How can you improve it now Task where u showed your ownership and how you could have improved in your WoW now. A Task where you improved the lives of your colleagues/team And few more behavioral questions which were similar to what was asked in the hiring manager round(Both of them were stressing different leadership principles) By God’s grace, next day got a call from the recruiter that I am selected and package negotiation had started. Within a week, the offer was rolled out. Tip for Amazon interview: Each round is based on 2-3 Leadership principles, and you are expected to raise the bar in a few of them. They will not ask on what technology you have worked for but any behavioral question should be answered technically highlighting how efficiently you have contributed to the team/customer. Be ready to explain how you have crossed your responsibilities to work across teams for your tasks. You cannot bluff. You cannot crack if you don’t have those 14 leadership principles(at least a few of them). Your programming question also will be actually evaluated against any of the leadership principles, so don’t concentrate on getting the solution but how efficiently you arrive at the optimized solution. And speak throughout the interview. I hope this helps the reader and pray that God bless you with your interview at Amazon. Amazon Marketing Experienced Interview Experiences Amazon Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Feb, 2021" }, { "code": null, "e": 276, "s": 28, "text": "Applied through Referral for Bangalore location. All rounds happened over amazon chime(virtually) due to covid-19. The entire process took 2months-1month to get a call and then next month interviews+offer rollout. Was interviewed in December 2020." }, { "code": null, "e": 434, "s": 276, "text": "Round 1(Hiring Manager round): Supposed to be second round but was rescheduled. Brief introduction followed by behavioral questions(on leadership principles." }, { "code": null, "e": 884, "s": 434, "text": "Tell me a situation where you had to convince your client and how did you persuade him to agree to you.What do you think of operational excellence?What would you do if the delivery cannot be done before the deadline due to incomplete features?Tell me a situation where you had a conflict of interests with your co-worker and how you dealt with itTell me of a situation where you achieved a way beyond your bar. How you can improve that task further?" }, { "code": null, "e": 988, "s": 884, "text": "Tell me a situation where you had to convince your client and how did you persuade him to agree to you." }, { "code": null, "e": 1033, "s": 988, "text": "What do you think of operational excellence?" }, { "code": null, "e": 1130, "s": 1033, "text": "What would you do if the delivery cannot be done before the deadline due to incomplete features?" }, { "code": null, "e": 1234, "s": 1130, "text": "Tell me a situation where you had a conflict of interests with your co-worker and how you dealt with it" }, { "code": null, "e": 1338, "s": 1234, "text": "Tell me of a situation where you achieved a way beyond your bar. How you can improve that task further?" }, { "code": null, "e": 1377, "s": 1338, "text": "And few more scenario-based questions." }, { "code": null, "e": 1668, "s": 1377, "text": "Tip for this Round: Don’t bluff. Relate each leadership principle to your past work and answer. Think of how your work could impact the company/customer and answer from that perspective. Only if you have really worked/shown those leadership principles in the past, you can crack this round." }, { "code": null, "e": 1778, "s": 1668, "text": "Round 2 (Mostly on Linux fundamentals): Brief introduction followed by a question on one of my previous tasks" }, { "code": null, "e": 2366, "s": 1778, "text": "Explain your latest automation. Entire task and how you contributed to it from scratch.How can you improve that automation now?Few Linux questions-processing a log file and fetching for few error codes from debugging prints. Can be solved using cat and sed.Write a shell script for tasks performed in (c) —> I wrote a simple for loop command. The interviewer was impressed.Discussion on how to debug disk space issue in LinuxWrite a shell script to generate a report on 10 top space-consuming workspaces (folders) with consumption details—> again a simple for loop with df & du commands." }, { "code": null, "e": 2454, "s": 2366, "text": "Explain your latest automation. Entire task and how you contributed to it from scratch." }, { "code": null, "e": 2495, "s": 2454, "text": "How can you improve that automation now?" }, { "code": null, "e": 2626, "s": 2495, "text": "Few Linux questions-processing a log file and fetching for few error codes from debugging prints. Can be solved using cat and sed." }, { "code": null, "e": 2743, "s": 2626, "text": "Write a shell script for tasks performed in (c) —> I wrote a simple for loop command. The interviewer was impressed." }, { "code": null, "e": 2796, "s": 2743, "text": "Discussion on how to debug disk space issue in Linux" }, { "code": null, "e": 2959, "s": 2796, "text": "Write a shell script to generate a report on 10 top space-consuming workspaces (folders) with consumption details—> again a simple for loop with df & du commands." }, { "code": null, "e": 3054, "s": 2959, "text": "Round 3 (Python coding- Any language you can choose): Brief introduction followed by questions" }, { "code": null, "e": 3223, "s": 3054, "text": "Array of numbers could be either in increasing order or decreasing order or increasing then decreasing order or vice-versa. Print the type of array based on this order." }, { "code": null, "e": 3331, "s": 3223, "text": "Example-if array is [1,2,3,4,3,2,1] output should be \n\"increasing-decreasing\"\nExpected time complexity-O(1)" }, { "code": null, "e": 3493, "s": 3331, "text": "Solution: Compare first and second elements. The same way compares the last 2 numbers in an array. Then decide what type of array it is based on these 2 results." }, { "code": null, "e": 3589, "s": 3493, "text": "Few leadership questions like what were previous achievements and how it impacted business etc." }, { "code": null, "e": 3673, "s": 3589, "text": "Round 4 (Debugging Round Mostly on Linux): Brief introduction followed by questions" }, { "code": null, "e": 3778, "s": 3673, "text": "Questions on file processing, solutions involved a cat, sed, awk, tail, head, grep -B, sort, unique, etc" }, { "code": null, "e": 3945, "s": 3778, "text": "How would you debug if there is an issue with API output -> Discuss all the scenarios ranging from network connectivity to data in DB from where API fetches its data." }, { "code": null, "e": 4112, "s": 3945, "text": "Round 5 (Bar Raiser round): Final round which will be scheduled only if you clear the previous 4 rounds. Brief introduction followed by following behavioral questions" }, { "code": null, "e": 4166, "s": 4112, "text": "How have you dealt with ambiguous data in your tasks." }, { "code": null, "e": 4251, "s": 4166, "text": "Failure in your task and what you have learned out of it. How can you improve it now" }, { "code": null, "e": 4335, "s": 4251, "text": "Task where u showed your ownership and how you could have improved in your WoW now." }, { "code": null, "e": 4395, "s": 4335, "text": "A Task where you improved the lives of your colleagues/team" }, { "code": null, "e": 4555, "s": 4395, "text": "And few more behavioral questions which were similar to what was asked in the hiring manager round(Both of them were stressing different leadership principles)" }, { "code": null, "e": 4708, "s": 4555, "text": "By God’s grace, next day got a call from the recruiter that I am selected and package negotiation had started. Within a week, the offer was rolled out. " }, { "code": null, "e": 5476, "s": 4708, "text": "Tip for Amazon interview: Each round is based on 2-3 Leadership principles, and you are expected to raise the bar in a few of them. They will not ask on what technology you have worked for but any behavioral question should be answered technically highlighting how efficiently you have contributed to the team/customer. Be ready to explain how you have crossed your responsibilities to work across teams for your tasks. You cannot bluff. You cannot crack if you don’t have those 14 leadership principles(at least a few of them). Your programming question also will be actually evaluated against any of the leadership principles, so don’t concentrate on getting the solution but how efficiently you arrive at the optimized solution. And speak throughout the interview." }, { "code": null, "e": 5564, "s": 5476, "text": "I hope this helps the reader and pray that God bless you with your interview at Amazon." }, { "code": null, "e": 5571, "s": 5564, "text": "Amazon" }, { "code": null, "e": 5581, "s": 5571, "text": "Marketing" }, { "code": null, "e": 5593, "s": 5581, "text": "Experienced" }, { "code": null, "e": 5615, "s": 5593, "text": "Interview Experiences" }, { "code": null, "e": 5622, "s": 5615, "text": "Amazon" } ]
Persistent Segment Tree | Set 1 (Introduction)
11 Jul, 2022 Prerequisite : Segment Tree Persistency in Data Structure Segment Tree is itself a great data structure that comes into play in many cases. In this post we will introduce the concept of Persistency in this data structure. Persistency, simply means to retain the changes. But obviously, retaining the changes cause extra memory consumption and hence affect the Time Complexity. Our aim is to apply persistency in segment tree and also to ensure that it does not take more than O(log n) time and space for each change. 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. Let’s think in terms of versions i.e. for each change in our segment tree we create a new version of it. We will consider our initial version to be Version-0. Now, as we do any update in the segment tree we will create a new version for it and in similar fashion track the record for all versions. But creating the whole tree for every version will take O(n log n) extra space and O(n log n) time. So, this idea runs out of time and memory for large number of versions. Let’s exploit the fact that for each new update(say point update for simplicity) in segment tree, At max logn nodes will be modified. So, our new version will only contain these log n new nodes and rest nodes will be the same as previous version. Therefore, it is quite clear that for each new version we only need to create these log n new nodes whereas the rest of nodes can be shared from the previous version. Consider the below figure for better visualization(click on the image for better view) :- Consider the segment tree with green nodes . Lets call this segment tree as version-0. The left child for each node is connected with solid red edge where as the right child for each node is connected with solid purple edge. Clearly, this segment tree consists of 15 nodes. Now consider we need to make change in the leaf node 13 of version-0. So, the affected nodes will be – node 13 , node 6 , node 3 , node 1. Therefore, for the new version (Version-1) we need to create only these 4 new nodes. Now, lets construct version-1 for this change in segment tree. We need a new node 1 as it is affected by change done in node 13. So , we will first create a new node 1′(yellow color) . The left child for node 1′ will be the same for left child for node 1 in version-0. So, we connect the left child of node 1′ with node 2 of version-0(red dashed line in figure). Let’s now examine the right child for node 1′ in version-1. We need to create a new node as it is affected . So we create a new node called node 3′ and make it the right child for node 1′(solid purple edge connection). In the similar fashion we will now examine for node 3′. The left child is affected , So we create a new node called node 6′ and connect it with solid red edge with node 3′ , where as the right child for node 3′ will be the same as right child of node 3 in version-0. So, we will make the right child of node 3 in version-0 as the right child of node 3′ in version-1(see the purple dash edge.) Same procedure is done for node 6′ and we see that the left child of node 6′ will be the left child of node 6 in version-0(red dashed connection) and right child is newly created node called node 13′(solid purple dashed edge).Each yellow color node is a newly created node and dashed edges are the inter-connection between the different versions of the segment tree. Now, the Question arises : How to keep track of all the versions? – We only need to keep track the first root node for all the versions and this will serve the purpose to track all the newly created nodes in the different versions. For this purpose we can maintain an array of pointers to the first node of segment trees for all versions. Let’s consider a very basic problem to see how to implement persistence in segment tree Problem : Given an array A[] and different point update operations.Considering each point operation to create a new version of the array. We need to answer the queries of type Q v l r : output the sum of elements in range l to r just after the v-th update. We will create all the versions of the segment tree and keep track of their root node.Then for each range sum query we will pass the required version’s root node in our query function and output the required sum. Below is the implementation for the above problem:- Implementation: C++ Java C# Javascript // C++ program to implement persistent segment// tree.#include "bits/stdc++.h"using namespace std; #define MAXN 100 /* data type for individual * node in the segment tree */struct node{ // stores sum of the elements in node int val; // pointer to left and right children node* left, *right; // required constructors........ node() {} node(node* l, node* r, int v) { left = l; right = r; val = v; }}; // input arrayint arr[MAXN]; // root pointers for all versionsnode* version[MAXN]; // Constructs Version-0// Time Complexity : O(nlogn)void build(node* n,int low,int high){ if (low==high) { n->val = arr[low]; return; } int mid = (low+high) / 2; n->left = new node(NULL, NULL, 0); n->right = new node(NULL, NULL, 0); build(n->left, low, mid); build(n->right, mid+1, high); n->val = n->left->val + n->right->val;} /** * Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */void upgrade(node* prev, node* cur, int low, int high, int idx, int value){ if (idx > high or idx < low or low > high) return; if (low == high) { // modification in new version cur->val = value; return; } int mid = (low+high) / 2; if (idx <= mid) { // link to right child of previous version cur->right = prev->right; // create new node in current version cur->left = new node(NULL, NULL, 0); upgrade(prev->left,cur->left, low, mid, idx, value); } else { // link to left child of previous version cur->left = prev->left; // create new node for current version cur->right = new node(NULL, NULL, 0); upgrade(prev->right, cur->right, mid+1, high, idx, value); } // calculating data for current version // by combining previous version and current // modification cur->val = cur->left->val + cur->right->val;} int query(node* n, int low, int high, int l, int r){ if (l > high or r < low or low > high) return 0; if (l <= low and high <= r) return n->val; int mid = (low+high) / 2; int p1 = query(n->left,low,mid,l,r); int p2 = query(n->right,mid+1,high,l,r); return p1+p2;} int main(int argc, char const *argv[]){ int A[] = {1,2,3,4,5}; int n = sizeof(A)/sizeof(int); for (int i=0; i<n; i++) arr[i] = A[i]; // creating Version-0 node* root = new node(NULL, NULL, 0); build(root, 0, n-1); // storing root node for version-0 version[0] = root; // upgrading to version-1 version[1] = new node(NULL, NULL, 0); upgrade(version[0], version[1], 0, n-1, 4, 1); // upgrading to version-2 version[2] = new node(NULL, NULL, 0); upgrade(version[1],version[2], 0, n-1, 2, 10); cout << "In version 1 , query(0,4) : "; cout << query(version[1], 0, n-1, 0, 4) << endl; cout << "In version 2 , query(3,4) : "; cout << query(version[2], 0, n-1, 3, 4) << endl; cout << "In version 0 , query(0,3) : "; cout << query(version[0], 0, n-1, 0, 3) << endl; return 0;} // Java program to implement persistent// segment tree.class GFG{ // Declaring maximum numberstatic Integer MAXN = 100; // Making Node for treestatic class node { // Stores sum of the elements in node int val; // Reference to left and right children node left, right; // Required constructors.. node() {} // Node constructor for l,r,v node(node l, node r, int v) { left = l; right = r; val = v; }} // Input arraystatic int[] arr = new int[MAXN]; // Root pointers for all versionsstatic node version[] = new node[MAXN]; // Constructs Version-0// Time Complexity : O(nlogn)static void build(node n, int low, int high){ if (low == high) { n.val = arr[low]; return; } int mid = (low + high) / 2; n.left = new node(null, null, 0); n.right = new node(null, null, 0); build(n.left, low, mid); build(n.right, mid + 1, high); n.val = n.left.val + n.right.val;} /* Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */static void upgrade(node prev, node cur, int low, int high, int idx, int value){ if (idx > high || idx < low || low > high) return; if (low == high) { // Modification in new version cur.val = value; return; } int mid = (low + high) / 2; if (idx <= mid) { // Link to right child of previous version cur.right = prev.right; // Create new node in current version cur.left = new node(null, null, 0); upgrade(prev.left, cur.left, low, mid, idx, value); } else { // Link to left child of previous version cur.left = prev.left; // Create new node for current version cur.right = new node(null, null, 0); upgrade(prev.right, cur.right, mid + 1, high, idx, value); } // Calculating data for current version // by combining previous version and current // modification cur.val = cur.left.val + cur.right.val;} static int query(node n, int low, int high, int l, int r){ if (l > high || r < low || low > high) return 0; if (l <= low && high <= r) return n.val; int mid = (low + high) / 2; int p1 = query(n.left, low, mid, l, r); int p2 = query(n.right, mid + 1, high, l, r); return p1 + p2;} // Driver codepublic static void main(String[] args){ int A[] = { 1, 2, 3, 4, 5 }; int n = A.length; for(int i = 0; i < n; i++) arr[i] = A[i]; // Creating Version-0 node root = new node(null, null, 0); build(root, 0, n - 1); // Storing root node for version-0 version[0] = root; // Upgrading to version-1 version[1] = new node(null, null, 0); upgrade(version[0], version[1], 0, n - 1, 4, 1); // Upgrading to version-2 version[2] = new node(null, null, 0); upgrade(version[1], version[2], 0, n - 1, 2, 10); // For print System.out.print("In version 1 , query(0,4) : "); System.out.print(query(version[1], 0, n - 1, 0, 4)); System.out.print("\nIn version 2 , query(3,4) : "); System.out.print(query(version[2], 0, n - 1, 3, 4)); System.out.print("\nIn version 0 , query(0,3) : "); System.out.print(query(version[0], 0, n - 1, 0, 3));}} // This code is contributed by mark_85 // C# program to implement persistent// segment tree.using System; class node{ // Stores sum of the elements in node public int val; // Reference to left and right children public node left, right; // Required constructors.. public node() {} // Node constructor for l,r,v public node(node l, node r, int v) { left = l; right = r; val = v; }} class GFG{ // Declaring maximum numberstatic int MAXN = 100; // Making Node for tree// Input arraystatic int[] arr = new int[MAXN]; // Root pointers for all versionsstatic node[] version = new node[MAXN]; // Constructs Version-0// Time Complexity : O(nlogn)static void build(node n, int low, int high){ if (low == high) { n.val = arr[low]; return; } int mid = (low + high) / 2; n.left = new node(null, null, 0); n.right = new node(null, null, 0); build(n.left, low, mid); build(n.right, mid + 1, high); n.val = n.left.val + n.right.val;} /* Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */static void upgrade(node prev, node cur, int low, int high, int idx, int value){ if (idx > high || idx < low || low > high) return; if (low == high) { // Modification in new version cur.val = value; return; } int mid = (low + high) / 2; if (idx <= mid) { // Link to right child of previous version cur.right = prev.right; // Create new node in current version cur.left = new node(null, null, 0); upgrade(prev.left, cur.left, low, mid, idx, value); } else { // Link to left child of previous version cur.left = prev.left; // Create new node for current version cur.right = new node(null, null, 0); upgrade(prev.right, cur.right, mid + 1, high, idx, value); } // Calculating data for current version // by combining previous version and current // modification cur.val = cur.left.val + cur.right.val;} static int query(node n, int low, int high, int l, int r){ if (l > high || r < low || low > high) return 0; if (l <= low && high <= r) return n.val; int mid = (low + high) / 2; int p1 = query(n.left, low, mid, l, r); int p2 = query(n.right, mid + 1, high, l, r); return p1 + p2;} // Driver codepublic static void Main(String[] args){ int[] A = { 1, 2, 3, 4, 5 }; int n = A.Length; for(int i = 0; i < n; i++) arr[i] = A[i]; // Creating Version-0 node root = new node(null, null, 0); build(root, 0, n - 1); // Storing root node for version-0 version[0] = root; // Upgrading to version-1 version[1] = new node(null, null, 0); upgrade(version[0], version[1], 0, n - 1, 4, 1); // Upgrading to version-2 version[2] = new node(null, null, 0); upgrade(version[1], version[2], 0, n - 1, 2, 10); // For print Console.Write("In version 1 , query(0,4) : "); Console.Write(query(version[1], 0, n - 1, 0, 4)); Console.Write("\nIn version 2 , query(3,4) : "); Console.Write(query(version[2], 0, n - 1, 3, 4)); Console.Write("\nIn version 0 , query(0,3) : "); Console.Write(query(version[0], 0, n - 1, 0, 3));}} // This code is contributed by sanjeev2552 <script> // JavaScript program to implement persistent// segment tree.class node{ // Node constructor for l,r,v constructor(l, r, v) { this.left = l; this.right = r; this.val = v; }} // Declaring maximum numbervar MAXN = 100; // Making Node for tree// Input arrayvar arr = Array(MAXN); // Root pointers for all versionsvar version = Array(MAXN); // Constructs Version-0// Time Complexity : O(nlogn)function build(n, low, high){ if (low == high) { n.val = arr[low]; return; } var mid = parseInt((low + high) / 2); n.left = new node(null, null, 0); n.right = new node(null, null, 0); build(n.left, low, mid); build(n.right, mid + 1, high); n.val = n.left.val + n.right.val;} /* Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */function upgrade(prev, cur, low, high, idx, value){ if (idx > high || idx < low || low > high) return; if (low == high) { // Modification in new version cur.val = value; return; } var mid = parseInt((low + high) / 2); if (idx <= mid) { // Link to right child of previous version cur.right = prev.right; // Create new node in current version cur.left = new node(null, null, 0); upgrade(prev.left, cur.left, low, mid, idx, value); } else { // Link to left child of previous version cur.left = prev.left; // Create new node for current version cur.right = new node(null, null, 0); upgrade(prev.right, cur.right, mid + 1, high, idx, value); } // Calculating data for current version // by combining previous version and current // modification cur.val = cur.left.val + cur.right.val;} function query(n, low, high, l, r){ if (l > high || r < low || low > high) return 0; if (l <= low && high <= r) return n.val; var mid = parseInt((low + high) / 2); var p1 = query(n.left, low, mid, l, r); var p2 = query(n.right, mid + 1, high, l, r); return p1 + p2;} // Driver codevar A = [1, 2, 3, 4, 5];var n = A.length; for(var i = 0; i < n; i++) arr[i] = A[i]; // Creating Version-0var root = new node(null, null, 0);build(root, 0, n - 1); // Storing root node for version-0version[0] = root; // Upgrading to version-1version[1] = new node(null, null, 0);upgrade(version[0], version[1], 0, n - 1, 4, 1); // Upgrading to version-2version[2] = new node(null, null, 0);upgrade(version[1], version[2], 0, n - 1, 2, 10); // For printdocument.write("In version 1 , query(0,4) : ");document.write(query(version[1], 0, n - 1, 0, 4)); document.write("<br>In version 2 , query(3,4) : ");document.write(query(version[2], 0, n - 1, 3, 4)); document.write("<br>In version 0 , query(0,3) : ");document.write(query(version[0], 0, n - 1, 0, 3)); </script> In version 1 , query(0,4) : 11 In version 2 , query(3,4) : 5 In version 0 , query(0,3) : 10 Note: The above problem can also be solved by processing the queries offline by sorting it with respect to the version and answering the queries just after the corresponding update. Time Complexity: The time complexity will be the same as the query and point update operation in the segment tree as we can consider the extra node creation step to be done in O(1). Hence, the overall Time Complexity per query for new version creation and range sum query will be O(log n). Auxiliary Space: O(log n) This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Related Topic: Segment Tree sujitmeshram sanjeev2552 itsok rishavnitro hardikkoriintern array-range-queries Segment-Tree Advanced Data Structure Tree Tree Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 125, "s": 52, "text": "Prerequisite : Segment Tree\n Persistency in Data Structure" }, { "code": null, "e": 444, "s": 125, "text": "Segment Tree is itself a great data structure that comes into play in many cases. In this post we will introduce the concept of Persistency in this data structure. Persistency, simply means to retain the changes. But obviously, retaining the changes cause extra memory consumption and hence affect the Time Complexity." }, { "code": null, "e": 584, "s": 444, "text": "Our aim is to apply persistency in segment tree and also to ensure that it does not take more than O(log n) time and space for each change." }, { "code": null, "e": 593, "s": 584, "text": "Chapters" }, { "code": null, "e": 620, "s": 593, "text": "descriptions off, selected" }, { "code": null, "e": 670, "s": 620, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 693, "s": 670, "text": "captions off, selected" }, { "code": null, "e": 701, "s": 693, "text": "English" }, { "code": null, "e": 725, "s": 701, "text": "This is a modal window." }, { "code": null, "e": 794, "s": 725, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 816, "s": 794, "text": "End of dialog window." }, { "code": null, "e": 1114, "s": 816, "text": "Let’s think in terms of versions i.e. for each change in our segment tree we create a new version of it. We will consider our initial version to be Version-0. Now, as we do any update in the segment tree we will create a new version for it and in similar fashion track the record for all versions." }, { "code": null, "e": 1286, "s": 1114, "text": "But creating the whole tree for every version will take O(n log n) extra space and O(n log n) time. So, this idea runs out of time and memory for large number of versions." }, { "code": null, "e": 1700, "s": 1286, "text": "Let’s exploit the fact that for each new update(say point update for simplicity) in segment tree, At max logn nodes will be modified. So, our new version will only contain these log n new nodes and rest nodes will be the same as previous version. Therefore, it is quite clear that for each new version we only need to create these log n new nodes whereas the rest of nodes can be shared from the previous version." }, { "code": null, "e": 1791, "s": 1700, "text": "Consider the below figure for better visualization(click on the image for better view) :- " }, { "code": null, "e": 2065, "s": 1791, "text": "Consider the segment tree with green nodes . Lets call this segment tree as version-0. The left child for each node is connected with solid red edge where as the right child for each node is connected with solid purple edge. Clearly, this segment tree consists of 15 nodes." }, { "code": null, "e": 2289, "s": 2065, "text": "Now consider we need to make change in the leaf node 13 of version-0. So, the affected nodes will be – node 13 , node 6 , node 3 , node 1. Therefore, for the new version (Version-1) we need to create only these 4 new nodes." }, { "code": null, "e": 2871, "s": 2289, "text": "Now, lets construct version-1 for this change in segment tree. We need a new node 1 as it is affected by change done in node 13. So , we will first create a new node 1′(yellow color) . The left child for node 1′ will be the same for left child for node 1 in version-0. So, we connect the left child of node 1′ with node 2 of version-0(red dashed line in figure). Let’s now examine the right child for node 1′ in version-1. We need to create a new node as it is affected . So we create a new node called node 3′ and make it the right child for node 1′(solid purple edge connection)." }, { "code": null, "e": 3265, "s": 2871, "text": "In the similar fashion we will now examine for node 3′. The left child is affected , So we create a new node called node 6′ and connect it with solid red edge with node 3′ , where as the right child for node 3′ will be the same as right child of node 3 in version-0. So, we will make the right child of node 3 in version-0 as the right child of node 3′ in version-1(see the purple dash edge.) " }, { "code": null, "e": 3632, "s": 3265, "text": "Same procedure is done for node 6′ and we see that the left child of node 6′ will be the left child of node 6 in version-0(red dashed connection) and right child is newly created node called node 13′(solid purple dashed edge).Each yellow color node is a newly created node and dashed edges are the inter-connection between the different versions of the segment tree." }, { "code": null, "e": 3971, "s": 3632, "text": "Now, the Question arises : How to keep track of all the versions? – We only need to keep track the first root node for all the versions and this will serve the purpose to track all the newly created nodes in the different versions. For this purpose we can maintain an array of pointers to the first node of segment trees for all versions." }, { "code": null, "e": 4060, "s": 3971, "text": "Let’s consider a very basic problem to see how to implement persistence in segment tree " }, { "code": null, "e": 4319, "s": 4060, "text": "Problem : Given an array A[] and different point update operations.Considering \neach point operation to create a new version of the array. We need to answer \nthe queries of type\nQ v l r : output the sum of elements in range l to r just after the v-th update." }, { "code": null, "e": 4532, "s": 4319, "text": "We will create all the versions of the segment tree and keep track of their root node.Then for each range sum query we will pass the required version’s root node in our query function and output the required sum." }, { "code": null, "e": 4585, "s": 4532, "text": "Below is the implementation for the above problem:- " }, { "code": null, "e": 4601, "s": 4585, "text": "Implementation:" }, { "code": null, "e": 4605, "s": 4601, "text": "C++" }, { "code": null, "e": 4610, "s": 4605, "text": "Java" }, { "code": null, "e": 4613, "s": 4610, "text": "C#" }, { "code": null, "e": 4624, "s": 4613, "text": "Javascript" }, { "code": "// C++ program to implement persistent segment// tree.#include \"bits/stdc++.h\"using namespace std; #define MAXN 100 /* data type for individual * node in the segment tree */struct node{ // stores sum of the elements in node int val; // pointer to left and right children node* left, *right; // required constructors........ node() {} node(node* l, node* r, int v) { left = l; right = r; val = v; }}; // input arrayint arr[MAXN]; // root pointers for all versionsnode* version[MAXN]; // Constructs Version-0// Time Complexity : O(nlogn)void build(node* n,int low,int high){ if (low==high) { n->val = arr[low]; return; } int mid = (low+high) / 2; n->left = new node(NULL, NULL, 0); n->right = new node(NULL, NULL, 0); build(n->left, low, mid); build(n->right, mid+1, high); n->val = n->left->val + n->right->val;} /** * Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */void upgrade(node* prev, node* cur, int low, int high, int idx, int value){ if (idx > high or idx < low or low > high) return; if (low == high) { // modification in new version cur->val = value; return; } int mid = (low+high) / 2; if (idx <= mid) { // link to right child of previous version cur->right = prev->right; // create new node in current version cur->left = new node(NULL, NULL, 0); upgrade(prev->left,cur->left, low, mid, idx, value); } else { // link to left child of previous version cur->left = prev->left; // create new node for current version cur->right = new node(NULL, NULL, 0); upgrade(prev->right, cur->right, mid+1, high, idx, value); } // calculating data for current version // by combining previous version and current // modification cur->val = cur->left->val + cur->right->val;} int query(node* n, int low, int high, int l, int r){ if (l > high or r < low or low > high) return 0; if (l <= low and high <= r) return n->val; int mid = (low+high) / 2; int p1 = query(n->left,low,mid,l,r); int p2 = query(n->right,mid+1,high,l,r); return p1+p2;} int main(int argc, char const *argv[]){ int A[] = {1,2,3,4,5}; int n = sizeof(A)/sizeof(int); for (int i=0; i<n; i++) arr[i] = A[i]; // creating Version-0 node* root = new node(NULL, NULL, 0); build(root, 0, n-1); // storing root node for version-0 version[0] = root; // upgrading to version-1 version[1] = new node(NULL, NULL, 0); upgrade(version[0], version[1], 0, n-1, 4, 1); // upgrading to version-2 version[2] = new node(NULL, NULL, 0); upgrade(version[1],version[2], 0, n-1, 2, 10); cout << \"In version 1 , query(0,4) : \"; cout << query(version[1], 0, n-1, 0, 4) << endl; cout << \"In version 2 , query(3,4) : \"; cout << query(version[2], 0, n-1, 3, 4) << endl; cout << \"In version 0 , query(0,3) : \"; cout << query(version[0], 0, n-1, 0, 3) << endl; return 0;}", "e": 7871, "s": 4624, "text": null }, { "code": "// Java program to implement persistent// segment tree.class GFG{ // Declaring maximum numberstatic Integer MAXN = 100; // Making Node for treestatic class node { // Stores sum of the elements in node int val; // Reference to left and right children node left, right; // Required constructors.. node() {} // Node constructor for l,r,v node(node l, node r, int v) { left = l; right = r; val = v; }} // Input arraystatic int[] arr = new int[MAXN]; // Root pointers for all versionsstatic node version[] = new node[MAXN]; // Constructs Version-0// Time Complexity : O(nlogn)static void build(node n, int low, int high){ if (low == high) { n.val = arr[low]; return; } int mid = (low + high) / 2; n.left = new node(null, null, 0); n.right = new node(null, null, 0); build(n.left, low, mid); build(n.right, mid + 1, high); n.val = n.left.val + n.right.val;} /* Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */static void upgrade(node prev, node cur, int low, int high, int idx, int value){ if (idx > high || idx < low || low > high) return; if (low == high) { // Modification in new version cur.val = value; return; } int mid = (low + high) / 2; if (idx <= mid) { // Link to right child of previous version cur.right = prev.right; // Create new node in current version cur.left = new node(null, null, 0); upgrade(prev.left, cur.left, low, mid, idx, value); } else { // Link to left child of previous version cur.left = prev.left; // Create new node for current version cur.right = new node(null, null, 0); upgrade(prev.right, cur.right, mid + 1, high, idx, value); } // Calculating data for current version // by combining previous version and current // modification cur.val = cur.left.val + cur.right.val;} static int query(node n, int low, int high, int l, int r){ if (l > high || r < low || low > high) return 0; if (l <= low && high <= r) return n.val; int mid = (low + high) / 2; int p1 = query(n.left, low, mid, l, r); int p2 = query(n.right, mid + 1, high, l, r); return p1 + p2;} // Driver codepublic static void main(String[] args){ int A[] = { 1, 2, 3, 4, 5 }; int n = A.length; for(int i = 0; i < n; i++) arr[i] = A[i]; // Creating Version-0 node root = new node(null, null, 0); build(root, 0, n - 1); // Storing root node for version-0 version[0] = root; // Upgrading to version-1 version[1] = new node(null, null, 0); upgrade(version[0], version[1], 0, n - 1, 4, 1); // Upgrading to version-2 version[2] = new node(null, null, 0); upgrade(version[1], version[2], 0, n - 1, 2, 10); // For print System.out.print(\"In version 1 , query(0,4) : \"); System.out.print(query(version[1], 0, n - 1, 0, 4)); System.out.print(\"\\nIn version 2 , query(3,4) : \"); System.out.print(query(version[2], 0, n - 1, 3, 4)); System.out.print(\"\\nIn version 0 , query(0,3) : \"); System.out.print(query(version[0], 0, n - 1, 0, 3));}} // This code is contributed by mark_85", "e": 11386, "s": 7871, "text": null }, { "code": "// C# program to implement persistent// segment tree.using System; class node{ // Stores sum of the elements in node public int val; // Reference to left and right children public node left, right; // Required constructors.. public node() {} // Node constructor for l,r,v public node(node l, node r, int v) { left = l; right = r; val = v; }} class GFG{ // Declaring maximum numberstatic int MAXN = 100; // Making Node for tree// Input arraystatic int[] arr = new int[MAXN]; // Root pointers for all versionsstatic node[] version = new node[MAXN]; // Constructs Version-0// Time Complexity : O(nlogn)static void build(node n, int low, int high){ if (low == high) { n.val = arr[low]; return; } int mid = (low + high) / 2; n.left = new node(null, null, 0); n.right = new node(null, null, 0); build(n.left, low, mid); build(n.right, mid + 1, high); n.val = n.left.val + n.right.val;} /* Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */static void upgrade(node prev, node cur, int low, int high, int idx, int value){ if (idx > high || idx < low || low > high) return; if (low == high) { // Modification in new version cur.val = value; return; } int mid = (low + high) / 2; if (idx <= mid) { // Link to right child of previous version cur.right = prev.right; // Create new node in current version cur.left = new node(null, null, 0); upgrade(prev.left, cur.left, low, mid, idx, value); } else { // Link to left child of previous version cur.left = prev.left; // Create new node for current version cur.right = new node(null, null, 0); upgrade(prev.right, cur.right, mid + 1, high, idx, value); } // Calculating data for current version // by combining previous version and current // modification cur.val = cur.left.val + cur.right.val;} static int query(node n, int low, int high, int l, int r){ if (l > high || r < low || low > high) return 0; if (l <= low && high <= r) return n.val; int mid = (low + high) / 2; int p1 = query(n.left, low, mid, l, r); int p2 = query(n.right, mid + 1, high, l, r); return p1 + p2;} // Driver codepublic static void Main(String[] args){ int[] A = { 1, 2, 3, 4, 5 }; int n = A.Length; for(int i = 0; i < n; i++) arr[i] = A[i]; // Creating Version-0 node root = new node(null, null, 0); build(root, 0, n - 1); // Storing root node for version-0 version[0] = root; // Upgrading to version-1 version[1] = new node(null, null, 0); upgrade(version[0], version[1], 0, n - 1, 4, 1); // Upgrading to version-2 version[2] = new node(null, null, 0); upgrade(version[1], version[2], 0, n - 1, 2, 10); // For print Console.Write(\"In version 1 , query(0,4) : \"); Console.Write(query(version[1], 0, n - 1, 0, 4)); Console.Write(\"\\nIn version 2 , query(3,4) : \"); Console.Write(query(version[2], 0, n - 1, 3, 4)); Console.Write(\"\\nIn version 0 , query(0,3) : \"); Console.Write(query(version[0], 0, n - 1, 0, 3));}} // This code is contributed by sanjeev2552", "e": 15007, "s": 11386, "text": null }, { "code": "<script> // JavaScript program to implement persistent// segment tree.class node{ // Node constructor for l,r,v constructor(l, r, v) { this.left = l; this.right = r; this.val = v; }} // Declaring maximum numbervar MAXN = 100; // Making Node for tree// Input arrayvar arr = Array(MAXN); // Root pointers for all versionsvar version = Array(MAXN); // Constructs Version-0// Time Complexity : O(nlogn)function build(n, low, high){ if (low == high) { n.val = arr[low]; return; } var mid = parseInt((low + high) / 2); n.left = new node(null, null, 0); n.right = new node(null, null, 0); build(n.left, low, mid); build(n.right, mid + 1, high); n.val = n.left.val + n.right.val;} /* Upgrades to new Version * @param prev : points to node of previous version * @param cur : points to node of current version * Time Complexity : O(logn) * Space Complexity : O(logn) */function upgrade(prev, cur, low, high, idx, value){ if (idx > high || idx < low || low > high) return; if (low == high) { // Modification in new version cur.val = value; return; } var mid = parseInt((low + high) / 2); if (idx <= mid) { // Link to right child of previous version cur.right = prev.right; // Create new node in current version cur.left = new node(null, null, 0); upgrade(prev.left, cur.left, low, mid, idx, value); } else { // Link to left child of previous version cur.left = prev.left; // Create new node for current version cur.right = new node(null, null, 0); upgrade(prev.right, cur.right, mid + 1, high, idx, value); } // Calculating data for current version // by combining previous version and current // modification cur.val = cur.left.val + cur.right.val;} function query(n, low, high, l, r){ if (l > high || r < low || low > high) return 0; if (l <= low && high <= r) return n.val; var mid = parseInt((low + high) / 2); var p1 = query(n.left, low, mid, l, r); var p2 = query(n.right, mid + 1, high, l, r); return p1 + p2;} // Driver codevar A = [1, 2, 3, 4, 5];var n = A.length; for(var i = 0; i < n; i++) arr[i] = A[i]; // Creating Version-0var root = new node(null, null, 0);build(root, 0, n - 1); // Storing root node for version-0version[0] = root; // Upgrading to version-1version[1] = new node(null, null, 0);upgrade(version[0], version[1], 0, n - 1, 4, 1); // Upgrading to version-2version[2] = new node(null, null, 0);upgrade(version[1], version[2], 0, n - 1, 2, 10); // For printdocument.write(\"In version 1 , query(0,4) : \");document.write(query(version[1], 0, n - 1, 0, 4)); document.write(\"<br>In version 2 , query(3,4) : \");document.write(query(version[2], 0, n - 1, 3, 4)); document.write(\"<br>In version 0 , query(0,3) : \");document.write(query(version[0], 0, n - 1, 0, 3)); </script>", "e": 18109, "s": 15007, "text": null }, { "code": null, "e": 18201, "s": 18109, "text": "In version 1 , query(0,4) : 11\nIn version 2 , query(3,4) : 5\nIn version 0 , query(0,3) : 10" }, { "code": null, "e": 18383, "s": 18201, "text": "Note: The above problem can also be solved by processing the queries offline by sorting it with respect to the version and answering the queries just after the corresponding update." }, { "code": null, "e": 18673, "s": 18383, "text": "Time Complexity: The time complexity will be the same as the query and point update operation in the segment tree as we can consider the extra node creation step to be done in O(1). Hence, the overall Time Complexity per query for new version creation and range sum query will be O(log n)." }, { "code": null, "e": 18700, "s": 18673, "text": "Auxiliary Space: O(log n) " }, { "code": null, "e": 18997, "s": 18700, "text": "This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 19025, "s": 18997, "text": "Related Topic: Segment Tree" }, { "code": null, "e": 19038, "s": 19025, "text": "sujitmeshram" }, { "code": null, "e": 19050, "s": 19038, "text": "sanjeev2552" }, { "code": null, "e": 19056, "s": 19050, "text": "itsok" }, { "code": null, "e": 19068, "s": 19056, "text": "rishavnitro" }, { "code": null, "e": 19085, "s": 19068, "text": "hardikkoriintern" }, { "code": null, "e": 19105, "s": 19085, "text": "array-range-queries" }, { "code": null, "e": 19118, "s": 19105, "text": "Segment-Tree" }, { "code": null, "e": 19142, "s": 19118, "text": "Advanced Data Structure" }, { "code": null, "e": 19147, "s": 19142, "text": "Tree" }, { "code": null, "e": 19152, "s": 19147, "text": "Tree" }, { "code": null, "e": 19165, "s": 19152, "text": "Segment-Tree" } ]
HTML | <object> align Attribute
22 Feb, 2022 The HTML <object> align Attribute is used to specify an alignment for an object Element. It is an inline element means that can not insert a new line on a page. The text and other elements can also wrap around it. Note: This attribute is not supported by HTML5. Syntax: <object align="left | right | middle | top | bottom"> Attribute Values: left: It sets the object to the left-align. right: It sets the object to the right-align. middle: It sets the object to the middle. top: It sets the object to the top-align. Bottom: It sets the object to the bottom align. Example: html <!DOCTYPE html><html> <head> <title> HTML object align Attribute </title></head> <body style="text-align:center;"> <h2>HTML object align Attribute</h2> <object id="myobject" width="200" height="100" align="left" data="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png"> </object> <object id="myobject" width="200" height="100" align="right" data="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png"> </object> <object id="myobject" width="200" height="100" align="middle" data= "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png"> </object> <object id="myobject" width="200" height="100" align="top" data="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png"> </object></body> </html> Output: Supported Browsers: The browser supported by HTML object align attribute are listed below: Google Chrome 10.0 Internet Explorer 10.0 Firefox 4.0 Opera 10.6 Apple Safari hritikbhatnagar2182 kashishsoda chhabradhanvi HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2022" }, { "code": null, "e": 291, "s": 28, "text": "The HTML <object> align Attribute is used to specify an alignment for an object Element. It is an inline element means that can not insert a new line on a page. The text and other elements can also wrap around it. Note: This attribute is not supported by HTML5. " }, { "code": null, "e": 301, "s": 291, "text": "Syntax: " }, { "code": null, "e": 355, "s": 301, "text": "<object align=\"left | right | middle | top | bottom\">" }, { "code": null, "e": 375, "s": 355, "text": "Attribute Values: " }, { "code": null, "e": 419, "s": 375, "text": "left: It sets the object to the left-align." }, { "code": null, "e": 465, "s": 419, "text": "right: It sets the object to the right-align." }, { "code": null, "e": 507, "s": 465, "text": "middle: It sets the object to the middle." }, { "code": null, "e": 549, "s": 507, "text": "top: It sets the object to the top-align." }, { "code": null, "e": 597, "s": 549, "text": "Bottom: It sets the object to the bottom align." }, { "code": null, "e": 608, "s": 597, "text": "Example: " }, { "code": null, "e": 613, "s": 608, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML object align Attribute </title></head> <body style=\"text-align:center;\"> <h2>HTML object align Attribute</h2> <object id=\"myobject\" width=\"200\" height=\"100\" align=\"left\" data=\"https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png\"> </object> <object id=\"myobject\" width=\"200\" height=\"100\" align=\"right\" data=\"https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png\"> </object> <object id=\"myobject\" width=\"200\" height=\"100\" align=\"middle\" data= \"https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png\"> </object> <object id=\"myobject\" width=\"200\" height=\"100\" align=\"top\" data=\"https://cdncontribute.geeksforgeeks.org/wp-content/uploads/geek-8.png\"> </object></body> </html>", "e": 1604, "s": 613, "text": null }, { "code": null, "e": 1614, "s": 1604, "text": "Output: " }, { "code": null, "e": 1707, "s": 1614, "text": "Supported Browsers: The browser supported by HTML object align attribute are listed below: " }, { "code": null, "e": 1726, "s": 1707, "text": "Google Chrome 10.0" }, { "code": null, "e": 1749, "s": 1726, "text": "Internet Explorer 10.0" }, { "code": null, "e": 1761, "s": 1749, "text": "Firefox 4.0" }, { "code": null, "e": 1772, "s": 1761, "text": "Opera 10.6" }, { "code": null, "e": 1785, "s": 1772, "text": "Apple Safari" }, { "code": null, "e": 1807, "s": 1787, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1819, "s": 1807, "text": "kashishsoda" }, { "code": null, "e": 1833, "s": 1819, "text": "chhabradhanvi" }, { "code": null, "e": 1849, "s": 1833, "text": "HTML-Attributes" }, { "code": null, "e": 1854, "s": 1849, "text": "HTML" }, { "code": null, "e": 1871, "s": 1854, "text": "Web Technologies" }, { "code": null, "e": 1876, "s": 1871, "text": "HTML" } ]
Node.js process.traceDeprecation Property
10 Jun, 2021 The process.traceDeprecation property is an inbuilt application programming interface of the process module which is used to indicate whether the –trace-deprecation flag is set on the current Node.js process. Syntax: process.traceDeprecation Return Value: This property indicates whether the –trace-deprecation flag is set on the current Node.js process. Below examples illustrate the use of the process.traceDeprecation property in Node.js: Example 1: index.js // Node.js program to demonstrate the// process.traceDeprecation Property // Include process moduleconst process = require('process'); // Printing process.traceDeprecation property valueconsole.log(process.traceDeprecation); Run the index.js file using the following command: node --trace-deprecation index.js Output: true Again run the same file, but using the different command as shown below: node index.js Output: undefined Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// process.traceDeprecation Property // Include process moduleconst process = require('process'); // Instance Properties process.traceDeprecation = false; // Printing process.traceDeprecation// property valueconsole.log(process.traceDeprecation); // Instance Properties process.traceDeprecation = true; // Printing process.traceDeprecation// property valueconsole.log(process.traceDeprecation); Run the index.js file using the following command: node --trace-deprecation index.js Output: true true Again run the same file, but using the different command as shown below: node index.js Output: false true Node.js-process-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2021" }, { "code": null, "e": 237, "s": 28, "text": "The process.traceDeprecation property is an inbuilt application programming interface of the process module which is used to indicate whether the –trace-deprecation flag is set on the current Node.js process." }, { "code": null, "e": 245, "s": 237, "text": "Syntax:" }, { "code": null, "e": 270, "s": 245, "text": "process.traceDeprecation" }, { "code": null, "e": 383, "s": 270, "text": "Return Value: This property indicates whether the –trace-deprecation flag is set on the current Node.js process." }, { "code": null, "e": 470, "s": 383, "text": "Below examples illustrate the use of the process.traceDeprecation property in Node.js:" }, { "code": null, "e": 483, "s": 472, "text": "Example 1:" }, { "code": null, "e": 492, "s": 483, "text": "index.js" }, { "code": "// Node.js program to demonstrate the// process.traceDeprecation Property // Include process moduleconst process = require('process'); // Printing process.traceDeprecation property valueconsole.log(process.traceDeprecation);", "e": 719, "s": 492, "text": null }, { "code": null, "e": 770, "s": 719, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 804, "s": 770, "text": "node --trace-deprecation index.js" }, { "code": null, "e": 812, "s": 804, "text": "Output:" }, { "code": null, "e": 817, "s": 812, "text": "true" }, { "code": null, "e": 890, "s": 817, "text": "Again run the same file, but using the different command as shown below:" }, { "code": null, "e": 904, "s": 890, "text": "node index.js" }, { "code": null, "e": 912, "s": 904, "text": "Output:" }, { "code": null, "e": 922, "s": 912, "text": "undefined" }, { "code": null, "e": 933, "s": 922, "text": "Example 2:" }, { "code": null, "e": 952, "s": 933, "text": "Filename: index.js" }, { "code": null, "e": 963, "s": 952, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// process.traceDeprecation Property // Include process moduleconst process = require('process'); // Instance Properties process.traceDeprecation = false; // Printing process.traceDeprecation// property valueconsole.log(process.traceDeprecation); // Instance Properties process.traceDeprecation = true; // Printing process.traceDeprecation// property valueconsole.log(process.traceDeprecation);", "e": 1400, "s": 963, "text": null }, { "code": null, "e": 1451, "s": 1400, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 1485, "s": 1451, "text": "node --trace-deprecation index.js" }, { "code": null, "e": 1493, "s": 1485, "text": "Output:" }, { "code": null, "e": 1503, "s": 1493, "text": "true\ntrue" }, { "code": null, "e": 1576, "s": 1503, "text": "Again run the same file, but using the different command as shown below:" }, { "code": null, "e": 1590, "s": 1576, "text": "node index.js" }, { "code": null, "e": 1598, "s": 1590, "text": "Output:" }, { "code": null, "e": 1609, "s": 1598, "text": "false\ntrue" }, { "code": null, "e": 1632, "s": 1609, "text": "Node.js-process-module" }, { "code": null, "e": 1639, "s": 1632, "text": "Picked" }, { "code": null, "e": 1647, "s": 1639, "text": "Node.js" }, { "code": null, "e": 1664, "s": 1647, "text": "Web Technologies" } ]
Lodash | _.castArray() Method - GeeksforGeeks
22 Jul, 2021 The _.castArray() method is used to cast value into an array if it is not an array. Syntax: _.castArray( value ) Parameters: This method accepts single parameter as mentioned above and described below: value: This parameter holds the value that need to be inspect. Return Value: It returns an array with the including value passed in the _.castArray(). Example 1: This example using integer value as a parameter. Javascript const _ = require('lodash'); let x = 10; let arr = _.castArray(x); console.log("\n\nThe value returned to by _castArray(x) is", arr); Here, const _ = require(‘lodash’) is used to import the lodash library into the file.Output: Example 2: This example using String, null, and undefined as a parameter. Javascript const _ = require('lodash'); let x = _.castArray('abc'); console.log('\n With String ', x ); let y = _.castArray(null); console.log('\n With null ', y ); let z = _.castArray(undefined); console.log('\n With undefined ', z); Output: Example 3: With no parameter, object, and function. Javascript const _ = require('lodash'); let x = _.castArray(); console.log("\n With no parameter ", x); let y = _.castArray({"name":"lodash", "work":"I'm make js more" }); console.log("\n With object ", y); let z = _.castArray(function hello() { console.log("hello");}); console.log("\n with function ", z); Output: Example 4: This example using multiple parameters, it will take only the first parameter and with an array, it will just return the same array. Javascript const _ = require('lodash'); let x = _.castArray(1, 2, "hello"); console.log('\n With multiple parameter ', x); let y = _.castArray([1, 2, 3]); console.log('\n With array ', y); Output: Note: This will not work in normal JavaScript because it requires the library lodash to be installed.Reference: https://lodash.com/docs/4.17.15#castArray sumitgumber28 surinderdawra388 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 38681, "s": 38653, "text": "\n22 Jul, 2021" }, { "code": null, "e": 38765, "s": 38681, "text": "The _.castArray() method is used to cast value into an array if it is not an array." }, { "code": null, "e": 38774, "s": 38765, "text": "Syntax: " }, { "code": null, "e": 38795, "s": 38774, "text": "_.castArray( value )" }, { "code": null, "e": 38886, "s": 38795, "text": "Parameters: This method accepts single parameter as mentioned above and described below: " }, { "code": null, "e": 38949, "s": 38886, "text": "value: This parameter holds the value that need to be inspect." }, { "code": null, "e": 39037, "s": 38949, "text": "Return Value: It returns an array with the including value passed in the _.castArray()." }, { "code": null, "e": 39099, "s": 39037, "text": "Example 1: This example using integer value as a parameter. " }, { "code": null, "e": 39110, "s": 39099, "text": "Javascript" }, { "code": "const _ = require('lodash'); let x = 10; let arr = _.castArray(x); console.log(\"\\n\\nThe value returned to by _castArray(x) is\", arr);", "e": 39244, "s": 39110, "text": null }, { "code": null, "e": 39338, "s": 39244, "text": "Here, const _ = require(‘lodash’) is used to import the lodash library into the file.Output: " }, { "code": null, "e": 39414, "s": 39338, "text": "Example 2: This example using String, null, and undefined as a parameter. " }, { "code": null, "e": 39425, "s": 39414, "text": "Javascript" }, { "code": "const _ = require('lodash'); let x = _.castArray('abc'); console.log('\\n With String ', x ); let y = _.castArray(null); console.log('\\n With null ', y ); let z = _.castArray(undefined); console.log('\\n With undefined ', z);", "e": 39651, "s": 39425, "text": null }, { "code": null, "e": 39660, "s": 39651, "text": "Output: " }, { "code": null, "e": 39713, "s": 39660, "text": "Example 3: With no parameter, object, and function. " }, { "code": null, "e": 39724, "s": 39713, "text": "Javascript" }, { "code": "const _ = require('lodash'); let x = _.castArray(); console.log(\"\\n With no parameter \", x); let y = _.castArray({\"name\":\"lodash\", \"work\":\"I'm make js more\" }); console.log(\"\\n With object \", y); let z = _.castArray(function hello() { console.log(\"hello\");}); console.log(\"\\n with function \", z);", "e": 40032, "s": 39724, "text": null }, { "code": null, "e": 40041, "s": 40032, "text": "Output: " }, { "code": null, "e": 40186, "s": 40041, "text": "Example 4: This example using multiple parameters, it will take only the first parameter and with an array, it will just return the same array. " }, { "code": null, "e": 40197, "s": 40186, "text": "Javascript" }, { "code": "const _ = require('lodash'); let x = _.castArray(1, 2, \"hello\"); console.log('\\n With multiple parameter ', x); let y = _.castArray([1, 2, 3]); console.log('\\n With array ', y);", "e": 40375, "s": 40197, "text": null }, { "code": null, "e": 40384, "s": 40375, "text": "Output: " }, { "code": null, "e": 40539, "s": 40384, "text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed.Reference: https://lodash.com/docs/4.17.15#castArray " }, { "code": null, "e": 40553, "s": 40539, "text": "sumitgumber28" }, { "code": null, "e": 40570, "s": 40553, "text": "surinderdawra388" }, { "code": null, "e": 40588, "s": 40570, "text": "JavaScript-Lodash" }, { "code": null, "e": 40599, "s": 40588, "text": "JavaScript" }, { "code": null, "e": 40616, "s": 40599, "text": "Web Technologies" }, { "code": null, "e": 40714, "s": 40616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40754, "s": 40714, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40799, "s": 40754, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40860, "s": 40799, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40932, "s": 40860, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41001, "s": 40932, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 41041, "s": 41001, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41074, "s": 41041, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41119, "s": 41074, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41162, "s": 41119, "text": "How to fetch data from an API in ReactJS ?" } ]
Commit & RollBack Operation in Python - GeeksforGeeks
08 Oct, 2021 Python’s commit() method and rollback() method are among the various methods used for making database transactions. Database transactions are necessary as they ensure the atomicity, consistency, isolation and durability of the database.In this article, we will focus on the use of commit() and rollback() method in detail. 1. The commit() method: The commit() method is used to make sure the changes made to the database are consistent. It basically provides the database confirmation regarding the changes made by a user or an application in the database. Syntax: comm.commit() #comm refers to the database connection object For a better understanding of the concept look into the code below followed by the code explanation. The below demonstration of the commit() method is performed on a MySQL database. Example: Program to update the age of a student named Rishi Kumar and commit it to the database.MySQL Table in use: Python3 # Python program to demonstrate# commit() method import mysql.connector # Connecting to the Databasemydb = mysql.connector.connect(host ='localhost',database ='College',user ='root',) cs = mydb.cursor() # drop clausestatement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'" cs.execute(statement) # commit changes to the databasemydb.commit() # Disconnecting from the databasemydb.close() Output: 2. The rollback() method: The rollback() method is used to revert the last changes made to the database. If a condition arises where one is not satisfied with the changes made to the database or a database transaction fails, the rollback() method can be used to retrieve the original data that was changed through the commit() method. Syntax: comm.rollback() #comm refers to the database connection object The below code shows the use of rollback() method to revert changes if a database transaction fails: Python3 # Python program to demonstrate# rollback() method import mysql.connectorfrom mysql.connector import Errorfrom mysql.connector import errorcode try: # Connecting to the Database mydb = mysql.connector.connect( host ='localhost', database ='College', user ='root', ) cs = mydb.cursor() # drop clause statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'" cs.execute(statement) # commit changes to the database mydb.commit() # update successful message print("Database Updated !") except mysql.connector.Error as error : # update failed message as an error print("Database Update Failed !: {}".format(error)) # reverting changes because of exception mydb.rollback() # Disconnecting from the databasemydb.close() Output: If the database transaction is successful the output will be, Database Updated! If the database transaction fails the output is an error raised as, Database Update Failed! akshaysingh98088 anikaseth98 Python-database Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n08 Oct, 2021" }, { "code": null, "e": 25861, "s": 25537, "text": "Python’s commit() method and rollback() method are among the various methods used for making database transactions. Database transactions are necessary as they ensure the atomicity, consistency, isolation and durability of the database.In this article, we will focus on the use of commit() and rollback() method in detail. " }, { "code": null, "e": 25885, "s": 25861, "text": "1. The commit() method:" }, { "code": null, "e": 26095, "s": 25885, "text": "The commit() method is used to make sure the changes made to the database are consistent. It basically provides the database confirmation regarding the changes made by a user or an application in the database." }, { "code": null, "e": 26104, "s": 26095, "text": "Syntax: " }, { "code": null, "e": 26165, "s": 26104, "text": "comm.commit() #comm refers to the database connection object" }, { "code": null, "e": 26347, "s": 26165, "text": "For a better understanding of the concept look into the code below followed by the code explanation. The below demonstration of the commit() method is performed on a MySQL database." }, { "code": null, "e": 26465, "s": 26347, "text": "Example: Program to update the age of a student named Rishi Kumar and commit it to the database.MySQL Table in use: " }, { "code": null, "e": 26473, "s": 26465, "text": "Python3" }, { "code": "# Python program to demonstrate# commit() method import mysql.connector # Connecting to the Databasemydb = mysql.connector.connect(host ='localhost',database ='College',user ='root',) cs = mydb.cursor() # drop clausestatement =\"UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'\" cs.execute(statement) # commit changes to the databasemydb.commit() # Disconnecting from the databasemydb.close()", "e": 26871, "s": 26473, "text": null }, { "code": null, "e": 26880, "s": 26871, "text": "Output: " }, { "code": null, "e": 26906, "s": 26880, "text": "2. The rollback() method:" }, { "code": null, "e": 27215, "s": 26906, "text": "The rollback() method is used to revert the last changes made to the database. If a condition arises where one is not satisfied with the changes made to the database or a database transaction fails, the rollback() method can be used to retrieve the original data that was changed through the commit() method." }, { "code": null, "e": 27225, "s": 27215, "text": "Syntax: " }, { "code": null, "e": 27288, "s": 27225, "text": "comm.rollback() #comm refers to the database connection object" }, { "code": null, "e": 27391, "s": 27288, "text": "The below code shows the use of rollback() method to revert changes if a database transaction fails: " }, { "code": null, "e": 27399, "s": 27391, "text": "Python3" }, { "code": "# Python program to demonstrate# rollback() method import mysql.connectorfrom mysql.connector import Errorfrom mysql.connector import errorcode try: # Connecting to the Database mydb = mysql.connector.connect( host ='localhost', database ='College', user ='root', ) cs = mydb.cursor() # drop clause statement =\"UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'\" cs.execute(statement) # commit changes to the database mydb.commit() # update successful message print(\"Database Updated !\") except mysql.connector.Error as error : # update failed message as an error print(\"Database Update Failed !: {}\".format(error)) # reverting changes because of exception mydb.rollback() # Disconnecting from the databasemydb.close()", "e": 28198, "s": 27399, "text": null }, { "code": null, "e": 28207, "s": 28198, "text": "Output: " }, { "code": null, "e": 28270, "s": 28207, "text": "If the database transaction is successful the output will be, " }, { "code": null, "e": 28288, "s": 28270, "text": "Database Updated!" }, { "code": null, "e": 28358, "s": 28288, "text": "If the database transaction fails the output is an error raised as, " }, { "code": null, "e": 28382, "s": 28358, "text": "Database Update Failed!" }, { "code": null, "e": 28401, "s": 28384, "text": "akshaysingh98088" }, { "code": null, "e": 28413, "s": 28401, "text": "anikaseth98" }, { "code": null, "e": 28429, "s": 28413, "text": "Python-database" }, { "code": null, "e": 28442, "s": 28429, "text": "Python-mySQL" }, { "code": null, "e": 28449, "s": 28442, "text": "Python" }, { "code": null, "e": 28547, "s": 28449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28579, "s": 28547, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28621, "s": 28579, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28663, "s": 28621, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28690, "s": 28663, "text": "Python Classes and Objects" }, { "code": null, "e": 28746, "s": 28690, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28768, "s": 28746, "text": "Defaultdict in Python" }, { "code": null, "e": 28807, "s": 28768, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28838, "s": 28807, "text": "Python | os.path.join() method" }, { "code": null, "e": 28867, "s": 28838, "text": "Create a directory in Python" } ]
Rearrange given binary strings to maximize their Bitwise XOR value - GeeksforGeeks
15 Jun, 2021 Given three binary strings S1, S2, and S3 each of length N, the task is to find the maximum possible Bitwise XOR that can be obtained by rearranging the characters of the given strings. Examples: Input: S1 = “1001”, S2 = “0010”, S3 = “1110”Output: 15Explanation:Rearrange the digits of S1 as “1010”, S2 as “1000” and S3 as “1101”.The XOR of these strings is “1111” which is 15 in decimal form. Input: S1 = “11111”, S2 = “11111”, S3 = “11111” Output: 31Explanation:There is no other way to arrange the digits. Hence, XOR is “11111” which is 31 in decimal form. Naive Approach: The simplest approach is to generate all possible ways to rearrange S1, S2, and S3. Suppose there are O1, O2 and O3 set bits in the strings S1, S2, and S3 respectively. The total number of rearrangements to check to get the maximum Bitwise XOR value is as follows: Total ways to rearrange S1 = NCO1 Total ways to rearrange S2 = NCO2 Total ways to rearrange S3 = NCO3 Hence, total possible rearrangements to check = NCO1*NCO2 * NCO3 Time Complexity: O((N!)3), where N is the length of the given strings.Auxiliary Space: O(N) Efficient Approach: The idea is to find a suitable rearrangement of S1, S2, and S3 such that their Bitwise XOR value is maximized using Dynamic Programming. The subproblems can be stored in a dp[][][][] table where dp[i][o1][o2][o3] stores the maximum XOR value up to position N-1 starting from the index i, where o1 is, o2 and o3 are the number of 1s still remaining to be placed in strings S1, S2 and S3 respectively. There can be four cases possible at any position i from 0 to (N – 1): Assign 1s to all the three stringsAssign 1s to any two stringsAssign 1s to any one of the strings.Assign 0s to all the strings. Assign 1s to all the three strings Assign 1s to any two strings Assign 1s to any one of the strings. Assign 0s to all the strings. From the above possible cases for each position, calculate the maximum Bitwise XOR obtainable from the four possibilities: Follow the steps below to solve the problem: Initialize a table dp[][][][] to store the number of ones in S1, S2 and S3 for the positions i from 0 to N-1. The transition states is as follows: dp[i][o1][o2][o3] = max(dp(assign 1s to all three strings), dp(assign 1s to any of the two strings), dp(assign 1s to any one string), dp(do not assign 1 to any string)) where, i = current positiono1 = remaining ones to be placed in the string S1o2 = remaining ones to be placed in the string S2o3 = remaining ones to be placed in the string S3 Solve the subproblems for all cases using the above transition and print the maximum XOR value amongst them. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Dp table to store the sub-problemsint dp[20][20][20][20]; // Function to find the maximum XOR// value after rearranging the digitsint maxXorValue(int i, string& s1, string& s2, string& s3, int ones1, int ones2, int ones3, int n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i][ones1][ones2][ones3] != -1) return dp[i][ones1][ones2][ones3]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all string at // position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i][ones1][ones2][ones3] = max(option1, max(option2, max(option3, max(option4, max(option5, max(option6, max(option7, option8)))))));} // Function to get the count of ones// in the string sint onesCount(string& s){ int count = 0; // Traverse the string for (auto x : s) { if (x == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsvoid maxXORUtil(string s1, string s2, string s3, int n){ // Find the count of ones in // each of the strings int ones1 = onesCount(s1); int ones2 = onesCount(s2); int ones3 = onesCount(s3); // Initialize dp table with -1 memset(dp, -1, sizeof dp); // Function Call cout << maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n);} // Driver codeint main(){ string s1 = "11110"; string s2 = "10101"; string s3 = "00111"; int n = s1.size(); // Function Call maxXORUtil(s1, s2, s3, n); return 0;} // Java program for the above approachimport java.util.*;import java.lang.*;class GFG{ // Dp table to store the sub-problemsstatic int[][][][] dp = new int[20][20][20][20]; // Function to find the maximum XOR// value after rearranging the digitsstatic int maxXorValue(int i, String s1, String s2, String s3, int ones1, int ones2, int ones3, int n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i][ones1][ones2][ones3] != -1) return dp[i][ones1][ones2][ones3]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all string at // position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i][ones1][ones2][ones3] = Math.max(option1, Math.max(option2, Math.max(option3, Math.max(option4, Math.max(option5, Math.max(option6, Math.max(option7, option8)))))));} // Function to get the count of ones// in the string sstatic int onesCount(String s){ int count = 0; // Traverse the string for(char x : s.toCharArray()) { if (x == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsstatic void maxXORUtil(String s1, String s2, String s3, int n){ // Find the count of ones in // each of the strings int ones1 = onesCount(s1); int ones2 = onesCount(s2); int ones3 = onesCount(s3); // Initialize dp table with -1 for(int[][][] i : dp) for(int[][] j : i) for(int[] k : j) Arrays.fill(k, -1); // Function Call System.out.println(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n));} // Driver codepublic static void main (String[] args){ String s1 = "11110"; String s2 = "10101"; String s3 = "00111"; int n = s1.length(); // Function call maxXORUtil(s1, s2, s3, n);}} // This code is contributed by offbeat # Python3 program for the# above approach # Dp table to store the# sub-problemsdp = [[[[-1 for x in range(20)] for y in range(20)] for z in range(20)] for p in range(20)] # Function to find the maximum# XOR value after rearranging# the digitsdef maxXorValue(i, s1, s2, s3, ones1, ones2, ones3, n): # Base Case if (i >= n): return 0 # Return if already #calculated if (dp[i][ones1][ones2][ones3] != -1): return dp[i][ones1][ones2][ones3] option1 = 0 option2 = 0 option3 = 0 option4 = 0 option5 = 0 option6 = 0 option7 = 0 option8 = 0 # Assigning 1's to all # string at position 'i'. if (ones1 > 0 and ones2 > 0 and ones3 > 0): # 2^(n-1-i) is the value # added to the total option1 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n)) # Assigning 1's to strings # 1 & 2 if (ones1 > 0 and ones2 > 0 and (n - i > ones3)): option2 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n)) # Assigning 1's to strings # 2 & 3 if (ones2 > 0 and ones3 > 0 and (n - i > ones1)): option3 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n)) # Assigning 1's to strings # 3 & 1 if (ones3 > 0 and ones1 > 0 and (n - i > ones2)): option4 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n)) # Assigning 1 to string 1 if (ones1 > 0 and (n - i > ones2) and (n - i > ones3)): option5 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n)) # Assigning 1 to string 2 if (ones2 > 0 and (n - i > ones3) and (n - i > ones1)): option6 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n)) # Assigning 1 to string 3. if (ones3 > 0 and (n - i > ones2) and (n - i > ones1)): option7 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n)) # Assigning 0 to all the strings if ((n - i > ones2) and (n - i > ones3) and (n - i > ones1)): option8 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n)) # Take the maximum amongst all of # the above solutions dp[i][ones1][ones2][ones3] = max(option1, max(option2, max(option3, max(option4, max(option5, max(option6, max(option7, option8))))))) return dp[i][ones1][ones2][ones3] # Function to get the count# of ones in the string sdef onesCount(s): count = 0 # Traverse the string for x in s: if (x == '1'): count += 1 # Return the count return count # Utility Function to find# the maximum XOR value after# rearranging the digitsdef maxXORUtil(s1, s2, s3, n): # Find the count of ones in # each of the strings ones1 = onesCount(s1) ones2 = onesCount(s2) ones3 = onesCount(s3) global dp # Function Call print(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n)) # Driver codeif __name__ == "__main__": s1 = "11110" s2 = "10101" s3 = "00111" n = len(s1) # Function Call maxXORUtil(s1, s2, s3, n) # This code is contributed by Chitranayal // C# program for the// above approachusing System;class GFG{ // Dp table to store// the sub-problemsstatic int[,,,] dp = new int[20, 20, 20, 20]; // Function to find the// maximum XOR value after// rearranging the digitsstatic int maxXorValue(int i, String s1, String s2, String s3, int ones1, int ones2, int ones3, int n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i, ones1, ones2, ones3] != -1) return dp[i, ones1, ones2, ones3]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all // string at position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to // strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2,s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i, ones1, ones2, ones3] = Math.Max(option1, Math.Max(option2, Math.Max(option3, Math.Max(option4, Math.Max(option5, Math.Max(option6, Math.Max(option7, option8)))))));} // Function to get the count// of ones in the string sstatic int onesCount(String s){ int count = 0; // Traverse the string foreach(char x in s.ToCharArray()) { if (x == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsstatic void maxXORUtil(String s1, String s2, String s3, int n){ // Find the count of ones in // each of the strings int ones1 = onesCount(s1); int ones2 = onesCount(s2); int ones3 = onesCount(s3); // Initialize dp table with -1 for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { for(int l = 0; l < 20; l++) for(int k = 0; k < 20; k++) dp[i, j, l, k] =- 1; } } // Function Call Console.WriteLine(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n));} // Driver codepublic static void Main(String[] args){ String s1 = "11110"; String s2 = "10101"; String s3 = "00111"; int n = s1.Length; // Function call maxXORUtil(s1, s2, s3, n);}} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Dp table to store the sub-problemslet dp = new Array(20);for(let i = 0; i < 20; i++){ dp[i] = new Array(20); for(let j = 0; j < 20; j++) { dp[i][j] = new Array(20); for(let k = 0; k < 20; k++) { dp[i][j][k] = new Array(20); for(let l = 0; l < 20; l++) { dp[i][j][k][l] = -1; } } }} // Function to find the maximum XOR// value after rearranging the digitsfunction maxXorValue(i, s1, s2, s3, ones1, ones2, ones3, n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i][ones1][ones2][ones3] != -1) return dp[i][ones1][ones2][ones3]; let option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all string at // position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i][ones1][ones2][ones3] = Math.max(option1, Math.max(option2, Math.max(option3, Math.max(option4, Math.max(option5, Math.max(option6, Math.max(option7, option8)))))));} // Function to get the count of ones// in the string sfunction onesCount(s){ let count = 0; // Traverse the string for(let x = 0; x < s.length; x++) { if (s[x] == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsfunction maxXORUtil(s1, s2, s3, n){ // Find the count of ones in // each of the strings let ones1 = onesCount(s1); let ones2 = onesCount(s2); let ones3 = onesCount(s3); // Function Call document.write(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n));} // Driver codelet s1 = "11110";let s2 = "10101";let s3 = "00111";let n = s1.length; // Function callmaxXORUtil(s1, s2, s3, n); // This code is contributed by avanitrachhadiya2155 </script> 30 Time Complexity: O(N4)Auxiliary Space: O(N) offbeat 29AjayKumar ukasp avanitrachhadiya2155 binary-string Bitwise-XOR Permutation and Combination Bit Magic Combinatorial Dynamic Programming Mathematical Strings Strings Dynamic Programming Mathematical Bit Magic Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Binary representation of a given number Add two numbers without using arithmetic operators Josephus problem | Set 1 (A O(n) Solution) Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number itertools.combinations() module in Python to print all possible combinations
[ { "code": null, "e": 26643, "s": 26615, "text": "\n15 Jun, 2021" }, { "code": null, "e": 26829, "s": 26643, "text": "Given three binary strings S1, S2, and S3 each of length N, the task is to find the maximum possible Bitwise XOR that can be obtained by rearranging the characters of the given strings." }, { "code": null, "e": 26839, "s": 26829, "text": "Examples:" }, { "code": null, "e": 27037, "s": 26839, "text": "Input: S1 = “1001”, S2 = “0010”, S3 = “1110”Output: 15Explanation:Rearrange the digits of S1 as “1010”, S2 as “1000” and S3 as “1101”.The XOR of these strings is “1111” which is 15 in decimal form." }, { "code": null, "e": 27204, "s": 27037, "text": "Input: S1 = “11111”, S2 = “11111”, S3 = “11111” Output: 31Explanation:There is no other way to arrange the digits. Hence, XOR is “11111” which is 31 in decimal form. " }, { "code": null, "e": 27485, "s": 27204, "text": "Naive Approach: The simplest approach is to generate all possible ways to rearrange S1, S2, and S3. Suppose there are O1, O2 and O3 set bits in the strings S1, S2, and S3 respectively. The total number of rearrangements to check to get the maximum Bitwise XOR value is as follows:" }, { "code": null, "e": 27591, "s": 27485, "text": "Total ways to rearrange S1 = NCO1 Total ways to rearrange S2 = NCO2 Total ways to rearrange S3 = NCO3 " }, { "code": null, "e": 27656, "s": 27591, "text": "Hence, total possible rearrangements to check = NCO1*NCO2 * NCO3" }, { "code": null, "e": 27748, "s": 27656, "text": "Time Complexity: O((N!)3), where N is the length of the given strings.Auxiliary Space: O(N)" }, { "code": null, "e": 28168, "s": 27748, "text": "Efficient Approach: The idea is to find a suitable rearrangement of S1, S2, and S3 such that their Bitwise XOR value is maximized using Dynamic Programming. The subproblems can be stored in a dp[][][][] table where dp[i][o1][o2][o3] stores the maximum XOR value up to position N-1 starting from the index i, where o1 is, o2 and o3 are the number of 1s still remaining to be placed in strings S1, S2 and S3 respectively." }, { "code": null, "e": 28238, "s": 28168, "text": "There can be four cases possible at any position i from 0 to (N – 1):" }, { "code": null, "e": 28366, "s": 28238, "text": "Assign 1s to all the three stringsAssign 1s to any two stringsAssign 1s to any one of the strings.Assign 0s to all the strings." }, { "code": null, "e": 28401, "s": 28366, "text": "Assign 1s to all the three strings" }, { "code": null, "e": 28430, "s": 28401, "text": "Assign 1s to any two strings" }, { "code": null, "e": 28467, "s": 28430, "text": "Assign 1s to any one of the strings." }, { "code": null, "e": 28497, "s": 28467, "text": "Assign 0s to all the strings." }, { "code": null, "e": 28620, "s": 28497, "text": "From the above possible cases for each position, calculate the maximum Bitwise XOR obtainable from the four possibilities:" }, { "code": null, "e": 28665, "s": 28620, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 28775, "s": 28665, "text": "Initialize a table dp[][][][] to store the number of ones in S1, S2 and S3 for the positions i from 0 to N-1." }, { "code": null, "e": 28812, "s": 28775, "text": "The transition states is as follows:" }, { "code": null, "e": 28988, "s": 28812, "text": "dp[i][o1][o2][o3] = max(dp(assign 1s to all three strings), dp(assign 1s to any of the two strings), dp(assign 1s to any one string), dp(do not assign 1 to any string)) where," }, { "code": null, "e": 29156, "s": 28988, "text": "i = current positiono1 = remaining ones to be placed in the string S1o2 = remaining ones to be placed in the string S2o3 = remaining ones to be placed in the string S3" }, { "code": null, "e": 29265, "s": 29156, "text": "Solve the subproblems for all cases using the above transition and print the maximum XOR value amongst them." }, { "code": null, "e": 29316, "s": 29265, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29320, "s": 29316, "text": "C++" }, { "code": null, "e": 29325, "s": 29320, "text": "Java" }, { "code": null, "e": 29333, "s": 29325, "text": "Python3" }, { "code": null, "e": 29336, "s": 29333, "text": "C#" }, { "code": null, "e": 29347, "s": 29336, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Dp table to store the sub-problemsint dp[20][20][20][20]; // Function to find the maximum XOR// value after rearranging the digitsint maxXorValue(int i, string& s1, string& s2, string& s3, int ones1, int ones2, int ones3, int n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i][ones1][ones2][ones3] != -1) return dp[i][ones1][ones2][ones3]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all string at // position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i][ones1][ones2][ones3] = max(option1, max(option2, max(option3, max(option4, max(option5, max(option6, max(option7, option8)))))));} // Function to get the count of ones// in the string sint onesCount(string& s){ int count = 0; // Traverse the string for (auto x : s) { if (x == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsvoid maxXORUtil(string s1, string s2, string s3, int n){ // Find the count of ones in // each of the strings int ones1 = onesCount(s1); int ones2 = onesCount(s2); int ones3 = onesCount(s3); // Initialize dp table with -1 memset(dp, -1, sizeof dp); // Function Call cout << maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n);} // Driver codeint main(){ string s1 = \"11110\"; string s2 = \"10101\"; string s3 = \"00111\"; int n = s1.size(); // Function Call maxXORUtil(s1, s2, s3, n); return 0;}", "e": 33917, "s": 29347, "text": null }, { "code": "// Java program for the above approachimport java.util.*;import java.lang.*;class GFG{ // Dp table to store the sub-problemsstatic int[][][][] dp = new int[20][20][20][20]; // Function to find the maximum XOR// value after rearranging the digitsstatic int maxXorValue(int i, String s1, String s2, String s3, int ones1, int ones2, int ones3, int n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i][ones1][ones2][ones3] != -1) return dp[i][ones1][ones2][ones3]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all string at // position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i][ones1][ones2][ones3] = Math.max(option1, Math.max(option2, Math.max(option3, Math.max(option4, Math.max(option5, Math.max(option6, Math.max(option7, option8)))))));} // Function to get the count of ones// in the string sstatic int onesCount(String s){ int count = 0; // Traverse the string for(char x : s.toCharArray()) { if (x == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsstatic void maxXORUtil(String s1, String s2, String s3, int n){ // Find the count of ones in // each of the strings int ones1 = onesCount(s1); int ones2 = onesCount(s2); int ones3 = onesCount(s3); // Initialize dp table with -1 for(int[][][] i : dp) for(int[][] j : i) for(int[] k : j) Arrays.fill(k, -1); // Function Call System.out.println(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n));} // Driver codepublic static void main (String[] args){ String s1 = \"11110\"; String s2 = \"10101\"; String s3 = \"00111\"; int n = s1.length(); // Function call maxXORUtil(s1, s2, s3, n);}} // This code is contributed by offbeat", "e": 38607, "s": 33917, "text": null }, { "code": "# Python3 program for the# above approach # Dp table to store the# sub-problemsdp = [[[[-1 for x in range(20)] for y in range(20)] for z in range(20)] for p in range(20)] # Function to find the maximum# XOR value after rearranging# the digitsdef maxXorValue(i, s1, s2, s3, ones1, ones2, ones3, n): # Base Case if (i >= n): return 0 # Return if already #calculated if (dp[i][ones1][ones2][ones3] != -1): return dp[i][ones1][ones2][ones3] option1 = 0 option2 = 0 option3 = 0 option4 = 0 option5 = 0 option6 = 0 option7 = 0 option8 = 0 # Assigning 1's to all # string at position 'i'. if (ones1 > 0 and ones2 > 0 and ones3 > 0): # 2^(n-1-i) is the value # added to the total option1 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n)) # Assigning 1's to strings # 1 & 2 if (ones1 > 0 and ones2 > 0 and (n - i > ones3)): option2 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n)) # Assigning 1's to strings # 2 & 3 if (ones2 > 0 and ones3 > 0 and (n - i > ones1)): option3 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n)) # Assigning 1's to strings # 3 & 1 if (ones3 > 0 and ones1 > 0 and (n - i > ones2)): option4 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n)) # Assigning 1 to string 1 if (ones1 > 0 and (n - i > ones2) and (n - i > ones3)): option5 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n)) # Assigning 1 to string 2 if (ones2 > 0 and (n - i > ones3) and (n - i > ones1)): option6 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n)) # Assigning 1 to string 3. if (ones3 > 0 and (n - i > ones2) and (n - i > ones1)): option7 = ((1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n)) # Assigning 0 to all the strings if ((n - i > ones2) and (n - i > ones3) and (n - i > ones1)): option8 = (0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n)) # Take the maximum amongst all of # the above solutions dp[i][ones1][ones2][ones3] = max(option1, max(option2, max(option3, max(option4, max(option5, max(option6, max(option7, option8))))))) return dp[i][ones1][ones2][ones3] # Function to get the count# of ones in the string sdef onesCount(s): count = 0 # Traverse the string for x in s: if (x == '1'): count += 1 # Return the count return count # Utility Function to find# the maximum XOR value after# rearranging the digitsdef maxXORUtil(s1, s2, s3, n): # Find the count of ones in # each of the strings ones1 = onesCount(s1) ones2 = onesCount(s2) ones3 = onesCount(s3) global dp # Function Call print(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n)) # Driver codeif __name__ == \"__main__\": s1 = \"11110\" s2 = \"10101\" s3 = \"00111\" n = len(s1) # Function Call maxXORUtil(s1, s2, s3, n) # This code is contributed by Chitranayal", "e": 43231, "s": 38607, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Dp table to store// the sub-problemsstatic int[,,,] dp = new int[20, 20, 20, 20]; // Function to find the// maximum XOR value after// rearranging the digitsstatic int maxXorValue(int i, String s1, String s2, String s3, int ones1, int ones2, int ones3, int n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i, ones1, ones2, ones3] != -1) return dp[i, ones1, ones2, ones3]; int option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all // string at position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to // strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2,s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i, ones1, ones2, ones3] = Math.Max(option1, Math.Max(option2, Math.Max(option3, Math.Max(option4, Math.Max(option5, Math.Max(option6, Math.Max(option7, option8)))))));} // Function to get the count// of ones in the string sstatic int onesCount(String s){ int count = 0; // Traverse the string foreach(char x in s.ToCharArray()) { if (x == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsstatic void maxXORUtil(String s1, String s2, String s3, int n){ // Find the count of ones in // each of the strings int ones1 = onesCount(s1); int ones2 = onesCount(s2); int ones3 = onesCount(s3); // Initialize dp table with -1 for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { for(int l = 0; l < 20; l++) for(int k = 0; k < 20; k++) dp[i, j, l, k] =- 1; } } // Function Call Console.WriteLine(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n));} // Driver codepublic static void Main(String[] args){ String s1 = \"11110\"; String s2 = \"10101\"; String s3 = \"00111\"; int n = s1.Length; // Function call maxXORUtil(s1, s2, s3, n);}} // This code is contributed by 29AjayKumar", "e": 47820, "s": 43231, "text": null }, { "code": "<script> // Javascript program for the above approach // Dp table to store the sub-problemslet dp = new Array(20);for(let i = 0; i < 20; i++){ dp[i] = new Array(20); for(let j = 0; j < 20; j++) { dp[i][j] = new Array(20); for(let k = 0; k < 20; k++) { dp[i][j][k] = new Array(20); for(let l = 0; l < 20; l++) { dp[i][j][k][l] = -1; } } }} // Function to find the maximum XOR// value after rearranging the digitsfunction maxXorValue(i, s1, s2, s3, ones1, ones2, ones3, n){ // Base Case if (i >= n) return 0; // Return if already calculated if (dp[i][ones1][ones2][ones3] != -1) return dp[i][ones1][ones2][ones3]; let option1 = 0, option2 = 0, option3 = 0, option4 = 0, option5 = 0, option6 = 0, option7 = 0, option8 = 0; // Assigning 1's to all string at // position 'i'. if (ones1 > 0 && ones2 > 0 && ones3 > 0) // 2^(n-1-i) is the value // added to the total option1 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 1 & 2 if (ones1 > 0 && ones2 > 0 && (n - i > ones3)) option2 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2 - 1, ones3, n); // Assigning 1's to strings 2 & 3 if (ones2 > 0 && ones3 > 0 && (n - i > ones1)) option3 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3 - 1, n); // Assigning 1's to strings 3 & 1 if (ones3 > 0 && ones1 > 0 && (n - i > ones2)) option4 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3 - 1, n); // Assigning 1 to string 1 if (ones1 > 0 && (n - i > ones2) && (n - i > ones3)) option5 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1 - 1, ones2, ones3, n); // Assigning 1 to string 2 if (ones2 > 0 && (n - i > ones3) && (n - i > ones1)) option6 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2 - 1, ones3, n); // Assigning 1 to string 3. if (ones3 > 0 && (n - i > ones2) && (n - i > ones1)) option7 = (1 << ((n - 1) - i)) + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3 - 1, n); // Assigning 0 to all the strings if ((n - i > ones2) && (n - i > ones3) && (n - i > ones1)) option8 = 0 + maxXorValue(i + 1, s1, s2, s3, ones1, ones2, ones3, n); // Take the maximum amongst all of // the above solutions return dp[i][ones1][ones2][ones3] = Math.max(option1, Math.max(option2, Math.max(option3, Math.max(option4, Math.max(option5, Math.max(option6, Math.max(option7, option8)))))));} // Function to get the count of ones// in the string sfunction onesCount(s){ let count = 0; // Traverse the string for(let x = 0; x < s.length; x++) { if (s[x] == '1') ++count; } // Return the count return count;} // Utility Function to find the maximum// XOR value after rearranging the digitsfunction maxXORUtil(s1, s2, s3, n){ // Find the count of ones in // each of the strings let ones1 = onesCount(s1); let ones2 = onesCount(s2); let ones3 = onesCount(s3); // Function Call document.write(maxXorValue(0, s1, s2, s3, ones1, ones2, ones3, n));} // Driver codelet s1 = \"11110\";let s2 = \"10101\";let s3 = \"00111\";let n = s1.length; // Function callmaxXORUtil(s1, s2, s3, n); // This code is contributed by avanitrachhadiya2155 </script>", "e": 52420, "s": 47820, "text": null }, { "code": null, "e": 52423, "s": 52420, "text": "30" }, { "code": null, "e": 52467, "s": 52423, "text": "Time Complexity: O(N4)Auxiliary Space: O(N)" }, { "code": null, "e": 52475, "s": 52467, "text": "offbeat" }, { "code": null, "e": 52487, "s": 52475, "text": "29AjayKumar" }, { "code": null, "e": 52493, "s": 52487, "text": "ukasp" }, { "code": null, "e": 52514, "s": 52493, "text": "avanitrachhadiya2155" }, { "code": null, "e": 52528, "s": 52514, "text": "binary-string" }, { "code": null, "e": 52540, "s": 52528, "text": "Bitwise-XOR" }, { "code": null, "e": 52568, "s": 52540, "text": "Permutation and Combination" }, { "code": null, "e": 52578, "s": 52568, "text": "Bit Magic" }, { "code": null, "e": 52592, "s": 52578, "text": "Combinatorial" }, { "code": null, "e": 52612, "s": 52592, "text": "Dynamic Programming" }, { "code": null, "e": 52625, "s": 52612, "text": "Mathematical" }, { "code": null, "e": 52633, "s": 52625, "text": "Strings" }, { "code": null, "e": 52641, "s": 52633, "text": "Strings" }, { "code": null, "e": 52661, "s": 52641, "text": "Dynamic Programming" }, { "code": null, "e": 52674, "s": 52661, "text": "Mathematical" }, { "code": null, "e": 52684, "s": 52674, "text": "Bit Magic" }, { "code": null, "e": 52698, "s": 52684, "text": "Combinatorial" }, { "code": null, "e": 52796, "s": 52698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52826, "s": 52796, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 52872, "s": 52826, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 52912, "s": 52872, "text": "Binary representation of a given number" }, { "code": null, "e": 52963, "s": 52912, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 53006, "s": 52963, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 53066, "s": 53006, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 53104, "s": 53066, "text": "Permutation and Combination in Python" }, { "code": null, "e": 53132, "s": 53104, "text": "Factorial of a large number" } ]
How to pop an alert message box using PHP ? - GeeksforGeeks
17 Nov, 2021 An alert box is used in the website to display a warning message to the user that they have entered the wrong value other than what is required to fill in that position. An alert box can still be used for friendlier messages. The alert box gives only one button “OK” to select and proceed. The alert message just like a pop-up window on the screen. Using this you can alert to the user with some information and message. PHP doesn’t support alert message box because it is a server-side language but you can use JavaScript code within the PHP body to alert the message box on the screen. Syntax: alert("Message") Program 1: PHP program to pop up an alert box on the screen. PHP <?php// PHP program to pop an alert// message box on the screen // Display the alert box echo '<script>alert("Welcome to Geeks for Geeks")</script>'; ?> Output: Program 2: PHP program to pop up an alert box on the screen. PHP <?php// PHP program to pop an alert// message box on the screen // Function definitionfunction function_alert($message) { // Display the alert box echo "<script>alert('$message');</script>";} // Function callfunction_alert("Welcome to Geeks for Geeks"); ?> Output: 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. gulshankumarar231 Picked 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. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP Download file from URL using PHP How to convert array to string in PHP ? How to pass JavaScript variables to PHP ? Split a comma delimited string into an array in PHP How to get parameters from a URL string in PHP? How to declare a global variable in PHP?
[ { "code": null, "e": 26050, "s": 26022, "text": "\n17 Nov, 2021" }, { "code": null, "e": 26341, "s": 26050, "text": "An alert box is used in the website to display a warning message to the user that they have entered the wrong value other than what is required to fill in that position. An alert box can still be used for friendlier messages. The alert box gives only one button “OK” to select and proceed. " }, { "code": null, "e": 26639, "s": 26341, "text": "The alert message just like a pop-up window on the screen. Using this you can alert to the user with some information and message. PHP doesn’t support alert message box because it is a server-side language but you can use JavaScript code within the PHP body to alert the message box on the screen." }, { "code": null, "e": 26648, "s": 26639, "text": "Syntax: " }, { "code": null, "e": 26665, "s": 26648, "text": "alert(\"Message\")" }, { "code": null, "e": 26728, "s": 26665, "text": "Program 1: PHP program to pop up an alert box on the screen. " }, { "code": null, "e": 26732, "s": 26728, "text": "PHP" }, { "code": "<?php// PHP program to pop an alert// message box on the screen // Display the alert box echo '<script>alert(\"Welcome to Geeks for Geeks\")</script>'; ?>", "e": 26887, "s": 26732, "text": null }, { "code": null, "e": 26896, "s": 26887, "text": "Output: " }, { "code": null, "e": 26959, "s": 26896, "text": "Program 2: PHP program to pop up an alert box on the screen. " }, { "code": null, "e": 26963, "s": 26959, "text": "PHP" }, { "code": "<?php// PHP program to pop an alert// message box on the screen // Function definitionfunction function_alert($message) { // Display the alert box echo \"<script>alert('$message');</script>\";} // Function callfunction_alert(\"Welcome to Geeks for Geeks\"); ?>", "e": 27238, "s": 26963, "text": null }, { "code": null, "e": 27247, "s": 27238, "text": "Output: " }, { "code": null, "e": 27418, "s": 27249, "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": 27436, "s": 27418, "text": "gulshankumarar231" }, { "code": null, "e": 27443, "s": 27436, "text": "Picked" }, { "code": null, "e": 27447, "s": 27443, "text": "PHP" }, { "code": null, "e": 27460, "s": 27447, "text": "PHP Programs" }, { "code": null, "e": 27477, "s": 27460, "text": "Web Technologies" }, { "code": null, "e": 27504, "s": 27477, "text": "Web technologies Questions" }, { "code": null, "e": 27508, "s": 27504, "text": "PHP" }, { "code": null, "e": 27606, "s": 27508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27646, "s": 27606, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27691, "s": 27646, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27733, "s": 27691, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27785, "s": 27733, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 27818, "s": 27785, "text": "Download file from URL using PHP" }, { "code": null, "e": 27858, "s": 27818, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27900, "s": 27858, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 27952, "s": 27900, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 28000, "s": 27952, "text": "How to get parameters from a URL string in PHP?" } ]
Program to check if an array is sorted or not (Iterative and Recursive) - GeeksforGeeks
09 Jun, 2021 Given an array of size n, write a program to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted. Examples: Input : 20 21 45 89 89 90 Output : Yes Input : 20 20 45 89 89 90 Output : Yes Input : 20 20 78 98 99 97 Output : No Recursive approach:The basic idea for the recursive approach: 1: If size of array is zero or one, return true. 2: Check last two elements of array, if they are sorted, perform a recursive call with n-1 else, return false. If all the elements will be found sorted, n will eventually fall to one, satisfying Step 1. Below is the implementation using recursion: C++ Java Python3 C# Javascript // Recursive approach to check if an// Array is sorted or not#include <bits/stdc++.h>using namespace std; // Function that returns 0 if a pair// is found unsortedint arraySortedOrNot(int arr[], int n){ // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1);} // Driver codeint main(){ int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = sizeof(arr) / sizeof(arr[0]); if (arraySortedOrNot(arr, n)) cout << "Yes\n"; else cout << "No\n";} // Recursive approach to check if an// Array is sorted or not class CkeckSorted { // Function that returns 0 if a pair // is found unsorted static int arraySortedOrNot(int arr[], int n) { // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1); } // main function public static void main(String[] args) { int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = arr.length; if (arraySortedOrNot(arr, n) != 0) System.out.println("Yes"); else System.out.println("No"); }} # Recursive approach to check if an# Array is sorted or not # Function that returns 0 if a pair# is found unsorted def arraySortedOrNot(arr): # Calculating length n = len(arr) # Array has one or no element or the # rest are already checked and approved. if n == 1 or n == 0: return True # Recursion applied till last element return arr[0] <= arr[1] and arraySortedOrNot(arr[1:]) arr = [20, 23, 23, 45, 78, 88] # Displaying resultif arraySortedOrNot(arr): print("Yes")else: print("No") // Recursive approach to check if an// Array is sorted or notusing System; class CkeckSorted { // Function that returns 0 if a pair // is found unsorted static int arraySortedOrNot(int[] arr, int n) { // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1); } // Driver Code public static void Main(String[] args) { int[] arr = { 20, 23, 23, 45, 78, 88 }; int n = arr.Length; if (arraySortedOrNot(arr, n) != 0) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by 29AjayKumar <script> // Recursive approach to check if an// Array is sorted or not // Function that returns 0 if a pair// is found unsortedfunction arraySortedOrNot(arr, n){ // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1);} // Driver codelet arr = [ 20, 23, 23, 45, 78, 88 ];let n = arr.length; if (arraySortedOrNot(arr, n) != 0) document.write("Yes");else document.write("No"); // This code is contributed by sravan kumar G </script> Output: Yes Time Complexity: O(n) Auxiliary Space: O(n) for Recursion Call Stack. Another Recursive approach: C++ Java Python3 C# Javascript // C++ Recursive approach to check if an// Array is sorted or not#include <iostream>using namespace std; // Function that returns true if array is// sorted in non-decreasing order.bool arraySortedOrNot(int a[], int n){ // Base case if (n == 1 || n == 0) { return true; } // Check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1);} // Driver codeint main(){ int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call if (arraySortedOrNot(arr, n)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0;} // This code is contributed by avanitrachhadiya2155 // Java Recursive approach to check if an// Array is sorted or notclass GFG { // Function that returns true if array is // sorted in non-decreasing order. static boolean arraySortedOrNot(int a[], int n) { // base case if (n == 1 || n == 0) return true; // check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1); } // Driver code public static void main(String[] args) { int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = arr.length; // Function Call if (arraySortedOrNot(arr, n)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Durgesh N. Birmiwal. # Python3 recursive program to check# if an Array is sorted or not # Function that returns true if array# is sorted in non-decreasing order.def arraySortedOrNot(arr, n): # Base case if (n == 0 or n == 1): return True # Check if present index and index # previous to it are in correct order # and rest of the array is also sorted # if true then return true else return # false return (arr[n - 1] >= arr[n - 2] and arraySortedOrNot(arr, n - 1)) # Driver codearr = [ 20, 23, 23, 45, 78, 88 ]n = len(arr) # Function Callif (arraySortedOrNot(arr, n)): print("Yes")else: print("No") # This code is contributed by Virusbuddah // C# recursive approach to check if an// Array is sorted or notusing System; class GFG{ // Function that returns true if array is// sorted in non-decreasing order.static bool arraySortedOrNot(int[] a, int n){ // Base case if (n == 1 || n == 0) { return true; } // Check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1);} // Driver codestatic public void Main(){ int[] arr = { 20, 23, 23, 45, 78, 88 }; int n = arr.Length; // Function Call if (arraySortedOrNot(arr, n)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); }}} // This code is contributed by rag2127 <script> // JavaScript Recursive approach to check if an// Array is sorted or not // Function that returns true if array is// sorted in non-decreasing order.function arraySortedOrNot(a, n){ // Base case if (n == 1 || n == 0) { return true; } // Check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1);} // Driver codelet arr = [ 20, 23, 23, 45, 78, 88 ];let n = arr.length; // Function Callif (arraySortedOrNot(arr, n)){ document.write("Yes" + "<br>");}else{ document.write("No" + "<br>");} // This code is contributed by Surbhi Tyagi. </script> Yes Time Complexity: O(n) Auxiliary Space: O(n) for Recursion Call Stack. Iterative approach: The idea is pretty much the same. The benefit of the iterative approach is it avoids the usage of recursion stack space and recursion overhead. Below is the implementation using iteration: C++ Java Python3 C# Javascript // C++ program to check if an// Array is sorted or not#include <bits/stdc++.h>using namespace std; // Function that returns true if array is// sorted in non-decreasing order.bool arraySortedOrNot(int arr[], int n){ // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true;} // Driver codeint main(){ int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = sizeof(arr) / sizeof(arr[0]); if (arraySortedOrNot(arr, n)) cout << "Yes\n"; else cout << "No\n";} // Recursive approach to check if an// Array is sorted or notclass GFG { // Function that returns true if array is // sorted in non-decreasing order. static boolean arraySortedOrNot(int arr[], int n) { // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true; } // driver code public static void main(String[] args) { int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = arr.length; if (arraySortedOrNot(arr, n)) System.out.print("Yes\n"); else System.out.print("No\n"); }} // This code is contributed by Anant Agarwal. # Python3 program to check if an# Array is sorted or not # Function that returns true if array is# sorted in non-decreasing order.def arraySortedOrNot(arr, n): # Array has one or no element if (n == 0 or n == 1): return True for i in range(1, n): # Unsorted pair found if (arr[i-1] > arr[i]): return False # No unsorted pair found return True # Driver codearr = [20, 23, 23, 45, 78, 88]n = len(arr)if (arraySortedOrNot(arr, n)): print("Yes")else: print("No") # This code is contributed by Anant Agarwal. // Recursive approach to check if an// Array is sorted or notusing System; class GFG{ // Function that returns true if array is // sorted in non-decreasing order. static bool arraySortedOrNot(int []arr, int n) { // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true; } // Driver code public static void Main(String[] args) { int []arr = { 20, 23, 23, 45, 78, 88 }; int n = arr.Length; if (arraySortedOrNot(arr, n)) Console.Write("Yes\n"); else Console.Write("No\n"); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program Recursive approach to check if an// Array is sorted or not // Function that returns true if array is // sorted in non-decreasing order. function arraySortedOrNot(arr, n) { // Array has one or no element if (n == 0 || n == 1) return true; for (let i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true; } // Driver Code let arr = [ 20, 23, 23, 45, 78, 88 ]; let n = arr.length; if (arraySortedOrNot(arr, n)) document.write("Yes\n"); else document.write("No\n"); // This code is contributed by sanjoy_62.</script> Output: Yes Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. princiraj1992 29AjayKumar durgeshagrawal38 virusbuddha avanitrachhadiya2155 rag2127 sravankumar8128 surbhityagi15 sanjoy_62 Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java
[ { "code": null, "e": 26777, "s": 26749, "text": "\n09 Jun, 2021" }, { "code": null, "e": 26964, "s": 26777, "text": "Given an array of size n, write a program to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted." }, { "code": null, "e": 26975, "s": 26964, "text": "Examples: " }, { "code": null, "e": 27093, "s": 26975, "text": "Input : 20 21 45 89 89 90\nOutput : Yes\n\nInput : 20 20 45 89 89 90\nOutput : Yes\n\nInput : 20 20 78 98 99 97\nOutput : No" }, { "code": null, "e": 27157, "s": 27093, "text": "Recursive approach:The basic idea for the recursive approach: " }, { "code": null, "e": 27415, "s": 27157, "text": "1: If size of array is zero or one, return true.\n2: Check last two elements of array, if they are\n sorted, perform a recursive call with n-1\n else, return false.\nIf all the elements will be found sorted, n will\neventually fall to one, satisfying Step 1." }, { "code": null, "e": 27460, "s": 27415, "text": "Below is the implementation using recursion:" }, { "code": null, "e": 27464, "s": 27460, "text": "C++" }, { "code": null, "e": 27469, "s": 27464, "text": "Java" }, { "code": null, "e": 27477, "s": 27469, "text": "Python3" }, { "code": null, "e": 27480, "s": 27477, "text": "C#" }, { "code": null, "e": 27491, "s": 27480, "text": "Javascript" }, { "code": "// Recursive approach to check if an// Array is sorted or not#include <bits/stdc++.h>using namespace std; // Function that returns 0 if a pair// is found unsortedint arraySortedOrNot(int arr[], int n){ // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1);} // Driver codeint main(){ int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = sizeof(arr) / sizeof(arr[0]); if (arraySortedOrNot(arr, n)) cout << \"Yes\\n\"; else cout << \"No\\n\";}", "e": 28211, "s": 27491, "text": null }, { "code": "// Recursive approach to check if an// Array is sorted or not class CkeckSorted { // Function that returns 0 if a pair // is found unsorted static int arraySortedOrNot(int arr[], int n) { // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1); } // main function public static void main(String[] args) { int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = arr.length; if (arraySortedOrNot(arr, n) != 0) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 29051, "s": 28211, "text": null }, { "code": "# Recursive approach to check if an# Array is sorted or not # Function that returns 0 if a pair# is found unsorted def arraySortedOrNot(arr): # Calculating length n = len(arr) # Array has one or no element or the # rest are already checked and approved. if n == 1 or n == 0: return True # Recursion applied till last element return arr[0] <= arr[1] and arraySortedOrNot(arr[1:]) arr = [20, 23, 23, 45, 78, 88] # Displaying resultif arraySortedOrNot(arr): print(\"Yes\")else: print(\"No\")", "e": 29575, "s": 29051, "text": null }, { "code": "// Recursive approach to check if an// Array is sorted or notusing System; class CkeckSorted { // Function that returns 0 if a pair // is found unsorted static int arraySortedOrNot(int[] arr, int n) { // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1); } // Driver Code public static void Main(String[] args) { int[] arr = { 20, 23, 23, 45, 78, 88 }; int n = arr.Length; if (arraySortedOrNot(arr, n) != 0) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by 29AjayKumar", "e": 30467, "s": 29575, "text": null }, { "code": "<script> // Recursive approach to check if an// Array is sorted or not // Function that returns 0 if a pair// is found unsortedfunction arraySortedOrNot(arr, n){ // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return arraySortedOrNot(arr, n - 1);} // Driver codelet arr = [ 20, 23, 23, 45, 78, 88 ];let n = arr.length; if (arraySortedOrNot(arr, n) != 0) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by sravan kumar G </script>", "e": 31170, "s": 30467, "text": null }, { "code": null, "e": 31178, "s": 31170, "text": "Output:" }, { "code": null, "e": 31182, "s": 31178, "text": "Yes" }, { "code": null, "e": 31252, "s": 31182, "text": "Time Complexity: O(n) Auxiliary Space: O(n) for Recursion Call Stack." }, { "code": null, "e": 31280, "s": 31252, "text": "Another Recursive approach:" }, { "code": null, "e": 31284, "s": 31280, "text": "C++" }, { "code": null, "e": 31289, "s": 31284, "text": "Java" }, { "code": null, "e": 31297, "s": 31289, "text": "Python3" }, { "code": null, "e": 31300, "s": 31297, "text": "C#" }, { "code": null, "e": 31311, "s": 31300, "text": "Javascript" }, { "code": "// C++ Recursive approach to check if an// Array is sorted or not#include <iostream>using namespace std; // Function that returns true if array is// sorted in non-decreasing order.bool arraySortedOrNot(int a[], int n){ // Base case if (n == 1 || n == 0) { return true; } // Check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1);} // Driver codeint main(){ int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call if (arraySortedOrNot(arr, n)) { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; } return 0;} // This code is contributed by avanitrachhadiya2155", "e": 32183, "s": 31311, "text": null }, { "code": "// Java Recursive approach to check if an// Array is sorted or notclass GFG { // Function that returns true if array is // sorted in non-decreasing order. static boolean arraySortedOrNot(int a[], int n) { // base case if (n == 1 || n == 0) return true; // check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1); } // Driver code public static void main(String[] args) { int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = arr.length; // Function Call if (arraySortedOrNot(arr, n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Durgesh N. Birmiwal.", "e": 33118, "s": 32183, "text": null }, { "code": "# Python3 recursive program to check# if an Array is sorted or not # Function that returns true if array# is sorted in non-decreasing order.def arraySortedOrNot(arr, n): # Base case if (n == 0 or n == 1): return True # Check if present index and index # previous to it are in correct order # and rest of the array is also sorted # if true then return true else return # false return (arr[n - 1] >= arr[n - 2] and arraySortedOrNot(arr, n - 1)) # Driver codearr = [ 20, 23, 23, 45, 78, 88 ]n = len(arr) # Function Callif (arraySortedOrNot(arr, n)): print(\"Yes\")else: print(\"No\") # This code is contributed by Virusbuddah", "e": 33799, "s": 33118, "text": null }, { "code": "// C# recursive approach to check if an// Array is sorted or notusing System; class GFG{ // Function that returns true if array is// sorted in non-decreasing order.static bool arraySortedOrNot(int[] a, int n){ // Base case if (n == 1 || n == 0) { return true; } // Check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1);} // Driver codestatic public void Main(){ int[] arr = { 20, 23, 23, 45, 78, 88 }; int n = arr.Length; // Function Call if (arraySortedOrNot(arr, n)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); }}} // This code is contributed by rag2127", "e": 34639, "s": 33799, "text": null }, { "code": "<script> // JavaScript Recursive approach to check if an// Array is sorted or not // Function that returns true if array is// sorted in non-decreasing order.function arraySortedOrNot(a, n){ // Base case if (n == 1 || n == 0) { return true; } // Check if present index and index // previous to it are in correct order // and rest of the array is also sorted // if true then return true else return // false return a[n - 1] >= a[n - 2] && arraySortedOrNot(a, n - 1);} // Driver codelet arr = [ 20, 23, 23, 45, 78, 88 ];let n = arr.length; // Function Callif (arraySortedOrNot(arr, n)){ document.write(\"Yes\" + \"<br>\");}else{ document.write(\"No\" + \"<br>\");} // This code is contributed by Surbhi Tyagi. </script>", "e": 35405, "s": 34639, "text": null }, { "code": null, "e": 35409, "s": 35405, "text": "Yes" }, { "code": null, "e": 35479, "s": 35409, "text": "Time Complexity: O(n) Auxiliary Space: O(n) for Recursion Call Stack." }, { "code": null, "e": 35643, "s": 35479, "text": "Iterative approach: The idea is pretty much the same. The benefit of the iterative approach is it avoids the usage of recursion stack space and recursion overhead." }, { "code": null, "e": 35689, "s": 35643, "text": "Below is the implementation using iteration: " }, { "code": null, "e": 35693, "s": 35689, "text": "C++" }, { "code": null, "e": 35698, "s": 35693, "text": "Java" }, { "code": null, "e": 35706, "s": 35698, "text": "Python3" }, { "code": null, "e": 35709, "s": 35706, "text": "C#" }, { "code": null, "e": 35720, "s": 35709, "text": "Javascript" }, { "code": "// C++ program to check if an// Array is sorted or not#include <bits/stdc++.h>using namespace std; // Function that returns true if array is// sorted in non-decreasing order.bool arraySortedOrNot(int arr[], int n){ // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true;} // Driver codeint main(){ int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = sizeof(arr) / sizeof(arr[0]); if (arraySortedOrNot(arr, n)) cout << \"Yes\\n\"; else cout << \"No\\n\";}", "e": 36380, "s": 35720, "text": null }, { "code": "// Recursive approach to check if an// Array is sorted or notclass GFG { // Function that returns true if array is // sorted in non-decreasing order. static boolean arraySortedOrNot(int arr[], int n) { // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true; } // driver code public static void main(String[] args) { int arr[] = { 20, 23, 23, 45, 78, 88 }; int n = arr.length; if (arraySortedOrNot(arr, n)) System.out.print(\"Yes\\n\"); else System.out.print(\"No\\n\"); }} // This code is contributed by Anant Agarwal.", "e": 37200, "s": 36380, "text": null }, { "code": "# Python3 program to check if an# Array is sorted or not # Function that returns true if array is# sorted in non-decreasing order.def arraySortedOrNot(arr, n): # Array has one or no element if (n == 0 or n == 1): return True for i in range(1, n): # Unsorted pair found if (arr[i-1] > arr[i]): return False # No unsorted pair found return True # Driver codearr = [20, 23, 23, 45, 78, 88]n = len(arr)if (arraySortedOrNot(arr, n)): print(\"Yes\")else: print(\"No\") # This code is contributed by Anant Agarwal.", "e": 37766, "s": 37200, "text": null }, { "code": "// Recursive approach to check if an// Array is sorted or notusing System; class GFG{ // Function that returns true if array is // sorted in non-decreasing order. static bool arraySortedOrNot(int []arr, int n) { // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true; } // Driver code public static void Main(String[] args) { int []arr = { 20, 23, 23, 45, 78, 88 }; int n = arr.Length; if (arraySortedOrNot(arr, n)) Console.Write(\"Yes\\n\"); else Console.Write(\"No\\n\"); }} // This code is contributed by PrinciRaj1992", "e": 38588, "s": 37766, "text": null }, { "code": "<script> // Javascript program Recursive approach to check if an// Array is sorted or not // Function that returns true if array is // sorted in non-decreasing order. function arraySortedOrNot(arr, n) { // Array has one or no element if (n == 0 || n == 1) return true; for (let i = 1; i < n; i++) // Unsorted pair found if (arr[i - 1] > arr[i]) return false; // No unsorted pair found return true; } // Driver Code let arr = [ 20, 23, 23, 45, 78, 88 ]; let n = arr.length; if (arraySortedOrNot(arr, n)) document.write(\"Yes\\n\"); else document.write(\"No\\n\"); // This code is contributed by sanjoy_62.</script>", "e": 39353, "s": 38588, "text": null }, { "code": null, "e": 39362, "s": 39353, "text": "Output: " }, { "code": null, "e": 39366, "s": 39362, "text": "Yes" }, { "code": null, "e": 39410, "s": 39366, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 39834, "s": 39410, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 39848, "s": 39834, "text": "princiraj1992" }, { "code": null, "e": 39860, "s": 39848, "text": "29AjayKumar" }, { "code": null, "e": 39877, "s": 39860, "text": "durgeshagrawal38" }, { "code": null, "e": 39889, "s": 39877, "text": "virusbuddha" }, { "code": null, "e": 39910, "s": 39889, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39918, "s": 39910, "text": "rag2127" }, { "code": null, "e": 39934, "s": 39918, "text": "sravankumar8128" }, { "code": null, "e": 39948, "s": 39934, "text": "surbhityagi15" }, { "code": null, "e": 39958, "s": 39948, "text": "sanjoy_62" }, { "code": null, "e": 39965, "s": 39958, "text": "Arrays" }, { "code": null, "e": 39973, "s": 39965, "text": "Sorting" }, { "code": null, "e": 39980, "s": 39973, "text": "Arrays" }, { "code": null, "e": 39988, "s": 39980, "text": "Sorting" }, { "code": null, "e": 40086, "s": 39988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40154, "s": 40086, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40198, "s": 40154, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40246, "s": 40198, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 40269, "s": 40246, "text": "Introduction to Arrays" } ]
PHP | array() Function - GeeksforGeeks
30 May, 2019 The array() function is an inbuilt function in PHP which is used to create an array. There are three types of array in PHP: Indexed array: The array which contains numeric index.Syntax:array( val1, val2, val3, ... ) array( val1, val2, val3, ... ) Associative array: The array which contains name as keys.Syntax:array( key=>val, key=>val, key=>value, ... ) array( key=>val, key=>val, key=>value, ... ) Multidimensional array: The array which contains one or more arrays.Syntax:array( array( val11, val12, ...) array( val21, val22, ...) ... ) array( array( val11, val12, ...) array( val21, val22, ...) ... ) Parameters: This function accepts atmost two parameters as mentioned above and described below: val: This parameter is used to hold the value of array. key: This parameter is used to hold the key value: Return Value: This function returns an array of parameters. Below programs illustrates the array() function in PHP: Program 1: This example illustrate the Indexed array. <?php // Create an array$sub = array("DBMS", "Algorithm", "C++", "JAVA"); // Find length of array$len = count( $sub ); // Loop to print array elementsfor( $i = 0; $i < $len; $i++) { echo $sub[$i] . "\n";}?> DBMS Algorithm C++ JAVA Program 2: This example illustrate the Associative array. <?php // Declare an associative array$detail = array( "Name"=>"GeeksforGeeks", "Address"=>"Noida", "Type"=>"Educational site"); // Display the outputvar_dump ($detail);?> array(3) { ["Name"]=> string(13) "GeeksforGeeks" ["Address"]=> string(5) "Noida" ["Type"]=> string(16) "Educational site" } Program 3: This example illustrate the Multidimensional array. <?php // Declare 2D array$detail = array(array(1, 2, 3, 4), array(5, 6, 7, 8)); // Display the outputvar_dump ($detail);?> array(2) { [0]=> array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) } [1]=> array(4) { [0]=> int(5) [1]=> int(6) [2]=> int(7) [3]=> int(8) } } PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? 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": 42139, "s": 42111, "text": "\n30 May, 2019" }, { "code": null, "e": 42263, "s": 42139, "text": "The array() function is an inbuilt function in PHP which is used to create an array. There are three types of array in PHP:" }, { "code": null, "e": 42355, "s": 42263, "text": "Indexed array: The array which contains numeric index.Syntax:array( val1, val2, val3, ... )" }, { "code": null, "e": 42386, "s": 42355, "text": "array( val1, val2, val3, ... )" }, { "code": null, "e": 42495, "s": 42386, "text": "Associative array: The array which contains name as keys.Syntax:array( key=>val, key=>val, key=>value, ... )" }, { "code": null, "e": 42540, "s": 42495, "text": "array( key=>val, key=>val, key=>value, ... )" }, { "code": null, "e": 42694, "s": 42540, "text": "Multidimensional array: The array which contains one or more arrays.Syntax:array( array( val11, val12, ...)\n array( val21, val22, ...)\n ... )" }, { "code": null, "e": 42773, "s": 42694, "text": "array( array( val11, val12, ...)\n array( val21, val22, ...)\n ... )" }, { "code": null, "e": 42869, "s": 42773, "text": "Parameters: This function accepts atmost two parameters as mentioned above and described below:" }, { "code": null, "e": 42925, "s": 42869, "text": "val: This parameter is used to hold the value of array." }, { "code": null, "e": 42976, "s": 42925, "text": "key: This parameter is used to hold the key value:" }, { "code": null, "e": 43036, "s": 42976, "text": "Return Value: This function returns an array of parameters." }, { "code": null, "e": 43092, "s": 43036, "text": "Below programs illustrates the array() function in PHP:" }, { "code": null, "e": 43146, "s": 43092, "text": "Program 1: This example illustrate the Indexed array." }, { "code": "<?php // Create an array$sub = array(\"DBMS\", \"Algorithm\", \"C++\", \"JAVA\"); // Find length of array$len = count( $sub ); // Loop to print array elementsfor( $i = 0; $i < $len; $i++) { echo $sub[$i] . \"\\n\";}?>", "e": 43359, "s": 43146, "text": null }, { "code": null, "e": 43384, "s": 43359, "text": "DBMS\nAlgorithm\nC++\nJAVA\n" }, { "code": null, "e": 43442, "s": 43384, "text": "Program 2: This example illustrate the Associative array." }, { "code": "<?php // Declare an associative array$detail = array( \"Name\"=>\"GeeksforGeeks\", \"Address\"=>\"Noida\", \"Type\"=>\"Educational site\"); // Display the outputvar_dump ($detail);?> ", "e": 43650, "s": 43442, "text": null }, { "code": null, "e": 43787, "s": 43650, "text": "array(3) {\n [\"Name\"]=>\n string(13) \"GeeksforGeeks\"\n [\"Address\"]=>\n string(5) \"Noida\"\n [\"Type\"]=>\n string(16) \"Educational site\"\n}\n" }, { "code": null, "e": 43850, "s": 43787, "text": "Program 3: This example illustrate the Multidimensional array." }, { "code": "<?php // Declare 2D array$detail = array(array(1, 2, 3, 4), array(5, 6, 7, 8)); // Display the outputvar_dump ($detail);?> ", "e": 43991, "s": 43850, "text": null }, { "code": null, "e": 44223, "s": 43991, "text": "array(2) {\n [0]=>\n array(4) {\n [0]=>\n int(1)\n [1]=>\n int(2)\n [2]=>\n int(3)\n [3]=>\n int(4)\n }\n [1]=>\n array(4) {\n [0]=>\n int(5)\n [1]=>\n int(6)\n [2]=>\n int(7)\n [3]=>\n int(8)\n }\n}\n" }, { "code": null, "e": 44236, "s": 44223, "text": "PHP-function" }, { "code": null, "e": 44240, "s": 44236, "text": "PHP" }, { "code": null, "e": 44257, "s": 44240, "text": "Web Technologies" }, { "code": null, "e": 44261, "s": 44257, "text": "PHP" }, { "code": null, "e": 44359, "s": 44261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44404, "s": 44359, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 44454, "s": 44404, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 44494, "s": 44454, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 44518, "s": 44494, "text": "PHP in_array() Function" }, { "code": null, "e": 44562, "s": 44518, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 44602, "s": 44562, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 44635, "s": 44602, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 44680, "s": 44635, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 44723, "s": 44680, "text": "How to fetch data from an API in ReactJS ?" } ]
AngularJS | lowercase Filter - GeeksforGeeks
22 Apr, 2019 The lowercase filter is used to convert a string into lowercase letters. Syntax: {{expression|lowercase}} Example-1: <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <h2>AngularJS - lowercase</h2> <br> <br> <div ng-app="myApp" ng-controller="myCtrl"> <strong>Input:</strong> <br> <input type="text" ng-model="string"> <br> <br> <strong>Output:</strong> <br> {{string|lowercase}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.string = ""; }); </script> </body> </html> Example-2: <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <body> <h2>AngularJS - lowercase</h2> <br> <br> <div ng-app="myApp" ng-controller="myCtrl"> <strong>First Name:</strong> <br> <input type="text" ng-model="firstName"> <br> <br> <strong>Last Name:</strong> <br> <input type="text" ng-model="lastName"> <br> <strong>Output:</strong> <br> {{firstName|lowercase}} {{lastName|lowercase}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = ""; $scope.lastName = ""; }); </script> </body> </html> Output: Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular PrimeNG Dropdown Component Angular | keyup event Auth Guards in Angular 9/10/11 How to Display Spinner on the Screen till the data from the API loads using Angular 8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 29516, "s": 29488, "text": "\n22 Apr, 2019" }, { "code": null, "e": 29589, "s": 29516, "text": "The lowercase filter is used to convert a string into lowercase letters." }, { "code": null, "e": 29597, "s": 29589, "text": "Syntax:" }, { "code": null, "e": 29622, "s": 29597, "text": "{{expression|lowercase}}" }, { "code": null, "e": 29633, "s": 29622, "text": "Example-1:" }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <body> <h2>AngularJS - lowercase</h2> <br> <br> <div ng-app=\"myApp\" ng-controller=\"myCtrl\"> <strong>Input:</strong> <br> <input type=\"text\" ng-model=\"string\"> <br> <br> <strong>Output:</strong> <br> {{string|lowercase}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.string = \"\"; }); </script> </body> </html>", "e": 30257, "s": 29633, "text": null }, { "code": null, "e": 30268, "s": 30257, "text": "Example-2:" }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <body> <h2>AngularJS - lowercase</h2> <br> <br> <div ng-app=\"myApp\" ng-controller=\"myCtrl\"> <strong>First Name:</strong> <br> <input type=\"text\" ng-model=\"firstName\"> <br> <br> <strong>Last Name:</strong> <br> <input type=\"text\" ng-model=\"lastName\"> <br> <strong>Output:</strong> <br> {{firstName|lowercase}} {{lastName|lowercase}} </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = \"\"; $scope.lastName = \"\"; }); </script> </body> </html>", "e": 31095, "s": 30268, "text": null }, { "code": null, "e": 31103, "s": 31095, "text": "Output:" }, { "code": null, "e": 31110, "s": 31103, "text": "Picked" }, { "code": null, "e": 31120, "s": 31110, "text": "AngularJS" }, { "code": null, "e": 31137, "s": 31120, "text": "Web Technologies" }, { "code": null, "e": 31235, "s": 31137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31255, "s": 31235, "text": "Angular File Upload" }, { "code": null, "e": 31290, "s": 31255, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31312, "s": 31290, "text": "Angular | keyup event" }, { "code": null, "e": 31343, "s": 31312, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31431, "s": 31343, "text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?" }, { "code": null, "e": 31471, "s": 31431, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31504, "s": 31471, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31549, "s": 31504, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31592, "s": 31549, "text": "How to fetch data from an API in ReactJS ?" } ]
Angular PrimeNG RadioButton Component - GeeksforGeeks
22 Aug, 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 RadioButton component in Angular PrimeNG. RadioButton component: It allows the user to select one option at a time from a set. Properties: name: It is used to set the name of the radiobutton group. It is of string data type, the default value is null. value: It is used to set the value of the radiobutton. It is of string data type, the default value is null. label: It is used to set the label of the radiobutton. It is of string data type, the default value is null. disabled: It specifies that the element should be disabled, It is of the boolean data type, the default value is false. tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null. inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null. ariaLabelledBy: It is the ariaLabelledBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null. style: It is used to set the inline style of the element. It is of object data type, the default value is null. styleClass: It is used to set the style class of the element. It is of string data type, the default value is null. ariaLabel: It is used to define a string that labels the input element. It is of string data type, the default value is null. labelStyleClass: It is used to set the style class of the label. It is of string data type, the default value is null. Events: onClick: It is a callback that is fired on radio button click. onFocus: It is a callback that is fired when the radio button receives focus. onBlur: It is a callback that is fired when the radio button loses focus. Methods: focus: This method is used to apply focus on the element. Styling: p-radiobutton: It styles the container element. p-radiobutton-box: It styles the container of icons. p-radiobutton-icon: It styles the icon element. p-chkbox-label: It styles the label element. p-label-active: It styles the label element of a checked state. p-label-focus: It styles the label element of a focused state. p-label-disabled: It styles the label element of a disabled state. Creating Angular Application & module installation: Step 1: Create an Angular application using the following command.ng new appname 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 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 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 basic example illustrates the use of the RadioButton component without a preselected value. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG RadioButton component</h5><div class="p-field-radiobutton"> <p-radioButton value="AngularJS" [(ngModel)]=" gfg" inputId=" gfg1"> </p-radioButton> <label for=" gfg1">AngularJS</label></div><div class="p-field-radiobutton"> <p-radioButton value="ReactJS" [(ngModel)]=" gfg" inputId=" gfg2"> </p-radioButton> <label for=" gfg2">ReactJS</label></div><div class="p-field-radiobutton"> <p-radioButton value="HTML" [(ngModel)]=" gfg" inputId="gfg3"> </p-radioButton> <label for="gfg3">HTML</label></div><div class="p-field-radiobutton"> <p-radioButton value="JavaScript" [(ngModel)]=" gfg" inputId=" gfg4"> </p-radioButton> <label for=" gfg4">JavaScript</label></div> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: string;} app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { RadioButtonModule } from 'primeng/radiobutton'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, RadioButtonModule, FormsModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} Output: Example 2: In this example, we are building a radioButton Group dynamically with the pre-selected value. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG RadioButton Component</h5><div *ngFor="let a of gfg" class="p-field-checkbox"> <p-radioButton [value]="a" [(ngModel)]="selected"> </p-radioButton> <label [for]="a.key">{{a.name}}</label></div> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { selected: any = null; gfg: any[] = [ { name: 'A' }, { name: 'B' }, { name: 'C' }, { name: 'D' }, { name: 'E' } ]; ngOnInit() { this.selected = this.gfg[0]; }} app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { RadioButtonModule } from 'primeng/radiobutton'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, RadioButtonModule, FormsModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/radiobutton 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": "\n22 Aug, 2021" }, { "code": null, "e": 26641, "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 RadioButton component in Angular PrimeNG." }, { "code": null, "e": 26726, "s": 26641, "text": "RadioButton component: It allows the user to select one option at a time from a set." }, { "code": null, "e": 26738, "s": 26726, "text": "Properties:" }, { "code": null, "e": 26851, "s": 26738, "text": "name: It is used to set the name of the radiobutton group. It is of string data type, the default value is null." }, { "code": null, "e": 26960, "s": 26851, "text": "value: It is used to set the value of the radiobutton. It is of string data type, the default value is null." }, { "code": null, "e": 27069, "s": 26960, "text": "label: It is used to set the label of the radiobutton. It is of string data type, the default value is null." }, { "code": null, "e": 27189, "s": 27069, "text": "disabled: It specifies that the element should be disabled, It is of the boolean data type, the default value is false." }, { "code": null, "e": 27313, "s": 27189, "text": "tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null." }, { "code": null, "e": 27432, "s": 27313, "text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null." }, { "code": null, "e": 27653, "s": 27432, "text": "ariaLabelledBy: It is the ariaLabelledBy property that establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null." }, { "code": null, "e": 27765, "s": 27653, "text": "style: It is used to set the inline style of the element. It is of object data type, the default value is null." }, { "code": null, "e": 27881, "s": 27765, "text": "styleClass: It is used to set the style class of the element. It is of string data type, the default value is null." }, { "code": null, "e": 28007, "s": 27881, "text": "ariaLabel: It is used to define a string that labels the input element. It is of string data type, the default value is null." }, { "code": null, "e": 28126, "s": 28007, "text": "labelStyleClass: It is used to set the style class of the label. It is of string data type, the default value is null." }, { "code": null, "e": 28134, "s": 28126, "text": "Events:" }, { "code": null, "e": 28197, "s": 28134, "text": "onClick: It is a callback that is fired on radio button click." }, { "code": null, "e": 28275, "s": 28197, "text": "onFocus: It is a callback that is fired when the radio button receives focus." }, { "code": null, "e": 28349, "s": 28275, "text": "onBlur: It is a callback that is fired when the radio button loses focus." }, { "code": null, "e": 28360, "s": 28351, "text": "Methods:" }, { "code": null, "e": 28418, "s": 28360, "text": "focus: This method is used to apply focus on the element." }, { "code": null, "e": 28428, "s": 28418, "text": "Styling: " }, { "code": null, "e": 28476, "s": 28428, "text": "p-radiobutton: It styles the container element." }, { "code": null, "e": 28529, "s": 28476, "text": "p-radiobutton-box: It styles the container of icons." }, { "code": null, "e": 28577, "s": 28529, "text": "p-radiobutton-icon: It styles the icon element." }, { "code": null, "e": 28622, "s": 28577, "text": "p-chkbox-label: It styles the label element." }, { "code": null, "e": 28686, "s": 28622, "text": "p-label-active: It styles the label element of a checked state." }, { "code": null, "e": 28749, "s": 28686, "text": "p-label-focus: It styles the label element of a focused state." }, { "code": null, "e": 28817, "s": 28749, "text": "p-label-disabled: It styles the label element of a disabled state. " }, { "code": null, "e": 28869, "s": 28817, "text": "Creating Angular Application & module installation:" }, { "code": null, "e": 28950, "s": 28869, "text": "Step 1: Create an Angular application using the following command.ng new appname" }, { "code": null, "e": 29017, "s": 28950, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 29032, "s": 29017, "text": "ng new appname" }, { "code": null, "e": 29139, "s": 29032, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname" }, { "code": null, "e": 29236, "s": 29139, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 29247, "s": 29236, "text": "cd appname" }, { "code": null, "e": 29352, "s": 29247, "text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 29401, "s": 29352, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 29458, "s": 29401, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 29510, "s": 29458, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 29618, "s": 29510, "text": "Example 1: This basic example illustrates the use of the RadioButton component without a preselected value." }, { "code": null, "e": 29637, "s": 29618, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG RadioButton component</h5><div class=\"p-field-radiobutton\"> <p-radioButton value=\"AngularJS\" [(ngModel)]=\" gfg\" inputId=\" gfg1\"> </p-radioButton> <label for=\" gfg1\">AngularJS</label></div><div class=\"p-field-radiobutton\"> <p-radioButton value=\"ReactJS\" [(ngModel)]=\" gfg\" inputId=\" gfg2\"> </p-radioButton> <label for=\" gfg2\">ReactJS</label></div><div class=\"p-field-radiobutton\"> <p-radioButton value=\"HTML\" [(ngModel)]=\" gfg\" inputId=\"gfg3\"> </p-radioButton> <label for=\"gfg3\">HTML</label></div><div class=\"p-field-radiobutton\"> <p-radioButton value=\"JavaScript\" [(ngModel)]=\" gfg\" inputId=\" gfg4\"> </p-radioButton> <label for=\" gfg4\">JavaScript</label></div>", "e": 30482, "s": 29637, "text": null }, { "code": null, "e": 30499, "s": 30482, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: string;}", "e": 30658, "s": 30499, "text": null }, { "code": null, "e": 30672, "s": 30658, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { RadioButtonModule } from 'primeng/radiobutton'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, RadioButtonModule, FormsModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 31204, "s": 30672, "text": null }, { "code": null, "e": 31212, "s": 31204, "text": "Output:" }, { "code": null, "e": 31318, "s": 31212, "text": "Example 2: In this example, we are building a radioButton Group dynamically with the pre-selected value. " }, { "code": null, "e": 31337, "s": 31318, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG RadioButton Component</h5><div *ngFor=\"let a of gfg\" class=\"p-field-checkbox\"> <p-radioButton [value]=\"a\" [(ngModel)]=\"selected\"> </p-radioButton> <label [for]=\"a.key\">{{a.name}}</label></div>", "e": 31567, "s": 31337, "text": null }, { "code": null, "e": 31584, "s": 31567, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { selected: any = null; gfg: any[] = [ { name: 'A' }, { name: 'B' }, { name: 'C' }, { name: 'D' }, { name: 'E' } ]; ngOnInit() { this.selected = this.gfg[0]; }}", "e": 31914, "s": 31584, "text": null }, { "code": null, "e": 31928, "s": 31914, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { RadioButtonModule } from 'primeng/radiobutton'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, RadioButtonModule, FormsModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 32460, "s": 31928, "text": null }, { "code": null, "e": 32468, "s": 32460, "text": "Output:" }, { "code": null, "e": 32533, "s": 32468, "text": "Reference: https://primefaces.org/primeng/showcase/#/radiobutton" }, { "code": null, "e": 32549, "s": 32533, "text": "Angular-PrimeNG" }, { "code": null, "e": 32559, "s": 32549, "text": "AngularJS" }, { "code": null, "e": 32576, "s": 32559, "text": "Web Technologies" }, { "code": null, "e": 32674, "s": 32576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32709, "s": 32674, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32744, "s": 32709, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 32768, "s": 32744, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32803, "s": 32768, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 32856, "s": 32803, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32896, "s": 32856, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32929, "s": 32896, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32974, "s": 32929, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33017, "s": 32974, "text": "How to fetch data from an API in ReactJS ?" } ]
How to call base class constructor from child class in TypeScript ? - GeeksforGeeks
14 Jun, 2021 In this article, we will learn how we can call the base class constructor from the child class. When a class inherits the properties of another class, it is called a child class and the class whose properties are inherited is called the parent class and the whole process is called Inheritance. In Inheritance, the child class acquires the properties of the base class or parent class. You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class. Example: Javascript class Person { // Properties of the Person class Name: string; Profession: string; // Constructor of Person class constructor(name: string, profession: string) { this.Name = name; this.Profession = profession; }} class Details extends Person { // Properties of the class Name: string; Profession: string; // Constructor of the Details class constructor(name: string, profession: string) { // Calling the base class constructor super(name, profession); // Setting the properties this.Name = name; this.Profession = profession; } details(): string { return this.Name + " is " + this.Profession; }} // Creating an objectvar data = new Details("A", "Android Developer");var data2 = new Details("B", "Web Developer"); // Accessing the function details() // and printingconsole.log(data.details());console.log(data2.details()); Output: A is Android Developer B is Web Developer Here, the Person class is our parent class and the Details class is our child class and also the Details class inherits the Person class. For Inheriting another class extends keyword is used. The Details class inherits the properties of the Person class. Now in the derived class, we have used the super() which will call the constructor of the base class or parent class. After this, we have created an instance of the Details class and passed two parameters name and profession to its constructor and after this, we have called the details method which will print the value provided into the constructor parameter. Example 2: Javascript class Square { // Properties of the Square class side: number; // Constructor of the Square class constructor(side: number) { this.side = side; }} class Area extends Square { // Properties of the Area class side: number; // Constructor of the Area class constructor(side: number) { // Calling the base class constructor super(side); // Setting the properties this.side = side; } // Returns the area of square area(): string { return "The area of Square is " + t his.side * this.side; }} // Creating object of class Areavar data = new Area(7); // Getting the property and // printing the valueconsole.log(data.area()); Output: The area of Square is 49 JavaScript-Questions Picked TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n14 Jun, 2021" }, { "code": null, "e": 26932, "s": 26545, "text": "In this article, we will learn how we can call the base class constructor from the child class. When a class inherits the properties of another class, it is called a child class and the class whose properties are inherited is called the parent class and the whole process is called Inheritance. In Inheritance, the child class acquires the properties of the base class or parent class. " }, { "code": null, "e": 27068, "s": 26932, "text": "You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class." }, { "code": null, "e": 27077, "s": 27068, "text": "Example:" }, { "code": null, "e": 27088, "s": 27077, "text": "Javascript" }, { "code": "class Person { // Properties of the Person class Name: string; Profession: string; // Constructor of Person class constructor(name: string, profession: string) { this.Name = name; this.Profession = profession; }} class Details extends Person { // Properties of the class Name: string; Profession: string; // Constructor of the Details class constructor(name: string, profession: string) { // Calling the base class constructor super(name, profession); // Setting the properties this.Name = name; this.Profession = profession; } details(): string { return this.Name + \" is \" + this.Profession; }} // Creating an objectvar data = new Details(\"A\", \"Android Developer\");var data2 = new Details(\"B\", \"Web Developer\"); // Accessing the function details() // and printingconsole.log(data.details());console.log(data2.details());", "e": 27972, "s": 27088, "text": null }, { "code": null, "e": 27982, "s": 27974, "text": "Output:" }, { "code": null, "e": 28024, "s": 27982, "text": "A is Android Developer\nB is Web Developer" }, { "code": null, "e": 28280, "s": 28024, "text": "Here, the Person class is our parent class and the Details class is our child class and also the Details class inherits the Person class. For Inheriting another class extends keyword is used. The Details class inherits the properties of the Person class. " }, { "code": null, "e": 28642, "s": 28280, "text": "Now in the derived class, we have used the super() which will call the constructor of the base class or parent class. After this, we have created an instance of the Details class and passed two parameters name and profession to its constructor and after this, we have called the details method which will print the value provided into the constructor parameter." }, { "code": null, "e": 28653, "s": 28642, "text": "Example 2:" }, { "code": null, "e": 28664, "s": 28653, "text": "Javascript" }, { "code": "class Square { // Properties of the Square class side: number; // Constructor of the Square class constructor(side: number) { this.side = side; }} class Area extends Square { // Properties of the Area class side: number; // Constructor of the Area class constructor(side: number) { // Calling the base class constructor super(side); // Setting the properties this.side = side; } // Returns the area of square area(): string { return \"The area of Square is \" + t his.side * this.side; }} // Creating object of class Areavar data = new Area(7); // Getting the property and // printing the valueconsole.log(data.area());", "e": 29337, "s": 28664, "text": null }, { "code": null, "e": 29345, "s": 29337, "text": "Output:" }, { "code": null, "e": 29370, "s": 29345, "text": "The area of Square is 49" }, { "code": null, "e": 29391, "s": 29370, "text": "JavaScript-Questions" }, { "code": null, "e": 29398, "s": 29391, "text": "Picked" }, { "code": null, "e": 29409, "s": 29398, "text": "TypeScript" }, { "code": null, "e": 29420, "s": 29409, "text": "JavaScript" }, { "code": null, "e": 29437, "s": 29420, "text": "Web Technologies" }, { "code": null, "e": 29535, "s": 29437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29575, "s": 29535, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29636, "s": 29575, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29677, "s": 29636, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29699, "s": 29677, "text": "JavaScript | Promises" }, { "code": null, "e": 29753, "s": 29699, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29793, "s": 29753, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29826, "s": 29793, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29869, "s": 29826, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29919, "s": 29869, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Searching Algorithms in Java - GeeksforGeeks
08 Jul, 2021 Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories: Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear Search.Interval Search: These algorithms are specifically designed for searching in sorted data-structures. These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. For Example: Binary Search. Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear Search. Interval Search: These algorithms are specifically designed for searching in sorted data-structures. These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. For Example: Binary Search. Linear Search: The idea is to traverse the given array arr[] and find the index at which the element is present. Below are the steps: Let the element to be search be x. Start from the leftmost element of arr[] and one by one compare x with each element of arr[]. If x matches with an element then return that index. If x doesn’t match with any of elements then return -1. Below is the implementation of the Sequential Search in Java: Java // Java program to implement Linear Search class GFG { // Function for linear search public static int search(int arr[], int x) { int n = arr.length; // Traverse array arr[] for (int i = 0; i < n; i++) { // If element found then // return that index if (arr[i] == x) return i; } return -1; } // Driver Code public static void main(String args[]) { // Given arr[] int arr[] = { 2, 3, 4, 10, 40 }; // Element to search int x = 10; // Function Call int result = search(arr, x); if (result == -1) System.out.print( "Element is not present in array"); else System.out.print("Element is present" + " at index " + result); }} Element is present at index 3 Time Complexity: O(N) Auxiliary Space: O(1) Binary Search: This algorithm search element in a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Below are the steps: Compare x with the middle element.If x matches with middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for right half.Else (x is smaller) recur for the left half. Compare x with the middle element. If x matches with middle element, we return the mid index. Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for right half. Else (x is smaller) recur for the left half. Recursive implementation of Binary Search Java // Java implementation of recursive// Binary Search class BinarySearch { // Function that returns index of // x if it is present in arr[l, r] int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present // at the middle itself if (arr[mid] == x) return mid; // If element is smaller than // mid, then it can only be // present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be // present in right subarray return binarySearch(arr, mid + 1, r, x); } // Reach here when element is // not present in array return -1; } // Driver Code public static void main(String args[]) { // Create object of this class BinarySearch ob = new BinarySearch(); // Given array arr[] int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; int x = 10; // Function Call int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1) System.out.println("Element " + "not present"); else System.out.println("Element found" + " at index " + result); }} Element found at index 3 Time Complexity: O(N*log N) Auxiliary Space: O(1) Iterative implementation of Binary Search Java // Java implementation of iterative// Binary Search class BinarySearch { // Returns index of x if it is present // in arr[], else return -1 int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; // Iterate until l <= r while (l <= r) { int m = l + (r - l) / 2; // Check if x is at mid if (arr[m] == x) return m; // If x greater than arr[m] // then ignore left half if (arr[m] < x) l = m + 1; // If x is smaller than arr[m] // ignore right half else r = m - 1; } // If we reach here, then element // was not present return -1; } // Driver Code public static void main(String args[]) { // Create object of this class BinarySearch ob = new BinarySearch(); // Given array arr[] int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; int x = 10; // Function Call int result = ob.binarySearch(arr, x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); }} Element found at index 3 Time Complexity: O(N) Auxiliary Space: O(1) sooda367 Algorithms-Searching Binary Search Java Searching Searching Java Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Maximum and minimum of an array using minimum number of comparisons Search an element in a sorted and rotated array Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1 Program to find largest element in an array
[ { "code": null, "e": 25509, "s": 25481, "text": "\n08 Jul, 2021" }, { "code": null, "e": 25737, "s": 25509, "text": "Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories: " }, { "code": null, "e": 26171, "s": 25737, "text": "Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear Search.Interval Search: These algorithms are specifically designed for searching in sorted data-structures. These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. For Example: Binary Search." }, { "code": null, "e": 26301, "s": 26171, "text": "Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear Search." }, { "code": null, "e": 26606, "s": 26301, "text": "Interval Search: These algorithms are specifically designed for searching in sorted data-structures. These type of searching algorithms are much more efficient than Linear Search as they repeatedly target the center of the search structure and divide the search space in half. For Example: Binary Search." }, { "code": null, "e": 26741, "s": 26606, "text": "Linear Search: The idea is to traverse the given array arr[] and find the index at which the element is present. Below are the steps: " }, { "code": null, "e": 26776, "s": 26741, "text": "Let the element to be search be x." }, { "code": null, "e": 26870, "s": 26776, "text": "Start from the leftmost element of arr[] and one by one compare x with each element of arr[]." }, { "code": null, "e": 26923, "s": 26870, "text": "If x matches with an element then return that index." }, { "code": null, "e": 26979, "s": 26923, "text": "If x doesn’t match with any of elements then return -1." }, { "code": null, "e": 27042, "s": 26979, "text": "Below is the implementation of the Sequential Search in Java: " }, { "code": null, "e": 27047, "s": 27042, "text": "Java" }, { "code": "// Java program to implement Linear Search class GFG { // Function for linear search public static int search(int arr[], int x) { int n = arr.length; // Traverse array arr[] for (int i = 0; i < n; i++) { // If element found then // return that index if (arr[i] == x) return i; } return -1; } // Driver Code public static void main(String args[]) { // Given arr[] int arr[] = { 2, 3, 4, 10, 40 }; // Element to search int x = 10; // Function Call int result = search(arr, x); if (result == -1) System.out.print( \"Element is not present in array\"); else System.out.print(\"Element is present\" + \" at index \" + result); }}", "e": 27928, "s": 27047, "text": null }, { "code": null, "e": 27958, "s": 27928, "text": "Element is present at index 3" }, { "code": null, "e": 28005, "s": 27960, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 28423, "s": 28007, "text": "Binary Search: This algorithm search element in a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Below are the steps: " }, { "code": null, "e": 28700, "s": 28423, "text": "Compare x with the middle element.If x matches with middle element, we return the mid index.Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for right half.Else (x is smaller) recur for the left half." }, { "code": null, "e": 28735, "s": 28700, "text": "Compare x with the middle element." }, { "code": null, "e": 28794, "s": 28735, "text": "If x matches with middle element, we return the mid index." }, { "code": null, "e": 28935, "s": 28794, "text": "Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for right half." }, { "code": null, "e": 28980, "s": 28935, "text": "Else (x is smaller) recur for the left half." }, { "code": null, "e": 29024, "s": 28982, "text": "Recursive implementation of Binary Search" }, { "code": null, "e": 29031, "s": 29026, "text": "Java" }, { "code": "// Java implementation of recursive// Binary Search class BinarySearch { // Function that returns index of // x if it is present in arr[l, r] int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present // at the middle itself if (arr[mid] == x) return mid; // If element is smaller than // mid, then it can only be // present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be // present in right subarray return binarySearch(arr, mid + 1, r, x); } // Reach here when element is // not present in array return -1; } // Driver Code public static void main(String args[]) { // Create object of this class BinarySearch ob = new BinarySearch(); // Given array arr[] int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; int x = 10; // Function Call int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1) System.out.println(\"Element \" + \"not present\"); else System.out.println(\"Element found\" + \" at index \" + result); }}", "e": 30603, "s": 29031, "text": null }, { "code": null, "e": 30628, "s": 30603, "text": "Element found at index 3" }, { "code": null, "e": 30681, "s": 30630, "text": "Time Complexity: O(N*log N) Auxiliary Space: O(1) " }, { "code": null, "e": 30725, "s": 30683, "text": "Iterative implementation of Binary Search" }, { "code": null, "e": 30732, "s": 30727, "text": "Java" }, { "code": "// Java implementation of iterative// Binary Search class BinarySearch { // Returns index of x if it is present // in arr[], else return -1 int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; // Iterate until l <= r while (l <= r) { int m = l + (r - l) / 2; // Check if x is at mid if (arr[m] == x) return m; // If x greater than arr[m] // then ignore left half if (arr[m] < x) l = m + 1; // If x is smaller than arr[m] // ignore right half else r = m - 1; } // If we reach here, then element // was not present return -1; } // Driver Code public static void main(String args[]) { // Create object of this class BinarySearch ob = new BinarySearch(); // Given array arr[] int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; int x = 10; // Function Call int result = ob.binarySearch(arr, x); if (result == -1) System.out.println(\"Element not present\"); else System.out.println(\"Element found at index \" + result); }}", "e": 32018, "s": 30732, "text": null }, { "code": null, "e": 32043, "s": 32018, "text": "Element found at index 3" }, { "code": null, "e": 32090, "s": 32045, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 32101, "s": 32092, "text": "sooda367" }, { "code": null, "e": 32122, "s": 32101, "text": "Algorithms-Searching" }, { "code": null, "e": 32136, "s": 32122, "text": "Binary Search" }, { "code": null, "e": 32141, "s": 32136, "text": "Java" }, { "code": null, "e": 32151, "s": 32141, "text": "Searching" }, { "code": null, "e": 32161, "s": 32151, "text": "Searching" }, { "code": null, "e": 32166, "s": 32161, "text": "Java" }, { "code": null, "e": 32180, "s": 32166, "text": "Binary Search" }, { "code": null, "e": 32278, "s": 32180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32293, "s": 32278, "text": "Stream In Java" }, { "code": null, "e": 32312, "s": 32293, "text": "Interfaces in Java" }, { "code": null, "e": 32330, "s": 32312, "text": "ArrayList in Java" }, { "code": null, "e": 32362, "s": 32330, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32382, "s": 32362, "text": "Stack Class in Java" }, { "code": null, "e": 32450, "s": 32382, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32498, "s": 32450, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 32522, "s": 32498, "text": "Find the Missing Number" }, { "code": null, "e": 32578, "s": 32522, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Design the Data Structures(classes and objects)for a generic deck of cards - GeeksforGeeks
01 Apr, 2019 Design the data structures for a generic deck of cards Explain how you would sub-class it to implement particular card games and how you would subclass the data structures to implement blackjack. Solution: First, we need to recognize that a “generic” deck of cards can mean many things. Generic could mean a standard deck of cards that can play a poker-like game, or it could even stretch to Uno or Baseball cards. To implement particular card games Let’s assume that the deck is a standard 52-card set like you might see used in a blackjack or poker game. If so, the design might look like this: The structure is clear here: a deck contains four suits and a suit contains 13 card. Each card has a numerical value from 1 to 13. If you think about a card game, different games differ from ways of dealing cards and putting cards back in. So we can have a set of abstract methods inside the class ‘Deck’ to allow sub-class implements its own way of dealing. The class diagram I draw is here: Below is C++ implementation of the idea. /*1. Investigation on an individual card instead of a collection of cards, focus on a card's state and interface.2. A card game has its own specific constrain and requirement on cards, such that a generic card cannot satisfy a blackjack card3. Player manage multiple cards */ #include <bits/stdc++.h>using namespace std; namespace SUIT {enum Enum { SPADE, HEART, CLUB, DIAMOND};}; class Card {private: SUIT::Enum s; int v; public: virtual SUIT::Enum suit() const { return s; }; virtual int val() const { return v; }; Card(int val, SUIT::Enum suit) : s(suit), v(val){};}; class BlackJackCard : public Card {public: virtual int val() { int v = Card::val(); if (v < 10) return v; return 10; } BlackJackCard(int val, SUIT::Enum suit) : Card(val, suit){};}; class player {private: int id; int bet; set<int> points; vector<BlackJackCard*> bjcs; bool addPoint(set<int>& amp; points, BlackJackCard * card) { if (points.empty()) { points.insert(card->val()); if (card->val() == 1) points.insert(11); } else { /* Set elements are ALWAYS CONST, they can't be modified once inserted. */ set<int> tmp; for (auto it = points.begin(); it != points.end(); ++it) { tmp.insert(*it + card->val()); if (card->val() == 1) tmp.insert(*it + 11); } points = tmp; } } void getPoints() { cout << "You All Possible Points : " << endl; for (auto it = points.begin(); it != points.end(); ++it) { cout << *it << endl; } }; int getMinPoints() { /* set is implemented by commonly BST, so else are in order!!! learn to use lower_bound() and upper_bound() "they allow the direct iteration on subsets based on their order." which gives us another option to find min. preferable */ // return *(points.lower_bound(0)); return *(points.begin()); }; void printCards() { cout << "You Cards : " << endl; for (auto it = bjcs.begin(); it != bjcs.end(); ++it) { cout << (*it)->val() << endl; } } public: player(int i, int j) : id(i), bet(j) { bjcs.push_back(new BlackJackCard(rand() % 13 + 1, SUIT::SPADE)); bjcs.push_back(new BlackJackCard(rand() % 13 + 1, SUIT::SPADE)); addPoint(points, bjcs[0]); addPoint(points, bjcs[1]); }; void getAnotherCard() { for (set<int>::iterator it = points.begin(); it != points.end(); ++it) { /* predefined strategy for the player */ if (*it <= 21 && 21 - *it <= 4) { printCards(); getPoints(); cout << "Stand" << endl; exit(1); } } bjcs.push_back(new BlackJackCard(rand() % 13 + 1, SUIT::SPADE)); addPoint(points, bjcs.back()); if (getMinPoints() > 21) { printCards(); getPoints(); cout << "Busted" << endl; exit(2); } }; virtual ~player() { for (auto it = bjcs.begin(); it != bjcs.end(); ++it) { delete *it; } };};// Driver codeint main(){ srand(time(NULL)); player p(1, 1000); p.getAnotherCard(); p.getAnotherCard(); p.getAnotherCard(); return 0;} Output: You Cards : 10 10 You All Possible Points : 20 Stand To implement Blackjack. Note: Now, let’s say we’re building a blackjack game, so we need to know the value of the cards. Face cards are 10 and an ace is 11 (most of the time, but that’s the job of the Hand class, not the following class). At the start of a blackjack game, the players and the dealer receive two cards each. The players’ cards are normally dealt face up, while the dealer has one face down (called the hole card) and one face up. The best possible blackjack hand is an opening deal of an ace with any ten-point card. This is called a “blackjack”, or a natural 21, and the player holding this automatically wins unless the dealer also has a blackjack. If a player and the dealer each have a blackjack, the result is a push for that player. If the dealer has a blackjack, all players not holding a blackjack lose. Main logic of Blackjack in Java public class BlackJackHand extends Hand<BlackJackCard> { /* There are multiple possible scores for a blackjack hand, since aces have 3 * multiple values. Return the highest possible score that's under 21, or the 4 * lowest score that's over. */ public int score() { Arraylist<Integer> scores = possibleScores(); int maxUnder = Integer.MIN_VALUE; int minOver = Integer.MAX_VALUE; for (int score : scores) { if (score > 21 & amp; &score < minOver) { minOver = score; } else if (score <= 21 & amp; &score > maxUnder) { maxUnder = score; } } return maxUnder Integer.MIN_VALUE ? minOver maxUnder; } /* return a list of all possible scores this hand could have (evaluating each * ace as both 1 and 11 */ private Arraylist<Integer> possibleScores() { ... } public boolean busted() { return score() > 21; } public boolean is21() { return score() == 21; } public boolean isBlackJack() { ... }} public class BlackJackCard extends Card { public BlackJackCard(int c, Suit s) { super(c, s); } public int value() { if (isAce()) return 1; else if (faceValue >= 11 & amp; &faceValue <= 13) return 10; else return faceValue; } public int minValue() { if (isAce()) return 1; else return value(); } public int maxValue() { if (isAce()) return 11; else return value(); } public boolean isAce() { return faceValue == 1; } public boolean isFaceCard() { return faceValue >= 11 & amp; &faceValue <= 13; }} /* This is just one way of handling aces. We could, alternatively, create a classof type Ace that extends BlackJackCard. */ References :https://www.careercup.com/question?id=2983http://stackoverflow.com/questions/37363008/a-singleton-class-to-design-a-generic-deck-of-card This article is contributed by Mr. Somesh Awasthi. 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. AnamikaPandey2 Amazon Microsoft Design Pattern Amazon Microsoft Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Command Pattern Strategy Pattern | Set 1 (Introduction) Template Method Design Pattern State Design Pattern Conceptual Model of the Unified Modeling Language (UML) Visitor design pattern Flyweight Design Pattern Difference between Sequence Diagram and Activity Diagram Difference Between Architectural Style, Architectural Patterns and Design Patterns
[ { "code": null, "e": 24247, "s": 24219, "text": "\n01 Apr, 2019" }, { "code": null, "e": 24443, "s": 24247, "text": "Design the data structures for a generic deck of cards Explain how you would sub-class it to implement particular card games and how you would subclass the data structures to implement blackjack." }, { "code": null, "e": 24453, "s": 24443, "text": "Solution:" }, { "code": null, "e": 24662, "s": 24453, "text": "First, we need to recognize that a “generic” deck of cards can mean many things. Generic could mean a standard deck of cards that can play a poker-like game, or it could even stretch to Uno or Baseball cards." }, { "code": null, "e": 24697, "s": 24662, "text": "To implement particular card games" }, { "code": null, "e": 24844, "s": 24697, "text": "Let’s assume that the deck is a standard 52-card set like you might see used in a blackjack or poker game. If so, the design might look like this:" }, { "code": null, "e": 25237, "s": 24844, "text": "The structure is clear here: a deck contains four suits and a suit contains 13 card. Each card has a numerical value from 1 to 13. If you think about a card game, different games differ from ways of dealing cards and putting cards back in. So we can have a set of abstract methods inside the class ‘Deck’ to allow sub-class implements its own way of dealing. The class diagram I draw is here:" }, { "code": null, "e": 25280, "s": 25239, "text": "Below is C++ implementation of the idea." }, { "code": "/*1. Investigation on an individual card instead of a collection of cards, focus on a card's state and interface.2. A card game has its own specific constrain and requirement on cards, such that a generic card cannot satisfy a blackjack card3. Player manage multiple cards */ #include <bits/stdc++.h>using namespace std; namespace SUIT {enum Enum { SPADE, HEART, CLUB, DIAMOND};}; class Card {private: SUIT::Enum s; int v; public: virtual SUIT::Enum suit() const { return s; }; virtual int val() const { return v; }; Card(int val, SUIT::Enum suit) : s(suit), v(val){};}; class BlackJackCard : public Card {public: virtual int val() { int v = Card::val(); if (v < 10) return v; return 10; } BlackJackCard(int val, SUIT::Enum suit) : Card(val, suit){};}; class player {private: int id; int bet; set<int> points; vector<BlackJackCard*> bjcs; bool addPoint(set<int>& amp; points, BlackJackCard * card) { if (points.empty()) { points.insert(card->val()); if (card->val() == 1) points.insert(11); } else { /* Set elements are ALWAYS CONST, they can't be modified once inserted. */ set<int> tmp; for (auto it = points.begin(); it != points.end(); ++it) { tmp.insert(*it + card->val()); if (card->val() == 1) tmp.insert(*it + 11); } points = tmp; } } void getPoints() { cout << \"You All Possible Points : \" << endl; for (auto it = points.begin(); it != points.end(); ++it) { cout << *it << endl; } }; int getMinPoints() { /* set is implemented by commonly BST, so else are in order!!! learn to use lower_bound() and upper_bound() \"they allow the direct iteration on subsets based on their order.\" which gives us another option to find min. preferable */ // return *(points.lower_bound(0)); return *(points.begin()); }; void printCards() { cout << \"You Cards : \" << endl; for (auto it = bjcs.begin(); it != bjcs.end(); ++it) { cout << (*it)->val() << endl; } } public: player(int i, int j) : id(i), bet(j) { bjcs.push_back(new BlackJackCard(rand() % 13 + 1, SUIT::SPADE)); bjcs.push_back(new BlackJackCard(rand() % 13 + 1, SUIT::SPADE)); addPoint(points, bjcs[0]); addPoint(points, bjcs[1]); }; void getAnotherCard() { for (set<int>::iterator it = points.begin(); it != points.end(); ++it) { /* predefined strategy for the player */ if (*it <= 21 && 21 - *it <= 4) { printCards(); getPoints(); cout << \"Stand\" << endl; exit(1); } } bjcs.push_back(new BlackJackCard(rand() % 13 + 1, SUIT::SPADE)); addPoint(points, bjcs.back()); if (getMinPoints() > 21) { printCards(); getPoints(); cout << \"Busted\" << endl; exit(2); } }; virtual ~player() { for (auto it = bjcs.begin(); it != bjcs.end(); ++it) { delete *it; } };};// Driver codeint main(){ srand(time(NULL)); player p(1, 1000); p.getAnotherCard(); p.getAnotherCard(); p.getAnotherCard(); return 0;}", "e": 28828, "s": 25280, "text": null }, { "code": null, "e": 28836, "s": 28828, "text": "Output:" }, { "code": null, "e": 28892, "s": 28836, "text": "You Cards : \n10\n10\nYou All Possible Points : \n20\nStand\n" }, { "code": null, "e": 28916, "s": 28892, "text": "To implement Blackjack." }, { "code": null, "e": 29131, "s": 28916, "text": "Note: Now, let’s say we’re building a blackjack game, so we need to know the value of the cards. Face cards are 10 and an ace is 11 (most of the time, but that’s the job of the Hand class, not the following class)." }, { "code": null, "e": 29338, "s": 29131, "text": "At the start of a blackjack game, the players and the dealer receive two cards each. The players’ cards are normally dealt face up, while the dealer has one face down (called the hole card) and one face up." }, { "code": null, "e": 29720, "s": 29338, "text": "The best possible blackjack hand is an opening deal of an ace with any ten-point card. This is called a “blackjack”, or a natural 21, and the player holding this automatically wins unless the dealer also has a blackjack. If a player and the dealer each have a blackjack, the result is a push for that player. If the dealer has a blackjack, all players not holding a blackjack lose." }, { "code": null, "e": 29754, "s": 29722, "text": "Main logic of Blackjack in Java" }, { "code": "public class BlackJackHand extends Hand<BlackJackCard> { /* There are multiple possible scores for a blackjack hand, since aces have 3 * multiple values. Return the highest possible score that's under 21, or the 4 * lowest score that's over. */ public int score() { Arraylist<Integer> scores = possibleScores(); int maxUnder = Integer.MIN_VALUE; int minOver = Integer.MAX_VALUE; for (int score : scores) { if (score > 21 & amp; &score < minOver) { minOver = score; } else if (score <= 21 & amp; &score > maxUnder) { maxUnder = score; } } return maxUnder Integer.MIN_VALUE ? minOver maxUnder; } /* return a list of all possible scores this hand could have (evaluating each * ace as both 1 and 11 */ private Arraylist<Integer> possibleScores() { ... } public boolean busted() { return score() > 21; } public boolean is21() { return score() == 21; } public boolean isBlackJack() { ... }} public class BlackJackCard extends Card { public BlackJackCard(int c, Suit s) { super(c, s); } public int value() { if (isAce()) return 1; else if (faceValue >= 11 & amp; &faceValue <= 13) return 10; else return faceValue; } public int minValue() { if (isAce()) return 1; else return value(); } public int maxValue() { if (isAce()) return 11; else return value(); } public boolean isAce() { return faceValue == 1; } public boolean isFaceCard() { return faceValue >= 11 & amp; &faceValue <= 13; }} /* This is just one way of handling aces. We could, alternatively, create a classof type Ace that extends BlackJackCard. */", "e": 31618, "s": 29754, "text": null }, { "code": null, "e": 31767, "s": 31618, "text": "References :https://www.careercup.com/question?id=2983http://stackoverflow.com/questions/37363008/a-singleton-class-to-design-a-generic-deck-of-card" }, { "code": null, "e": 32073, "s": 31767, "text": "This article is contributed by Mr. Somesh Awasthi. 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": 32198, "s": 32073, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32213, "s": 32198, "text": "AnamikaPandey2" }, { "code": null, "e": 32220, "s": 32213, "text": "Amazon" }, { "code": null, "e": 32230, "s": 32220, "text": "Microsoft" }, { "code": null, "e": 32245, "s": 32230, "text": "Design Pattern" }, { "code": null, "e": 32252, "s": 32245, "text": "Amazon" }, { "code": null, "e": 32262, "s": 32252, "text": "Microsoft" }, { "code": null, "e": 32360, "s": 32262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32369, "s": 32360, "text": "Comments" }, { "code": null, "e": 32382, "s": 32369, "text": "Old Comments" }, { "code": null, "e": 32398, "s": 32382, "text": "Command Pattern" }, { "code": null, "e": 32438, "s": 32398, "text": "Strategy Pattern | Set 1 (Introduction)" }, { "code": null, "e": 32469, "s": 32438, "text": "Template Method Design Pattern" }, { "code": null, "e": 32490, "s": 32469, "text": "State Design Pattern" }, { "code": null, "e": 32546, "s": 32490, "text": "Conceptual Model of the Unified Modeling Language (UML)" }, { "code": null, "e": 32569, "s": 32546, "text": "Visitor design pattern" }, { "code": null, "e": 32594, "s": 32569, "text": "Flyweight Design Pattern" }, { "code": null, "e": 32651, "s": 32594, "text": "Difference between Sequence Diagram and Activity Diagram" } ]
C Program for Insertion Sort - GeeksforGeeks
23 Feb, 2022 Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. C // C program for insertion sort#include <math.h>#include <stdio.h> /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // A utility function to print an array of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} /* Driver program to test insertion sort */int main(){ int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;} 5 6 11 12 13 Please refer complete article on Insertion Sort for more details! simmytarika5 C Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C
[ { "code": null, "e": 24641, "s": 24613, "text": "\n23 Feb, 2022" }, { "code": null, "e": 24742, "s": 24641, "text": "Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. " }, { "code": null, "e": 24744, "s": 24742, "text": "C" }, { "code": "// C program for insertion sort#include <math.h>#include <stdio.h> /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // A utility function to print an array of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} /* Driver program to test insertion sort */int main(){ int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;}", "e": 25624, "s": 24744, "text": null }, { "code": null, "e": 25637, "s": 25624, "text": "5 6 11 12 13" }, { "code": null, "e": 25706, "s": 25639, "text": "Please refer complete article on Insertion Sort for more details! " }, { "code": null, "e": 25719, "s": 25706, "text": "simmytarika5" }, { "code": null, "e": 25730, "s": 25719, "text": "C Programs" }, { "code": null, "e": 25738, "s": 25730, "text": "Sorting" }, { "code": null, "e": 25746, "s": 25738, "text": "Sorting" }, { "code": null, "e": 25844, "s": 25746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25853, "s": 25844, "text": "Comments" }, { "code": null, "e": 25866, "s": 25853, "text": "Old Comments" }, { "code": null, "e": 25907, "s": 25866, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 25938, "s": 25907, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 25979, "s": 25938, "text": "C program to find the length of a string" }, { "code": null, "e": 26013, "s": 25979, "text": "Exit codes in C/C++ with Examples" } ]
Design and Implement Calculator using jQuery - GeeksforGeeks
19 Feb, 2020 In this post, we are going to implement an easy to build calculator using jQuery and using eval() function. For the sake of simplicity, our calculator will only take input from the buttons on the screen only. Prerequisites:Basic knowledge of front-end technologies like HTML, CSS, JavaScript, jQuery and Bootstrap. Procedure: Developing the Calculator face:Here, we will make use of bootstrap to save time developing the calculator face. The following are the requirements that are needed to be fulfilled while doing the same:Primary (Expression) ScreenSecondary (Result) ScreenInput buttons : Numbers, operators for evaluation etc.<!-- Initialize the layout --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> + </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> - </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> * </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> / </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ( </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ) </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> AC </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> = </div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div></body> </html>Output:Implement functionality of expression screen:Now we will implement the following steps accordingly for expression screen to work fine:Adding button’s value when the screen is pressed.Implementing backspace for input.Clear expression screen (AC)<!-- Script for Expression Screen --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> + </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> - </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> * </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not" id="backspace"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> / </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ( </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ) </div> </div> <div class="col-sm-3"> <div class="design not" id="allClear" style="background-color:red;"> AC </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> = </div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(".design").click(function() { if (!$(this).hasClass("not")) { if ($("#expression").val() == 0) $("#expression").val($(this).text()); else $("#expression").val($( "#expression").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $("#expression").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $("#expression").val(value.slice(0, value.length - 1)); if (value.length == 1) $("#expression").val("0"); }); }); // All Clear $("#allClear").click(function() { $("#expression").val("0"); }); </script></body> </html>Output:Evaluate the result:For this we need to add the following steps in sequenced manner:Extract the value of expression screen.Evaluate the expression screen.Report errors in the output(if any)Clear expression screen and append the output on the result screen.Whenever, other input button is used, clear both the primary and secondary screen.Final result:<!-- jQuery Calculator --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> +</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> -</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> *</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not" id="backspace"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> /</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> (</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> )</div> </div> <div class="col-sm-3"> <div class="design not" id="allClear" style="background-color:red;"> AC</div> </div> <div class="col-sm-3"> <div class="design not" id="equals" style="background-color:red;"> =</div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(".design").click(function() { if (!$(this).hasClass("not")) { if ($("#expression").val() == 0) $("#expression").val($(this).text()); else $("#expression").val($("#expression").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $("#expression").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $("#expression").val(value.slice(0, value.length - 1)); if (value.length == 1) $("#expression").val("0"); }); }); // All Clear $("#allClear").click(function() { $("#expression").val("0"); $("#result").val("0"); }); //Evalution $("#equals").click(function() { var result; //Check for syntax error try { result = (eval(($("#expression").val()))); } catch (e) { if (e instanceof SyntaxError) { alert("Error! Resetting values."); $("#expression").val("0"); $("#result").val("0"); } if (e instanceof TypeError) { alert("Error! Resetting values."); $("#expression").val("0"); $("#result").val("0"); } } // Append if the result is correct $("#result").val(result); $("#expression").val("0"); }); </script></body> </html>Output:With Error: (Not a valid expression since multiply sign was needed for operation)Without Error:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes arrow_drop_upSave Developing the Calculator face:Here, we will make use of bootstrap to save time developing the calculator face. The following are the requirements that are needed to be fulfilled while doing the same:Primary (Expression) ScreenSecondary (Result) ScreenInput buttons : Numbers, operators for evaluation etc.<!-- Initialize the layout --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> + </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> - </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> * </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> / </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ( </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ) </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> AC </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> = </div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div></body> </html>Output: Primary (Expression) Screen Secondary (Result) Screen Input buttons : Numbers, operators for evaluation etc. <!-- Initialize the layout --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> + </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> - </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> * </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> / </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ( </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ) </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> AC </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> = </div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div></body> </html> Output: Implement functionality of expression screen:Now we will implement the following steps accordingly for expression screen to work fine:Adding button’s value when the screen is pressed.Implementing backspace for input.Clear expression screen (AC)<!-- Script for Expression Screen --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> + </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> - </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> * </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not" id="backspace"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> / </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ( </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ) </div> </div> <div class="col-sm-3"> <div class="design not" id="allClear" style="background-color:red;"> AC </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> = </div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(".design").click(function() { if (!$(this).hasClass("not")) { if ($("#expression").val() == 0) $("#expression").val($(this).text()); else $("#expression").val($( "#expression").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $("#expression").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $("#expression").val(value.slice(0, value.length - 1)); if (value.length == 1) $("#expression").val("0"); }); }); // All Clear $("#allClear").click(function() { $("#expression").val("0"); }); </script></body> </html>Output: Adding button’s value when the screen is pressed. Implementing backspace for input. Clear expression screen (AC) <!-- Script for Expression Screen --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> + </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> - </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> * </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not" id="backspace"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> / </div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ( </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> ) </div> </div> <div class="col-sm-3"> <div class="design not" id="allClear" style="background-color:red;"> AC </div> </div> <div class="col-sm-3"> <div class="design not" style="background-color:red;"> = </div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(".design").click(function() { if (!$(this).hasClass("not")) { if ($("#expression").val() == 0) $("#expression").val($(this).text()); else $("#expression").val($( "#expression").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $("#expression").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $("#expression").val(value.slice(0, value.length - 1)); if (value.length == 1) $("#expression").val("0"); }); }); // All Clear $("#allClear").click(function() { $("#expression").val("0"); }); </script></body> </html> Output: Evaluate the result:For this we need to add the following steps in sequenced manner:Extract the value of expression screen.Evaluate the expression screen.Report errors in the output(if any)Clear expression screen and append the output on the result screen.Whenever, other input button is used, clear both the primary and secondary screen.Final result:<!-- jQuery Calculator --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> +</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> -</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> *</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not" id="backspace"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> /</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> (</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> )</div> </div> <div class="col-sm-3"> <div class="design not" id="allClear" style="background-color:red;"> AC</div> </div> <div class="col-sm-3"> <div class="design not" id="equals" style="background-color:red;"> =</div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(".design").click(function() { if (!$(this).hasClass("not")) { if ($("#expression").val() == 0) $("#expression").val($(this).text()); else $("#expression").val($("#expression").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $("#expression").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $("#expression").val(value.slice(0, value.length - 1)); if (value.length == 1) $("#expression").val("0"); }); }); // All Clear $("#allClear").click(function() { $("#expression").val("0"); $("#result").val("0"); }); //Evalution $("#equals").click(function() { var result; //Check for syntax error try { result = (eval(($("#expression").val()))); } catch (e) { if (e instanceof SyntaxError) { alert("Error! Resetting values."); $("#expression").val("0"); $("#result").val("0"); } if (e instanceof TypeError) { alert("Error! Resetting values."); $("#expression").val("0"); $("#result").val("0"); } } // Append if the result is correct $("#result").val(result); $("#expression").val("0"); }); </script></body> </html>Output:With Error: (Not a valid expression since multiply sign was needed for operation)Without Error:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes arrow_drop_upSave Extract the value of expression screen. Evaluate the expression screen. Report errors in the output(if any) Clear expression screen and append the output on the result screen. Whenever, other input button is used, clear both the primary and secondary screen. Final result: <!-- jQuery Calculator --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type="text"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style="background-color:#f9f9fa;"> <div class="row"> <div class="col-sm-2 col-md-4"> </div> <div class="col-sm-8 col-md-4"> <!-- Calculator UI --> <br> <br> <br> <br> <div class="container calculator"> <div class="form-input"> <input type="text" class="form-control input-lg" id="expression" value="0" disabled> <input type="text" class="form-control input-xs" id="result" value="0" disabled> </div> <br> <br> <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <div class="design">1</div> </div> <div class="col-sm-3"> <div class="design">2</div> </div> <div class="col-sm-3"> <div class="design">3</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> +</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">4</div> </div> <div class="col-sm-3"> <div class="design">5</div> </div> <div class="col-sm-3"> <div class="design">6</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> -</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">7</div> </div> <div class="col-sm-3"> <div class="design">8</div> </div> <div class="col-sm-3"> <div class="design">9</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> *</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design">0</div> </div> <div class="col-sm-3"> <div class="design">.</div> </div> <div class="col-sm-3"> <div class="design not" id="backspace"> ? </div> </div> <div class="col-sm-3"> <div class="design" style="background-color:orange;"> /</div> </div> </div> <div class="row"> <div class="col-sm-3"> <div class="design" style="background-color:red;"> (</div> </div> <div class="col-sm-3"> <div class="design" style="background-color:red;"> )</div> </div> <div class="col-sm-3"> <div class="design not" id="allClear" style="background-color:red;"> AC</div> </div> <div class="col-sm-3"> <div class="design not" id="equals" style="background-color:red;"> =</div> </div> </div> </div> </div> </div> <div class="col-sm-2 col-md-4"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(".design").click(function() { if (!$(this).hasClass("not")) { if ($("#expression").val() == 0) $("#expression").val($(this).text()); else $("#expression").val($("#expression").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $("#expression").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $("#expression").val(value.slice(0, value.length - 1)); if (value.length == 1) $("#expression").val("0"); }); }); // All Clear $("#allClear").click(function() { $("#expression").val("0"); $("#result").val("0"); }); //Evalution $("#equals").click(function() { var result; //Check for syntax error try { result = (eval(($("#expression").val()))); } catch (e) { if (e instanceof SyntaxError) { alert("Error! Resetting values."); $("#expression").val("0"); $("#result").val("0"); } if (e instanceof TypeError) { alert("Error! Resetting values."); $("#expression").val("0"); $("#result").val("0"); } } // Append if the result is correct $("#result").val(result); $("#expression").val("0"); }); </script></body> </html> Output: With Error: (Not a valid expression since multiply sign was needed for operation)Without Error: With Error: (Not a valid expression since multiply sign was needed for operation) Without Error: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-Misc Bootstrap CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? Create a Homepage for Restaurant using HTML , CSS and Bootstrap Difference between Bootstrap 4 and Bootstrap 5 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24463, "s": 24435, "text": "\n19 Feb, 2020" }, { "code": null, "e": 24672, "s": 24463, "text": "In this post, we are going to implement an easy to build calculator using jQuery and using eval() function. For the sake of simplicity, our calculator will only take input from the buttons on the screen only." }, { "code": null, "e": 24778, "s": 24672, "text": "Prerequisites:Basic knowledge of front-end technologies like HTML, CSS, JavaScript, jQuery and Bootstrap." }, { "code": null, "e": 24789, "s": 24778, "text": "Procedure:" }, { "code": null, "e": 47786, "s": 24789, "text": "Developing the Calculator face:Here, we will make use of bootstrap to save time developing the calculator face. The following are the requirements that are needed to be fulfilled while doing the same:Primary (Expression) ScreenSecondary (Result) ScreenInput buttons : Numbers, operators for evaluation etc.<!-- Initialize the layout --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> + </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> - </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> * </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> / </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ( </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ) </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> AC </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> = </div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div></body> </html>Output:Implement functionality of expression screen:Now we will implement the following steps accordingly for expression screen to work fine:Adding button’s value when the screen is pressed.Implementing backspace for input.Clear expression screen (AC)<!-- Script for Expression Screen --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> + </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> - </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> * </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"backspace\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> / </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ( </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ) </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"allClear\" style=\"background-color:red;\"> AC </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> = </div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(\".design\").click(function() { if (!$(this).hasClass(\"not\")) { if ($(\"#expression\").val() == 0) $(\"#expression\").val($(this).text()); else $(\"#expression\").val($( \"#expression\").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $(\"#expression\").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $(\"#expression\").val(value.slice(0, value.length - 1)); if (value.length == 1) $(\"#expression\").val(\"0\"); }); }); // All Clear $(\"#allClear\").click(function() { $(\"#expression\").val(\"0\"); }); </script></body> </html>Output:Evaluate the result:For this we need to add the following steps in sequenced manner:Extract the value of expression screen.Evaluate the expression screen.Report errors in the output(if any)Clear expression screen and append the output on the result screen.Whenever, other input button is used, clear both the primary and secondary screen.Final result:<!-- jQuery Calculator --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> +</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> -</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> *</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"backspace\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> /</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> (</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> )</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"allClear\" style=\"background-color:red;\"> AC</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"equals\" style=\"background-color:red;\"> =</div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(\".design\").click(function() { if (!$(this).hasClass(\"not\")) { if ($(\"#expression\").val() == 0) $(\"#expression\").val($(this).text()); else $(\"#expression\").val($(\"#expression\").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $(\"#expression\").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $(\"#expression\").val(value.slice(0, value.length - 1)); if (value.length == 1) $(\"#expression\").val(\"0\"); }); }); // All Clear $(\"#allClear\").click(function() { $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); }); //Evalution $(\"#equals\").click(function() { var result; //Check for syntax error try { result = (eval(($(\"#expression\").val()))); } catch (e) { if (e instanceof SyntaxError) { alert(\"Error! Resetting values.\"); $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); } if (e instanceof TypeError) { alert(\"Error! Resetting values.\"); $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); } } // Append if the result is correct $(\"#result\").val(result); $(\"#expression\").val(\"0\"); }); </script></body> </html>Output:With Error: (Not a valid expression since multiply sign was needed for operation)Without Error:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 54445, "s": 47786, "text": "Developing the Calculator face:Here, we will make use of bootstrap to save time developing the calculator face. The following are the requirements that are needed to be fulfilled while doing the same:Primary (Expression) ScreenSecondary (Result) ScreenInput buttons : Numbers, operators for evaluation etc.<!-- Initialize the layout --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> + </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> - </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> * </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> / </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ( </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ) </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> AC </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> = </div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div></body> </html>Output:" }, { "code": null, "e": 54473, "s": 54445, "text": "Primary (Expression) Screen" }, { "code": null, "e": 54499, "s": 54473, "text": "Secondary (Result) Screen" }, { "code": null, "e": 54554, "s": 54499, "text": "Input buttons : Numbers, operators for evaluation etc." }, { "code": "<!-- Initialize the layout --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> + </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> - </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> * </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> / </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ( </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ) </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> AC </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> = </div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div></body> </html>", "e": 60900, "s": 54554, "text": null }, { "code": null, "e": 60908, "s": 60900, "text": "Output:" }, { "code": null, "e": 68601, "s": 60908, "text": "Implement functionality of expression screen:Now we will implement the following steps accordingly for expression screen to work fine:Adding button’s value when the screen is pressed.Implementing backspace for input.Clear expression screen (AC)<!-- Script for Expression Screen --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> + </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> - </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> * </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"backspace\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> / </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ( </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ) </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"allClear\" style=\"background-color:red;\"> AC </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> = </div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(\".design\").click(function() { if (!$(this).hasClass(\"not\")) { if ($(\"#expression\").val() == 0) $(\"#expression\").val($(this).text()); else $(\"#expression\").val($( \"#expression\").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $(\"#expression\").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $(\"#expression\").val(value.slice(0, value.length - 1)); if (value.length == 1) $(\"#expression\").val(\"0\"); }); }); // All Clear $(\"#allClear\").click(function() { $(\"#expression\").val(\"0\"); }); </script></body> </html>Output:" }, { "code": null, "e": 68651, "s": 68601, "text": "Adding button’s value when the screen is pressed." }, { "code": null, "e": 68685, "s": 68651, "text": "Implementing backspace for input." }, { "code": null, "e": 68714, "s": 68685, "text": "Clear expression screen (AC)" }, { "code": "<!-- Script for Expression Screen --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> + </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> - </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> * </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"backspace\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> / </div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ( </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> ) </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"allClear\" style=\"background-color:red;\"> AC </div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" style=\"background-color:red;\"> = </div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(\".design\").click(function() { if (!$(this).hasClass(\"not\")) { if ($(\"#expression\").val() == 0) $(\"#expression\").val($(this).text()); else $(\"#expression\").val($( \"#expression\").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $(\"#expression\").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $(\"#expression\").val(value.slice(0, value.length - 1)); if (value.length == 1) $(\"#expression\").val(\"0\"); }); }); // All Clear $(\"#allClear\").click(function() { $(\"#expression\").val(\"0\"); }); </script></body> </html>", "e": 76156, "s": 68714, "text": null }, { "code": null, "e": 76164, "s": 76156, "text": "Output:" }, { "code": null, "e": 84811, "s": 76164, "text": "Evaluate the result:For this we need to add the following steps in sequenced manner:Extract the value of expression screen.Evaluate the expression screen.Report errors in the output(if any)Clear expression screen and append the output on the result screen.Whenever, other input button is used, clear both the primary and secondary screen.Final result:<!-- jQuery Calculator --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> +</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> -</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> *</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"backspace\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> /</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> (</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> )</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"allClear\" style=\"background-color:red;\"> AC</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"equals\" style=\"background-color:red;\"> =</div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(\".design\").click(function() { if (!$(this).hasClass(\"not\")) { if ($(\"#expression\").val() == 0) $(\"#expression\").val($(this).text()); else $(\"#expression\").val($(\"#expression\").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $(\"#expression\").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $(\"#expression\").val(value.slice(0, value.length - 1)); if (value.length == 1) $(\"#expression\").val(\"0\"); }); }); // All Clear $(\"#allClear\").click(function() { $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); }); //Evalution $(\"#equals\").click(function() { var result; //Check for syntax error try { result = (eval(($(\"#expression\").val()))); } catch (e) { if (e instanceof SyntaxError) { alert(\"Error! Resetting values.\"); $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); } if (e instanceof TypeError) { alert(\"Error! Resetting values.\"); $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); } } // Append if the result is correct $(\"#result\").val(result); $(\"#expression\").val(\"0\"); }); </script></body> </html>Output:With Error: (Not a valid expression since multiply sign was needed for operation)Without Error:Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 84851, "s": 84811, "text": "Extract the value of expression screen." }, { "code": null, "e": 84883, "s": 84851, "text": "Evaluate the expression screen." }, { "code": null, "e": 84919, "s": 84883, "text": "Report errors in the output(if any)" }, { "code": null, "e": 84987, "s": 84919, "text": "Clear expression screen and append the output on the result screen." }, { "code": null, "e": 85070, "s": 84987, "text": "Whenever, other input button is used, clear both the primary and secondary screen." }, { "code": null, "e": 85084, "s": 85070, "text": "Final result:" }, { "code": "<!-- jQuery Calculator --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> .calculator { padding: 4px; margin: 4px; background-color: #3a4655; width: 100%; height: auto; /* Box shadow for different browsers */ -webkit-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 8px 4px rgba(0, 0, 0, 0.75); } .form-control { border: 0px solid transparent; padding: 0px; border: 0px; border-radius: 0px; } input[type=\"text\"]:disabled { background-color: white; text-align: right; padding: 8px; } .design { text-align: center; border-radius: 4px; width: 100%; height: auto; color: white; padding: 4px; margin: 4px; background-color: #2a2e4b; } </style></head> <body style=\"background-color:#f9f9fa;\"> <div class=\"row\"> <div class=\"col-sm-2 col-md-4\"> </div> <div class=\"col-sm-8 col-md-4\"> <!-- Calculator UI --> <br> <br> <br> <br> <div class=\"container calculator\"> <div class=\"form-input\"> <input type=\"text\" class=\"form-control input-lg\" id=\"expression\" value=\"0\" disabled> <input type=\"text\" class=\"form-control input-xs\" id=\"result\" value=\"0\" disabled> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">1</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">2</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">3</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> +</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">4</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">5</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">6</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> -</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">7</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">8</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">9</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> *</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\">0</div> </div> <div class=\"col-sm-3\"> <div class=\"design\">.</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"backspace\"> ? </div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:orange;\"> /</div> </div> </div> <div class=\"row\"> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> (</div> </div> <div class=\"col-sm-3\"> <div class=\"design\" style=\"background-color:red;\"> )</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"allClear\" style=\"background-color:red;\"> AC</div> </div> <div class=\"col-sm-3\"> <div class=\"design not\" id=\"equals\" style=\"background-color:red;\"> =</div> </div> </div> </div> </div> </div> <div class=\"col-sm-2 col-md-4\"> </div> </div> <script> $(document).ready(function() { //Adding to the expression $(\".design\").click(function() { if (!$(this).hasClass(\"not\")) { if ($(\"#expression\").val() == 0) $(\"#expression\").val($(this).text()); else $(\"#expression\").val($(\"#expression\").val() + $(this).text()); } }); //Backspace $('#backspace').click(function() { var value = $(\"#expression\").val(); if (!(parseInt(parseFloat(value)) == 0 && value.length == 1)) $(\"#expression\").val(value.slice(0, value.length - 1)); if (value.length == 1) $(\"#expression\").val(\"0\"); }); }); // All Clear $(\"#allClear\").click(function() { $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); }); //Evalution $(\"#equals\").click(function() { var result; //Check for syntax error try { result = (eval(($(\"#expression\").val()))); } catch (e) { if (e instanceof SyntaxError) { alert(\"Error! Resetting values.\"); $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); } if (e instanceof TypeError) { alert(\"Error! Resetting values.\"); $(\"#expression\").val(\"0\"); $(\"#result\").val(\"0\"); } } // Append if the result is correct $(\"#result\").val(result); $(\"#expression\").val(\"0\"); }); </script></body> </html>", "e": 93107, "s": 85084, "text": null }, { "code": null, "e": 93115, "s": 93107, "text": "Output:" }, { "code": null, "e": 93211, "s": 93115, "text": "With Error: (Not a valid expression since multiply sign was needed for operation)Without Error:" }, { "code": null, "e": 93293, "s": 93211, "text": "With Error: (Not a valid expression since multiply sign was needed for operation)" }, { "code": null, "e": 93308, "s": 93293, "text": "Without Error:" }, { "code": null, "e": 93445, "s": 93308, "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": 93457, "s": 93445, "text": "jQuery-Misc" }, { "code": null, "e": 93467, "s": 93457, "text": "Bootstrap" }, { "code": null, "e": 93471, "s": 93467, "text": "CSS" }, { "code": null, "e": 93476, "s": 93471, "text": "HTML" }, { "code": null, "e": 93483, "s": 93476, "text": "JQuery" }, { "code": null, "e": 93500, "s": 93483, "text": "Web Technologies" }, { "code": null, "e": 93505, "s": 93500, "text": "HTML" }, { "code": null, "e": 93603, "s": 93505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 93612, "s": 93603, "text": "Comments" }, { "code": null, "e": 93625, "s": 93612, "text": "Old Comments" }, { "code": null, "e": 93666, "s": 93625, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 93729, "s": 93666, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 93770, "s": 93729, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 93834, "s": 93770, "text": "Create a Homepage for Restaurant using HTML , CSS and Bootstrap" }, { "code": null, "e": 93881, "s": 93834, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 93943, "s": 93881, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 93993, "s": 93943, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 94051, "s": 93993, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 94099, "s": 94051, "text": "How to update Node.js and NPM to next version ?" } ]
Sum of the first N terms of the series 2, 6, 12, 20, 30.... - GeeksforGeeks
25 Feb, 2021 Given a number N, the task is to find the sum of first N terms of the below series: Sn = 2 + 6 + 12 + 20 + 30 ... upto n terms Examples: Input: N = 2 Output: 8 2 + 6 = 8 Input: N = 4 Output: 40 2 + 6+ 12 + 20 = 40 Approach: Let, the nth term be denoted by tn. This problem can easily be solved by splitting each term as follows : Sn = 2 + 6 + 12 + 20 + 30...... Sn = (1+1^2) + (2+2^2) + (3+3^2) + (4+4^2) +...... Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^2 + 2^2 + 3^2 + 4^2 + ...upto n terms) We observed that Sn can broken down into summation of two series. Hence, the sum of first n terms is given as follows: Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^2 + 2^2 + 3^2 + 4^2 + ...upto n terms) Sn = n*(n + 1)/2 + n*(n + 1)*(2*n + 1)/6 Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to find sum of first n terms#include <bits/stdc++.h>using namespace std; // Function to calculate the sumint calculateSum(int n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver codeint main(){ // number of terms to be // included in the sum int n = 3; // find the Sn cout << "Sum = " << calculateSum(n); return 0;} // Java program to find sum of first n terms import java.util.*;import java.lang.*;import java.io.*;class GFG{ // Function to calculate the sumstatic int calculateSum(int n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver codepublic static void main(String args[]){ // number of terms to be // included in the sum int n = 3; // find the Sn System.out.print("Sum = " + calculateSum(n)); }} # Python program to find sum of# first n terms # Function to calculate the sumdef calculateSum(n): return (n * (n + 1) // 2 + n * (n + 1) * (2 * n + 1) // 6) # Driver code # number of terms to be# included in the sumn = 3 # find the Sumprint("Sum = ", calculateSum(n)) # This code is contributed by# Sanjit_Prasad // C# program to find sum of// first n termsusing System; class GFG{ // Function to calculate the sumstatic int calculateSum(int n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver codepublic static void Main(){ // number of terms to be // included in the sum int n = 3; // find the Sn Console.WriteLine("Sum = " + calculateSum(n));}} // This code is contributed by inder_verma <?php// PHP program to find sum// of first n terms // Function to calculate the sumfunction calculateSum($n){ return $n * ($n + 1) / 2 + $n * ($n + 1) * (2 * $n + 1) / 6;} // Driver code // number of terms to be// included in the sum$n = 3; // find the Snecho "Sum = " , calculateSum($n); // This code is contributed// by inder_verma?> <script> // Javascript program to find sum of first n terms // Function to calculate the sumfunction calculateSum(n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver code // number of terms to be // included in the sum let n = 3; // find the Sn document.write("Sum = " + calculateSum(n)); // This code is contributed by Mayank Tyagi </script> Sum = 20 Sanjit_Prasad tufan_gupta2000 inderDuMCA shubham_singh mayanktyagi1709 series series-sum Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Program to convert a given number to words Program to multiply two matrices Modular multiplicative inverse Program to print prime numbers from 1 to N. Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24612, "s": 24584, "text": "\n25 Feb, 2021" }, { "code": null, "e": 24697, "s": 24612, "text": "Given a number N, the task is to find the sum of first N terms of the below series: " }, { "code": null, "e": 24740, "s": 24697, "text": "Sn = 2 + 6 + 12 + 20 + 30 ... upto n terms" }, { "code": null, "e": 24752, "s": 24740, "text": "Examples: " }, { "code": null, "e": 24831, "s": 24752, "text": "Input: N = 2\nOutput: 8\n2 + 6\n= 8\n\nInput: N = 4 \nOutput: 40\n2 + 6+ 12 + 20\n= 40" }, { "code": null, "e": 24951, "s": 24833, "text": "Approach: Let, the nth term be denoted by tn. This problem can easily be solved by splitting each term as follows : " }, { "code": null, "e": 25117, "s": 24951, "text": "Sn = 2 + 6 + 12 + 20 + 30......\nSn = (1+1^2) + (2+2^2) + (3+3^2) + (4+4^2) +......\nSn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^2 + 2^2 + 3^2 + 4^2 + ...upto n terms)" }, { "code": null, "e": 25238, "s": 25117, "text": "We observed that Sn can broken down into summation of two series. Hence, the sum of first n terms is given as follows: " }, { "code": null, "e": 25362, "s": 25238, "text": "Sn = (1 + 2 + 3 + 4 + ...unto n terms) + (1^2 + 2^2 + 3^2 + 4^2 + ...upto n terms)\nSn = n*(n + 1)/2 + n*(n + 1)*(2*n + 1)/6" }, { "code": null, "e": 25411, "s": 25362, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 25415, "s": 25411, "text": "C++" }, { "code": null, "e": 25420, "s": 25415, "text": "Java" }, { "code": null, "e": 25428, "s": 25420, "text": "Python3" }, { "code": null, "e": 25431, "s": 25428, "text": "C#" }, { "code": null, "e": 25435, "s": 25431, "text": "PHP" }, { "code": null, "e": 25446, "s": 25435, "text": "Javascript" }, { "code": "// C++ program to find sum of first n terms#include <bits/stdc++.h>using namespace std; // Function to calculate the sumint calculateSum(int n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver codeint main(){ // number of terms to be // included in the sum int n = 3; // find the Sn cout << \"Sum = \" << calculateSum(n); return 0;}", "e": 25831, "s": 25446, "text": null }, { "code": "// Java program to find sum of first n terms import java.util.*;import java.lang.*;import java.io.*;class GFG{ // Function to calculate the sumstatic int calculateSum(int n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver codepublic static void main(String args[]){ // number of terms to be // included in the sum int n = 3; // find the Sn System.out.print(\"Sum = \" + calculateSum(n)); }}", "e": 26284, "s": 25831, "text": null }, { "code": "# Python program to find sum of# first n terms # Function to calculate the sumdef calculateSum(n): return (n * (n + 1) // 2 + n * (n + 1) * (2 * n + 1) // 6) # Driver code # number of terms to be# included in the sumn = 3 # find the Sumprint(\"Sum = \", calculateSum(n)) # This code is contributed by# Sanjit_Prasad", "e": 26611, "s": 26284, "text": null }, { "code": "// C# program to find sum of// first n termsusing System; class GFG{ // Function to calculate the sumstatic int calculateSum(int n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver codepublic static void Main(){ // number of terms to be // included in the sum int n = 3; // find the Sn Console.WriteLine(\"Sum = \" + calculateSum(n));}} // This code is contributed by inder_verma", "e": 27068, "s": 26611, "text": null }, { "code": "<?php// PHP program to find sum// of first n terms // Function to calculate the sumfunction calculateSum($n){ return $n * ($n + 1) / 2 + $n * ($n + 1) * (2 * $n + 1) / 6;} // Driver code // number of terms to be// included in the sum$n = 3; // find the Snecho \"Sum = \" , calculateSum($n); // This code is contributed// by inder_verma?>", "e": 27422, "s": 27068, "text": null }, { "code": "<script> // Javascript program to find sum of first n terms // Function to calculate the sumfunction calculateSum(n){ return n * (n + 1) / 2 + n * (n + 1) * (2 * n + 1) / 6;} // Driver code // number of terms to be // included in the sum let n = 3; // find the Sn document.write(\"Sum = \" + calculateSum(n)); // This code is contributed by Mayank Tyagi </script>", "e": 27816, "s": 27422, "text": null }, { "code": null, "e": 27825, "s": 27816, "text": "Sum = 20" }, { "code": null, "e": 27841, "s": 27827, "text": "Sanjit_Prasad" }, { "code": null, "e": 27857, "s": 27841, "text": "tufan_gupta2000" }, { "code": null, "e": 27868, "s": 27857, "text": "inderDuMCA" }, { "code": null, "e": 27882, "s": 27868, "text": "shubham_singh" }, { "code": null, "e": 27898, "s": 27882, "text": "mayanktyagi1709" }, { "code": null, "e": 27905, "s": 27898, "text": "series" }, { "code": null, "e": 27916, "s": 27905, "text": "series-sum" }, { "code": null, "e": 27929, "s": 27916, "text": "Mathematical" }, { "code": null, "e": 27948, "s": 27929, "text": "School Programming" }, { "code": null, "e": 27961, "s": 27948, "text": "Mathematical" }, { "code": null, "e": 27968, "s": 27961, "text": "series" }, { "code": null, "e": 28066, "s": 27968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28075, "s": 28066, "text": "Comments" }, { "code": null, "e": 28088, "s": 28075, "text": "Old Comments" }, { "code": null, "e": 28120, "s": 28088, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28163, "s": 28120, "text": "Program to convert a given number to words" }, { "code": null, "e": 28196, "s": 28163, "text": "Program to multiply two matrices" }, { "code": null, "e": 28227, "s": 28196, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28271, "s": 28227, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28289, "s": 28271, "text": "Python Dictionary" }, { "code": null, "e": 28305, "s": 28289, "text": "Arrays in C/C++" }, { "code": null, "e": 28324, "s": 28305, "text": "Inheritance in C++" }, { "code": null, "e": 28349, "s": 28324, "text": "Reverse a string in Java" } ]
IDE | GeeksforGeeks | A computer science portal for geeks
Please enter your email address or userHandle. 12345678910111213141516171819202122232425262728293031323334353637https://pastelink.net/h8l4y6dghttps://paiza.io/projects/xSg95cR8tnZzN6zNgn6AJQ?language=phphttps://ide.geeksforgeeks.org/U0LUPqZlwYhttps://bitbin.it/HhEX27Hp/http://pastie.org/p/31mlJ3v8wxHBz0f6D2QhWOhttps://controlc.com/85b52465https://pastebin.com/riDehjRFhttps://paste2.org/hVzXg0aGhttps://p.teknik.io/QaScrhttps://www.bankier.pl/forum/zapisz-wiadomoschttps://www.techrum.vn/threads/qwsedrftgyhuj.537257/https://paste.rs/yGXhttps://ideone.com/rqXLbzhttps://rextester.com/l/php_online_compilerhttps://pasteio.com/xaHqr84LItD6http://cpp.sh/https://tech.io/snippet?l=phphttps://paste.cutelyst.org/ZCFYcqFSThttps://paste.artemix.org/-/jeyZfnhttps://0paste.com/345541https://paste.tbee-clan.de/GYJ94#http://paste.akingi.com/uQ53Rleshttps://paste.feed-the-beast.com/view/b82967echttps://caribbeanfever.com/photo/albums/qwedrftgyhj-1https://kukooo.com/promotion/business-promotion/qwedrftgyh_i192981https://webhitlist.com/profiles/blogs/qwedrftgyhujhttp://beterhbo.ning.com/profiles/blogs/wsedrftgyhujhttp://zacriley.ning.com/photo/albums/wsedrftgyhuj-1https://myclc.clcillinois.edu/web/jeff_test/tutoring/-/message_boards/message/32109862http://ptits.net/boards/t/59079/wsedrftgyhjk.aspxhttp://taylorhicks.ning.com/photo/photo/listForContributor?screenName=c42f49c509f4476f948f11b1a4654b56http://www.shadowville.com/board/general-discussions/qwedrftgyhuj#p509335ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX https://ide.geeksforgeeks.org/jboZmyGimN Output has been truncated..please click on RUN to regenrate complete output when required.
[ { "code": null, "e": 164, "s": 117, "text": "Please enter your email address or userHandle." }, { "code": null, "e": 2101, "s": 164, "text": "12345678910111213141516171819202122232425262728293031323334353637https://pastelink.net/h8l4y6dghttps://paiza.io/projects/xSg95cR8tnZzN6zNgn6AJQ?language=phphttps://ide.geeksforgeeks.org/U0LUPqZlwYhttps://bitbin.it/HhEX27Hp/http://pastie.org/p/31mlJ3v8wxHBz0f6D2QhWOhttps://controlc.com/85b52465https://pastebin.com/riDehjRFhttps://paste2.org/hVzXg0aGhttps://p.teknik.io/QaScrhttps://www.bankier.pl/forum/zapisz-wiadomoschttps://www.techrum.vn/threads/qwsedrftgyhuj.537257/https://paste.rs/yGXhttps://ideone.com/rqXLbzhttps://rextester.com/l/php_online_compilerhttps://pasteio.com/xaHqr84LItD6http://cpp.sh/https://tech.io/snippet?l=phphttps://paste.cutelyst.org/ZCFYcqFSThttps://paste.artemix.org/-/jeyZfnhttps://0paste.com/345541https://paste.tbee-clan.de/GYJ94#http://paste.akingi.com/uQ53Rleshttps://paste.feed-the-beast.com/view/b82967echttps://caribbeanfever.com/photo/albums/qwedrftgyhj-1https://kukooo.com/promotion/business-promotion/qwedrftgyh_i192981https://webhitlist.com/profiles/blogs/qwedrftgyhujhttp://beterhbo.ning.com/profiles/blogs/wsedrftgyhujhttp://zacriley.ning.com/photo/albums/wsedrftgyhuj-1https://myclc.clcillinois.edu/web/jeff_test/tutoring/-/message_boards/message/32109862http://ptits.net/boards/t/59079/wsedrftgyhjk.aspxhttp://taylorhicks.ning.com/photo/photo/listForContributor?screenName=c42f49c509f4476f948f11b1a4654b56http://www.shadowville.com/board/general-discussions/qwedrftgyhuj#p509335ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" }, { "code": null, "e": 2142, "s": 2101, "text": "https://ide.geeksforgeeks.org/jboZmyGimN" } ]
How to List all Files and Directories in FTP Server using Python?
13 Jan, 2021 FTP ( File Transfer Protocol ) is set of rules that computer follows to transfer files across computer network. It is TCP/IP based protocol. FTP lets clients share files. FTP is less secure because of files are shared as plain text without any encryption across the network. It is possible using python to retrieve list of file and directories from FTP server using its in-built ftplib module. ftplib is a pre-installed python package, which enables us to implement client side FTP protocol and in order to use it we simply have to import it like any other module. Basic approach to extract list or directories remains the same. Import module Connect to host on default port Syntax: FTP(host=”, user=”, passwd=”, acct=”, timeout=None, source_address=None, *, encoding=’utf-8′) Log in to the server using login() function Syntax: login(user=’anonymous’, passwd=”, acct=”) Retrieve files and directories accordingly. Close connection Method 1: using retrlines() Files and directories can be listed with retrlines() function. It returns filename, modified time, file size, owner, file type, permissions and Mode. Syntax: retrlines(cmd, callback=None) Passing ‘LIST’ in this function retrieves files and information about those files. Program: Python3 from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.retrlines('LIST') ftp.quit() Output: fig: 2 This function could also be user to search for a file or directory. Search query can be entered in between asterisk(*). Syntax: ftp.retrlines(‘LIST *query*’) Program: listing file names starting with “README”. Python3 from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.retrlines('LIST *README*') ftp.quit() Output: fig: 3 Method 2: Using dir() Files and directories can be listed with dir(). It returns filename, modified time, file size, owner, file type, permissions and Mode. Syntax: ftp.dir() Program: Python3 from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.dir() ftp.quit() Output: fig: 4 Method 3: Using nlst() Files and directories can be listed with nlst(). It returns name of files and directories of list type. Syntax: ftp.nlst() Program: Python3 from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.nlst() ftp.quit() Output: fig: 5 Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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 Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2021" }, { "code": null, "e": 304, "s": 28, "text": "FTP ( File Transfer Protocol ) is set of rules that computer follows to transfer files across computer network. It is TCP/IP based protocol. FTP lets clients share files. FTP is less secure because of files are shared as plain text without any encryption across the network. " }, { "code": null, "e": 658, "s": 304, "text": "It is possible using python to retrieve list of file and directories from FTP server using its in-built ftplib module. ftplib is a pre-installed python package, which enables us to implement client side FTP protocol and in order to use it we simply have to import it like any other module. Basic approach to extract list or directories remains the same." }, { "code": null, "e": 672, "s": 658, "text": "Import module" }, { "code": null, "e": 705, "s": 672, "text": "Connect to host on default port " }, { "code": null, "e": 713, "s": 705, "text": "Syntax:" }, { "code": null, "e": 807, "s": 713, "text": "FTP(host=”, user=”, passwd=”, acct=”, timeout=None, source_address=None, *, encoding=’utf-8′)" }, { "code": null, "e": 851, "s": 807, "text": "Log in to the server using login() function" }, { "code": null, "e": 859, "s": 851, "text": "Syntax:" }, { "code": null, "e": 901, "s": 859, "text": "login(user=’anonymous’, passwd=”, acct=”)" }, { "code": null, "e": 945, "s": 901, "text": "Retrieve files and directories accordingly." }, { "code": null, "e": 962, "s": 945, "text": "Close connection" }, { "code": null, "e": 990, "s": 962, "text": "Method 1: using retrlines()" }, { "code": null, "e": 1140, "s": 990, "text": "Files and directories can be listed with retrlines() function. It returns filename, modified time, file size, owner, file type, permissions and Mode." }, { "code": null, "e": 1148, "s": 1140, "text": "Syntax:" }, { "code": null, "e": 1178, "s": 1148, "text": "retrlines(cmd, callback=None)" }, { "code": null, "e": 1261, "s": 1178, "text": "Passing ‘LIST’ in this function retrieves files and information about those files." }, { "code": null, "e": 1270, "s": 1261, "text": "Program:" }, { "code": null, "e": 1278, "s": 1270, "text": "Python3" }, { "code": "from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.retrlines('LIST') ftp.quit()", "e": 1420, "s": 1278, "text": null }, { "code": null, "e": 1428, "s": 1420, "text": "Output:" }, { "code": null, "e": 1435, "s": 1428, "text": "fig: 2" }, { "code": null, "e": 1555, "s": 1435, "text": "This function could also be user to search for a file or directory. Search query can be entered in between asterisk(*)." }, { "code": null, "e": 1563, "s": 1555, "text": "Syntax:" }, { "code": null, "e": 1593, "s": 1563, "text": "ftp.retrlines(‘LIST *query*’)" }, { "code": null, "e": 1645, "s": 1593, "text": "Program: listing file names starting with “README”." }, { "code": null, "e": 1653, "s": 1645, "text": "Python3" }, { "code": "from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.retrlines('LIST *README*') ftp.quit()", "e": 1804, "s": 1653, "text": null }, { "code": null, "e": 1812, "s": 1804, "text": "Output:" }, { "code": null, "e": 1819, "s": 1812, "text": "fig: 3" }, { "code": null, "e": 1841, "s": 1819, "text": "Method 2: Using dir()" }, { "code": null, "e": 1976, "s": 1841, "text": "Files and directories can be listed with dir(). It returns filename, modified time, file size, owner, file type, permissions and Mode." }, { "code": null, "e": 1984, "s": 1976, "text": "Syntax:" }, { "code": null, "e": 1994, "s": 1984, "text": "ftp.dir()" }, { "code": null, "e": 2003, "s": 1994, "text": "Program:" }, { "code": null, "e": 2011, "s": 2003, "text": "Python3" }, { "code": "from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.dir() ftp.quit()", "e": 2141, "s": 2011, "text": null }, { "code": null, "e": 2149, "s": 2141, "text": "Output:" }, { "code": null, "e": 2156, "s": 2149, "text": "fig: 4" }, { "code": null, "e": 2179, "s": 2156, "text": "Method 3: Using nlst()" }, { "code": null, "e": 2283, "s": 2179, "text": "Files and directories can be listed with nlst(). It returns name of files and directories of list type." }, { "code": null, "e": 2291, "s": 2283, "text": "Syntax:" }, { "code": null, "e": 2302, "s": 2291, "text": "ftp.nlst()" }, { "code": null, "e": 2311, "s": 2302, "text": "Program:" }, { "code": null, "e": 2319, "s": 2311, "text": "Python3" }, { "code": "from ftplib import FTP ftp = FTP('ftp.us.debian.org') ftp.login() # changing directoryftp.cwd('debian') ftp.nlst() ftp.quit()", "e": 2450, "s": 2319, "text": null }, { "code": null, "e": 2458, "s": 2450, "text": "Output:" }, { "code": null, "e": 2465, "s": 2458, "text": "fig: 5" }, { "code": null, "e": 2472, "s": 2465, "text": "Picked" }, { "code": null, "e": 2487, "s": 2472, "text": "python-utility" }, { "code": null, "e": 2494, "s": 2487, "text": "Python" }, { "code": null, "e": 2592, "s": 2494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2624, "s": 2592, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2651, "s": 2624, "text": "Python Classes and Objects" }, { "code": null, "e": 2672, "s": 2651, "text": "Python OOPs Concepts" }, { "code": null, "e": 2695, "s": 2672, "text": "Introduction To PYTHON" }, { "code": null, "e": 2726, "s": 2695, "text": "Python | os.path.join() method" }, { "code": null, "e": 2782, "s": 2726, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2824, "s": 2782, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2866, "s": 2824, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2905, "s": 2866, "text": "Python | Get unique values from a list" } ]
Python Tkinter - SpinBox range Validation - GeeksforGeeks
17 Sep, 2021 Prerequisites: Python GUI – tkinter, Python Tkinter – Validating Entry Widget Tkinter is a Python GUI (Graphical User Interface) module which is quick and easy to implement and is widely used for creating desktop applications. It provides various basic widgets to build a GUI program. In Tkinter, Spinbox is commonly used widget to select the fixed number of values from the range provided by the programmer, but by default Spinbox accepts all types of input given by user. Hence we need to validate the input and accept only those values which are in the range. Below is the implementation: Note: For more information on Validatecommand, refer to Python Tkinter – Validating Entry Widget Python3 from tkinter import * # Validating functiondef validate(user_input): # check if the input is numeric if user_input.isdigit(): # Fetching minimum and maximum value of the spinbox minval = int(root.nametowidget(spinbox).config('from')[4]) maxval = int(root.nametowidget(spinbox).config('to')[4]) # check if the number is within the range if int(user_input) not in range(minval, maxval): print ("Out of range") return False # Printing the user input to the console print(user_input) return True # if input is blank string elif user_input is "": print(user_input) return True # return false is input is not numeric else: print("Not numeric") return False root = Tk()root.geometry("300x300")root.title("Spinbox Range Validation") # Creating Spinboxspinbox = Spinbox(root, from_ = 1, to = 1000)spinbox.pack()range_validation = root.register(validate) spinbox.config(validate ="key", validatecommand =(range_validation, '% P')) root.mainloop() Output: simmytarika5 abhishek0719kadiyan Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Sep, 2021" }, { "code": null, "e": 26130, "s": 25537, "text": "Prerequisites: Python GUI – tkinter, Python Tkinter – Validating Entry Widget Tkinter is a Python GUI (Graphical User Interface) module which is quick and easy to implement and is widely used for creating desktop applications. It provides various basic widgets to build a GUI program. In Tkinter, Spinbox is commonly used widget to select the fixed number of values from the range provided by the programmer, but by default Spinbox accepts all types of input given by user. Hence we need to validate the input and accept only those values which are in the range. Below is the implementation: " }, { "code": null, "e": 26229, "s": 26130, "text": "Note: For more information on Validatecommand, refer to Python Tkinter – Validating Entry Widget " }, { "code": null, "e": 26237, "s": 26229, "text": "Python3" }, { "code": "from tkinter import * # Validating functiondef validate(user_input): # check if the input is numeric if user_input.isdigit(): # Fetching minimum and maximum value of the spinbox minval = int(root.nametowidget(spinbox).config('from')[4]) maxval = int(root.nametowidget(spinbox).config('to')[4]) # check if the number is within the range if int(user_input) not in range(minval, maxval): print (\"Out of range\") return False # Printing the user input to the console print(user_input) return True # if input is blank string elif user_input is \"\": print(user_input) return True # return false is input is not numeric else: print(\"Not numeric\") return False root = Tk()root.geometry(\"300x300\")root.title(\"Spinbox Range Validation\") # Creating Spinboxspinbox = Spinbox(root, from_ = 1, to = 1000)spinbox.pack()range_validation = root.register(validate) spinbox.config(validate =\"key\", validatecommand =(range_validation, '% P')) root.mainloop()", "e": 27312, "s": 26237, "text": null }, { "code": null, "e": 27322, "s": 27312, "text": "Output: " }, { "code": null, "e": 27337, "s": 27324, "text": "simmytarika5" }, { "code": null, "e": 27357, "s": 27337, "text": "abhishek0719kadiyan" }, { "code": null, "e": 27372, "s": 27357, "text": "Python-tkinter" }, { "code": null, "e": 27379, "s": 27372, "text": "Python" }, { "code": null, "e": 27477, "s": 27379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27509, "s": 27477, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27551, "s": 27509, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27593, "s": 27551, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27620, "s": 27593, "text": "Python Classes and Objects" }, { "code": null, "e": 27676, "s": 27620, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27715, "s": 27676, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27737, "s": 27715, "text": "Defaultdict in Python" }, { "code": null, "e": 27768, "s": 27737, "text": "Python | os.path.join() method" }, { "code": null, "e": 27797, "s": 27768, "text": "Create a directory in Python" } ]
How to Remove Duplicates from ArrayList in Java - GeeksforGeeks
11 Dec, 2018 Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java. Examples: Input: List = [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5] Output: List = [1, 10, 2, 3, 4, 5] Input: List = ["G", "e", "e", "k", "s"] Output: List = ["G", "e", "k", "s"] Using IteratorApproach:Get the ArrayList with duplicate values.Create another ArrayList.Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new ArrayList ArrayList<T> newList = new ArrayList<T>(); // Traverse through the first list for (T element : list) { // If this element is not present in newList // then add it if (!newList.contains(element)) { newList.add(element); } } // return the new list return newList; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] Using LinkedHashSetA better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order.Approach:Get the ArrayList with duplicate values.Create a LinkedHashSet from this ArrayList. This will remove the duplicatesConvert this LinkedHashSet back to Arraylist.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] Using Java 8 Stream.distinct()You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect().Approach:Get the ArrayList with duplicate values.Create a new List from this ArrayList.Using Stream().distinct() method which return distinct object stream.convert this object stream into ListBelow is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to remove duplicates from a List in Java 8class GFG{ public static void main(String[] args) { // input list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Construct a new list from the set constucted from elements // of the original list List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] Using IteratorApproach:Get the ArrayList with duplicate values.Create another ArrayList.Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new ArrayList ArrayList<T> newList = new ArrayList<T>(); // Traverse through the first list for (T element : list) { // If this element is not present in newList // then add it if (!newList.contains(element)) { newList.add(element); } } // return the new list return newList; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] Approach: Get the ArrayList with duplicate values.Create another ArrayList.Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.The second ArrayList contains the elements with duplicates removed. Get the ArrayList with duplicate values. Create another ArrayList. Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method. The second ArrayList contains the elements with duplicates removed. Below is the implementation of the above approach: // Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new ArrayList ArrayList<T> newList = new ArrayList<T>(); // Traverse through the first list for (T element : list) { // If this element is not present in newList // then add it if (!newList.contains(element)) { newList.add(element); } } // return the new list return newList; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }} ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] Using LinkedHashSetA better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order.Approach:Get the ArrayList with duplicate values.Create a LinkedHashSet from this ArrayList. This will remove the duplicatesConvert this LinkedHashSet back to Arraylist.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] A better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order. Approach: Get the ArrayList with duplicate values.Create a LinkedHashSet from this ArrayList. This will remove the duplicatesConvert this LinkedHashSet back to Arraylist.The second ArrayList contains the elements with duplicates removed. Get the ArrayList with duplicate values. Create a LinkedHashSet from this ArrayList. This will remove the duplicates Convert this LinkedHashSet back to Arraylist. The second ArrayList contains the elements with duplicates removed. Below is the implementation of the above approach: // Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }} ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] Using Java 8 Stream.distinct()You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect().Approach:Get the ArrayList with duplicate values.Create a new List from this ArrayList.Using Stream().distinct() method which return distinct object stream.convert this object stream into ListBelow is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to remove duplicates from a List in Java 8class GFG{ public static void main(String[] args) { // input list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Construct a new list from the set constucted from elements // of the original list List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect(). Approach: Get the ArrayList with duplicate values.Create a new List from this ArrayList.Using Stream().distinct() method which return distinct object stream.convert this object stream into List Get the ArrayList with duplicate values. Create a new List from this ArrayList. Using Stream().distinct() method which return distinct object stream. convert this object stream into List Below is the implementation of the above approach: // Java program to remove duplicates from ArrayList import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to remove duplicates from a List in Java 8class GFG{ public static void main(String[] args) { // input list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println("ArrayList with duplicates: " + list); // Construct a new list from the set constucted from elements // of the original list List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); // Print the ArrayList with duplicates removed System.out.println("ArrayList with duplicates removed: " + newList); }} ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5] 29AjayKumar Java-ArrayList Java-Collections java-LinkedHashSet Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples Reverse a string in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 25111, "s": 25083, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25225, "s": 25111, "text": "Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java." }, { "code": null, "e": 25235, "s": 25225, "text": "Examples:" }, { "code": null, "e": 25398, "s": 25235, "text": "Input: List = [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]\nOutput: List = [1, 10, 2, 3, 4, 5]\n\nInput: List = [\"G\", \"e\", \"e\", \"k\", \"s\"]\nOutput: List = [\"G\", \"e\", \"k\", \"s\"]\n" }, { "code": null, "e": 30810, "s": 25398, "text": "Using IteratorApproach:Get the ArrayList with duplicate values.Create another ArrayList.Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new ArrayList ArrayList<T> newList = new ArrayList<T>(); // Traverse through the first list for (T element : list) { // If this element is not present in newList // then add it if (!newList.contains(element)) { newList.add(element); } } // return the new list return newList; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\nUsing LinkedHashSetA better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order.Approach:Get the ArrayList with duplicate values.Create a LinkedHashSet from this ArrayList. This will remove the duplicatesConvert this LinkedHashSet back to Arraylist.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\nUsing Java 8 Stream.distinct()You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect().Approach:Get the ArrayList with duplicate values.Create a new List from this ArrayList.Using Stream().distinct() method which return distinct object stream.convert this object stream into ListBelow is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to remove duplicates from a List in Java 8class GFG{ public static void main(String[] args) { // input list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Construct a new list from the set constucted from elements // of the original list List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 32569, "s": 30810, "text": "Using IteratorApproach:Get the ArrayList with duplicate values.Create another ArrayList.Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new ArrayList ArrayList<T> newList = new ArrayList<T>(); // Traverse through the first list for (T element : list) { // If this element is not present in newList // then add it if (!newList.contains(element)) { newList.add(element); } } // return the new list return newList; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 32579, "s": 32569, "text": "Approach:" }, { "code": null, "e": 32846, "s": 32579, "text": "Get the ArrayList with duplicate values.Create another ArrayList.Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.The second ArrayList contains the elements with duplicates removed." }, { "code": null, "e": 32887, "s": 32846, "text": "Get the ArrayList with duplicate values." }, { "code": null, "e": 32913, "s": 32887, "text": "Create another ArrayList." }, { "code": null, "e": 33048, "s": 32913, "text": "Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method." }, { "code": null, "e": 33116, "s": 33048, "text": "The second ArrayList contains the elements with duplicates removed." }, { "code": null, "e": 33167, "s": 33116, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new ArrayList ArrayList<T> newList = new ArrayList<T>(); // Traverse through the first list for (T element : list) { // If this element is not present in newList // then add it if (!newList.contains(element)) { newList.add(element); } } // return the new list return newList; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}", "e": 34459, "s": 33167, "text": null }, { "code": null, "e": 34581, "s": 34459, "text": "ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 36534, "s": 34581, "text": "Using LinkedHashSetA better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order.Approach:Get the ArrayList with duplicate values.Create a LinkedHashSet from this ArrayList. This will remove the duplicatesConvert this LinkedHashSet back to Arraylist.The second ArrayList contains the elements with duplicates removed.Below is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 36828, "s": 36534, "text": "A better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order." }, { "code": null, "e": 36838, "s": 36828, "text": "Approach:" }, { "code": null, "e": 37066, "s": 36838, "text": "Get the ArrayList with duplicate values.Create a LinkedHashSet from this ArrayList. This will remove the duplicatesConvert this LinkedHashSet back to Arraylist.The second ArrayList contains the elements with duplicates removed." }, { "code": null, "e": 37107, "s": 37066, "text": "Get the ArrayList with duplicate values." }, { "code": null, "e": 37183, "s": 37107, "text": "Create a LinkedHashSet from this ArrayList. This will remove the duplicates" }, { "code": null, "e": 37229, "s": 37183, "text": "Convert this LinkedHashSet back to Arraylist." }, { "code": null, "e": 37297, "s": 37229, "text": "The second ArrayList contains the elements with duplicates removed." }, { "code": null, "e": 37348, "s": 37297, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to remove duplicates from ArrayList import java.util.*; public class GFG { // Function to remove duplicates from an ArrayList public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) { // Create a new LinkedHashSet Set<T> set = new LinkedHashSet<>(); // Add the elements to set set.addAll(list); // Clear the list list.clear(); // add the elements of set // with no duplicates to the list list.addAll(set); // return the list return list; } // Driver code public static void main(String args[]) { // Get the ArrayList with duplicate values ArrayList<Integer> list = new ArrayList<>( Arrays .asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Remove duplicates ArrayList<Integer> newList = removeDuplicates(list); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}", "e": 38575, "s": 37348, "text": null }, { "code": null, "e": 38697, "s": 38575, "text": "ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 40399, "s": 38697, "text": "Using Java 8 Stream.distinct()You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect().Approach:Get the ArrayList with duplicate values.Create a new List from this ArrayList.Using Stream().distinct() method which return distinct object stream.convert this object stream into ListBelow is the implementation of the above approach:// Java program to remove duplicates from ArrayList import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to remove duplicates from a List in Java 8class GFG{ public static void main(String[] args) { // input list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Construct a new list from the set constucted from elements // of the original list List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}Output:ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 40728, "s": 40399, "text": "You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect()." }, { "code": null, "e": 40738, "s": 40728, "text": "Approach:" }, { "code": null, "e": 40922, "s": 40738, "text": "Get the ArrayList with duplicate values.Create a new List from this ArrayList.Using Stream().distinct() method which return distinct object stream.convert this object stream into List" }, { "code": null, "e": 40963, "s": 40922, "text": "Get the ArrayList with duplicate values." }, { "code": null, "e": 41002, "s": 40963, "text": "Create a new List from this ArrayList." }, { "code": null, "e": 41072, "s": 41002, "text": "Using Stream().distinct() method which return distinct object stream." }, { "code": null, "e": 41109, "s": 41072, "text": "convert this object stream into List" }, { "code": null, "e": 41160, "s": 41109, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to remove duplicates from ArrayList import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors; // Program to remove duplicates from a List in Java 8class GFG{ public static void main(String[] args) { // input list with duplicates List<Integer> list = new ArrayList<>( Arrays.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5)); // Print the Arraylist System.out.println(\"ArrayList with duplicates: \" + list); // Construct a new list from the set constucted from elements // of the original list List<Integer> newList = list.stream() .distinct() .collect(Collectors.toList()); // Print the ArrayList with duplicates removed System.out.println(\"ArrayList with duplicates removed: \" + newList); }}", "e": 42134, "s": 41160, "text": null }, { "code": null, "e": 42256, "s": 42134, "text": "ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5]\nArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]\n" }, { "code": null, "e": 42268, "s": 42256, "text": "29AjayKumar" }, { "code": null, "e": 42283, "s": 42268, "text": "Java-ArrayList" }, { "code": null, "e": 42300, "s": 42283, "text": "Java-Collections" }, { "code": null, "e": 42319, "s": 42300, "text": "java-LinkedHashSet" }, { "code": null, "e": 42338, "s": 42319, "text": "Java-List-Programs" }, { "code": null, "e": 42343, "s": 42338, "text": "Java" }, { "code": null, "e": 42348, "s": 42343, "text": "Java" }, { "code": null, "e": 42365, "s": 42348, "text": "Java-Collections" }, { "code": null, "e": 42463, "s": 42365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42478, "s": 42463, "text": "Arrays in Java" }, { "code": null, "e": 42522, "s": 42478, "text": "Split() String method in Java with examples" }, { "code": null, "e": 42544, "s": 42522, "text": "For-each loop in Java" }, { "code": null, "e": 42595, "s": 42544, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 42631, "s": 42595, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 42656, "s": 42631, "text": "Reverse a string in Java" }, { "code": null, "e": 42686, "s": 42656, "text": "HashMap in Java with Examples" }, { "code": null, "e": 42701, "s": 42686, "text": "Stream In Java" }, { "code": null, "e": 42720, "s": 42701, "text": "Interfaces in Java" } ]
C# Program to Reverse a String without using Reverse() Method - GeeksforGeeks
16 Nov, 2021 C# has a built-in function to reverse a string. First, the string is converted to a character array by using ToCharArray() then by using the Reverse() the character array will be reversed, But in this article, we will understand how to Reverse a String without using Reverse(). Example Input : Geek Output : keeG Input : For Output : roF Method 1: Using a for loop to reverse a string. An empty string is declared and name as ReversedString. The input string will be iterated from right to left and each character is appended to the ReversedString. By the end of the iteration, the ReversedString will have the reversed string stored in it. C# // C# program to reverse a string using a for loopusing System; class GFG{ public static string Reverse(string Input) { // Converting string to character array char[] charArray = Input.ToCharArray(); // Declaring an empty string string reversedString = String.Empty; // Iterating the each character from right to left for(int i = charArray.Length - 1; i > -1; i--) { // Append each character to the reversedstring. reversedString += charArray[i]; } // Return the reversed string. return reversedString;} // Driver codestatic void Main(string[] args) { Console.WriteLine(Reverse("GeeksForGeeks")); } } skeeGroFskeeG Method 2: Using a while loop to reverse a string. In this method, an empty string is declared and name as reversedString now the input string will be iterated from right to left using the while loop, and each character is appended to the reversedString. By the end of the iteration, the reversedString will have the reversed string stored in it. C# // C# program to reverse a string using while loopusing System; class GFG{ public static string Reverse(string Input) { // Converting string to character array char[] charArray = Input.ToCharArray(); // Declaring an empty string string reversedString = String.Empty; int length, index; length = charArray.Length - 1; index = length; // Iterating the each character from right to left while (index > -1) { // Appending character to the reversedstring. reversedString = reversedString + charArray[index]; index--; } // Return the reversed string. return reversedString;} // Driver codestatic void Main(string[] args) { Console.WriteLine(Reverse("GeeksForGeeks")); } } skeeGroFskeeG anikakapoor sagartomar9927 CSharp LINQ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n16 Nov, 2021" }, { "code": null, "e": 25825, "s": 25547, "text": "C# has a built-in function to reverse a string. First, the string is converted to a character array by using ToCharArray() then by using the Reverse() the character array will be reversed, But in this article, we will understand how to Reverse a String without using Reverse()." }, { "code": null, "e": 25833, "s": 25825, "text": "Example" }, { "code": null, "e": 25888, "s": 25833, "text": "Input : Geek\nOutput : keeG\n\nInput : For\nOutput : roF" }, { "code": null, "e": 25936, "s": 25888, "text": "Method 1: Using a for loop to reverse a string." }, { "code": null, "e": 26191, "s": 25936, "text": "An empty string is declared and name as ReversedString. The input string will be iterated from right to left and each character is appended to the ReversedString. By the end of the iteration, the ReversedString will have the reversed string stored in it." }, { "code": null, "e": 26194, "s": 26191, "text": "C#" }, { "code": "// C# program to reverse a string using a for loopusing System; class GFG{ public static string Reverse(string Input) { // Converting string to character array char[] charArray = Input.ToCharArray(); // Declaring an empty string string reversedString = String.Empty; // Iterating the each character from right to left for(int i = charArray.Length - 1; i > -1; i--) { // Append each character to the reversedstring. reversedString += charArray[i]; } // Return the reversed string. return reversedString;} // Driver codestatic void Main(string[] args) { Console.WriteLine(Reverse(\"GeeksForGeeks\")); } }", "e": 26883, "s": 26194, "text": null }, { "code": null, "e": 26897, "s": 26883, "text": "skeeGroFskeeG" }, { "code": null, "e": 26947, "s": 26897, "text": "Method 2: Using a while loop to reverse a string." }, { "code": null, "e": 27243, "s": 26947, "text": "In this method, an empty string is declared and name as reversedString now the input string will be iterated from right to left using the while loop, and each character is appended to the reversedString. By the end of the iteration, the reversedString will have the reversed string stored in it." }, { "code": null, "e": 27246, "s": 27243, "text": "C#" }, { "code": "// C# program to reverse a string using while loopusing System; class GFG{ public static string Reverse(string Input) { // Converting string to character array char[] charArray = Input.ToCharArray(); // Declaring an empty string string reversedString = String.Empty; int length, index; length = charArray.Length - 1; index = length; // Iterating the each character from right to left while (index > -1) { // Appending character to the reversedstring. reversedString = reversedString + charArray[index]; index--; } // Return the reversed string. return reversedString;} // Driver codestatic void Main(string[] args) { Console.WriteLine(Reverse(\"GeeksForGeeks\")); } }", "e": 28020, "s": 27246, "text": null }, { "code": null, "e": 28034, "s": 28020, "text": "skeeGroFskeeG" }, { "code": null, "e": 28046, "s": 28034, "text": "anikakapoor" }, { "code": null, "e": 28061, "s": 28046, "text": "sagartomar9927" }, { "code": null, "e": 28073, "s": 28061, "text": "CSharp LINQ" }, { "code": null, "e": 28089, "s": 28073, "text": "CSharp-programs" }, { "code": null, "e": 28096, "s": 28089, "text": "Picked" }, { "code": null, "e": 28099, "s": 28096, "text": "C#" }, { "code": null, "e": 28197, "s": 28099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28220, "s": 28197, "text": "Extension Method in C#" }, { "code": null, "e": 28248, "s": 28220, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28265, "s": 28248, "text": "C# | Inheritance" }, { "code": null, "e": 28287, "s": 28265, "text": "Partial Classes in C#" }, { "code": null, "e": 28316, "s": 28287, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28356, "s": 28316, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28379, "s": 28356, "text": "Switch Statement in C#" }, { "code": null, "e": 28419, "s": 28379, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28462, "s": 28419, "text": "C# | How to insert an element in an Array?" } ]
Python Program for Selection Sort - GeeksforGeeks
30 Dec, 2020 The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted.2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. Python # Python program for implementation of Selection# Sortimport sysA = [64, 25, 12, 22, 11] # Traverse through all array elementsfor i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test aboveprint ("Sorted array")for i in range(len(A)): print("%d" %A[i]), python sorting-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Iterate over characters of a string in Python Python Program for factorial of a number Python | Convert set into a list Python | Convert a list into a tuple Python | Check if a variable is string Add a key:value pair to dictionary in Python Appending to list in Python dictionary Python program to find sum of elements in list Python program to find largest number in a list
[ { "code": null, "e": 25603, "s": 25575, "text": "\n30 Dec, 2020" }, { "code": null, "e": 25827, "s": 25603, "text": "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array." }, { "code": null, "e": 25908, "s": 25827, "text": "1) The subarray which is already sorted.2) Remaining subarray which is unsorted." }, { "code": null, "e": 26067, "s": 25908, "text": "In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray." }, { "code": null, "e": 26074, "s": 26067, "text": "Python" }, { "code": "# Python program for implementation of Selection# Sortimport sysA = [64, 25, 12, 22, 11] # Traverse through all array elementsfor i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test aboveprint (\"Sorted array\")for i in range(len(A)): print(\"%d\" %A[i]), ", "e": 26617, "s": 26074, "text": null }, { "code": null, "e": 26642, "s": 26617, "text": "python sorting-exercises" }, { "code": null, "e": 26658, "s": 26642, "text": "Python Programs" }, { "code": null, "e": 26756, "s": 26658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26805, "s": 26756, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 26851, "s": 26805, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 26892, "s": 26851, "text": "Python Program for factorial of a number" }, { "code": null, "e": 26925, "s": 26892, "text": "Python | Convert set into a list" }, { "code": null, "e": 26962, "s": 26925, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 27001, "s": 26962, "text": "Python | Check if a variable is string" }, { "code": null, "e": 27046, "s": 27001, "text": "Add a key:value pair to dictionary in Python" }, { "code": null, "e": 27085, "s": 27046, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 27132, "s": 27085, "text": "Python program to find sum of elements in list" } ]
Creating a dataframe using CSV files - GeeksforGeeks
17 Feb, 2022 CSV files are the “comma-separated values”, these values are separated by commas, this file can be viewed like an excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format. Creating a pandas data frame using CSV files can be achieved in multiple ways.Note: Get the csv file used in the below examples from here.Method #1: Using read_csv() method: read_csv() is an important pandas function to read csv files and do operations on it.Example: Python3 # Python program to illustrate# creating a data frame using CSV files # import pandas moduleimport pandas as pd # creating a data framedf = pd.read_csv("CardioGoodFitness.csv")print(df.head()) Output: Method #2: Using read_table() method: read_table() is another important pandas function to read csv files and create data frame from it.Example: Python3 # Python program to illustrate# creating a data frame using CSV files # import pandas moduleimport pandas as pd # creating a data framedf = pd.read_table("CardioGoodFitness.csv", delimiter =", ")print(df.head()) Output: Method #3: Using the csv module: One can directly import the csv files using the csv module and then create a data frame using that csv file.Example: Python3 # Python program to illustrate# creating a data frame using CSV files # import pandas moduleimport pandas as pd# import csv moduleimport csv with open("CardioGoodFitness.csv") as csv_file: # read the csv file csv_reader = csv.reader(csv_file) # now we can use this csv files into the pandas df = pd.DataFrame([csv_reader], index = None) # iterating values of first columnfor val in list(df[1]): print(val) Output: ['TM195', '18', 'Male', '14', 'Single', '3', '4', '29562', '112'] punamsingh628700 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": 25581, "s": 25553, "text": "\n17 Feb, 2022" }, { "code": null, "e": 26152, "s": 25581, "text": "CSV files are the “comma-separated values”, these values are separated by commas, this file can be viewed like an excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format. Creating a pandas data frame using CSV files can be achieved in multiple ways.Note: Get the csv file used in the below examples from here.Method #1: Using read_csv() method: read_csv() is an important pandas function to read csv files and do operations on it.Example: " }, { "code": null, "e": 26160, "s": 26152, "text": "Python3" }, { "code": "# Python program to illustrate# creating a data frame using CSV files # import pandas moduleimport pandas as pd # creating a data framedf = pd.read_csv(\"CardioGoodFitness.csv\")print(df.head())", "e": 26353, "s": 26160, "text": null }, { "code": null, "e": 26362, "s": 26353, "text": "Output: " }, { "code": null, "e": 26509, "s": 26362, "text": "Method #2: Using read_table() method: read_table() is another important pandas function to read csv files and create data frame from it.Example: " }, { "code": null, "e": 26517, "s": 26509, "text": "Python3" }, { "code": "# Python program to illustrate# creating a data frame using CSV files # import pandas moduleimport pandas as pd # creating a data framedf = pd.read_table(\"CardioGoodFitness.csv\", delimiter =\", \")print(df.head())", "e": 26729, "s": 26517, "text": null }, { "code": null, "e": 26738, "s": 26729, "text": "Output: " }, { "code": null, "e": 26890, "s": 26738, "text": "Method #3: Using the csv module: One can directly import the csv files using the csv module and then create a data frame using that csv file.Example: " }, { "code": null, "e": 26898, "s": 26890, "text": "Python3" }, { "code": "# Python program to illustrate# creating a data frame using CSV files # import pandas moduleimport pandas as pd# import csv moduleimport csv with open(\"CardioGoodFitness.csv\") as csv_file: # read the csv file csv_reader = csv.reader(csv_file) # now we can use this csv files into the pandas df = pd.DataFrame([csv_reader], index = None) # iterating values of first columnfor val in list(df[1]): print(val)", "e": 27320, "s": 26898, "text": null }, { "code": null, "e": 27330, "s": 27320, "text": "Output: " }, { "code": null, "e": 27396, "s": 27330, "text": "['TM195', '18', 'Male', '14', 'Single', '3', '4', '29562', '112']" }, { "code": null, "e": 27415, "s": 27398, "text": "punamsingh628700" }, { "code": null, "e": 27439, "s": 27415, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27453, "s": 27439, "text": "Python-pandas" }, { "code": null, "e": 27460, "s": 27453, "text": "Python" }, { "code": null, "e": 27558, "s": 27460, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27590, "s": 27558, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27632, "s": 27590, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27674, "s": 27632, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27730, "s": 27674, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27757, "s": 27730, "text": "Python Classes and Objects" }, { "code": null, "e": 27788, "s": 27757, "text": "Python | os.path.join() method" }, { "code": null, "e": 27827, "s": 27788, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27856, "s": 27827, "text": "Create a directory in Python" }, { "code": null, "e": 27878, "s": 27856, "text": "Defaultdict in Python" } ]
How to find the width of a div using vanilla JavaScript? - GeeksforGeeks
21 Jun, 2019 To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels. Syntax: element.offsetWidth Returns the corresponding element’s layout pixel width. Example: The following program will illustrate the solution using offsetWidth:Program 1: <!DOCTYPE html><html> <head> <title> GeeksforGeeks </title> <style> #GFG { height: 30px; width: 300px; padding: 10px; margin: 15px; background-color: green; } </style></head> <body> <div id="GFG"> <b>Division</b> </div> <button type="button" onclick="Geeks()"> Check </button> <script> function Geeks() { var elemWidth = document.getElementById("GFG").offsetWidth; alert(elemWidth); } </script></body> </html> Output: 320 The another method to measure the width of a div element we will utilize the clientWidth() property of JavaScript. The following program will illustrate the solution using clientWidth:Program 2: <!DOCTYPE html><html> <head> <title> GeeksforGeeks </title> <style> #GFG { height: 30px; width: 300px; padding: 10px; margin: 15px; background-color: green; } </style></head> <body> <div id="GFG"> <b>Division</b> </div> <button type="button" onclick="Geeks()"> Check </button> <script> function Geeks() { var elemWidth = document.getElementById("GFG").clientWidth; alert(elemWidth); } </script></body> </html> Output: 320 Note: clientWidth returns the inner width which includes padding but excludes borders and scroll bars whereas offsetWidth returns the outer width which includes padding and borders. JavaScript-Misc Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n21 Jun, 2019" }, { "code": null, "e": 26351, "s": 26139, "text": "To measure the width of a div element we will utilize the offsetWidth property of JavaScript. This property of JavaScript returns an integer representing the layout width of an element and is measured in pixels." }, { "code": null, "e": 26359, "s": 26351, "text": "Syntax:" }, { "code": null, "e": 26379, "s": 26359, "text": "element.offsetWidth" }, { "code": null, "e": 26435, "s": 26379, "text": "Returns the corresponding element’s layout pixel width." }, { "code": null, "e": 26444, "s": 26435, "text": "Example:" }, { "code": null, "e": 26524, "s": 26444, "text": "The following program will illustrate the solution using offsetWidth:Program 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> GeeksforGeeks </title> <style> #GFG { height: 30px; width: 300px; padding: 10px; margin: 15px; background-color: green; } </style></head> <body> <div id=\"GFG\"> <b>Division</b> </div> <button type=\"button\" onclick=\"Geeks()\"> Check </button> <script> function Geeks() { var elemWidth = document.getElementById(\"GFG\").offsetWidth; alert(elemWidth); } </script></body> </html>", "e": 27130, "s": 26524, "text": null }, { "code": null, "e": 27138, "s": 27130, "text": "Output:" }, { "code": null, "e": 27142, "s": 27138, "text": "320" }, { "code": null, "e": 27257, "s": 27142, "text": "The another method to measure the width of a div element we will utilize the clientWidth() property of JavaScript." }, { "code": null, "e": 27337, "s": 27257, "text": "The following program will illustrate the solution using clientWidth:Program 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> GeeksforGeeks </title> <style> #GFG { height: 30px; width: 300px; padding: 10px; margin: 15px; background-color: green; } </style></head> <body> <div id=\"GFG\"> <b>Division</b> </div> <button type=\"button\" onclick=\"Geeks()\"> Check </button> <script> function Geeks() { var elemWidth = document.getElementById(\"GFG\").clientWidth; alert(elemWidth); } </script></body> </html>", "e": 27932, "s": 27337, "text": null }, { "code": null, "e": 27940, "s": 27932, "text": "Output:" }, { "code": null, "e": 27944, "s": 27940, "text": "320" }, { "code": null, "e": 28126, "s": 27944, "text": "Note: clientWidth returns the inner width which includes padding but excludes borders and scroll bars whereas offsetWidth returns the outer width which includes padding and borders." }, { "code": null, "e": 28142, "s": 28126, "text": "JavaScript-Misc" }, { "code": null, "e": 28149, "s": 28142, "text": "Picked" }, { "code": null, "e": 28154, "s": 28149, "text": "HTML" }, { "code": null, "e": 28165, "s": 28154, "text": "JavaScript" }, { "code": null, "e": 28182, "s": 28165, "text": "Web Technologies" }, { "code": null, "e": 28187, "s": 28182, "text": "HTML" }, { "code": null, "e": 28285, "s": 28187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28309, "s": 28285, "text": "REST API (Introduction)" }, { "code": null, "e": 28350, "s": 28309, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28387, "s": 28350, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28416, "s": 28387, "text": "Form validation using jQuery" }, { "code": null, "e": 28436, "s": 28416, "text": "Angular File Upload" }, { "code": null, "e": 28476, "s": 28436, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28521, "s": 28476, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28582, "s": 28521, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28654, "s": 28582, "text": "Differences between Functional Components and Class Components in React" } ]
Find the closest pair from two sorted arrays - GeeksforGeeks
09 Mar, 2022 Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. We are given two arrays ar1[0...m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] – x) is minimum.Example: Input: ar1[] = {1, 4, 5, 7}; ar2[] = {10, 20, 30, 40}; x = 32 Output: 1 and 30 Input: ar1[] = {1, 4, 5, 7}; ar2[] = {10, 20, 30, 40}; x = 50 Output: 7 and 40 We strongly recommend to minimize your browser and try this yourself first.A Simple Solution is to run two loops. The outer loop considers every element of first array and inner loop checks for the pair in second array. We keep track of minimum difference between ar1[i] + ar2[j] and x.We can do it in O(n) time using following steps. 1) Merge given two arrays into an auxiliary array of size m+n using merge process of merge sort. While merging keep another boolean array of size m+n to indicate whether the current element in merged array is from ar1[] or ar2[].2) Consider the merged array and use the linear time algorithm to find the pair with sum closest to x. One extra thing we need to consider only those pairs which have one element from ar1[] and other from ar2[], we use the boolean array for this purpose.Can we do it in a single pass and O(1) extra space? The idea is to start from left side of one array and right side of another array, and use the algorithm same as step 2 of above approach. Following is detailed algorithm. 1) Initialize a variable diff as infinite (Diff is used to store the difference between pair and x). We need to find the minimum diff. 2) Initialize two index variables l and r in the given sorted array. (a) Initialize first to the leftmost index in ar1: l = 0 (b) Initialize second the rightmost index in ar2: r = n-1 3) Loop while l< length.ar1 and r>=0 (a) If abs(ar1[l] + ar2[r] - sum) < diff then update diff and result (b) If (ar1[l] + ar2[r] < sum ) then l++ (c) Else r-- 4) Print the result. Following is the implementation of this approach. C++ Java Python3 C# PHP Javascript // C++ program to find the pair from two sorted arrays such// that the sum of pair is closest to a given number x#include <iostream>#include <climits>#include <cstdlib>using namespace std; // ar1[0..m-1] and ar2[0..n-1] are two given sorted arrays// and x is given number. This function prints the pair from// both arrays such that the sum of the pair is closest to x.void printClosest(int ar1[], int ar2[], int m, int n, int x){ // Initialize the diff between pair sum and x. int diff = INT_MAX; // res_l and res_r are result indexes from ar1[] and ar2[] // respectively int res_l, res_r; // Start from left side of ar1[] and right side of ar2[] int l = 0, r = n-1; while (l<m && r>=0) { // If this pair is closer to x than the previously // found closest, then update res_l, res_r and diff if (abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more than x, move to smaller // side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result cout << "The closest pair is [" << ar1[res_l] << ", " << ar2[res_r] << "] \n";} // Driver program to test above functionsint main(){ int ar1[] = {1, 4, 5, 7}; int ar2[] = {10, 20, 30, 40}; int m = sizeof(ar1)/sizeof(ar1[0]); int n = sizeof(ar2)/sizeof(ar2[0]); int x = 38; printClosest(ar1, ar2, m, n, x); return 0;} // Java program to find closest pair in an arrayclass ClosestPair{ // ar1[0..m-1] and ar2[0..n-1] are two given sorted // arrays/ and x is given number. This function prints // the pair from both arrays such that the sum of the // pair is closest to x. void printClosest(int ar1[], int ar2[], int m, int n, int x) { // Initialize the diff between pair sum and x. int diff = Integer.MAX_VALUE; // res_l and res_r are result indexes from ar1[] and ar2[] // respectively int res_l = 0, res_r = 0; // Start from left side of ar1[] and right side of ar2[] int l = 0, r = n-1; while (l<m && r>=0) { // If this pair is closer to x than the previously // found closest, then update res_l, res_r and diff if (Math.abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more than x, move to smaller // side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result System.out.print("The closest pair is [" + ar1[res_l] + ", " + ar2[res_r] + "]"); } // Driver program to test above functions public static void main(String args[]) { ClosestPair ob = new ClosestPair(); int ar1[] = {1, 4, 5, 7}; int ar2[] = {10, 20, 30, 40}; int m = ar1.length; int n = ar2.length; int x = 38; ob.printClosest(ar1, ar2, m, n, x); }}/*This code is contributed by Rajat Mishra */ # Python3 program to find the pair from# two sorted arrays such that the sum# of pair is closest to a given number ximport sys # ar1[0..m-1] and ar2[0..n-1] are two# given sorted arrays and x is given# number. This function prints the pair# from both arrays such that the sum# of the pair is closest to x.def printClosest(ar1, ar2, m, n, x): # Initialize the diff between # pair sum and x. diff=sys.maxsize # res_l and res_r are result # indexes from ar1[] and ar2[] # respectively. Start from left # side of ar1[] and right side of ar2[] l = 0 r = n-1 while(l < m and r >= 0): # If this pair is closer to x than # the previously found closest, # then update res_l, res_r and diff if abs(ar1[l] + ar2[r] - x) < diff: res_l = l res_r = r diff = abs(ar1[l] + ar2[r] - x) # If sum of this pair is more than x, # move to smaller side if ar1[l] + ar2[r] > x: r=r-1 else: # move to the greater side l=l+1 # Print the result print("The closest pair is [", ar1[res_l],",",ar2[res_r],"]") # Driver program to test above functionsar1 = [1, 4, 5, 7]ar2 = [10, 20, 30, 40]m = len(ar1)n = len(ar2)x = 38printClosest(ar1, ar2, m, n, x) # This code is contributed by Smitha Dinesh Semwal // C# program to find closest pair in// an arrayusing System; class GFG { // ar1[0..m-1] and ar2[0..n-1] are two // given sorted arrays/ and x is given // number. This function prints the // pair from both arrays such that the // sum of the pair is closest to x. static void printClosest(int []ar1, int []ar2, int m, int n, int x) { // Initialize the diff between pair // sum and x. int diff = int.MaxValue; // res_l and res_r are result // indexes from ar1[] and ar2[] // respectively int res_l = 0, res_r = 0; // Start from left side of ar1[] // and right side of ar2[] int l = 0, r = n-1; while (l < m && r >= 0) { // If this pair is closer to // x than the previously // found closest, then update // res_l, res_r and diff if (Math.Abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = Math.Abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more // than x, move to smaller // side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result Console.Write("The closest pair is [" + ar1[res_l] + ", " + ar2[res_r] + "]"); } // Driver program to test above functions public static void Main() { int []ar1 = {1, 4, 5, 7}; int []ar2 = {10, 20, 30, 40}; int m = ar1.Length; int n = ar2.Length; int x = 38; printClosest(ar1, ar2, m, n, x); }} // This code is contributed by nitin mittal. <?php// PHP program to find the pair// from two sorted arrays such// that the sum of pair is// closest to a given number x // ar1[0..m-1] and ar2[0..n-1]// are two given sorted arrays// and x is given number. This// function prints the pair from// both arrays such that the sum// of the pair is closest to x.function printClosest($ar1, $ar2, $m, $n, $x){ // Initialize the diff between // pair sum and x. $diff = PHP_INT_MAX; // res_l and res_r are result // indexes from ar1[] and ar2[] // respectively $res_l; $res_r; // Start from left side of // ar1[] and right side of ar2[] $l = 0; $r = $n - 1; while ($l < $m and $r >= 0) { // If this pair is closer to // x than the previously // found closest, then // update res_l, res_r and // diff if (abs($ar1[$l] + $ar2[$r] - $x) < $diff) { $res_l = $l; $res_r = $r; $diff = abs($ar1[$l] + $ar2[$r] - $x); } // If sum of this pair is // more than x, move to smaller // side if ($ar1[$l] + $ar2[$r] > $x) $r--; // move to the greater side else $l++; } // Print the result echo "The closest pair is [" , $ar1[$res_l] , ", " , $ar2[$res_r] , "] \n";} // Driver Code $ar1 = array(1, 4, 5, 7); $ar2 = array(10, 20, 30, 40); $m = count($ar1); $n = count($ar2); $x = 38; printClosest($ar1, $ar2, $m, $n, $x); // This code is contributed by anuj_67.?> <script> // Javascript program to find// the pair from two sorted arrays such// that the sum of pair is closest// to a given number x // ar1[0..m-1] and ar2[0..n-1] are// two given sorted arrays// and x is given number.// This function prints the pair// from both arrays such that the// sum of the pair is closest to x.function printClosest( ar1, ar2, m, n, x){ // Initialize the diff // between pair sum and x. let diff = Number.MAX_VALUE; // res_l and res_r are result // indexes from ar1[] and ar2[] // respectively let res_l, res_r; // Start from left side of ar1[] and // right side of ar2[] let l = 0, r = n-1; while (l<m && r>=0) { // If this pair is closer to // x than the previously // found closest, then update // res_l, res_r and diff if (Math.abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more than x, // move to smaller side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result document.write("The closest pair is [" + ar1[res_l] + ", " + ar2[res_r] + "] </br>");} // driver code let ar1 = [1, 4, 5, 7]; let ar2 = [10, 20, 30, 40]; let m = ar1.length; let n = ar2.length; let x = 38; printClosest(ar1, ar2, m, n, x); </script> Output: The closest pair is [7, 30] YouTubeGeeksforGeeks507K subscribersFind the closest pair from two sorted arrays | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=090fGlXqKzw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Smallest Difference pair of values between two unsorted ArraysThis article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal vt_m nielgp93 jana_sayantan akshaysingh98088 rajatkumargla19 two-pointer-algorithm Arrays Searching two-pointer-algorithm Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26429, "s": 26401, "text": "\n09 Mar, 2022" }, { "code": null, "e": 26735, "s": 26429, "text": "Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. We are given two arrays ar1[0...m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] – x) is minimum.Example: " }, { "code": null, "e": 26942, "s": 26735, "text": "Input: ar1[] = {1, 4, 5, 7};\n ar2[] = {10, 20, 30, 40};\n x = 32 \nOutput: 1 and 30\n\nInput: ar1[] = {1, 4, 5, 7};\n ar2[] = {10, 20, 30, 40};\n x = 50 \nOutput: 7 and 40" }, { "code": null, "e": 27984, "s": 26942, "text": "We strongly recommend to minimize your browser and try this yourself first.A Simple Solution is to run two loops. The outer loop considers every element of first array and inner loop checks for the pair in second array. We keep track of minimum difference between ar1[i] + ar2[j] and x.We can do it in O(n) time using following steps. 1) Merge given two arrays into an auxiliary array of size m+n using merge process of merge sort. While merging keep another boolean array of size m+n to indicate whether the current element in merged array is from ar1[] or ar2[].2) Consider the merged array and use the linear time algorithm to find the pair with sum closest to x. One extra thing we need to consider only those pairs which have one element from ar1[] and other from ar2[], we use the boolean array for this purpose.Can we do it in a single pass and O(1) extra space? The idea is to start from left side of one array and right side of another array, and use the algorithm same as step 2 of above approach. Following is detailed algorithm. " }, { "code": null, "e": 28550, "s": 27984, "text": "1) Initialize a variable diff as infinite (Diff is used to store the \n difference between pair and x). We need to find the minimum diff.\n2) Initialize two index variables l and r in the given sorted array.\n (a) Initialize first to the leftmost index in ar1: l = 0\n (b) Initialize second the rightmost index in ar2: r = n-1\n3) Loop while l< length.ar1 and r>=0\n (a) If abs(ar1[l] + ar2[r] - sum) < diff then \n update diff and result \n (b) If (ar1[l] + ar2[r] < sum ) then l++\n (c) Else r-- \n4) Print the result. " }, { "code": null, "e": 28602, "s": 28550, "text": "Following is the implementation of this approach. " }, { "code": null, "e": 28606, "s": 28602, "text": "C++" }, { "code": null, "e": 28611, "s": 28606, "text": "Java" }, { "code": null, "e": 28619, "s": 28611, "text": "Python3" }, { "code": null, "e": 28622, "s": 28619, "text": "C#" }, { "code": null, "e": 28626, "s": 28622, "text": "PHP" }, { "code": null, "e": 28637, "s": 28626, "text": "Javascript" }, { "code": "// C++ program to find the pair from two sorted arrays such// that the sum of pair is closest to a given number x#include <iostream>#include <climits>#include <cstdlib>using namespace std; // ar1[0..m-1] and ar2[0..n-1] are two given sorted arrays// and x is given number. This function prints the pair from// both arrays such that the sum of the pair is closest to x.void printClosest(int ar1[], int ar2[], int m, int n, int x){ // Initialize the diff between pair sum and x. int diff = INT_MAX; // res_l and res_r are result indexes from ar1[] and ar2[] // respectively int res_l, res_r; // Start from left side of ar1[] and right side of ar2[] int l = 0, r = n-1; while (l<m && r>=0) { // If this pair is closer to x than the previously // found closest, then update res_l, res_r and diff if (abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more than x, move to smaller // side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result cout << \"The closest pair is [\" << ar1[res_l] << \", \" << ar2[res_r] << \"] \\n\";} // Driver program to test above functionsint main(){ int ar1[] = {1, 4, 5, 7}; int ar2[] = {10, 20, 30, 40}; int m = sizeof(ar1)/sizeof(ar1[0]); int n = sizeof(ar2)/sizeof(ar2[0]); int x = 38; printClosest(ar1, ar2, m, n, x); return 0;}", "e": 30170, "s": 28637, "text": null }, { "code": "// Java program to find closest pair in an arrayclass ClosestPair{ // ar1[0..m-1] and ar2[0..n-1] are two given sorted // arrays/ and x is given number. This function prints // the pair from both arrays such that the sum of the // pair is closest to x. void printClosest(int ar1[], int ar2[], int m, int n, int x) { // Initialize the diff between pair sum and x. int diff = Integer.MAX_VALUE; // res_l and res_r are result indexes from ar1[] and ar2[] // respectively int res_l = 0, res_r = 0; // Start from left side of ar1[] and right side of ar2[] int l = 0, r = n-1; while (l<m && r>=0) { // If this pair is closer to x than the previously // found closest, then update res_l, res_r and diff if (Math.abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more than x, move to smaller // side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result System.out.print(\"The closest pair is [\" + ar1[res_l] + \", \" + ar2[res_r] + \"]\"); } // Driver program to test above functions public static void main(String args[]) { ClosestPair ob = new ClosestPair(); int ar1[] = {1, 4, 5, 7}; int ar2[] = {10, 20, 30, 40}; int m = ar1.length; int n = ar2.length; int x = 38; ob.printClosest(ar1, ar2, m, n, x); }}/*This code is contributed by Rajat Mishra */", "e": 31876, "s": 30170, "text": null }, { "code": "# Python3 program to find the pair from# two sorted arrays such that the sum# of pair is closest to a given number ximport sys # ar1[0..m-1] and ar2[0..n-1] are two# given sorted arrays and x is given# number. This function prints the pair# from both arrays such that the sum# of the pair is closest to x.def printClosest(ar1, ar2, m, n, x): # Initialize the diff between # pair sum and x. diff=sys.maxsize # res_l and res_r are result # indexes from ar1[] and ar2[] # respectively. Start from left # side of ar1[] and right side of ar2[] l = 0 r = n-1 while(l < m and r >= 0): # If this pair is closer to x than # the previously found closest, # then update res_l, res_r and diff if abs(ar1[l] + ar2[r] - x) < diff: res_l = l res_r = r diff = abs(ar1[l] + ar2[r] - x) # If sum of this pair is more than x, # move to smaller side if ar1[l] + ar2[r] > x: r=r-1 else: # move to the greater side l=l+1 # Print the result print(\"The closest pair is [\", ar1[res_l],\",\",ar2[res_r],\"]\") # Driver program to test above functionsar1 = [1, 4, 5, 7]ar2 = [10, 20, 30, 40]m = len(ar1)n = len(ar2)x = 38printClosest(ar1, ar2, m, n, x) # This code is contributed by Smitha Dinesh Semwal", "e": 33203, "s": 31876, "text": null }, { "code": "// C# program to find closest pair in// an arrayusing System; class GFG { // ar1[0..m-1] and ar2[0..n-1] are two // given sorted arrays/ and x is given // number. This function prints the // pair from both arrays such that the // sum of the pair is closest to x. static void printClosest(int []ar1, int []ar2, int m, int n, int x) { // Initialize the diff between pair // sum and x. int diff = int.MaxValue; // res_l and res_r are result // indexes from ar1[] and ar2[] // respectively int res_l = 0, res_r = 0; // Start from left side of ar1[] // and right side of ar2[] int l = 0, r = n-1; while (l < m && r >= 0) { // If this pair is closer to // x than the previously // found closest, then update // res_l, res_r and diff if (Math.Abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = Math.Abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more // than x, move to smaller // side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result Console.Write(\"The closest pair is [\" + ar1[res_l] + \", \" + ar2[res_r] + \"]\"); } // Driver program to test above functions public static void Main() { int []ar1 = {1, 4, 5, 7}; int []ar2 = {10, 20, 30, 40}; int m = ar1.Length; int n = ar2.Length; int x = 38; printClosest(ar1, ar2, m, n, x); }} // This code is contributed by nitin mittal.", "e": 35076, "s": 33203, "text": null }, { "code": "<?php// PHP program to find the pair// from two sorted arrays such// that the sum of pair is// closest to a given number x // ar1[0..m-1] and ar2[0..n-1]// are two given sorted arrays// and x is given number. This// function prints the pair from// both arrays such that the sum// of the pair is closest to x.function printClosest($ar1, $ar2, $m, $n, $x){ // Initialize the diff between // pair sum and x. $diff = PHP_INT_MAX; // res_l and res_r are result // indexes from ar1[] and ar2[] // respectively $res_l; $res_r; // Start from left side of // ar1[] and right side of ar2[] $l = 0; $r = $n - 1; while ($l < $m and $r >= 0) { // If this pair is closer to // x than the previously // found closest, then // update res_l, res_r and // diff if (abs($ar1[$l] + $ar2[$r] - $x) < $diff) { $res_l = $l; $res_r = $r; $diff = abs($ar1[$l] + $ar2[$r] - $x); } // If sum of this pair is // more than x, move to smaller // side if ($ar1[$l] + $ar2[$r] > $x) $r--; // move to the greater side else $l++; } // Print the result echo \"The closest pair is [\" , $ar1[$res_l] , \", \" , $ar2[$res_r] , \"] \\n\";} // Driver Code $ar1 = array(1, 4, 5, 7); $ar2 = array(10, 20, 30, 40); $m = count($ar1); $n = count($ar2); $x = 38; printClosest($ar1, $ar2, $m, $n, $x); // This code is contributed by anuj_67.?>", "e": 36720, "s": 35076, "text": null }, { "code": "<script> // Javascript program to find// the pair from two sorted arrays such// that the sum of pair is closest// to a given number x // ar1[0..m-1] and ar2[0..n-1] are// two given sorted arrays// and x is given number.// This function prints the pair// from both arrays such that the// sum of the pair is closest to x.function printClosest( ar1, ar2, m, n, x){ // Initialize the diff // between pair sum and x. let diff = Number.MAX_VALUE; // res_l and res_r are result // indexes from ar1[] and ar2[] // respectively let res_l, res_r; // Start from left side of ar1[] and // right side of ar2[] let l = 0, r = n-1; while (l<m && r>=0) { // If this pair is closer to // x than the previously // found closest, then update // res_l, res_r and diff if (Math.abs(ar1[l] + ar2[r] - x) < diff) { res_l = l; res_r = r; diff = Math.abs(ar1[l] + ar2[r] - x); } // If sum of this pair is more than x, // move to smaller side if (ar1[l] + ar2[r] > x) r--; else // move to the greater side l++; } // Print the result document.write(\"The closest pair is [\" + ar1[res_l] + \", \" + ar2[res_r] + \"] </br>\");} // driver code let ar1 = [1, 4, 5, 7]; let ar2 = [10, 20, 30, 40]; let m = ar1.length; let n = ar2.length; let x = 38; printClosest(ar1, ar2, m, n, x); </script>", "e": 38184, "s": 36720, "text": null }, { "code": null, "e": 38193, "s": 38184, "text": "Output: " }, { "code": null, "e": 38223, "s": 38193, "text": " The closest pair is [7, 30] " }, { "code": null, "e": 39068, "s": 38225, "text": "YouTubeGeeksforGeeks507K subscribersFind the closest pair from two sorted arrays | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=090fGlXqKzw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 39293, "s": 39068, "text": "Smallest Difference pair of values between two unsorted ArraysThis article is contributed by Harsh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 39306, "s": 39293, "text": "nitin mittal" }, { "code": null, "e": 39311, "s": 39306, "text": "vt_m" }, { "code": null, "e": 39320, "s": 39311, "text": "nielgp93" }, { "code": null, "e": 39334, "s": 39320, "text": "jana_sayantan" }, { "code": null, "e": 39351, "s": 39334, "text": "akshaysingh98088" }, { "code": null, "e": 39367, "s": 39351, "text": "rajatkumargla19" }, { "code": null, "e": 39389, "s": 39367, "text": "two-pointer-algorithm" }, { "code": null, "e": 39396, "s": 39389, "text": "Arrays" }, { "code": null, "e": 39406, "s": 39396, "text": "Searching" }, { "code": null, "e": 39428, "s": 39406, "text": "two-pointer-algorithm" }, { "code": null, "e": 39435, "s": 39428, "text": "Arrays" }, { "code": null, "e": 39445, "s": 39435, "text": "Searching" }, { "code": null, "e": 39543, "s": 39445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39611, "s": 39543, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39655, "s": 39611, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39703, "s": 39655, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39726, "s": 39703, "text": "Introduction to Arrays" }, { "code": null, "e": 39758, "s": 39726, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39772, "s": 39758, "text": "Binary Search" }, { "code": null, "e": 39840, "s": 39772, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39854, "s": 39840, "text": "Linear Search" }, { "code": null, "e": 39902, "s": 39854, "text": "Search an element in a sorted and rotated array" } ]
Scala Map drop() method with example - GeeksforGeeks
13 Aug, 2019 The drop() method is utilized to delete the first ‘n’ elements. Method Definition: def drop(n: Int): Map[A, B] Return Type: It returns all the elements of the map except the first ‘n’ elements. Example #1: // Scala program of drop()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 5) // Applying drop method val result = m1.drop(1) // Displays output println(result) }} Map(for -> 3, cs -> 5) Example #2: // Scala program of drop()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map("geeks" -> 5, "for" -> 3, "geeks" -> 5) // Applying drop method val result = m1.drop(1) // Displays output println(result) }} Map(for -> 3) So, both the identical keys are removed from the map. Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in Scala Scala | Traits Scala ListBuffer Hello World in Scala Scala | Case Class and Case Object Scala | Functions - Basics Scala | Decision Making (if, if-else, Nested if-else, if-else if) Scala List map() method with example Comments In Scala Abstract Classes in Scala
[ { "code": null, "e": 25301, "s": 25273, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25365, "s": 25301, "text": "The drop() method is utilized to delete the first ‘n’ elements." }, { "code": null, "e": 25412, "s": 25365, "text": "Method Definition: def drop(n: Int): Map[A, B]" }, { "code": null, "e": 25495, "s": 25412, "text": "Return Type: It returns all the elements of the map except the first ‘n’ elements." }, { "code": null, "e": 25507, "s": 25495, "text": "Example #1:" }, { "code": "// Scala program of drop()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"cs\" -> 5) // Applying drop method val result = m1.drop(1) // Displays output println(result) }}", "e": 25863, "s": 25507, "text": null }, { "code": null, "e": 25887, "s": 25863, "text": "Map(for -> 3, cs -> 5)\n" }, { "code": null, "e": 25899, "s": 25887, "text": "Example #2:" }, { "code": "// Scala program of drop()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"geeks\" -> 5) // Applying drop method val result = m1.drop(1) // Displays output println(result) }}", "e": 26258, "s": 25899, "text": null }, { "code": null, "e": 26273, "s": 26258, "text": "Map(for -> 3)\n" }, { "code": null, "e": 26327, "s": 26273, "text": "So, both the identical keys are removed from the map." }, { "code": null, "e": 26333, "s": 26327, "text": "Scala" }, { "code": null, "e": 26343, "s": 26333, "text": "Scala-Map" }, { "code": null, "e": 26356, "s": 26343, "text": "Scala-Method" }, { "code": null, "e": 26362, "s": 26356, "text": "Scala" }, { "code": null, "e": 26460, "s": 26362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26481, "s": 26460, "text": "Inheritance in Scala" }, { "code": null, "e": 26496, "s": 26481, "text": "Scala | Traits" }, { "code": null, "e": 26513, "s": 26496, "text": "Scala ListBuffer" }, { "code": null, "e": 26534, "s": 26513, "text": "Hello World in Scala" }, { "code": null, "e": 26569, "s": 26534, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 26596, "s": 26569, "text": "Scala | Functions - Basics" }, { "code": null, "e": 26662, "s": 26596, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" }, { "code": null, "e": 26699, "s": 26662, "text": "Scala List map() method with example" }, { "code": null, "e": 26717, "s": 26699, "text": "Comments In Scala" } ]
How to access a local variable from a different function using C++ pointers?
You can't access a local variable once it goes out of scope. This is what it means to be a local variable. Though, Let us look at an example where you MIGHT be able to access a local variable's memory outside its scope. #include<iostream> int* foo() { int x = 3; return &x; } int main() { int* address = foo(); cout << *address; *address = 12; cout << *address; } This might give the output − 3 12 As I've mentioned before, this code MIGHT work. We are simply reading and writing to memory that USED to be the address of x. In main, you're outside of foo's scope, the address is a pointer to some random memory area. In the above example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it(you won't be using another process' memory area or any other unauthorized memory area), and nothing else has overwritten it yet. Hence, the 3 is still there. In a real program, that memory might have been re-used almost immediately and you'd break something by something like doing this. Such memory access bugs are very difficult to track and kill. When you return from foo, the program tells the OS that x's memory is no longer being used and it can be reassigned to something else. If you're lucky and it gets reassigned, and the OS doesn't catch you using it again, then you can get away with it.
[ { "code": null, "e": 1282, "s": 1062, "text": "You can't access a local variable once it goes out of scope. This is what it means to be a local variable. Though, Let us look at an example where you MIGHT be able to access a local variable's memory outside its scope." }, { "code": null, "e": 1444, "s": 1282, "text": "#include<iostream>\nint* foo() {\n int x = 3;\n return &x;\n}\nint main() {\n int* address = foo();\n cout << *address;\n *address = 12;\n cout << *address;\n}" }, { "code": null, "e": 1473, "s": 1444, "text": "This might give the output −" }, { "code": null, "e": 1478, "s": 1473, "text": "3\n12" }, { "code": null, "e": 1998, "s": 1478, "text": "As I've mentioned before, this code MIGHT work. We are simply reading and writing to memory that USED to be the address of x. In main, you're outside of foo's scope, the address is a pointer to some random memory area. In the above example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it(you won't be using another process' memory area or any other unauthorized memory area), and nothing else has overwritten it yet. Hence, the 3 is still there." }, { "code": null, "e": 2190, "s": 1998, "text": "In a real program, that memory might have been re-used almost immediately and you'd break something by something like doing this. Such memory access bugs are very difficult to track and kill." }, { "code": null, "e": 2441, "s": 2190, "text": "When you return from foo, the program tells the OS that x's memory is no longer being used and it can be reassigned to something else. If you're lucky and it gets reassigned, and the OS doesn't catch you using it again, then you can get away with it." } ]
Recursive Programming. How to solve a problem by pretending... | by Tom Grigg | Towards Data Science
Despite often being introduced early-on in most ventures into programming, the concept of recursion can seem strange and potentially off-putting upon first encountering it. It seems almost paradoxical: how can we find a solution to a problem using the solution to the same problem? For those trying to get to grips with the concept of recursion, I often feel it can be beneficial to first realise that recursion is more than just a programmatic practise — it is a philosophy of problem solving that is suitable for problems that can be worked on and partially solved, leaving the remainder of the problem in the same form, but easier or smaller in some way. This does not just apply to functions in programming; we can frame simple everyday problems using recursion. For example, take me, writing this post: let’s say I want to make it around 1000 words long, if I aim to write 100 words every time I open it up, then the first time I write 100 words, and leave myself 900 words left to write. Next time, I write 100 words and only have 800 to go. I can continue this until I have 0 words left to write. Each time, I partially solve the problem and the remaining problem is being reduced. The code for writing my post could look like this: write_words(words_left): if words left > 0: write_100_words() words_left = words_left - 100 write_words(words_left) I could also implement this algorithm iteratively: write_words(words_left): while words_left > 0: write_100_words() words_left = words_left - 100 If you walk the function call write_words(1000) through with either implementation, you will find that they have exactly the same behaviour. In fact, every problem we can solve using recursion, we can also solve using iteration (for and while loops). So why would we ever choose to use recursion? Believe it or not, once we get to grips with it, some problems are easier to solve using recursion than they are to solve using iteration. Sometimes recursion is more efficient, and sometimes it is more readable; sometimes recursion is neither faster nor more readable, but quicker to implement. There are data-structures, such as trees, that are well-suited to recursive algorithms. There are even some programming languages with no concept of a loop — purely functional languages such as Haskell depend entirely on recursion for iterative problem solving. The point is simple: You don’t have to understand recursion to be a programmer, but you do have to understand recursion to start to become a good programmer. In fact, I’d go as far as to say that understanding recursion is part of being a good problem solver, all programming aside! In general, with recursion we try to break down a more complex problem into a simple step towards the solution and a remainder that is an easier version of the same problem. We can then repeat this process, taking the same step towards the solution each time, until we reach a version of our problem with a very simple solution (referred to as a base case). The simple solution to our base case aggregated with the steps we took to get there then form a solution to our original problem. Suppose we are given some actual data of some data-type, call it do. The idea with recursion is to pretend that we have already solved the problem or computed the desired function f for all forms of this data-type that are simpler than do according to some degree of difficulty that we need to define. Then, if we can find a way of expressing f(do) in terms of one or more f(d)s, where all of these d s are less difficult (have smaller degree) than do, then we have found a way to reduce and solve for f(do). We repeat this process, and hopefully, at some point, the remaining f(d)s will get so simple that we can easily implement a fixed, closed solution to them. Then, our solution to the original problem will reveal itself as our solutions to progressively simpler problems aggregate and cascade back up to the top. In the above example of writing this post, the data is the text contained in this document waiting to be written, and the degree of difficulty is the length of the document. It’s a bit of a contrived example, but assuming I’ve already solved the problem f(900) of how to write 900 words, then all I need to do to solve f(1000) is to write 100 words and then execute my solution for 900 words, f(900). A better example is found in considering the Fibonacci numbers, where the 1st Fibonacci number is 0, the 2nd is 1 and the nth Fibonacci number is equal to the sum of the previous two. Let’s say we have a Fibonacci function that tells us the nth Fibonacci number: fib(n): if n == 0: return 0 if n == 1: return 1 else: return fib(n-1) + fib(n-2) What does the execution of this function look like? Let’s try fib(4) : A useful mantra to adopt when solving problems recursively is ‘fake it ’til you make it’, that is, pretend you’ve already solved the problem for a simpler case, and then try to reduce the larger problem to use the solution for this simpler case. If a problem is suited to recursion, there should actually only be a small number of simple cases which you need to explicitly solve, i.e. this method of reducing to a simpler problem can be used to solve every other case. This is exemplified in the Fibonacci example fib where to define fib(n) we just act like we've already computed fib(n-1) and fib(n-2) and, as we hoped, this cascades and reduces the problem to progressively simpler cases, until we reach fib(0) and fib(1) which have fixed and easy solutions. Recursion is somewhat nuanced and really depends on what problem you’re trying to solve. However, there are some general steps we can come up with that can more or less lead us in the right direction. This strategy is contained in three steps: Order Your DataSolve the Little CasesSolve the Big Cases Order Your Data Solve the Little Cases Solve the Big Cases As I’ve said before, I think it can be useful to carry an example through as we learn, but remember that recursion is problem dependent and so try to focus on the general principles here. We’ll use the simple example of reversing a string, i.e. we want to write the function reverse such that reverse('Hello world') = 'dlrow olleH'. I’d recommend going back and seeing how these steps apply to the Fibonacci function, and then take them and try them on some other examples (there are plenty of exercises online). This step is absolutely the key to getting started in solving a problem recursively, and yet it is often overlooked or performed implicitly. Whatever data we are operating on, whether it is numbers, strings, lists, binary trees or people, it is necessary to explicitly find an appropriate ordering that gives us a direction to move in to make the problem smaller. This ordering depends entirely on the problem, but a good start is to think of the obvious orderings: numbers come with their own ordering, strings and lists can be ordered by their length, binary trees can be ordered by depth, and people can be ordered in an infinite number of sensible ways, e.g. height, weight or rank in an organisation. As previously mentioned, this ordering should correspond to the degree of difficulty for the problem we are trying to solve. Once we’ve ordered our data, we can think of it as something that we can reduce. In fact, we can write out our ordering as a sequence: 0, 1, 2, ..., n for integers (i.e. for integer data d, degree(d) = d) [], [■], [■, ■], ..., [■, ... , ■] for lists(notice len = 0, len = 1, ..., len = n i.e. for list data d, degree(d) = len(d)) Moving from right to left we move through the general (‘big’) cases, to the base (‘little’) cases. For our reverse example, we are operating on a string, and we can choose the length of the string as an ordering or degree of our problem. This is normally the easy part. Once we have the correct ordering, we need to look at the smallest elements in our ordering, and decide how we are going to handle them. Usually there is an obvious solution: in the case of reverse(s), once we get to len(s) == 0 and we have reverse('') then we know our answer, because reversing the empty string would do nothing, i.e. we’d just return the empty string since we have no characters to move around. Once we have solved our base cases, and we know our ordering, then solving the general case is as simple as reducing the problem in such a way that the degree of the data we’re operating on moves towards the base cases. We need to be careful that we don’t miss any of the little cases out: the reason they’re called base cases is because they cover the base of the ordering — in more complicated recursion problems it is common to miss a base case so that the reduction step shoots past the sensible end of our ordering and starts operating on nonsense data, or resulting in an error. Here, we handle the data rightwards in our ordering, that is, data of high degree. Usually, we consider data of arbitrary degree and aim to find a way to solve the problem by reducing it to an expression containing the same problem of lesser degree, e.g. in our Fibonacci example we started with arbitrary n and reduced fib(n) to fib(n-1) + fib(n-2) which is an expression containing two instances of the problem we started with, of lesser degree (n-1 and n-2, respectively). When it comes to reverse we can consider an arbitrary string of length n, and we can pretend our reverse function works on all strings of length less than n. How can we use this to solve the problem for a string of length n? Well, we could just reverse the string containing everything except the last character, and then stick that last character on the front. In code: reverse(string) = reverse(string[-1]) + reverse(string[:-1]) where string[-1] corresponds to the last character, and string[:-1] corresponds to the string without the last character (these are pythonisms). That last reverse(string[:-1]) term is our original problem, but operating on a string of length n-1, i.e. we’ve expressed our original problem in terms of a step towards the solution combined with the same problem of reduced degree. Putting the solution to our reverse function together, we get the following: reverse(string): if len(string) == 0: return '' else: return string[-1] + reverse(string[:-1]) There is often more than one recursive case that needs to be considered as data of a given data-type can take slightly different forms, but this is entirely problem dependent. For an example, consider if we wanted to flatten a list of items, some of which could themselves be lists, we would need to distinguish between the cases where the item we are pulling out of the list is an individual item or a sublist, leading to at least two recursive cases. The only real way to get better at recursion is practise. Have a look online for some of the thousands of recursion problems, or challenge yourself to come up with problems that you think might be suited to recursion. Once you inevitably get the hang of recursion, remember that if you find yourself having difficulty solving a problem recursively, then try iteration instead. Outside of learning to be a better programmer, recursion is a method of problem solving to make your life easier. If a problem isn’t suited to recursion, it just isn’t suited to recursion; you’ll develop a feel for this as you spend more time approaching problems that lend themselves to either recursive or iterative approaches. Sometimes in more difficult recursion problems, steps 2 and 3 in the strategy we saw above take the form of a more cyclic feedback-loop process. If you can’t find an overall solution to the problem quickly, the best process is to solve the recursive/‘big’ cases that you can think of, and solve the base/‘little’ cases that you can think of, and then see how your method breaks on different pieces of data. This should unveil any missing base and recursive cases, or any that are interacting with each other poorly and need to be rethought. Finally, recall that knowing your ordering is the most important step to solving a recursive problem, and your aim is always to cover both the rightward (recursive) and leftmost (base) cases of this ordering to solve the problem for all data of the given type. That’s a wrap — thanks for reading! If you enjoyed this introduction to recursion, feel free to get in touch with me (Tom Grigg) regarding any thoughts, queries or suggestions for future blog posts! Now, back to working on my data science posts, stay tuned!
[ { "code": null, "e": 454, "s": 172, "text": "Despite often being introduced early-on in most ventures into programming, the concept of recursion can seem strange and potentially off-putting upon first encountering it. It seems almost paradoxical: how can we find a solution to a problem using the solution to the same problem?" }, { "code": null, "e": 1361, "s": 454, "text": "For those trying to get to grips with the concept of recursion, I often feel it can be beneficial to first realise that recursion is more than just a programmatic practise — it is a philosophy of problem solving that is suitable for problems that can be worked on and partially solved, leaving the remainder of the problem in the same form, but easier or smaller in some way. This does not just apply to functions in programming; we can frame simple everyday problems using recursion. For example, take me, writing this post: let’s say I want to make it around 1000 words long, if I aim to write 100 words every time I open it up, then the first time I write 100 words, and leave myself 900 words left to write. Next time, I write 100 words and only have 800 to go. I can continue this until I have 0 words left to write. Each time, I partially solve the problem and the remaining problem is being reduced." }, { "code": null, "e": 1412, "s": 1361, "text": "The code for writing my post could look like this:" }, { "code": null, "e": 1538, "s": 1412, "text": "write_words(words_left): if words left > 0: write_100_words() words_left = words_left - 100 write_words(words_left)" }, { "code": null, "e": 1589, "s": 1538, "text": "I could also implement this algorithm iteratively:" }, { "code": null, "e": 1691, "s": 1589, "text": "write_words(words_left): while words_left > 0: write_100_words() words_left = words_left - 100" }, { "code": null, "e": 1988, "s": 1691, "text": "If you walk the function call write_words(1000) through with either implementation, you will find that they have exactly the same behaviour. In fact, every problem we can solve using recursion, we can also solve using iteration (for and while loops). So why would we ever choose to use recursion?" }, { "code": null, "e": 2829, "s": 1988, "text": "Believe it or not, once we get to grips with it, some problems are easier to solve using recursion than they are to solve using iteration. Sometimes recursion is more efficient, and sometimes it is more readable; sometimes recursion is neither faster nor more readable, but quicker to implement. There are data-structures, such as trees, that are well-suited to recursive algorithms. There are even some programming languages with no concept of a loop — purely functional languages such as Haskell depend entirely on recursion for iterative problem solving. The point is simple: You don’t have to understand recursion to be a programmer, but you do have to understand recursion to start to become a good programmer. In fact, I’d go as far as to say that understanding recursion is part of being a good problem solver, all programming aside!" }, { "code": null, "e": 3317, "s": 2829, "text": "In general, with recursion we try to break down a more complex problem into a simple step towards the solution and a remainder that is an easier version of the same problem. We can then repeat this process, taking the same step towards the solution each time, until we reach a version of our problem with a very simple solution (referred to as a base case). The simple solution to our base case aggregated with the steps we took to get there then form a solution to our original problem." }, { "code": null, "e": 4137, "s": 3317, "text": "Suppose we are given some actual data of some data-type, call it do. The idea with recursion is to pretend that we have already solved the problem or computed the desired function f for all forms of this data-type that are simpler than do according to some degree of difficulty that we need to define. Then, if we can find a way of expressing f(do) in terms of one or more f(d)s, where all of these d s are less difficult (have smaller degree) than do, then we have found a way to reduce and solve for f(do). We repeat this process, and hopefully, at some point, the remaining f(d)s will get so simple that we can easily implement a fixed, closed solution to them. Then, our solution to the original problem will reveal itself as our solutions to progressively simpler problems aggregate and cascade back up to the top." }, { "code": null, "e": 4538, "s": 4137, "text": "In the above example of writing this post, the data is the text contained in this document waiting to be written, and the degree of difficulty is the length of the document. It’s a bit of a contrived example, but assuming I’ve already solved the problem f(900) of how to write 900 words, then all I need to do to solve f(1000) is to write 100 words and then execute my solution for 900 words, f(900)." }, { "code": null, "e": 4801, "s": 4538, "text": "A better example is found in considering the Fibonacci numbers, where the 1st Fibonacci number is 0, the 2nd is 1 and the nth Fibonacci number is equal to the sum of the previous two. Let’s say we have a Fibonacci function that tells us the nth Fibonacci number:" }, { "code": null, "e": 4894, "s": 4801, "text": "fib(n): if n == 0: return 0 if n == 1: return 1 else: return fib(n-1) + fib(n-2)" }, { "code": null, "e": 4965, "s": 4894, "text": "What does the execution of this function look like? Let’s try fib(4) :" }, { "code": null, "e": 5726, "s": 4965, "text": "A useful mantra to adopt when solving problems recursively is ‘fake it ’til you make it’, that is, pretend you’ve already solved the problem for a simpler case, and then try to reduce the larger problem to use the solution for this simpler case. If a problem is suited to recursion, there should actually only be a small number of simple cases which you need to explicitly solve, i.e. this method of reducing to a simpler problem can be used to solve every other case. This is exemplified in the Fibonacci example fib where to define fib(n) we just act like we've already computed fib(n-1) and fib(n-2) and, as we hoped, this cascades and reduces the problem to progressively simpler cases, until we reach fib(0) and fib(1) which have fixed and easy solutions." }, { "code": null, "e": 5970, "s": 5726, "text": "Recursion is somewhat nuanced and really depends on what problem you’re trying to solve. However, there are some general steps we can come up with that can more or less lead us in the right direction. This strategy is contained in three steps:" }, { "code": null, "e": 6027, "s": 5970, "text": "Order Your DataSolve the Little CasesSolve the Big Cases" }, { "code": null, "e": 6043, "s": 6027, "text": "Order Your Data" }, { "code": null, "e": 6066, "s": 6043, "text": "Solve the Little Cases" }, { "code": null, "e": 6086, "s": 6066, "text": "Solve the Big Cases" }, { "code": null, "e": 6599, "s": 6086, "text": "As I’ve said before, I think it can be useful to carry an example through as we learn, but remember that recursion is problem dependent and so try to focus on the general principles here. We’ll use the simple example of reversing a string, i.e. we want to write the function reverse such that reverse('Hello world') = 'dlrow olleH'. I’d recommend going back and seeing how these steps apply to the Fibonacci function, and then take them and try them on some other examples (there are plenty of exercises online)." }, { "code": null, "e": 7430, "s": 6599, "text": "This step is absolutely the key to getting started in solving a problem recursively, and yet it is often overlooked or performed implicitly. Whatever data we are operating on, whether it is numbers, strings, lists, binary trees or people, it is necessary to explicitly find an appropriate ordering that gives us a direction to move in to make the problem smaller. This ordering depends entirely on the problem, but a good start is to think of the obvious orderings: numbers come with their own ordering, strings and lists can be ordered by their length, binary trees can be ordered by depth, and people can be ordered in an infinite number of sensible ways, e.g. height, weight or rank in an organisation. As previously mentioned, this ordering should correspond to the degree of difficulty for the problem we are trying to solve." }, { "code": null, "e": 7565, "s": 7430, "text": "Once we’ve ordered our data, we can think of it as something that we can reduce. In fact, we can write out our ordering as a sequence:" }, { "code": null, "e": 7635, "s": 7565, "text": "0, 1, 2, ..., n for integers (i.e. for integer data d, degree(d) = d)" }, { "code": null, "e": 7760, "s": 7635, "text": "[], [■], [■, ■], ..., [■, ... , ■] for lists(notice len = 0, len = 1, ..., len = n i.e. for list data d, degree(d) = len(d))" }, { "code": null, "e": 7998, "s": 7760, "text": "Moving from right to left we move through the general (‘big’) cases, to the base (‘little’) cases. For our reverse example, we are operating on a string, and we can choose the length of the string as an ordering or degree of our problem." }, { "code": null, "e": 9029, "s": 7998, "text": "This is normally the easy part. Once we have the correct ordering, we need to look at the smallest elements in our ordering, and decide how we are going to handle them. Usually there is an obvious solution: in the case of reverse(s), once we get to len(s) == 0 and we have reverse('') then we know our answer, because reversing the empty string would do nothing, i.e. we’d just return the empty string since we have no characters to move around. Once we have solved our base cases, and we know our ordering, then solving the general case is as simple as reducing the problem in such a way that the degree of the data we’re operating on moves towards the base cases. We need to be careful that we don’t miss any of the little cases out: the reason they’re called base cases is because they cover the base of the ordering — in more complicated recursion problems it is common to miss a base case so that the reduction step shoots past the sensible end of our ordering and starts operating on nonsense data, or resulting in an error." }, { "code": null, "e": 9505, "s": 9029, "text": "Here, we handle the data rightwards in our ordering, that is, data of high degree. Usually, we consider data of arbitrary degree and aim to find a way to solve the problem by reducing it to an expression containing the same problem of lesser degree, e.g. in our Fibonacci example we started with arbitrary n and reduced fib(n) to fib(n-1) + fib(n-2) which is an expression containing two instances of the problem we started with, of lesser degree (n-1 and n-2, respectively)." }, { "code": null, "e": 9876, "s": 9505, "text": "When it comes to reverse we can consider an arbitrary string of length n, and we can pretend our reverse function works on all strings of length less than n. How can we use this to solve the problem for a string of length n? Well, we could just reverse the string containing everything except the last character, and then stick that last character on the front. In code:" }, { "code": null, "e": 9938, "s": 9876, "text": "reverse(string) = reverse(string[-1]) + reverse(string[:-1]) " }, { "code": null, "e": 10317, "s": 9938, "text": "where string[-1] corresponds to the last character, and string[:-1] corresponds to the string without the last character (these are pythonisms). That last reverse(string[:-1]) term is our original problem, but operating on a string of length n-1, i.e. we’ve expressed our original problem in terms of a step towards the solution combined with the same problem of reduced degree." }, { "code": null, "e": 10394, "s": 10317, "text": "Putting the solution to our reverse function together, we get the following:" }, { "code": null, "e": 10497, "s": 10394, "text": "reverse(string): if len(string) == 0: return '' else: return string[-1] + reverse(string[:-1])" }, { "code": null, "e": 10950, "s": 10497, "text": "There is often more than one recursive case that needs to be considered as data of a given data-type can take slightly different forms, but this is entirely problem dependent. For an example, consider if we wanted to flatten a list of items, some of which could themselves be lists, we would need to distinguish between the cases where the item we are pulling out of the list is an individual item or a sublist, leading to at least two recursive cases." }, { "code": null, "e": 11657, "s": 10950, "text": "The only real way to get better at recursion is practise. Have a look online for some of the thousands of recursion problems, or challenge yourself to come up with problems that you think might be suited to recursion. Once you inevitably get the hang of recursion, remember that if you find yourself having difficulty solving a problem recursively, then try iteration instead. Outside of learning to be a better programmer, recursion is a method of problem solving to make your life easier. If a problem isn’t suited to recursion, it just isn’t suited to recursion; you’ll develop a feel for this as you spend more time approaching problems that lend themselves to either recursive or iterative approaches." }, { "code": null, "e": 12198, "s": 11657, "text": "Sometimes in more difficult recursion problems, steps 2 and 3 in the strategy we saw above take the form of a more cyclic feedback-loop process. If you can’t find an overall solution to the problem quickly, the best process is to solve the recursive/‘big’ cases that you can think of, and solve the base/‘little’ cases that you can think of, and then see how your method breaks on different pieces of data. This should unveil any missing base and recursive cases, or any that are interacting with each other poorly and need to be rethought." }, { "code": null, "e": 12459, "s": 12198, "text": "Finally, recall that knowing your ordering is the most important step to solving a recursive problem, and your aim is always to cover both the rightward (recursive) and leftmost (base) cases of this ordering to solve the problem for all data of the given type." }, { "code": null, "e": 12495, "s": 12459, "text": "That’s a wrap — thanks for reading!" }, { "code": null, "e": 12658, "s": 12495, "text": "If you enjoyed this introduction to recursion, feel free to get in touch with me (Tom Grigg) regarding any thoughts, queries or suggestions for future blog posts!" } ]
Deploying an ML Model on Google Compute Engine | by Alara Dirik | Towards Data Science
Deploying and maintaining machine learning models as a web service can be expensive and tricky. I’ve recently started using Compute Engine for my projects and found that Google Cloud, very much like AWS, has a rather steep learning curve. In this post, I will be discussing how to deploy an object detection model as an API with Flask on Google Compute Engine. The accompanying code for this tutorial can be found here. Using a pre-trained object detection model to detect and annotate various objects within images. Building a simple Flask API that receives images through POST requests and serves the predicted labels, bounding box coordinates, box colors and confidence levels of detected objects. Setting up a Google Cloud project and configuring a Compute Engine instance. Installing and setting up a virtual environment with Miniconda. Deploying a Flask app and setting up a stable production server that can handle a high number of requests with NGINX and Gunicorn. Requirements: Basic knowledge of object detection, Flask and a Google Cloud account with billing enabled. Note: Google Cloud has a free tier program that offers 300$ in credits for new users. App Engine vs Compute Engine App Engine and Compute Engine are two of the Google Cloud products you can use to deploy ML models. The main difference between the two services is Compute Engine is an Infrastructure-as-a-Service (IaaS) whereas App Engine is a Platform-as-a-Service (PaaS) built on top of Compute Engine. This basically means that Compute Engine is a bare-bones service whereas App Engine provides extra services to make deploying, maintaining and scaling web apps easier, albeit at a higher cost per hour. The good thing about App Engine is it automatically scales up or down based on the volume of incoming requests and allows you to focus on apps, rather than system administration. However, it’s cheaper to keep a Compute Engine instance running if you have a constant load of API requests. I won’t be going into the details of the object detection code in this tutorial. The code I will be using is an edited version of Adrian Rosebrock’s excellent tutorial on YOLO Object Detection with Open CV and can be found here. We’ll be using the YOLOv3 model trained on the COCO dataset, a large-scale object detection, segmentation, and captioning dataset that contains 330K images in 80 object categories. .├── yolo-coco # Pre-trained model files └── coco.names # Object labels (person, car, etc.) └── yolov3.cfg # Model configuration └── yolov3.weights # Model weights ├── app.py # Flask app serving predictions├── yolo.py # Functions to generate predictions├── requirements.txt # Dependencies└── README.md The two main functions in yolo.py are download_model_weights and get_predictions, which expects a single encoded image as input. The get_predictions function processes the encoded input image, loads and runs the model and returns the box coordinates, box display color, label and confidence level for each detected object. The model weights are automatically downloaded the first time you run the app locally or on GCE. Our Flask app sits in app.py and has a single endpoint /predict. On a higher level, we want our app to: Be accessible by other computers (your customers!) Accept POST requests with encoded images at the endpoint /predict Call the object detection functions in yolo.py and return the predictions as the response Stay alive at all times and be capable of handling a high number of requests from flask import Flask, jsonify, requestfrom yolo import get_predictionsapp = Flask(__name__)@app.route(“/predict”, methods=[‘POST’])def predict(): predictions = get_predictions(request) return jsonify(predictions)if __name__ == “__main__”: app.run(host=’0.0.0.0', port=5000, debug=True) Flask by default hosts the app on 127.0.0.1 which refers to the local IP address of your computer and only can be accessed by programs running on the same computer as your exposed server. Obviously, we need our app to be accessible outside the Compute Engine instance it will be deployed in. Changing the host address as 0.0.0.0 allows us to access the app from other computers using the the GCE instance’s external IP address. The first thing we need to is to create a project. You can either use an existing Google Cloud project or create a new one over here. I named my project demo1 and Compute Engine instance flask-demo but the project and instance names can be anything you like. Once you created and/or selected a project, you can head over to Compute Engine > VM instances to create a new GCE instance. We can now configure our VM instance, I selected europe-west2 as the region but any region/zone will do for this tutorial. Compute Engine also allows you to change and customize the number of CPU cores, memory, GPUs, and boot disk. To follow along the tutorial, select the g1-small (or a larger) instance, change the boot disk to Ubuntu 18.04 LTS and set the Firewall settings to allow HTTP traffic. Pricing might differ across regions but this particular configuration got me a monthly estimate cost of $17.04. It might take a few minutes to boot up the VM instance once you click create. We enabled HTTP traffic for our GCE instance but there is one more thing we need to do. Our Flask app will be running on port 5000 and Google Cloud, by default, doesn’t listen to port 5000. The default network in the project comes with default firewall rules “default-allow-http” and “default-allow-https” to allow traffic on port 80 and 443. We need to head over to VPC network > Firewall rules and create a new firewall rule to accept incoming connections and requests on the port our app will be running on. Click Create a firewall rule and configure the settings as shown below. Make sure to add http-server to target tags, 0.0.0.0/0 to source IP ranges and set 5000 as the specified port. Time to configure our GCE instance! You can list your Compute Engine instances at Compute Engine > VM instances. Make sure to note down the External IP address of your instance, you will need it to access your app and send API requests outside the GCE instance. Click the SSH button to login to the instance from your browser. Note: Be careful when copying/pasting commands. Some characters might not transfer exactly as intended. If all else fails, write the command out manually. We are now ready to setup our production environment. We will be using Miniconda to manage the dependencies and the environment. On your instance’s SSH terminal, run: # update system packages and install the required packagessudo apt-get updatesudo apt-get install bzip2 libxml2-dev libsm6 libxrender1 libfontconfig1# clone the project repogit clone https://github.com/alaradirik/google-cloud-flask-tutorial.git# download and install minicondawget https://repo.anaconda.com/miniconda/Miniconda3-4.7.10-Linux-x86_64.shbash Miniconda3-4.7.10-Linux-x86_64.sh Follow the instructions and agree to the terms to install Miniconda. Keep the default installation location and answer “yes” to “Do you wish the installer to initialize Miniconda3 by running conda init?”. Once installed, we will need to export the full path of Miniconda to make it executable by the conda command. We can then go ahead and create a new conda environment. You might need to close and re-open the SSH terminal for changes to take effect after running conda init. export PATH=/home/<your name here>/miniconda3/bin:$PATHrm Miniconda3-4.7.10-Linux-x86_64.sh# confirm installationwhich conda# create and activate a new environmentconda create -n flask-tutorial python=3.7conda activate flask-tutorial Here is the fun part! We already installed Miniconda and cloned the project repo, the next thing we need to do is to install the project dependencies, start the app and make sure that it can receive requests from other computers. # go to project root and install the requirementscd google-cloud-flask-tutorialpip install -r requirements.txt# run the apppython app.py You can test your app by sending a POST request from your local computer terminal to the API using the external IP address of instance. If you don’t have the external IP, head over to Compute Engine > VM instances to find it. The project repo on Github includes a sample request script named request.py and an images folder containing sample images to test the app. You can either clone the repo to your local computer or download the files from the instance’s SSH terminal using the Settings > Download file button. request.py sends an encoded image to the /predict endpoint of our API over a POST request to the instance. You should insert in the external IP of your instance into the url and create a virtual environment with the dependencies to execute request.py. Our app sends the box coordinates, box display color, label and confidence level of each detected object as the response. request.py uses these values to create and save an annotated version of the image on the client side. # request.py dependenciesimport requestsimport jsonimport cv2url = "http://<external IP address>:5000/predict"headers = {"content-type": "image/jpg"}# encode imageimage = cv2.imread('images/baggage_claim.jpg')_, img_encoded = cv2.imencode(".jpg", image)# send HTTP request to the serverresponse = requests.post(url, data=img_encoded.tostring(), headers=headers)predictions = response.json()# annotate the imagefor pred in predictions: # print prediction print(pred) # extract the bounding box coordinates (x, y) = (pred["boxes"][0], pred["boxes"][1]) (w, h) = (pred["boxes"][2], pred["boxes"][3]) # draw a bounding box rectangle and label on the image cv2.rectangle(image, (x, y), (x + w, y + h), pred["color"], 2) text = "{}: {:.4f}".format(pred["label"], pred["confidence"]) cv2.putText( image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, pred["color"], 2 )# save annotated imagecv2.imwrite("annotated_image.jpg", image) It will take a bit longer to receive a response the first time you send a request, this is because model weights need to be downloaded first. Flask is not a web server. It is a micro web application framework: a set of tools and libraries that make it easier and prettier to build web applications. As a refresher, communication between clients and servers is done by requests and responses: A client sends an HTTP request to the webAn web server receives the requestThe server runs an application to process the requestThe server returns an HTTP response (output) to the clientThe client receives the response A client sends an HTTP request to the web An web server receives the request The server runs an application to process the request The server returns an HTTP response (output) to the client The client receives the response Flask can’t handle the HTTP requests and responses on its own but it comes with Werkzeug, a WSGI utility library that provides a simple web server for development purposes. While Flask’s development server is good enough to test the main functionality of the app, we shouldn’t use it in production. As the official docs state: While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time. For this tutorial, we will be using Gunicorn and NGINX to create a production server that can handle multiple users and a high number of incoming requests, without users/clients having to wait noticeable amounts of time. Gunicorn is a web server that can execute Python code (also called a WSGI server), we need to couple Gunicorn with NGINX, another web server, because there there are features of a non-Python based server (non-WSGI server) that we’d like to utilize: we can distribute requests through NGINX to multiple Gunicorn instances, serve static content without having to communicate with the Flask app, efficiently handle high connection levels, etc. Heading back to the GCE instance terminal, the first thing we need to do is to install and start NGINX. cdsudo apt-get install nginx-fullsudo /etc/init.d/nginx start Next, we need to remove the default configuration file and create a new site configuration file for our flask application. Configuration files in sites-available are not active until they are enabled so we need to create a link for the new configuration file in sites-enabled. # remove default configuration filesudo rm /etc/nginx/sites-enabled/default# create a new site configuration filesudo touch /etc/nginx/sites-available/flask_projectsudo ln -s /etc/nginx/sites-available/flask_project /etc/nginx/sites-enabled/flask_project We can now edit the configuration file for our app by opening the file with an editor like nano or vim: sudo nano /etc/nginx/sites-enabled/flask_project Copy and paste the code below and save the configuration file. server { location / { proxy_pass http://0.0.0.0:5000; }} Restart the NGINX server. sudo /etc/init.d/nginx restart We are almost done! The last thing we need to do is to head back to the project folder and bind the Flask app to the Gunicorn server. One important thing to keep in mind is we want the server and the Flask app keep running after we close the terminal window. Adding the daemon flag keeps the process running in background. cd google-cloud-flask-tutorialgunicorn --bind 0.0.0.0:5000 app:app --daemon That’s it! You deployed an object detection model as an API on Compute Engine and setup a production server. You can close the Compute Engine terminal and send requests to the API anytime you want. Hope you enjoyed the tutorial! If you have any questions or comments please free to get in touch using the comment section below or through Linkedin.
[ { "code": null, "e": 533, "s": 172, "text": "Deploying and maintaining machine learning models as a web service can be expensive and tricky. I’ve recently started using Compute Engine for my projects and found that Google Cloud, very much like AWS, has a rather steep learning curve. In this post, I will be discussing how to deploy an object detection model as an API with Flask on Google Compute Engine." }, { "code": null, "e": 592, "s": 533, "text": "The accompanying code for this tutorial can be found here." }, { "code": null, "e": 689, "s": 592, "text": "Using a pre-trained object detection model to detect and annotate various objects within images." }, { "code": null, "e": 873, "s": 689, "text": "Building a simple Flask API that receives images through POST requests and serves the predicted labels, bounding box coordinates, box colors and confidence levels of detected objects." }, { "code": null, "e": 950, "s": 873, "text": "Setting up a Google Cloud project and configuring a Compute Engine instance." }, { "code": null, "e": 1014, "s": 950, "text": "Installing and setting up a virtual environment with Miniconda." }, { "code": null, "e": 1145, "s": 1014, "text": "Deploying a Flask app and setting up a stable production server that can handle a high number of requests with NGINX and Gunicorn." }, { "code": null, "e": 1251, "s": 1145, "text": "Requirements: Basic knowledge of object detection, Flask and a Google Cloud account with billing enabled." }, { "code": null, "e": 1337, "s": 1251, "text": "Note: Google Cloud has a free tier program that offers 300$ in credits for new users." }, { "code": null, "e": 1366, "s": 1337, "text": "App Engine vs Compute Engine" }, { "code": null, "e": 1655, "s": 1366, "text": "App Engine and Compute Engine are two of the Google Cloud products you can use to deploy ML models. The main difference between the two services is Compute Engine is an Infrastructure-as-a-Service (IaaS) whereas App Engine is a Platform-as-a-Service (PaaS) built on top of Compute Engine." }, { "code": null, "e": 2145, "s": 1655, "text": "This basically means that Compute Engine is a bare-bones service whereas App Engine provides extra services to make deploying, maintaining and scaling web apps easier, albeit at a higher cost per hour. The good thing about App Engine is it automatically scales up or down based on the volume of incoming requests and allows you to focus on apps, rather than system administration. However, it’s cheaper to keep a Compute Engine instance running if you have a constant load of API requests." }, { "code": null, "e": 2555, "s": 2145, "text": "I won’t be going into the details of the object detection code in this tutorial. The code I will be using is an edited version of Adrian Rosebrock’s excellent tutorial on YOLO Object Detection with Open CV and can be found here. We’ll be using the YOLOv3 model trained on the COCO dataset, a large-scale object detection, segmentation, and captioning dataset that contains 330K images in 80 object categories." }, { "code": null, "e": 2949, "s": 2555, "text": ".├── yolo-coco # Pre-trained model files └── coco.names # Object labels (person, car, etc.) └── yolov3.cfg # Model configuration └── yolov3.weights # Model weights ├── app.py # Flask app serving predictions├── yolo.py # Functions to generate predictions├── requirements.txt # Dependencies└── README.md" }, { "code": null, "e": 3369, "s": 2949, "text": "The two main functions in yolo.py are download_model_weights and get_predictions, which expects a single encoded image as input. The get_predictions function processes the encoded input image, loads and runs the model and returns the box coordinates, box display color, label and confidence level for each detected object. The model weights are automatically downloaded the first time you run the app locally or on GCE." }, { "code": null, "e": 3473, "s": 3369, "text": "Our Flask app sits in app.py and has a single endpoint /predict. On a higher level, we want our app to:" }, { "code": null, "e": 3524, "s": 3473, "text": "Be accessible by other computers (your customers!)" }, { "code": null, "e": 3590, "s": 3524, "text": "Accept POST requests with encoded images at the endpoint /predict" }, { "code": null, "e": 3680, "s": 3590, "text": "Call the object detection functions in yolo.py and return the predictions as the response" }, { "code": null, "e": 3757, "s": 3680, "text": "Stay alive at all times and be capable of handling a high number of requests" }, { "code": null, "e": 4052, "s": 3757, "text": "from flask import Flask, jsonify, requestfrom yolo import get_predictionsapp = Flask(__name__)@app.route(“/predict”, methods=[‘POST’])def predict(): predictions = get_predictions(request) return jsonify(predictions)if __name__ == “__main__”: app.run(host=’0.0.0.0', port=5000, debug=True)" }, { "code": null, "e": 4480, "s": 4052, "text": "Flask by default hosts the app on 127.0.0.1 which refers to the local IP address of your computer and only can be accessed by programs running on the same computer as your exposed server. Obviously, we need our app to be accessible outside the Compute Engine instance it will be deployed in. Changing the host address as 0.0.0.0 allows us to access the app from other computers using the the GCE instance’s external IP address." }, { "code": null, "e": 4614, "s": 4480, "text": "The first thing we need to is to create a project. You can either use an existing Google Cloud project or create a new one over here." }, { "code": null, "e": 4864, "s": 4614, "text": "I named my project demo1 and Compute Engine instance flask-demo but the project and instance names can be anything you like. Once you created and/or selected a project, you can head over to Compute Engine > VM instances to create a new GCE instance." }, { "code": null, "e": 5096, "s": 4864, "text": "We can now configure our VM instance, I selected europe-west2 as the region but any region/zone will do for this tutorial. Compute Engine also allows you to change and customize the number of CPU cores, memory, GPUs, and boot disk." }, { "code": null, "e": 5376, "s": 5096, "text": "To follow along the tutorial, select the g1-small (or a larger) instance, change the boot disk to Ubuntu 18.04 LTS and set the Firewall settings to allow HTTP traffic. Pricing might differ across regions but this particular configuration got me a monthly estimate cost of $17.04." }, { "code": null, "e": 5454, "s": 5376, "text": "It might take a few minutes to boot up the VM instance once you click create." }, { "code": null, "e": 5797, "s": 5454, "text": "We enabled HTTP traffic for our GCE instance but there is one more thing we need to do. Our Flask app will be running on port 5000 and Google Cloud, by default, doesn’t listen to port 5000. The default network in the project comes with default firewall rules “default-allow-http” and “default-allow-https” to allow traffic on port 80 and 443." }, { "code": null, "e": 5965, "s": 5797, "text": "We need to head over to VPC network > Firewall rules and create a new firewall rule to accept incoming connections and requests on the port our app will be running on." }, { "code": null, "e": 6148, "s": 5965, "text": "Click Create a firewall rule and configure the settings as shown below. Make sure to add http-server to target tags, 0.0.0.0/0 to source IP ranges and set 5000 as the specified port." }, { "code": null, "e": 6261, "s": 6148, "text": "Time to configure our GCE instance! You can list your Compute Engine instances at Compute Engine > VM instances." }, { "code": null, "e": 6475, "s": 6261, "text": "Make sure to note down the External IP address of your instance, you will need it to access your app and send API requests outside the GCE instance. Click the SSH button to login to the instance from your browser." }, { "code": null, "e": 6630, "s": 6475, "text": "Note: Be careful when copying/pasting commands. Some characters might not transfer exactly as intended. If all else fails, write the command out manually." }, { "code": null, "e": 6797, "s": 6630, "text": "We are now ready to setup our production environment. We will be using Miniconda to manage the dependencies and the environment. On your instance’s SSH terminal, run:" }, { "code": null, "e": 7186, "s": 6797, "text": "# update system packages and install the required packagessudo apt-get updatesudo apt-get install bzip2 libxml2-dev libsm6 libxrender1 libfontconfig1# clone the project repogit clone https://github.com/alaradirik/google-cloud-flask-tutorial.git# download and install minicondawget https://repo.anaconda.com/miniconda/Miniconda3-4.7.10-Linux-x86_64.shbash Miniconda3-4.7.10-Linux-x86_64.sh" }, { "code": null, "e": 7391, "s": 7186, "text": "Follow the instructions and agree to the terms to install Miniconda. Keep the default installation location and answer “yes” to “Do you wish the installer to initialize Miniconda3 by running conda init?”." }, { "code": null, "e": 7558, "s": 7391, "text": "Once installed, we will need to export the full path of Miniconda to make it executable by the conda command. We can then go ahead and create a new conda environment." }, { "code": null, "e": 7664, "s": 7558, "text": "You might need to close and re-open the SSH terminal for changes to take effect after running conda init." }, { "code": null, "e": 7898, "s": 7664, "text": "export PATH=/home/<your name here>/miniconda3/bin:$PATHrm Miniconda3-4.7.10-Linux-x86_64.sh# confirm installationwhich conda# create and activate a new environmentconda create -n flask-tutorial python=3.7conda activate flask-tutorial" }, { "code": null, "e": 8128, "s": 7898, "text": "Here is the fun part! We already installed Miniconda and cloned the project repo, the next thing we need to do is to install the project dependencies, start the app and make sure that it can receive requests from other computers." }, { "code": null, "e": 8265, "s": 8128, "text": "# go to project root and install the requirementscd google-cloud-flask-tutorialpip install -r requirements.txt# run the apppython app.py" }, { "code": null, "e": 8491, "s": 8265, "text": "You can test your app by sending a POST request from your local computer terminal to the API using the external IP address of instance. If you don’t have the external IP, head over to Compute Engine > VM instances to find it." }, { "code": null, "e": 8782, "s": 8491, "text": "The project repo on Github includes a sample request script named request.py and an images folder containing sample images to test the app. You can either clone the repo to your local computer or download the files from the instance’s SSH terminal using the Settings > Download file button." }, { "code": null, "e": 9034, "s": 8782, "text": "request.py sends an encoded image to the /predict endpoint of our API over a POST request to the instance. You should insert in the external IP of your instance into the url and create a virtual environment with the dependencies to execute request.py." }, { "code": null, "e": 9258, "s": 9034, "text": "Our app sends the box coordinates, box display color, label and confidence level of each detected object as the response. request.py uses these values to create and save an annotated version of the image on the client side." }, { "code": null, "e": 10253, "s": 9258, "text": "# request.py dependenciesimport requestsimport jsonimport cv2url = \"http://<external IP address>:5000/predict\"headers = {\"content-type\": \"image/jpg\"}# encode imageimage = cv2.imread('images/baggage_claim.jpg')_, img_encoded = cv2.imencode(\".jpg\", image)# send HTTP request to the serverresponse = requests.post(url, data=img_encoded.tostring(), headers=headers)predictions = response.json()# annotate the imagefor pred in predictions: # print prediction print(pred) # extract the bounding box coordinates (x, y) = (pred[\"boxes\"][0], pred[\"boxes\"][1]) (w, h) = (pred[\"boxes\"][2], pred[\"boxes\"][3]) # draw a bounding box rectangle and label on the image cv2.rectangle(image, (x, y), (x + w, y + h), pred[\"color\"], 2) text = \"{}: {:.4f}\".format(pred[\"label\"], pred[\"confidence\"]) cv2.putText( image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, pred[\"color\"], 2 )# save annotated imagecv2.imwrite(\"annotated_image.jpg\", image)" }, { "code": null, "e": 10395, "s": 10253, "text": "It will take a bit longer to receive a response the first time you send a request, this is because model weights need to be downloaded first." }, { "code": null, "e": 10552, "s": 10395, "text": "Flask is not a web server. It is a micro web application framework: a set of tools and libraries that make it easier and prettier to build web applications." }, { "code": null, "e": 10645, "s": 10552, "text": "As a refresher, communication between clients and servers is done by requests and responses:" }, { "code": null, "e": 10864, "s": 10645, "text": "A client sends an HTTP request to the webAn web server receives the requestThe server runs an application to process the requestThe server returns an HTTP response (output) to the clientThe client receives the response" }, { "code": null, "e": 10906, "s": 10864, "text": "A client sends an HTTP request to the web" }, { "code": null, "e": 10941, "s": 10906, "text": "An web server receives the request" }, { "code": null, "e": 10995, "s": 10941, "text": "The server runs an application to process the request" }, { "code": null, "e": 11054, "s": 10995, "text": "The server returns an HTTP response (output) to the client" }, { "code": null, "e": 11087, "s": 11054, "text": "The client receives the response" }, { "code": null, "e": 11414, "s": 11087, "text": "Flask can’t handle the HTTP requests and responses on its own but it comes with Werkzeug, a WSGI utility library that provides a simple web server for development purposes. While Flask’s development server is good enough to test the main functionality of the app, we shouldn’t use it in production. As the official docs state:" }, { "code": null, "e": 11579, "s": 11414, "text": "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well and by default serves only one request at a time." }, { "code": null, "e": 11800, "s": 11579, "text": "For this tutorial, we will be using Gunicorn and NGINX to create a production server that can handle multiple users and a high number of incoming requests, without users/clients having to wait noticeable amounts of time." }, { "code": null, "e": 12241, "s": 11800, "text": "Gunicorn is a web server that can execute Python code (also called a WSGI server), we need to couple Gunicorn with NGINX, another web server, because there there are features of a non-Python based server (non-WSGI server) that we’d like to utilize: we can distribute requests through NGINX to multiple Gunicorn instances, serve static content without having to communicate with the Flask app, efficiently handle high connection levels, etc." }, { "code": null, "e": 12345, "s": 12241, "text": "Heading back to the GCE instance terminal, the first thing we need to do is to install and start NGINX." }, { "code": null, "e": 12407, "s": 12345, "text": "cdsudo apt-get install nginx-fullsudo /etc/init.d/nginx start" }, { "code": null, "e": 12684, "s": 12407, "text": "Next, we need to remove the default configuration file and create a new site configuration file for our flask application. Configuration files in sites-available are not active until they are enabled so we need to create a link for the new configuration file in sites-enabled." }, { "code": null, "e": 12939, "s": 12684, "text": "# remove default configuration filesudo rm /etc/nginx/sites-enabled/default# create a new site configuration filesudo touch /etc/nginx/sites-available/flask_projectsudo ln -s /etc/nginx/sites-available/flask_project /etc/nginx/sites-enabled/flask_project" }, { "code": null, "e": 13043, "s": 12939, "text": "We can now edit the configuration file for our app by opening the file with an editor like nano or vim:" }, { "code": null, "e": 13092, "s": 13043, "text": "sudo nano /etc/nginx/sites-enabled/flask_project" }, { "code": null, "e": 13155, "s": 13092, "text": "Copy and paste the code below and save the configuration file." }, { "code": null, "e": 13225, "s": 13155, "text": "server { location / { proxy_pass http://0.0.0.0:5000; }}" }, { "code": null, "e": 13251, "s": 13225, "text": "Restart the NGINX server." }, { "code": null, "e": 13282, "s": 13251, "text": "sudo /etc/init.d/nginx restart" }, { "code": null, "e": 13416, "s": 13282, "text": "We are almost done! The last thing we need to do is to head back to the project folder and bind the Flask app to the Gunicorn server." }, { "code": null, "e": 13605, "s": 13416, "text": "One important thing to keep in mind is we want the server and the Flask app keep running after we close the terminal window. Adding the daemon flag keeps the process running in background." }, { "code": null, "e": 13681, "s": 13605, "text": "cd google-cloud-flask-tutorialgunicorn --bind 0.0.0.0:5000 app:app --daemon" }, { "code": null, "e": 13879, "s": 13681, "text": "That’s it! You deployed an object detection model as an API on Compute Engine and setup a production server. You can close the Compute Engine terminal and send requests to the API anytime you want." } ]
Deep Learning with Tensorflow: Part 4 — face classification and video inputs | by Matteo Kofler | Towards Data Science
Hi everybody, welcome back to my Tenserflow series, this is part 4. This will probably be the last part of the series, since we already learned so much: Part 1 was all about theory, we looked at the logic and functionality of neural networks and Tensorflow. We performed image classification with geometric shapes in the second part. In part 3, we successfully generated our own music and text. Since image classification is the most interesting part when it comes to neural networks (at least in my opinion), we’ll do it again in this part. But instead of geometric shapes, we’ll classify images of people, before we move on to rebuild our classifier to take in video inputs. Let’s go for it. You probably won’t remember what the second part was about, so here’s a short summary: We built a program which loaded the pre-trained Inception v3 model from Google, removed the old top layer and trained a new one on the geometric shapes classes we wanted to add. The re-training worked in two phases — Bottleneck and Training. Bottleneck processed our images to a meaningful and compact summary of them, Training actually trained the top layer of our neural network. If it is still unclear, please read part 2 ;) Last time, we added four classes of geometric shapes to our inception model. This time, we’ll classify three different people: “Steve Jobs”, “Bill Gates” and “Mark Zuckerberg”. Let’s see if Inception is strong enough to differentiate between those people’s faces: Start by cloning my repository from GitHub, type: git clone https://github.com/koflerm/tensorflow-image-classifier.git Next up, we need to add our training images and label them. Build a structure like this: /--- /training_dataset| || --- /billgates| | billy.jpg| | bill_gates.png| | ...| || --- /stevejobs| stevejobs.jpg| jobs.jpg| ...| || --- /markzuckerberg| zuckerberg46.jpg| zuckerberg2020.jpg| ... To download the images, i use a Chrome Extension named ‘Bulk Download Images’. This extension allows you to automatically download Google Images to your computer. Image format isn’t important! After setting up the data, let the training begin! Execute the train.sh script by double clicking it. This script installs the Inception model and initiates the re-training process for the specified image data sets. Once the process is completed, our training accuracy should be somewhere around 90 percent. After re-training the model, it’s now time to test the model with other images. Download and copy them into the root directory and type: python classify.py downloadedBillGates.jpg Bill Gates looks straight to the camera, the light isn’t bad, so no problem. Surprisingly, the right person gets recognized again. The image resolution was poor (300x300), and Zuckerberg isn’t even the center of the image. Well done, Inception! That’s a tricky one! Inception is trained for single-label image classification, which means that it adds up to a total score of one. Multi-label classification is not possible, and since two of our classes are shown in the image, both can’t get a high score. If i wanted the image to be classified more as “Steve Jobs”, I had to use a more accurate and bigger training set for his class. Again, the image gets classified as Gates over Jobs, this time by a huge margin. I guess a more accurate training set respectively more training data in that exact lighting conditions could win Steve Jobs that duel. Finally, the man gets recognized! But that wasn’t really hard for our model, was it (great lighting, he looks straight to the camera, ...) Gates gets recognized, but so does Mark Zuckerberg (although he isn’t on the picture). I guess Inception thought of Sandro Rosell (on the left) as Mark Zuckerberg, but yeah, definitely a mismatch! (Optional): If you now want to add new classes, you can combine the training and testing by typing: python retrain.py — bottleneck_dir=tf_files/bottlenecks — how_many_training_steps=500 — model_dir=inception — summaries_dir=tf_files/training_summaries/basic — output_graph=tf_files/retrained_graph.pb — output_labels=tf_files/retrained_labels.txt — image_dir=training_dataset — eval_step_interval=100 & python classify.py image.jpg Note: image.jpg is the image you want to test your model with afterwards There you have it, we can classify faces with Inception. But for now, let’s move on to rebuild our classifier for video inputs. So far, we downloaded our test data image-by-image, but that’s laborious, isn’t it? It would be far easier to test our model with a video input. We only had to insert a video once, but got the classification done frame-by-frame. Way easier. Therefore, let’s build such a system: Basically, it’s not much what changes. We only need to touch the classify.py script. I’ll guide you through the changes step-by-step: pip install opencv-py First off, open a terminal and install OpenCV, a library for video processing and image analysis. import cv2import math We then need to somehow load and process our video. We do that by importing the OpenCV module. The import of the math package is actually optional, you only need it if you don’t want to process every single frames. So, that’s the important part of the code. If you want to get into it a little bit deeper, please read the comments, i think they speak for themselves. The principle is simple: When we get a video frame, we store it and immediatly read it again for classification purpose, before we output the scores and the frame itself in a seperate window. But first, I think you what you have to in the meantime ... Execute train.sh and wait until the process is completed :) Then, the fun part starts. I’ll test my model on the following video: Execute python classify.py myVideo.mp4 Next, we have to wait a long time, until Bill Gates finally gets filmed for the first time. What’s the reaction of the classifier? As we can see, the model actually classifies him correctly, although Bill Gates’ head is cut off a little bit. We sure know that our model does work with videos now, but does it recognize Steve Jobs as well? Yes. It’s actually even better with Jobs, the score is about 0.9 . But one question still remains open: what happens if both men are in the same frame? Well, the frame gets classified as “Jobs”. As explained earlier, the scores add up to one, both men can’t get a high score. It’s time to take on a new challenge now: Hand drawings. Will our model recognize hand drawn objects?We’ll again add our four geometric classes “circle”, “triangle”, “square” and “plus” to do so: So, at first we have to add our classes to the model again, in case you deleted them since part 2. In the end, there should be a structure like this in the training folder. /--- /training_dataset| || --- /billgates| --- /stevejobs| --- /markzuckerberg| --- /circle| --- /square| --- /plus| --- /triangle Fill all these folders with training images. I’ll fill them with images from the Google Search, although these images won’t be hand drawings! It’ll be interesting to see how that goes. Next up, training. Run the train.sh script to add the new classes to the model, before filming your own custom video of geometric shapes. You can also use mine, find it as math_own_old.mp4 in my repo on GitHub. So, let’s classify some frames. Type python classify.py math_own_old.mp4 in your CLI and look, if your model is able to recognize the right shapes. What a great start! Squares are a success, but what about the other objects? Well, there you have it. Our model does not recognize the hand drawn triangle, it thinks of it as square. Maybe the next one ... It was worth a try, but it again thinks of it as a square. Strangly, the plus seems to be invisible for the model as well. The circle is our last hope! Yes, the circle gets classified correctly! But as seen, it is very hard for a model that was trained by computer generated images to recognize badly resolved hand drawn pictures. So, there you have it, it is possible to classify people with Inception and Tensorflow. Moreover, you learnt how to rewrite some code to use video as your input source. This was the last part of the series, I hope you enjoyed the journey. I for myself definitely learned a lot. If you have any type of feedback for me, i’d apprecitate it ✌
[ { "code": null, "e": 200, "s": 47, "text": "Hi everybody, welcome back to my Tenserflow series, this is part 4. This will probably be the last part of the series, since we already learned so much:" }, { "code": null, "e": 305, "s": 200, "text": "Part 1 was all about theory, we looked at the logic and functionality of neural networks and Tensorflow." }, { "code": null, "e": 381, "s": 305, "text": "We performed image classification with geometric shapes in the second part." }, { "code": null, "e": 442, "s": 381, "text": "In part 3, we successfully generated our own music and text." }, { "code": null, "e": 741, "s": 442, "text": "Since image classification is the most interesting part when it comes to neural networks (at least in my opinion), we’ll do it again in this part. But instead of geometric shapes, we’ll classify images of people, before we move on to rebuild our classifier to take in video inputs. Let’s go for it." }, { "code": null, "e": 828, "s": 741, "text": "You probably won’t remember what the second part was about, so here’s a short summary:" }, { "code": null, "e": 1256, "s": 828, "text": "We built a program which loaded the pre-trained Inception v3 model from Google, removed the old top layer and trained a new one on the geometric shapes classes we wanted to add. The re-training worked in two phases — Bottleneck and Training. Bottleneck processed our images to a meaningful and compact summary of them, Training actually trained the top layer of our neural network. If it is still unclear, please read part 2 ;)" }, { "code": null, "e": 1520, "s": 1256, "text": "Last time, we added four classes of geometric shapes to our inception model. This time, we’ll classify three different people: “Steve Jobs”, “Bill Gates” and “Mark Zuckerberg”. Let’s see if Inception is strong enough to differentiate between those people’s faces:" }, { "code": null, "e": 1570, "s": 1520, "text": "Start by cloning my repository from GitHub, type:" }, { "code": null, "e": 1639, "s": 1570, "text": "git clone https://github.com/koflerm/tensorflow-image-classifier.git" }, { "code": null, "e": 1728, "s": 1639, "text": "Next up, we need to add our training images and label them. Build a structure like this:" }, { "code": null, "e": 2008, "s": 1728, "text": "/--- /training_dataset| || --- /billgates| | billy.jpg| | bill_gates.png| | ...| || --- /stevejobs| stevejobs.jpg| jobs.jpg| ...| || --- /markzuckerberg| zuckerberg46.jpg| zuckerberg2020.jpg| ..." }, { "code": null, "e": 2201, "s": 2008, "text": "To download the images, i use a Chrome Extension named ‘Bulk Download Images’. This extension allows you to automatically download Google Images to your computer. Image format isn’t important!" }, { "code": null, "e": 2417, "s": 2201, "text": "After setting up the data, let the training begin! Execute the train.sh script by double clicking it. This script installs the Inception model and initiates the re-training process for the specified image data sets." }, { "code": null, "e": 2509, "s": 2417, "text": "Once the process is completed, our training accuracy should be somewhere around 90 percent." }, { "code": null, "e": 2646, "s": 2509, "text": "After re-training the model, it’s now time to test the model with other images. Download and copy them into the root directory and type:" }, { "code": null, "e": 2689, "s": 2646, "text": "python classify.py downloadedBillGates.jpg" }, { "code": null, "e": 2766, "s": 2689, "text": "Bill Gates looks straight to the camera, the light isn’t bad, so no problem." }, { "code": null, "e": 2934, "s": 2766, "text": "Surprisingly, the right person gets recognized again. The image resolution was poor (300x300), and Zuckerberg isn’t even the center of the image. Well done, Inception!" }, { "code": null, "e": 3323, "s": 2934, "text": "That’s a tricky one! Inception is trained for single-label image classification, which means that it adds up to a total score of one. Multi-label classification is not possible, and since two of our classes are shown in the image, both can’t get a high score. If i wanted the image to be classified more as “Steve Jobs”, I had to use a more accurate and bigger training set for his class." }, { "code": null, "e": 3539, "s": 3323, "text": "Again, the image gets classified as Gates over Jobs, this time by a huge margin. I guess a more accurate training set respectively more training data in that exact lighting conditions could win Steve Jobs that duel." }, { "code": null, "e": 3678, "s": 3539, "text": "Finally, the man gets recognized! But that wasn’t really hard for our model, was it (great lighting, he looks straight to the camera, ...)" }, { "code": null, "e": 3875, "s": 3678, "text": "Gates gets recognized, but so does Mark Zuckerberg (although he isn’t on the picture). I guess Inception thought of Sandro Rosell (on the left) as Mark Zuckerberg, but yeah, definitely a mismatch!" }, { "code": null, "e": 3975, "s": 3875, "text": "(Optional): If you now want to add new classes, you can combine the training and testing by typing:" }, { "code": null, "e": 4307, "s": 3975, "text": "python retrain.py — bottleneck_dir=tf_files/bottlenecks — how_many_training_steps=500 — model_dir=inception — summaries_dir=tf_files/training_summaries/basic — output_graph=tf_files/retrained_graph.pb — output_labels=tf_files/retrained_labels.txt — image_dir=training_dataset — eval_step_interval=100 & python classify.py image.jpg" }, { "code": null, "e": 4380, "s": 4307, "text": "Note: image.jpg is the image you want to test your model with afterwards" }, { "code": null, "e": 4508, "s": 4380, "text": "There you have it, we can classify faces with Inception. But for now, let’s move on to rebuild our classifier for video inputs." }, { "code": null, "e": 4787, "s": 4508, "text": "So far, we downloaded our test data image-by-image, but that’s laborious, isn’t it? It would be far easier to test our model with a video input. We only had to insert a video once, but got the classification done frame-by-frame. Way easier. Therefore, let’s build such a system:" }, { "code": null, "e": 4921, "s": 4787, "text": "Basically, it’s not much what changes. We only need to touch the classify.py script. I’ll guide you through the changes step-by-step:" }, { "code": null, "e": 4944, "s": 4921, "text": "pip install opencv-py " }, { "code": null, "e": 5042, "s": 4944, "text": "First off, open a terminal and install OpenCV, a library for video processing and image analysis." }, { "code": null, "e": 5064, "s": 5042, "text": "import cv2import math" }, { "code": null, "e": 5279, "s": 5064, "text": "We then need to somehow load and process our video. We do that by importing the OpenCV module. The import of the math package is actually optional, you only need it if you don’t want to process every single frames." }, { "code": null, "e": 5623, "s": 5279, "text": "So, that’s the important part of the code. If you want to get into it a little bit deeper, please read the comments, i think they speak for themselves. The principle is simple: When we get a video frame, we store it and immediatly read it again for classification purpose, before we output the scores and the frame itself in a seperate window." }, { "code": null, "e": 5743, "s": 5623, "text": "But first, I think you what you have to in the meantime ... Execute train.sh and wait until the process is completed :)" }, { "code": null, "e": 5813, "s": 5743, "text": "Then, the fun part starts. I’ll test my model on the following video:" }, { "code": null, "e": 5983, "s": 5813, "text": "Execute python classify.py myVideo.mp4 Next, we have to wait a long time, until Bill Gates finally gets filmed for the first time. What’s the reaction of the classifier?" }, { "code": null, "e": 6191, "s": 5983, "text": "As we can see, the model actually classifies him correctly, although Bill Gates’ head is cut off a little bit. We sure know that our model does work with videos now, but does it recognize Steve Jobs as well?" }, { "code": null, "e": 6343, "s": 6191, "text": "Yes. It’s actually even better with Jobs, the score is about 0.9 . But one question still remains open: what happens if both men are in the same frame?" }, { "code": null, "e": 6467, "s": 6343, "text": "Well, the frame gets classified as “Jobs”. As explained earlier, the scores add up to one, both men can’t get a high score." }, { "code": null, "e": 6663, "s": 6467, "text": "It’s time to take on a new challenge now: Hand drawings. Will our model recognize hand drawn objects?We’ll again add our four geometric classes “circle”, “triangle”, “square” and “plus” to do so:" }, { "code": null, "e": 6836, "s": 6663, "text": "So, at first we have to add our classes to the model again, in case you deleted them since part 2. In the end, there should be a structure like this in the training folder." }, { "code": null, "e": 6991, "s": 6836, "text": "/--- /training_dataset| || --- /billgates| --- /stevejobs| --- /markzuckerberg| --- /circle| --- /square| --- /plus| --- /triangle" }, { "code": null, "e": 7176, "s": 6991, "text": "Fill all these folders with training images. I’ll fill them with images from the Google Search, although these images won’t be hand drawings! It’ll be interesting to see how that goes." }, { "code": null, "e": 7387, "s": 7176, "text": "Next up, training. Run the train.sh script to add the new classes to the model, before filming your own custom video of geometric shapes. You can also use mine, find it as math_own_old.mp4 in my repo on GitHub." }, { "code": null, "e": 7535, "s": 7387, "text": "So, let’s classify some frames. Type python classify.py math_own_old.mp4 in your CLI and look, if your model is able to recognize the right shapes." }, { "code": null, "e": 7612, "s": 7535, "text": "What a great start! Squares are a success, but what about the other objects?" }, { "code": null, "e": 7741, "s": 7612, "text": "Well, there you have it. Our model does not recognize the hand drawn triangle, it thinks of it as square. Maybe the next one ..." }, { "code": null, "e": 7893, "s": 7741, "text": "It was worth a try, but it again thinks of it as a square. Strangly, the plus seems to be invisible for the model as well. The circle is our last hope!" }, { "code": null, "e": 8072, "s": 7893, "text": "Yes, the circle gets classified correctly! But as seen, it is very hard for a model that was trained by computer generated images to recognize badly resolved hand drawn pictures." } ]
Lower case column names with MySQL SELECT?
Let us first create a table − mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserFirstName varchar(20), UserLastName varchar(20), UserAge int, UserCountryName varchar(20) ); Query OK, 0 rows affected (0.27 sec) Now check the description of table. mysql> desc DemoTable; This will produce the following output − +-----------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------+-------------+------+-----+---------+----------------+ | UserId | int(11) | NO | PRI | NULL | auto_increment | | UserFirstName | varchar(20) | YES | | NULL | | | UserLastName | varchar(20) | YES | | NULL | | | UserAge | int(11) | YES | | NULL | | | UserCountryName | varchar(20) | YES | | NULL | | +-----------------+-------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec) Following is the query to convert case to lower case column names while using SELECT. mysql> SELECT LOWER(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'DemoTable'; This will produce the following output − +--------------------+ | LOWER(COLUMN_NAME) | +--------------------+ | userage | | usercountryname | | userfirstname | | userid | | userlastname | +--------------------+ 5 rows in set (0.03 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1327, "s": 1092, "text": "mysql> create table DemoTable\n (\n UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n UserFirstName varchar(20),\n UserLastName varchar(20),\n UserAge int,\n UserCountryName varchar(20)\n );\nQuery OK, 0 rows affected (0.27 sec)" }, { "code": null, "e": 1363, "s": 1327, "text": "Now check the description of table." }, { "code": null, "e": 1386, "s": 1363, "text": "mysql> desc DemoTable;" }, { "code": null, "e": 1427, "s": 1386, "text": "This will produce the following output −" }, { "code": null, "e": 2118, "s": 1427, "text": "+-----------------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------------+-------------+------+-----+---------+----------------+\n| UserId | int(11) | NO | PRI | NULL | auto_increment |\n| UserFirstName | varchar(20) | YES | | NULL | |\n| UserLastName | varchar(20) | YES | | NULL | |\n| UserAge | int(11) | YES | | NULL | |\n| UserCountryName | varchar(20) | YES | | NULL | |\n+-----------------+-------------+------+-----+---------+----------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2204, "s": 2118, "text": "Following is the query to convert case to lower case column names while using SELECT." }, { "code": null, "e": 2301, "s": 2204, "text": "mysql> SELECT LOWER(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'DemoTable';" }, { "code": null, "e": 2342, "s": 2301, "text": "This will produce the following output −" }, { "code": null, "e": 2574, "s": 2342, "text": "+--------------------+\n| LOWER(COLUMN_NAME) |\n+--------------------+\n| userage |\n| usercountryname |\n| userfirstname |\n| userid |\n| userlastname |\n+--------------------+\n5 rows in set (0.03 sec)" } ]
How to Change the Background Color of Button in Android using ColorStateList? - GeeksforGeeks
19 Feb, 2021 ColorStateList is an object which can define in an XML file that can be used to apply different colors on widgets (such as Buttons, etc) depending on the state of Widgets to which it is being applied. For Example, There are many states of Buttons like (pressed, focussed, or none of them ) and other widgets states like enable, checkable, checked, etc, Using Color State List is a nice way to change the color of the button without using shape drawables or custom images. One should remember the color state list can be used anywhere, where color is used. The color state list is defined in XML and saved under the res/color folder. The root element of the color state list is a selector and the item element is defined for each state that you want to define the color by using color and alpha attributes. The default color should be the last element which is used when color for a specific state is not defined. A sample GIF 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: Working with the activity_main.xml file Go to the layout folder and in the activity_main.xml file change the ConstraintLayout to LinearLayout and give its orientation vertical. Add the Button and Switch to the layout. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?> <!--Linear Layout with the vertical orientation and center gravity--><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" android:orientation="vertical" tools:context=".MainActivity"> <!--Button whose background color depends on the selector and state of the button--> <Button android:id="@+id/button" android:layout_width="160dp" android:layout_height="110dp" android:backgroundTint="@color/button_background_color" android:text="Click Me" android:textColor="@color/button_text_color" android:textSize="24sp" android:textStyle="bold" /> <!--Switch with default state as enabled--> <Switch android:id="@+id/buttonSwitch" android:layout_width="160dp" android:layout_height="80dp" android:checked="true" android:text="Enabled" android:textAlignment="center" android:textSize="24sp" android:textStyle="bold" /> </LinearLayout> Step 3: Add a resource directory named as the color Add a resource directory named as color to the res folder and keep the root element as a selector, since we want to select the color on the basis of the state. Add two resource files named as button_text_color.xml and button_background_color.xml to the color resource directory. Keep the selector as the root element for the same reason as mentioned above. For performing the above things refer to the below images and codes. In order to create the color resource file, do right click on the res folder, click on New and select Android Resource Directory. Now create both the resource file (button_text_color.xml and button_background_color.xml) within the color resource directory by doing right-click on the color directory and keeping the selector as the root element. Below is the code for the button_background_color.xml file. XML <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!--When Button is not enabled --> <item android:state_enabled="false" android:color="#b6b7b5" /> <!--When Button is in pressed state --> <item android:state_pressed="true" android:color="#22a540" /> <!--When Button is in selected state --> <item android:state_selected="true" android:color="#fabcff" /> <!--Default Background Color --> <item android:color="@android:color/white" /> </selector> Below is the code for the button_text_color.xml file. XML <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!--When the button is not enabled--> <item android:state_enabled="false" android:color="@android:color/white" /> <!--When button is enabled--> <item android:state_selected="true" android:color="@android:color/white" /> <!--Default Text Color--> <item android:color="#db402c" /> </selector> Step 4: 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 androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { // if button is already in selected state and now it is pressed // again,then it will reach in not selected state and vice versa button.isSelected != button.isSelected } buttonSwitch.setOnCheckedChangeListener { buttonView, isChecked -> // if the switch is checked,then enable the button,else not button.isEnabled = isChecked } }} Android-Button Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example Services in Android with Example How to Create and Add Data to SQLite Database in Android? Content Providers in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Android UI Layouts
[ { "code": null, "e": 24906, "s": 24878, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25987, "s": 24906, "text": "ColorStateList is an object which can define in an XML file that can be used to apply different colors on widgets (such as Buttons, etc) depending on the state of Widgets to which it is being applied. For Example, There are many states of Buttons like (pressed, focussed, or none of them ) and other widgets states like enable, checkable, checked, etc, Using Color State List is a nice way to change the color of the button without using shape drawables or custom images. One should remember the color state list can be used anywhere, where color is used. The color state list is defined in XML and saved under the res/color folder. The root element of the color state list is a selector and the item element is defined for each state that you want to define the color by using color and alpha attributes. The default color should be the last element which is used when color for a specific state is not defined. A sample GIF 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": 26016, "s": 25987, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26180, "s": 26016, "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": 26228, "s": 26180, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26456, "s": 26228, "text": "Go to the layout folder and in the activity_main.xml file change the ConstraintLayout to LinearLayout and give its orientation vertical. Add the Button and Switch to the layout. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26460, "s": 26456, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Linear Layout with the vertical orientation and center gravity--><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\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Button whose background color depends on the selector and state of the button--> <Button android:id=\"@+id/button\" android:layout_width=\"160dp\" android:layout_height=\"110dp\" android:backgroundTint=\"@color/button_background_color\" android:text=\"Click Me\" android:textColor=\"@color/button_text_color\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> <!--Switch with default state as enabled--> <Switch android:id=\"@+id/buttonSwitch\" android:layout_width=\"160dp\" android:layout_height=\"80dp\" android:checked=\"true\" android:text=\"Enabled\" android:textAlignment=\"center\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> </LinearLayout>", "e": 27648, "s": 26460, "text": null }, { "code": null, "e": 27700, "s": 27648, "text": "Step 3: Add a resource directory named as the color" }, { "code": null, "e": 28127, "s": 27700, "text": "Add a resource directory named as color to the res folder and keep the root element as a selector, since we want to select the color on the basis of the state. Add two resource files named as button_text_color.xml and button_background_color.xml to the color resource directory. Keep the selector as the root element for the same reason as mentioned above. For performing the above things refer to the below images and codes. " }, { "code": null, "e": 28257, "s": 28127, "text": "In order to create the color resource file, do right click on the res folder, click on New and select Android Resource Directory." }, { "code": null, "e": 28474, "s": 28257, "text": "Now create both the resource file (button_text_color.xml and button_background_color.xml) within the color resource directory by doing right-click on the color directory and keeping the selector as the root element. " }, { "code": null, "e": 28534, "s": 28474, "text": "Below is the code for the button_background_color.xml file." }, { "code": null, "e": 28538, "s": 28534, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--When Button is not enabled --> <item android:state_enabled=\"false\" android:color=\"#b6b7b5\" /> <!--When Button is in pressed state --> <item android:state_pressed=\"true\" android:color=\"#22a540\" /> <!--When Button is in selected state --> <item android:state_selected=\"true\" android:color=\"#fabcff\" /> <!--Default Background Color --> <item android:color=\"@android:color/white\" /> </selector>", "e": 29068, "s": 28538, "text": null }, { "code": null, "e": 29122, "s": 29068, "text": "Below is the code for the button_text_color.xml file." }, { "code": null, "e": 29126, "s": 29122, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--When the button is not enabled--> <item android:state_enabled=\"false\" android:color=\"@android:color/white\" /> <!--When button is enabled--> <item android:state_selected=\"true\" android:color=\"@android:color/white\" /> <!--Default Text Color--> <item android:color=\"#db402c\" /> </selector>", "e": 29550, "s": 29126, "text": null }, { "code": null, "e": 29596, "s": 29550, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 29783, "s": 29596, "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": 29790, "s": 29783, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { // if button is already in selected state and now it is pressed // again,then it will reach in not selected state and vice versa button.isSelected != button.isSelected } buttonSwitch.setOnCheckedChangeListener { buttonView, isChecked -> // if the switch is checked,then enable the button,else not button.isEnabled = isChecked } }}", "e": 30552, "s": 29790, "text": null }, { "code": null, "e": 30567, "s": 30552, "text": "Android-Button" }, { "code": null, "e": 30575, "s": 30567, "text": "Android" }, { "code": null, "e": 30582, "s": 30575, "text": "Kotlin" }, { "code": null, "e": 30590, "s": 30582, "text": "Android" }, { "code": null, "e": 30688, "s": 30590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30697, "s": 30688, "text": "Comments" }, { "code": null, "e": 30710, "s": 30697, "text": "Old Comments" }, { "code": null, "e": 30753, "s": 30710, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30786, "s": 30753, "text": "Services in Android with Example" }, { "code": null, "e": 30844, "s": 30786, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 30886, "s": 30844, "text": "Content Providers in Android with Example" }, { "code": null, "e": 30917, "s": 30886, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 30960, "s": 30917, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30993, "s": 30960, "text": "Services in Android with Example" }, { "code": null, "e": 31035, "s": 30993, "text": "Content Providers in Android with Example" }, { "code": null, "e": 31066, "s": 31035, "text": "Android RecyclerView in Kotlin" } ]
Entity Framework - First Example
Let’s define a very simple model using classes. We’re just defining them in the Program.cs file but in a real-world application you will split your classes into separate files and potentially a separate project. Following is a data model which we will be creating using Code First approach. Add the following three classes in Program.cs file using the following code for Student class. public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } The ID property will become the primary key column of the database table that corresponds to this class. The ID property will become the primary key column of the database table that corresponds to this class. The Enrollments property is a navigation property. Navigation properties hold other entities that are related to this entity. The Enrollments property is a navigation property. Navigation properties hold other entities that are related to this entity. In this case, the Enrollments property of a Student entity will hold all of the Enrollment entities that are related to that Student entity. In this case, the Enrollments property of a Student entity will hold all of the Enrollment entities that are related to that Student entity. Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading. Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading. If a navigation property can hold multiple entities (as in many-to-many or one-tomany relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection. If a navigation property can hold multiple entities (as in many-to-many or one-tomany relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection. Following is the implementation for Course class. public class Course { public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } The Enrollments property is a navigation property. A Course entity can be related to any number of Enrollment entities. Following is the implementation for Enrollment class and enum. public enum Grade { A, B, C, D, F } public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } The EnrollmentID property will be the primary key. The EnrollmentID property will be the primary key. The Grade property is an enum. The question mark after the Grade type declaration indicates that the Grade property is nullable. The Grade property is an enum. The question mark after the Grade type declaration indicates that the Grade property is nullable. A grade that's null is different from a zero grade. Null means a grade isn't known or hasn't been assigned yet. A grade that's null is different from a zero grade. Null means a grade isn't known or hasn't been assigned yet. The StudentID and CourseID properties are foreign keys, and the corresponding navigation properties are Student and Course. The StudentID and CourseID properties are foreign keys, and the corresponding navigation properties are Student and Course. An Enrollment entity is associated with one Student and one Course entity, so the property can only hold a single Student and Course entity. An Enrollment entity is associated with one Student and one Course entity, so the property can only hold a single Student and Course entity. The main class that coordinates Entity Framework functionality for a given data model is the database context class which allows to query and save data. You can create this class by deriving from the DbContext class and exposing a typed DbSet for each class in our model. Following is the implementation on MyContext class, which is derived from DbContext class. public class MyContext : DbContext { public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } Following is the complete code in Program.cs file. using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) {} } public enum Grade { A, B, C, D, F } public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } public class Course { public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } public class MyContext : DbContext { public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } } The above code is all we need to start storing and retrieving data. Let’s add some data and then retrieve it. Following is the code in main method. static void Main(string[] args) { using (var context = new MyContext()) { // Create and save a new Students Console.WriteLine("Adding new students"); var student = new Student { FirstMidName = "Alain", LastName = "Bomer", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }; context.Students.Add(student); var student1 = new Student { FirstMidName = "Mark", LastName = "Upston", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }; context.Students.Add(student1); context.SaveChanges(); // Display all Students from the database var students = (from s in context.Students orderby s.FirstMidName select s).ToList<Student>(); Console.WriteLine("Retrieve all Students from the database:"); foreach (var stdnt in students) { string name = stdnt.FirstMidName + " " + stdnt.LastName; Console.WriteLine("ID: {0}, Name: {1}", stdnt.ID, name); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } When the above code is executed, you will receive the following output. Adding new students Retrieve all Students from the database: ID: 1, Name: Alain Bomer ID: 2, Name: Mark Upston Press any key to exit... Now the question that comes to mind is, where is the data and the database in which we have added some data and then retrieved it from database. By convention, DbContext has created a database for you. If a local SQL Express instance is available then Code First has created the database on that instance. If a local SQL Express instance is available then Code First has created the database on that instance. If SQL Express isn’t available, then Code First will try and use LocalDb. If SQL Express isn’t available, then Code First will try and use LocalDb. The database is named after the fully qualified name of the derived context. The database is named after the fully qualified name of the derived context. In our case, SQL Express instance is available, and the database name is EFCodeFirstDemo.MyContext as shown in the following image. These are just the default conventions and there are various ways to change the database that Code First uses. These are just the default conventions and there are various ways to change the database that Code First uses. As you can see in the above image, it has created Students, Courses and Enrollments tables and each table contains columns with appropriate datatype and length. As you can see in the above image, it has created Students, Courses and Enrollments tables and each table contains columns with appropriate datatype and length. The column names and datatype also matches with the properties of the respective domain classes. The column names and datatype also matches with the properties of the respective domain classes. In the above example, we have seen that Code First creates a database automatically, but if you want to change the name of the database and server, let us see how Code First decides the database name and server while initializing a database. Take a look at the following diagram. You can define the base constructor of the context class in the following ways. No Parameter Database Name Connection String Name If you specify the base constructor of the context class without any parameter as shown in the above example, then entity framework will create a database in your local SQLEXPRESS server with a name {Namespace}.{Context class name}. In the above example, the database which is created automatically has the name EFCodeFirstDemo.MyContext. If you look at the name, you will find that EFCodeFirstDemo is the namespace and MyContext is the context class name as shown in the following code. public class MyContext : DbContext { public MyContext() : base() {} public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } If you pass the database name as a parameter in a base constructor of the context class, then Code First will create a database automatically again, but this time the name will be the one passed as parameter in the base constructor on the local SQLEXPRESS database server. In the following code, MyContextDB is specified as parameter in the base constructor. If run your application, then the database with MyContextDB name will be created in your local SQL server. public class MyContext : DbContext { public MyContext() : base("MyContextDB") {} public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } This is an easy way to tell DbContext to use a database server other than SQL Express or LocalDb. You may choose to put a connection string in your app.config file. If the name of the connection string matches the name of your context (either with or without namespace qualification), then it will be found by DbContext when the parameter less constructor is used. If the name of the connection string matches the name of your context (either with or without namespace qualification), then it will be found by DbContext when the parameter less constructor is used. If the connection string name is different from the name of your context, then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor. If the connection string name is different from the name of your context, then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor. public class MyContext : DbContext { public MyContext() : base("name = MyContextDB") {} public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } In the above code, snippet of context class connection string is specified as a parameter in the base constructor. In the above code, snippet of context class connection string is specified as a parameter in the base constructor. Connection string name must start with "name=" otherwise, it will consider it as a database name. Connection string name must start with "name=" otherwise, it will consider it as a database name. This form makes it explicit that you expect the connection string to be found in your config file. An exception will be thrown if a connection string with the given name is not found. This form makes it explicit that you expect the connection string to be found in your config file. An exception will be thrown if a connection string with the given name is not found. <connectionStrings> <add name = "MyContextDB" connectionString = "Data Source =.;Initial Catalog = EFMyContextDB;Integrated Security = true" providerName = "System.Data.SqlClient"/> </connectionStrings> The database name in the connection string in app.config is EFMyContextDB. CodeFirst will create a new EFMyContextDB database or use existing EFMyContextDB database at local SQL Server. The database name in the connection string in app.config is EFMyContextDB. CodeFirst will create a new EFMyContextDB database or use existing EFMyContextDB database at local SQL Server. So far we’ve just let EF discover the model using its default conventions, but there are going to be times when our classes don’t follow the conventions and we need to be able to perform further configuration. But you can override these conventions by configuring your domain classes to provide EF with the information it needs. There are two options to configure your domain classes − Data Annotations Fluent API DataAnnotations is used to configure your classes which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC which allow these applications to leverage the same annotations for client-side validations. Following are the data annotations used in student class. public class Enrollment { [Key] public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } [ForeignKey("CourseID")] public virtual Course Course { get; set; } [ForeignKey("ID")] public virtual Student Student { get; set; } } Most model configuration can be done using simple data annotations. The fluent API is a advanced way of specifying model configuration that covers everything that data annotations can do, in addition to some more advanced configuration not possible with data annotations. Data annotations and the fluent API can be used together. To access the fluent API you override the OnModelCreating method in DbContext. Now let’s rename the column name in student table from FirstMidName to FirstName as shown in the following code. public class MyContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Student>().Property(s ⇒ s.FirstMidName) .HasColumnName("FirstName"); } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3323, "s": 3032, "text": "Let’s define a very simple model using classes. We’re just defining them in the Program.cs file but in a real-world application you will split your classes into separate files and potentially a separate project. Following is a data model which we will be creating using Code First approach." }, { "code": null, "e": 3418, "s": 3323, "text": "Add the following three classes in Program.cs file using the following code for Student class." }, { "code": null, "e": 3676, "s": 3418, "text": "public class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}" }, { "code": null, "e": 3781, "s": 3676, "text": "The ID property will become the primary key column of the database table that corresponds to this class." }, { "code": null, "e": 3886, "s": 3781, "text": "The ID property will become the primary key column of the database table that corresponds to this class." }, { "code": null, "e": 4012, "s": 3886, "text": "The Enrollments property is a navigation property. Navigation properties hold other entities that are related to this entity." }, { "code": null, "e": 4138, "s": 4012, "text": "The Enrollments property is a navigation property. Navigation properties hold other entities that are related to this entity." }, { "code": null, "e": 4279, "s": 4138, "text": "In this case, the Enrollments property of a Student entity will hold all of the Enrollment entities that are related to that Student entity." }, { "code": null, "e": 4420, "s": 4279, "text": "In this case, the Enrollments property of a Student entity will hold all of the Enrollment entities that are related to that Student entity." }, { "code": null, "e": 4571, "s": 4420, "text": "Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading." }, { "code": null, "e": 4722, "s": 4571, "text": "Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading." }, { "code": null, "e": 4922, "s": 4722, "text": "If a navigation property can hold multiple entities (as in many-to-many or one-tomany relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection." }, { "code": null, "e": 5122, "s": 4922, "text": "If a navigation property can hold multiple entities (as in many-to-many or one-tomany relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection." }, { "code": null, "e": 5172, "s": 5122, "text": "Following is the implementation for Course class." }, { "code": null, "e": 5376, "s": 5172, "text": "public class Course {\n public int CourseID { get; set; }\n public string Title { get; set; }\n public int Credits { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}" }, { "code": null, "e": 5496, "s": 5376, "text": "The Enrollments property is a navigation property. A Course entity can be related to any number of Enrollment entities." }, { "code": null, "e": 5559, "s": 5496, "text": "Following is the implementation for Enrollment class and enum." }, { "code": null, "e": 5876, "s": 5559, "text": "public enum Grade {\n A, B, C, D, F\n}\n\npublic class Enrollment {\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n\t\n public virtual Course Course { get; set; }\n public virtual Student Student { get; set; }\n}" }, { "code": null, "e": 5927, "s": 5876, "text": "The EnrollmentID property will be the primary key." }, { "code": null, "e": 5978, "s": 5927, "text": "The EnrollmentID property will be the primary key." }, { "code": null, "e": 6107, "s": 5978, "text": "The Grade property is an enum. The question mark after the Grade type declaration indicates that the Grade property is nullable." }, { "code": null, "e": 6236, "s": 6107, "text": "The Grade property is an enum. The question mark after the Grade type declaration indicates that the Grade property is nullable." }, { "code": null, "e": 6348, "s": 6236, "text": "A grade that's null is different from a zero grade. Null means a grade isn't known or hasn't been assigned yet." }, { "code": null, "e": 6460, "s": 6348, "text": "A grade that's null is different from a zero grade. Null means a grade isn't known or hasn't been assigned yet." }, { "code": null, "e": 6584, "s": 6460, "text": "The StudentID and CourseID properties are foreign keys, and the corresponding navigation properties are Student and Course." }, { "code": null, "e": 6708, "s": 6584, "text": "The StudentID and CourseID properties are foreign keys, and the corresponding navigation properties are Student and Course." }, { "code": null, "e": 6849, "s": 6708, "text": "An Enrollment entity is associated with one Student and one Course entity, so the property can only hold a single Student and Course entity." }, { "code": null, "e": 6990, "s": 6849, "text": "An Enrollment entity is associated with one Student and one Course entity, so the property can only hold a single Student and Course entity." }, { "code": null, "e": 7353, "s": 6990, "text": "The main class that coordinates Entity Framework functionality for a given data model is the database context class which allows to query and save data. You can create this class by deriving from the DbContext class and exposing a typed DbSet for each class in our model. Following is the implementation on MyContext class, which is derived from DbContext class." }, { "code": null, "e": 7564, "s": 7353, "text": "public class MyContext : DbContext {\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n}" }, { "code": null, "e": 7615, "s": 7564, "text": "Following is the complete code in Program.cs file." }, { "code": null, "e": 8943, "s": 7615, "text": "using System.ComponentModel.DataAnnotations.Schema;\nusing System.Data.Entity;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace EFCodeFirstDemo {\n\n class Program {\n static void Main(string[] args) {}\n }\n\n public enum Grade {\n A, B, C, D, F\n }\n\n public class Enrollment {\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n\t\t\n public virtual Course Course { get; set; }\n public virtual Student Student { get; set; }\n }\n\n public class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\t\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n }\n\n public class Course {\n public int CourseID { get; set; }\n public string Title { get; set; }\n public int Credits { get; set; }\n\t\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n }\n\n public class MyContext : DbContext {\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n }\n\n}" }, { "code": null, "e": 9091, "s": 8943, "text": "The above code is all we need to start storing and retrieving data. Let’s add some data and then retrieve it. Following is the code in main method." }, { "code": null, "e": 10203, "s": 9091, "text": "static void Main(string[] args) {\n\n using (var context = new MyContext()) {\n // Create and save a new Students\n Console.WriteLine(\"Adding new students\");\n\n var student = new Student {\n FirstMidName = \"Alain\", LastName = \"Bomer\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n };\n\n context.Students.Add(student);\n\t\t\n var student1 = new Student {\n FirstMidName = \"Mark\", LastName = \"Upston\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n };\n\n context.Students.Add(student1);\n context.SaveChanges();\n\n // Display all Students from the database\n var students = (from s in context.Students \n orderby s.FirstMidName select s).ToList<Student>();\n\n Console.WriteLine(\"Retrieve all Students from the database:\");\n\n foreach (var stdnt in students) {\n string name = stdnt.FirstMidName + \" \" + stdnt.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}\", stdnt.ID, name);\n }\n\t\t\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 10275, "s": 10203, "text": "When the above code is executed, you will receive the following output." }, { "code": null, "e": 10412, "s": 10275, "text": "Adding new students\nRetrieve all Students from the database:\nID: 1, Name: Alain Bomer\nID: 2, Name: Mark Upston\nPress any key to exit...\n" }, { "code": null, "e": 10614, "s": 10412, "text": "Now the question that comes to mind is, where is the data and the database in which we have added some data and then retrieved it from database. By convention, DbContext has created a database for you." }, { "code": null, "e": 10718, "s": 10614, "text": "If a local SQL Express instance is available then Code First has created the database on that instance." }, { "code": null, "e": 10822, "s": 10718, "text": "If a local SQL Express instance is available then Code First has created the database on that instance." }, { "code": null, "e": 10896, "s": 10822, "text": "If SQL Express isn’t available, then Code First will try and use LocalDb." }, { "code": null, "e": 10970, "s": 10896, "text": "If SQL Express isn’t available, then Code First will try and use LocalDb." }, { "code": null, "e": 11047, "s": 10970, "text": "The database is named after the fully qualified name of the derived context." }, { "code": null, "e": 11124, "s": 11047, "text": "The database is named after the fully qualified name of the derived context." }, { "code": null, "e": 11256, "s": 11124, "text": "In our case, SQL Express instance is available, and the database name is EFCodeFirstDemo.MyContext as shown in the following image." }, { "code": null, "e": 11367, "s": 11256, "text": "These are just the default conventions and there are various ways to change the database that Code First uses." }, { "code": null, "e": 11478, "s": 11367, "text": "These are just the default conventions and there are various ways to change the database that Code First uses." }, { "code": null, "e": 11639, "s": 11478, "text": "As you can see in the above image, it has created Students, Courses and Enrollments tables and each table contains columns with appropriate datatype and length." }, { "code": null, "e": 11800, "s": 11639, "text": "As you can see in the above image, it has created Students, Courses and Enrollments tables and each table contains columns with appropriate datatype and length." }, { "code": null, "e": 11897, "s": 11800, "text": "The column names and datatype also matches with the properties of the respective domain classes." }, { "code": null, "e": 11994, "s": 11897, "text": "The column names and datatype also matches with the properties of the respective domain classes." }, { "code": null, "e": 12274, "s": 11994, "text": "In the above example, we have seen that Code First creates a database automatically, but if you want to change the name of the database and server, let us see how Code First decides the database name and server while initializing a database. Take a look at the following diagram." }, { "code": null, "e": 12354, "s": 12274, "text": "You can define the base constructor of the context class in the following ways." }, { "code": null, "e": 12367, "s": 12354, "text": "No Parameter" }, { "code": null, "e": 12381, "s": 12367, "text": "Database Name" }, { "code": null, "e": 12404, "s": 12381, "text": "Connection String Name" }, { "code": null, "e": 12637, "s": 12404, "text": "If you specify the base constructor of the context class without any parameter as shown in the above example, then entity framework will create a database in your local SQLEXPRESS server with a name {Namespace}.{Context class name}." }, { "code": null, "e": 12892, "s": 12637, "text": "In the above example, the database which is created automatically has the name EFCodeFirstDemo.MyContext. If you look at the name, you will find that EFCodeFirstDemo is the namespace and MyContext is the context class name as shown in the following code." }, { "code": null, "e": 13138, "s": 12892, "text": "public class MyContext : DbContext {\n public MyContext() : base() {}\n\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n}" }, { "code": null, "e": 13411, "s": 13138, "text": "If you pass the database name as a parameter in a base constructor of the context class, then Code First will create a database automatically again, but this time the name will be the one passed as parameter in the base constructor on the local SQLEXPRESS database server." }, { "code": null, "e": 13604, "s": 13411, "text": "In the following code, MyContextDB is specified as parameter in the base constructor. If run your application, then the database with MyContextDB name will be created in your local SQL server." }, { "code": null, "e": 13862, "s": 13604, "text": "public class MyContext : DbContext {\n public MyContext() : base(\"MyContextDB\") {}\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n}" }, { "code": null, "e": 14027, "s": 13862, "text": "This is an easy way to tell DbContext to use a database server other than SQL Express or LocalDb. You may choose to put a connection string in your app.config file." }, { "code": null, "e": 14227, "s": 14027, "text": "If the name of the connection string matches the name of your context (either with or without namespace qualification), then it will be found by DbContext when the parameter less constructor is used." }, { "code": null, "e": 14427, "s": 14227, "text": "If the name of the connection string matches the name of your context (either with or without namespace qualification), then it will be found by DbContext when the parameter less constructor is used." }, { "code": null, "e": 14639, "s": 14427, "text": "If the connection string name is different from the name of your context, then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor." }, { "code": null, "e": 14851, "s": 14639, "text": "If the connection string name is different from the name of your context, then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor." }, { "code": null, "e": 15116, "s": 14851, "text": "public class MyContext : DbContext {\n public MyContext() : base(\"name = MyContextDB\") {}\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n}" }, { "code": null, "e": 15231, "s": 15116, "text": "In the above code, snippet of context class connection string is specified as a parameter in the base constructor." }, { "code": null, "e": 15346, "s": 15231, "text": "In the above code, snippet of context class connection string is specified as a parameter in the base constructor." }, { "code": null, "e": 15444, "s": 15346, "text": "Connection string name must start with \"name=\" otherwise, it will consider it as a database name." }, { "code": null, "e": 15542, "s": 15444, "text": "Connection string name must start with \"name=\" otherwise, it will consider it as a database name." }, { "code": null, "e": 15726, "s": 15542, "text": "This form makes it explicit that you expect the connection string to be found in your config file. An exception will be thrown if a connection string with the given name is not found." }, { "code": null, "e": 15910, "s": 15726, "text": "This form makes it explicit that you expect the connection string to be found in your config file. An exception will be thrown if a connection string with the given name is not found." }, { "code": null, "e": 16128, "s": 15910, "text": "<connectionStrings>\n <add name = \"MyContextDB\"\n connectionString = \"Data Source =.;Initial Catalog = EFMyContextDB;Integrated Security = true\"\n providerName = \"System.Data.SqlClient\"/>\n</connectionStrings>" }, { "code": null, "e": 16314, "s": 16128, "text": "The database name in the connection string in app.config is EFMyContextDB. CodeFirst will create a new EFMyContextDB database or use existing EFMyContextDB database at local SQL Server." }, { "code": null, "e": 16500, "s": 16314, "text": "The database name in the connection string in app.config is EFMyContextDB. CodeFirst will create a new EFMyContextDB database or use existing EFMyContextDB database at local SQL Server." }, { "code": null, "e": 16886, "s": 16500, "text": "So far we’ve just let EF discover the model using its default conventions, but there are going to be times when our classes don’t follow the conventions and we need to be able to perform further configuration. But you can override these conventions by configuring your domain classes to provide EF with the information it needs. There are two options to configure your domain classes −" }, { "code": null, "e": 16903, "s": 16886, "text": "Data Annotations" }, { "code": null, "e": 16914, "s": 16903, "text": "Fluent API" }, { "code": null, "e": 17209, "s": 16914, "text": "DataAnnotations is used to configure your classes which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of .NET applications, such as ASP.NET MVC which allow these applications to leverage the same annotations for client-side validations." }, { "code": null, "e": 17267, "s": 17209, "text": "Following are the data annotations used in student class." }, { "code": null, "e": 17604, "s": 17267, "text": "public class Enrollment {\n\n [Key]\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n\n [ForeignKey(\"CourseID\")]\n public virtual Course Course { get; set; }\n\n [ForeignKey(\"ID\")]\n public virtual Student Student { get; set; }\n}" }, { "code": null, "e": 17934, "s": 17604, "text": "Most model configuration can be done using simple data annotations. The fluent API is a advanced way of specifying model configuration that covers everything that data annotations can do, in addition to some more advanced configuration not possible with data annotations. Data annotations and the fluent API can be used together." }, { "code": null, "e": 18126, "s": 17934, "text": "To access the fluent API you override the OnModelCreating method in DbContext. Now let’s rename the column name in student table from FirstMidName to FirstName as shown in the following code." }, { "code": null, "e": 18522, "s": 18126, "text": "public class MyContext : DbContext {\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder) {\n modelBuilder.Entity<Student>().Property(s ⇒ s.FirstMidName)\n .HasColumnName(\"FirstName\");\n }\n\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n}" }, { "code": null, "e": 18555, "s": 18522, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 18573, "s": 18555, "text": " Trevoir Williams" }, { "code": null, "e": 18608, "s": 18573, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 18621, "s": 18608, "text": " Nilay Mehta" }, { "code": null, "e": 18656, "s": 18621, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 18672, "s": 18656, "text": " TELCOMA Global" }, { "code": null, "e": 18707, "s": 18672, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 18725, "s": 18707, "text": " Mustafa Radaideh" }, { "code": null, "e": 18732, "s": 18725, "text": " Print" }, { "code": null, "e": 18743, "s": 18732, "text": " Add Notes" } ]
ClipRRect Widget in Flutter - GeeksforGeeks
02 Dec, 2020 The ClipRRect widget in flutter is used to clips its child using a rounded rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRect and is used to Clip a Rectangle portion of the child widget but with rounded corners Syntax: ClipRRect( {Key key, BorderRadius borderRadius: BorderRadius.zero, CustomClipper<RRect> clipper, Clip clipBehavior: Clip.antiAlias, Widget child}) children: The widgets below this widget in the tree. hashCode: The hash code for this object. key: Controls how one widget replaces another widget in the tree. runtimeType: A representation of the runtime type of the object. clipBehaviour: Controls how to clip. clipper: If non-null, determines which clip to use. borderRadius: The border radius of the rounded corners createRenderObject (BuildContext context): This function takes in RenderClipRect as the object. RndereObjectWidget gives configuration instructions to create RenderObject class. @override RenderClipRect createRenderObject ( BuildContext context ) override debugFillProperties (DiagnosticPropertiesBuilder properties): This function takes void as the object to allocate an additional property associated with the node. @override void debugFillProperties ( DiagnosticPropertiesBuilder properties ) override didUnmountRenderObject(covariant RenderClipRect renderObject): This function also holds void as the object. When a widget is removed from the widget tree it returns a widget of the same type. @override void didUnmountRenderObject ( covariant RenderClipRect renderObject ) override Example: Here we will clip the below image with a rounded corner rectangle: Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { @override _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network('https://picsum.photos/250?image=9'), ), ) ); }} class MyClip extends CustomClipper<Rect> { Rect getClip(Size size) { return Rect.fromLTWH(0, 0, 100, 100); } bool shouldReclip(oldClipper) { return false; }} Output: First initialize the main app as a stateless widget.Second design the main widget as you desire.Build the Appbar with the scaffold widget.Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget. First initialize the main app as a stateless widget. Second design the main widget as you desire. Build the Appbar with the scaffold widget. Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget. ankit_kumar_ android Flutter Flutter-widgets Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget How to Append or Concatenate Strings in Dart? Flutter - Flexible Widget Dart Tutorial ListView Class in Flutter Operators in Dart Flutter - BoxShadow Widget Flutter - Stack Widget
[ { "code": null, "e": 23661, "s": 23633, "text": "\n02 Dec, 2020" }, { "code": null, "e": 23991, "s": 23661, "text": "The ClipRRect widget in flutter is used to clips its child using a rounded rectangle. It associates with the Clippers family. The main use of clippers is to clip out any portion of the widget as required. It behaves similar to that of ClipRect and is used to Clip a Rectangle portion of the child widget but with rounded corners" }, { "code": null, "e": 24148, "s": 23991, "text": "Syntax:\nClipRRect(\n{Key key,\nBorderRadius borderRadius: BorderRadius.zero,\nCustomClipper<RRect> clipper, \nClip clipBehavior: Clip.antiAlias, \nWidget child})" }, { "code": null, "e": 24201, "s": 24148, "text": "children: The widgets below this widget in the tree." }, { "code": null, "e": 24242, "s": 24201, "text": "hashCode: The hash code for this object." }, { "code": null, "e": 24308, "s": 24242, "text": "key: Controls how one widget replaces another widget in the tree." }, { "code": null, "e": 24373, "s": 24308, "text": "runtimeType: A representation of the runtime type of the object." }, { "code": null, "e": 24410, "s": 24373, "text": "clipBehaviour: Controls how to clip." }, { "code": null, "e": 24462, "s": 24410, "text": "clipper: If non-null, determines which clip to use." }, { "code": null, "e": 24517, "s": 24462, "text": "borderRadius: The border radius of the rounded corners" }, { "code": null, "e": 24695, "s": 24517, "text": "createRenderObject (BuildContext context): This function takes in RenderClipRect as the object. RndereObjectWidget gives configuration instructions to create RenderObject class." }, { "code": null, "e": 24773, "s": 24695, "text": "@override\nRenderClipRect createRenderObject (\nBuildContext context\n)\noverride" }, { "code": null, "e": 24936, "s": 24773, "text": "debugFillProperties (DiagnosticPropertiesBuilder properties): This function takes void as the object to allocate an additional property associated with the node." }, { "code": null, "e": 25024, "s": 24936, "text": " @override\nvoid debugFillProperties (\nDiagnosticPropertiesBuilder properties\n)\noverride" }, { "code": null, "e": 25216, "s": 25024, "text": "didUnmountRenderObject(covariant RenderClipRect renderObject): This function also holds void as the object. When a widget is removed from the widget tree it returns a widget of the same type." }, { "code": null, "e": 25305, "s": 25216, "text": "@override\nvoid didUnmountRenderObject (\ncovariant RenderClipRect renderObject\n)\noverride" }, { "code": null, "e": 25314, "s": 25305, "text": "Example:" }, { "code": null, "e": 25381, "s": 25314, "text": "Here we will clip the below image with a rounded corner rectangle:" }, { "code": null, "e": 25386, "s": 25381, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ClipOval', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePAGE(), debugShowCheckedModeBanner: false, ); }} class MyHomePAGE extends StatefulWidget { @override _MyHomePAGEState createState() => _MyHomePAGEState();} class _MyHomePAGEState extends State<MyHomePAGE> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network('https://picsum.photos/250?image=9'), ), ) ); }} class MyClip extends CustomClipper<Rect> { Rect getClip(Size size) { return Rect.fromLTWH(0, 0, 100, 100); } bool shouldReclip(oldClipper) { return false; }}", "e": 26506, "s": 25386, "text": null }, { "code": null, "e": 26514, "s": 26506, "text": "Output:" }, { "code": null, "e": 26771, "s": 26514, "text": "First initialize the main app as a stateless widget.Second design the main widget as you desire.Build the Appbar with the scaffold widget.Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget." }, { "code": null, "e": 26824, "s": 26771, "text": "First initialize the main app as a stateless widget." }, { "code": null, "e": 26869, "s": 26824, "text": "Second design the main widget as you desire." }, { "code": null, "e": 26912, "s": 26869, "text": "Build the Appbar with the scaffold widget." }, { "code": null, "e": 27031, "s": 26912, "text": "Now use the ClipRect widget inside the body of the scaffold widget and place it in the middle using the center widget." }, { "code": null, "e": 27044, "s": 27031, "text": "ankit_kumar_" }, { "code": null, "e": 27052, "s": 27044, "text": "android" }, { "code": null, "e": 27060, "s": 27052, "text": "Flutter" }, { "code": null, "e": 27076, "s": 27060, "text": "Flutter-widgets" }, { "code": null, "e": 27081, "s": 27076, "text": "Dart" }, { "code": null, "e": 27179, "s": 27081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27188, "s": 27179, "text": "Comments" }, { "code": null, "e": 27201, "s": 27188, "text": "Old Comments" }, { "code": null, "e": 27233, "s": 27201, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 27272, "s": 27233, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27298, "s": 27272, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27344, "s": 27298, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 27370, "s": 27344, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27384, "s": 27370, "text": "Dart Tutorial" }, { "code": null, "e": 27410, "s": 27384, "text": "ListView Class in Flutter" }, { "code": null, "e": 27428, "s": 27410, "text": "Operators in Dart" }, { "code": null, "e": 27455, "s": 27428, "text": "Flutter - BoxShadow Widget" } ]
How to set the favicon size in CSS rather than HTML attributes?
A favicon is a little icon visible on the web browser tab, just before the page title. It is generally a logo with the smaller size. You cannot add the size using CSS. The standards do not support adding Favicon size using CSS. Let’s add it using attributes, <link rel="icon" type="image/png" href="https://tutorialspoint.com/favicon-16x16.png" sizes="16x16"> The result after adding Favicon above will be,
[ { "code": null, "e": 1195, "s": 1062, "text": "A favicon is a little icon visible on the web browser tab, just before the page title. It is generally a logo with the smaller size." }, { "code": null, "e": 1321, "s": 1195, "text": "You cannot add the size using CSS. The standards do not support adding Favicon size using CSS. Let’s add it using attributes," }, { "code": null, "e": 1422, "s": 1321, "text": "<link rel=\"icon\" type=\"image/png\" href=\"https://tutorialspoint.com/favicon-16x16.png\" sizes=\"16x16\">" }, { "code": null, "e": 1469, "s": 1422, "text": "The result after adding Favicon above will be," } ]
What is correct syntax to create Python lists?
List is a collection of comma separated objects, not necessarily of same type, and put inside square brackets []. List object is mutable and an item can appear more than once in the collection. >>> L1=["Raaj", 23, ["Phy", "Che", "maths"],8.5]
[ { "code": null, "e": 1256, "s": 1062, "text": "List is a collection of comma separated objects, not necessarily of same type, and put inside square brackets []. List object is mutable and an item can appear more than once in the collection." }, { "code": null, "e": 1305, "s": 1256, "text": ">>> L1=[\"Raaj\", 23, [\"Phy\", \"Che\", \"maths\"],8.5]" } ]
Date toInstant() Method in Java with Examples - GeeksforGeeks
26 Mar, 2019 The toInstant() method of Date class in Java is used to convert a Date object to an Instant object. An Instant is created during the conversion which is used to represent the same point on the timeline as this Date. Syntax: public Instant toInstant() Parameters: The method does not take any parameters. Return Value: The method returns an Instant representing the same point on the timeline as this Date. Below programs illustrate the use of toInstant() method in Java:Example 1: // Java code to demonstrate// toInstant() method of Date class import java.util.Date;import java.util.Calendar;import java.time.Instant; public class GfG { public static void main(String args[]) { // Creating a Calendar object Calendar c1 = Calendar.getInstance(); // Set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 00); // Set Date c1.set(Calendar.DATE, 30); // Set Year c1.set(Calendar.YEAR, 2019); // Creating a date object // with specified time. Date dateOne = c1.getTime(); Instant inst = dateOne.toInstant(); System.out.println( "Original Date: " + dateOne.toString()); System.out.println( "Instant: " + inst); }} Original Date: Wed Jan 30 06:01:46 UTC 2019 Instant: 2019-01-30T06:01:46.730Z Example 2: // Java code to demonstrate// clone() method of Date class import java.util.Date;import java.util.Calendar;import java.time.Instant; public class GfG { public static void main(String args[]) { // Creating a Calendar object Calendar c1 = Calendar.getInstance(); // Set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 06); // Set Date c1.set(Calendar.DATE, 12); // Set Year c1.set(Calendar.YEAR, 1996); // Creating a date object // with specified time. Date dateOne = c1.getTime(); Instant inst = dateOne.toInstant(); System.out.println( "Original Date: " + dateOne.toString()); System.out.println( "Instant: " + inst); }} Original Date: Fri Jul 12 06:01:49 UTC 1996 Instant: 1996-07-12T06:01:49.766Z Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant– Java - util package Java-Functions Java-util-Date Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java
[ { "code": null, "e": 24472, "s": 24444, "text": "\n26 Mar, 2019" }, { "code": null, "e": 24688, "s": 24472, "text": "The toInstant() method of Date class in Java is used to convert a Date object to an Instant object. An Instant is created during the conversion which is used to represent the same point on the timeline as this Date." }, { "code": null, "e": 24696, "s": 24688, "text": "Syntax:" }, { "code": null, "e": 24723, "s": 24696, "text": "public Instant toInstant()" }, { "code": null, "e": 24776, "s": 24723, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 24878, "s": 24776, "text": "Return Value: The method returns an Instant representing the same point on the timeline as this Date." }, { "code": null, "e": 24953, "s": 24878, "text": "Below programs illustrate the use of toInstant() method in Java:Example 1:" }, { "code": "// Java code to demonstrate// toInstant() method of Date class import java.util.Date;import java.util.Calendar;import java.time.Instant; public class GfG { public static void main(String args[]) { // Creating a Calendar object Calendar c1 = Calendar.getInstance(); // Set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 00); // Set Date c1.set(Calendar.DATE, 30); // Set Year c1.set(Calendar.YEAR, 2019); // Creating a date object // with specified time. Date dateOne = c1.getTime(); Instant inst = dateOne.toInstant(); System.out.println( \"Original Date: \" + dateOne.toString()); System.out.println( \"Instant: \" + inst); }}", "e": 25759, "s": 24953, "text": null }, { "code": null, "e": 25838, "s": 25759, "text": "Original Date: Wed Jan 30 06:01:46 UTC 2019\nInstant: 2019-01-30T06:01:46.730Z\n" }, { "code": null, "e": 25849, "s": 25838, "text": "Example 2:" }, { "code": "// Java code to demonstrate// clone() method of Date class import java.util.Date;import java.util.Calendar;import java.time.Instant; public class GfG { public static void main(String args[]) { // Creating a Calendar object Calendar c1 = Calendar.getInstance(); // Set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 06); // Set Date c1.set(Calendar.DATE, 12); // Set Year c1.set(Calendar.YEAR, 1996); // Creating a date object // with specified time. Date dateOne = c1.getTime(); Instant inst = dateOne.toInstant(); System.out.println( \"Original Date: \" + dateOne.toString()); System.out.println( \"Instant: \" + inst); }}", "e": 26651, "s": 25849, "text": null }, { "code": null, "e": 26730, "s": 26651, "text": "Original Date: Fri Jul 12 06:01:49 UTC 1996\nInstant: 1996-07-12T06:01:49.766Z\n" }, { "code": null, "e": 26814, "s": 26730, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant–" }, { "code": null, "e": 26834, "s": 26814, "text": "Java - util package" }, { "code": null, "e": 26849, "s": 26834, "text": "Java-Functions" }, { "code": null, "e": 26864, "s": 26849, "text": "Java-util-Date" }, { "code": null, "e": 26869, "s": 26864, "text": "Java" }, { "code": null, "e": 26874, "s": 26869, "text": "Java" }, { "code": null, "e": 26972, "s": 26874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26981, "s": 26972, "text": "Comments" }, { "code": null, "e": 26994, "s": 26981, "text": "Old Comments" }, { "code": null, "e": 27024, "s": 26994, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27043, "s": 27024, "text": "Interfaces in Java" }, { "code": null, "e": 27094, "s": 27043, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27112, "s": 27094, "text": "ArrayList in Java" }, { "code": null, "e": 27143, "s": 27112, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27175, "s": 27143, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27199, "s": 27175, "text": "Singleton Class in Java" }, { "code": null, "e": 27218, "s": 27199, "text": "Overriding in Java" }, { "code": null, "e": 27238, "s": 27218, "text": "Collections in Java" } ]
Check mirror in n-ary tree - GeeksforGeeks
07 Sep, 2021 Given two n-ary trees, the task is to check if they are the mirror of each other or not. Print “Yes” if they are the mirror of each other else “No”. Examples: Input : Node = 3, Edges = 2 Edge 1 of first N-ary: 1 2 Edge 2 of first N-ary: 1 3 Edge 1 of second N-ary: 1 3 Edge 2 of second N-ary: 1 2 Output : Yes Input : Node = 3, Edges = 2 Edge 1 of first N-ary: 1 2 Edge 2 of first N-ary: 1 3 Edge 1 of second N-ary: 1 2 Edge 2 of second N-ary: 1 3 Output : No Approach 1: (Using Hashing) The idea is to use an unordered map of stacks to check if given N-ary tree are mirror of each other or not. Let the first n-ary tree be t1 and the second n-ary tree is t2. For each node in t1, push its connected node in their corresponding stack in the map. Now, for each node in t2, their connected node match with the top of the stack, then pop elements from the stack. Otherwise, if the node does not match with the top of the stack then it means two trees are not mirror of each other. Now, for each corresponding node do the following: 1. Iterate over map of stack Push all connected nodes of each node of first tree in map of stack. 2. Again iterate over map for each node of second tree For example : Let us take one node X of second tree For this node X , check in map which stack is used a = Top of that stack for node X present in second tree; b = Connected node of X in second tree if (a != b) return false; pop node X from stack. C++ Java Python3 C# // C++ program to check if two n-ary trees are// mirror.#include <bits/stdc++.h>using namespace std; // Function to check given two trees are mirror// of each other or notint checkMirrorTree(int M, int N, int u1[ ], int v1[ ] , int u2[], int v2[]) { // Map to store nodes of the tree unordered_map<int , stack<int>>mp; // Traverse first tree nodes for (int i = 0 ; i < N ; i++ ) { mp[u1[i]].push(v1[i]); } // Traverse second tree nodes for (int i = 0 ; i < N ; i++) { if(mp[u2[i]].top() != v2[i]) return 0; mp[u2[i]].pop(); } return 1; } // Driver codeint main(){ int M = 7, N = 6; //Tree 1 int u1[] = { 1, 1, 1, 10, 10, 10 }; int v1[] = { 10, 7, 3, 4, 5, 6 }; //Tree 2 int u2[] = { 1, 1, 1, 10, 10, 10 }; int v2[] = { 3, 7, 10, 6, 5, 4 }; if(checkMirrorTree(M, N, u1, v1, u2, v2)) cout<<"Yes"; else cout<<"No"; return 0;} // Java program to check if two n-ary trees are mirror.import java.util.*;public class Main{ // Function to check given two trees are mirror // of each other or not static boolean checkMirrorTree(int M, int N, int[] u1, int[] v1, int[] u2, int[] v2) { // Map to store nodes of the tree HashMap<Integer, Stack<Integer>> mp = new HashMap<>(); // Traverse first tree nodes for (int i = 0 ; i < N ; i++ ) { if(!mp.containsKey(u1[i])) { mp.put(u1[i], new Stack<Integer>()); } else{ mp.get(u1[i]).push(v1[i]); } } // Traverse second tree nodes for (int i = 0 ; i < N ; i++) { if(mp.containsKey(u2[i]) && mp.get(u2[i]).size() > 0) { if(mp.get(u2[i]).peek() != v2[i]) return false; mp.get(u2[i]).pop(); } } return true; } // Driver code public static void main(String[] args) { int M = 7, N = 6; // Tree 1 int[] u1 = { 1, 1, 1, 10, 10, 10 }; int[] v1 = { 10, 7, 3, 4, 5, 6 }; // Tree 2 int[] u2 = { 1, 1, 1, 10, 10, 10 }; int[] v2 = { 3, 7, 10, 6, 5, 4 }; if(checkMirrorTree(M, N, u1, v1, u2, v2)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by divyeshrabadiya07. # Python3 program to check if two n-ary trees are mirror. # Function to check given two trees are mirror# of each other or notdef checkMirrorTree(M, N, u1, v1, u2, v2): # Map to store nodes of the tree mp = {} # Traverse first tree nodes for i in range(N): if u1[i] in mp: mp[u1[i]].append(v1[i]) else: mp[u1[i]] = [] # Traverse second tree nodes for i in range(N): if u2[i] in mp and len(mp[u2[i]]) > 0: if(mp[u2[i]][-1] != v2[i]): return 0 mp[u2[i]].pop() return 1 M, N = 7, 6 #Tree 1u1 = [ 1, 1, 1, 10, 10, 10 ]v1 = [ 10, 7, 3, 4, 5, 6 ] #Tree 2u2 = [ 1, 1, 1, 10, 10, 10 ]v2 = [ 3, 7, 10, 6, 5, 4 ] if(checkMirrorTree(M, N, u1, v1, u2, v2)): print("Yes")else: print("No") # This code is contributed by rameshtravel07. // C# program to check if two n-ary trees are mirror.using System;using System.Collections.Generic;class GFG { // Function to check given two trees are mirror // of each other or not static bool checkMirrorTree(int M, int N, int[] u1, int[] v1, int[] u2, int[] v2) { // Map to store nodes of the tree Dictionary<int, Stack<int>> mp = new Dictionary<int, Stack<int>>(); // Traverse first tree nodes for (int i = 0 ; i < N ; i++ ) { if(!mp.ContainsKey(u1[i])) { mp[u1[i]] = new Stack<int>(); } else{ mp[u1[i]].Push(v1[i]); } } // Traverse second tree nodes for (int i = 0 ; i < N ; i++) { if(mp.ContainsKey(u2[i]) && mp[u2[i]].Count > 0) { if(mp[u2[i]].Peek() != v2[i]) return false; mp[u2[i]].Pop(); } } return true; } // Driver code static void Main() { int M = 7, N = 6; // Tree 1 int[] u1 = { 1, 1, 1, 10, 10, 10 }; int[] v1 = { 10, 7, 3, 4, 5, 6 }; // Tree 2 int[] u2 = { 1, 1, 1, 10, 10, 10 }; int[] v2 = { 3, 7, 10, 6, 5, 4 }; if(checkMirrorTree(M, N, u1, v1, u2, v2)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by mukesh07. Yes Approach 2: (Using LinkedList): The main approach is to use one list of stack and one list of queue to store to value of nodes given in the form of two arrays. 1. Initialize both the lists with empty stack and empty queues respectively. 2. Now, iterate over the lists Push all connected nodes of each node of first tree in list of stack and second tree list of queue. 3. Now iterate over the array and pop item from both stack and queue and check if they are same, if not same then return 0. Java Python3 C# Javascript // Java program to check two n-ary trees are mirror. import java.io.*;import java.util.*; class GFG { // Function to check given two trees are mirror // of each other or not static int checkMirrorTree(int n, int e, int[] A, int[] B) { //Lists to store nodes of the tree List<Stack<Integer>> s = new ArrayList<>(); List<Queue<Integer>> q = new ArrayList<>(); // initializing both list with empty stack and queue for (int i = 0; i <= n; i++) { s.add(new Stack<>()); Queue<Integer> queue = new LinkedList<>(); q.add(queue); } // add all nodes of tree 1 to list of stack and tree 2 to list of queue for (int i = 0; i < 2 * e; i += 2) { s.get(A[i]).push(A[i + 1]); q.get(B[i]).add(B[i + 1]); } // now take out the stack and queues // for each of the nodes and compare them // one by one for (int i = 1; i <= n; i++) { while (!s.get(i).isEmpty() && !q.get(i).isEmpty()) { int a = s.get(i).pop(); int b = q.get(i).poll(); if (a != b) { return 0; } } } return 1; } public static void main (String[] args) { int n = 3; int e = 2; int A[] = { 1, 2, 1, 3 }; int B[] = { 1, 3, 1, 2 }; if (checkMirrorTree(n, e, A, B) == 1) { System.out.println("Yes"); } else { System.out.println("No"); } }} # Python3 program to check two n-ary trees are mirror. # Function to check given two trees are mirror# of each other or notdef checkMirrorTree(n, e, A, B): # Lists to store nodes of the tree s = [] q = [] # initializing both list with empty stack and queue for i in range(n + 1): s.append([]) queue = [] q.append(queue) # add all nodes of tree 1 to # list of stack and tree 2 to list of queue for i in range(0, 2 * e, 2): s[A[i]].append(A[i + 1]) q[B[i]].append(B[i + 1]) # now take out the stack and queues # for each of the nodes and compare them # one by one for i in range(1, n + 1): while (len(s[i]) > 0 and len(q[i]) > 0): a = s[i][len(s[i]) - 1] s[i].pop() b = q[i][0] q[i].pop(0) if (a != b): return 0 return 1 # Driver coden = 3e = 2A = [ 1, 2, 1, 3 ]B = [ 1, 3, 1, 2 ] if (checkMirrorTree(n, e, A, B) == 1): print("Yes")else: print("No") # This code is contributed by decode2207. // C# program to check two n-ary trees are mirror.using System;using System.Collections;using System.Collections.Generic;class GFG { // Function to check given two trees are mirror // of each other or not static int checkMirrorTree(int n, int e, int[] A, int[] B) { //Lists to store nodes of the tree List<Stack> s = new List<Stack>(); List<Queue> q = new List<Queue>(); // initializing both list with empty stack and queue for (int i = 0; i <= n; i++) { s.Add(new Stack()); Queue queue = new Queue(); q.Add(queue); } // add all nodes of tree 1 to list of stack and tree 2 to list of queue for (int i = 0; i < 2 * e; i += 2) { s[A[i]].Push(A[i + 1]); q[B[i]].Enqueue(B[i + 1]); } // now take out the stack and queues // for each of the nodes and compare them // one by one for (int i = 1; i <= n; i++) { while (s[i].Count > 0 && q[i].Count > 0) { int a = (int)s[i].Pop(); int b = (int)q[i].Dequeue(); if (a != b) { return 0; } } } return 1; } static void Main() { int n = 3; int e = 2; int[] A = { 1, 2, 1, 3 }; int[] B = { 1, 3, 1, 2 }; if (checkMirrorTree(n, e, A, B) == 1) { Console.Write("Yes"); } else { Console.Write("No"); } }} // This code is contributed by divyesh072019. <script> // Javascript program to check two n-ary trees are mirror. // Function to check given two trees are mirror // of each other or not function checkMirrorTree(n, e, A, B) { //Lists to store nodes of the tree let s = []; let q = []; // initializing both list with empty stack and queue for (let i = 0; i <= n; i++) { s.push([]); let queue = []; q.push(queue); } // add all nodes of tree 1 to // list of stack and tree 2 to list of queue for (let i = 0; i < 2 * e; i += 2) { s[A[i]].push(A[i + 1]); q[B[i]].push(B[i + 1]); } // now take out the stack and queues // for each of the nodes and compare them // one by one for (let i = 1; i <= n; i++) { while (s[i].length > 0 && q[i].length > 0) { let a = s[i][s[i].length - 1]; s[i].pop(); let b = q[i][0]; q[i].shift(); if (a != b) { return 0; } } } return 1; } let n = 3; let e = 2; let A = [ 1, 2, 1, 3 ]; let B = [ 1, 3, 1, 2 ]; if (checkMirrorTree(n, e, A, B) == 1) { document.write("Yes"); } else { document.write("No"); } // This code is contributed by suresh07.</script> Yes Reference: https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0This article is contributed by Nitin Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. cs_abhi rutvik_56 tridib_samanta GauravRajput1 nitinkumarco19 dwightschrute05 suresh07 rameshtravel07 mukesh07 divyeshrabadiya07 divyesh072019 decode2207 Amazon MakeMyTrip n-ary-tree STL Queue Stack Tree Amazon MakeMyTrip Stack Queue Tree STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue | Set 1 (Introduction and Array Implementation) Priority Queue | Set 1 (Introduction) LRU Cache Implementation Queue - Linked List Implementation Circular Queue | Set 1 (Introduction and Array Implementation) Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Program for Tower of Hanoi
[ { "code": null, "e": 24912, "s": 24884, "text": "\n07 Sep, 2021" }, { "code": null, "e": 25061, "s": 24912, "text": "Given two n-ary trees, the task is to check if they are the mirror of each other or not. Print “Yes” if they are the mirror of each other else “No”." }, { "code": null, "e": 25072, "s": 25061, "text": "Examples: " }, { "code": null, "e": 25223, "s": 25072, "text": "Input : Node = 3, Edges = 2\nEdge 1 of first N-ary: 1 2\nEdge 2 of first N-ary: 1 3\nEdge 1 of second N-ary: 1 3\nEdge 2 of second N-ary: 1 2\nOutput : Yes" }, { "code": null, "e": 25374, "s": 25223, "text": "Input : Node = 3, Edges = 2\nEdge 1 of first N-ary: 1 2 \nEdge 2 of first N-ary: 1 3\nEdge 1 of second N-ary: 1 2\nEdge 2 of second N-ary: 1 3\nOutput : No" }, { "code": null, "e": 25403, "s": 25374, "text": "Approach 1: (Using Hashing)" }, { "code": null, "e": 25777, "s": 25403, "text": "The idea is to use an unordered map of stacks to check if given N-ary tree are mirror of each other or not. Let the first n-ary tree be t1 and the second n-ary tree is t2. For each node in t1, push its connected node in their corresponding stack in the map. Now, for each node in t2, their connected node match with the top of the stack, then pop elements from the stack. " }, { "code": null, "e": 25948, "s": 25777, "text": "Otherwise, if the node does not match with the top of the stack then it means two trees are not mirror of each other. Now, for each corresponding node do the following: " }, { "code": null, "e": 26429, "s": 25948, "text": " 1. Iterate over map of stack\n Push all connected nodes of each node of first tree in map of stack.\n\n 2. Again iterate over map for each node of second tree\n For example : \n\n Let us take one node X of second tree \n \n For this node X , check in map which stack is used\n\n a = Top of that stack for node X present in second tree;\n b = Connected node of X in second tree\n if (a != b)\n return false;\n pop node X from stack." }, { "code": null, "e": 26433, "s": 26429, "text": "C++" }, { "code": null, "e": 26438, "s": 26433, "text": "Java" }, { "code": null, "e": 26446, "s": 26438, "text": "Python3" }, { "code": null, "e": 26449, "s": 26446, "text": "C#" }, { "code": "// C++ program to check if two n-ary trees are// mirror.#include <bits/stdc++.h>using namespace std; // Function to check given two trees are mirror// of each other or notint checkMirrorTree(int M, int N, int u1[ ], int v1[ ] , int u2[], int v2[]) { // Map to store nodes of the tree unordered_map<int , stack<int>>mp; // Traverse first tree nodes for (int i = 0 ; i < N ; i++ ) { mp[u1[i]].push(v1[i]); } // Traverse second tree nodes for (int i = 0 ; i < N ; i++) { if(mp[u2[i]].top() != v2[i]) return 0; mp[u2[i]].pop(); } return 1; } // Driver codeint main(){ int M = 7, N = 6; //Tree 1 int u1[] = { 1, 1, 1, 10, 10, 10 }; int v1[] = { 10, 7, 3, 4, 5, 6 }; //Tree 2 int u2[] = { 1, 1, 1, 10, 10, 10 }; int v2[] = { 3, 7, 10, 6, 5, 4 }; if(checkMirrorTree(M, N, u1, v1, u2, v2)) cout<<\"Yes\"; else cout<<\"No\"; return 0;}", "e": 27492, "s": 26449, "text": null }, { "code": "// Java program to check if two n-ary trees are mirror.import java.util.*;public class Main{ // Function to check given two trees are mirror // of each other or not static boolean checkMirrorTree(int M, int N, int[] u1, int[] v1, int[] u2, int[] v2) { // Map to store nodes of the tree HashMap<Integer, Stack<Integer>> mp = new HashMap<>(); // Traverse first tree nodes for (int i = 0 ; i < N ; i++ ) { if(!mp.containsKey(u1[i])) { mp.put(u1[i], new Stack<Integer>()); } else{ mp.get(u1[i]).push(v1[i]); } } // Traverse second tree nodes for (int i = 0 ; i < N ; i++) { if(mp.containsKey(u2[i]) && mp.get(u2[i]).size() > 0) { if(mp.get(u2[i]).peek() != v2[i]) return false; mp.get(u2[i]).pop(); } } return true; } // Driver code public static void main(String[] args) { int M = 7, N = 6; // Tree 1 int[] u1 = { 1, 1, 1, 10, 10, 10 }; int[] v1 = { 10, 7, 3, 4, 5, 6 }; // Tree 2 int[] u2 = { 1, 1, 1, 10, 10, 10 }; int[] v2 = { 3, 7, 10, 6, 5, 4 }; if(checkMirrorTree(M, N, u1, v1, u2, v2)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by divyeshrabadiya07.", "e": 28986, "s": 27492, "text": null }, { "code": "# Python3 program to check if two n-ary trees are mirror. # Function to check given two trees are mirror# of each other or notdef checkMirrorTree(M, N, u1, v1, u2, v2): # Map to store nodes of the tree mp = {} # Traverse first tree nodes for i in range(N): if u1[i] in mp: mp[u1[i]].append(v1[i]) else: mp[u1[i]] = [] # Traverse second tree nodes for i in range(N): if u2[i] in mp and len(mp[u2[i]]) > 0: if(mp[u2[i]][-1] != v2[i]): return 0 mp[u2[i]].pop() return 1 M, N = 7, 6 #Tree 1u1 = [ 1, 1, 1, 10, 10, 10 ]v1 = [ 10, 7, 3, 4, 5, 6 ] #Tree 2u2 = [ 1, 1, 1, 10, 10, 10 ]v2 = [ 3, 7, 10, 6, 5, 4 ] if(checkMirrorTree(M, N, u1, v1, u2, v2)): print(\"Yes\")else: print(\"No\") # This code is contributed by rameshtravel07.", "e": 29833, "s": 28986, "text": null }, { "code": "// C# program to check if two n-ary trees are mirror.using System;using System.Collections.Generic;class GFG { // Function to check given two trees are mirror // of each other or not static bool checkMirrorTree(int M, int N, int[] u1, int[] v1, int[] u2, int[] v2) { // Map to store nodes of the tree Dictionary<int, Stack<int>> mp = new Dictionary<int, Stack<int>>(); // Traverse first tree nodes for (int i = 0 ; i < N ; i++ ) { if(!mp.ContainsKey(u1[i])) { mp[u1[i]] = new Stack<int>(); } else{ mp[u1[i]].Push(v1[i]); } } // Traverse second tree nodes for (int i = 0 ; i < N ; i++) { if(mp.ContainsKey(u2[i]) && mp[u2[i]].Count > 0) { if(mp[u2[i]].Peek() != v2[i]) return false; mp[u2[i]].Pop(); } } return true; } // Driver code static void Main() { int M = 7, N = 6; // Tree 1 int[] u1 = { 1, 1, 1, 10, 10, 10 }; int[] v1 = { 10, 7, 3, 4, 5, 6 }; // Tree 2 int[] u2 = { 1, 1, 1, 10, 10, 10 }; int[] v2 = { 3, 7, 10, 6, 5, 4 }; if(checkMirrorTree(M, N, u1, v1, u2, v2)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by mukesh07.", "e": 31239, "s": 29833, "text": null }, { "code": null, "e": 31243, "s": 31239, "text": "Yes" }, { "code": null, "e": 31275, "s": 31243, "text": "Approach 2: (Using LinkedList):" }, { "code": null, "e": 31403, "s": 31275, "text": "The main approach is to use one list of stack and one list of queue to store to value of nodes given in the form of two arrays." }, { "code": null, "e": 31745, "s": 31403, "text": "1. Initialize both the lists with empty stack and empty queues respectively.\n\n2. Now, iterate over the lists\n Push all connected nodes of each node of first tree in list of stack and second tree list of queue.\n \n3. Now iterate over the array and pop item from both stack and queue and check if they are same, if not same then return 0." }, { "code": null, "e": 31750, "s": 31745, "text": "Java" }, { "code": null, "e": 31758, "s": 31750, "text": "Python3" }, { "code": null, "e": 31761, "s": 31758, "text": "C#" }, { "code": null, "e": 31772, "s": 31761, "text": "Javascript" }, { "code": "// Java program to check two n-ary trees are mirror. import java.io.*;import java.util.*; class GFG { // Function to check given two trees are mirror // of each other or not static int checkMirrorTree(int n, int e, int[] A, int[] B) { //Lists to store nodes of the tree List<Stack<Integer>> s = new ArrayList<>(); List<Queue<Integer>> q = new ArrayList<>(); // initializing both list with empty stack and queue for (int i = 0; i <= n; i++) { s.add(new Stack<>()); Queue<Integer> queue = new LinkedList<>(); q.add(queue); } // add all nodes of tree 1 to list of stack and tree 2 to list of queue for (int i = 0; i < 2 * e; i += 2) { s.get(A[i]).push(A[i + 1]); q.get(B[i]).add(B[i + 1]); } // now take out the stack and queues // for each of the nodes and compare them // one by one for (int i = 1; i <= n; i++) { while (!s.get(i).isEmpty() && !q.get(i).isEmpty()) { int a = s.get(i).pop(); int b = q.get(i).poll(); if (a != b) { return 0; } } } return 1; } public static void main (String[] args) { int n = 3; int e = 2; int A[] = { 1, 2, 1, 3 }; int B[] = { 1, 3, 1, 2 }; if (checkMirrorTree(n, e, A, B) == 1) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}", "e": 33327, "s": 31772, "text": null }, { "code": "# Python3 program to check two n-ary trees are mirror. # Function to check given two trees are mirror# of each other or notdef checkMirrorTree(n, e, A, B): # Lists to store nodes of the tree s = [] q = [] # initializing both list with empty stack and queue for i in range(n + 1): s.append([]) queue = [] q.append(queue) # add all nodes of tree 1 to # list of stack and tree 2 to list of queue for i in range(0, 2 * e, 2): s[A[i]].append(A[i + 1]) q[B[i]].append(B[i + 1]) # now take out the stack and queues # for each of the nodes and compare them # one by one for i in range(1, n + 1): while (len(s[i]) > 0 and len(q[i]) > 0): a = s[i][len(s[i]) - 1] s[i].pop() b = q[i][0] q[i].pop(0) if (a != b): return 0 return 1 # Driver coden = 3e = 2A = [ 1, 2, 1, 3 ]B = [ 1, 3, 1, 2 ] if (checkMirrorTree(n, e, A, B) == 1): print(\"Yes\")else: print(\"No\") # This code is contributed by decode2207.", "e": 34386, "s": 33327, "text": null }, { "code": "// C# program to check two n-ary trees are mirror.using System;using System.Collections;using System.Collections.Generic;class GFG { // Function to check given two trees are mirror // of each other or not static int checkMirrorTree(int n, int e, int[] A, int[] B) { //Lists to store nodes of the tree List<Stack> s = new List<Stack>(); List<Queue> q = new List<Queue>(); // initializing both list with empty stack and queue for (int i = 0; i <= n; i++) { s.Add(new Stack()); Queue queue = new Queue(); q.Add(queue); } // add all nodes of tree 1 to list of stack and tree 2 to list of queue for (int i = 0; i < 2 * e; i += 2) { s[A[i]].Push(A[i + 1]); q[B[i]].Enqueue(B[i + 1]); } // now take out the stack and queues // for each of the nodes and compare them // one by one for (int i = 1; i <= n; i++) { while (s[i].Count > 0 && q[i].Count > 0) { int a = (int)s[i].Pop(); int b = (int)q[i].Dequeue(); if (a != b) { return 0; } } } return 1; } static void Main() { int n = 3; int e = 2; int[] A = { 1, 2, 1, 3 }; int[] B = { 1, 3, 1, 2 }; if (checkMirrorTree(n, e, A, B) == 1) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); } }} // This code is contributed by divyesh072019.", "e": 35906, "s": 34386, "text": null }, { "code": "<script> // Javascript program to check two n-ary trees are mirror. // Function to check given two trees are mirror // of each other or not function checkMirrorTree(n, e, A, B) { //Lists to store nodes of the tree let s = []; let q = []; // initializing both list with empty stack and queue for (let i = 0; i <= n; i++) { s.push([]); let queue = []; q.push(queue); } // add all nodes of tree 1 to // list of stack and tree 2 to list of queue for (let i = 0; i < 2 * e; i += 2) { s[A[i]].push(A[i + 1]); q[B[i]].push(B[i + 1]); } // now take out the stack and queues // for each of the nodes and compare them // one by one for (let i = 1; i <= n; i++) { while (s[i].length > 0 && q[i].length > 0) { let a = s[i][s[i].length - 1]; s[i].pop(); let b = q[i][0]; q[i].shift(); if (a != b) { return 0; } } } return 1; } let n = 3; let e = 2; let A = [ 1, 2, 1, 3 ]; let B = [ 1, 3, 1, 2 ]; if (checkMirrorTree(n, e, A, B) == 1) { document.write(\"Yes\"); } else { document.write(\"No\"); } // This code is contributed by suresh07.</script>", "e": 37321, "s": 35906, "text": null }, { "code": null, "e": 37325, "s": 37321, "text": "Yes" }, { "code": null, "e": 37828, "s": 37325, "text": "Reference: https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0This article is contributed by Nitin Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 37836, "s": 37828, "text": "cs_abhi" }, { "code": null, "e": 37846, "s": 37836, "text": "rutvik_56" }, { "code": null, "e": 37861, "s": 37846, "text": "tridib_samanta" }, { "code": null, "e": 37875, "s": 37861, "text": "GauravRajput1" }, { "code": null, "e": 37890, "s": 37875, "text": "nitinkumarco19" }, { "code": null, "e": 37906, "s": 37890, "text": "dwightschrute05" }, { "code": null, "e": 37915, "s": 37906, "text": "suresh07" }, { "code": null, "e": 37930, "s": 37915, "text": "rameshtravel07" }, { "code": null, "e": 37939, "s": 37930, "text": "mukesh07" }, { "code": null, "e": 37957, "s": 37939, "text": "divyeshrabadiya07" }, { "code": null, "e": 37971, "s": 37957, "text": "divyesh072019" }, { "code": null, "e": 37982, "s": 37971, "text": "decode2207" }, { "code": null, "e": 37989, "s": 37982, "text": "Amazon" }, { "code": null, "e": 38000, "s": 37989, "text": "MakeMyTrip" }, { "code": null, "e": 38011, "s": 38000, "text": "n-ary-tree" }, { "code": null, "e": 38015, "s": 38011, "text": "STL" }, { "code": null, "e": 38021, "s": 38015, "text": "Queue" }, { "code": null, "e": 38027, "s": 38021, "text": "Stack" }, { "code": null, "e": 38032, "s": 38027, "text": "Tree" }, { "code": null, "e": 38039, "s": 38032, "text": "Amazon" }, { "code": null, "e": 38050, "s": 38039, "text": "MakeMyTrip" }, { "code": null, "e": 38056, "s": 38050, "text": "Stack" }, { "code": null, "e": 38062, "s": 38056, "text": "Queue" }, { "code": null, "e": 38067, "s": 38062, "text": "Tree" }, { "code": null, "e": 38071, "s": 38067, "text": "STL" }, { "code": null, "e": 38169, "s": 38071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38223, "s": 38169, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 38261, "s": 38223, "text": "Priority Queue | Set 1 (Introduction)" }, { "code": null, "e": 38286, "s": 38261, "text": "LRU Cache Implementation" }, { "code": null, "e": 38321, "s": 38286, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 38384, "s": 38321, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 38432, "s": 38384, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38452, "s": 38432, "text": "Stack Class in Java" }, { "code": null, "e": 38468, "s": 38452, "text": "Stack in Python" }, { "code": null, "e": 38543, "s": 38468, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Scikit Learn - Decision Trees
In this chapter, we will learn about learning method in Sklearn which is termed as decision trees. Decisions tress (DTs) are the most powerful non-parametric supervised learning method. They can be used for the classification and regression tasks. The main goal of DTs is to create a model predicting target variable value by learning simple decision rules deduced from the data features. Decision trees have two main entities; one is root node, where the data splits, and other is decision nodes or leaves, where we got final output. Different Decision Tree algorithms are explained below − It was developed by Ross Quinlan in 1986. It is also called Iterative Dichotomiser 3. The main goal of this algorithm is to find those categorical features, for every node, that will yield the largest information gain for categorical targets. It lets the tree to be grown to their maximum size and then to improve the tree’s ability on unseen data, applies a pruning step. The output of this algorithm would be a multiway tree. It is the successor to ID3 and dynamically defines a discrete attribute that partition the continuous attribute value into a discrete set of intervals. That’s the reason it removed the restriction of categorical features. It converts the ID3 trained tree into sets of ‘IF-THEN’ rules. In order to determine the sequence in which these rules should applied, the accuracy of each rule will be evaluated first. It works similar as C4.5 but it uses less memory and build smaller rulesets. It is more accurate than C4.5. It is called Classification and Regression Trees alsgorithm. It basically generates binary splits by using the features and threshold yielding the largest information gain at each node (called the Gini index). Homogeneity depends upon Gini index, higher the value of Gini index, higher would be the homogeneity. It is like C4.5 algorithm, but, the difference is that it does not compute rule sets and does not support numerical target variables (regression) as well. In this case, the decision variables are categorical. Sklearn Module − The Scikit-learn library provides the module name DecisionTreeClassifier for performing multiclass classification on dataset. Following table consist the parameters used by sklearn.tree.DecisionTreeClassifier module − criterion − string, optional default= “gini” It represents the function to measure the quality of a split. Supported criteria are “gini” and “entropy”. The default is gini which is for Gini impurity while entropy is for the information gain. splitter − string, optional default= “best” It tells the model, which strategy from “best” or “random” to choose the split at each node. max_depth − int or None, optional default=None This parameter decides the maximum depth of the tree. The default value is None which means the nodes will expand until all leaves are pure or until all leaves contain less than min_smaples_split samples. min_samples_split − int, float, optional default=2 This parameter provides the minimum number of samples required to split an internal node. min_samples_leaf − int, float, optional default=1 This parameter provides the minimum number of samples required to be at a leaf node. min_weight_fraction_leaf − float, optional default=0. With this parameter, the model will get the minimum weighted fraction of the sum of weights required to be at a leaf node. max_features − int, float, string or None, optional default=None It gives the model the number of features to be considered when looking for the best split. random_state − int, RandomState instance or None, optional, default = none This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options − int − In this case, random_state is the seed used by random number generator. int − In this case, random_state is the seed used by random number generator. RandomState instance − In this case, random_state is the random number generator. RandomState instance − In this case, random_state is the random number generator. None − In this case, the random number generator is the RandonState instance used by np.random. None − In this case, the random number generator is the RandonState instance used by np.random. max_leaf_nodes − int or None, optional default=None This parameter will let grow a tree with max_leaf_nodes in best-first fashion. The default is none which means there would be unlimited number of leaf nodes. min_impurity_decrease − float, optional default=0. This value works as a criterion for a node to split because the model will split a node if this split induces a decrease of the impurity greater than or equal to min_impurity_decrease value. min_impurity_split − float, default=1e-7 It represents the threshold for early stopping in tree growth. class_weight − dict, list of dicts, “balanced” or None, default=None It represents the weights associated with classes. The form is {class_label: weight}. If we use the default option, it means all the classes are supposed to have weight one. On the other hand, if you choose class_weight: balanced, it will use the values of y to automatically adjust weights. presort − bool, optional default=False It tells the model whether to presort the data to speed up the finding of best splits in fitting. The default is false but of set to true, it may slow down the training process. Following table consist the attributes used by sklearn.tree.DecisionTreeClassifier module − feature_importances_ − array of shape =[n_features] This attribute will return the feature importance. classes_: − array of shape = [n_classes] or a list of such arrays It represents the classes labels i.e. the single output problem, or a list of arrays of class labels i.e. multi-output problem. max_features_ − int It represents the deduced value of max_features parameter. n_classes_ − int or list It represents the number of classes i.e. the single output problem, or a list of number of classes for every output i.e. multi-output problem. n_features_ − int It gives the number of features when fit() method is performed. n_outputs_ − int It gives the number of outputs when fit() method is performed. Following table consist the methods used by sklearn.tree.DecisionTreeClassifier module − apply(self, X[, check_input]) This method will return the index of the leaf. decision_path(self, X[, check_input]) As name suggests, this method will return the decision path in the tree fit(self, X, y[, sample_weight, ...]) fit() method will build a decision tree classifier from given training set (X, y). get_depth(self) As name suggests, this method will return the depth of the decision tree get_n_leaves(self) As name suggests, this method will return the number of leaves of the decision tree. get_params(self[, deep]) We can use this method to get the parameters for estimator. predict(self, X[, check_input]) It will predict class value for X. predict_log_proba(self, X) It will predict class log-probabilities of the input samples provided by us, X. predict_proba(self, X[, check_input]) It will predict class probabilities of the input samples provided by us, X. score(self, X, y[, sample_weight]) As the name implies, the score() method will return the mean accuracy on the given test data and labels.. set_params(self, \*\*params) We can set the parameters of estimator with this method. The Python script below will use sklearn.tree.DecisionTreeClassifier module to construct a classifier for predicting male or female from our data set having 25 samples and two features namely ‘height’ and ‘length of hair’ − from sklearn import tree from sklearn.model_selection import train_test_split X=[[165,19],[175,32],[136,35],[174,65],[141,28],[176,15] ,[131,32],[166,6],[128,32],[179,10],[136,34],[186,2],[12 6,25],[176,28],[112,38],[169,9],[171,36],[116,25],[196,2 5], [196,38], [126,40], [197,20], [150,25], [140,32],[136,35]] Y=['Man','Woman','Woman','Man','Woman','Man','Woman','Ma n','Woman','Man','Woman','Man','Woman','Woman','Woman',' Man','Woman','Woman','Man', 'Woman', 'Woman', 'Man', 'Man', 'Woman', 'Woman'] data_feature_names = ['height','length of hair'] X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state = 1) DTclf = tree.DecisionTreeClassifier() DTclf = clf.fit(X,Y) prediction = DTclf.predict([[135,29]]) print(prediction) ['Woman'] We can also predict the probability of each class by using following python predict_proba() method as follows − prediction = DTclf.predict_proba([[135,29]]) print(prediction) [[0. 1.]] In this case the decision variables are continuous. Sklearn Module − The Scikit-learn library provides the module name DecisionTreeRegressor for applying decision trees on regression problems. Parameters used by DecisionTreeRegressor are almost same as that were used in DecisionTreeClassifier module. The difference lies in ‘criterion’ parameter. For DecisionTreeRegressor modules ‘criterion: string, optional default= “mse”’ parameter have the following values − mse − It stands for the mean squared error. It is equal to variance reduction as feature selectin criterion. It minimises the L2 loss using the mean of each terminal node. mse − It stands for the mean squared error. It is equal to variance reduction as feature selectin criterion. It minimises the L2 loss using the mean of each terminal node. freidman_mse − It also uses mean squared error but with Friedman’s improvement score. freidman_mse − It also uses mean squared error but with Friedman’s improvement score. mae − It stands for the mean absolute error. It minimizes the L1 loss using the median of each terminal node. mae − It stands for the mean absolute error. It minimizes the L1 loss using the median of each terminal node. Another difference is that it does not have ‘class_weight’ parameter. Attributes of DecisionTreeRegressor are also same as that were of DecisionTreeClassifier module. The difference is that it does not have ‘classes_’ and ‘n_classes_’ attributes. Methods of DecisionTreeRegressor are also same as that were of DecisionTreeClassifier module. The difference is that it does not have ‘predict_log_proba()’ and ‘predict_proba()’’ attributes. The fit() method in Decision tree regression model will take floating point values of y. let’s see a simple implementation example by using Sklearn.tree.DecisionTreeRegressor − from sklearn import tree X = [[1, 1], [5, 5]] y = [0.1, 1.5] DTreg = tree.DecisionTreeRegressor() DTreg = clf.fit(X, y) Once fitted, we can use this regression model to make prediction as follows − DTreg.predict([[4, 5]]) array([1.5]) 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2320, "s": 2221, "text": "In this chapter, we will learn about learning method in Sklearn which is termed as decision trees." }, { "code": null, "e": 2756, "s": 2320, "text": "Decisions tress (DTs) are the most powerful non-parametric supervised learning method. They can be used for the classification and regression tasks. The main goal of DTs is to create a model predicting target variable value by learning simple decision rules deduced from the data features. Decision trees have two main entities; one is root node, where the data splits, and other is decision nodes or leaves, where we got final output." }, { "code": null, "e": 2813, "s": 2756, "text": "Different Decision Tree algorithms are explained below −" }, { "code": null, "e": 3056, "s": 2813, "text": "It was developed by Ross Quinlan in 1986. It is also called Iterative Dichotomiser 3. The main goal of this algorithm is to find those categorical features, for every node, that will yield the largest information gain for categorical targets." }, { "code": null, "e": 3241, "s": 3056, "text": "It lets the tree to be grown to their maximum size and then to improve the tree’s ability on unseen data, applies a pruning step. The output of this algorithm would be a multiway tree." }, { "code": null, "e": 3526, "s": 3241, "text": "It is the successor to ID3 and dynamically defines a discrete attribute that partition the continuous attribute value into a discrete set of intervals. That’s the reason it removed the restriction of categorical features. It converts the ID3 trained tree into sets of ‘IF-THEN’ rules." }, { "code": null, "e": 3649, "s": 3526, "text": "In order to determine the sequence in which these rules should applied, the accuracy of each rule will be evaluated first." }, { "code": null, "e": 3757, "s": 3649, "text": "It works similar as C4.5 but it uses less memory and build smaller rulesets. It is more accurate than C4.5." }, { "code": null, "e": 3967, "s": 3757, "text": "It is called Classification and Regression Trees alsgorithm. It basically generates binary splits by using the features and threshold yielding the largest information gain at each node (called the Gini index)." }, { "code": null, "e": 4224, "s": 3967, "text": "Homogeneity depends upon Gini index, higher the value of Gini index, higher would be the homogeneity. It is like C4.5 algorithm, but, the difference is that it does not compute rule sets and does not support numerical target variables (regression) as well." }, { "code": null, "e": 4278, "s": 4224, "text": "In this case, the decision variables are categorical." }, { "code": null, "e": 4421, "s": 4278, "text": "Sklearn Module − The Scikit-learn library provides the module name DecisionTreeClassifier for performing multiclass classification on dataset." }, { "code": null, "e": 4513, "s": 4421, "text": "Following table consist the parameters used by sklearn.tree.DecisionTreeClassifier module −" }, { "code": null, "e": 4558, "s": 4513, "text": "criterion − string, optional default= “gini”" }, { "code": null, "e": 4755, "s": 4558, "text": "It represents the function to measure the quality of a split. Supported criteria are “gini” and “entropy”. The default is gini which is for Gini impurity while entropy is for the information gain." }, { "code": null, "e": 4799, "s": 4755, "text": "splitter − string, optional default= “best”" }, { "code": null, "e": 4892, "s": 4799, "text": "It tells the model, which strategy from “best” or “random” to choose the split at each node." }, { "code": null, "e": 4939, "s": 4892, "text": "max_depth − int or None, optional default=None" }, { "code": null, "e": 5144, "s": 4939, "text": "This parameter decides the maximum depth of the tree. The default value is None which means the nodes will expand until all leaves are pure or until all leaves contain less than min_smaples_split samples." }, { "code": null, "e": 5195, "s": 5144, "text": "min_samples_split − int, float, optional default=2" }, { "code": null, "e": 5285, "s": 5195, "text": "This parameter provides the minimum number of samples required to split an internal node." }, { "code": null, "e": 5335, "s": 5285, "text": "min_samples_leaf − int, float, optional default=1" }, { "code": null, "e": 5420, "s": 5335, "text": "This parameter provides the minimum number of samples required to be at a leaf node." }, { "code": null, "e": 5474, "s": 5420, "text": "min_weight_fraction_leaf − float, optional default=0." }, { "code": null, "e": 5597, "s": 5474, "text": "With this parameter, the model will get the minimum weighted fraction of the sum of weights required to be at a leaf node." }, { "code": null, "e": 5662, "s": 5597, "text": "max_features − int, float, string or None, optional default=None" }, { "code": null, "e": 5754, "s": 5662, "text": "It gives the model the number of features to be considered when looking for the best split." }, { "code": null, "e": 5829, "s": 5754, "text": "random_state − int, RandomState instance or None, optional, default = none" }, { "code": null, "e": 5971, "s": 5829, "text": "This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options −" }, { "code": null, "e": 6049, "s": 5971, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 6127, "s": 6049, "text": "int − In this case, random_state is the seed used by random number generator." }, { "code": null, "e": 6209, "s": 6127, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 6291, "s": 6209, "text": "RandomState instance − In this case, random_state is the random number generator." }, { "code": null, "e": 6387, "s": 6291, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 6483, "s": 6387, "text": "None − In this case, the random number generator is the RandonState instance used by np.random." }, { "code": null, "e": 6535, "s": 6483, "text": "max_leaf_nodes − int or None, optional default=None" }, { "code": null, "e": 6693, "s": 6535, "text": "This parameter will let grow a tree with max_leaf_nodes in best-first fashion. The default is none which means there would be unlimited number of leaf nodes." }, { "code": null, "e": 6744, "s": 6693, "text": "min_impurity_decrease − float, optional default=0." }, { "code": null, "e": 6935, "s": 6744, "text": "This value works as a criterion for a node to split because the model will split a node if this split induces a decrease of the impurity greater than or equal to min_impurity_decrease value." }, { "code": null, "e": 6976, "s": 6935, "text": "min_impurity_split − float, default=1e-7" }, { "code": null, "e": 7039, "s": 6976, "text": "It represents the threshold for early stopping in tree growth." }, { "code": null, "e": 7108, "s": 7039, "text": "class_weight − dict, list of dicts, “balanced” or None, default=None" }, { "code": null, "e": 7400, "s": 7108, "text": "It represents the weights associated with classes. The form is {class_label: weight}. If we use the default option, it means all the classes are supposed to have weight one. On the other hand, if you choose class_weight: balanced, it will use the values of y to automatically adjust weights." }, { "code": null, "e": 7439, "s": 7400, "text": "presort − bool, optional default=False" }, { "code": null, "e": 7617, "s": 7439, "text": "It tells the model whether to presort the data to speed up the finding of best splits in fitting. The default is false but of set to true, it may slow down the training process." }, { "code": null, "e": 7709, "s": 7617, "text": "Following table consist the attributes used by sklearn.tree.DecisionTreeClassifier module −" }, { "code": null, "e": 7761, "s": 7709, "text": "feature_importances_ − array of shape =[n_features]" }, { "code": null, "e": 7812, "s": 7761, "text": "This attribute will return the feature importance." }, { "code": null, "e": 7878, "s": 7812, "text": "classes_: − array of shape = [n_classes] or a list of such arrays" }, { "code": null, "e": 8006, "s": 7878, "text": "It represents the classes labels i.e. the single output problem, or a list of arrays of class labels i.e. multi-output problem." }, { "code": null, "e": 8026, "s": 8006, "text": "max_features_ − int" }, { "code": null, "e": 8085, "s": 8026, "text": "It represents the deduced value of max_features parameter." }, { "code": null, "e": 8110, "s": 8085, "text": "n_classes_ − int or list" }, { "code": null, "e": 8253, "s": 8110, "text": "It represents the number of classes i.e. the single output problem, or a list of number of classes for every output i.e. multi-output problem." }, { "code": null, "e": 8271, "s": 8253, "text": "n_features_ − int" }, { "code": null, "e": 8335, "s": 8271, "text": "It gives the number of features when fit() method is performed." }, { "code": null, "e": 8352, "s": 8335, "text": "n_outputs_ − int" }, { "code": null, "e": 8415, "s": 8352, "text": "It gives the number of outputs when fit() method is performed." }, { "code": null, "e": 8504, "s": 8415, "text": "Following table consist the methods used by sklearn.tree.DecisionTreeClassifier module −" }, { "code": null, "e": 8534, "s": 8504, "text": "apply(self, X[, check_input])" }, { "code": null, "e": 8581, "s": 8534, "text": "This method will return the index of the leaf." }, { "code": null, "e": 8619, "s": 8581, "text": "decision_path(self, X[, check_input])" }, { "code": null, "e": 8691, "s": 8619, "text": "As name suggests, this method will return the decision path in the tree" }, { "code": null, "e": 8729, "s": 8691, "text": "fit(self, X, y[, sample_weight, ...])" }, { "code": null, "e": 8812, "s": 8729, "text": "fit() method will build a decision tree classifier from given training set (X, y)." }, { "code": null, "e": 8828, "s": 8812, "text": "get_depth(self)" }, { "code": null, "e": 8901, "s": 8828, "text": "As name suggests, this method will return the depth of the decision tree" }, { "code": null, "e": 8920, "s": 8901, "text": "get_n_leaves(self)" }, { "code": null, "e": 9005, "s": 8920, "text": "As name suggests, this method will return the number of leaves of the decision tree." }, { "code": null, "e": 9030, "s": 9005, "text": "get_params(self[, deep])" }, { "code": null, "e": 9090, "s": 9030, "text": "We can use this method to get the parameters for estimator." }, { "code": null, "e": 9122, "s": 9090, "text": "predict(self, X[, check_input])" }, { "code": null, "e": 9157, "s": 9122, "text": "It will predict class value for X." }, { "code": null, "e": 9184, "s": 9157, "text": "predict_log_proba(self, X)" }, { "code": null, "e": 9264, "s": 9184, "text": "It will predict class log-probabilities of the input samples provided by us, X." }, { "code": null, "e": 9302, "s": 9264, "text": "predict_proba(self, X[, check_input])" }, { "code": null, "e": 9378, "s": 9302, "text": "It will predict class probabilities of the input samples provided by us, X." }, { "code": null, "e": 9413, "s": 9378, "text": "score(self, X, y[, sample_weight])" }, { "code": null, "e": 9519, "s": 9413, "text": "As the name implies, the score() method will return the mean accuracy on the given test data and labels.." }, { "code": null, "e": 9548, "s": 9519, "text": "set_params(self, \\*\\*params)" }, { "code": null, "e": 9605, "s": 9548, "text": "We can set the parameters of estimator with this method." }, { "code": null, "e": 9829, "s": 9605, "text": "The Python script below will use sklearn.tree.DecisionTreeClassifier module to construct a classifier for predicting male or female from our data set having 25 samples and two features namely ‘height’ and ‘length of hair’ −" }, { "code": null, "e": 10591, "s": 9829, "text": "from sklearn import tree\nfrom sklearn.model_selection import train_test_split\nX=[[165,19],[175,32],[136,35],[174,65],[141,28],[176,15]\n,[131,32],[166,6],[128,32],[179,10],[136,34],[186,2],[12\n6,25],[176,28],[112,38],[169,9],[171,36],[116,25],[196,2\n5], [196,38], [126,40], [197,20], [150,25], [140,32],[136,35]]\nY=['Man','Woman','Woman','Man','Woman','Man','Woman','Ma\nn','Woman','Man','Woman','Man','Woman','Woman','Woman','\nMan','Woman','Woman','Man', 'Woman', 'Woman', 'Man', 'Man', 'Woman', 'Woman']\ndata_feature_names = ['height','length of hair']\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state = 1)\nDTclf = tree.DecisionTreeClassifier()\nDTclf = clf.fit(X,Y)\nprediction = DTclf.predict([[135,29]])\nprint(prediction)" }, { "code": null, "e": 10602, "s": 10591, "text": "['Woman']\n" }, { "code": null, "e": 10714, "s": 10602, "text": "We can also predict the probability of each class by using following python predict_proba() method as follows −" }, { "code": null, "e": 10777, "s": 10714, "text": "prediction = DTclf.predict_proba([[135,29]])\nprint(prediction)" }, { "code": null, "e": 10788, "s": 10777, "text": "[[0. 1.]]\n" }, { "code": null, "e": 10840, "s": 10788, "text": "In this case the decision variables are continuous." }, { "code": null, "e": 10981, "s": 10840, "text": "Sklearn Module − The Scikit-learn library provides the module name DecisionTreeRegressor for applying decision trees on regression problems." }, { "code": null, "e": 11253, "s": 10981, "text": "Parameters used by DecisionTreeRegressor are almost same as that were used in DecisionTreeClassifier module. The difference lies in ‘criterion’ parameter. For DecisionTreeRegressor modules ‘criterion: string, optional default= “mse”’ parameter have the following values −" }, { "code": null, "e": 11425, "s": 11253, "text": "mse − It stands for the mean squared error. It is equal to variance reduction as feature selectin criterion. It minimises the L2 loss using the mean of each terminal node." }, { "code": null, "e": 11597, "s": 11425, "text": "mse − It stands for the mean squared error. It is equal to variance reduction as feature selectin criterion. It minimises the L2 loss using the mean of each terminal node." }, { "code": null, "e": 11683, "s": 11597, "text": "freidman_mse − It also uses mean squared error but with Friedman’s improvement score." }, { "code": null, "e": 11769, "s": 11683, "text": "freidman_mse − It also uses mean squared error but with Friedman’s improvement score." }, { "code": null, "e": 11879, "s": 11769, "text": "mae − It stands for the mean absolute error. It minimizes the L1 loss using the median of each terminal node." }, { "code": null, "e": 11989, "s": 11879, "text": "mae − It stands for the mean absolute error. It minimizes the L1 loss using the median of each terminal node." }, { "code": null, "e": 12059, "s": 11989, "text": "Another difference is that it does not have ‘class_weight’ parameter." }, { "code": null, "e": 12236, "s": 12059, "text": "Attributes of DecisionTreeRegressor are also same as that were of DecisionTreeClassifier module. The difference is that it does not have ‘classes_’ and ‘n_classes_’ attributes." }, { "code": null, "e": 12427, "s": 12236, "text": "Methods of DecisionTreeRegressor are also same as that were of DecisionTreeClassifier module. The difference is that it does not have ‘predict_log_proba()’ and ‘predict_proba()’’ attributes." }, { "code": null, "e": 12604, "s": 12427, "text": "The fit() method in Decision tree regression model will take floating point values of y. let’s see a simple implementation example by using Sklearn.tree.DecisionTreeRegressor −" }, { "code": null, "e": 12724, "s": 12604, "text": "from sklearn import tree\nX = [[1, 1], [5, 5]]\ny = [0.1, 1.5]\nDTreg = tree.DecisionTreeRegressor()\nDTreg = clf.fit(X, y)" }, { "code": null, "e": 12802, "s": 12724, "text": "Once fitted, we can use this regression model to make prediction as follows −" }, { "code": null, "e": 12827, "s": 12802, "text": "DTreg.predict([[4, 5]])\n" }, { "code": null, "e": 12841, "s": 12827, "text": "array([1.5])\n" }, { "code": null, "e": 12874, "s": 12841, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 12891, "s": 12874, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 12898, "s": 12891, "text": " Print" }, { "code": null, "e": 12909, "s": 12898, "text": " Add Notes" } ]
MongoDB - Environment
Let us now see how to install MongoDB on Windows. To install MongoDB on Windows, first download the latest release of MongoDB from https://www.mongodb.com/download-center. Enter the required details, select the Server tab, in it you can choose the version of MongoDB, operating system and, packaging as: Now install the downloaded file, by default, it will be installed in the folder C:\Program Files\. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute the following command sequence. C:\>md data C:\md data\db Then you need to specify set the dbpath to the created directory in mongod.exe. For the same, issue the following commands. In the command prompt, navigate to the bin directory current in the MongoDB installation folder. Suppose my installation folder is C:\Program Files\MongoDB C:\Users\XYZ>d:cd C:\Program Files\MongoDB\Server\4.2\bin C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data" This will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully. Now to run the MongoDB, you need to open another command prompt and issue the following command. C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe MongoDB shell version v4.2.1 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("4260beda-f662-4cbe-9bc7-5c1f2242663c") } MongoDB server version: 4.2.1 > This will show that MongoDB is installed and run successfully. Next time when you run MongoDB, you need to issue only commands. C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data" C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe Run the following command to import the MongoDB public GPG key − sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 Create a /etc/apt/sources.list.d/mongodb.list file using the following command. echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list Now issue the following command to update the repository − sudo apt-get update Next install the MongoDB by using the following command − apt-get install mongodb-10gen = 4.2 In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install the latest version always. Now MongoDB is installed successfully. sudo service mongodb start sudo service mongodb stop sudo service mongodb restart To use MongoDB run the following command. mongo This will connect you to running MongoDB instance. To get a list of commands, type db.help() in MongoDB client. This will give you a list of commands as shown in the following screenshot. To get stats about MongoDB server, type the command db.stats() in MongoDB client. This will show the database name, number of collection and documents in the database. Output of the command is shown in the following screenshot. 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2603, "s": 2553, "text": "Let us now see how to install MongoDB on Windows." }, { "code": null, "e": 2725, "s": 2603, "text": "To install MongoDB on Windows, first download the latest release of MongoDB from https://www.mongodb.com/download-center." }, { "code": null, "e": 2857, "s": 2725, "text": "Enter the required details, select the Server tab, in it you can choose the version of MongoDB, operating system and, packaging as:" }, { "code": null, "e": 2956, "s": 2857, "text": "Now install the downloaded file, by default, it will be installed in the folder C:\\Program Files\\." }, { "code": null, "e": 3174, "s": 2956, "text": "MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\\data\\db. So you need to create this folder using the Command Prompt. Execute the following command sequence." }, { "code": null, "e": 3201, "s": 3174, "text": "C:\\>md data\nC:\\md data\\db\n" }, { "code": null, "e": 3325, "s": 3201, "text": "Then you need to specify set the dbpath to the created directory in mongod.exe. For the same, issue the following commands." }, { "code": null, "e": 3481, "s": 3325, "text": "In the command prompt, navigate to the bin directory current in the MongoDB installation folder. Suppose my installation folder is C:\\Program Files\\MongoDB" }, { "code": null, "e": 3611, "s": 3481, "text": "C:\\Users\\XYZ>d:cd C:\\Program Files\\MongoDB\\Server\\4.2\\bin\nC:\\Program Files\\MongoDB\\Server\\4.2\\bin>mongod.exe --dbpath \"C:\\data\" \n" }, { "code": null, "e": 3750, "s": 3611, "text": "This will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully." }, { "code": null, "e": 3847, "s": 3750, "text": "Now to run the MongoDB, you need to open another command prompt and issue the following command." }, { "code": null, "e": 4130, "s": 3847, "text": "C:\\Program Files\\MongoDB\\Server\\4.2\\bin>mongo.exe\nMongoDB shell version v4.2.1\nconnecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb\nImplicit session: session { \"id\" : UUID(\"4260beda-f662-4cbe-9bc7-5c1f2242663c\") }\nMongoDB server version: 4.2.1\n>\n" }, { "code": null, "e": 4258, "s": 4130, "text": "This will show that MongoDB is installed and run successfully. Next time when you run MongoDB, you need to issue only commands." }, { "code": null, "e": 4379, "s": 4258, "text": "C:\\Program Files\\MongoDB\\Server\\4.2\\bin>mongod.exe --dbpath \"C:\\data\"\nC:\\Program Files\\MongoDB\\Server\\4.2\\bin>mongo.exe\n" }, { "code": null, "e": 4444, "s": 4379, "text": "Run the following command to import the MongoDB public GPG key −" }, { "code": null, "e": 4520, "s": 4444, "text": "sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10\n" }, { "code": null, "e": 4600, "s": 4520, "text": "Create a /etc/apt/sources.list.d/mongodb.list file using the following command." }, { "code": null, "e": 4731, "s": 4600, "text": "echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' \n | sudo tee /etc/apt/sources.list.d/mongodb.list\n" }, { "code": null, "e": 4790, "s": 4731, "text": "Now issue the following command to update the repository −" }, { "code": null, "e": 4811, "s": 4790, "text": "sudo apt-get update\n" }, { "code": null, "e": 4869, "s": 4811, "text": "Next install the MongoDB by using the following command −" }, { "code": null, "e": 4906, "s": 4869, "text": "apt-get install mongodb-10gen = 4.2\n" }, { "code": null, "e": 5065, "s": 4906, "text": "In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install the latest version always. Now MongoDB is installed successfully." }, { "code": null, "e": 5093, "s": 5065, "text": "sudo service mongodb start\n" }, { "code": null, "e": 5120, "s": 5093, "text": "sudo service mongodb stop\n" }, { "code": null, "e": 5150, "s": 5120, "text": "sudo service mongodb restart\n" }, { "code": null, "e": 5192, "s": 5150, "text": "To use MongoDB run the following command." }, { "code": null, "e": 5199, "s": 5192, "text": "mongo\n" }, { "code": null, "e": 5250, "s": 5199, "text": "This will connect you to running MongoDB instance." }, { "code": null, "e": 5387, "s": 5250, "text": "To get a list of commands, type db.help() in MongoDB client. This will give you a list of commands as shown in the following screenshot." }, { "code": null, "e": 5615, "s": 5387, "text": "To get stats about MongoDB server, type the command db.stats() in MongoDB client. This will show the database name, number of collection and documents in the database. Output of the command is shown in the following screenshot." }, { "code": null, "e": 5648, "s": 5615, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 5667, "s": 5648, "text": " Arnab Chakraborty" }, { "code": null, "e": 5702, "s": 5667, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5730, "s": 5702, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5765, "s": 5730, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5788, "s": 5765, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5823, "s": 5788, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5840, "s": 5823, "text": " University Code" }, { "code": null, "e": 5873, "s": 5840, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 5892, "s": 5873, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 5927, "s": 5892, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5947, "s": 5927, "text": " Skillbakerystudios" }, { "code": null, "e": 5954, "s": 5947, "text": " Print" }, { "code": null, "e": 5965, "s": 5954, "text": " Add Notes" } ]
How to listen for Webview loading a URL using Kotlin?
This example demonstrates how to listen for a webview finishing loading a URL in android. Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:textColor="#000000" android:textSize="24sp" /> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/textView" /> <Button android:id="@+id/btnLoad" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="Load URL" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt package app.com.kotlinapp import android.os.Bundle import android.view.View import android.webkit.WebChromeClient import android.webkit.WebView import android.webkit.WebViewClient import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private var webView: WebView? = null private var textView: TextView? = null private var btnLoad: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.textView); btnLoad = findViewById(R.id.btnLoad); webView = findViewById(R.id.webView); webView!!.webViewClient = WebViewClient() btnLoad!!.setOnClickListener(View.OnClickListener { webView!!.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView, weburl: String) { Toast.makeText(this@MainActivity, "Your WebView is Loaded....", Toast.LENGTH_LONG).show() } } webView!!.webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView, newProgress: Int) { textView!!.text = "Page loading : $newProgress%" if (newProgress == 100) { textView!!.text = "Page Loaded." } } } webView!!.loadUrl("http://www.tutorialspoint.com") }) } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" > <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1152, "s": 1062, "text": "This example demonstrates how to listen for a webview finishing loading a URL in android." }, { "code": null, "e": 1280, "s": 1152, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project." }, { "code": null, "e": 1345, "s": 1280, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2273, "s": 1345, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:padding=\"5dp\"\n android:textColor=\"#000000\"\n android:textSize=\"24sp\" />\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@id/textView\" />\n <Button\n android:id=\"@+id/btnLoad\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:text=\"Load URL\" />\n</RelativeLayout>\n" }, { "code": null, "e": 2328, "s": 2273, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3963, "s": 2328, "text": "package app.com.kotlinapp\nimport android.os.Bundle\nimport android.view.View\nimport android.webkit.WebChromeClient\nimport android.webkit.WebView\nimport android.webkit.WebViewClient\nimport android.widget.Button\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private var webView: WebView? = null\n private var textView: TextView? = null\n private var btnLoad: Button? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n textView = findViewById(R.id.textView);\n btnLoad = findViewById(R.id.btnLoad);\n webView = findViewById(R.id.webView);\n webView!!.webViewClient = WebViewClient()\n btnLoad!!.setOnClickListener(View.OnClickListener {\n webView!!.webViewClient = object : WebViewClient() {\n override fun onPageFinished(view: WebView, weburl: String) {\n Toast.makeText(this@MainActivity, \"Your WebView is Loaded....\",\n Toast.LENGTH_LONG).show()\n }\n }\n webView!!.webChromeClient = object : WebChromeClient() {\n override fun onProgressChanged(view: WebView, newProgress: Int) {\n textView!!.text = \"Page loading : $newProgress%\"\n if (newProgress == 100) {\n textView!!.text = \"Page Loaded.\"\n }\n }\n }\n webView!!.loadUrl(\"http://www.tutorialspoint.com\")\n })\n }\n}" }, { "code": null, "e": 4018, "s": 3963, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4760, "s": 4018, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.myapplication\">\n<uses-permission android:name=\"android.permission.INTERNET\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" >\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5111, "s": 4760, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5152, "s": 5111, "text": "Click here to download the project code." } ]
Retrieve property value selectively from array of objects in JavaScript
Suppose, we have an array of objects like this − const arr = [ { id : "23", name : "Item 1", isActive : true}, { id : "25", name : "Item 2", isActive : false}, { id : "26", name : "Item 3", isActive : false}, { id : "30", name : "Item 4", isActive : true}, { id : "45", name : "Item 5", isActive : true} ]; We are required to write a JavaScript function that takes in one such object and return an array of the value of "id" property of all those objects that have true value for the "isActive" property. The code for this will be − const arr = [ { id : "23", name : "Item 1", isActive : true}, { id : "25", name : "Item 2", isActive : false}, { id : "26", name : "Item 3", isActive : false}, { id : "30", name : "Item 4", isActive : true}, { id : "45", name : "Item 5", isActive : true} ]; const findActive = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const obj = arr[i]; const { id, isActive } = obj; if(isActive){ res.push(id); } }; return res; }; console.log(findActive(arr)); And the output in the console will be − [ '23', '30', '45' ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose, we have an array of objects like this −" }, { "code": null, "e": 1384, "s": 1111, "text": "const arr = [\n { id : \"23\", name : \"Item 1\", isActive : true},\n { id : \"25\", name : \"Item 2\", isActive : false},\n { id : \"26\", name : \"Item 3\", isActive : false},\n { id : \"30\", name : \"Item 4\", isActive : true},\n { id : \"45\", name : \"Item 5\", isActive : true}\n];" }, { "code": null, "e": 1582, "s": 1384, "text": "We are required to write a JavaScript function that takes in one such object and return an array of the value of \"id\" property of all those objects that have true value for the \"isActive\" property." }, { "code": null, "e": 1610, "s": 1582, "text": "The code for this will be −" }, { "code": null, "e": 2168, "s": 1610, "text": "const arr = [\n { id : \"23\", name : \"Item 1\", isActive : true},\n { id : \"25\", name : \"Item 2\", isActive : false},\n { id : \"26\", name : \"Item 3\", isActive : false},\n { id : \"30\", name : \"Item 4\", isActive : true},\n { id : \"45\", name : \"Item 5\", isActive : true}\n];\nconst findActive = (arr = []) => {\n const res = [];\n for(let i = 0; i < arr.length; i++){\n const obj = arr[i];\n const {\n id,\n isActive\n } = obj;\n if(isActive){\n res.push(id);\n }\n };\n return res;\n};\nconsole.log(findActive(arr));" }, { "code": null, "e": 2208, "s": 2168, "text": "And the output in the console will be −" }, { "code": null, "e": 2229, "s": 2208, "text": "[ '23', '30', '45' ]" } ]
Program to perform XOR operation in an array using Python
Suppose we have an integer n and another integer start. We have to create an array called nums where nums[i] = start + 2*i (i start from 0) and n is the size of nums. Then find the bitwise XOR of all elements of nums. So, if the input is like n = 6, start = 2, then the output will be 14 because the array will be like [2+2*0, 2+2*1, ... 2+2*5] = [2,4,6,8,10,12], then XOR of each element present in the array is 14. To solve this, we will follow these steps − count := start count := start while n-1 > 0, docount := count XOR 2 + startn := n - 1start := start + 2 while n-1 > 0, do count := count XOR 2 + start count := count XOR 2 + start n := n - 1 n := n - 1 start := start + 2 start := start + 2 return count return count Let us see the following implementation to get better understanding − Live Demo def solve(n, start): count = start while n-1 > 0: count ^= 2 + start n -= 1 start += 2 return count n = 6 start = 2 print(solve(n, start)) 6, 2 14
[ { "code": null, "e": 1280, "s": 1062, "text": "Suppose we have an integer n and another integer start. We have to create an array called nums where nums[i] = start + 2*i (i start from 0) and n is the size of nums. Then find the bitwise XOR of all elements of nums." }, { "code": null, "e": 1479, "s": 1280, "text": "So, if the input is like n = 6, start = 2, then the output will be 14 because the array will be like [2+2*0, 2+2*1, ... 2+2*5] = [2,4,6,8,10,12], then XOR of each element present in the array is 14." }, { "code": null, "e": 1523, "s": 1479, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1538, "s": 1523, "text": "count := start" }, { "code": null, "e": 1553, "s": 1538, "text": "count := start" }, { "code": null, "e": 1627, "s": 1553, "text": "while n-1 > 0, docount := count XOR 2 + startn := n - 1start := start + 2" }, { "code": null, "e": 1645, "s": 1627, "text": "while n-1 > 0, do" }, { "code": null, "e": 1674, "s": 1645, "text": "count := count XOR 2 + start" }, { "code": null, "e": 1703, "s": 1674, "text": "count := count XOR 2 + start" }, { "code": null, "e": 1714, "s": 1703, "text": "n := n - 1" }, { "code": null, "e": 1725, "s": 1714, "text": "n := n - 1" }, { "code": null, "e": 1744, "s": 1725, "text": "start := start + 2" }, { "code": null, "e": 1763, "s": 1744, "text": "start := start + 2" }, { "code": null, "e": 1776, "s": 1763, "text": "return count" }, { "code": null, "e": 1789, "s": 1776, "text": "return count" }, { "code": null, "e": 1859, "s": 1789, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1870, "s": 1859, "text": " Live Demo" }, { "code": null, "e": 2037, "s": 1870, "text": "def solve(n, start):\n count = start\n while n-1 > 0:\n count ^= 2 + start\n n -= 1\n start += 2\n return count\n\nn = 6\nstart = 2\nprint(solve(n, start))" }, { "code": null, "e": 2042, "s": 2037, "text": "6, 2" }, { "code": null, "e": 2045, "s": 2042, "text": "14" } ]
numpy.ndarray.flat
This function returns a 1-D iterator over the array. It behaves similar to Python's built-in iterator. import numpy as np a = np.arange(8).reshape(2,4) print 'The original array:' print a print '\n' print 'After applying the flat function:' # returns element corresponding to index in flattened array print a.flat[5] Its output is as follows − The original array: [[0 1 2 3] [4 5 6 7]] After applying the flat function: 5 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": 2346, "s": 2243, "text": "This function returns a 1-D iterator over the array. It behaves similar to Python's built-in iterator." }, { "code": null, "e": 2568, "s": 2346, "text": "import numpy as np \na = np.arange(8).reshape(2,4) \nprint 'The original array:' \nprint a \nprint '\\n' \n\nprint 'After applying the flat function:' \n# returns element corresponding to index in flattened array \nprint a.flat[5]" }, { "code": null, "e": 2595, "s": 2568, "text": "Its output is as follows −" }, { "code": null, "e": 2676, "s": 2595, "text": "The original array:\n[[0 1 2 3]\n [4 5 6 7]]\n\nAfter applying the flat function:\n5\n" }, { "code": null, "e": 2709, "s": 2676, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2726, "s": 2709, "text": " Abhilash Nelson" }, { "code": null, "e": 2759, "s": 2726, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 2794, "s": 2759, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2827, "s": 2794, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 2862, "s": 2827, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2897, "s": 2862, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2909, "s": 2897, "text": " Akbar Khan" }, { "code": null, "e": 2942, "s": 2909, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 2957, "s": 2942, "text": " Pruthviraja L" }, { "code": null, "e": 2990, "s": 2957, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2997, "s": 2990, "text": " Anmol" }, { "code": null, "e": 3004, "s": 2997, "text": " Print" }, { "code": null, "e": 3015, "s": 3004, "text": " Add Notes" } ]
How to append elements to a Pandas series?
In this program, we will append elements to a Pandas series. We will use the append() function for this task. Please note that we can only append a series or list/tuple of series to the existing series. Step1: Define a Pandas series, s1. Step 2: Define another series, s2. Step 3: Append s2 to s1. Step 4: Print the final appended series. import pandas as pd s1 = pd.Series([10,20,30,40,50]) s2 = pd.Series([11,22,33,44,55]) print("S1:\n",s1) print("\nS2:\n",s2) appended_series = s1.append(s2) print("\nFinal Series after appending:\n",appended_series) S1: 0 10 1 20 2 30 3 40 4 50 dtype: int64 S2: 0 11 1 22 2 33 3 44 4 55 dtype: int64 Final Series after appending: 0 10 1 20 2 30 3 40 4 50 0 11 1 22 2 33 3 44 4 55 dtype: int64
[ { "code": null, "e": 1265, "s": 1062, "text": "In this program, we will append elements to a Pandas series. We will use the append() function for this task. Please note that we can only append a series or list/tuple of series to the existing series." }, { "code": null, "e": 1401, "s": 1265, "text": "Step1: Define a Pandas series, s1.\nStep 2: Define another series, s2.\nStep 3: Append s2 to s1.\nStep 4: Print the final appended series." }, { "code": null, "e": 1619, "s": 1401, "text": "import pandas as pd\n\ns1 = pd.Series([10,20,30,40,50])\ns2 = pd.Series([11,22,33,44,55])\n\nprint(\"S1:\\n\",s1)\nprint(\"\\nS2:\\n\",s2)\n\nappended_series = s1.append(s2)\nprint(\"\\nFinal Series after appending:\\n\",appended_series)" }, { "code": null, "e": 1858, "s": 1619, "text": "S1:\n0 10\n1 20\n2 30\n3 40\n4 50\ndtype: int64\n\nS2:\n0 11\n1 22\n2 33\n3 44\n4 55\ndtype: int64\n\nFinal Series after appending:\n0 10\n1 20\n2 30\n3 40\n4 50\n0 11\n1 22\n2 33\n3 44\n4 55\ndtype: int64" } ]
fopen() for an existing file in write mode - GeeksforGeeks
28 May, 2017 In C, fopen() is used to open a file in different modes. To open a file in write mode, “w” is specified. When mode “w” is specified, it creates an empty file for output operations. What if the file already exists?If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the following program, if “test.txt” already exists, its contents are removed and “GeeksforGeeks” is written to it. #include <stdio.h>#include <stdlib.h> int main(){ FILE *fp = fopen("test.txt", "w"); if (fp == NULL) { puts("Couldn't open file"); exit(0); } else { fputs("GeeksforGeeks", fp); puts("Done"); fclose(fp); } return 0;} The above behavior may lead to unexpected results. If programmer’s intention was to create a new file and a file with same name already exists, the existing file’s contents are overwritten. The latest C standard C11 provides a new mode “x” which is exclusive create-and-open mode. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”. When x is used with w, fopen() returns NULL if file already exists or could not open. Following is modified C11 program that doesn’t overwrite an existing file. #include <stdio.h>#include <stdlib.h> int main(){ FILE *fp = fopen("test.txt", "wx"); if (fp == NULL) { puts("Couldn't open file or file already exists"); exit(0); } else { fputs("GeeksforGeeks", fp); puts("Done"); fclose(fp); } return 0;} References:Do not make assumptions about fopen() and file creationhttp://en.wikipedia.org/wiki/C11_(C_standard_revision)http://www.cplusplus.com/reference/cstdio/freopen/ This article is compiled by Abhay Rathi. 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. fork() in C Command line arguments in C/C++ Function Pointer in C Substring in C++ Different methods to reverse a string in C/C++ Structures in C TCP Server-Client implementation in C Enumeration (or enum) in C std::string class in C++ Data Types in C
[ { "code": null, "e": 24514, "s": 24486, "text": "\n28 May, 2017" }, { "code": null, "e": 24695, "s": 24514, "text": "In C, fopen() is used to open a file in different modes. To open a file in write mode, “w” is specified. When mode “w” is specified, it creates an empty file for output operations." }, { "code": null, "e": 24976, "s": 24695, "text": "What if the file already exists?If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the following program, if “test.txt” already exists, its contents are removed and “GeeksforGeeks” is written to it." }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ FILE *fp = fopen(\"test.txt\", \"w\"); if (fp == NULL) { puts(\"Couldn't open file\"); exit(0); } else { fputs(\"GeeksforGeeks\", fp); puts(\"Done\"); fclose(fp); } return 0;}", "e": 25252, "s": 24976, "text": null }, { "code": null, "e": 25442, "s": 25252, "text": "The above behavior may lead to unexpected results. If programmer’s intention was to create a new file and a file with same name already exists, the existing file’s contents are overwritten." }, { "code": null, "e": 25757, "s": 25442, "text": "The latest C standard C11 provides a new mode “x” which is exclusive create-and-open mode. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”. When x is used with w, fopen() returns NULL if file already exists or could not open. Following is modified C11 program that doesn’t overwrite an existing file." }, { "code": "#include <stdio.h>#include <stdlib.h> int main(){ FILE *fp = fopen(\"test.txt\", \"wx\"); if (fp == NULL) { puts(\"Couldn't open file or file already exists\"); exit(0); } else { fputs(\"GeeksforGeeks\", fp); puts(\"Done\"); fclose(fp); } return 0;}", "e": 26057, "s": 25757, "text": null }, { "code": null, "e": 26228, "s": 26057, "text": "References:Do not make assumptions about fopen() and file creationhttp://en.wikipedia.org/wiki/C11_(C_standard_revision)http://www.cplusplus.com/reference/cstdio/freopen/" }, { "code": null, "e": 26393, "s": 26228, "text": "This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26409, "s": 26393, "text": "C-File Handling" }, { "code": null, "e": 26427, "s": 26409, "text": "cpp-file-handling" }, { "code": null, "e": 26438, "s": 26427, "text": "C Language" }, { "code": null, "e": 26536, "s": 26438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26548, "s": 26536, "text": "fork() in C" }, { "code": null, "e": 26580, "s": 26548, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26602, "s": 26580, "text": "Function Pointer in C" }, { "code": null, "e": 26619, "s": 26602, "text": "Substring in C++" }, { "code": null, "e": 26666, "s": 26619, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 26682, "s": 26666, "text": "Structures in C" }, { "code": null, "e": 26720, "s": 26682, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26747, "s": 26720, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 26772, "s": 26747, "text": "std::string class in C++" } ]
Batch Script - COPY
This batch command is used for copying files from one location to the other. Copy [source] [destination] The files will be copied from source to destination location. The following example shows the different variants of the copy command. @echo off cd Rem Copies lists.txt to the present working directory. If there is no destination identified , it defaults to the present working directory. copy c:\lists.txt Rem The file lists.txt will be copied from C:\ to C:\tp location copy C:\lists.txt c:\tp Rem Quotation marks are required if the file name contains spaces copy “C:\My File.txt” Rem Copies all the files in F drive which have the txt file extension to the current working directory copy F:\*.txt Rem Copies all files from dirA to dirB. Note that directories nested in dirA will not be copied copy C:\dirA dirB All actions are performed as per the remarks in the batch file. Print Add Notes Bookmark this page
[ { "code": null, "e": 2246, "s": 2169, "text": "This batch command is used for copying files from one location to the other." }, { "code": null, "e": 2275, "s": 2246, "text": "Copy [source] [destination]\n" }, { "code": null, "e": 2337, "s": 2275, "text": "The files will be copied from source to destination location." }, { "code": null, "e": 2409, "s": 2337, "text": "The following example shows the different variants of the copy command." }, { "code": null, "e": 2989, "s": 2409, "text": "@echo off\ncd\nRem Copies lists.txt to the present working directory.\nIf there is no destination identified , it defaults to the present working directory.\ncopy c:\\lists.txt\nRem The file lists.txt will be copied from C:\\ to C:\\tp location\ncopy C:\\lists.txt c:\\tp\nRem Quotation marks are required if the file name contains spaces\ncopy “C:\\My File.txt”\nRem Copies all the files in F drive which have the txt file extension to the\ncurrent working directory copy\nF:\\*.txt\nRem Copies all files from dirA to dirB. Note that directories nested in dirA will not be copied\ncopy C:\\dirA dirB" }, { "code": null, "e": 3053, "s": 2989, "text": "All actions are performed as per the remarks in the batch file." }, { "code": null, "e": 3060, "s": 3053, "text": " Print" }, { "code": null, "e": 3071, "s": 3060, "text": " Add Notes" } ]
xargs - Unix, Linux Command
Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the ‘-0’ option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the ‘-print0’ option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. find /tmp -name core -type f -print | xargs /bin/rm -f find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. cut -d: -f1 < /etc/passwd | sort | xargs echo 0 if it succeeds 123 if any invocation of the command exited with status 1-125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn’t intend. For a more detailed discussion of this and related problems, please refer to the ‘‘Security Considerations’’ chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I ’{}’ -s 100000 rm ’{}’ Here, the first invocation of xargs has no input line length limit because it doesn’t use the -i option. The second invocation of xargs does have such a limit, but we have ensured that the it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn’t occur with the output of find(1) because it emits just one filename per line. The best way to report a bug is to use the form at http://savannah.gnu.org/bugs/?group=findutils. The reason for this is that you will then be able to track progress in fixing the problem. Other comments about xargs(1) and about the findutils package in general can be sent to the bug-findutils mailing list. To join the list, send email to bug-findutils-request@gnu.org. 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": 11073, "s": 10577, "text": "\nBecause Unix filenames can contain blanks and newlines, this default\nbehaviour is often problematic; filenames containing blanks\nand/or newlines are incorrectly processed by\nxargs. In these situations it is better to use the ‘-0’ option, which\nprevents such problems. When using this option you will need to\nensure that the program which produces the input for\nxargs also uses a null character as a separator. If that program is\nGNU\nfind for example, the ‘-print0’ option does this for you.\n" }, { "code": null, "e": 11256, "s": 11073, "text": "\nIf any invocation of the command exits with a status of 255,\nxargs will stop immediately without reading any further input. An error\nmessage is issued on stderr when this happens.\n" }, { "code": null, "e": 11318, "s": 11260, "text": "find /tmp -name core -type f -print | xargs /bin/rm -f \n\n" }, { "code": null, "e": 11381, "s": 11320, "text": "\nfind /tmp -name core -type f -print0 | xargs -0 /bin/rm -f " }, { "code": null, "e": 11570, "s": 11381, "text": "\nFind files named\ncore in or below the directory\n/tmp and delete them, processing filenames in such a way that file or\ndirectory names containing spaces or newlines are correctly handled.\n" }, { "code": null, "e": 11621, "s": 11572, "text": "cut -d: -f1 < /etc/passwd | sort | xargs echo \n\n" }, { "code": null, "e": 11883, "s": 11623, "text": "0 if it succeeds\n123 if any invocation of the command exited with status 1-125\n124 if the command exited with status 255\n125 if the command is killed by a signal\n126 if the command cannot be run\n127 if the command is not found\n1 if some other error occurred.\n" }, { "code": null, "e": 11990, "s": 11883, "text": "\nExit codes greater than 128 are used by the shell to indicate that\na program died due to a fatal signal.\n" }, { "code": null, "e": 12177, "s": 11990, "text": "\nThe -l and -i options appear in the 1997 version of the POSIX\nstandard, but do not appear in the 2004 version of the standard.\nTherefore you should use -L and -I instead, respectively.\n" }, { "code": null, "e": 12794, "s": 12179, "text": "\nIt is not possible for\nxargs to be used securely, since there will always be a time gap between the\nproduction of the list of input files and their use in the commands\nthat\nxargs issues. If other users have access to the system, they can manipulate\nthe filesystem during this time window to force the action of the\ncommands\nxargs runs to apply to files that you didn’t intend. For a more detailed\ndiscussion of this and related problems, please refer to the\n‘‘Security Considerations’’ chapter in the findutils Texinfo\ndocumentation. The -execdir option of\nfind can often be used as a more secure alternative.\n" }, { "code": null, "e": 13225, "s": 12794, "text": "\nWhen you use the -I option, each line read from the input is buffered\ninternally. This means that there is an upper limit on the length\nof input line that\nxargs will accept when used with the -I option. To work around this\nlimitation, you can use the -s option to increase the amount of\nbuffer space that\nxargs uses, and you can also use an extra invocation of\nxargs to ensure that very long lines do not occur. \nFor example:\n" }, { "code": null, "e": 13295, "s": 13225, "text": "\nsomecommand | xargs -s 50000 echo | xargs -I ’{}’ -s 100000 rm ’{}’ " }, { "code": null, "e": 13802, "s": 13295, "text": "\nHere, the first invocation of\nxargs has no input line length limit\nbecause it doesn’t use the -i option. The second invocation of\nxargs does have such a limit, but we have ensured that the it never encounters\na line which is longer than it can handle. This is not an ideal\nsolution. Instead, the -i option should not impose a line length\nlimit, which is why this discussion appears in the BUGS section.\nThe problem doesn’t occur with the output of\nfind(1)\nbecause it emits just one filename per line.\n" }, { "code": null, "e": 14189, "s": 13802, "text": "\nThe best way to report a bug is to use the form at\nhttp://savannah.gnu.org/bugs/?group=findutils. \nThe reason for this is that you will then be able to track progress in\nfixing the problem. Other comments about xargs(1) and about\nthe findutils package in general can be sent to the\nbug-findutils mailing list. To join the list, send email to\nbug-findutils-request@gnu.org. \n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 14206, "s": 14189, "text": "\nAdvertisements\n" }, { "code": null, "e": 14241, "s": 14206, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14269, "s": 14241, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14303, "s": 14269, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14320, "s": 14303, "text": " Frahaan Hussain" }, { "code": null, "e": 14353, "s": 14320, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14364, "s": 14353, "text": " Pradeep D" }, { "code": null, "e": 14399, "s": 14364, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14415, "s": 14399, "text": " Musab Zayadneh" }, { "code": null, "e": 14448, "s": 14415, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14460, "s": 14448, "text": " GUHARAJANM" }, { "code": null, "e": 14492, "s": 14460, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14500, "s": 14492, "text": " Uplatz" }, { "code": null, "e": 14507, "s": 14500, "text": " Print" }, { "code": null, "e": 14518, "s": 14507, "text": " Add Notes" } ]
Python PIL | MedianFilter() and ModeFilter() method - GeeksforGeeks
29 Jun, 2019 PIL.ImageFilter.MedianFilter() method creates a median filter. Picks the median pixel value in a window with the given size. Syntax: PIL.ImageFilter.MedianFilter(size=3) Parameters: size: The kernel size, in pixels. Image used: # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the median filter im2 = im1.filter(ImageFilter.MedianFilter(size = 3)) im2.show() Output: PIL.ImageFilter.ModeFilter() method creates a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved. Syntax: PIL.ImageFilter.ModeFilter(size=3) Parameters: size: The kernel size, in pixels. # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG") # applying the mode filter im2 = im1.filter(ImageFilter.ModeFilter(size = 3)) im2.show() Output: Image-Processing Python-pil python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python Deque in Python How to Install PIP on Windows ? Python String | replace()
[ { "code": null, "e": 24425, "s": 24397, "text": "\n29 Jun, 2019" }, { "code": null, "e": 24550, "s": 24425, "text": "PIL.ImageFilter.MedianFilter() method creates a median filter. Picks the median pixel value in a window with the given size." }, { "code": null, "e": 24643, "s": 24550, "text": "Syntax: PIL.ImageFilter.MedianFilter(size=3)\n\nParameters:\nsize: The kernel size, in pixels.\n" }, { "code": null, "e": 24655, "s": 24643, "text": "Image used:" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the median filter im2 = im1.filter(ImageFilter.MedianFilter(size = 3)) im2.show() ", "e": 24945, "s": 24655, "text": null }, { "code": null, "e": 24953, "s": 24945, "text": "Output:" }, { "code": null, "e": 25215, "s": 24953, "text": "PIL.ImageFilter.ModeFilter() method creates a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved." }, { "code": null, "e": 25306, "s": 25215, "text": "Syntax: PIL.ImageFilter.ModeFilter(size=3)\n\nParameters:\nsize: The kernel size, in pixels.\n" }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\download2.JPG\") # applying the mode filter im2 = im1.filter(ImageFilter.ModeFilter(size = 3)) im2.show() ", "e": 25592, "s": 25306, "text": null }, { "code": null, "e": 25600, "s": 25592, "text": "Output:" }, { "code": null, "e": 25617, "s": 25600, "text": "Image-Processing" }, { "code": null, "e": 25628, "s": 25617, "text": "Python-pil" }, { "code": null, "e": 25643, "s": 25628, "text": "python-utility" }, { "code": null, "e": 25650, "s": 25643, "text": "Python" }, { "code": null, "e": 25748, "s": 25650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25757, "s": 25748, "text": "Comments" }, { "code": null, "e": 25770, "s": 25757, "text": "Old Comments" }, { "code": null, "e": 25788, "s": 25770, "text": "Python Dictionary" }, { "code": null, "e": 25810, "s": 25788, "text": "Enumerate() in Python" }, { "code": null, "e": 25845, "s": 25810, "text": "Read a file line by line in Python" }, { "code": null, "e": 25867, "s": 25845, "text": "Defaultdict in Python" }, { "code": null, "e": 25909, "s": 25867, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25934, "s": 25909, "text": "sum() function in Python" }, { "code": null, "e": 25964, "s": 25934, "text": "Iterate over a list in Python" }, { "code": null, "e": 25980, "s": 25964, "text": "Deque in Python" }, { "code": null, "e": 26012, "s": 25980, "text": "How to Install PIP on Windows ?" } ]
Retrieve a set of Map.Entry elements from a HashMap in Java
Create a HashMap and add elements to it − HashMap hm = new HashMap(); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); hm.put("Backpack", new Integer(1200)); The following is the code snippet to retrieve a set of Map.Entry elements − Set s = hm.entrySet(); Iterator iter = s.iterator(); System.out.println("\nKey\tValue"); while (iter.hasNext()) { Map.Entry e = (Map.Entry) iter.next(); System.out.println(e.getKey() + " " + e.getValue()); } The following is an example to retrieve a set of Map.Entry elements from a HashMap − Live Demo import java.util.*; public class Demo { public static void main(String args[]) { // Create hash map HashMap hm = new HashMap(); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); hm.put("Backpack", new Integer(1200)); System.out.println("Map = "+hm); Set s = hm.entrySet(); Iterator iter = s.iterator(); System.out.println("\nKey\tValue"); while (iter.hasNext()) { Map.Entry e = (Map.Entry) iter.next(); System.out.println(e.getKey() + " " + e.getValue()); } } } Map = {Backpack=1200, Belt=600, Wallet=700} KeyValue Backpack 1200 Belt 600 Wallet 700
[ { "code": null, "e": 1104, "s": 1062, "text": "Create a HashMap and add elements to it −" }, { "code": null, "e": 1241, "s": 1104, "text": "HashMap hm = new HashMap();\nhm.put(\"Wallet\", new Integer(700));\nhm.put(\"Belt\", new Integer(600));\nhm.put(\"Backpack\", new Integer(1200));" }, { "code": null, "e": 1317, "s": 1241, "text": "The following is the code snippet to retrieve a set of Map.Entry elements −" }, { "code": null, "e": 1531, "s": 1317, "text": "Set s = hm.entrySet();\nIterator iter = s.iterator();\nSystem.out.println(\"\\nKey\\tValue\");\nwhile (iter.hasNext()) {\n Map.Entry e = (Map.Entry) iter.next();\n System.out.println(e.getKey() + \" \" + e.getValue());\n}" }, { "code": null, "e": 1616, "s": 1531, "text": "The following is an example to retrieve a set of Map.Entry elements from a HashMap −" }, { "code": null, "e": 1627, "s": 1616, "text": " Live Demo" }, { "code": null, "e": 2199, "s": 1627, "text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create hash map\n HashMap hm = new HashMap();\n hm.put(\"Wallet\", new Integer(700));\n hm.put(\"Belt\", new Integer(600));\n hm.put(\"Backpack\", new Integer(1200));\n System.out.println(\"Map = \"+hm);\n Set s = hm.entrySet();\n Iterator iter = s.iterator();\n System.out.println(\"\\nKey\\tValue\");\n while (iter.hasNext()) {\n Map.Entry e = (Map.Entry) iter.next();\n System.out.println(e.getKey() + \" \" + e.getValue());\n }\n }\n}" }, { "code": null, "e": 2287, "s": 2199, "text": "Map = {Backpack=1200, Belt=600, Wallet=700}\n\nKeyValue\nBackpack 1200\nBelt 600\nWallet 700" } ]
How to change the color of links in HTML?
To change the color of links in HTML, use the CSS property color. Use it with the style attribute. The style attribute specifies an inline style for an element. Use the style attribute with the CSS property color to change the link color. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code change the color of links in HTML Live Demo <!DOCTYPE html> <html> <head> <title>HTML Link Color</title> </head> <body> <h2>About</h2> <p> Our <a href="/about/about_team.htm" style="color: red">Team</a> comprises of programmers, writers, and analysts. </p> </body> </html>
[ { "code": null, "e": 1223, "s": 1062, "text": "To change the color of links in HTML, use the CSS property color. Use it with the style attribute. The style attribute specifies an inline style for an element." }, { "code": null, "e": 1463, "s": 1223, "text": "Use the style attribute with the CSS property color to change the link color. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1535, "s": 1463, "text": "You can try to run the following code change the color of links in HTML" }, { "code": null, "e": 1545, "s": 1535, "text": "Live Demo" }, { "code": null, "e": 1831, "s": 1545, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Link Color</title>\n </head>\n <body>\n <h2>About</h2>\n <p>\n Our <a href=\"/about/about_team.htm\" style=\"color: red\">Team</a>\n comprises of programmers, writers, and analysts.\n </p>\n </body>\n</html>" } ]
find_by_order() in C++ - GeeksforGeeks
06 Apr, 2021 The find_by_order() is a built-in function of Ordered Set which is a Policy Based Data Structure in C++. Policy-based data structures are not part of the C++ Standard Template Library but the g++ compiler supports them. Ordered Set is a policy-based data structure in g++ that maintains unique elements in sorted order. It performs all the operations as performed by Set in STL in O(logN) complexity. In addition to that, the following two operations are also performed in O(logN) complexity: order_of_key (K): Number of items strictly smaller than K. find_by_order(k): Kth element in a Set (counting from zero). The find_by_order() function accepts a key, say K, as an argument and returns the iterator to the Kth largest element in the Set. Examples: Considering a Set S = {1, 5, 6, 17, 88}, s.find_by_order(0): Returns the 0th largest element, i.e. the minimum element, i.e. 1.s.find_by_order(2): Returns the 2nd largest element, i.e. 6. Note: If K >= N, where N is the size of the set, then the function returns either 0 or in some compilers, the iterator to the smallest element. Below is the implementation of find_by_order() function in C++: C++14 // C++ program to implement find_by_order()// for Policy Based Data Structures #include <bits/stdc++.h> // Importing header files#include <ext/pb_ds/assoc_container.hpp>using namespace std;using namespace __gnu_pbds; // Declaring Ordered Settypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // Driver Codeint main(){ int arr[] = {1, 5, 6, 17, 88}; int n = sizeof(arr)/sizeof(arr[0]); pbds S; // Traverse the array for (int i = 0; i < n; i++) { // Insert array elements // into the ordered set S.insert(arr[i]); } // Returns iterator to 0-th // largest element in the set cout << *S.find_by_order(0) << " "; // Returns iterator to 2-nd // largest element in the set cout << *S.find_by_order(2); return 0;} 1 6 cpp-advanced cpp-set Advanced Data Structure Competitive Programming Hash Sorting Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extendible Hashing (Dynamic approach to DBMS) Ternary Search Tree Proof that Dominant Set of a Graph is NP-Complete 2-3 Trees | (Search, Insert and Deletion) Advantages of Trie Data Structure Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Competitive Programming - A Complete Guide Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24071, "s": 24043, "text": "\n06 Apr, 2021" }, { "code": null, "e": 24291, "s": 24071, "text": "The find_by_order() is a built-in function of Ordered Set which is a Policy Based Data Structure in C++. Policy-based data structures are not part of the C++ Standard Template Library but the g++ compiler supports them." }, { "code": null, "e": 24564, "s": 24291, "text": "Ordered Set is a policy-based data structure in g++ that maintains unique elements in sorted order. It performs all the operations as performed by Set in STL in O(logN) complexity. In addition to that, the following two operations are also performed in O(logN) complexity:" }, { "code": null, "e": 24623, "s": 24564, "text": "order_of_key (K): Number of items strictly smaller than K." }, { "code": null, "e": 24684, "s": 24623, "text": "find_by_order(k): Kth element in a Set (counting from zero)." }, { "code": null, "e": 24814, "s": 24684, "text": "The find_by_order() function accepts a key, say K, as an argument and returns the iterator to the Kth largest element in the Set." }, { "code": null, "e": 24824, "s": 24814, "text": "Examples:" }, { "code": null, "e": 25012, "s": 24824, "text": "Considering a Set S = {1, 5, 6, 17, 88}, s.find_by_order(0): Returns the 0th largest element, i.e. the minimum element, i.e. 1.s.find_by_order(2): Returns the 2nd largest element, i.e. 6." }, { "code": null, "e": 25157, "s": 25012, "text": "Note: If K >= N, where N is the size of the set, then the function returns either 0 or in some compilers, the iterator to the smallest element. " }, { "code": null, "e": 25221, "s": 25157, "text": "Below is the implementation of find_by_order() function in C++:" }, { "code": null, "e": 25227, "s": 25221, "text": "C++14" }, { "code": "// C++ program to implement find_by_order()// for Policy Based Data Structures #include <bits/stdc++.h> // Importing header files#include <ext/pb_ds/assoc_container.hpp>using namespace std;using namespace __gnu_pbds; // Declaring Ordered Settypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; // Driver Codeint main(){ int arr[] = {1, 5, 6, 17, 88}; int n = sizeof(arr)/sizeof(arr[0]); pbds S; // Traverse the array for (int i = 0; i < n; i++) { // Insert array elements // into the ordered set S.insert(arr[i]); } // Returns iterator to 0-th // largest element in the set cout << *S.find_by_order(0) << \" \"; // Returns iterator to 2-nd // largest element in the set cout << *S.find_by_order(2); return 0;}", "e": 26095, "s": 25227, "text": null }, { "code": null, "e": 26100, "s": 26095, "text": "1 6\n" }, { "code": null, "e": 26113, "s": 26100, "text": "cpp-advanced" }, { "code": null, "e": 26121, "s": 26113, "text": "cpp-set" }, { "code": null, "e": 26145, "s": 26121, "text": "Advanced Data Structure" }, { "code": null, "e": 26169, "s": 26145, "text": "Competitive Programming" }, { "code": null, "e": 26174, "s": 26169, "text": "Hash" }, { "code": null, "e": 26182, "s": 26174, "text": "Sorting" }, { "code": null, "e": 26187, "s": 26182, "text": "Hash" }, { "code": null, "e": 26195, "s": 26187, "text": "Sorting" }, { "code": null, "e": 26293, "s": 26195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26302, "s": 26293, "text": "Comments" }, { "code": null, "e": 26315, "s": 26302, "text": "Old Comments" }, { "code": null, "e": 26361, "s": 26315, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 26381, "s": 26361, "text": "Ternary Search Tree" }, { "code": null, "e": 26431, "s": 26381, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 26473, "s": 26431, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 26507, "s": 26473, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 26550, "s": 26507, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 26591, "s": 26550, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26618, "s": 26591, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 26661, "s": 26618, "text": "Competitive Programming - A Complete Guide" } ]
TabNet - GeeksforGeeks
16 Oct, 2021 TabNet was proposed by the researchers at Google Cloud in the year 2019. The idea behind TabNet is to effectively apply deep neural networks on tabular data which still consists of a large portion of users and processed data across various applications such as healthcare, banking, retail, finance, marketing, etc. One motivation to apply deep learning to the tabular dataset comes from other domains such as (image, language, speech) data when applied on it demonstrated a significant performance improvement on the large datasets as compared to other machine learning techniques. So, we can expect it to work on tabular data. Another reason can be those tree-based algorithms unlike the deep neural network do not efficiently learn to reduce the error by using techniques like Gradient Descent. TabNet provides a high-performance and interpretable tabular data deep learning architecture. It uses a method called sequential attention mechanism to enabling which feature to choose to cause high interpretability and efficient training. TabNet Encoder Architecture The TabNet architecture basically consists of multi-steps which are sequential, passing the input from one step to another. There are different ways to decide the number of steps depending upon the capacity. Each step consists of the following steps: In the initial step, the complete dataset is input into the model without any feature engineering. It is then passed through a batch normalization layer, and after that, it is then passed in a feature transformer. Feature Transformer: It consists of n-number (eg. 4) of different GLU blocks. Each GLU bloc consists of the following layers: GLU block = Fully-Connected - Batch Normalization - GLU (Gated Linear Unit) where , GLU(x) = For 4 layers of GLU blocks, the 2 GLU blocks should be shared and 2 should be independent, which helps in robust and efficient learning. There is a skip connection also existed b/w two consecutive blocks. After each block, we perform the normalization with in order to get the stability and ensuring that the variance doesn’t vary considerably. The feature transformer outputs the two outputs: It is the output decision from the particular step giving its prediction of continuous values/ classes. The output for the next attentive transformer where the next cycle begins. It is the output decision from the particular step giving its prediction of continuous values/ classes. The output for the next attentive transformer where the next cycle begins. Feature Transformer Attentive Transformer: An attentive transformer consists of a fully connected (FC) layer, a BatchNorm layer, and Prior scales layer, and a Sparsemax layer. It receives input \mathbb{n_a} and after passing through the fully connected layer and Batch normalization layer, then it passes through the prior scales layer.This prior scale layer aggregates how much each feature has been used before the current decision step. This prior scale layer aggregates how much each feature has been used before the current decision step. ; all features are equal. P_i = \prod_{j=1}^{i} (\gamma – M ) ; the smaller the value of \gamma the more independent step, looking at different features. Sparsemax layer: It is used for normalization of the coefficient (similar to softmax), resulting in sparse selection of features: If a lot of the features will be zeros, then we will apply instance-wise feature selection, where only a subset of different features is used for different steps. Attentive transformer Attention Mask: The output from the attentive transformer step, are then fed into the a attention mask, which it helps in identify the selected features. It quantifies aggregate feature importance in addition to analysis of each step. Combining the masks at different steps requires a coefficient that can weigh the relative importance of each step in the decision. Therefore, the author proposes: denote the aggregate decision contribution at ith decision step for the bth sample. Scaling the decision mask at each decision step with , the author propose the aggregate feature important mask: TabNet Decoder The TabNet decoder architecture consists of a feature transformer, followed by the fully connected layers at the decision step. The output is then summed to the reconstructed features. The reconstruction loss function in self-supervised phase: We will be using the Pytorch implementation of the TabNet in this implementation. For datasets, we will be using the Loan Approval prediction, whether a person will get a loan or not which it applied for: Python3 # Install TabNetpip install pytorch-tabnet # imports necessary modulesfrom pytorch_tabnet.tab_model import TabNetClassifier import osimport torchimport pandas as pdimport numpy as np from sklearn.model_selection import KFoldfrom sklearn.preprocessing import LabelEncoder, MinMaxScalarfrom sklearn.metrics import accuracy_score # Load training and test datadata =pd.read_csv('/content/train.csv')data.head()data.isna().sum()# load test datatest_data = pd.read_csv('/content/test.csv')test_data.head()test_data.isna().sum() # set index columndata.set_index('Loan_ID', inplace=True)test_data.set_index('Loan_ID', inplace=True) # Replace NAsdata.fillna(method="bfill", inplace=True)test_data.fillna(method="bfill", inplace=True) # convert categorical column to integer Labels gen = LabelEncoder().fit(data['Gender'])data['Gender'] = gen.transform(data['Gender']) s_type= LabelEncoder().fit(data['Married'])data['Married'] = s_type.transform(data['Married']) n_dep= LabelEncoder().fit(data['Dependents'])data['Dependents'] = n_dep.transform(data['Dependents']) edu= LabelEncoder().fit(data['Education'])data['Education'] = edu.transform(data['Education']) s_emp = LabelEncoder().fit(data['Self_Employed'])data['Self_Employed'] = s_emp.transform(data['Self_Employed']) c_history = LabelEncoder().fit(data['Credit_History'])data['Credit_History'] = c_history.transform(data['Credit_History']) p_area = LabelEncoder().fit(data['Property_Area'])data['Property_Area'] = p_area.transform(data['Property_Area']) l_status = LabelEncoder().fit(data['Loan_Status'])data['Loan_Status'] = l_status.transform(data['Loan_Status']) # For test datatest_data['Gender'] = gen.transform(test_data['Gender'])test_data['Married'] = s_type.transform(test_data['Married'])test_data['Dependents'] = n_dep.transform(test_data['Dependents'])test_data['Education'] = edu.transform(test_data['Education'])test_data['Self_Employed'] = s_emp.transform(test_data['Self_Employed'])test_data['Credit_History'] = c_history.transform(test_data['Credit_History'])test_data['Property_Area'] = p_area.transform(test_data['Property_Area']) # select feature and target variableX = data.loc[:,data.columns != 'Loan_Status']y = data.loc[:,data.columns == 'Loan_Status']X.shape, y.shape # convert to numpyX= X.to_numpy()y= y.to_numpy() y= y.flatten() # define and train the Tabnet model with cross validationkf = KFold(n_splits=5, random_state=42, shuffle=True)CV_score_array =[]for train_index, test_index in kf.split(X): X_train, X_valid = X[train_index], X[test_index] y_train, y_valid = y[train_index], y[test_index] tb_cls = TabNetClassifier(optimizer_fn=torch.optim.Adam, optimizer_params=dict(lr=1e-3), scheduler_params={"step_size":10, "gamma":0.9}, scheduler_fn=torch.optim.lr_scheduler.StepLR, mask_type='entmax' # "sparsemax" ) tb_cls.fit(X_train,y_train, eval_set=[(X_train, y_train), (X_val, y_val)], eval_name=['train', 'valid'], eval_metric=['accuracy'], max_epochs=1000 , patience=100, batch_size=28, drop_last=False) CV_score_array.append(tb_cls.best_cost) # Test model and generate predictionpredictions =[ 'N' if i < 0.5 else 'Y' for i in tb_cls.predict(X_test)] Collecting pytorch-tabnet Downloading pytorch_tabnet-3.1.1-py3-none-any.whl (39 kB) Requirement already satisfied: numpy<2.0,>=1.17 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (1.19.5) Requirement already satisfied: scikit_learn>0.21 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (0.22.2.post1) Requirement already satisfied: torch<2.0,>=1.2 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (1.9.0+cu102) Requirement already satisfied: scipy>1.4 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (1.4.1) Requirement already satisfied: tqdm<5.0,>=4.36 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (4.62.2) Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit_learn>0.21->pytorch-tabnet) (1.0.1) Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch<2.0,>=1.2->pytorch-tabnet) (3.7.4.3) Installing collected packages: pytorch-tabnet Successfully installed pytorch-tabnet-3.1.1 # train data Loan_ID Gender Married Dependents Education Self_Employed ApplicantIncome CoapplicantIncome LoanAmount Loan_Amount_Term Credit_History Property_Area Loan_Status 0 LP001002 Male No 0 Graduate No 5849 0.0 NaN 360.0 1.0 Urban Y 1 LP001003 Male Yes 1 Graduate No 4583 1508.0 128.0 360.0 1.0 Rural N 2 LP001005 Male Yes 0 Graduate Yes 3000 0.0 66.0 360.0 1.0 Urban Y 3 LP001006 Male Yes 0 Not Graduate No 2583 2358.0 120.0 360.0 1.0 Urban Y 4 LP001008 Male No 0 Graduate No 6000 0.0 141.0 360.0 1.0 Urban Y # null values Loan_ID 0 Gender 13 Married 3 Dependents 15 Education 0 Self_Employed 32 ApplicantIncome 0 CoapplicantIncome 0 LoanAmount 22 Loan_Amount_Term 14 Credit_History 50 Property_Area 0 Loan_Status 0 dtype: int64 # test data Loan_ID Gender Married Dependents Education Self_Employed ApplicantIncome CoapplicantIncome LoanAmount Loan_Amount_Term Credit_History Property_Area 0 LP001015 Male Yes 0 Graduate No 5720 0 110.0 360.0 1.0 Urban 1 LP001022 Male Yes 1 Graduate No 3076 1500 126.0 360.0 1.0 Urban 2 LP001031 Male Yes 2 Graduate No 5000 1800 208.0 360.0 1.0 Urban 3 LP001035 Male Yes 2 Graduate No 2340 2546 100.0 360.0 NaN Urban 4 LP001051 Male No 0 Not Graduate No 3276 0 78.0 360.0 1.0 Urban # Null values Loan_ID 0 Gender 11 Married 0 Dependents 10 Education 0 Self_Employed 23 ApplicantIncome 0 CoapplicantIncome 0 LoanAmount 5 Loan_Amount_Term 6 Credit_History 29 Property_Area 0 dtype: int64 # x, y shape ((614, 11), (614, 1)) Device used : cpu Early stopping occurred at epoch 137 with best_epoch = 37 and best_valid_accuracy = 0.84416 Best weights from best epoch are automatically used! Device used : cpu Early stopping occurred at epoch 292 with best_epoch = 192 and best_valid_accuracy = 0.86364 Best weights from best epoch are automatically used! Device used : cpu Early stopping occurred at epoch 324 with best_epoch = 224 and best_valid_accuracy = 0.85065 Best weights from best epoch are automatically used! Device used : cpu Early stopping occurred at epoch 143 with best_epoch = 43 and best_valid_accuracy = 0.84416 Best weights from best epoch are automatically used! Device used : cpu Early stopping occurred at epoch 253 with best_epoch = 153 and best_valid_accuracy = 0.84416 Best weights from best epoch are automatically used! TabNet paper Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python Principal Component Analysis with Python Python | Decision Tree Regression using sklearn Python | Stemming words with NLTK Normalization vs Standardization Intuition of Adam Optimizer
[ { "code": null, "e": 23953, "s": 23925, "text": "\n16 Oct, 2021" }, { "code": null, "e": 24268, "s": 23953, "text": "TabNet was proposed by the researchers at Google Cloud in the year 2019. The idea behind TabNet is to effectively apply deep neural networks on tabular data which still consists of a large portion of users and processed data across various applications such as healthcare, banking, retail, finance, marketing, etc." }, { "code": null, "e": 24750, "s": 24268, "text": "One motivation to apply deep learning to the tabular dataset comes from other domains such as (image, language, speech) data when applied on it demonstrated a significant performance improvement on the large datasets as compared to other machine learning techniques. So, we can expect it to work on tabular data. Another reason can be those tree-based algorithms unlike the deep neural network do not efficiently learn to reduce the error by using techniques like Gradient Descent." }, { "code": null, "e": 24990, "s": 24750, "text": "TabNet provides a high-performance and interpretable tabular data deep learning architecture. It uses a method called sequential attention mechanism to enabling which feature to choose to cause high interpretability and efficient training." }, { "code": null, "e": 25018, "s": 24990, "text": "TabNet Encoder Architecture" }, { "code": null, "e": 25269, "s": 25018, "text": "The TabNet architecture basically consists of multi-steps which are sequential, passing the input from one step to another. There are different ways to decide the number of steps depending upon the capacity. Each step consists of the following steps:" }, { "code": null, "e": 25483, "s": 25269, "text": "In the initial step, the complete dataset is input into the model without any feature engineering. It is then passed through a batch normalization layer, and after that, it is then passed in a feature transformer." }, { "code": null, "e": 25611, "s": 25483, "text": "Feature Transformer: It consists of n-number (eg. 4) of different GLU blocks. Each GLU bloc consists of the following layers:" }, { "code": null, "e": 25689, "s": 25611, "text": "GLU block = Fully-Connected - Batch Normalization - GLU (Gated Linear Unit)" }, { "code": null, "e": 25708, "s": 25689, "text": "where , GLU(x) = " }, { "code": null, "e": 26103, "s": 25708, "text": "For 4 layers of GLU blocks, the 2 GLU blocks should be shared and 2 should be independent, which helps in robust and efficient learning. There is a skip connection also existed b/w two consecutive blocks. After each block, we perform the normalization with in order to get the stability and ensuring that the variance doesn’t vary considerably. The feature transformer outputs the two outputs:" }, { "code": null, "e": 26283, "s": 26103, "text": " It is the output decision from the particular step giving its prediction of continuous values/ classes. The output for the next attentive transformer where the next cycle begins." }, { "code": null, "e": 26388, "s": 26283, "text": " It is the output decision from the particular step giving its prediction of continuous values/ classes." }, { "code": null, "e": 26464, "s": 26388, "text": " The output for the next attentive transformer where the next cycle begins." }, { "code": null, "e": 26484, "s": 26464, "text": "Feature Transformer" }, { "code": null, "e": 26905, "s": 26484, "text": "Attentive Transformer: An attentive transformer consists of a fully connected (FC) layer, a BatchNorm layer, and Prior scales layer, and a Sparsemax layer. It receives input \\mathbb{n_a} and after passing through the fully connected layer and Batch normalization layer, then it passes through the prior scales layer.This prior scale layer aggregates how much each feature has been used before the current decision step." }, { "code": null, "e": 27009, "s": 26905, "text": "This prior scale layer aggregates how much each feature has been used before the current decision step." }, { "code": null, "e": 27037, "s": 27009, "text": " ; all features are equal." }, { "code": null, "e": 27167, "s": 27037, "text": "P_i = \\prod_{j=1}^{i} (\\gamma – M ) ; the smaller the value of \\gamma the more independent step, looking at different features." }, { "code": null, "e": 27297, "s": 27167, "text": "Sparsemax layer: It is used for normalization of the coefficient (similar to softmax), resulting in sparse selection of features:" }, { "code": null, "e": 27460, "s": 27297, "text": "If a lot of the features will be zeros, then we will apply instance-wise feature selection, where only a subset of different features is used for different steps." }, { "code": null, "e": 27482, "s": 27460, "text": "Attentive transformer" }, { "code": null, "e": 27880, "s": 27482, "text": "Attention Mask: The output from the attentive transformer step, are then fed into the a attention mask, which it helps in identify the selected features. It quantifies aggregate feature importance in addition to analysis of each step. Combining the masks at different steps requires a coefficient that can weigh the relative importance of each step in the decision. Therefore, the author proposes:" }, { "code": null, "e": 28077, "s": 27880, "text": " denote the aggregate decision contribution at ith decision step for the bth sample. Scaling the decision mask at each decision step with , the author propose the aggregate feature important mask:" }, { "code": null, "e": 28092, "s": 28077, "text": "TabNet Decoder" }, { "code": null, "e": 28337, "s": 28092, "text": "The TabNet decoder architecture consists of a feature transformer, followed by the fully connected layers at the decision step. The output is then summed to the reconstructed features. The reconstruction loss function in self-supervised phase: " }, { "code": null, "e": 28542, "s": 28337, "text": "We will be using the Pytorch implementation of the TabNet in this implementation. For datasets, we will be using the Loan Approval prediction, whether a person will get a loan or not which it applied for:" }, { "code": null, "e": 28550, "s": 28542, "text": "Python3" }, { "code": "# Install TabNetpip install pytorch-tabnet # imports necessary modulesfrom pytorch_tabnet.tab_model import TabNetClassifier import osimport torchimport pandas as pdimport numpy as np from sklearn.model_selection import KFoldfrom sklearn.preprocessing import LabelEncoder, MinMaxScalarfrom sklearn.metrics import accuracy_score # Load training and test datadata =pd.read_csv('/content/train.csv')data.head()data.isna().sum()# load test datatest_data = pd.read_csv('/content/test.csv')test_data.head()test_data.isna().sum() # set index columndata.set_index('Loan_ID', inplace=True)test_data.set_index('Loan_ID', inplace=True) # Replace NAsdata.fillna(method=\"bfill\", inplace=True)test_data.fillna(method=\"bfill\", inplace=True) # convert categorical column to integer Labels gen = LabelEncoder().fit(data['Gender'])data['Gender'] = gen.transform(data['Gender']) s_type= LabelEncoder().fit(data['Married'])data['Married'] = s_type.transform(data['Married']) n_dep= LabelEncoder().fit(data['Dependents'])data['Dependents'] = n_dep.transform(data['Dependents']) edu= LabelEncoder().fit(data['Education'])data['Education'] = edu.transform(data['Education']) s_emp = LabelEncoder().fit(data['Self_Employed'])data['Self_Employed'] = s_emp.transform(data['Self_Employed']) c_history = LabelEncoder().fit(data['Credit_History'])data['Credit_History'] = c_history.transform(data['Credit_History']) p_area = LabelEncoder().fit(data['Property_Area'])data['Property_Area'] = p_area.transform(data['Property_Area']) l_status = LabelEncoder().fit(data['Loan_Status'])data['Loan_Status'] = l_status.transform(data['Loan_Status']) # For test datatest_data['Gender'] = gen.transform(test_data['Gender'])test_data['Married'] = s_type.transform(test_data['Married'])test_data['Dependents'] = n_dep.transform(test_data['Dependents'])test_data['Education'] = edu.transform(test_data['Education'])test_data['Self_Employed'] = s_emp.transform(test_data['Self_Employed'])test_data['Credit_History'] = c_history.transform(test_data['Credit_History'])test_data['Property_Area'] = p_area.transform(test_data['Property_Area']) # select feature and target variableX = data.loc[:,data.columns != 'Loan_Status']y = data.loc[:,data.columns == 'Loan_Status']X.shape, y.shape # convert to numpyX= X.to_numpy()y= y.to_numpy() y= y.flatten() # define and train the Tabnet model with cross validationkf = KFold(n_splits=5, random_state=42, shuffle=True)CV_score_array =[]for train_index, test_index in kf.split(X): X_train, X_valid = X[train_index], X[test_index] y_train, y_valid = y[train_index], y[test_index] tb_cls = TabNetClassifier(optimizer_fn=torch.optim.Adam, optimizer_params=dict(lr=1e-3), scheduler_params={\"step_size\":10, \"gamma\":0.9}, scheduler_fn=torch.optim.lr_scheduler.StepLR, mask_type='entmax' # \"sparsemax\" ) tb_cls.fit(X_train,y_train, eval_set=[(X_train, y_train), (X_val, y_val)], eval_name=['train', 'valid'], eval_metric=['accuracy'], max_epochs=1000 , patience=100, batch_size=28, drop_last=False) CV_score_array.append(tb_cls.best_cost) # Test model and generate predictionpredictions =[ 'N' if i < 0.5 else 'Y' for i in tb_cls.predict(X_test)]", "e": 31914, "s": 28550, "text": null }, { "code": null, "e": 32972, "s": 31914, "text": "Collecting pytorch-tabnet\n Downloading pytorch_tabnet-3.1.1-py3-none-any.whl (39 kB)\nRequirement already satisfied: numpy<2.0,>=1.17 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (1.19.5)\nRequirement already satisfied: scikit_learn>0.21 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (0.22.2.post1)\nRequirement already satisfied: torch<2.0,>=1.2 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (1.9.0+cu102)\nRequirement already satisfied: scipy>1.4 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (1.4.1)\nRequirement already satisfied: tqdm<5.0,>=4.36 in /usr/local/lib/python3.7/dist-packages (from pytorch-tabnet) (4.62.2)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit_learn>0.21->pytorch-tabnet) (1.0.1)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch<2.0,>=1.2->pytorch-tabnet) (3.7.4.3)\nInstalling collected packages: pytorch-tabnet\nSuccessfully installed pytorch-tabnet-3.1.1" }, { "code": null, "e": 34058, "s": 32972, "text": "# train data\nLoan_ID Gender Married Dependents Education Self_Employed ApplicantIncome CoapplicantIncome LoanAmount Loan_Amount_Term Credit_History Property_Area Loan_Status\n0 LP001002 Male No 0 Graduate No 5849 0.0 NaN 360.0 1.0 Urban Y\n1 LP001003 Male Yes 1 Graduate No 4583 1508.0 128.0 360.0 1.0 Rural N\n2 LP001005 Male Yes 0 Graduate Yes 3000 0.0 66.0 360.0 1.0 Urban Y\n3 LP001006 Male Yes 0 Not Graduate No 2583 2358.0 120.0 360.0 1.0 Urban Y\n4 LP001008 Male No 0 Graduate No 6000 0.0 141.0 360.0 1.0 Urban Y\n\n# null values\nLoan_ID 0\nGender 13\nMarried 3\nDependents 15\nEducation 0\nSelf_Employed 32\nApplicantIncome 0\nCoapplicantIncome 0\nLoanAmount 22\nLoan_Amount_Term 14\nCredit_History 50\nProperty_Area 0\nLoan_Status 0\ndtype: int64" }, { "code": null, "e": 35074, "s": 34058, "text": "# test data\nLoan_ID Gender Married Dependents Education Self_Employed ApplicantIncome CoapplicantIncome LoanAmount Loan_Amount_Term Credit_History Property_Area\n0 LP001015 Male Yes 0 Graduate No 5720 0 110.0 360.0 1.0 Urban\n1 LP001022 Male Yes 1 Graduate No 3076 1500 126.0 360.0 1.0 Urban\n2 LP001031 Male Yes 2 Graduate No 5000 1800 208.0 360.0 1.0 Urban\n3 LP001035 Male Yes 2 Graduate No 2340 2546 100.0 360.0 NaN Urban\n4 LP001051 Male No 0 Not Graduate No 3276 0 78.0 360.0 1.0 Urban\n\n# Null values\nLoan_ID 0\nGender 11\nMarried 0\nDependents 10\nEducation 0\nSelf_Employed 23\nApplicantIncome 0\nCoapplicantIncome 0\nLoanAmount 5\nLoan_Amount_Term 6\nCredit_History 29\nProperty_Area 0\ndtype: int64" }, { "code": null, "e": 35109, "s": 35074, "text": "# x, y shape\n((614, 11), (614, 1))" }, { "code": null, "e": 35927, "s": 35109, "text": "Device used : cpu\nEarly stopping occurred at epoch 137 with best_epoch = 37 and best_valid_accuracy = 0.84416\nBest weights from best epoch are automatically used!\nDevice used : cpu\nEarly stopping occurred at epoch 292 with best_epoch = 192 and best_valid_accuracy = 0.86364\nBest weights from best epoch are automatically used!\nDevice used : cpu\nEarly stopping occurred at epoch 324 with best_epoch = 224 and best_valid_accuracy = 0.85065\nBest weights from best epoch are automatically used!\nDevice used : cpu\nEarly stopping occurred at epoch 143 with best_epoch = 43 and best_valid_accuracy = 0.84416\nBest weights from best epoch are automatically used!\nDevice used : cpu\nEarly stopping occurred at epoch 253 with best_epoch = 153 and best_valid_accuracy = 0.84416\nBest weights from best epoch are automatically used!" }, { "code": null, "e": 35940, "s": 35927, "text": "TabNet paper" }, { "code": null, "e": 36138, "s": 35940, "text": "Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready." }, { "code": null, "e": 36155, "s": 36138, "text": "Machine Learning" }, { "code": null, "e": 36172, "s": 36155, "text": "Machine Learning" }, { "code": null, "e": 36270, "s": 36172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36279, "s": 36270, "text": "Comments" }, { "code": null, "e": 36292, "s": 36279, "text": "Old Comments" }, { "code": null, "e": 36348, "s": 36292, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 36390, "s": 36348, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 36423, "s": 36390, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 36451, "s": 36423, "text": "Types of Environments in AI" }, { "code": null, "e": 36490, "s": 36451, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 36531, "s": 36490, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 36579, "s": 36531, "text": "Python | Decision Tree Regression using sklearn" }, { "code": null, "e": 36613, "s": 36579, "text": "Python | Stemming words with NLTK" }, { "code": null, "e": 36646, "s": 36613, "text": "Normalization vs Standardization" } ]
PostgreSQL - AUTO INCREMENT
PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases. If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type. The type name serial creates an integer columns. The type name bigserial creates a bigint column. bigserial should be used if you anticipate the use of more than 231 identifiers over the lifetime of the table. The type name smallserial creates a smallint column. The basic usage of SERIAL dataype is as follows − CREATE TABLE tablename ( colname SERIAL ); Consider the COMPANY table to be created as follows − testdb=# CREATE TABLE COMPANY( ID SERIAL PRIMARY KEY, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); Now, insert the following records into table COMPANY − INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ('Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'David', 27, 'Texas', 85000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'Kim', 22, 'South-Hall', 45000.00 ); INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY) VALUES ( 'James', 24, 'Houston', 10000.00 ); This will insert seven tuples into the table COMPANY and COMPANY will have the following records − id | name | age | address | salary ----+-------+-----+------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 23 Lectures 1.5 hours John Elder 49 Lectures 3.5 hours Niyazi Erdogan 126 Lectures 10.5 hours Abhishek And Pukhraj 35 Lectures 5 hours Karthikeya T 5 Lectures 51 mins Vinay Kumar 5 Lectures 52 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 3072, "s": 2825, "text": "PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases." }, { "code": null, "e": 3206, "s": 3072, "text": "If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type." }, { "code": null, "e": 3469, "s": 3206, "text": "The type name serial creates an integer columns. The type name bigserial creates a bigint column. bigserial should be used if you anticipate the use of more than 231 identifiers over the lifetime of the table. The type name smallserial creates a smallint column." }, { "code": null, "e": 3519, "s": 3469, "text": "The basic usage of SERIAL dataype is as follows −" }, { "code": null, "e": 3566, "s": 3519, "text": "CREATE TABLE tablename (\n colname SERIAL\n);\n" }, { "code": null, "e": 3620, "s": 3566, "text": "Consider the COMPANY table to be created as follows −" }, { "code": null, "e": 3808, "s": 3620, "text": "testdb=# CREATE TABLE COMPANY(\n ID SERIAL PRIMARY KEY,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 3863, "s": 3808, "text": "Now, insert the following records into table COMPANY −" }, { "code": null, "e": 4505, "s": 3863, "text": "INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Paul', 32, 'California', 20000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ('Allen', 25, 'Texas', 15000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ('Teddy', 23, 'Norway', 20000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'David', 27, 'Texas', 85000.00 );\n\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'Kim', 22, 'South-Hall', 45000.00 );\n\nINSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)\nVALUES ( 'James', 24, 'Houston', 10000.00 );" }, { "code": null, "e": 4604, "s": 4505, "text": "This will insert seven tuples into the table COMPANY and COMPANY will have the following records −" }, { "code": null, "e": 4965, "s": 4604, "text": " id | name | age | address | salary\n----+-------+-----+------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000" }, { "code": null, "e": 5000, "s": 4965, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5012, "s": 5000, "text": " John Elder" }, { "code": null, "e": 5047, "s": 5012, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5063, "s": 5047, "text": " Niyazi Erdogan" }, { "code": null, "e": 5100, "s": 5063, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5122, "s": 5100, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5155, "s": 5122, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 5169, "s": 5155, "text": " Karthikeya T" }, { "code": null, "e": 5200, "s": 5169, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 5213, "s": 5200, "text": " Vinay Kumar" }, { "code": null, "e": 5244, "s": 5213, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 5257, "s": 5244, "text": " Vinay Kumar" }, { "code": null, "e": 5264, "s": 5257, "text": " Print" }, { "code": null, "e": 5275, "s": 5264, "text": " Add Notes" } ]
The Complete Guide to Linear Regression in Python | by Marco Peixeiro | Towards Data Science
This article attempts to be the reference you need when it comes to understanding and performing linear regression. Although the algorithm is simple, only a few truly understand the underlying principles. First, we will dig deep into the theory of linear regression to understand its inner workings. Then, we will implement the algorithm in Python to model a business problem. I hope this article finds its way to your bookmarks! For now, let’s get to it! For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel. Linear regression is probably the simplest approach for statistical learning. It is a good starting point for more advanced approaches, and in fact, many fancy statistical learning techniques can be seen as an extension of linear regression. Therefore, understanding this simple model will build a good base before moving on to more complex approaches. Linear regression is very good to answer the following questions: Is there a relationship between 2 variables? How strong is the relationship? Which variable contributes the most? How accurately can we estimate the effect of each variable? How accurately can we predict the target? Is the relationship linear? (duh) Is there an interaction effect? Let’s assume we only have one variable and one target. Then, linear regression is expressed as: In the equation above, the betas are the coefficients. These coefficients are what we need in order to make predictions with our model. So how do we find these parameters? To find the parameters, we need to minimize the least squares or the sum of squared errors. Of course, the linear model is not perfect and it will not predict all the data accurately, meaning that there is a difference between the actual value and the prediction. The error is easily calculated with: But why are the errors squared? We square the error, because the prediction can be either above or below the true value, resulting in a negative or positive difference respectively. If we did not square the errors, the sum of errors could decrease because of negative differences and not because the model is a good fit. Also, squaring the errors penalizes large differences, and so the minimizing the squared errors “guarantees” a better model. Let’s take a look at a graph to better understand. In the graph above, the red dots are the true data and the blue line is linear model. The grey lines illustrate the errors between the predicted and the true values. The blue line is thus the one that minimizes the sum of the squared length of the grey lines. After some math that is too heavy for this article, you can finally estimate the coefficients with the following equations: Where x bar and y bar represent the mean. Now that you have coefficients, how can you tell if they are relevant to predict your target? The best way is to find the p-value. The p-value is used to quantify statistical significance; it allows to tell whether the null hypothesis is to be rejected or not. The null hypothesis? For any modelling task, the hypothesis is that there is some correlation between the features and the target. The null hypothesis is therefore the opposite: there is no correlation between the features and the target. So, finding the p-value for each coefficient will tell if the variable is statistically significant to predict the target. As a general rule of thumb, if the p-value is less than 0.05: there is a strong relationship between the variable and the target. You found out that your variable was statistically significant by finding its p-value. Great! Now, how do you know if your linear model is any good? To assess that, we usually use the RSE (residual standard error) and the R2 statistic. The first error metric is simple to understand: the lower the residual errors, the better the model fits the data (in this case, the closer the data is to a linear relationship). As for the R2 metric, it measures the proportion of variability in the target that can be explained using a feature X. Therefore, assuming a linear relationship, if feature X can explain (predict) the target, then the proportion is high and the R2 value will be close to 1. If the opposite is true, the R2 value is then closer to 0. In real life situations, there will never be a single feature to predict a target. So, do we perform linear regression on one feature at a time? Of course not. We simply perform multiple linear regression. The equation is very similar to simple linear regression; simply add the number of predictors and their corresponding coefficients: Previously, in simple linear regression, we assess the relevancy of a feature by finding its p-value. In the case of multiple linear regression, we use another metric: the F-statistic. Here, the F-statistic is calculated for the overall model, whereas the p-value is specific to each predictor. If there is a strong relationship, then F will be much larger than 1. Otherwise, it will be approximately equal to 1. How larger than 1 is large enough? This is hard to answer. Usually, if there is a large number of data points, F could be slightly larger than 1 and suggest a strong relationship. For small data sets, then the F value must be way larger than 1 to suggest a strong relationship. Why can’t we use the p-value in this case? Since we are fitting many predictors, we need to consider a case where there are a lot of features (p is large). With a very large amount of predictors, there will always be about 5% of them that will have, by chance, a very small p-value even though they are not statistically significant. Therefore, we use the F-statistic to avoid considering unimportant predictors as significant predictors. Just like in simple linear regression, the R2 can be used for multiple linear regression. However, know that adding more predictors will always increase the R2 value, because the model will necessarily better fit the training data. Yet, this does not mean it will perform well on test data (making predictions for unknown data points). Having multiple predictors in a linear model means that some predictors may have an influence on other predictors. For example, you want to predict the salary of a person, knowing her age and number of years spent in school. Of course, the older the person, the more time that person could have spent in school. So how do we model this interaction effect? Consider this very simple example with 2 predictors: As you can see, we simply multiply both predictors together and associate a new coefficient. Simplifying the formula, we see now that the coefficient is influenced by the value of another feature. As a general rule, if we include the interaction model, we should include the individual effect of a feature, even if its p-value is not significant. This is known as the hierarchical principle. The rationale behind this is that if two predictors are interacting, then including their individual contribution will have a small impact on the model. Alright! Now that we know how it works, let’s make it work! We will work through both a simple and multiple linear regression in Python and I will show how to assess the quality of the parameters and the overall model in both situations. You can grab the code and the data here. I strongly recommend that you follow and recreate the steps in your own Jupyter notebook to take full advantage of this tutorial. Let’s get to it! The data set contains information about money spent on advertisement and their generated sales. Money was spent on TV, radio and newspaper ads. The objective is to use linear regression to understand how advertisement spending impacts sales. The advantage of working with Python is that we have access to many libraries that allow us to rapidly read data, plot the data, and perform a linear regression. I like to import all the necessary libraries on top of the notebook to keep everything organized. Import the following: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_scoreimport statsmodels.api as sm Assuming that you downloaded the data set, place it in a data directory within your project folder. Then, read the data like so: data = pd.read_csv("data/Advertising.csv") To see what the data looks like, we do the following: data.head() And you should see this: As you can see, the column Unnamed: 0 is redundant. Hence, we remove it. data.drop(['Unnamed: 0'], axis=1) Alright, our data is clean and ready for linear regression! For simple linear regression, let’s consider only the effect of TV ads on sales. Before jumping right into the modelling, let’s take a look at what the data looks like. We use matplotlib , a popular Python plotting library to make a scatter plot. plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.xlabel("Money spent on TV ads ($)")plt.ylabel("Sales ($)")plt.show() Run this cell of code and you should see this graph: As you can see, there is a clear relationship between the amount spent on TV ads and sales. Let’s see how we can generate a linear approximation of this data. X = data['TV'].values.reshape(-1,1)y = data['sales'].values.reshape(-1,1)reg = LinearRegression()reg.fit(X, y)print("The linear model is: Y = {:.5} + {:.5}X".format(reg.intercept_[0], reg.coef_[0][0])) That’s it? Yes! It is that simple to fit a straight line to the data set and see the parameters of the equation. In this case, we have Let’s visualize how the line fits the data. predictions = reg.predict(X)plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.plot( data['TV'], predictions, c='blue', linewidth=2)plt.xlabel("Money spent on TV ads ($)")plt.ylabel("Sales ($)")plt.show() And now, you see: From the graph above, it seems that a simple linear regression can explain the general impact of amount spent on TV ads and sales. Now, if you remember from this post, to see if the model is any good, we need to look at the R2 value and the p-value from each coefficient. Here’s how we do it: X = data['TV']y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary()) Which gives you this lovely output: Looking at both coefficients, we have a p-value that is very low (although it is probably not exactly 0). This means that there is a strong correlation between these coefficients and the target (Sales). Then, looking at the R2 value, we have 0.612. Therefore, about 60% of the variability of sales is explained by the amount spent on TV ads. This is okay, but definitely not the best we can to accurately predict the sales. Surely, spending on newspaper and radio ads must have a certain impact on sales. Let’s see if a multiple linear regression will perform better. Just like for simple linear regression, we will define our features and target variable and use scikit-learn library to perform linear regression. Xs = data.drop(['sales', 'Unnamed: 0'], axis=1)y = data['sales'].reshape(-1,1)reg = LinearRegression()reg.fit(Xs, y)print("The linear model is: Y = {:.5} + {:.5}*TV + {:.5}*radio + {:.5}*newspaper".format(reg.intercept_[0], reg.coef_[0][0], reg.coef_[0][1], reg.coef_[0][2])) Nothing more! From this code cell, we get the following equation: Of course, we cannot visualize the impact of all three mediums on sales, since it has a total of four dimensions. Notice that the coefficient for newspaper is negative, but also fairly small. Is it relevant to our model? Let’s see by calculating the F-statistic, R2 value and p-value for each coefficient. As you must expect, the procedure here is very similar to what we did in simple linear regression. X = np.column_stack((data['TV'], data['radio'], data['newspaper']))y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary()) And you get the following: As you can see, the R2 is much higher than that of simple linear regression, with a value of 0.897! Also, the F-statistic is 570.3. This is much greater than 1, and since our data set if fairly small (only 200 data points), it demonstrates that there is a strong relationship between ad spending and sales. Finally, because we only have three predictors, we can consider their p-value to determine if they are relevant to the model or not. Of course, you notice that the third coefficient (the one for newspaper) has a large p-value. Therefore, ad spending on newspaper is not statistically significant. Removing that predictor would slightly reduce the R2 value, but we might make better predictions. You rock 🤘. Congratulations on making it to the end, you are now a master of linear regression! As aforementioned, this might not be the top performing algorithm, but is is important to understand linear regression as it forms the basis of more complex statistical learning approaches. I hope you will refer back to this article sometime.
[ { "code": null, "e": 377, "s": 172, "text": "This article attempts to be the reference you need when it comes to understanding and performing linear regression. Although the algorithm is simple, only a few truly understand the underlying principles." }, { "code": null, "e": 549, "s": 377, "text": "First, we will dig deep into the theory of linear regression to understand its inner workings. Then, we will implement the algorithm in Python to model a business problem." }, { "code": null, "e": 628, "s": 549, "text": "I hope this article finds its way to your bookmarks! For now, let’s get to it!" }, { "code": null, "e": 751, "s": 628, "text": "For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel." }, { "code": null, "e": 1104, "s": 751, "text": "Linear regression is probably the simplest approach for statistical learning. It is a good starting point for more advanced approaches, and in fact, many fancy statistical learning techniques can be seen as an extension of linear regression. Therefore, understanding this simple model will build a good base before moving on to more complex approaches." }, { "code": null, "e": 1170, "s": 1104, "text": "Linear regression is very good to answer the following questions:" }, { "code": null, "e": 1215, "s": 1170, "text": "Is there a relationship between 2 variables?" }, { "code": null, "e": 1247, "s": 1215, "text": "How strong is the relationship?" }, { "code": null, "e": 1284, "s": 1247, "text": "Which variable contributes the most?" }, { "code": null, "e": 1344, "s": 1284, "text": "How accurately can we estimate the effect of each variable?" }, { "code": null, "e": 1386, "s": 1344, "text": "How accurately can we predict the target?" }, { "code": null, "e": 1420, "s": 1386, "text": "Is the relationship linear? (duh)" }, { "code": null, "e": 1452, "s": 1420, "text": "Is there an interaction effect?" }, { "code": null, "e": 1548, "s": 1452, "text": "Let’s assume we only have one variable and one target. Then, linear regression is expressed as:" }, { "code": null, "e": 1684, "s": 1548, "text": "In the equation above, the betas are the coefficients. These coefficients are what we need in order to make predictions with our model." }, { "code": null, "e": 1720, "s": 1684, "text": "So how do we find these parameters?" }, { "code": null, "e": 2021, "s": 1720, "text": "To find the parameters, we need to minimize the least squares or the sum of squared errors. Of course, the linear model is not perfect and it will not predict all the data accurately, meaning that there is a difference between the actual value and the prediction. The error is easily calculated with:" }, { "code": null, "e": 2053, "s": 2021, "text": "But why are the errors squared?" }, { "code": null, "e": 2342, "s": 2053, "text": "We square the error, because the prediction can be either above or below the true value, resulting in a negative or positive difference respectively. If we did not square the errors, the sum of errors could decrease because of negative differences and not because the model is a good fit." }, { "code": null, "e": 2467, "s": 2342, "text": "Also, squaring the errors penalizes large differences, and so the minimizing the squared errors “guarantees” a better model." }, { "code": null, "e": 2518, "s": 2467, "text": "Let’s take a look at a graph to better understand." }, { "code": null, "e": 2778, "s": 2518, "text": "In the graph above, the red dots are the true data and the blue line is linear model. The grey lines illustrate the errors between the predicted and the true values. The blue line is thus the one that minimizes the sum of the squared length of the grey lines." }, { "code": null, "e": 2902, "s": 2778, "text": "After some math that is too heavy for this article, you can finally estimate the coefficients with the following equations:" }, { "code": null, "e": 2944, "s": 2902, "text": "Where x bar and y bar represent the mean." }, { "code": null, "e": 3038, "s": 2944, "text": "Now that you have coefficients, how can you tell if they are relevant to predict your target?" }, { "code": null, "e": 3205, "s": 3038, "text": "The best way is to find the p-value. The p-value is used to quantify statistical significance; it allows to tell whether the null hypothesis is to be rejected or not." }, { "code": null, "e": 3226, "s": 3205, "text": "The null hypothesis?" }, { "code": null, "e": 3444, "s": 3226, "text": "For any modelling task, the hypothesis is that there is some correlation between the features and the target. The null hypothesis is therefore the opposite: there is no correlation between the features and the target." }, { "code": null, "e": 3697, "s": 3444, "text": "So, finding the p-value for each coefficient will tell if the variable is statistically significant to predict the target. As a general rule of thumb, if the p-value is less than 0.05: there is a strong relationship between the variable and the target." }, { "code": null, "e": 3791, "s": 3697, "text": "You found out that your variable was statistically significant by finding its p-value. Great!" }, { "code": null, "e": 3846, "s": 3791, "text": "Now, how do you know if your linear model is any good?" }, { "code": null, "e": 3933, "s": 3846, "text": "To assess that, we usually use the RSE (residual standard error) and the R2 statistic." }, { "code": null, "e": 4112, "s": 3933, "text": "The first error metric is simple to understand: the lower the residual errors, the better the model fits the data (in this case, the closer the data is to a linear relationship)." }, { "code": null, "e": 4445, "s": 4112, "text": "As for the R2 metric, it measures the proportion of variability in the target that can be explained using a feature X. Therefore, assuming a linear relationship, if feature X can explain (predict) the target, then the proportion is high and the R2 value will be close to 1. If the opposite is true, the R2 value is then closer to 0." }, { "code": null, "e": 4651, "s": 4445, "text": "In real life situations, there will never be a single feature to predict a target. So, do we perform linear regression on one feature at a time? Of course not. We simply perform multiple linear regression." }, { "code": null, "e": 4783, "s": 4651, "text": "The equation is very similar to simple linear regression; simply add the number of predictors and their corresponding coefficients:" }, { "code": null, "e": 4885, "s": 4783, "text": "Previously, in simple linear regression, we assess the relevancy of a feature by finding its p-value." }, { "code": null, "e": 4968, "s": 4885, "text": "In the case of multiple linear regression, we use another metric: the F-statistic." }, { "code": null, "e": 5196, "s": 4968, "text": "Here, the F-statistic is calculated for the overall model, whereas the p-value is specific to each predictor. If there is a strong relationship, then F will be much larger than 1. Otherwise, it will be approximately equal to 1." }, { "code": null, "e": 5231, "s": 5196, "text": "How larger than 1 is large enough?" }, { "code": null, "e": 5474, "s": 5231, "text": "This is hard to answer. Usually, if there is a large number of data points, F could be slightly larger than 1 and suggest a strong relationship. For small data sets, then the F value must be way larger than 1 to suggest a strong relationship." }, { "code": null, "e": 5517, "s": 5474, "text": "Why can’t we use the p-value in this case?" }, { "code": null, "e": 5913, "s": 5517, "text": "Since we are fitting many predictors, we need to consider a case where there are a lot of features (p is large). With a very large amount of predictors, there will always be about 5% of them that will have, by chance, a very small p-value even though they are not statistically significant. Therefore, we use the F-statistic to avoid considering unimportant predictors as significant predictors." }, { "code": null, "e": 6145, "s": 5913, "text": "Just like in simple linear regression, the R2 can be used for multiple linear regression. However, know that adding more predictors will always increase the R2 value, because the model will necessarily better fit the training data." }, { "code": null, "e": 6249, "s": 6145, "text": "Yet, this does not mean it will perform well on test data (making predictions for unknown data points)." }, { "code": null, "e": 6364, "s": 6249, "text": "Having multiple predictors in a linear model means that some predictors may have an influence on other predictors." }, { "code": null, "e": 6605, "s": 6364, "text": "For example, you want to predict the salary of a person, knowing her age and number of years spent in school. Of course, the older the person, the more time that person could have spent in school. So how do we model this interaction effect?" }, { "code": null, "e": 6658, "s": 6605, "text": "Consider this very simple example with 2 predictors:" }, { "code": null, "e": 6855, "s": 6658, "text": "As you can see, we simply multiply both predictors together and associate a new coefficient. Simplifying the formula, we see now that the coefficient is influenced by the value of another feature." }, { "code": null, "e": 7203, "s": 6855, "text": "As a general rule, if we include the interaction model, we should include the individual effect of a feature, even if its p-value is not significant. This is known as the hierarchical principle. The rationale behind this is that if two predictors are interacting, then including their individual contribution will have a small impact on the model." }, { "code": null, "e": 7441, "s": 7203, "text": "Alright! Now that we know how it works, let’s make it work! We will work through both a simple and multiple linear regression in Python and I will show how to assess the quality of the parameters and the overall model in both situations." }, { "code": null, "e": 7482, "s": 7441, "text": "You can grab the code and the data here." }, { "code": null, "e": 7612, "s": 7482, "text": "I strongly recommend that you follow and recreate the steps in your own Jupyter notebook to take full advantage of this tutorial." }, { "code": null, "e": 7629, "s": 7612, "text": "Let’s get to it!" }, { "code": null, "e": 7773, "s": 7629, "text": "The data set contains information about money spent on advertisement and their generated sales. Money was spent on TV, radio and newspaper ads." }, { "code": null, "e": 7871, "s": 7773, "text": "The objective is to use linear regression to understand how advertisement spending impacts sales." }, { "code": null, "e": 8033, "s": 7871, "text": "The advantage of working with Python is that we have access to many libraries that allow us to rapidly read data, plot the data, and perform a linear regression." }, { "code": null, "e": 8153, "s": 8033, "text": "I like to import all the necessary libraries on top of the notebook to keep everything organized. Import the following:" }, { "code": null, "e": 8335, "s": 8153, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_scoreimport statsmodels.api as sm" }, { "code": null, "e": 8464, "s": 8335, "text": "Assuming that you downloaded the data set, place it in a data directory within your project folder. Then, read the data like so:" }, { "code": null, "e": 8507, "s": 8464, "text": "data = pd.read_csv(\"data/Advertising.csv\")" }, { "code": null, "e": 8561, "s": 8507, "text": "To see what the data looks like, we do the following:" }, { "code": null, "e": 8573, "s": 8561, "text": "data.head()" }, { "code": null, "e": 8598, "s": 8573, "text": "And you should see this:" }, { "code": null, "e": 8671, "s": 8598, "text": "As you can see, the column Unnamed: 0 is redundant. Hence, we remove it." }, { "code": null, "e": 8705, "s": 8671, "text": "data.drop(['Unnamed: 0'], axis=1)" }, { "code": null, "e": 8765, "s": 8705, "text": "Alright, our data is clean and ready for linear regression!" }, { "code": null, "e": 8934, "s": 8765, "text": "For simple linear regression, let’s consider only the effect of TV ads on sales. Before jumping right into the modelling, let’s take a look at what the data looks like." }, { "code": null, "e": 9012, "s": 8934, "text": "We use matplotlib , a popular Python plotting library to make a scatter plot." }, { "code": null, "e": 9171, "s": 9012, "text": "plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.xlabel(\"Money spent on TV ads ($)\")plt.ylabel(\"Sales ($)\")plt.show()" }, { "code": null, "e": 9224, "s": 9171, "text": "Run this cell of code and you should see this graph:" }, { "code": null, "e": 9316, "s": 9224, "text": "As you can see, there is a clear relationship between the amount spent on TV ads and sales." }, { "code": null, "e": 9383, "s": 9316, "text": "Let’s see how we can generate a linear approximation of this data." }, { "code": null, "e": 9585, "s": 9383, "text": "X = data['TV'].values.reshape(-1,1)y = data['sales'].values.reshape(-1,1)reg = LinearRegression()reg.fit(X, y)print(\"The linear model is: Y = {:.5} + {:.5}X\".format(reg.intercept_[0], reg.coef_[0][0]))" }, { "code": null, "e": 9596, "s": 9585, "text": "That’s it?" }, { "code": null, "e": 9720, "s": 9596, "text": "Yes! It is that simple to fit a straight line to the data set and see the parameters of the equation. In this case, we have" }, { "code": null, "e": 9764, "s": 9720, "text": "Let’s visualize how the line fits the data." }, { "code": null, "e": 10020, "s": 9764, "text": "predictions = reg.predict(X)plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.plot( data['TV'], predictions, c='blue', linewidth=2)plt.xlabel(\"Money spent on TV ads ($)\")plt.ylabel(\"Sales ($)\")plt.show()" }, { "code": null, "e": 10038, "s": 10020, "text": "And now, you see:" }, { "code": null, "e": 10169, "s": 10038, "text": "From the graph above, it seems that a simple linear regression can explain the general impact of amount spent on TV ads and sales." }, { "code": null, "e": 10310, "s": 10169, "text": "Now, if you remember from this post, to see if the model is any good, we need to look at the R2 value and the p-value from each coefficient." }, { "code": null, "e": 10331, "s": 10310, "text": "Here’s how we do it:" }, { "code": null, "e": 10442, "s": 10331, "text": "X = data['TV']y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary())" }, { "code": null, "e": 10478, "s": 10442, "text": "Which gives you this lovely output:" }, { "code": null, "e": 10681, "s": 10478, "text": "Looking at both coefficients, we have a p-value that is very low (although it is probably not exactly 0). This means that there is a strong correlation between these coefficients and the target (Sales)." }, { "code": null, "e": 10983, "s": 10681, "text": "Then, looking at the R2 value, we have 0.612. Therefore, about 60% of the variability of sales is explained by the amount spent on TV ads. This is okay, but definitely not the best we can to accurately predict the sales. Surely, spending on newspaper and radio ads must have a certain impact on sales." }, { "code": null, "e": 11046, "s": 10983, "text": "Let’s see if a multiple linear regression will perform better." }, { "code": null, "e": 11193, "s": 11046, "text": "Just like for simple linear regression, we will define our features and target variable and use scikit-learn library to perform linear regression." }, { "code": null, "e": 11469, "s": 11193, "text": "Xs = data.drop(['sales', 'Unnamed: 0'], axis=1)y = data['sales'].reshape(-1,1)reg = LinearRegression()reg.fit(Xs, y)print(\"The linear model is: Y = {:.5} + {:.5}*TV + {:.5}*radio + {:.5}*newspaper\".format(reg.intercept_[0], reg.coef_[0][0], reg.coef_[0][1], reg.coef_[0][2]))" }, { "code": null, "e": 11535, "s": 11469, "text": "Nothing more! From this code cell, we get the following equation:" }, { "code": null, "e": 11649, "s": 11535, "text": "Of course, we cannot visualize the impact of all three mediums on sales, since it has a total of four dimensions." }, { "code": null, "e": 11841, "s": 11649, "text": "Notice that the coefficient for newspaper is negative, but also fairly small. Is it relevant to our model? Let’s see by calculating the F-statistic, R2 value and p-value for each coefficient." }, { "code": null, "e": 11940, "s": 11841, "text": "As you must expect, the procedure here is very similar to what we did in simple linear regression." }, { "code": null, "e": 12104, "s": 11940, "text": "X = np.column_stack((data['TV'], data['radio'], data['newspaper']))y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary())" }, { "code": null, "e": 12131, "s": 12104, "text": "And you get the following:" }, { "code": null, "e": 12231, "s": 12131, "text": "As you can see, the R2 is much higher than that of simple linear regression, with a value of 0.897!" }, { "code": null, "e": 12438, "s": 12231, "text": "Also, the F-statistic is 570.3. This is much greater than 1, and since our data set if fairly small (only 200 data points), it demonstrates that there is a strong relationship between ad spending and sales." }, { "code": null, "e": 12833, "s": 12438, "text": "Finally, because we only have three predictors, we can consider their p-value to determine if they are relevant to the model or not. Of course, you notice that the third coefficient (the one for newspaper) has a large p-value. Therefore, ad spending on newspaper is not statistically significant. Removing that predictor would slightly reduce the R2 value, but we might make better predictions." }, { "code": null, "e": 12929, "s": 12833, "text": "You rock 🤘. Congratulations on making it to the end, you are now a master of linear regression!" }, { "code": null, "e": 13119, "s": 12929, "text": "As aforementioned, this might not be the top performing algorithm, but is is important to understand linear regression as it forms the basis of more complex statistical learning approaches." } ]
Custom Implementation of Feature Importance for your Voting Classifier Model | by Satyam Kumar | Towards Data Science
Machine learning models are becoming increasingly employed in complex high settings such as financial technology, medical science, etc. Despite the increase in utilization, there’s a lack of techniques to explain the model. The higher the interpretability of the model, the easier it becomes for someone to comprehend the results. There are various advanced techniques and algorithms to interpret the models including LIME, SHAP, etc. Feature Importance is the simplest and most efficient technique to interpret the importance of the feature for the estimator. Feature Importance can help to get a better interpretation of the estimator and lead to model improvements by employing feature selection. There are various techniques to compute the feature importance score of the estimator: Scikit-Learn built-in implementation of Feature Importance Feature Importance computed with the Permutation method Feature Importance computed with the SHAP value In this article, we will further discuss the first feature importance strategy. Scikit-Learn package comes up with a function model.feature_importances_ to compute the feature importance for most of the estimators except the Voting Classifier estimator. Scikit-learn employs different algorithms to compute the feature importance score. For Random Forest or Decision Tree models, it computes the importance score using Gini Importance, for Logistic Regression it uses the vector weight. In this article, we will discuss the implementation to compute the Importance score for a Voting Classifier model. Voting Classifier is an ensemble technique that combines the predictions of various models together predicts an output (class) based on their highest probability. The voting classifier algorithm simply aggregates the findings of each classifier passed into the model and predicts the output class based on the highest majority of voting. Voting Classifier supports two types of voting techniques: Hard Voting: The predicted output of the voting classifier estimator will be calculated based on the highest majority of votes i.e the class which had the highest probability of being predicted by each of the classifiers. Soft Voting: The output class is the prediction based on the average probability given to that class. To get a better understanding of the Voting Classifier, read an article by Mubarak Ganiyu: towardsdatascience.com Unlike other model estimators, Scikit-learn does not come up with the feature importance implementation of Voting Classifier. But each of the base estimators used for the Voting Classifier has its implementation. The idea is to combine the importance score of each of the estimators based on the weights. The steps of the algorithm to compute the feature importance of the Voting Classifier is: Compute Feature Importance score of each of the base estimatorsMultiply the weights of the base estimator to the importance score of each of the features.Average out the features importance score (from step 2) for each feature. Compute Feature Importance score of each of the base estimators Multiply the weights of the base estimator to the importance score of each of the features. Average out the features importance score (from step 2) for each feature. import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import VotingClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import * import numpy as np df = pd.read_csv("DATA/creditcard.csv") df.shape (284807, 31) y = df['Class'] X = df.drop(['Class'], axis=1) X_train, X_test, Y_train, Y_test = train_test_split(X, y) print(X_train.shape) print(X_test.shape) (213605, 30) (71202, 30) clf1 = DecisionTreeClassifier(random_state=42) clf2 = DecisionTreeClassifier(random_state=42, max_depth=20) clf3 = RandomForestClassifier(random_state=42, n_jobs=-1) %%time estimators = [('DT1', clf1), ('DT2', clf2), ('RF', clf3)] voting_clf = VotingClassifier(estimators=estimators, voting='soft', weights=[1,1,2]) voting_clf.fit(X_train, Y_train) Wall time: 1min 22s VotingClassifier(estimators=[('DT1', DecisionTreeClassifier(random_state=42)), ('DT2', DecisionTreeClassifier(max_depth=20, random_state=42)), ('RF', RandomForestClassifier(n_jobs=-1, random_state=42))], voting='soft', weights=[1, 1, 2]) def compute_feature_importance(voting_clf, weights): """ Function to compute feature importance of Voting Classifier """ feature_importance = dict() for est in voting_clf.estimators_: feature_importance[str(est)] = est.feature_importances_ fe_scores = [0]*len(list(feature_importance.values())[0]) for idx, imp_score in enumerate(feature_importance.values()): imp_score_with_weight = imp_score*weights[idx] fe_scores = list(np.add(fe_scores, list(imp_score_with_weight))) return fe_scores df = pd.DataFrame() df['Feature'] = X_train.columns df['Feature Importance'] = compute_feature_importance(voting_clf, [1, 1, 2]) df.sort_values('Feature Importance', ascending=False) In this article, we have discussed a technique or hack to compute the feature importance score for the Voting Classifier ensemble model. Feature importance score can be helpful to understand the top important features for the model and may lead to model improvements by employing feature selection. [1] Voting Classifier Documentation from Scikit-Learn: https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.VotingClassifier.html Thank You for Reading
[ { "code": null, "e": 607, "s": 172, "text": "Machine learning models are becoming increasingly employed in complex high settings such as financial technology, medical science, etc. Despite the increase in utilization, there’s a lack of techniques to explain the model. The higher the interpretability of the model, the easier it becomes for someone to comprehend the results. There are various advanced techniques and algorithms to interpret the models including LIME, SHAP, etc." }, { "code": null, "e": 959, "s": 607, "text": "Feature Importance is the simplest and most efficient technique to interpret the importance of the feature for the estimator. Feature Importance can help to get a better interpretation of the estimator and lead to model improvements by employing feature selection. There are various techniques to compute the feature importance score of the estimator:" }, { "code": null, "e": 1018, "s": 959, "text": "Scikit-Learn built-in implementation of Feature Importance" }, { "code": null, "e": 1074, "s": 1018, "text": "Feature Importance computed with the Permutation method" }, { "code": null, "e": 1122, "s": 1074, "text": "Feature Importance computed with the SHAP value" }, { "code": null, "e": 1609, "s": 1122, "text": "In this article, we will further discuss the first feature importance strategy. Scikit-Learn package comes up with a function model.feature_importances_ to compute the feature importance for most of the estimators except the Voting Classifier estimator. Scikit-learn employs different algorithms to compute the feature importance score. For Random Forest or Decision Tree models, it computes the importance score using Gini Importance, for Logistic Regression it uses the vector weight." }, { "code": null, "e": 1724, "s": 1609, "text": "In this article, we will discuss the implementation to compute the Importance score for a Voting Classifier model." }, { "code": null, "e": 2062, "s": 1724, "text": "Voting Classifier is an ensemble technique that combines the predictions of various models together predicts an output (class) based on their highest probability. The voting classifier algorithm simply aggregates the findings of each classifier passed into the model and predicts the output class based on the highest majority of voting." }, { "code": null, "e": 2121, "s": 2062, "text": "Voting Classifier supports two types of voting techniques:" }, { "code": null, "e": 2343, "s": 2121, "text": "Hard Voting: The predicted output of the voting classifier estimator will be calculated based on the highest majority of votes i.e the class which had the highest probability of being predicted by each of the classifiers." }, { "code": null, "e": 2445, "s": 2343, "text": "Soft Voting: The output class is the prediction based on the average probability given to that class." }, { "code": null, "e": 2536, "s": 2445, "text": "To get a better understanding of the Voting Classifier, read an article by Mubarak Ganiyu:" }, { "code": null, "e": 2559, "s": 2536, "text": "towardsdatascience.com" }, { "code": null, "e": 2864, "s": 2559, "text": "Unlike other model estimators, Scikit-learn does not come up with the feature importance implementation of Voting Classifier. But each of the base estimators used for the Voting Classifier has its implementation. The idea is to combine the importance score of each of the estimators based on the weights." }, { "code": null, "e": 2954, "s": 2864, "text": "The steps of the algorithm to compute the feature importance of the Voting Classifier is:" }, { "code": null, "e": 3182, "s": 2954, "text": "Compute Feature Importance score of each of the base estimatorsMultiply the weights of the base estimator to the importance score of each of the features.Average out the features importance score (from step 2) for each feature." }, { "code": null, "e": 3246, "s": 3182, "text": "Compute Feature Importance score of each of the base estimators" }, { "code": null, "e": 3338, "s": 3246, "text": "Multiply the weights of the base estimator to the importance score of each of the features." }, { "code": null, "e": 3412, "s": 3338, "text": "Average out the features importance score (from step 2) for each feature." }, { "code": null, "e": 3681, "s": 3412, "text": "import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import *\nimport numpy as np\n" }, { "code": null, "e": 3731, "s": 3681, "text": "df = pd.read_csv(\"DATA/creditcard.csv\")\ndf.shape\n" }, { "code": null, "e": 3744, "s": 3731, "text": "(284807, 31)" }, { "code": null, "e": 3892, "s": 3744, "text": "y = df['Class']\nX = df.drop(['Class'], axis=1)\nX_train, X_test, Y_train, Y_test = train_test_split(X, y)\n\nprint(X_train.shape)\nprint(X_test.shape)\n" }, { "code": null, "e": 3918, "s": 3892, "text": "(213605, 30)\n(71202, 30)\n" }, { "code": null, "e": 4085, "s": 3918, "text": "clf1 = DecisionTreeClassifier(random_state=42)\nclf2 = DecisionTreeClassifier(random_state=42, max_depth=20)\nclf3 = RandomForestClassifier(random_state=42, n_jobs=-1)\n" }, { "code": null, "e": 4270, "s": 4085, "text": "%%time\n\nestimators = [('DT1', clf1), ('DT2', clf2), ('RF', clf3)]\nvoting_clf = VotingClassifier(estimators=estimators, voting='soft', weights=[1,1,2])\nvoting_clf.fit(X_train, Y_train)\n" }, { "code": null, "e": 4291, "s": 4270, "text": "Wall time: 1min 22s\n" }, { "code": null, "e": 4770, "s": 4291, "text": "VotingClassifier(estimators=[('DT1', DecisionTreeClassifier(random_state=42)),\n ('DT2',\n DecisionTreeClassifier(max_depth=20,\n random_state=42)),\n ('RF',\n RandomForestClassifier(n_jobs=-1,\n random_state=42))],\n voting='soft', weights=[1, 1, 2])" }, { "code": null, "e": 5318, "s": 4770, "text": "def compute_feature_importance(voting_clf, weights):\n \"\"\" Function to compute feature importance of Voting Classifier \"\"\"\n \n feature_importance = dict()\n for est in voting_clf.estimators_:\n feature_importance[str(est)] = est.feature_importances_\n \n fe_scores = [0]*len(list(feature_importance.values())[0])\n for idx, imp_score in enumerate(feature_importance.values()):\n imp_score_with_weight = imp_score*weights[idx]\n fe_scores = list(np.add(fe_scores, list(imp_score_with_weight)))\n return fe_scores\n" }, { "code": null, "e": 5502, "s": 5318, "text": "df = pd.DataFrame()\ndf['Feature'] = X_train.columns\ndf['Feature Importance'] = compute_feature_importance(voting_clf, [1, 1, 2])\ndf.sort_values('Feature Importance', ascending=False)\n" }, { "code": null, "e": 5804, "s": 5505, "text": "In this article, we have discussed a technique or hack to compute the feature importance score for the Voting Classifier ensemble model. Feature importance score can be helpful to understand the top important features for the model and may lead to model improvements by employing feature selection." }, { "code": null, "e": 5948, "s": 5804, "text": "[1] Voting Classifier Documentation from Scikit-Learn: https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.VotingClassifier.html" } ]
Finding the Quantile and Decile Ranks of a Pandas DataFrame column - GeeksforGeeks
20 Dec, 2021 A Quantile is where a sample is divided into equal-sized, adjacent, subgroups. The median is a quantile; the median is placed in a probability distribution so that exactly half of the data is lower than the median and half of the data is above the median. The median cuts a distribution into two equal areas and so it is sometimes called 2-quantile. Quartiles are also quantiles; they divide the distribution into four equal parts. Percentiles are quantiles that divide a distribution into 100 equal parts and deciles are quantiles that divide a distribution into 10 equal parts. We can use the following formula to estimate the ith observation: ith observation = q (n + 1) where q is the quantile, the proportion below the ith value that you are looking for n is the number of items in a data set. So for finding Quantile rank, q should be 0.25 as we want to divide our data set into 4 equal parts and rank the values from 0-3 based on which quartile they fall upon. And similarly for Decile rank, q should be 0.1 as we want our data set to be divided into 10 equal parts. Before moving to Pandas, lets us try the above concept on an example to understand how our Quantile and Decile Ranks are calculated. Sample question : Find the number in the following set of data where 25 percent of values fall below it, and 75 percent fall above. Data : 32, 47, 55, 62, 74, 77, 86 Step 1: Order the data from smallest to largest. The data in the question is already in ascending order. Step 2: Count how many observations you have in your data set. this particular data set has 7 items. Step 3: Convert any percentage to a decimal for “q”. We are looking for the number where 25 percent of the values fall below it, so convert that to .25. Step 4: Insert your values into the formula: Answer: ith observation = q (n + 1) ith observation = .25(7 + 1) = 2 The ith observation is at 2. The 2nd number in the set is 47, which is the number where 25 percent of the values fall below it. And then we can start ranking our numbers from 0-3 since we are finding Quantile Rank. Similar approach for finding Decile Rank, in this case its just that the value of q will be 0.1. Now let us now look in Pandas how we can quickly achieve the same. Code for Creating a DataFrame: python3 # Import pandasimport pandas as pd # Create a DataFramedf1 = {'Name':['George', 'Andrea', 'John', 'Helen', 'Ravi', 'Julia', 'Justin'], 'EnglishScore':[62, 47, 55, 74, 32, 77, 86]} df1 = pd.DataFrame(df1, columns = ['Name', '']) # Sorting the DataFrame in Ascending Order of English Scoredf1.sort_values(by =['EnglishScore'], inplace = True) If we print the above dataframe we get the below result : Data Frame Now we can find the Quantile Rank using the pandas function qcut() by passing the column name which is to be considered for the Rank, the value for parameter q which signifies the Number of quantiles. 10 for deciles, 4 for quartiles, etc. and labels = False to return the bins as Integers. Following is code for Quantile Rank python3 # codedf1['QuantileRank']= pd.qcut(df1['EnglishScore'], q = 4, labels = False) And now if we print the dataframe we can see the new column QauntileRank ranking our data based on EnglishScore column. Quantile Rank Similarly to calculate Decile Rank we set q = 10 python3 # codedf1['DecileRank']= pd.qcut(df1['EnglishScore'], q = 10, labels = False) Now if we print our DataFrame we get the following output. DecileRank That is how we can use the Pandas qcut() method to calculate the various Quantiles on a column. The entire code for the above example is given below. python3 # codeimport pandas as pd # Create a DataFramedf1 = {'Name':['George', 'Andrea', 'John', 'Helen', 'Ravi', 'Julia', 'Justin'], 'EnglishScore':[62, 47, 55, 74, 32, 77, 86]} df1 = pd.DataFrame(df1, columns =['Name', 'EnglishScore']) # Sorting the DataFrame in Ascending Order of English Score# Sorting just for the purpose of better data readability.df1.sort_values(by =['EnglishScore'], inplace = True) # Calculating Quantile Rankdf1['QuantileRank']= pd.qcut(df1['EnglishScore'], q = 4, labels = False) # Calculating Decile Rankdf1['DecileRank'] = pd.qcut(df1['EnglishScore'], q = 10, labels = False) # printing the dataframeprint(df1) gabaa406 surinderdawra388 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23965, "s": 23937, "text": "\n20 Dec, 2021" }, { "code": null, "e": 24045, "s": 23965, "text": "A Quantile is where a sample is divided into equal-sized, adjacent, subgroups. " }, { "code": null, "e": 24316, "s": 24045, "text": "The median is a quantile; the median is placed in a probability distribution so that exactly half of the data is lower than the median and half of the data is above the median. The median cuts a distribution into two equal areas and so it is sometimes called 2-quantile." }, { "code": null, "e": 24399, "s": 24316, "text": "Quartiles are also quantiles; they divide the distribution into four equal parts. " }, { "code": null, "e": 24547, "s": 24399, "text": "Percentiles are quantiles that divide a distribution into 100 equal parts and deciles are quantiles that divide a distribution into 10 equal parts." }, { "code": null, "e": 24613, "s": 24547, "text": "We can use the following formula to estimate the ith observation:" }, { "code": null, "e": 24643, "s": 24615, "text": "ith observation = q (n + 1)" }, { "code": null, "e": 24728, "s": 24643, "text": "where q is the quantile, the proportion below the ith value that you are looking for" }, { "code": null, "e": 24768, "s": 24728, "text": "n is the number of items in a data set." }, { "code": null, "e": 24937, "s": 24768, "text": "So for finding Quantile rank, q should be 0.25 as we want to divide our data set into 4 equal parts and rank the values from 0-3 based on which quartile they fall upon." }, { "code": null, "e": 25043, "s": 24937, "text": "And similarly for Decile rank, q should be 0.1 as we want our data set to be divided into 10 equal parts." }, { "code": null, "e": 25176, "s": 25043, "text": "Before moving to Pandas, lets us try the above concept on an example to understand how our Quantile and Decile Ranks are calculated." }, { "code": null, "e": 25309, "s": 25176, "text": "Sample question : Find the number in the following set of data where 25 percent of values fall below it, and 75 percent fall above. " }, { "code": null, "e": 25344, "s": 25309, "text": "Data : 32, 47, 55, 62, 74, 77, 86" }, { "code": null, "e": 25451, "s": 25346, "text": "Step 1: Order the data from smallest to largest. The data in the question is already in ascending order." }, { "code": null, "e": 25554, "s": 25453, "text": "Step 2: Count how many observations you have in your data set. this particular data set has 7 items." }, { "code": null, "e": 25709, "s": 25556, "text": "Step 3: Convert any percentage to a decimal for “q”. We are looking for the number where 25 percent of the values fall below it, so convert that to .25." }, { "code": null, "e": 25756, "s": 25711, "text": "Step 4: Insert your values into the formula:" }, { "code": null, "e": 25766, "s": 25758, "text": "Answer:" }, { "code": null, "e": 25796, "s": 25768, "text": "ith observation = q (n + 1)" }, { "code": null, "e": 25831, "s": 25798, "text": "ith observation = .25(7 + 1) = 2" }, { "code": null, "e": 26145, "s": 25833, "text": "The ith observation is at 2. The 2nd number in the set is 47, which is the number where 25 percent of the values fall below it. And then we can start ranking our numbers from 0-3 since we are finding Quantile Rank. Similar approach for finding Decile Rank, in this case its just that the value of q will be 0.1." }, { "code": null, "e": 26214, "s": 26147, "text": "Now let us now look in Pandas how we can quickly achieve the same." }, { "code": null, "e": 26247, "s": 26216, "text": "Code for Creating a DataFrame:" }, { "code": null, "e": 26257, "s": 26249, "text": "python3" }, { "code": "# Import pandasimport pandas as pd # Create a DataFramedf1 = {'Name':['George', 'Andrea', 'John', 'Helen', 'Ravi', 'Julia', 'Justin'], 'EnglishScore':[62, 47, 55, 74, 32, 77, 86]} df1 = pd.DataFrame(df1, columns = ['Name', '']) # Sorting the DataFrame in Ascending Order of English Scoredf1.sort_values(by =['EnglishScore'], inplace = True)", "e": 26617, "s": 26257, "text": null }, { "code": null, "e": 26675, "s": 26617, "text": "If we print the above dataframe we get the below result :" }, { "code": null, "e": 26686, "s": 26675, "text": "Data Frame" }, { "code": null, "e": 26977, "s": 26686, "text": "Now we can find the Quantile Rank using the pandas function qcut() by passing the column name which is to be considered for the Rank, the value for parameter q which signifies the Number of quantiles. 10 for deciles, 4 for quartiles, etc. and labels = False to return the bins as Integers." }, { "code": null, "e": 27013, "s": 26977, "text": "Following is code for Quantile Rank" }, { "code": null, "e": 27021, "s": 27013, "text": "python3" }, { "code": "# codedf1['QuantileRank']= pd.qcut(df1['EnglishScore'], q = 4, labels = False)", "e": 27128, "s": 27021, "text": null }, { "code": null, "e": 27248, "s": 27128, "text": "And now if we print the dataframe we can see the new column QauntileRank ranking our data based on EnglishScore column." }, { "code": null, "e": 27262, "s": 27248, "text": "Quantile Rank" }, { "code": null, "e": 27311, "s": 27262, "text": "Similarly to calculate Decile Rank we set q = 10" }, { "code": null, "e": 27319, "s": 27311, "text": "python3" }, { "code": "# codedf1['DecileRank']= pd.qcut(df1['EnglishScore'], q = 10, labels = False)", "e": 27423, "s": 27319, "text": null }, { "code": null, "e": 27482, "s": 27423, "text": "Now if we print our DataFrame we get the following output." }, { "code": null, "e": 27493, "s": 27482, "text": "DecileRank" }, { "code": null, "e": 27589, "s": 27493, "text": "That is how we can use the Pandas qcut() method to calculate the various Quantiles on a column." }, { "code": null, "e": 27643, "s": 27589, "text": "The entire code for the above example is given below." }, { "code": null, "e": 27651, "s": 27643, "text": "python3" }, { "code": "# codeimport pandas as pd # Create a DataFramedf1 = {'Name':['George', 'Andrea', 'John', 'Helen', 'Ravi', 'Julia', 'Justin'], 'EnglishScore':[62, 47, 55, 74, 32, 77, 86]} df1 = pd.DataFrame(df1, columns =['Name', 'EnglishScore']) # Sorting the DataFrame in Ascending Order of English Score# Sorting just for the purpose of better data readability.df1.sort_values(by =['EnglishScore'], inplace = True) # Calculating Quantile Rankdf1['QuantileRank']= pd.qcut(df1['EnglishScore'], q = 4, labels = False) # Calculating Decile Rankdf1['DecileRank'] = pd.qcut(df1['EnglishScore'], q = 10, labels = False) # printing the dataframeprint(df1)", "e": 28306, "s": 27651, "text": null }, { "code": null, "e": 28315, "s": 28306, "text": "gabaa406" }, { "code": null, "e": 28332, "s": 28315, "text": "surinderdawra388" }, { "code": null, "e": 28356, "s": 28332, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28370, "s": 28356, "text": "Python-pandas" }, { "code": null, "e": 28377, "s": 28370, "text": "Python" }, { "code": null, "e": 28475, "s": 28377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28484, "s": 28475, "text": "Comments" }, { "code": null, "e": 28497, "s": 28484, "text": "Old Comments" }, { "code": null, "e": 28515, "s": 28497, "text": "Python Dictionary" }, { "code": null, "e": 28550, "s": 28515, "text": "Read a file line by line in Python" }, { "code": null, "e": 28572, "s": 28550, "text": "Enumerate() in Python" }, { "code": null, "e": 28604, "s": 28572, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28634, "s": 28604, "text": "Iterate over a list in Python" }, { "code": null, "e": 28676, "s": 28634, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28719, "s": 28676, "text": "Python program to convert a list to string" }, { "code": null, "e": 28745, "s": 28719, "text": "Python String | replace()" }, { "code": null, "e": 28789, "s": 28745, "text": "Reading and Writing to text files in Python" } ]
How to use tensorflow.js in react.js — Sentimental Analysis | by Manfye Goh | Towards Data Science
In March 2018, Google announced Tensorflow.js version 1.0, which enable developer to use machine learning (ML) models directly in browser or in Node.js via JavaScript. Since then I always want to use those fancy pre-trained model published by google in my project such as object detection, pose estimation and etc. It is however, those example and demo are shown in pure JavaScript and there are a less guide on how to use it in a react application. Inspired by Benson Rua code in Tensorflow.js Community “Show & Tell”. I had decided to write something on using create-react-app + tensorflow.js to encourage more people to join the community: The ultimate ending of this tutorial is to create a sentimental analysis calculator which can calculate the positivity (1) or negativity (0) of the written sentences. This is particular useful when you need to detect and prevent negative comments in your application. Demo app here Create a Create-React-App via the following commands in your terminal: npx create-react-app tfjs-sentimentcd tfjs-sentiment Install tensorflow.js as below: npm install @tensorflow/tfjs and start the app npm start The model we will be using here is the convolution neural network (CNN) model from tensorflow.js Sentimental Analysis example. It was trained on a set of 25,000 movie reviews from IMDB dataset, labelled as having positive or negative sentiment. The Model is available here and the metadata is available here. Take a look before we begin our coding. Basically the model is the trained neural network that will be the “special algorithm” that function to classified your sentences input into positive (1) and negative (0) class. We must fit the correct input into the model to enable our model to work smoothly. First thing you must know is the model work as a mathematical logic and being trained using mathematical input, it doesn’t understand “words” or “English language” literally. We must change our sentences into some mathematical input in order to get it works. Here come the metadata, the metadata convert the words input into numerical input for example: book >>> 274cutely >>> 68327 Note: As this tutorial focus on how to use in react, the theory behind these model can refer to word2vec or other NLP theories A sentences is coded into these numerical input by splitting each words into numerical token: this is a book >>> 14,9,6,274 Then the numerical tokens are changed to a fixed length (100) sequence in order to change to a 2d tensor 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,9,6,274 Finally, this sequence is then converted to a 2D tensor (basically a matrix) to feed into the model and the magic happens, the model will automatically classified the sentences into positive or negative statement. If you understand the logic above, it is easily convert it into action. 3.1 Load model and metadata import * as tf from '@tensorflow/tfjs';//Model and metadata URLconst url = {model: 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/model.json',metadata: 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/metadata.json'};async function loadModel(url) {try {const model = await tf.loadLayersModel(url.model);setModel(model);} catch (err) {console.log(err);}}async function loadMetadata(url) {try {const metadataJson = await fetch(url.metadata);const metadata = await metadataJson.json();setMetadata(metadata);} catch (err) {console.log(err);}}//React Hookconst [metadata, setMetadata] = useState();const [model, setModel] = useState();useEffect(()=>{tf.ready().then(()=>{loadModel(url)loadMetadata(url)});},[]) 3.2 Convert sentences to tensor input: Here we will setup a function to process the input text function by function according to theory above: Tokenize each word in the sentences: const inputText = text.trim().toLowerCase().replace(/(\.|\,|\!)/g, '').split(' '); Convert the alphabetical token to numerical token using metadata: //Convert the alphabetical token to numerical token using metadataconst OOV_INDEX = 2;const sequence = inputText.map(word => {let wordIndex = metadata.word_index[word] + metadata.index_from;if (wordIndex > metadata.vocabulary_size) {wordIndex = OOV_INDEX;}return wordIndex;}); Fix the sequence into fix length (truncation and padding) via a padSequences function const PAD_INDEX = 0;const padSequences = (sequences, maxLen, padding = 'pre', truncating = 'pre', value = PAD_INDEX) => {return sequences.map(seq => {if (seq.length > maxLen) {if (truncating === 'pre') {seq.splice(0, seq.length - maxLen);} else {seq.splice(maxLen, seq.length - maxLen);}}if (seq.length < maxLen) {const pad = [];for (let i = 0; i < maxLen - seq.length; ++i) {pad.push(value);}if (padding === 'pre') {seq = pad.concat(seq);} else {seq = seq.concat(pad);}}return seq;});}const paddedSequence = padSequences([sequence], metadata.max_len); Lastly, convert the paddedSequence into our tensor2D matrix const input = tf.tensor2d(paddedSequence, [1, metadata.max_len]); 3.3 Load tensor2D into our model After you get all the input right, it is the last easy step to use model.predict to classified your input. const predictOut = model.predict(input);const score = predictOut.dataSync()[0];predictOut.dispose();setScore(score)return score; 3.4 Setup TextField and Button Install material-ui via npm npm install @material-ui/core Then put the code below into your react app, a text box will appear and happy playing with the model! import {TextField,Button} from '@material-ui/core'const [testText, setText] = useState("");<TextFieldid="standard-read-only-input"label="Type your sentences here"onChange={(e)=> setText(e.target.value)}defaultValue=""value={testText}multilinerows={4}variant="outlined"/>{testText !== "" ?<Button style={{width:"20vh", height:"5vh"}} variant= "outlined" onClick={()=>getSentimentScore(testText)}>Calculate</Button>: <></>} As a react front-end developer and a data science student, I’m actively seeking a solution to integrate both my data science knowledge and react skill together. TF.js provide an ease to integrate deep learning model in react, the advantage of this is everything can be done in front end, we don’t need a backend server (e.g fastAPI, flask) or a server-less feature (e.g AWS lambda) to integrate our python based model in which we can take advantage of current free hosting provider such as netlify and vercel. The drawback of using TF.js is that without a server, all the model of deep learning must be downloaded before they can be use, some model are worth more than 100Mb which is a bad experience to the users as compared to the model that pre-loaded in the server. Lastly, the developer should choose the appropriate implementation of deep learning model according to the needs. Thank you for reading, Hope you enjoy it. Source code is available here
[ { "code": null, "e": 340, "s": 172, "text": "In March 2018, Google announced Tensorflow.js version 1.0, which enable developer to use machine learning (ML) models directly in browser or in Node.js via JavaScript." }, { "code": null, "e": 622, "s": 340, "text": "Since then I always want to use those fancy pre-trained model published by google in my project such as object detection, pose estimation and etc. It is however, those example and demo are shown in pure JavaScript and there are a less guide on how to use it in a react application." }, { "code": null, "e": 815, "s": 622, "text": "Inspired by Benson Rua code in Tensorflow.js Community “Show & Tell”. I had decided to write something on using create-react-app + tensorflow.js to encourage more people to join the community:" }, { "code": null, "e": 1083, "s": 815, "text": "The ultimate ending of this tutorial is to create a sentimental analysis calculator which can calculate the positivity (1) or negativity (0) of the written sentences. This is particular useful when you need to detect and prevent negative comments in your application." }, { "code": null, "e": 1097, "s": 1083, "text": "Demo app here" }, { "code": null, "e": 1168, "s": 1097, "text": "Create a Create-React-App via the following commands in your terminal:" }, { "code": null, "e": 1221, "s": 1168, "text": "npx create-react-app tfjs-sentimentcd tfjs-sentiment" }, { "code": null, "e": 1253, "s": 1221, "text": "Install tensorflow.js as below:" }, { "code": null, "e": 1283, "s": 1253, "text": "npm install @tensorflow/tfjs " }, { "code": null, "e": 1301, "s": 1283, "text": "and start the app" }, { "code": null, "e": 1311, "s": 1301, "text": "npm start" }, { "code": null, "e": 1556, "s": 1311, "text": "The model we will be using here is the convolution neural network (CNN) model from tensorflow.js Sentimental Analysis example. It was trained on a set of 25,000 movie reviews from IMDB dataset, labelled as having positive or negative sentiment." }, { "code": null, "e": 1660, "s": 1556, "text": "The Model is available here and the metadata is available here. Take a look before we begin our coding." }, { "code": null, "e": 1838, "s": 1660, "text": "Basically the model is the trained neural network that will be the “special algorithm” that function to classified your sentences input into positive (1) and negative (0) class." }, { "code": null, "e": 2275, "s": 1838, "text": "We must fit the correct input into the model to enable our model to work smoothly. First thing you must know is the model work as a mathematical logic and being trained using mathematical input, it doesn’t understand “words” or “English language” literally. We must change our sentences into some mathematical input in order to get it works. Here come the metadata, the metadata convert the words input into numerical input for example:" }, { "code": null, "e": 2304, "s": 2275, "text": "book >>> 274cutely >>> 68327" }, { "code": null, "e": 2431, "s": 2304, "text": "Note: As this tutorial focus on how to use in react, the theory behind these model can refer to word2vec or other NLP theories" }, { "code": null, "e": 2525, "s": 2431, "text": "A sentences is coded into these numerical input by splitting each words into numerical token:" }, { "code": null, "e": 2555, "s": 2525, "text": "this is a book >>> 14,9,6,274" }, { "code": null, "e": 2660, "s": 2555, "text": "Then the numerical tokens are changed to a fixed length (100) sequence in order to change to a 2d tensor" }, { "code": null, "e": 2863, "s": 2660, "text": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,9,6,274" }, { "code": null, "e": 3077, "s": 2863, "text": "Finally, this sequence is then converted to a 2D tensor (basically a matrix) to feed into the model and the magic happens, the model will automatically classified the sentences into positive or negative statement." }, { "code": null, "e": 3149, "s": 3077, "text": "If you understand the logic above, it is easily convert it into action." }, { "code": null, "e": 3177, "s": 3149, "text": "3.1 Load model and metadata" }, { "code": null, "e": 3919, "s": 3177, "text": "import * as tf from '@tensorflow/tfjs';//Model and metadata URLconst url = {model: 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/model.json',metadata: 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/metadata.json'};async function loadModel(url) {try {const model = await tf.loadLayersModel(url.model);setModel(model);} catch (err) {console.log(err);}}async function loadMetadata(url) {try {const metadataJson = await fetch(url.metadata);const metadata = await metadataJson.json();setMetadata(metadata);} catch (err) {console.log(err);}}//React Hookconst [metadata, setMetadata] = useState();const [model, setModel] = useState();useEffect(()=>{tf.ready().then(()=>{loadModel(url)loadMetadata(url)});},[])" }, { "code": null, "e": 3958, "s": 3919, "text": "3.2 Convert sentences to tensor input:" }, { "code": null, "e": 4062, "s": 3958, "text": "Here we will setup a function to process the input text function by function according to theory above:" }, { "code": null, "e": 4099, "s": 4062, "text": "Tokenize each word in the sentences:" }, { "code": null, "e": 4182, "s": 4099, "text": "const inputText = text.trim().toLowerCase().replace(/(\\.|\\,|\\!)/g, '').split(' ');" }, { "code": null, "e": 4248, "s": 4182, "text": "Convert the alphabetical token to numerical token using metadata:" }, { "code": null, "e": 4525, "s": 4248, "text": "//Convert the alphabetical token to numerical token using metadataconst OOV_INDEX = 2;const sequence = inputText.map(word => {let wordIndex = metadata.word_index[word] + metadata.index_from;if (wordIndex > metadata.vocabulary_size) {wordIndex = OOV_INDEX;}return wordIndex;});" }, { "code": null, "e": 4611, "s": 4525, "text": "Fix the sequence into fix length (truncation and padding) via a padSequences function" }, { "code": null, "e": 5164, "s": 4611, "text": "const PAD_INDEX = 0;const padSequences = (sequences, maxLen, padding = 'pre', truncating = 'pre', value = PAD_INDEX) => {return sequences.map(seq => {if (seq.length > maxLen) {if (truncating === 'pre') {seq.splice(0, seq.length - maxLen);} else {seq.splice(maxLen, seq.length - maxLen);}}if (seq.length < maxLen) {const pad = [];for (let i = 0; i < maxLen - seq.length; ++i) {pad.push(value);}if (padding === 'pre') {seq = pad.concat(seq);} else {seq = seq.concat(pad);}}return seq;});}const paddedSequence = padSequences([sequence], metadata.max_len);" }, { "code": null, "e": 5224, "s": 5164, "text": "Lastly, convert the paddedSequence into our tensor2D matrix" }, { "code": null, "e": 5290, "s": 5224, "text": "const input = tf.tensor2d(paddedSequence, [1, metadata.max_len]);" }, { "code": null, "e": 5323, "s": 5290, "text": "3.3 Load tensor2D into our model" }, { "code": null, "e": 5430, "s": 5323, "text": "After you get all the input right, it is the last easy step to use model.predict to classified your input." }, { "code": null, "e": 5559, "s": 5430, "text": "const predictOut = model.predict(input);const score = predictOut.dataSync()[0];predictOut.dispose();setScore(score)return score;" }, { "code": null, "e": 5590, "s": 5559, "text": "3.4 Setup TextField and Button" }, { "code": null, "e": 5618, "s": 5590, "text": "Install material-ui via npm" }, { "code": null, "e": 5648, "s": 5618, "text": "npm install @material-ui/core" }, { "code": null, "e": 5750, "s": 5648, "text": "Then put the code below into your react app, a text box will appear and happy playing with the model!" }, { "code": null, "e": 6172, "s": 5750, "text": "import {TextField,Button} from '@material-ui/core'const [testText, setText] = useState(\"\");<TextFieldid=\"standard-read-only-input\"label=\"Type your sentences here\"onChange={(e)=> setText(e.target.value)}defaultValue=\"\"value={testText}multilinerows={4}variant=\"outlined\"/>{testText !== \"\" ?<Button style={{width:\"20vh\", height:\"5vh\"}} variant= \"outlined\" onClick={()=>getSentimentScore(testText)}>Calculate</Button>: <></>}" }, { "code": null, "e": 6333, "s": 6172, "text": "As a react front-end developer and a data science student, I’m actively seeking a solution to integrate both my data science knowledge and react skill together." }, { "code": null, "e": 6682, "s": 6333, "text": "TF.js provide an ease to integrate deep learning model in react, the advantage of this is everything can be done in front end, we don’t need a backend server (e.g fastAPI, flask) or a server-less feature (e.g AWS lambda) to integrate our python based model in which we can take advantage of current free hosting provider such as netlify and vercel." }, { "code": null, "e": 6942, "s": 6682, "text": "The drawback of using TF.js is that without a server, all the model of deep learning must be downloaded before they can be use, some model are worth more than 100Mb which is a bad experience to the users as compared to the model that pre-loaded in the server." }, { "code": null, "e": 7056, "s": 6942, "text": "Lastly, the developer should choose the appropriate implementation of deep learning model according to the needs." }, { "code": null, "e": 7098, "s": 7056, "text": "Thank you for reading, Hope you enjoy it." } ]
Prolog - Basics
In this chapter, we will gain some basic knowledge about Prolog. So we will move on to the first step of our Prolog Programming. The different topics that will be covered in this chapter are − Knowledge Base − This is one of the fundamental parts of Logic Programming. We will see in detail about the Knowledge Base, and how it helps in logic programming. Facts, Rules and Queries − These are the building blocks of logic programming. We will get some detailed knowledge about facts and rules, and also see some kind of queries that will be used in logic programming. Here, we will discuss about the essential building blocks of logic programming. These building blocks are Facts, Rules and the Queries. We can define fact as an explicit relationship between objects, and properties these objects might have. So facts are unconditionally true in nature. Suppose we have some facts as given below − Tom is a cat Tom is a cat Kunal loves to eat Pasta Kunal loves to eat Pasta Hair is black Hair is black Nawaz loves to play games Nawaz loves to play games Pratyusha is lazy. Pratyusha is lazy. So these are some facts, that are unconditionally true. These are actually statements, that we have to consider as true. Following are some guidelines to write facts − Names of properties/relationships begin with lower case letters. Names of properties/relationships begin with lower case letters. The relationship name appears as the first term. The relationship name appears as the first term. Objects appear as comma-separated arguments within parentheses. Objects appear as comma-separated arguments within parentheses. A period "." must end a fact. A period "." must end a fact. Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’). Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’). phoneno(agnibha, 1122334455). is also called a predicate or clause. phoneno(agnibha, 1122334455). is also called a predicate or clause. The syntax for facts is as follows − relation(object1,object2...). Following is an example of the above concept − cat(tom). loves_to_eat(kunal,pasta). of_color(hair,black). loves_to_play_games(nawaz). lazy(pratyusha). We can define rule as an implicit relationship between objects. So facts are conditionally true. So when one associated condition is true, then the predicate is also true. Suppose we have some rules as given below − Lili is happy if she dances. Lili is happy if she dances. Tom is hungry if he is searching for food. Tom is hungry if he is searching for food. Jack and Bili are friends if both of them love to play cricket. Jack and Bili are friends if both of them love to play cricket. will go to play if school is closed, and he is free. will go to play if school is closed, and he is free. So these are some rules that are conditionally true, so when the right hand side is true, then the left hand side is also true. Here the symbol ( :- ) will be pronounced as “If”, or “is implied by”. This is also known as neck symbol, the LHS of this symbol is called the Head, and right hand side is called Body. Here we can use comma (,) which is known as conjunction, and we can also use semicolon, that is known as disjunction. rule_name(object1, object2, ...) :- fact/rule(object1, object2, ...) Suppose a clause is like : P :- Q;R. This can also be written as P :- Q. P :- R. If one clause is like : P :- Q,R;S,T,U. Is understood as P :- (Q,R);(S,T,U). Or can also be written as: P :- Q,R. P :- S,T,U. happy(lili) :- dances(lili). hungry(tom) :- search_for_food(tom). friends(jack, bili) :- lovesCricket(jack), lovesCricket(bili). goToPlay(ryan) :- isClosed(school), free(ryan). Queries are some questions on the relationships between objects and object properties. So question can be anything, as given below − Is tom a cat? Is tom a cat? Does Kunal love to eat pasta? Does Kunal love to eat pasta? Is Lili happy? Is Lili happy? Will Ryan go to play? Will Ryan go to play? So according to these queries, Logic programming language can find the answer and return them. In this section, we will see what knowledge base in logic programming is. Well, as we know there are three main components in logic programming − Facts, Rules and Queries. Among these three if we collect the facts and rules as a whole then that forms a Knowledge Base. So we can say that the knowledge base is a collection of facts and rules. Now, we will see how to write some knowledge bases. Suppose we have our very first knowledge base called KB1. Here in the KB1, we have some facts. The facts are used to state things, that are unconditionally true of the domain of interest. Suppose we have some knowledge, that Priya, Tiyasha, and Jaya are three girls, among them, Priya can cook. Let’s try to write these facts in a more generic way as shown below − girl(priya). girl(tiyasha). girl(jaya). can_cook(priya). Note − Here we have written the name in lowercase letters, because in Prolog, a string starting with uppercase letter indicates a variable. Now we can use this knowledge base by posing some queries. “Is priya a girl?”, it will reply “yes”, “is jamini a girl?” then it will answer “No”, because it does not know who jamini is. Our next question is “Can Priya cook?”, it will say “yes”, but if we ask the same question for Jaya, it will say “No”. GNU Prolog 1.4.5 (64 bits) Compiled Jul 14 2018, 13:19:42 with x86_64-w64-mingw32-gcc By Daniel Diaz Copyright (C) 1999-2018 Daniel Diaz | ?- change_directory('D:/TP Prolog/Sample_Codes'). yes | ?- [kb1] . compiling D:/TP Prolog/Sample_Codes/kb1.pl for byte code... D:/TP Prolog/Sample_Codes/kb1.pl compiled, 3 lines read - 489 bytes written, 10 ms yes | ?- girl(priya) . yes | ?- girl(jamini). no | ?- can_cook(priya). yes | ?- can_cook(jaya). no | ?- Let us see another knowledge base, where we have some rules. Rules contain some information that are conditionally true about the domain of interest. Suppose our knowledge base is as follows − sing_a_song(ananya). listens_to_music(rohit). listens_to_music(ananya) :- sing_a_song(ananya). happy(ananya) :- sing_a_song(ananya). happy(rohit) :- listens_to_music(rohit). playes_guitar(rohit) :- listens_to_music(rohit). So there are some facts and rules given above. The first two are facts, but the rest are rules. As we know that Ananya sings a song, this implies she also listens to music. So if we ask “Does Ananya listen to music?”, the answer will be true. Similarly, “is Rohit happy?”, this will also be true because he listens to music. But if our question is “does Ananya play guitar?”, then according to the knowledge base, it will say “No”. So these are some examples of queries based on this Knowledge base. | ?- [kb2]. compiling D:/TP Prolog/Sample_Codes/kb2.pl for byte code... D:/TP Prolog/Sample_Codes/kb2.pl compiled, 6 lines read - 1066 bytes written, 15 ms yes | ?- happy(rohit). yes | ?- sing_a_song(rohit). no | ?- sing_a_song(ananya). yes | ?- playes_guitar(rohit). yes | ?- playes_guitar(ananya). no | ?- listens_to_music(ananya). yes | ?- The facts and rules of Knowledge Base 3 are as follows − can_cook(priya). can_cook(jaya). can_cook(tiyasha). likes(priya,jaya) :- can_cook(jaya). likes(priya,tiyasha) :- can_cook(tiyasha). Suppose we want to see the members who can cook, we can use one variable in our query. The variables should start with uppercase letters. In the result, it will show one by one. If we press enter, then it will come out, otherwise if we press semicolon (;), then it will show the next result. Let us see one practical demonstration output to understand how it works. | ?- [kb3]. compiling D:/TP Prolog/Sample_Codes/kb3.pl for byte code... D:/TP Prolog/Sample_Codes/kb3.pl compiled, 5 lines read - 737 bytes written, 22 ms warning: D:/TP Prolog/Sample_Codes/kb3.pl:1: redefining procedure can_cook/1 D:/TP Prolog/Sample_Codes/kb1.pl:4: previous definition yes | ?- can_cook(X). X = priya ? ; X = jaya ? ; X = tiyasha yes | ?- likes(priya,X). X = jaya ? ; X = tiyasha yes | ?- 65 Lectures 5 hours Arnab Chakraborty 78 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2221, "s": 2092, "text": "In this chapter, we will gain some basic knowledge about Prolog. So we will move on to the first step of our Prolog Programming." }, { "code": null, "e": 2285, "s": 2221, "text": "The different topics that will be covered in this chapter are −" }, { "code": null, "e": 2448, "s": 2285, "text": "Knowledge Base − This is one of the fundamental parts of Logic Programming. We will see in detail about the Knowledge Base, and how it helps in logic programming." }, { "code": null, "e": 2660, "s": 2448, "text": "Facts, Rules and Queries − These are the building blocks of logic programming. We will get some detailed knowledge about facts and rules, and also see some kind of queries that will be used in logic programming." }, { "code": null, "e": 2796, "s": 2660, "text": "Here, we will discuss about the essential building blocks of logic programming. These building blocks are Facts, Rules and the Queries." }, { "code": null, "e": 2990, "s": 2796, "text": "We can define fact as an explicit relationship between objects, and properties these objects might have. So facts are unconditionally true in nature. Suppose we have some facts as given below −" }, { "code": null, "e": 3003, "s": 2990, "text": "Tom is a cat" }, { "code": null, "e": 3016, "s": 3003, "text": "Tom is a cat" }, { "code": null, "e": 3041, "s": 3016, "text": "Kunal loves to eat Pasta" }, { "code": null, "e": 3066, "s": 3041, "text": "Kunal loves to eat Pasta" }, { "code": null, "e": 3080, "s": 3066, "text": "Hair is black" }, { "code": null, "e": 3094, "s": 3080, "text": "Hair is black" }, { "code": null, "e": 3120, "s": 3094, "text": "Nawaz loves to play games" }, { "code": null, "e": 3146, "s": 3120, "text": "Nawaz loves to play games" }, { "code": null, "e": 3165, "s": 3146, "text": "Pratyusha is lazy." }, { "code": null, "e": 3184, "s": 3165, "text": "Pratyusha is lazy." }, { "code": null, "e": 3305, "s": 3184, "text": "So these are some facts, that are unconditionally true. These are actually statements, that we have to consider as true." }, { "code": null, "e": 3352, "s": 3305, "text": "Following are some guidelines to write facts −" }, { "code": null, "e": 3417, "s": 3352, "text": "Names of properties/relationships begin with lower case letters." }, { "code": null, "e": 3482, "s": 3417, "text": "Names of properties/relationships begin with lower case letters." }, { "code": null, "e": 3531, "s": 3482, "text": "The relationship name appears as the first term." }, { "code": null, "e": 3580, "s": 3531, "text": "The relationship name appears as the first term." }, { "code": null, "e": 3644, "s": 3580, "text": "Objects appear as comma-separated arguments within parentheses." }, { "code": null, "e": 3708, "s": 3644, "text": "Objects appear as comma-separated arguments within parentheses." }, { "code": null, "e": 3738, "s": 3708, "text": "A period \".\" must end a fact." }, { "code": null, "e": 3768, "s": 3738, "text": "A period \".\" must end a fact." }, { "code": null, "e": 3936, "s": 3768, "text": "Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’)." }, { "code": null, "e": 4104, "s": 3936, "text": "Objects also begin with lower case letters. They also can begin with digits (like 1234), and can be strings of characters enclosed in quotes e.g. color(penink, ‘red’)." }, { "code": null, "e": 4172, "s": 4104, "text": "phoneno(agnibha, 1122334455). is also called a predicate or clause." }, { "code": null, "e": 4240, "s": 4172, "text": "phoneno(agnibha, 1122334455). is also called a predicate or clause." }, { "code": null, "e": 4277, "s": 4240, "text": "The syntax for facts is as follows −" }, { "code": null, "e": 4308, "s": 4277, "text": "relation(object1,object2...).\n" }, { "code": null, "e": 4355, "s": 4308, "text": "Following is an example of the above concept −" }, { "code": null, "e": 4460, "s": 4355, "text": "cat(tom).\nloves_to_eat(kunal,pasta).\nof_color(hair,black).\nloves_to_play_games(nawaz).\nlazy(pratyusha).\n" }, { "code": null, "e": 4676, "s": 4460, "text": "We can define rule as an implicit relationship between objects. So facts are conditionally true. So when one associated condition is true, then the predicate is also true. Suppose we have some rules as given below −" }, { "code": null, "e": 4705, "s": 4676, "text": "Lili is happy if she dances." }, { "code": null, "e": 4734, "s": 4705, "text": "Lili is happy if she dances." }, { "code": null, "e": 4777, "s": 4734, "text": "Tom is hungry if he is searching for food." }, { "code": null, "e": 4820, "s": 4777, "text": "Tom is hungry if he is searching for food." }, { "code": null, "e": 4884, "s": 4820, "text": "Jack and Bili are friends if both of them love to play cricket." }, { "code": null, "e": 4948, "s": 4884, "text": "Jack and Bili are friends if both of them love to play cricket." }, { "code": null, "e": 5001, "s": 4948, "text": "will go to play if school is closed, and he is free." }, { "code": null, "e": 5054, "s": 5001, "text": "will go to play if school is closed, and he is free." }, { "code": null, "e": 5182, "s": 5054, "text": "So these are some rules that are conditionally true, so when the right hand side is true, then the left hand side is also true." }, { "code": null, "e": 5485, "s": 5182, "text": "Here the symbol ( :- ) will be pronounced as “If”, or “is implied by”. This is also known as neck symbol, the LHS of this symbol is called the Head, and right hand side is called Body. Here we can use comma (,) which is known as conjunction, and we can also use semicolon, that is known as disjunction." }, { "code": null, "e": 5765, "s": 5485, "text": "rule_name(object1, object2, ...) :- fact/rule(object1,\n object2, ...)\nSuppose a clause is like :\nP :- Q;R.\nThis can also be written as\nP :- Q.\nP :- R.\n\nIf one clause is like :\nP :- Q,R;S,T,U.\n\nIs understood as\nP :- (Q,R);(S,T,U).\nOr can also be written as:\nP :- Q,R.\nP :- S,T,U.\n" }, { "code": null, "e": 5943, "s": 5765, "text": "happy(lili) :- dances(lili).\nhungry(tom) :- search_for_food(tom).\nfriends(jack, bili) :- lovesCricket(jack), lovesCricket(bili).\ngoToPlay(ryan) :- isClosed(school), free(ryan).\n" }, { "code": null, "e": 6076, "s": 5943, "text": "Queries are some questions on the relationships between objects and object properties. So question can be anything, as given below −" }, { "code": null, "e": 6090, "s": 6076, "text": "Is tom a cat?" }, { "code": null, "e": 6104, "s": 6090, "text": "Is tom a cat?" }, { "code": null, "e": 6134, "s": 6104, "text": "Does Kunal love to eat pasta?" }, { "code": null, "e": 6164, "s": 6134, "text": "Does Kunal love to eat pasta?" }, { "code": null, "e": 6179, "s": 6164, "text": "Is Lili happy?" }, { "code": null, "e": 6194, "s": 6179, "text": "Is Lili happy?" }, { "code": null, "e": 6216, "s": 6194, "text": "Will Ryan go to play?" }, { "code": null, "e": 6238, "s": 6216, "text": "Will Ryan go to play?" }, { "code": null, "e": 6333, "s": 6238, "text": "So according to these queries, Logic programming language can find the answer and return them." }, { "code": null, "e": 6407, "s": 6333, "text": "In this section, we will see what knowledge base in logic programming is." }, { "code": null, "e": 6676, "s": 6407, "text": "Well, as we know there are three main components in logic programming − Facts, Rules and Queries. Among these three if we collect the facts and rules as a whole then that forms a Knowledge Base. So we can say that the knowledge base is a collection of facts and rules." }, { "code": null, "e": 6916, "s": 6676, "text": "Now, we will see how to write some knowledge bases. Suppose we have our very first knowledge base called KB1. Here in the KB1, we have some facts. The facts are used to state things, that are unconditionally true of the domain of interest." }, { "code": null, "e": 7093, "s": 6916, "text": "Suppose we have some knowledge, that Priya, Tiyasha, and Jaya are three girls, among them, Priya can cook. Let’s try to write these facts in a more generic way as shown below −" }, { "code": null, "e": 7151, "s": 7093, "text": "girl(priya).\ngirl(tiyasha).\ngirl(jaya).\ncan_cook(priya).\n" }, { "code": null, "e": 7291, "s": 7151, "text": "Note − Here we have written the name in lowercase letters, because in Prolog, a string starting with uppercase letter indicates a variable." }, { "code": null, "e": 7596, "s": 7291, "text": "Now we can use this knowledge base by posing some queries. “Is priya a girl?”, it will reply “yes”, “is jamini a girl?” then it will answer “No”, because it does not know who jamini is. Our next question is “Can Priya cook?”, it will say “yes”, but if we ask the same question for Jaya, it will say “No”." }, { "code": null, "e": 8056, "s": 7596, "text": "GNU Prolog 1.4.5 (64 bits)\nCompiled Jul 14 2018, 13:19:42 with x86_64-w64-mingw32-gcc\nBy Daniel Diaz\nCopyright (C) 1999-2018 Daniel Diaz\n| ?- change_directory('D:/TP Prolog/Sample_Codes').\n\nyes\n| ?- [kb1]\n.\ncompiling D:/TP Prolog/Sample_Codes/kb1.pl for byte code...\nD:/TP Prolog/Sample_Codes/kb1.pl compiled, 3 lines read - 489 bytes written, 10 ms\n\nyes\n| ?- girl(priya)\n.\n\nyes\n| ?- girl(jamini).\n\nno\n| ?- can_cook(priya).\n\nyes\n| ?- can_cook(jaya).\n\nno\n| ?-\n" }, { "code": null, "e": 8249, "s": 8056, "text": "Let us see another knowledge base, where we have some rules. Rules contain some information that are conditionally true about the domain of interest. Suppose our knowledge base is as follows −" }, { "code": null, "e": 8474, "s": 8249, "text": "sing_a_song(ananya).\nlistens_to_music(rohit).\n\nlistens_to_music(ananya) :- sing_a_song(ananya).\nhappy(ananya) :- sing_a_song(ananya).\nhappy(rohit) :- listens_to_music(rohit).\nplayes_guitar(rohit) :- listens_to_music(rohit).\n" }, { "code": null, "e": 8974, "s": 8474, "text": "So there are some facts and rules given above. The first two are facts, but the rest are rules. As we know that Ananya sings a song, this implies she also listens to music. So if we ask “Does Ananya listen to music?”, the answer will be true. Similarly, “is Rohit happy?”, this will also be true because he listens to music. But if our question is “does Ananya play guitar?”, then according to the knowledge base, it will say “No”. So these are some examples of queries based on this Knowledge base." }, { "code": null, "e": 9325, "s": 8974, "text": "| ?- [kb2].\ncompiling D:/TP Prolog/Sample_Codes/kb2.pl for byte code...\nD:/TP Prolog/Sample_Codes/kb2.pl compiled, 6 lines read - 1066 bytes written, 15 ms\n\nyes\n| ?- happy(rohit).\n\nyes\n| ?- sing_a_song(rohit).\n\nno\n| ?- sing_a_song(ananya).\n\nyes\n| ?- playes_guitar(rohit).\n\nyes\n| ?- playes_guitar(ananya).\n\nno\n| ?- listens_to_music(ananya).\n\nyes\n| ?-\n" }, { "code": null, "e": 9382, "s": 9325, "text": "The facts and rules of Knowledge Base 3 are as follows −" }, { "code": null, "e": 9516, "s": 9382, "text": "can_cook(priya).\ncan_cook(jaya).\ncan_cook(tiyasha).\n\nlikes(priya,jaya) :- can_cook(jaya).\nlikes(priya,tiyasha) :- can_cook(tiyasha).\n" }, { "code": null, "e": 9808, "s": 9516, "text": "Suppose we want to see the members who can cook, we can use one variable in our query. The variables should start with uppercase letters. In the result, it will show one by one. If we press enter, then it will come out, otherwise if we press semicolon (;), then it will show the next result." }, { "code": null, "e": 9882, "s": 9808, "text": "Let us see one practical demonstration output to understand how it works." }, { "code": null, "e": 10317, "s": 9882, "text": "| ?- [kb3].\ncompiling D:/TP Prolog/Sample_Codes/kb3.pl for byte code...\nD:/TP Prolog/Sample_Codes/kb3.pl compiled, 5 lines read - 737 bytes written, 22 ms\nwarning: D:/TP Prolog/Sample_Codes/kb3.pl:1: redefining procedure can_cook/1\n D:/TP Prolog/Sample_Codes/kb1.pl:4: previous definition\n \nyes\n| ?- can_cook(X).\n\nX = priya ? ;\n\nX = jaya ? ;\n\nX = tiyasha\n\nyes\n| ?- likes(priya,X).\n\nX = jaya ? ;\n\nX = tiyasha\n\nyes\n| ?-\n" }, { "code": null, "e": 10350, "s": 10317, "text": "\n 65 Lectures \n 5 hours \n" }, { "code": null, "e": 10369, "s": 10350, "text": " Arnab Chakraborty" }, { "code": null, "e": 10402, "s": 10369, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 10421, "s": 10402, "text": " Arnab Chakraborty" }, { "code": null, "e": 10428, "s": 10421, "text": " Print" }, { "code": null, "e": 10439, "s": 10428, "text": " Add Notes" } ]
KnockoutJS - If Binding
This binding allows you to present the conditionally. If the specified condition is true, then show data, else don't show. if binding is similar to visible binding. Difference being, in visible binding the underlying HTML markup actually stays on DOM and is made visible based on the condition whereas in if binding, HTML markup is added or removed from DOM based on the condition. Syntax if: <binding-condition> Parameters Parameter is a condition you want to evaluate. If the condition evaluates to true or true-like value, then the given HTML markup will be processed. Else, it will be removed from DOM. Parameter is a condition you want to evaluate. If the condition evaluates to true or true-like value, then the given HTML markup will be processed. Else, it will be removed from DOM. If the condition in the parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be added or removed based on the condition result. If the condition in the parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be added or removed based on the condition result. Example Let us take a look at the following example which demonstrates the use of if binding. <!DOCTYPE html> <head> <title>KnockoutJS if binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type = "text/javascript"></script> </head> <body> <p><strong>Product details</strong></p> <table border = "1"> <thead> <th>Product Name</th><th>Price</th><th>Nature</th> </thead> <tbody data-bind = "foreach: productArray "> <tr> <td><span data-bind = "text: productName"></span></td> <td><span data-bind = "text: price"></span></td> <td data-bind = "if: $data.price > 100 ">Expensive</td> </tr> </tbody> </table> <script type = "text/javascript"> function AppViewModel() { self = this; self.productArray = ko.observableArray ([ {productName: 'Milk', price: 100}, {productName: 'Oil', price: 10}, {productName: 'Shampoo', price: 1200} ]); }; var vm = new AppViewModel(); ko.applyBindings(vm); </script> </body> </html> Output Let's carry out the following steps to see how the above code works − Save the above code in if-bind.htm file. Save the above code in if-bind.htm file. Open this HTML file in a browser. Open this HTML file in a browser. This example will populate the third column which talks about the products’ nature (expensive or not) depending on the price. Note that the individual property is accessed using $data binding context. This example will populate the third column which talks about the products’ nature (expensive or not) depending on the price. Note that the individual property is accessed using $data binding context. Product details There might be a situation when it is not possible to place data-binding inside a DOM element. Essential checking can still be performed with the help of container-less syntax based on the comment tags shown as follows. The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax and binds the data as if it is a real container. Example Let's us take a look at the following example which demonstrates the use of container-less syntax. <!DOCTYPE html> <head> <title>KnockoutJS if binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type = "text/javascript"></script> </head> <body> <ul> <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> <li>Thursday</li> <li>Friday</li> <!-- ko {if: weekend} --> <li>Saturday - check if it is weekend.</li> <li>Sunday</li> <!-- /ko --> </ul> <script> function AppViewModel() { this.weekend = false; } var vm = new AppViewModel(); ko.applyBindings(vm); </script> </body> </html> Output Let's carry out the following steps to see how the above code works − Save the above code in if-container-less.htm file. Save the above code in if-container-less.htm file. Open this HTML file in a browser. Open this HTML file in a browser. Monday Tuesday Wednesday Thursday Friday 38 Lectures 2 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 1975, "s": 1852, "text": "This binding allows you to present the conditionally. If the specified condition is true, then show data, else don't show." }, { "code": null, "e": 2234, "s": 1975, "text": "if binding is similar to visible binding. Difference being, in visible binding the underlying HTML markup actually stays on DOM and is made visible based on the condition whereas in if binding, HTML markup is added or removed from DOM based on the condition." }, { "code": null, "e": 2241, "s": 2234, "text": "Syntax" }, { "code": null, "e": 2266, "s": 2241, "text": "if: <binding-condition>\n" }, { "code": null, "e": 2277, "s": 2266, "text": "Parameters" }, { "code": null, "e": 2460, "s": 2277, "text": "Parameter is a condition you want to evaluate. If the condition evaluates to true or true-like value, then the given HTML markup will be processed. Else, it will be removed from DOM." }, { "code": null, "e": 2643, "s": 2460, "text": "Parameter is a condition you want to evaluate. If the condition evaluates to true or true-like value, then the given HTML markup will be processed. Else, it will be removed from DOM." }, { "code": null, "e": 2869, "s": 2643, "text": "If the condition in the parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be added or removed based on the condition result." }, { "code": null, "e": 3095, "s": 2869, "text": "If the condition in the parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be added or removed based on the condition result." }, { "code": null, "e": 3103, "s": 3095, "text": "Example" }, { "code": null, "e": 3189, "s": 3103, "text": "Let us take a look at the following example which demonstrates the use of if binding." }, { "code": null, "e": 4391, "s": 3189, "text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS if binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <p><strong>Product details</strong></p>\n \n <table border = \"1\">\n <thead>\n <th>Product Name</th><th>Price</th><th>Nature</th>\n </thead>\n \n <tbody data-bind = \"foreach: productArray \">\n <tr>\n <td><span data-bind = \"text: productName\"></span></td>\n <td><span data-bind = \"text: price\"></span></td>\n <td data-bind = \"if: $data.price > 100 \">Expensive</td>\n </tr>\n </tbody>\n </table>\n\n <script type = \"text/javascript\">\n function AppViewModel() {\n self = this;\n \n self.productArray = ko.observableArray ([\n {productName: 'Milk', price: 100},\n {productName: 'Oil', price: 10},\n {productName: 'Shampoo', price: 1200}\n ]);\n };\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4398, "s": 4391, "text": "Output" }, { "code": null, "e": 4468, "s": 4398, "text": "Let's carry out the following steps to see how the above code works −" }, { "code": null, "e": 4509, "s": 4468, "text": "Save the above code in if-bind.htm file." }, { "code": null, "e": 4550, "s": 4509, "text": "Save the above code in if-bind.htm file." }, { "code": null, "e": 4584, "s": 4550, "text": "Open this HTML file in a browser." }, { "code": null, "e": 4618, "s": 4584, "text": "Open this HTML file in a browser." }, { "code": null, "e": 4819, "s": 4618, "text": "This example will populate the third column which talks about the products’ nature (expensive or not) depending on the price. Note that the individual property is accessed using $data binding context." }, { "code": null, "e": 5020, "s": 4819, "text": "This example will populate the third column which talks about the products’ nature (expensive or not) depending on the price. Note that the individual property is accessed using $data binding context." }, { "code": null, "e": 5036, "s": 5020, "text": "Product details" }, { "code": null, "e": 5256, "s": 5036, "text": "There might be a situation when it is not possible to place data-binding inside a DOM element. Essential checking can still be performed with the help of container-less syntax based on the comment tags shown as follows." }, { "code": null, "e": 5392, "s": 5256, "text": "The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax and binds the data as if it is a real container." }, { "code": null, "e": 5400, "s": 5392, "text": "Example" }, { "code": null, "e": 5499, "s": 5400, "text": "Let's us take a look at the following example which demonstrates the use of container-less syntax." }, { "code": null, "e": 6230, "s": 5499, "text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS if binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <ul>\n <li>Monday</li>\n <li>Tuesday</li>\n <li>Wednesday</li>\n <li>Thursday</li>\n <li>Friday</li>\n <!-- ko {if: weekend} -->\n <li>Saturday - check if it is weekend.</li>\n <li>Sunday</li>\n <!-- /ko -->\n </ul>\n \n <script>\n function AppViewModel() {\n this.weekend = false;\n }\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 6237, "s": 6230, "text": "Output" }, { "code": null, "e": 6307, "s": 6237, "text": "Let's carry out the following steps to see how the above code works −" }, { "code": null, "e": 6358, "s": 6307, "text": "Save the above code in if-container-less.htm file." }, { "code": null, "e": 6409, "s": 6358, "text": "Save the above code in if-container-less.htm file." }, { "code": null, "e": 6443, "s": 6409, "text": "Open this HTML file in a browser." }, { "code": null, "e": 6477, "s": 6443, "text": "Open this HTML file in a browser." }, { "code": null, "e": 6484, "s": 6477, "text": "Monday" }, { "code": null, "e": 6492, "s": 6484, "text": "Tuesday" }, { "code": null, "e": 6502, "s": 6492, "text": "Wednesday" }, { "code": null, "e": 6511, "s": 6502, "text": "Thursday" }, { "code": null, "e": 6518, "s": 6511, "text": "Friday" }, { "code": null, "e": 6551, "s": 6518, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 6571, "s": 6551, "text": " Skillbakerystudios" }, { "code": null, "e": 6578, "s": 6571, "text": " Print" }, { "code": null, "e": 6589, "s": 6578, "text": " Add Notes" } ]
Ugly Numbers
Ugly numbers are those number whose prime factors are 2, 3 or 5. From 1 to 15, there are 11 ugly numbers 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15. The numbers 7, 11, 13 are not ugly because they are prime. The number 14 is not ugly because in its prime factor the 7 will come. In this program, we will try to find the nth ugly number. Input: Take the term number. Say it is 10 Output: The 10th ugly number is 12 getUglyNumbers(n) Input: The number of terms. Output: Find nth Ugly numbers. Begin define array named uglyNum of size n i2 := 0, i3 := 0, i5 := 0 next2mul := 2, next3mul := 3, next5Mul := 5 next := 1 ugluNum[0] := 1 for i := 1 to n, do next := minimum of next2Mul, next3Mul and next5Mul uglyNum[i] := next if next = next2Mul, then i2 := i2 + 1 next2mul := uglyNum[i2] * 2 if next = next3Mul, then i3 := i3 + 1 next3mul := uglyNum[i3] * 3 if next = next5Mul, then i5 := i5 + 1 next5mul := uglyNum[i5] * 5 done return next End # include<iostream> using namespace std; int min(int x, int y, int z) { //find smallest among three numbers if(x < y) { if(x < z) return x; else return z; }else { if(y < z) return y; else return z; } } int getUglyNum(int n) { int uglyNum[n]; // To store ugly numbers int i2 = 0, i3 = 0, i5 = 0; //find next multiple as 1*2, 1*3, 1*5 int next2mul = 2; int next3mul = 3; int next5mul = 5; int next = 1; //initially the ugly number is 1 uglyNum[0] = 1; for (int i=1; i<n; i++) { next = min(next2mul, next3mul, next5mul); //find next ugly number uglyNum[i] = next; if (next == next2mul) { i2++; //increase iterator of ugly numbers whose factor is 2 next2mul = uglyNum[i2]*2; } if (next == next3mul) { i3++; //increase iterator of ugly numbers whose factor is 3 next3mul = uglyNum[i3]*3; } if (next == next5mul) { i5++; //increase iterator of ugly numbers whose factor is 5 next5mul = uglyNum[i5]*5; } } return next; //the nth ugly number } int main() { int n; cout << "Enter term: "; cin >> n; cout << n << "th Ugly number is: " << getUglyNum(n) << endl; } Enter term: 10 10th Ugly number is: 12
[ { "code": null, "e": 1333, "s": 1062, "text": "Ugly numbers are those number whose prime factors are 2, 3 or 5. From 1 to 15, there are 11 ugly numbers 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15. The numbers 7, 11, 13 are not ugly because they are prime. The number 14 is not ugly because in its prime factor the 7 will come." }, { "code": null, "e": 1391, "s": 1333, "text": "In this program, we will try to find the nth ugly number." }, { "code": null, "e": 1468, "s": 1391, "text": "Input:\nTake the term number. Say it is 10\nOutput:\nThe 10th ugly number is 12" }, { "code": null, "e": 1486, "s": 1468, "text": "getUglyNumbers(n)" }, { "code": null, "e": 1514, "s": 1486, "text": "Input: The number of terms." }, { "code": null, "e": 1545, "s": 1514, "text": "Output: Find nth Ugly numbers." }, { "code": null, "e": 2102, "s": 1545, "text": "Begin\n define array named uglyNum of size n\n i2 := 0, i3 := 0, i5 := 0\n next2mul := 2, next3mul := 3, next5Mul := 5\n next := 1\n ugluNum[0] := 1\n\n for i := 1 to n, do\n next := minimum of next2Mul, next3Mul and next5Mul\n uglyNum[i] := next\n if next = next2Mul, then\n i2 := i2 + 1\n next2mul := uglyNum[i2] * 2\n if next = next3Mul, then\n i3 := i3 + 1\n next3mul := uglyNum[i3] * 3\n if next = next5Mul, then\n i5 := i5 + 1\n next5mul := uglyNum[i5] * 5\n done\n return next\nEnd" }, { "code": null, "e": 3461, "s": 2102, "text": "# include<iostream>\nusing namespace std;\n\nint min(int x, int y, int z) { //find smallest among three numbers\n if(x < y) {\n if(x < z)\n return x;\n else\n return z;\n }else {\n if(y < z)\n return y;\n else\n return z;\n }\n}\n\nint getUglyNum(int n) {\n int uglyNum[n]; // To store ugly numbers\n int i2 = 0, i3 = 0, i5 = 0;\n\n //find next multiple as 1*2, 1*3, 1*5\n\n int next2mul = 2;\n int next3mul = 3;\n int next5mul = 5;\n int next = 1; //initially the ugly number is 1\n\n uglyNum[0] = 1;\n\n for (int i=1; i<n; i++) {\n next = min(next2mul, next3mul, next5mul); //find next ugly number\n uglyNum[i] = next;\n\n if (next == next2mul) {\n i2++; //increase iterator of ugly numbers whose factor is 2\n next2mul = uglyNum[i2]*2;\n }\n\n if (next == next3mul) {\n i3++; //increase iterator of ugly numbers whose factor is 3\n next3mul = uglyNum[i3]*3;\n }\n\n if (next == next5mul) {\n i5++; //increase iterator of ugly numbers whose factor is 5\n next5mul = uglyNum[i5]*5;\n }\n }\n return next; //the nth ugly number\n}\n\nint main() {\n int n;\n cout << \"Enter term: \"; cin >> n;\n cout << n << \"th Ugly number is: \" << getUglyNum(n) << endl;\n}" }, { "code": null, "e": 3500, "s": 3461, "text": "Enter term: 10\n10th Ugly number is: 12" } ]
Smallest element in an array that is repeated exactly 'k' times. - GeeksforGeeks
31 Jan, 2022 Given an array of size n, the goal is to find out the smallest number that is repeated exactly ‘k’ times where k > 0? Assume that array has only positive integers and 1 <= arr[i] < 1000 for each i = 0 to n -1.Examples: Input : arr[] = {2 2 1 3 1} k = 2 Output: 1 Explanation: Here in array, 2 is repeated 2 times 1 is repeated 2 times 3 is repeated 1 time Hence 2 and 1 both are repeated 'k' times i.e 2 and min(2, 1) is 1 Input : arr[] = {3 5 3 2} k = 1 Output : 2 Explanation: Both 2 and 5 are repeating 1 time but min(5, 2) is 2 Simple Approach: A simple approach is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the same element is present on right side of it. If present increase the count and make the number negative which we got on the right side to prevent it from counting again. C++ Java Python3 C# PHP Javascript // C++ program to find smallest number// in array that is repeated exactly// 'k' times.#include <bits/stdc++.h>using namespace std; const int MAX = 1000; int findDuplicate(int arr[], int n, int k){ // Since arr[] has numbers in range from // 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number is present // once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is equal to 'k' if (count == k) res = min(res, arr[i]); } } return res;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0;} // Java program to find smallest number// in array that is repeated exactly// 'k' times.public class GFG { static final int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Since arr[] has numbers in range from // 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number is // present once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is equal // to 'k' if (count == k) res = Math.min(res, arr[i]); } } return res; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); }}// This article is contributed by Sumit Ghosh # Python 3 program to find smallest# number in array that is repeated# exactly 'k' times.MAX = 1000 def findDuplicate(arr, n, k): # Since arr[] has numbers in # range from 1 to MAX res = MAX + 1 for i in range(0, n): if (arr[i] > 0): # set count to 1 as number # is present once count = 1 for j in range(i + 1, n): if (arr[i] == arr[j]): count += 1 # If frequency of number is equal to 'k' if (count == k): res = min(res, arr[i]) return res # Driver codearr = [2, 2, 1, 3, 1]k = 2n = len(arr)print(findDuplicate(arr, n, k)) # This code is contributed by Smitha Dinesh Semwal. // C# program to find smallest number// in array that is repeated exactly// 'k' times.using System; public class GFG { static int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Since arr[] has numbers in range // from 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number // is present once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is // equal to 'k' if (count == k) res = Math.Min(res, arr[i]); } } return res; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); }} // This article is contributed by vt_m. <?php// PHP program to find smallest number// in array that is repeated exactly// 'k' times.function findDuplicate($arr, $n, $k){ // Since arr[] has numbers in // range from 1 to MAX $MAX = 1000; $res = $MAX + 1; for ($i = 0; $i < $n; $i++) { if ($arr[$i] > 0) { // set count to 1 as number is // present once $count = 1; for ($j = $i + 1; $j < $n; $j++) if ($arr[$i] == $arr[$j]) $count += 1; // If frequency of number is // equal to 'k' if ($count == $k) $res = min($res, $arr[$i]); } } return $res;} // Driver code$arr = array(2, 2, 1, 3, 1);$k = 2;$n = count($arr);echo findDuplicate($arr, $n, $k); // This code is contributed by Rajput-Ji?> <script> // Javascript program to find smallest number// in array that is repeated exactly// 'k' times let MAX = 1000; // finds the smallest number in arr[] // that is repeated k times function findDuplicate(arr, n, k) { // Computing frequencies of all elements let freq = new Array(MAX).fill(0); for (let i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { document.write("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (let i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // driver program let arr = [ 2, 2, 1, 3, 1 ]; let k = 2; let n = arr.length; document.write(findDuplicate(arr, n, k)); // This code is contributed by code_hunt.</script> Output: 1 Time Complexity : O(n2) Auxiliary Space : O(1) This solution doesn’t require array elements to be in limited range.Better Solution : Sort the input array and find the first element with exactly k count of appearances. C++ Java Python3 C# PHP Javascript // C++ program to find smallest number// in array that is repeated exactly// 'k' times.#include <bits/stdc++.h>using namespace std; int findDuplicate(int arr[], int n, int k){ // Sort the array sort(arr, arr + n); // Find the first element with exactly // k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0;} // Java program to find smallest number// in array that is repeated exactly// 'k' times.import java.util.Arrays;public class GFG { // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Sort the array Arrays.sort(arr); // Find the first element with exactly // k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); }}// This article is contributed by Sumit Ghosh # Python program to find smallest number# in array that is repeated exactly# 'k' times. def findDuplicate(arr, n, k): # Sort the array arr.sort() # Find the first element with exactly # k occurrences. i = 0 while (i < n): j, count = i + 1, 1 while (j < n and arr[j] == arr[i]): count += 1 j += 1 if (count == k): return arr[i] i = j return -1 # Driver codearr = [ 2, 2, 1, 3, 1 ];k = 2n = len(arr)print(findDuplicate(arr, n, k)) # This code is contributed by Sachin Bisht // C# program to find smallest number// in array that is repeated exactly// 'k' times.using System; public class GFG { // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Sort the array Array.Sort(arr); // Find the first element with // exactly k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); }} // This article is contributed by vt_m. <?php// PHP program to find smallest number// in array that is repeated exactly// 'k' times. // finds the smallest number in arr[]// that is repeated k timesfunction findDuplicate($arr, $n, $k){ // Sort the array sort($arr); // Find the first element with // exactly k occurrences. $i = 0; while ($i < $n) { $j; $count = 1; for ($j = $i + 1; $j < $n && $arr[$j] == $arr[$i]; $j++) $count++; if ($count == $k) return $arr[$i]; $i = $j; } return -1;} // Driver code$arr = array( 2, 2, 1, 3, 1 );$k = 2;$n = sizeof($arr);echo(findDuplicate($arr, $n, $k)); // This code is contributed// by Code_Mech.?> <script> // JavaScript program to find smallest number // in array that is repeated exactly // 'k' times. // finds the smallest number in arr[] // that is repeated k times function findDuplicate(arr, n, k) { // Sort the array arr.sort(); // Find the first element with // exactly k occurrences. let i = 0; while (i < n) { let j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } let arr = [ 2, 2, 1, 3, 1 ]; let k = 2; let n = arr.length; document.write(findDuplicate(arr, n, k)); </script> Output: 1 Time Complexity : O(n Log n) Auxiliary Space : O(1)Efficient Approach : Efficient approach is based on the fact that array has numbers in small range (1 to 1000). We solve this problem by using a frequency array of size max and store the frequency of every number in that array. C++ Java Python3 C# PHP Javascript // C++ program to find smallest number// in array that is repeated exactly// 'k' times.#include <bits/stdc++.h>using namespace std; const int MAX = 1000; int findDuplicate(int arr[], int n, int k){ // Computing frequencies of all elements int freq[MAX]; memset(freq, 0, sizeof(freq)); for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { cout << "Out of range"; return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0;} // Java program to find smallest number// in array that is repeated exactly// 'k' times.public class GFG { static final int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Computing frequencies of all elements int[] freq = new int[MAX]; for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { System.out.println("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); }}// This article is contributed by Sumit Ghosh # Python program to find smallest number# in array that is repeated exactly# 'k' times. MAX = 1000 def findDuplicate(arr, n, k): # Computing frequencies of all elements freq = [0 for i in range(MAX)] for i in range(n): if (arr[i] < 1 and arr[i] > MAX): print("Out of range") return -1 freq[arr[i]] += 1 # Finding the smallest element with # frequency as k for i in range(MAX): # If frequency of any of the number # is equal to k starting from 0 # then return the number if (freq[i] == k): return i return -1 # Driver codearr = [ 2, 2, 1, 3, 1 ]k = 2n = len(arr)print(findDuplicate(arr, n, k)) # This code is contributed by Sachin Bisht // C# program to find smallest number// in array that is repeated exactly// 'k' times.using System; public class GFG { static int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Computing frequencies of all // elements int[] freq = new int[MAX]; for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { Console.WriteLine("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the // number is equal to k starting // from 0 then return the number if (freq[i] == k) return i; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); }} // This article is contributed by vt_m. <?php// PHP program to find smallest number// in array that is repeated exactly// 'k' times. $MAX = 1000; function findDuplicate($arr, $n, $k){ global $MAX; // Computing frequencies of all elements $freq=array_fill(0, $MAX, 0); for ($i = 0; $i < $n; $i++) { if ($arr[$i] < 1 && $arr[$i] > $MAX) { echo "Out of range"; return -1; } $freq[$arr[$i]] += 1; } // Finding the smallest element with // frequency as k for ($i = 0; $i < $MAX; $i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if ($freq[$i] == $k) return $i; } return -1;} // Driver code $arr = array( 2, 2, 1, 3, 1 ); $k = 2; $n = count($arr); echo findDuplicate($arr, $n, $k); // This code is contributed by mits?> <script> // javascript program to find smallest number// in array that is repeated exactly// 'k' times. var MAX = 1000; // finds the smallest number in arr// that is repeated k timesfunction findDuplicate(arr , n , k){ // Computing frequencies of all elements var freq = Array.from({length: MAX}, (_, i) => 0); for (var i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { document.write("Out of range"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (var i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1;} // Driver codevar arr = [ 2, 2, 1, 3, 1 ];var k = 2;var n = arr.length;document.write(findDuplicate(arr, n, k)); // This code is contributed by 29AjayKumar</script> Output: 1 Time Complexity: O(MAX + n) Auxiliary Space : O(MAX)Can we solve it in O(n) time if range is not limited? Please see Smallest element repeated exactly ‘k’ times (not limited to small range)This article is contributed by Abhijit Shankhdhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Rajput-Ji Code_Mech Mithun Kumar code_hunt 29AjayKumar divyeshrabadiya07 amartyaghoshgfg limited-range-elements Arrays Hash Sorting Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Building Heap from Array Trapping Rain Water Reversal algorithm for array rotation Program to find sum of elements in a given array Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 24820, "s": 24792, "text": "\n31 Jan, 2022" }, { "code": null, "e": 25041, "s": 24820, "text": "Given an array of size n, the goal is to find out the smallest number that is repeated exactly ‘k’ times where k > 0? Assume that array has only positive integers and 1 <= arr[i] < 1000 for each i = 0 to n -1.Examples: " }, { "code": null, "e": 25372, "s": 25041, "text": "Input : arr[] = {2 2 1 3 1}\n k = 2\nOutput: 1\nExplanation:\nHere in array,\n2 is repeated 2 times\n1 is repeated 2 times \n3 is repeated 1 time\nHence 2 and 1 both are repeated 'k' times\ni.e 2 and min(2, 1) is 1\n\nInput : arr[] = {3 5 3 2}\n k = 1\nOutput : 2\nExplanation:\nBoth 2 and 5 are repeating 1 time but\nmin(5, 2) is 2" }, { "code": null, "e": 25717, "s": 25374, "text": "Simple Approach: A simple approach is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the same element is present on right side of it. If present increase the count and make the number negative which we got on the right side to prevent it from counting again. " }, { "code": null, "e": 25721, "s": 25717, "text": "C++" }, { "code": null, "e": 25726, "s": 25721, "text": "Java" }, { "code": null, "e": 25734, "s": 25726, "text": "Python3" }, { "code": null, "e": 25737, "s": 25734, "text": "C#" }, { "code": null, "e": 25741, "s": 25737, "text": "PHP" }, { "code": null, "e": 25752, "s": 25741, "text": "Javascript" }, { "code": "// C++ program to find smallest number// in array that is repeated exactly// 'k' times.#include <bits/stdc++.h>using namespace std; const int MAX = 1000; int findDuplicate(int arr[], int n, int k){ // Since arr[] has numbers in range from // 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number is present // once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is equal to 'k' if (count == k) res = min(res, arr[i]); } } return res;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0;}", "e": 26614, "s": 25752, "text": null }, { "code": "// Java program to find smallest number// in array that is repeated exactly// 'k' times.public class GFG { static final int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Since arr[] has numbers in range from // 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number is // present once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is equal // to 'k' if (count == k) res = Math.min(res, arr[i]); } } return res; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); }}// This article is contributed by Sumit Ghosh", "e": 27728, "s": 26614, "text": null }, { "code": "# Python 3 program to find smallest# number in array that is repeated# exactly 'k' times.MAX = 1000 def findDuplicate(arr, n, k): # Since arr[] has numbers in # range from 1 to MAX res = MAX + 1 for i in range(0, n): if (arr[i] > 0): # set count to 1 as number # is present once count = 1 for j in range(i + 1, n): if (arr[i] == arr[j]): count += 1 # If frequency of number is equal to 'k' if (count == k): res = min(res, arr[i]) return res # Driver codearr = [2, 2, 1, 3, 1]k = 2n = len(arr)print(findDuplicate(arr, n, k)) # This code is contributed by Smitha Dinesh Semwal.", "e": 28454, "s": 27728, "text": null }, { "code": "// C# program to find smallest number// in array that is repeated exactly// 'k' times.using System; public class GFG { static int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Since arr[] has numbers in range // from 1 to MAX int res = MAX + 1; for (int i = 0; i < n; i++) { if (arr[i] > 0) { // set count to 1 as number // is present once int count = 1; for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]) count += 1; // If frequency of number is // equal to 'k' if (count == k) res = Math.Min(res, arr[i]); } } return res; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); }} // This article is contributed by vt_m.", "e": 29665, "s": 28454, "text": null }, { "code": "<?php// PHP program to find smallest number// in array that is repeated exactly// 'k' times.function findDuplicate($arr, $n, $k){ // Since arr[] has numbers in // range from 1 to MAX $MAX = 1000; $res = $MAX + 1; for ($i = 0; $i < $n; $i++) { if ($arr[$i] > 0) { // set count to 1 as number is // present once $count = 1; for ($j = $i + 1; $j < $n; $j++) if ($arr[$i] == $arr[$j]) $count += 1; // If frequency of number is // equal to 'k' if ($count == $k) $res = min($res, $arr[$i]); } } return $res;} // Driver code$arr = array(2, 2, 1, 3, 1);$k = 2;$n = count($arr);echo findDuplicate($arr, $n, $k); // This code is contributed by Rajput-Ji?>", "e": 30484, "s": 29665, "text": null }, { "code": "<script> // Javascript program to find smallest number// in array that is repeated exactly// 'k' times let MAX = 1000; // finds the smallest number in arr[] // that is repeated k times function findDuplicate(arr, n, k) { // Computing frequencies of all elements let freq = new Array(MAX).fill(0); for (let i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { document.write(\"Out of range\"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (let i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // driver program let arr = [ 2, 2, 1, 3, 1 ]; let k = 2; let n = arr.length; document.write(findDuplicate(arr, n, k)); // This code is contributed by code_hunt.</script>", "e": 31564, "s": 30484, "text": null }, { "code": null, "e": 31574, "s": 31564, "text": "Output: " }, { "code": null, "e": 31576, "s": 31574, "text": "1" }, { "code": null, "e": 31796, "s": 31576, "text": "Time Complexity : O(n2) Auxiliary Space : O(1) This solution doesn’t require array elements to be in limited range.Better Solution : Sort the input array and find the first element with exactly k count of appearances. " }, { "code": null, "e": 31800, "s": 31796, "text": "C++" }, { "code": null, "e": 31805, "s": 31800, "text": "Java" }, { "code": null, "e": 31813, "s": 31805, "text": "Python3" }, { "code": null, "e": 31816, "s": 31813, "text": "C#" }, { "code": null, "e": 31820, "s": 31816, "text": "PHP" }, { "code": null, "e": 31831, "s": 31820, "text": "Javascript" }, { "code": "// C++ program to find smallest number// in array that is repeated exactly// 'k' times.#include <bits/stdc++.h>using namespace std; int findDuplicate(int arr[], int n, int k){ // Sort the array sort(arr, arr + n); // Find the first element with exactly // k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0;}", "e": 32502, "s": 31831, "text": null }, { "code": "// Java program to find smallest number// in array that is repeated exactly// 'k' times.import java.util.Arrays;public class GFG { // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Sort the array Arrays.sort(arr); // Find the first element with exactly // k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); }}// This article is contributed by Sumit Ghosh", "e": 33402, "s": 32502, "text": null }, { "code": "# Python program to find smallest number# in array that is repeated exactly# 'k' times. def findDuplicate(arr, n, k): # Sort the array arr.sort() # Find the first element with exactly # k occurrences. i = 0 while (i < n): j, count = i + 1, 1 while (j < n and arr[j] == arr[i]): count += 1 j += 1 if (count == k): return arr[i] i = j return -1 # Driver codearr = [ 2, 2, 1, 3, 1 ];k = 2n = len(arr)print(findDuplicate(arr, n, k)) # This code is contributed by Sachin Bisht", "e": 33977, "s": 33402, "text": null }, { "code": "// C# program to find smallest number// in array that is repeated exactly// 'k' times.using System; public class GFG { // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Sort the array Array.Sort(arr); // Find the first element with // exactly k occurrences. int i = 0; while (i < n) { int j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); }} // This article is contributed by vt_m.", "e": 34926, "s": 33977, "text": null }, { "code": "<?php// PHP program to find smallest number// in array that is repeated exactly// 'k' times. // finds the smallest number in arr[]// that is repeated k timesfunction findDuplicate($arr, $n, $k){ // Sort the array sort($arr); // Find the first element with // exactly k occurrences. $i = 0; while ($i < $n) { $j; $count = 1; for ($j = $i + 1; $j < $n && $arr[$j] == $arr[$i]; $j++) $count++; if ($count == $k) return $arr[$i]; $i = $j; } return -1;} // Driver code$arr = array( 2, 2, 1, 3, 1 );$k = 2;$n = sizeof($arr);echo(findDuplicate($arr, $n, $k)); // This code is contributed// by Code_Mech.?>", "e": 35618, "s": 34926, "text": null }, { "code": "<script> // JavaScript program to find smallest number // in array that is repeated exactly // 'k' times. // finds the smallest number in arr[] // that is repeated k times function findDuplicate(arr, n, k) { // Sort the array arr.sort(); // Find the first element with // exactly k occurrences. let i = 0; while (i < n) { let j, count = 1; for (j = i + 1; j < n && arr[j] == arr[i]; j++) count++; if (count == k) return arr[i]; i = j; } return -1; } let arr = [ 2, 2, 1, 3, 1 ]; let k = 2; let n = arr.length; document.write(findDuplicate(arr, n, k)); </script>", "e": 36400, "s": 35618, "text": null }, { "code": null, "e": 36410, "s": 36400, "text": "Output: " }, { "code": null, "e": 36412, "s": 36410, "text": "1" }, { "code": null, "e": 36693, "s": 36412, "text": "Time Complexity : O(n Log n) Auxiliary Space : O(1)Efficient Approach : Efficient approach is based on the fact that array has numbers in small range (1 to 1000). We solve this problem by using a frequency array of size max and store the frequency of every number in that array. " }, { "code": null, "e": 36697, "s": 36693, "text": "C++" }, { "code": null, "e": 36702, "s": 36697, "text": "Java" }, { "code": null, "e": 36710, "s": 36702, "text": "Python3" }, { "code": null, "e": 36713, "s": 36710, "text": "C#" }, { "code": null, "e": 36717, "s": 36713, "text": "PHP" }, { "code": null, "e": 36728, "s": 36717, "text": "Javascript" }, { "code": "// C++ program to find smallest number// in array that is repeated exactly// 'k' times.#include <bits/stdc++.h>using namespace std; const int MAX = 1000; int findDuplicate(int arr[], int n, int k){ // Computing frequencies of all elements int freq[MAX]; memset(freq, 0, sizeof(freq)); for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { cout << \"Out of range\"; return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1;} // Driver codeint main(){ int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << findDuplicate(arr, n, k); return 0;}", "e": 37643, "s": 36728, "text": null }, { "code": "// Java program to find smallest number// in array that is repeated exactly// 'k' times.public class GFG { static final int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int arr[], int n, int k) { // Computing frequencies of all elements int[] freq = new int[MAX]; for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { System.out.println(\"Out of range\"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.length; System.out.println(findDuplicate(arr, n, k)); }}// This article is contributed by Sumit Ghosh", "e": 38787, "s": 37643, "text": null }, { "code": "# Python program to find smallest number# in array that is repeated exactly# 'k' times. MAX = 1000 def findDuplicate(arr, n, k): # Computing frequencies of all elements freq = [0 for i in range(MAX)] for i in range(n): if (arr[i] < 1 and arr[i] > MAX): print(\"Out of range\") return -1 freq[arr[i]] += 1 # Finding the smallest element with # frequency as k for i in range(MAX): # If frequency of any of the number # is equal to k starting from 0 # then return the number if (freq[i] == k): return i return -1 # Driver codearr = [ 2, 2, 1, 3, 1 ]k = 2n = len(arr)print(findDuplicate(arr, n, k)) # This code is contributed by Sachin Bisht", "e": 39546, "s": 38787, "text": null }, { "code": "// C# program to find smallest number// in array that is repeated exactly// 'k' times.using System; public class GFG { static int MAX = 1000; // finds the smallest number in arr[] // that is repeated k times static int findDuplicate(int[] arr, int n, int k) { // Computing frequencies of all // elements int[] freq = new int[MAX]; for (int i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { Console.WriteLine(\"Out of range\"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (int i = 0; i < MAX; i++) { // If frequency of any of the // number is equal to k starting // from 0 then return the number if (freq[i] == k) return i; } return -1; } // Driver code public static void Main() { int[] arr = { 2, 2, 1, 3, 1 }; int k = 2; int n = arr.Length; Console.WriteLine( findDuplicate(arr, n, k)); }} // This article is contributed by vt_m.", "e": 40777, "s": 39546, "text": null }, { "code": "<?php// PHP program to find smallest number// in array that is repeated exactly// 'k' times. $MAX = 1000; function findDuplicate($arr, $n, $k){ global $MAX; // Computing frequencies of all elements $freq=array_fill(0, $MAX, 0); for ($i = 0; $i < $n; $i++) { if ($arr[$i] < 1 && $arr[$i] > $MAX) { echo \"Out of range\"; return -1; } $freq[$arr[$i]] += 1; } // Finding the smallest element with // frequency as k for ($i = 0; $i < $MAX; $i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if ($freq[$i] == $k) return $i; } return -1;} // Driver code $arr = array( 2, 2, 1, 3, 1 ); $k = 2; $n = count($arr); echo findDuplicate($arr, $n, $k); // This code is contributed by mits?>", "e": 41655, "s": 40777, "text": null }, { "code": "<script> // javascript program to find smallest number// in array that is repeated exactly// 'k' times. var MAX = 1000; // finds the smallest number in arr// that is repeated k timesfunction findDuplicate(arr , n , k){ // Computing frequencies of all elements var freq = Array.from({length: MAX}, (_, i) => 0); for (var i = 0; i < n; i++) { if (arr[i] < 1 && arr[i] > MAX) { document.write(\"Out of range\"); return -1; } freq[arr[i]] += 1; } // Finding the smallest element with // frequency as k for (var i = 0; i < MAX; i++) { // If frequency of any of the number // is equal to k starting from 0 // then return the number if (freq[i] == k) return i; } return -1;} // Driver codevar arr = [ 2, 2, 1, 3, 1 ];var k = 2;var n = arr.length;document.write(findDuplicate(arr, n, k)); // This code is contributed by 29AjayKumar</script>", "e": 42599, "s": 41655, "text": null }, { "code": null, "e": 42609, "s": 42599, "text": "Output: " }, { "code": null, "e": 42611, "s": 42609, "text": "1" }, { "code": null, "e": 43227, "s": 42611, "text": "Time Complexity: O(MAX + n) Auxiliary Space : O(MAX)Can we solve it in O(n) time if range is not limited? Please see Smallest element repeated exactly ‘k’ times (not limited to small range)This article is contributed by Abhijit Shankhdhar. 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": 43232, "s": 43227, "text": "vt_m" }, { "code": null, "e": 43242, "s": 43232, "text": "Rajput-Ji" }, { "code": null, "e": 43252, "s": 43242, "text": "Code_Mech" }, { "code": null, "e": 43265, "s": 43252, "text": "Mithun Kumar" }, { "code": null, "e": 43275, "s": 43265, "text": "code_hunt" }, { "code": null, "e": 43287, "s": 43275, "text": "29AjayKumar" }, { "code": null, "e": 43305, "s": 43287, "text": "divyeshrabadiya07" }, { "code": null, "e": 43321, "s": 43305, "text": "amartyaghoshgfg" }, { "code": null, "e": 43344, "s": 43321, "text": "limited-range-elements" }, { "code": null, "e": 43351, "s": 43344, "text": "Arrays" }, { "code": null, "e": 43356, "s": 43351, "text": "Hash" }, { "code": null, "e": 43364, "s": 43356, "text": "Sorting" }, { "code": null, "e": 43371, "s": 43364, "text": "Arrays" }, { "code": null, "e": 43376, "s": 43371, "text": "Hash" }, { "code": null, "e": 43384, "s": 43376, "text": "Sorting" }, { "code": null, "e": 43482, "s": 43384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43507, "s": 43482, "text": "Window Sliding Technique" }, { "code": null, "e": 43532, "s": 43507, "text": "Building Heap from Array" }, { "code": null, "e": 43552, "s": 43532, "text": "Trapping Rain Water" }, { "code": null, "e": 43590, "s": 43552, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 43639, "s": 43590, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 43675, "s": 43639, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 43706, "s": 43675, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 43740, "s": 43706, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 43767, "s": 43740, "text": "Count pairs with given sum" } ]
C++ Program to Find Minimum Value of any Algebraic Expression
This is a C++ Program to Find Minimum Value of any Algebraic Expression.An algebraic expression of the form (x1 + x2 + x3 + . . . + xa) * (y1 + y2 + . . . + yb) and (a + b) integers is given.consider all possible combinations of a numbers and remaining b numbers and calculating their values, from which minimum value can be derived. Begin function MaxValue() : Arguments: a[] = array which store the elements. x,y = integers. Body of the function: 1) Find the sum of array elements. 2) Initialize s=0. 3) Make for loop i = 0 to (x + y)-1 Shift the integers by 25 so that they become positive. 4) Declare a boolean array p[i][j] that represents true if sum j can be reachable by choosing i numbers. 5) Initialization of the array. 6) Make for loop i = 0 to (x + y)-1 to determine If p[i][j] is true, that means it is possible to select i numbers from (x + y) numbers to sum upto j. 7) Initialize min_value=INF. 8) Make for loop i = 0 to (MAX * MAX + 1)-1 to Check if a particular sum can be reachable by choosing x numbers. if (p[x][i]) Get the actual sum as we shifted the numbers by 25 to avoid negative indexing in array . 9) Print the min_value. End #include <bits/stdc++.h> using namespace std; #define INF 1e9 #define MAX 25 int MinValue(int a[], int x, int y) { int s= 0; for (int i = 0; i < (x + y); i++) { s+= a[i]; a[i] += 25; } bool p[MAX+1][MAX * MAX + 1]; //Initialize the array to 01. memset(p, 0, sizeof(p)); p[0][0] = 1; for (int i = 0; i < (x + y); i++) { // k can be at max x because the // left expression has x numbers for (int k = min(x, i + 1); k >= 1; k--) { for (int j = 0; j < MAX * MAX + 1; j++) { if (p[k - 1][j]) p[k][j + a[i]] = 1; } } } int min_value = INF; for (int i = 0; i < MAX * MAX + 1; i++) { if (p[x][i]) { int tmp = i - 25 * x; min_value = min(min_value, tmp * (s - tmp)); } } cout << "Minimum Value: " << min_value ; } int main() { int x = 2, y = 2; //input is taken of x and y. int ar[] = { 7,6,4,3 }; MinValue(ar, x, y); return 0; } Minimum Value: 91
[ { "code": null, "e": 1396, "s": 1062, "text": "This is a C++ Program to Find Minimum Value of any Algebraic Expression.An algebraic expression of the form (x1 + x2 + x3 + . . . + xa) * (y1 + y2 + . . . + yb) and (a + b) integers is given.consider all possible combinations of a numbers and remaining b numbers and calculating their values, from which minimum value can be derived." }, { "code": null, "e": 2267, "s": 1396, "text": "Begin\n function MaxValue() :\n Arguments:\n a[] = array which store the elements.\n x,y = integers.\n Body of the function:\n 1) Find the sum of array elements.\n 2) Initialize s=0.\n 3) Make for loop i = 0 to (x + y)-1 Shift the integers by 25 so that they become positive.\n 4) Declare a boolean array p[i][j] that represents true if sum j can be reachable by choosing i numbers.\n 5) Initialization of the array.\n 6) Make for loop i = 0 to (x + y)-1 to determine If p[i][j] is true, that means it is possible to select i numbers from (x + y) numbers to sum upto j.\n 7) Initialize min_value=INF.\n 8) Make for loop i = 0 to (MAX * MAX + 1)-1 to Check if a particular sum can be reachable by choosing x numbers.\n if (p[x][i])\n Get the actual sum as we shifted the numbers by 25 to avoid negative indexing in array .\n 9) Print the min_value.\nEnd" }, { "code": null, "e": 3250, "s": 2267, "text": "#include <bits/stdc++.h>\nusing namespace std;\n#define INF 1e9\n#define MAX 25\nint MinValue(int a[], int x, int y) {\n int s= 0;\n for (int i = 0; i < (x + y); i++) {\n s+= a[i];\n a[i] += 25;\n }\n bool p[MAX+1][MAX * MAX + 1];\n //Initialize the array to 01.\n memset(p, 0, sizeof(p));\n p[0][0] = 1;\n for (int i = 0; i < (x + y); i++) {\n // k can be at max x because the\n // left expression has x numbers\n for (int k = min(x, i + 1); k >= 1; k--) {\n for (int j = 0; j < MAX * MAX + 1; j++) {\n if (p[k - 1][j])\n p[k][j + a[i]] = 1;\n }\n }\n }\n int min_value = INF;\n for (int i = 0; i < MAX * MAX + 1; i++) {\n if (p[x][i]) {\n int tmp = i - 25 * x;\n min_value = min(min_value, tmp * (s - tmp));\n }\n }\n cout << \"Minimum Value: \" << min_value ;\n}\nint main() {\n int x = 2, y = 2; //input is taken of x and y.\n int ar[] = { 7,6,4,3 };\n MinValue(ar, x, y);\n return 0;\n}" }, { "code": null, "e": 3268, "s": 3250, "text": "Minimum Value: 91" } ]
How to display an image/screenshot in a Python Tkinter window without saving it?
Tkinter is a standard Python library that is used to create and develop GUI-based applications. To display an image, we use the PIL or Pillow library. Let us suppose that we want to create an application that will take a screenshot of the window and display the captured image in another window. To achieve this, we can follow the steps given below − Import the required libraries. Import the required libraries. Create a universal button to take the screenshot. Create a universal button to take the screenshot. Define a function to take the screenshot. Define a function to take the screenshot. In the given function, define the coords and region through which we want to take the screenshot. In the given function, define the coords and region through which we want to take the screenshot. Create a Toplevel window and define a label image in it. Create a Toplevel window and define a label image in it. Pack the widget and display the output image. Pack the widget and display the output image. # Import the required libraries from tkinter import * import pyautogui from PIL import ImageTk, Image # Create an instance of tknter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Define a function to take the screenshot def take_screenshot(): x = 500 y = 500 # Take the screenshot in the given corrds im1 = pyautogui.screenshot(region=(x, y, 700, 300)) # Create a toplevel window top = Toplevel(win) im1 = ImageTk.PhotoImage(im1) # Add the image in the label widget image1 = Label(top, image=im1) image1.image = im1 image1.place(x=0, y=0) Button(win, text='Take ScreenShot', command=take_screenshot).pack(padx=10, pady=10) win.mainloop() When we run the code, it will display a window with a button to take a screenshot. Now, click the button "Take ScreenShot" and it will capture the screen of size 700px wide and 300 px height, starting from the coordinates (x=500, y=500).
[ { "code": null, "e": 1213, "s": 1062, "text": "Tkinter is a standard Python library that is used to create and develop GUI-based applications. To display an image, we use the PIL or Pillow library." }, { "code": null, "e": 1413, "s": 1213, "text": "Let us suppose that we want to create an application that will take a screenshot of the window and display the captured image in another window. To achieve this, we can follow the steps given below −" }, { "code": null, "e": 1444, "s": 1413, "text": "Import the required libraries." }, { "code": null, "e": 1475, "s": 1444, "text": "Import the required libraries." }, { "code": null, "e": 1525, "s": 1475, "text": "Create a universal button to take the screenshot." }, { "code": null, "e": 1575, "s": 1525, "text": "Create a universal button to take the screenshot." }, { "code": null, "e": 1617, "s": 1575, "text": "Define a function to take the screenshot." }, { "code": null, "e": 1659, "s": 1617, "text": "Define a function to take the screenshot." }, { "code": null, "e": 1757, "s": 1659, "text": "In the given function, define the coords and region through which we want to take the screenshot." }, { "code": null, "e": 1855, "s": 1757, "text": "In the given function, define the coords and region through which we want to take the screenshot." }, { "code": null, "e": 1912, "s": 1855, "text": "Create a Toplevel window and define a label image in it." }, { "code": null, "e": 1969, "s": 1912, "text": "Create a Toplevel window and define a label image in it." }, { "code": null, "e": 2015, "s": 1969, "text": "Pack the widget and display the output image." }, { "code": null, "e": 2061, "s": 2015, "text": "Pack the widget and display the output image." }, { "code": null, "e": 2776, "s": 2061, "text": "# Import the required libraries\nfrom tkinter import *\nimport pyautogui\nfrom PIL import ImageTk, Image\n\n# Create an instance of tknter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n\n# Define a function to take the screenshot\ndef take_screenshot():\n x = 500\n y = 500\n # Take the screenshot in the given corrds\n im1 = pyautogui.screenshot(region=(x, y, 700, 300))\n\n # Create a toplevel window\n top = Toplevel(win)\n im1 = ImageTk.PhotoImage(im1)\n\n # Add the image in the label widget\n image1 = Label(top, image=im1)\n image1.image = im1\n image1.place(x=0, y=0)\n\nButton(win, text='Take ScreenShot', command=take_screenshot).pack(padx=10, pady=10)\n\nwin.mainloop()" }, { "code": null, "e": 2859, "s": 2776, "text": "When we run the code, it will display a window with a button to take a screenshot." }, { "code": null, "e": 3014, "s": 2859, "text": "Now, click the button \"Take ScreenShot\" and it will capture the screen of size 700px wide and 300 px height, starting from the coordinates (x=500, y=500)." } ]
Python Basics: Mutable vs Immutable Objects | by Ventsislav Yordanov | Towards Data Science
After reading this blog post you’ll know: What are an object’s identity, type, and value What are mutable and immutable objects All the data in a Python code is represented by objects or by relations between objects. Every object has an identity, a type, and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The is operator compares the identity of two objects; the id() function returns an integer representing its identity. An object’s type defines the possible values and operations (e.g. “does it have a length?”) that type supports. The type() function returns the type of an object. An object type is unchangeable like the identity. The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. The mutability of an object is determined by its type. Important noteSome objects contain references to other objects, these objects are called containers. Some examples of containers are a tuple, list, and dictionary. The value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed. However, the container is still considered immutable because when we talk about the mutability of a container only the identities of the contained objects are implied. In the next section, we’ll see more information and detailed examples to understand more about the differences between the mutable and immutable objects. Some of the mutable data types in Python are list, dictionary, set and user-defined classes. On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range. It’s time for some examples. Let’s start by comparing the tuple (immutable) and list (mutable) data types. We can define a list using square brackets [] like this: numbers = [1, 2, 3]. To define a tuple, we just need to replace the brackets with parentheses () like this: numbers = (1, 2, 3). From both data types, we can access elements by index and we can iterate over them. The main difference is that a tuple cannot be changed once it’s defined. Output: 110 Output: [100, 2, 3]--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-2-286c46a29f5d> in <module>() 3 list_values[0] = 100 4 print(list_values)----> 5 set_values[0] = 100TypeError: 'tuple' object does not support item assignment We can see that when we try to change the tuple we get an error, but we don’t have that problem with the list. Now, we can try to expand our list and tuple using the += operator. This will operation work for both data types. Let’s see what will happen. Output: 2450343168136245034320555224503431681362450341742248 We can see that the list identity is not changed, while the tuple identity is changed. This means that we have expanded our list, but created a completely new tuple. Lists are more memory efficient than tuples. We have seen that some of the other immutable data types are integers and strings. Once they are initialized, their values cannot be changed. Output: 16576966081657696640 Output: 24503431689442450343426208 We see that both for the number and text variables, their identity is changed. This means that new variables are created in both cases. Let’s see what happens if we give two names of the same object for a mutable data types. Output: 24503431666642450343166664True[4, 5, 6, 7][4, 5, 6, 7] We can see that the variable names have the same identity meaning that they are referencing to the same object in computer memory. Reminder: the is operator compares the identity of two objects. So, when we have changed the values of the second variable, the values of the first one are also changed. This happens only with the mutable objects. You can see how you can prevent this in one of my previous blog posts. Let’s try to do a similar example with an immutable object. We can try to copy two strings and change the value in any of them. Output: 30635114504883063511450488True30635516236483063511450488FalsePython is awesomePython Every time when we try to update the value of an immutable object, a new object is created instead. That’s when we have updated the first string it doesn’t change the value of the second. Sometimes we don’t want to compare the identity of two objects, but to compare the values of these objects. We can do this using the == operator. Output: TrueFalse We can clearly see the two objects have the same values, but their identities are different. As we said before the value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed. Let’s see an example of this. Output: <class 'tuple'>(129392130, ['Programming', 'Machine Learning', 'Statistics'])(129392130, ['Programming', 'Machine Learning', 'Maths']) We have changed the value of the skills variable. The other variable person contains a reference to the skills variable and that’s why its value is updated, too. ReminderThe object is still considered immutable because when we talk about the mutability of a container only the identities of the contained objects are implied. However, if your immutable object contains only immutable objects, we cannot change their value. Let’s see an example. Output: 16576966081657696032(42, 24, ('Python', 'pandas', 'scikit-learn'))16576968641657696064(42, 24, ('Python', 'pandas', 'scikit-learn')) Remember when you try to update the value of an immutable object, a new object is created instead. All the data in a Python code is represented by objects or by relations between objects. Every object has an identity, a type, and a value. An object’s identity never changes once it has been created. You may think of it as the object’s address in memory. An object’s type defines the possible values and operations. Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable. When we talk about the mutability of a container only the identities of the contained objects are implied. https://www.pythonforthelab.com/blog/mutable-and-immutable-objects/ https://standupdev.com/wiki/doku.php?id=python_tuples_are_immutable_but_may_change https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/ https://docs.python.org/3/reference/datamodel.html https://docs.python.org/3/library/functions.html#id You can also check my previous blog posts. Jupyter Notebook Shortcuts Python Basics for Data Science Python Basics: Iteration, Iterables, Iterators, and Looping Python Basics: List Comprehensions Data Science with Python: Intro to Data Visualization with Matplotlib Data Science with Python: Intro to Loading, Subsetting, and Filtering Data with pandas Introduction to Natural Language Processing for Text If you want to be notified when I post a new blog post you can subscribe to my newsletter. Here is my LinkedIn profile in case you want to connect with me. I’ll be happy to be connected with you. Thank you for the read. I hope that you have enjoyed the article. If you like it, please hold the clap button and share it with your friends. I’ll be happy to hear your feedback. If you have some questions, feel free to ask them. 😉
[ { "code": null, "e": 213, "s": 171, "text": "After reading this blog post you’ll know:" }, { "code": null, "e": 260, "s": 213, "text": "What are an object’s identity, type, and value" }, { "code": null, "e": 299, "s": 260, "text": "What are mutable and immutable objects" }, { "code": null, "e": 439, "s": 299, "text": "All the data in a Python code is represented by objects or by relations between objects. Every object has an identity, a type, and a value." }, { "code": null, "e": 673, "s": 439, "text": "An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The is operator compares the identity of two objects; the id() function returns an integer representing its identity." }, { "code": null, "e": 886, "s": 673, "text": "An object’s type defines the possible values and operations (e.g. “does it have a length?”) that type supports. The type() function returns the type of an object. An object type is unchangeable like the identity." }, { "code": null, "e": 1059, "s": 886, "text": "The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable." }, { "code": null, "e": 1114, "s": 1059, "text": "The mutability of an object is determined by its type." }, { "code": null, "e": 1578, "s": 1114, "text": "Important noteSome objects contain references to other objects, these objects are called containers. Some examples of containers are a tuple, list, and dictionary. The value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed. However, the container is still considered immutable because when we talk about the mutability of a container only the identities of the contained objects are implied." }, { "code": null, "e": 1732, "s": 1578, "text": "In the next section, we’ll see more information and detailed examples to understand more about the differences between the mutable and immutable objects." }, { "code": null, "e": 1825, "s": 1732, "text": "Some of the mutable data types in Python are list, dictionary, set and user-defined classes." }, { "code": null, "e": 1934, "s": 1825, "text": "On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range." }, { "code": null, "e": 2384, "s": 1934, "text": "It’s time for some examples. Let’s start by comparing the tuple (immutable) and list (mutable) data types. We can define a list using square brackets [] like this: numbers = [1, 2, 3]. To define a tuple, we just need to replace the brackets with parentheses () like this: numbers = (1, 2, 3). From both data types, we can access elements by index and we can iterate over them. The main difference is that a tuple cannot be changed once it’s defined." }, { "code": null, "e": 2392, "s": 2384, "text": "Output:" }, { "code": null, "e": 2396, "s": 2392, "text": "110" }, { "code": null, "e": 2404, "s": 2396, "text": "Output:" }, { "code": null, "e": 2734, "s": 2404, "text": "[100, 2, 3]--------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-2-286c46a29f5d> in <module>() 3 list_values[0] = 100 4 print(list_values)----> 5 set_values[0] = 100TypeError: 'tuple' object does not support item assignment" }, { "code": null, "e": 2845, "s": 2734, "text": "We can see that when we try to change the tuple we get an error, but we don’t have that problem with the list." }, { "code": null, "e": 2987, "s": 2845, "text": "Now, we can try to expand our list and tuple using the += operator. This will operation work for both data types. Let’s see what will happen." }, { "code": null, "e": 2995, "s": 2987, "text": "Output:" }, { "code": null, "e": 3048, "s": 2995, "text": "2450343168136245034320555224503431681362450341742248" }, { "code": null, "e": 3259, "s": 3048, "text": "We can see that the list identity is not changed, while the tuple identity is changed. This means that we have expanded our list, but created a completely new tuple. Lists are more memory efficient than tuples." }, { "code": null, "e": 3401, "s": 3259, "text": "We have seen that some of the other immutable data types are integers and strings. Once they are initialized, their values cannot be changed." }, { "code": null, "e": 3409, "s": 3401, "text": "Output:" }, { "code": null, "e": 3430, "s": 3409, "text": "16576966081657696640" }, { "code": null, "e": 3438, "s": 3430, "text": "Output:" }, { "code": null, "e": 3465, "s": 3438, "text": "24503431689442450343426208" }, { "code": null, "e": 3601, "s": 3465, "text": "We see that both for the number and text variables, their identity is changed. This means that new variables are created in both cases." }, { "code": null, "e": 3690, "s": 3601, "text": "Let’s see what happens if we give two names of the same object for a mutable data types." }, { "code": null, "e": 3698, "s": 3690, "text": "Output:" }, { "code": null, "e": 3753, "s": 3698, "text": "24503431666642450343166664True[4, 5, 6, 7][4, 5, 6, 7]" }, { "code": null, "e": 3948, "s": 3753, "text": "We can see that the variable names have the same identity meaning that they are referencing to the same object in computer memory. Reminder: the is operator compares the identity of two objects." }, { "code": null, "e": 4169, "s": 3948, "text": "So, when we have changed the values of the second variable, the values of the first one are also changed. This happens only with the mutable objects. You can see how you can prevent this in one of my previous blog posts." }, { "code": null, "e": 4297, "s": 4169, "text": "Let’s try to do a similar example with an immutable object. We can try to copy two strings and change the value in any of them." }, { "code": null, "e": 4305, "s": 4297, "text": "Output:" }, { "code": null, "e": 4390, "s": 4305, "text": "30635114504883063511450488True30635516236483063511450488FalsePython is awesomePython" }, { "code": null, "e": 4578, "s": 4390, "text": "Every time when we try to update the value of an immutable object, a new object is created instead. That’s when we have updated the first string it doesn’t change the value of the second." }, { "code": null, "e": 4724, "s": 4578, "text": "Sometimes we don’t want to compare the identity of two objects, but to compare the values of these objects. We can do this using the == operator." }, { "code": null, "e": 4732, "s": 4724, "text": "Output:" }, { "code": null, "e": 4742, "s": 4732, "text": "TrueFalse" }, { "code": null, "e": 4835, "s": 4742, "text": "We can clearly see the two objects have the same values, but their identities are different." }, { "code": null, "e": 5015, "s": 4835, "text": "As we said before the value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed. Let’s see an example of this." }, { "code": null, "e": 5023, "s": 5015, "text": "Output:" }, { "code": null, "e": 5158, "s": 5023, "text": "<class 'tuple'>(129392130, ['Programming', 'Machine Learning', 'Statistics'])(129392130, ['Programming', 'Machine Learning', 'Maths'])" }, { "code": null, "e": 5320, "s": 5158, "text": "We have changed the value of the skills variable. The other variable person contains a reference to the skills variable and that’s why its value is updated, too." }, { "code": null, "e": 5484, "s": 5320, "text": "ReminderThe object is still considered immutable because when we talk about the mutability of a container only the identities of the contained objects are implied." }, { "code": null, "e": 5603, "s": 5484, "text": "However, if your immutable object contains only immutable objects, we cannot change their value. Let’s see an example." }, { "code": null, "e": 5611, "s": 5603, "text": "Output:" }, { "code": null, "e": 5744, "s": 5611, "text": "16576966081657696032(42, 24, ('Python', 'pandas', 'scikit-learn'))16576968641657696064(42, 24, ('Python', 'pandas', 'scikit-learn'))" }, { "code": null, "e": 5843, "s": 5744, "text": "Remember when you try to update the value of an immutable object, a new object is created instead." }, { "code": null, "e": 5932, "s": 5843, "text": "All the data in a Python code is represented by objects or by relations between objects." }, { "code": null, "e": 5983, "s": 5932, "text": "Every object has an identity, a type, and a value." }, { "code": null, "e": 6099, "s": 5983, "text": "An object’s identity never changes once it has been created. You may think of it as the object’s address in memory." }, { "code": null, "e": 6160, "s": 6099, "text": "An object’s type defines the possible values and operations." }, { "code": null, "e": 6295, "s": 6160, "text": "Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable." }, { "code": null, "e": 6402, "s": 6295, "text": "When we talk about the mutability of a container only the identities of the contained objects are implied." }, { "code": null, "e": 6470, "s": 6402, "text": "https://www.pythonforthelab.com/blog/mutable-and-immutable-objects/" }, { "code": null, "e": 6553, "s": 6470, "text": "https://standupdev.com/wiki/doku.php?id=python_tuples_are_immutable_but_may_change" }, { "code": null, "e": 6623, "s": 6553, "text": "https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/" }, { "code": null, "e": 6674, "s": 6623, "text": "https://docs.python.org/3/reference/datamodel.html" }, { "code": null, "e": 6726, "s": 6674, "text": "https://docs.python.org/3/library/functions.html#id" }, { "code": null, "e": 6769, "s": 6726, "text": "You can also check my previous blog posts." }, { "code": null, "e": 6796, "s": 6769, "text": "Jupyter Notebook Shortcuts" }, { "code": null, "e": 6827, "s": 6796, "text": "Python Basics for Data Science" }, { "code": null, "e": 6887, "s": 6827, "text": "Python Basics: Iteration, Iterables, Iterators, and Looping" }, { "code": null, "e": 6922, "s": 6887, "text": "Python Basics: List Comprehensions" }, { "code": null, "e": 6992, "s": 6922, "text": "Data Science with Python: Intro to Data Visualization with Matplotlib" }, { "code": null, "e": 7079, "s": 6992, "text": "Data Science with Python: Intro to Loading, Subsetting, and Filtering Data with pandas" }, { "code": null, "e": 7132, "s": 7079, "text": "Introduction to Natural Language Processing for Text" }, { "code": null, "e": 7223, "s": 7132, "text": "If you want to be notified when I post a new blog post you can subscribe to my newsletter." }, { "code": null, "e": 7328, "s": 7223, "text": "Here is my LinkedIn profile in case you want to connect with me. I’ll be happy to be connected with you." } ]
Ruby on Rails 2.1 - Unit Testing
Before proceeding, let's have a quick look at a few definitions − The Tests − They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application. The Tests − They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application. The Assertion − This is a one line of code that evaluates an object (or expression) for expected results. For example – Is this value = that value? Is this object nil? The Assertion − This is a one line of code that evaluates an object (or expression) for expected results. For example – Is this value = that value? Is this object nil? The Test Case − This is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests. The Test Case − This is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests. The Test Suite − This is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it. The Test Suite − This is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it. When you run the helper script script/generate to create controllers and models, Rails generate a framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write. There are two important points to test in a Rails application − Testing the Models Testing the Models Testing the Controllers Testing the Controllers This tutorial will cover both the testings in brief. So let's create one testapp to understand the concept. C:\ruby> rails -d mysql testapp Till now, we have used only Rails application's development database, but now you need to make sure that the testing database is also created and appropriate sections of your config/database.yml file are set up correctly. Let's create development and testing databases as follows − mysql> create database testapp_test; Query OK, 1 row affected (0.01 sec) mysql> create database testapp_development; Query OK, 1 row affected (0.01 sec) mysql> use testapp_test; Database changed mysql> grant all privileges on testapp_test.* to 'root'@'localhost' identified by 'password'; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) Configure your config/database.yml as follows − development: adapter: mysql encoding: utf8 database: testapp_development username: root password: password host: localhost test: adapter: mysql encoding: utf8 database: testapp_test username: root password: password host: localhost production: adapter: mysql encoding: utf8 database: testapp_production username: root password: password host: localhost Assume you have a table containing books, including their titles, price, and a small description. The following migration sets up this table − testapp > ruby script/generate migration books Now modify the testapp/db/migrate/20080616170315_books.rb file as follows − class Books < ActiveRecord::Migration def self.up create_table :books do |t| t.string :title, :limit => 32, :null => false t.float :price t.text :description t.timestamp :created_at end end def self.down drop_table :books end end Now run the migration as follows − testapp > rake db:migrate This will create books table in testapp_development database. Thereafter, we need to set up your test database using rake command as follows − C:\ruby\testapp > rake db:test:clone_structure This will clone the testapp_development database into testapp_test database. It means whatever you have in the development database, now you will have the same data in the test database as well. When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the testapp_test database. This is the data against which your unit tests will run − testapp > ruby script/generate model Book exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/book.rb create test/unit/book_test.rb create test/fixtures/books.yml create db/migrate create db/migrate/20080616164236_create_books.rb As you write code in the model classes, you'll write corresponding tests in these files. So let's create two test book records using YAML in test/fixtures/books.yml as follows − perl_cb: id: 1 title: 'Ruby Tutorial' price: 102.00 description : 'This is a nice Ruby tutorial' java_cb: id: 2 title: 'Java Programming' price: 62.00 description : 'Java Programming for the beginners' Now let's replace the existing code in book unit test file test/unit/book_test.rb with the following code − require File.dirname(__FILE__) + '/../test_helper' class BookTest < ActiveSupport::TestCase fixtures :books def test_book perl_book = Book.new :title => books(:perl_cb).title, :price => books(:perl_cb).price, :description => books(:perl_cb).description, :created_at => books(:perl_cb).created_at assert perl_book.save perl_book_copy = Book.find(perl_book.id) assert_equal perl_book.title, perl_book_copy.title perl_book.title = "Ruby Tutorial" assert perl_book.save assert perl_book.destroy end end Finally, run the test method as follows − testapp > ruby test/unit/book_test.rb Here's the output of running the successful test case − testapp > ruby test/unit/book_test_crud.rb Loaded suite ./test/unit/book_test Started . Finished in 0.0625 seconds. 1 tests, 4 assertions, 0 failures, 0 errors Let’s analyze what happened here − The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable. The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable. The first assertion tests that saving the Book object was successful. The first assertion tests that saving the Book object was successful. Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we've tested the ability to create and read a database record. Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we've tested the ability to create and read a database record. The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful. The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful. Finally, the ability to destroy a Book object is tested. Finally, the ability to destroy a Book object is tested. This is how we can test our Rails Models. Controller testing is also known as functional testing. Functional testing tests the following type of functionalities of the controllers − Is the response redirected as expected? Is the expected template rendered? Is the routing as expected? Does the response contain the expected tags? Rails framework supports five types of requests − get post put head delete To write a functional test, you need to simulate any of the five HTTP request types that your controller will process. Request type "get" and "post" are the most commonly used in controller testing. All these methods take four arguments − The action of a controller An optional hash of request parameters An optional session hash An optional flash hash In this tutorial, we will see how to use get method to test our controller. You can test rest of the methods in similar way. When you generate a controller with generate, Rails creates a functional test script for the controller as follows − testapp > ruby script/generate controller Book exists app/controllers/ exists app/helpers/ create app/views/book exists test/functional/ create app/controllers/book_controller.rb create test/functional/book_controller_test.rb create app/helpers/book_helper.rb As you write code in the controller classes, you'll write corresponding tests in these files. Before that, let's define our controller functions list, show, and search inside app/controllers/book_controller.rb as follows − class BookController < ApplicationController def list @book_pages, @books = paginate :books, :per_page => 10 end def show @book = Book.find(params[:id]) end def search @book = Book.find_by_title(params[:title]) if @book redirect_to :action => 'show', :id => @book.id else flash[:error] = 'No such book available' redirect_to :action => 'list' end end end NOTE − You would need two views templates for show and list method. You can define those views and test them, but right now, we will proceed without defining those views. Now let's reuse our test fixture which is in the test/fixtures/books.yml file as follows − perl_cb: id: 1 title: 'Ruby Tutorial' price: 102.00 description : 'This is a nice Ruby tutorial' java_cb: id: 2 title: 'Java Programming' price: 62.00 description : 'Java Programming for the beginners' Add the following test_search_book and test_search_not_found methods to test/functional/book_controller_test.rb to test the functionality of the Book Controller's search action. require File.dirname(__FILE__) + '/../test_helper' require 'book_controller' # Re-raise errors caught by the controller. class BookController def rescue_action(e) raise e end end class BookControllerTest < Test::Unit::TestCase fixtures :books def setup @controller = BookController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_search_book get :search, :title => 'Ruby Tutorial' assert_not_nil assigns(:book) assert_equal books(:perl_cb).title, assigns(:book).title assert_valid assigns(:book) assert_redirected_to :action => 'show' end def test_search_not_found get :search, :title => 'HTML Tutorial' assert_redirected_to :action => 'list' assert_equal 'No such book available', flash[:error] end end Now run your test cases as follows − testapp > ruby test/functional/book_controller_test.rb It gives the following output − Loaded suite test/functional/book_controller_test Started .. Finished in 0.422 seconds. 2 tests, 7 assertions, 0 failures, 0 errors Let's analyze what has happened here − The setup method is a default method to create controller, request, and response objects. They would be used by Rails internally. The setup method is a default method to create controller, request, and response objects. They would be used by Rails internally. The first test method test_search_book generates a get request to the search action, passing in a title parameter. The first test method test_search_book generates a get request to the search action, passing in a title parameter. The next two assertions verify that a Book object was saved in an instance variable called @book and that the object passes any Active Record validations that might exist. The next two assertions verify that a Book object was saved in an instance variable called @book and that the object passes any Active Record validations that might exist. The final assertion inside first method tests that the request was redirected to the controller's show action. The final assertion inside first method tests that the request was redirected to the controller's show action. The second test method, test_search_not_found, performs another get request but passes in an invalid title The second test method, test_search_not_found, performs another get request but passes in an invalid title The first assertions test that a redirect to the list action was issued. The first assertions test that a redirect to the list action was issued. If the proceeding assertions passed, there should be a message in the flash hash which you can test with assert_equal.. If the proceeding assertions passed, there should be a message in the flash hash which you can test with assert_equal.. To obtain more information on Assertions, please refer Rails Standard Documentation. You can use rake utility to test your applications. Given below is a list of few important commands. $rake test − Test all unit tests and functional tests (and integration tests, if they exist). $rake test − Test all unit tests and functional tests (and integration tests, if they exist). $rake test:functionals− Run all functional tests. $rake test:functionals− Run all functional tests. $rake test:units − Run all unit tests. $rake test:units − Run all unit tests. $rake test:integration − Run all integration tests. $rake test:integration − Run all integration tests. $rake test:plugins − Run all test in ./vendor/plugins/**/test. $rake test:plugins − Run all test in ./vendor/plugins/**/test. $rake test:recent − Run tests for models and controllers that have been modified in the last 10 minutes − $rake test:recent − Run tests for models and controllers that have been modified in the last 10 minutes − $rake test:uncommitted − For projects in Subversion, run tests for the changes that took place in the models and controllers since the last commit − $rake test:uncommitted − For projects in Subversion, run tests for the changes that took place in the models and controllers since the last commit −
[ { "code": null, "e": 2357, "s": 2291, "text": "Before proceeding, let's have a quick look at a few definitions −" }, { "code": null, "e": 2556, "s": 2357, "text": "The Tests − They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application." }, { "code": null, "e": 2755, "s": 2556, "text": "The Tests − They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application." }, { "code": null, "e": 2923, "s": 2755, "text": "The Assertion − This is a one line of code that evaluates an object (or expression) for expected results. For example – Is this value = that value? Is this object nil?" }, { "code": null, "e": 3091, "s": 2923, "text": "The Assertion − This is a one line of code that evaluates an object (or expression) for expected results. For example – Is this value = that value? Is this object nil?" }, { "code": null, "e": 3230, "s": 3091, "text": "The Test Case − This is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests." }, { "code": null, "e": 3369, "s": 3230, "text": "The Test Case − This is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests." }, { "code": null, "e": 3505, "s": 3369, "text": "The Test Suite − This is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it." }, { "code": null, "e": 3641, "s": 3505, "text": "The Test Suite − This is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it." }, { "code": null, "e": 3954, "s": 3641, "text": "When you run the helper script script/generate to create controllers and models, Rails generate a framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write. There are two important points to test in a Rails application −" }, { "code": null, "e": 3973, "s": 3954, "text": "Testing the Models" }, { "code": null, "e": 3992, "s": 3973, "text": "Testing the Models" }, { "code": null, "e": 4016, "s": 3992, "text": "Testing the Controllers" }, { "code": null, "e": 4040, "s": 4016, "text": "Testing the Controllers" }, { "code": null, "e": 4148, "s": 4040, "text": "This tutorial will cover both the testings in brief. So let's create one testapp to understand the concept." }, { "code": null, "e": 4181, "s": 4148, "text": "C:\\ruby> rails -d mysql testapp\n" }, { "code": null, "e": 4403, "s": 4181, "text": "Till now, we have used only Rails application's development database, but now you need to make sure that the testing database is also created and appropriate sections of your config/database.yml file are set up correctly." }, { "code": null, "e": 4463, "s": 4403, "text": "Let's create development and testing databases as follows −" }, { "code": null, "e": 4860, "s": 4463, "text": "mysql> create database testapp_test;\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> create database testapp_development;\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> use testapp_test;\nDatabase changed\n\nmysql> grant all privileges on testapp_test.* \n to 'root'@'localhost' identified by 'password';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> FLUSH PRIVILEGES;\nQuery OK, 0 rows affected (0.00 sec)\n" }, { "code": null, "e": 4908, "s": 4860, "text": "Configure your config/database.yml as follows −" }, { "code": null, "e": 5316, "s": 4908, "text": "development:\n adapter: mysql\n encoding: utf8\n database: testapp_development\n username: root\n password: password\n host: localhost\ntest:\n adapter: mysql\n encoding: utf8\n database: testapp_test\n username: root\n password: password\n host: localhost\nproduction:\n adapter: mysql\n encoding: utf8\n database: testapp_production\n username: root\n password: password\n host: localhost\n" }, { "code": null, "e": 5459, "s": 5316, "text": "Assume you have a table containing books, including their titles, price, and a small description. The following migration sets up this table −" }, { "code": null, "e": 5507, "s": 5459, "text": "testapp > ruby script/generate migration books\n" }, { "code": null, "e": 5583, "s": 5507, "text": "Now modify the testapp/db/migrate/20080616170315_books.rb file as follows −" }, { "code": null, "e": 5898, "s": 5583, "text": "class Books < ActiveRecord::Migration\n def self.up\n create_table :books do |t|\n t.string :title, :limit => 32, :null => false\n t.float :price\n t.text :description\n t.timestamp :created_at\n end\n end\n \n def self.down\n drop_table :books\n end\nend" }, { "code": null, "e": 5933, "s": 5898, "text": "Now run the migration as follows −" }, { "code": null, "e": 5960, "s": 5933, "text": "testapp > rake db:migrate\n" }, { "code": null, "e": 6103, "s": 5960, "text": "This will create books table in testapp_development database. Thereafter, we need to set up your test database using rake command as follows −" }, { "code": null, "e": 6151, "s": 6103, "text": "C:\\ruby\\testapp > rake db:test:clone_structure\n" }, { "code": null, "e": 6346, "s": 6151, "text": "This will clone the testapp_development database into testapp_test database. It means whatever you have in the development database, now you will have the same data in the test database as well." }, { "code": null, "e": 6638, "s": 6346, "text": "When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the testapp_test database. This is the data against which your unit tests will run −" }, { "code": null, "e": 6925, "s": 6638, "text": "testapp > ruby script/generate model Book\n exists app/models/\n exists test/unit/\n exists test/fixtures/\n create app/models/book.rb\n create test/unit/book_test.rb\n create test/fixtures/books.yml\n create db/migrate\n create db/migrate/20080616164236_create_books.rb" }, { "code": null, "e": 7103, "s": 6925, "text": "As you write code in the model classes, you'll write corresponding tests in these files. So let's create two test book records using YAML in test/fixtures/books.yml as follows −" }, { "code": null, "e": 7329, "s": 7103, "text": "perl_cb:\n id: 1\n title: 'Ruby Tutorial'\n price: 102.00\n description : 'This is a nice Ruby tutorial'\njava_cb:\n id: 2\n title: 'Java Programming'\n price: 62.00\n description : 'Java Programming for the beginners'" }, { "code": null, "e": 7437, "s": 7329, "text": "Now let's replace the existing code in book unit test file test/unit/book_test.rb with the following code −" }, { "code": null, "e": 8023, "s": 7437, "text": "require File.dirname(__FILE__) + '/../test_helper'\n\nclass BookTest < ActiveSupport::TestCase\n fixtures :books\n\n def test_book\n\n perl_book = Book.new :title => books(:perl_cb).title, \n :price => books(:perl_cb).price,\n :description => books(:perl_cb).description,\n :created_at => books(:perl_cb).created_at\n\n assert perl_book.save\n\n perl_book_copy = Book.find(perl_book.id)\n\n assert_equal perl_book.title, perl_book_copy.title\n\n perl_book.title = \"Ruby Tutorial\"\n\n assert perl_book.save\n assert perl_book.destroy\n end\nend" }, { "code": null, "e": 8065, "s": 8023, "text": "Finally, run the test method as follows −" }, { "code": null, "e": 8104, "s": 8065, "text": "testapp > ruby test/unit/book_test.rb\n" }, { "code": null, "e": 8160, "s": 8104, "text": "Here's the output of running the successful test case −" }, { "code": null, "e": 8322, "s": 8160, "text": "testapp > ruby test/unit/book_test_crud.rb \nLoaded suite ./test/unit/book_test\nStarted\n.\nFinished in 0.0625 seconds.\n\n1 tests, 4 assertions, 0 failures, 0 errors" }, { "code": null, "e": 8357, "s": 8322, "text": "Let’s analyze what happened here −" }, { "code": null, "e": 8571, "s": 8357, "text": "The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable." }, { "code": null, "e": 8785, "s": 8571, "text": "The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable." }, { "code": null, "e": 8855, "s": 8785, "text": "The first assertion tests that saving the Book object was successful." }, { "code": null, "e": 8925, "s": 8855, "text": "The first assertion tests that saving the Book object was successful." }, { "code": null, "e": 9233, "s": 8925, "text": "Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we've tested the ability to create and read a database record." }, { "code": null, "e": 9541, "s": 9233, "text": "Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we've tested the ability to create and read a database record." }, { "code": null, "e": 9683, "s": 9541, "text": "The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful." }, { "code": null, "e": 9825, "s": 9683, "text": "The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful." }, { "code": null, "e": 9882, "s": 9825, "text": "Finally, the ability to destroy a Book object is tested." }, { "code": null, "e": 9939, "s": 9882, "text": "Finally, the ability to destroy a Book object is tested." }, { "code": null, "e": 9981, "s": 9939, "text": "This is how we can test our Rails Models." }, { "code": null, "e": 10121, "s": 9981, "text": "Controller testing is also known as functional testing. Functional testing tests the following type of functionalities of the controllers −" }, { "code": null, "e": 10161, "s": 10121, "text": "Is the response redirected as expected?" }, { "code": null, "e": 10196, "s": 10161, "text": "Is the expected template rendered?" }, { "code": null, "e": 10224, "s": 10196, "text": "Is the routing as expected?" }, { "code": null, "e": 10269, "s": 10224, "text": "Does the response contain the expected tags?" }, { "code": null, "e": 10319, "s": 10269, "text": "Rails framework supports five types of requests −" }, { "code": null, "e": 10323, "s": 10319, "text": "get" }, { "code": null, "e": 10328, "s": 10323, "text": "post" }, { "code": null, "e": 10332, "s": 10328, "text": "put" }, { "code": null, "e": 10337, "s": 10332, "text": "head" }, { "code": null, "e": 10344, "s": 10337, "text": "delete" }, { "code": null, "e": 10463, "s": 10344, "text": "To write a functional test, you need to simulate any of the five HTTP request types that your controller will process." }, { "code": null, "e": 10583, "s": 10463, "text": "Request type \"get\" and \"post\" are the most commonly used in controller testing. All these methods take four arguments −" }, { "code": null, "e": 10610, "s": 10583, "text": "The action of a controller" }, { "code": null, "e": 10649, "s": 10610, "text": "An optional hash of request parameters" }, { "code": null, "e": 10674, "s": 10649, "text": "An optional session hash" }, { "code": null, "e": 10697, "s": 10674, "text": "An optional flash hash" }, { "code": null, "e": 10822, "s": 10697, "text": "In this tutorial, we will see how to use get method to test our controller. You can test rest of the methods in similar way." }, { "code": null, "e": 10939, "s": 10822, "text": "When you generate a controller with generate, Rails creates a functional test script for the controller as follows −" }, { "code": null, "e": 11227, "s": 10939, "text": "testapp > ruby script/generate controller Book\n exists app/controllers/\n exists app/helpers/\n create app/views/book\n exists test/functional/\n create app/controllers/book_controller.rb\n create test/functional/book_controller_test.rb\n create app/helpers/book_helper.rb" }, { "code": null, "e": 11450, "s": 11227, "text": "As you write code in the controller classes, you'll write corresponding tests in these files. Before that, let's define our controller functions list, show, and search inside app/controllers/book_controller.rb as follows −" }, { "code": null, "e": 11892, "s": 11450, "text": "class BookController < ApplicationController\n def list\n @book_pages, @books = paginate :books, :per_page => 10\n end\n\n def show\n @book = Book.find(params[:id])\n end\n\n def search\n @book = Book.find_by_title(params[:title])\n if @book\n redirect_to :action => 'show', :id => @book.id\n else \n flash[:error] = 'No such book available'\n redirect_to :action => 'list'\n end\n end\nend" }, { "code": null, "e": 12063, "s": 11892, "text": "NOTE − You would need two views templates for show and list method. You can define those views and test them, but right now, we will proceed without defining those views." }, { "code": null, "e": 12154, "s": 12063, "text": "Now let's reuse our test fixture which is in the test/fixtures/books.yml file as follows −" }, { "code": null, "e": 12376, "s": 12154, "text": "perl_cb:\n id: 1\n title: 'Ruby Tutorial'\n price: 102.00\n description : 'This is a nice Ruby tutorial'\njava_cb:\n id: 2\n title: 'Java Programming'\n price: 62.00\n description : 'Java Programming for the beginners'" }, { "code": null, "e": 12554, "s": 12376, "text": "Add the following test_search_book and test_search_not_found methods to test/functional/book_controller_test.rb to test the functionality of the Book Controller's search action." }, { "code": null, "e": 13429, "s": 12554, "text": "require File.dirname(__FILE__) + '/../test_helper'\nrequire 'book_controller'\n\n# Re-raise errors caught by the controller.\nclass BookController\n def rescue_action(e) \n raise e \n end\nend\n\nclass BookControllerTest < Test::Unit::TestCase\n fixtures :books\n def setup\n @controller = BookController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n end\n\n def test_search_book\n get :search, :title => 'Ruby Tutorial'\n assert_not_nil assigns(:book)\n assert_equal books(:perl_cb).title, assigns(:book).title\n assert_valid assigns(:book)\n assert_redirected_to :action => 'show'\n end\n\n def test_search_not_found\n get :search, :title => 'HTML Tutorial'\n assert_redirected_to :action => 'list'\n assert_equal 'No such book available', flash[:error]\n end\nend" }, { "code": null, "e": 13466, "s": 13429, "text": "Now run your test cases as follows −" }, { "code": null, "e": 13523, "s": 13466, "text": "testapp > ruby test/functional/book_controller_test.rb \n" }, { "code": null, "e": 13555, "s": 13523, "text": "It gives the following output −" }, { "code": null, "e": 13689, "s": 13555, "text": "Loaded suite test/functional/book_controller_test\nStarted\n..\nFinished in 0.422 seconds.\n\n2 tests, 7 assertions, 0 failures, 0 errors\n" }, { "code": null, "e": 13728, "s": 13689, "text": "Let's analyze what has happened here −" }, { "code": null, "e": 13858, "s": 13728, "text": "The setup method is a default method to create controller, request, and response objects. They would be used by Rails internally." }, { "code": null, "e": 13988, "s": 13858, "text": "The setup method is a default method to create controller, request, and response objects. They would be used by Rails internally." }, { "code": null, "e": 14103, "s": 13988, "text": "The first test method test_search_book generates a get request to the search action, passing in a title parameter." }, { "code": null, "e": 14218, "s": 14103, "text": "The first test method test_search_book generates a get request to the search action, passing in a title parameter." }, { "code": null, "e": 14390, "s": 14218, "text": "The next two assertions verify that a Book object was saved in an instance variable called @book and that the object passes any Active Record validations that might exist." }, { "code": null, "e": 14562, "s": 14390, "text": "The next two assertions verify that a Book object was saved in an instance variable called @book and that the object passes any Active Record validations that might exist." }, { "code": null, "e": 14673, "s": 14562, "text": "The final assertion inside first method tests that the request was redirected to the controller's show action." }, { "code": null, "e": 14784, "s": 14673, "text": "The final assertion inside first method tests that the request was redirected to the controller's show action." }, { "code": null, "e": 14891, "s": 14784, "text": "The second test method, test_search_not_found, performs another get request but passes in an invalid title" }, { "code": null, "e": 14998, "s": 14891, "text": "The second test method, test_search_not_found, performs another get request but passes in an invalid title" }, { "code": null, "e": 15071, "s": 14998, "text": "The first assertions test that a redirect to the list action was issued." }, { "code": null, "e": 15144, "s": 15071, "text": "The first assertions test that a redirect to the list action was issued." }, { "code": null, "e": 15264, "s": 15144, "text": "If the proceeding assertions passed, there should be a message in the flash hash which you can test with assert_equal.." }, { "code": null, "e": 15384, "s": 15264, "text": "If the proceeding assertions passed, there should be a message in the flash hash which you can test with assert_equal.." }, { "code": null, "e": 15469, "s": 15384, "text": "To obtain more information on Assertions, please refer Rails Standard Documentation." }, { "code": null, "e": 15570, "s": 15469, "text": "You can use rake utility to test your applications. Given below is a list of few important commands." }, { "code": null, "e": 15664, "s": 15570, "text": "$rake test − Test all unit tests and functional tests (and integration tests, if they exist)." }, { "code": null, "e": 15758, "s": 15664, "text": "$rake test − Test all unit tests and functional tests (and integration tests, if they exist)." }, { "code": null, "e": 15808, "s": 15758, "text": "$rake test:functionals− Run all functional tests." }, { "code": null, "e": 15858, "s": 15808, "text": "$rake test:functionals− Run all functional tests." }, { "code": null, "e": 15897, "s": 15858, "text": "$rake test:units − Run all unit tests." }, { "code": null, "e": 15936, "s": 15897, "text": "$rake test:units − Run all unit tests." }, { "code": null, "e": 15988, "s": 15936, "text": "$rake test:integration − Run all integration tests." }, { "code": null, "e": 16040, "s": 15988, "text": "$rake test:integration − Run all integration tests." }, { "code": null, "e": 16103, "s": 16040, "text": "$rake test:plugins − Run all test in ./vendor/plugins/**/test." }, { "code": null, "e": 16166, "s": 16103, "text": "$rake test:plugins − Run all test in ./vendor/plugins/**/test." }, { "code": null, "e": 16272, "s": 16166, "text": "$rake test:recent − Run tests for models and controllers that have been modified in the last 10 minutes −" }, { "code": null, "e": 16378, "s": 16272, "text": "$rake test:recent − Run tests for models and controllers that have been modified in the last 10 minutes −" }, { "code": null, "e": 16527, "s": 16378, "text": "$rake test:uncommitted − For projects in Subversion, run tests for the changes that took place in the models and controllers since the last commit −" } ]
Number of n-digits non-decreasing integers
10 Sep, 2021 Given an integer n > 0, which denotes the number of digits, the task to find the total number of n-digit positive integers which are non-decreasing in nature. A non-decreasing integer is one in which all the digits from left to right are in non-decreasing form. ex: 1234, 1135, ..etc. Note: Leading zeros also count in non-decreasing integers such as 0000, 0001, 0023, etc are also non-decreasing integers of 4-digits. Examples : Input : n = 1 Output : 10 Numbers are 0, 1, 2, ...9. Input : n = 2 Output : 55 Input : n = 4 Output : 715 Naive Approach: We generate all possible n-digit numbers and then for each number we check whether it is non-decreasing or not. Time Complexity : (n*10^n), where 10^n is for generating all possible n-digits numbers and n is for checking whether a particular number is non-decreasing or not.Dynamic Programming: If we fill digits one by one from left to right, the following conditions hold. If current last digit is 9, we can fill only 9s in remaining places. So only one solution is possible if current last digit is 9.If current last digit is less than 9, then we can recursively compute count using following formula. If current last digit is 9, we can fill only 9s in remaining places. So only one solution is possible if current last digit is 9. If current last digit is less than 9, then we can recursively compute count using following formula. a[i][j] = a[i-1][j] + a[i][j + 1] For every digit j smaller than 9. We consider previous length count and count to be increased by all greater digits. We build a matrix a[][] where a[i][j] = count of all valid i-digit non-decreasing integers with j or greater than j as the leading digit. The solution is based on below observations. We fill this matrix column-wise, first calculating a[1][9] then using this value to compute a[2][8] and so on. At any instant if we wish to calculate a[i][j] means number of i-digits non-decreasing integers with leading digit as j or digit greater than j, we should add up a[i-1][j] (number of i-1 digit integers which should start from j or greater digit, because in this case if we place j as its left most digit then our number will be i-digit non-decreasing number) and a[i][j+1] (number of i-digit integers which should start with digit equals to greater than j+1). So, a[i][j] = a[i-1][j] + a[i][j+1]. C++ Java Python3 C# PHP Javascript // C++ program for counting n digit numbers with// non decreasing digits#include <bits/stdc++.h>using namespace std; // Returns count of non- decreasing numbers with// n digits.int nonDecNums(int n){ /* a[i][j] = count of all possible number with i digits having leading digit as j */ int a[n + 1][10]; // Initialization of all 0-digit number for (int i = 0; i <= 9; i++) a[0][i] = 1; /* Initialization of all i-digit non-decreasing number leading with 9*/ for (int i = 1; i <= n; i++) a[i][9] = 1; /* for all digits we should calculate number of ways depending upon leading digits*/ for (int i = 1; i <= n; i++) for (int j = 8; j >= 0; j--) a[i][j] = a[i - 1][j] + a[i][j + 1]; return a[n][0];} // driver programint main(){ int n = 2; cout << "Non-decreasing digits = " << nonDecNums(n) << endl; return 0;} // Java program for counting n digit numbers with// non decreasing digitsimport java.io.*; class GFG { // Function that returns count of non- decreasing numbers // with n digits static int nonDecNums(int n) { // a[i][j] = count of all possible number // with i digits having leading digit as j int[][] a = new int[n + 1][10]; // Initialization of all 0-digit number for (int i = 0; i <= 9; i++) a[0][i] = 1; // Initialization of all i-digit // non-decreasing number leading with 9 for (int i = 1; i <= n; i++) a[i][9] = 1; // for all digits we should calculate // number of ways depending upon leading // digits for (int i = 1; i <= n; i++) for (int j = 8; j >= 0; j--) a[i][j] = a[i - 1][j] + a[i][j + 1]; return a[n][0]; } // driver program public static void main(String[] args) { int n = 2; System.out.println("Non-decreasing digits = " + nonDecNums(n)); }} // Contributed by Pramod Kumar # Python3 program for counting n digit# numbers with non decreasing digitsimport numpy as np # Returns count of non- decreasing# numbers with n digits.def nonDecNums(n) : # a[i][j] = count of all possible number # with i digits having leading digit as j a = np.zeros((n + 1, 10)) # Initialization of all 0-digit number for i in range(10) : a[0][i] = 1 # Initialization of all i-digit # non-decreasing number leading with 9 for i in range(1, n + 1) : a[i][9] = 1 # for all digits we should calculate # number of ways depending upon # leading digits for i in range(1, n + 1) : for j in range(8, -1, -1) : a[i][j] = a[i - 1][j] + a[i][j + 1] return int(a[n][0]) # Driver Codeif __name__ == "__main__" : n = 2 print("Non-decreasing digits = ", nonDecNums(n)) # This code is contributed by Ryuga // C# function to find number of diagonals// in n sided convex polygonusing System; class GFG { // Function that returns count of non- // decreasing numbers with n digits static int nonDecNums(int n) { // a[i][j] = count of all possible number // with i digits having leading digit as j int[, ] a = new int[n + 1, 10]; // Initialization of all 0-digit number for (int i = 0; i <= 9; i++) a[0, i] = 1; // Initialization of all i-digit // non-decreasing number leading with 9 for (int i = 1; i <= n; i++) a[i, 9] = 1; // for all digits we should calculate // number of ways depending upon leading // digits for (int i = 1; i <= n; i++) for (int j = 8; j >= 0; j--) a[i, j] = a[i - 1, j] + a[i, j + 1]; return a[n, 0]; } // driver program public static void Main() { int n = 2; Console.WriteLine("Non-decreasing digits = " + nonDecNums(n)); }} // This code is contributed by Sam007 <?php// PHP program for counting// n digit numbers with// non decreasing digits // Returns count of non-// decreasing numbers with// n digits. function nonDecNums($n){ /* a[i][j] = count of all possible number with i digits having leading digit as j */ // Initialization of // all 0-digit number for ($i = 0; $i <= 9; $i++) $a[0][$i] = 1; /* Initialization of all i-digit non-decreasing number leading with 9*/ for ($i = 1; $i <= $n; $i++) $a[$i][9] = 1; /* for all digits we should calculate number of ways depending upon leading digits*/ for ($i = 1; $i <= $n; $i++) for ($j = 8; $j >= 0; $j--) $a[$i][$j] = $a[$i - 1][$j] + $a[$i][$j + 1]; return $a[$n][0];} // Driver Code$n = 2;echo "Non-decreasing digits = ", nonDecNums($n),"\n"; // This code is contributed by m_kit?> <script> // Javascript program for counting n digit // numbers with non decreasing digits // Function that returns count // of non- decreasing numbers // with n digits function nonDecNums(n) { // a[i][j] = count of all possible number // with i digits having leading digit as j let a = new Array(n + 1) for (let i = 0; i < n + 1; i++) { a[i] = new Array(10); } // Initialization of all 0-digit number for (let i = 0; i <= 9; i++) a[0][i] = 1; // Initialization of all i-digit // non-decreasing number leading with 9 for (let i = 1; i <= n; i++) a[i][9] = 1; // for all digits we should calculate // number of ways depending upon leading // digits for (let i = 1; i <= n; i++) for (let j = 8; j >= 0; j--) a[i][j] = a[i - 1][j] + a[i][j + 1]; return a[n][0]; } let n = 2; document.write( "Non-decreasing digits = " + nonDecNums(n) ); </script> Non-decreasing digits = 55 Output : Non-decreasing digits = 55 Time Complexity : O(10*n) equivalent to O(n). Another Approach: If we observe, we can see that 0 has to be placed before 1-9, 1 has to be placed before 2-9 and so on. As we are asked to find non-decreasing integers, 111223 is a valid non-decreasing integer which means same digit can occur conscuetively. Example 1: When N=2, we have 11C9, which is equal to 55. Example 2: When N=5, we have 14C9, which is equal to 2002. C++ Java Python3 C# Javascript // CPP program To calculate Number of n-digits non-decreasing integers//Contributed by Parishrut Kushwaha//#include <bits/stdc++.h>using namespace std; // Returns factorial of nlong long int fact(int n){ long long int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // returns nCrlong long int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Driver codeint main(){ int n = 2; cout <<"Number of Non-Decreasing digits: "<< nCr(n+9,9); return 0;} // Java program To calculate Number// of n-digits non-decreasing integersclass GFG { // Returns factorial of n static long fact(int n) { long res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } // returns nCr static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Driver code public static void main(String[] args) { int n = 2; System.out.println( "Number of Non-Decreasing digits: " + nCr(n + 9, 9)); }} // This code is contributed by rajsanghavi9. # Python program To calculate Number of n-digits non-decreasing integers#Contributed by Parishrut Kushwaha## Returns factorial of ndef fact(n): res = 1 for i in range (2,n+1): res = res * i return res # returns nCrdef nCr(n, r): return fact(n) // ((fact(r) * fact(n - r))) # Driver coden = 2print("Number of Non-Decreasing digits: " , nCr(n+9,9)) # This code is contributed by shivanisinghss2110 // C# program To calculate Number// of n-digits non-decreasing integersusing System; class GFG { // Returns factorial of n static long fact(int n) { long res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } // returns nCr static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Driver code public static void Main(String[] args) { int n = 2; Console.Write("Number of Non-Decreasing digits: " + nCr(n + 9, 9)); }} // This code is contributed by shivanisinghss2110 <script>// JavaScript program To calculate Number// of n-digits non-decreasing integers // Returns factorial of n function fact( n) { var res = 1; for (var i = 2; i <= n; i++) res = res * i; return res; } // returns nCr function nCr(n, r) { return fact(n) / (fact(r) * fact(n - r)); } // Driver code var n = 2; document.write("Number of Non-Decreasing digits: " + nCr(n + 9, 9)); // This code is contributed by shivanisinghss2110. </script> Number of Non-Decreasing digits: 55 Time Complexity : O(n). Space Complexity: O(n) .This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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. Sam007 jit_t ankthon suresh07 parishrutkushwaha rajsanghavi9 shivanisinghss2110 number-digits Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Sep, 2021" }, { "code": null, "e": 484, "s": 52, "text": "Given an integer n > 0, which denotes the number of digits, the task to find the total number of n-digit positive integers which are non-decreasing in nature. A non-decreasing integer is one in which all the digits from left to right are in non-decreasing form. ex: 1234, 1135, ..etc. Note: Leading zeros also count in non-decreasing integers such as 0000, 0001, 0023, etc are also non-decreasing integers of 4-digits. Examples : " }, { "code": null, "e": 592, "s": 484, "text": "Input : n = 1\nOutput : 10\nNumbers are 0, 1, 2, ...9.\n\nInput : n = 2\nOutput : 55\n\nInput : n = 4\nOutput : 715" }, { "code": null, "e": 987, "s": 594, "text": "Naive Approach: We generate all possible n-digit numbers and then for each number we check whether it is non-decreasing or not. Time Complexity : (n*10^n), where 10^n is for generating all possible n-digits numbers and n is for checking whether a particular number is non-decreasing or not.Dynamic Programming: If we fill digits one by one from left to right, the following conditions hold. " }, { "code": null, "e": 1219, "s": 987, "text": "If current last digit is 9, we can fill only 9s in remaining places. So only one solution is possible if current last digit is 9.If current last digit is less than 9, then we can recursively compute count using following formula. " }, { "code": null, "e": 1349, "s": 1219, "text": "If current last digit is 9, we can fill only 9s in remaining places. So only one solution is possible if current last digit is 9." }, { "code": null, "e": 1452, "s": 1349, "text": "If current last digit is less than 9, then we can recursively compute count using following formula. " }, { "code": null, "e": 1614, "s": 1452, "text": "a[i][j] = a[i-1][j] + a[i][j + 1] \n For every digit j smaller than 9.\n\nWe consider previous length count and count\nto be increased by all greater digits." }, { "code": null, "e": 2407, "s": 1614, "text": "We build a matrix a[][] where a[i][j] = count of all valid i-digit non-decreasing integers with j or greater than j as the leading digit. The solution is based on below observations. We fill this matrix column-wise, first calculating a[1][9] then using this value to compute a[2][8] and so on. At any instant if we wish to calculate a[i][j] means number of i-digits non-decreasing integers with leading digit as j or digit greater than j, we should add up a[i-1][j] (number of i-1 digit integers which should start from j or greater digit, because in this case if we place j as its left most digit then our number will be i-digit non-decreasing number) and a[i][j+1] (number of i-digit integers which should start with digit equals to greater than j+1). So, a[i][j] = a[i-1][j] + a[i][j+1]. " }, { "code": null, "e": 2413, "s": 2409, "text": "C++" }, { "code": null, "e": 2418, "s": 2413, "text": "Java" }, { "code": null, "e": 2426, "s": 2418, "text": "Python3" }, { "code": null, "e": 2429, "s": 2426, "text": "C#" }, { "code": null, "e": 2433, "s": 2429, "text": "PHP" }, { "code": null, "e": 2444, "s": 2433, "text": "Javascript" }, { "code": "// C++ program for counting n digit numbers with// non decreasing digits#include <bits/stdc++.h>using namespace std; // Returns count of non- decreasing numbers with// n digits.int nonDecNums(int n){ /* a[i][j] = count of all possible number with i digits having leading digit as j */ int a[n + 1][10]; // Initialization of all 0-digit number for (int i = 0; i <= 9; i++) a[0][i] = 1; /* Initialization of all i-digit non-decreasing number leading with 9*/ for (int i = 1; i <= n; i++) a[i][9] = 1; /* for all digits we should calculate number of ways depending upon leading digits*/ for (int i = 1; i <= n; i++) for (int j = 8; j >= 0; j--) a[i][j] = a[i - 1][j] + a[i][j + 1]; return a[n][0];} // driver programint main(){ int n = 2; cout << \"Non-decreasing digits = \" << nonDecNums(n) << endl; return 0;}", "e": 3343, "s": 2444, "text": null }, { "code": "// Java program for counting n digit numbers with// non decreasing digitsimport java.io.*; class GFG { // Function that returns count of non- decreasing numbers // with n digits static int nonDecNums(int n) { // a[i][j] = count of all possible number // with i digits having leading digit as j int[][] a = new int[n + 1][10]; // Initialization of all 0-digit number for (int i = 0; i <= 9; i++) a[0][i] = 1; // Initialization of all i-digit // non-decreasing number leading with 9 for (int i = 1; i <= n; i++) a[i][9] = 1; // for all digits we should calculate // number of ways depending upon leading // digits for (int i = 1; i <= n; i++) for (int j = 8; j >= 0; j--) a[i][j] = a[i - 1][j] + a[i][j + 1]; return a[n][0]; } // driver program public static void main(String[] args) { int n = 2; System.out.println(\"Non-decreasing digits = \" + nonDecNums(n)); }} // Contributed by Pramod Kumar", "e": 4422, "s": 3343, "text": null }, { "code": "# Python3 program for counting n digit# numbers with non decreasing digitsimport numpy as np # Returns count of non- decreasing# numbers with n digits.def nonDecNums(n) : # a[i][j] = count of all possible number # with i digits having leading digit as j a = np.zeros((n + 1, 10)) # Initialization of all 0-digit number for i in range(10) : a[0][i] = 1 # Initialization of all i-digit # non-decreasing number leading with 9 for i in range(1, n + 1) : a[i][9] = 1 # for all digits we should calculate # number of ways depending upon # leading digits for i in range(1, n + 1) : for j in range(8, -1, -1) : a[i][j] = a[i - 1][j] + a[i][j + 1] return int(a[n][0]) # Driver Codeif __name__ == \"__main__\" : n = 2 print(\"Non-decreasing digits = \", nonDecNums(n)) # This code is contributed by Ryuga", "e": 5326, "s": 4422, "text": null }, { "code": "// C# function to find number of diagonals// in n sided convex polygonusing System; class GFG { // Function that returns count of non- // decreasing numbers with n digits static int nonDecNums(int n) { // a[i][j] = count of all possible number // with i digits having leading digit as j int[, ] a = new int[n + 1, 10]; // Initialization of all 0-digit number for (int i = 0; i <= 9; i++) a[0, i] = 1; // Initialization of all i-digit // non-decreasing number leading with 9 for (int i = 1; i <= n; i++) a[i, 9] = 1; // for all digits we should calculate // number of ways depending upon leading // digits for (int i = 1; i <= n; i++) for (int j = 8; j >= 0; j--) a[i, j] = a[i - 1, j] + a[i, j + 1]; return a[n, 0]; } // driver program public static void Main() { int n = 2; Console.WriteLine(\"Non-decreasing digits = \" + nonDecNums(n)); }} // This code is contributed by Sam007", "e": 6433, "s": 5326, "text": null }, { "code": "<?php// PHP program for counting// n digit numbers with// non decreasing digits // Returns count of non-// decreasing numbers with// n digits. function nonDecNums($n){ /* a[i][j] = count of all possible number with i digits having leading digit as j */ // Initialization of // all 0-digit number for ($i = 0; $i <= 9; $i++) $a[0][$i] = 1; /* Initialization of all i-digit non-decreasing number leading with 9*/ for ($i = 1; $i <= $n; $i++) $a[$i][9] = 1; /* for all digits we should calculate number of ways depending upon leading digits*/ for ($i = 1; $i <= $n; $i++) for ($j = 8; $j >= 0; $j--) $a[$i][$j] = $a[$i - 1][$j] + $a[$i][$j + 1]; return $a[$n][0];} // Driver Code$n = 2;echo \"Non-decreasing digits = \", nonDecNums($n),\"\\n\"; // This code is contributed by m_kit?>", "e": 7328, "s": 6433, "text": null }, { "code": "<script> // Javascript program for counting n digit // numbers with non decreasing digits // Function that returns count // of non- decreasing numbers // with n digits function nonDecNums(n) { // a[i][j] = count of all possible number // with i digits having leading digit as j let a = new Array(n + 1) for (let i = 0; i < n + 1; i++) { a[i] = new Array(10); } // Initialization of all 0-digit number for (let i = 0; i <= 9; i++) a[0][i] = 1; // Initialization of all i-digit // non-decreasing number leading with 9 for (let i = 1; i <= n; i++) a[i][9] = 1; // for all digits we should calculate // number of ways depending upon leading // digits for (let i = 1; i <= n; i++) for (let j = 8; j >= 0; j--) a[i][j] = a[i - 1][j] + a[i][j + 1]; return a[n][0]; } let n = 2; document.write( \"Non-decreasing digits = \" + nonDecNums(n) ); </script>", "e": 8407, "s": 7328, "text": null }, { "code": null, "e": 8434, "s": 8407, "text": "Non-decreasing digits = 55" }, { "code": null, "e": 8445, "s": 8434, "text": "Output : " }, { "code": null, "e": 8472, "s": 8445, "text": "Non-decreasing digits = 55" }, { "code": null, "e": 8518, "s": 8472, "text": "Time Complexity : O(10*n) equivalent to O(n)." }, { "code": null, "e": 8537, "s": 8518, "text": "Another Approach: " }, { "code": null, "e": 8778, "s": 8537, "text": "If we observe, we can see that 0 has to be placed before 1-9, 1 has to be placed before 2-9 and so on. As we are asked to find non-decreasing integers, 111223 is a valid non-decreasing integer which means same digit can occur conscuetively." }, { "code": null, "e": 8835, "s": 8778, "text": "Example 1: When N=2, we have 11C9, which is equal to 55." }, { "code": null, "e": 8894, "s": 8835, "text": "Example 2: When N=5, we have 14C9, which is equal to 2002." }, { "code": null, "e": 8898, "s": 8894, "text": "C++" }, { "code": null, "e": 8903, "s": 8898, "text": "Java" }, { "code": null, "e": 8911, "s": 8903, "text": "Python3" }, { "code": null, "e": 8914, "s": 8911, "text": "C#" }, { "code": null, "e": 8925, "s": 8914, "text": "Javascript" }, { "code": "// CPP program To calculate Number of n-digits non-decreasing integers//Contributed by Parishrut Kushwaha//#include <bits/stdc++.h>using namespace std; // Returns factorial of nlong long int fact(int n){ long long int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // returns nCrlong long int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Driver codeint main(){ int n = 2; cout <<\"Number of Non-Decreasing digits: \"<< nCr(n+9,9); return 0;}", "e": 9433, "s": 8925, "text": null }, { "code": "// Java program To calculate Number// of n-digits non-decreasing integersclass GFG { // Returns factorial of n static long fact(int n) { long res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } // returns nCr static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Driver code public static void main(String[] args) { int n = 2; System.out.println( \"Number of Non-Decreasing digits: \" + nCr(n + 9, 9)); }} // This code is contributed by rajsanghavi9.", "e": 10036, "s": 9433, "text": null }, { "code": "# Python program To calculate Number of n-digits non-decreasing integers#Contributed by Parishrut Kushwaha## Returns factorial of ndef fact(n): res = 1 for i in range (2,n+1): res = res * i return res # returns nCrdef nCr(n, r): return fact(n) // ((fact(r) * fact(n - r))) # Driver coden = 2print(\"Number of Non-Decreasing digits: \" , nCr(n+9,9)) # This code is contributed by shivanisinghss2110 ", "e": 10467, "s": 10036, "text": null }, { "code": "// C# program To calculate Number// of n-digits non-decreasing integersusing System; class GFG { // Returns factorial of n static long fact(int n) { long res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } // returns nCr static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Driver code public static void Main(String[] args) { int n = 2; Console.Write(\"Number of Non-Decreasing digits: \" + nCr(n + 9, 9)); }} // This code is contributed by shivanisinghss2110", "e": 11059, "s": 10467, "text": null }, { "code": "<script>// JavaScript program To calculate Number// of n-digits non-decreasing integers // Returns factorial of n function fact( n) { var res = 1; for (var i = 2; i <= n; i++) res = res * i; return res; } // returns nCr function nCr(n, r) { return fact(n) / (fact(r) * fact(n - r)); } // Driver code var n = 2; document.write(\"Number of Non-Decreasing digits: \" + nCr(n + 9, 9)); // This code is contributed by shivanisinghss2110. </script>", "e": 11583, "s": 11059, "text": null }, { "code": null, "e": 11619, "s": 11583, "text": "Number of Non-Decreasing digits: 55" }, { "code": null, "e": 11644, "s": 11619, "text": "Time Complexity : O(n)." }, { "code": null, "e": 12109, "s": 11644, "text": "Space Complexity: O(n) .This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 12116, "s": 12109, "text": "Sam007" }, { "code": null, "e": 12122, "s": 12116, "text": "jit_t" }, { "code": null, "e": 12130, "s": 12122, "text": "ankthon" }, { "code": null, "e": 12139, "s": 12130, "text": "suresh07" }, { "code": null, "e": 12157, "s": 12139, "text": "parishrutkushwaha" }, { "code": null, "e": 12170, "s": 12157, "text": "rajsanghavi9" }, { "code": null, "e": 12189, "s": 12170, "text": "shivanisinghss2110" }, { "code": null, "e": 12203, "s": 12189, "text": "number-digits" }, { "code": null, "e": 12223, "s": 12203, "text": "Dynamic Programming" }, { "code": null, "e": 12243, "s": 12223, "text": "Dynamic Programming" } ]
How to Add Views Dynamically and Store Data in Arraylist in Android?
31 Aug, 2021 Dynamic Views are created when we don’t want to have repeating XML code. In this article we will create a separate layout and inflate them inside a LinearLayout after that we will store the user data in an ArrayList as then display them as toast. 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 View Binding dependency inside the build.gradle(app) and click on the sync now button. android { .. buildFeatures { viewBinding true } } 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. Notice that it has a Linear Layout with id parent_linear_layout which we will inflate to add our views. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="15dp" android:text="Programming Language List" android:textColor="@color/black" android:textSize="15sp" /> <!--This is the parent linear layout which we will inflate soon--> <LinearLayout android:id="@+id/parent_linear_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" /> <com.google.android.material.button.MaterialButton android:id="@+id/button_add" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_marginLeft="15dp" android:layout_marginTop="10dp" android:drawableRight="@drawable/ic_add" android:paddingLeft="10dp" android:paddingRight="10dp" android:text="Add" android:textAllCaps="false" android:textColor="@color/white" /> <com.google.android.material.button.MaterialButton android:id="@+id/button_submit_list" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginLeft="15dp" android:layout_marginTop="10dp" android:layout_marginRight="15dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:text="Submit List" android:textAllCaps="false" android:textColor="@color/white" /> <com.google.android.material.button.MaterialButton android:id="@+id/button_show_list" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginLeft="15dp" android:layout_marginTop="10dp" android:layout_marginRight="15dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:text="Show List Data" android:textAllCaps="false" android:textColor="@color/white" /> </LinearLayout> Step 4: Create a new layout Create a new layout named row_add_language.xml. This is the separate layout that we will inflate inside the Linear Layout with id parent_linear_layout. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp"> <EditText android:id="@+id/et_name" android:layout_width="200dp" android:layout_height="50dp" android:hint="Enter language" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Spinner android:id="@+id/exp_spinner" android:layout_width="100dp" android:layout_height="50dp" android:layout_marginStart="20dp" android:entries="@array/experience" app:layout_constraintLeft_toRightOf="@id/et_name" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout> Step 5: Add the entries item in string.xml that we have used in Spinner XML <string-array name="experience"> <item>Exp</item> <item>1 Year</item> <item>2 Year</item> <item>3 Year</item> <item>4 Year</item> </string-array> Step 6: Create a new Kotlin class Create a new Kotlin class Language.kt. This is the generic class which we will use for Arraylist to Store data. Kotlin class Language( var name: String = "", var exp: String = "") {} Step 7: 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.view.LayoutInflaterimport android.view.Viewimport android.widget.EditTextimport android.widget.Spinnerimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity // Provide your package name hereimport com.example.addviewsdynamically.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // initiate viewBinding private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! // create an arraylist in which // we will store user data private var languageList = ArrayList<Language>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // This addButton is used to add a new view // in the parent linear layout binding.buttonAdd.setOnClickListener { addNewView() } // This Submit Button is used to store all the // data entered by user in arraylist binding.buttonSubmitList.setOnClickListener { saveData() } // This Show button is used to show data // stored in the arraylist. binding.buttonShowList.setOnClickListener { showData() } } // This function is called after // user clicks on addButton private fun addNewView() { // this method inflates the single item layout // inside the parent linear layout val inflater = LayoutInflater.from(this).inflate(R.layout.row_add_language, null) binding.parentLinearLayout.addView(inflater, binding.parentLinearLayout.childCount) } // This function is called after user // clicks on Submit Button private fun saveData() { languageList.clear() // this counts the no of child layout // inside the parent Linear layout val count = binding.parentLinearLayout.childCount var v: View? for (i in 0 until count) { v = binding.parentLinearLayout.getChildAt(i) val languageName: EditText = v.findViewById(R.id.et_name) val experience: Spinner = v.findViewById(R.id.exp_spinner) // create an object of Language class val language = Language() language.name = languageName.text.toString() language.exp = experience.selectedItem as String // add the data to arraylist languageList.add(language) } } // This function is called after user // clicks on Show List data button private fun showData() { val count = binding.parentLinearLayout.childCount for (i in 0 until count) { Toast.makeText(this, "Language at $i is ${languageList[i].name} and experience is ${languageList[i].exp} ", Toast.LENGTH_SHORT).show() } } override fun onDestroy() { super.onDestroy() _binding = null }} Github repo here. gulshankumarar231 android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Aug, 2021" }, { "code": null, "e": 470, "s": 54, "text": "Dynamic Views are created when we don’t want to have repeating XML code. In this article we will create a separate layout and inflate them inside a LinearLayout after that we will store the user data in an ArrayList as then display them as toast. 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": 499, "s": 470, "text": "Step 1: Create a new project" }, { "code": null, "e": 662, "s": 499, "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": 710, "s": 662, "text": "Step 2: Add dependency inside build.gradle(app)" }, { "code": null, "e": 801, "s": 710, "text": "Add View Binding dependency inside the build.gradle(app) and click on the sync now button." }, { "code": null, "e": 811, "s": 801, "text": "android {" }, { "code": null, "e": 814, "s": 811, "text": ".." }, { "code": null, "e": 831, "s": 814, "text": " buildFeatures {" }, { "code": null, "e": 855, "s": 831, "text": " viewBinding true" }, { "code": null, "e": 860, "s": 855, "text": " }" }, { "code": null, "e": 862, "s": 860, "text": "}" }, { "code": null, "e": 910, "s": 862, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 1130, "s": 910, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Notice that it has a Linear Layout with id parent_linear_layout which we will inflate to add our views." }, { "code": null, "e": 1134, "s": 1130, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"15dp\" android:text=\"Programming Language List\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> <!--This is the parent linear layout which we will inflate soon--> <LinearLayout android:id=\"@+id/parent_linear_layout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" /> <com.google.android.material.button.MaterialButton android:id=\"@+id/button_add\" android:layout_width=\"wrap_content\" android:layout_height=\"50dp\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"10dp\" android:drawableRight=\"@drawable/ic_add\" android:paddingLeft=\"10dp\" android:paddingRight=\"10dp\" android:text=\"Add\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> <com.google.android.material.button.MaterialButton android:id=\"@+id/button_submit_list\" android:layout_width=\"match_parent\" android:layout_height=\"50dp\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"15dp\" android:paddingLeft=\"10dp\" android:paddingRight=\"10dp\" android:text=\"Submit List\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> <com.google.android.material.button.MaterialButton android:id=\"@+id/button_show_list\" android:layout_width=\"match_parent\" android:layout_height=\"50dp\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"10dp\" android:layout_marginRight=\"15dp\" android:paddingLeft=\"10dp\" android:paddingRight=\"10dp\" android:text=\"Show List Data\" android:textAllCaps=\"false\" android:textColor=\"@color/white\" /> </LinearLayout>", "e": 3418, "s": 1134, "text": null }, { "code": null, "e": 3447, "s": 3418, "text": "Step 4: Create a new layout " }, { "code": null, "e": 3600, "s": 3447, "text": "Create a new layout named row_add_language.xml. This is the separate layout that we will inflate inside the Linear Layout with id parent_linear_layout. " }, { "code": null, "e": 3604, "s": 3600, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\"> <EditText android:id=\"@+id/et_name\" android:layout_width=\"200dp\" android:layout_height=\"50dp\" android:hint=\"Enter language\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Spinner android:id=\"@+id/exp_spinner\" android:layout_width=\"100dp\" android:layout_height=\"50dp\" android:layout_marginStart=\"20dp\" android:entries=\"@array/experience\" app:layout_constraintLeft_toRightOf=\"@id/et_name\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 4548, "s": 3604, "text": null }, { "code": null, "e": 4621, "s": 4548, "text": "Step 5: Add the entries item in string.xml that we have used in Spinner " }, { "code": null, "e": 4625, "s": 4621, "text": "XML" }, { "code": "<string-array name=\"experience\"> <item>Exp</item> <item>1 Year</item> <item>2 Year</item> <item>3 Year</item> <item>4 Year</item> </string-array>", "e": 4791, "s": 4625, "text": null }, { "code": null, "e": 4826, "s": 4791, "text": "Step 6: Create a new Kotlin class " }, { "code": null, "e": 4940, "s": 4826, "text": "Create a new Kotlin class Language.kt. This is the generic class which we will use for Arraylist to Store data. " }, { "code": null, "e": 4947, "s": 4940, "text": "Kotlin" }, { "code": "class Language( var name: String = \"\", var exp: String = \"\") {}", "e": 5017, "s": 4947, "text": null }, { "code": null, "e": 5063, "s": 5017, "text": "Step 7: Working with the MainActivity.kt file" }, { "code": null, "e": 5250, "s": 5063, "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": 5257, "s": 5250, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.widget.EditTextimport android.widget.Spinnerimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity // Provide your package name hereimport com.example.addviewsdynamically.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // initiate viewBinding private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! // create an arraylist in which // we will store user data private var languageList = ArrayList<Language>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // This addButton is used to add a new view // in the parent linear layout binding.buttonAdd.setOnClickListener { addNewView() } // This Submit Button is used to store all the // data entered by user in arraylist binding.buttonSubmitList.setOnClickListener { saveData() } // This Show button is used to show data // stored in the arraylist. binding.buttonShowList.setOnClickListener { showData() } } // This function is called after // user clicks on addButton private fun addNewView() { // this method inflates the single item layout // inside the parent linear layout val inflater = LayoutInflater.from(this).inflate(R.layout.row_add_language, null) binding.parentLinearLayout.addView(inflater, binding.parentLinearLayout.childCount) } // This function is called after user // clicks on Submit Button private fun saveData() { languageList.clear() // this counts the no of child layout // inside the parent Linear layout val count = binding.parentLinearLayout.childCount var v: View? for (i in 0 until count) { v = binding.parentLinearLayout.getChildAt(i) val languageName: EditText = v.findViewById(R.id.et_name) val experience: Spinner = v.findViewById(R.id.exp_spinner) // create an object of Language class val language = Language() language.name = languageName.text.toString() language.exp = experience.selectedItem as String // add the data to arraylist languageList.add(language) } } // This function is called after user // clicks on Show List data button private fun showData() { val count = binding.parentLinearLayout.childCount for (i in 0 until count) { Toast.makeText(this, \"Language at $i is ${languageList[i].name} and experience is ${languageList[i].exp} \", Toast.LENGTH_SHORT).show() } } override fun onDestroy() { super.onDestroy() _binding = null }}", "e": 8224, "s": 5257, "text": null }, { "code": null, "e": 8244, "s": 8226, "text": "Github repo here." }, { "code": null, "e": 8264, "s": 8246, "text": "gulshankumarar231" }, { "code": null, "e": 8272, "s": 8264, "text": "android" }, { "code": null, "e": 8280, "s": 8272, "text": "Android" }, { "code": null, "e": 8287, "s": 8280, "text": "Kotlin" }, { "code": null, "e": 8295, "s": 8287, "text": "Android" }, { "code": null, "e": 8393, "s": 8295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8425, "s": 8393, "text": "Android SDK and it's Components" }, { "code": null, "e": 8464, "s": 8425, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8513, "s": 8464, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8555, "s": 8513, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 8606, "s": 8555, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 8625, "s": 8606, "text": "Android UI Layouts" }, { "code": null, "e": 8638, "s": 8625, "text": "Kotlin Array" }, { "code": null, "e": 8687, "s": 8638, "text": "How to Communicate Between Fragments in Android?" } ]
Textwrap – Text wrapping and filling in Python
31 May, 2017 The textwrap module can be used for wrapping and formatting of plain text. This module provides formatting of text by adjusting the line breaks in the input paragraph. The TextWrapper instance attributes (and keyword arguments to the constructor) are as follows: width: This refers to the maximum length allowed of the wrapped lines. It’s default value is set to 70. expand_tabs: It’s default value is set to TRUE. If the value is equal to true, then, all the tab characters in the sample input is expanded to spaces using this method. tabsize: It’s default value is set to 8. This method expands all tab characters in text to zero or more spaces, depending on the current column and the given tab size, if the value of expand_tabs is TRUE. replace_whitespace: It’s default value is set to TRUE. If the value is true, after tab expansion but before wrapping, the wrap() method replaces each whitespace character with a single space.These whitespace characters are replaced : tab, newline, vertical tab, formfeed, and carriage return (‘\t\n\v\f\r’). drop_whitespace: It’s default value is set to TRUE. The whitespaces at the beginning and ending of every line (after wrapping but before indenting) is dropped if the value is set to TRUE. initial_indent: It’s default value is set to’ ‘. This method prepends the given string to the first line of wrapped output. subsequent_indent: It’s default value is set to ‘ ‘. This method prepends the given string to all the lines of wrapped output except the first. placeholder: It’s default value is set to ‘ [...]’. This method appends the string at the end of the output text if it has been truncated. max_lines: It’s default value is set to None. If the value is not None, then the output text contains at most max_lines lines, having placeholder at the end of the output. break_long_words: It’s default value is set to True. If TRUE, then words longer than width are broken to fit every line in the given width. If it is FALSE, long words will not be broken and will be put on a line by themselves, in order to minimize the amount by which width is exceeded. break_on_hyphens: It’s default value is set to True. If the value is equal to TRUE, wrapping occurs on whitespaces and right after hyphens in compound words. If the value is equal to FALSE, line breaks occur only on whitespaces, but you need to set break_long_words to FALSE if you want truly insecable words. Functions provided by the Textwrap module : textwrap.wrap(text, width=70, **kwargs): This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Default width is taken as 70.import textwrap value = """This function wraps the input paragraph such that each linein the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.""" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) word_list = wrapper.wrap(text=value) # Print each line.for element in word_list: print(element)Output :This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. textwrap.fill(text, width=70, **kwargs): The fill() convenience function works similar to textwrap.wrap except it returns the data joined into a single, newline-separated string. This function wraps the input single paragraph in text, and returns a single string containing the wrapped paragraph.import textwrap value = """This function returns the answer as STRING and not LIST.""" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) string = wrapper.fill(text=value) print (string)Output :This function returns the answer as STRING and not LIST. textwrap.dedent(text): This function is used to remove any common leading whitespace from every line in the input text. This allows to use docstrings or embedded multi-line strings line up with the left edge of the display, while removing the formatting of the code itself.Example :import textwrap wrapper = textwrap.TextWrapper(width=50) s = '''\ hello world '''print(repr(s)) # prints ' hello\n world\n ' text = textwrap.dedent(s)print(repr(text)) # prints 'hello\n world\n'Output :' hello\n world\n ' 'hello\n world\n' textwrap.shorten(text, width, **kwargs): This function truncates the input string so that the length of the string becomes equal to the given width. At first, all the whitespaces are collapsed in the string by removing the whitespaces with a single space. If the modified string fits in the given string, then it is returned otherwise, the characters from the end are dropped so that the remaining words plus the placeholder fit within width.import textwrap sample_text = """This function wraps the input paragraph such that each linen the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.""" wrapper = textwrap.TextWrapper(width=50) dedented_text = textwrap.dedent(text=sample_text)original = wrapper.fill(text=dedented_text) print('Original:\n')print(original) shortened = textwrap.shorten(text=original, width=100)shortened_wrapped = wrapper.fill(text=shortened) print('\nShortened:\n')print(shortened_wrapped)Output :Original: This function wraps the input paragraph such that each line n the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Shortened: This function wraps the input paragraph such that each line n the paragraph is at most width [...] textwrap.indent(text, prefix, predicate=None): This function is used to add the given prefix to the beginning of the selected lines of the text. The predicate argument can be used to control which lines are indented.import textwrap s = 'hello\n\n \nworld's1 = textwrap.indent(text=s, prefix=' ') print (s1)print ("\n") s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)print (s2)Output :hello world + hello + + + world This article is contributed by Aditi Gupta. 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.My Personal Notes arrow_drop_upSave textwrap.wrap(text, width=70, **kwargs): This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Default width is taken as 70.import textwrap value = """This function wraps the input paragraph such that each linein the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.""" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) word_list = wrapper.wrap(text=value) # Print each line.for element in word_list: print(element)Output :This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. import textwrap value = """This function wraps the input paragraph such that each linein the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.""" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) word_list = wrapper.wrap(text=value) # Print each line.for element in word_list: print(element) Output : This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. textwrap.fill(text, width=70, **kwargs): The fill() convenience function works similar to textwrap.wrap except it returns the data joined into a single, newline-separated string. This function wraps the input single paragraph in text, and returns a single string containing the wrapped paragraph.import textwrap value = """This function returns the answer as STRING and not LIST.""" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) string = wrapper.fill(text=value) print (string)Output :This function returns the answer as STRING and not LIST. import textwrap value = """This function returns the answer as STRING and not LIST.""" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) string = wrapper.fill(text=value) print (string) Output : This function returns the answer as STRING and not LIST. textwrap.dedent(text): This function is used to remove any common leading whitespace from every line in the input text. This allows to use docstrings or embedded multi-line strings line up with the left edge of the display, while removing the formatting of the code itself.Example :import textwrap wrapper = textwrap.TextWrapper(width=50) s = '''\ hello world '''print(repr(s)) # prints ' hello\n world\n ' text = textwrap.dedent(s)print(repr(text)) # prints 'hello\n world\n'Output :' hello\n world\n ' 'hello\n world\n' Example : import textwrap wrapper = textwrap.TextWrapper(width=50) s = '''\ hello world '''print(repr(s)) # prints ' hello\n world\n ' text = textwrap.dedent(s)print(repr(text)) # prints 'hello\n world\n' Output : ' hello\n world\n ' 'hello\n world\n' textwrap.shorten(text, width, **kwargs): This function truncates the input string so that the length of the string becomes equal to the given width. At first, all the whitespaces are collapsed in the string by removing the whitespaces with a single space. If the modified string fits in the given string, then it is returned otherwise, the characters from the end are dropped so that the remaining words plus the placeholder fit within width.import textwrap sample_text = """This function wraps the input paragraph such that each linen the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.""" wrapper = textwrap.TextWrapper(width=50) dedented_text = textwrap.dedent(text=sample_text)original = wrapper.fill(text=dedented_text) print('Original:\n')print(original) shortened = textwrap.shorten(text=original, width=100)shortened_wrapped = wrapper.fill(text=shortened) print('\nShortened:\n')print(shortened_wrapped)Output :Original: This function wraps the input paragraph such that each line n the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Shortened: This function wraps the input paragraph such that each line n the paragraph is at most width [...] import textwrap sample_text = """This function wraps the input paragraph such that each linen the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.""" wrapper = textwrap.TextWrapper(width=50) dedented_text = textwrap.dedent(text=sample_text)original = wrapper.fill(text=dedented_text) print('Original:\n')print(original) shortened = textwrap.shorten(text=original, width=100)shortened_wrapped = wrapper.fill(text=shortened) print('\nShortened:\n')print(shortened_wrapped) Output : Original: This function wraps the input paragraph such that each line n the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Shortened: This function wraps the input paragraph such that each line n the paragraph is at most width [...] textwrap.indent(text, prefix, predicate=None): This function is used to add the given prefix to the beginning of the selected lines of the text. The predicate argument can be used to control which lines are indented.import textwrap s = 'hello\n\n \nworld's1 = textwrap.indent(text=s, prefix=' ') print (s1)print ("\n") s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)print (s2)Output :hello world + hello + + + world import textwrap s = 'hello\n\n \nworld's1 = textwrap.indent(text=s, prefix=' ') print (s1)print ("\n") s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)print (s2) Output : hello world + hello + + + world This article is contributed by Aditi Gupta. 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. Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2017" }, { "code": null, "e": 220, "s": 52, "text": "The textwrap module can be used for wrapping and formatting of plain text. This module provides formatting of text by adjusting the line breaks in the input paragraph." }, { "code": null, "e": 315, "s": 220, "text": "The TextWrapper instance attributes (and keyword arguments to the constructor) are as follows:" }, { "code": null, "e": 419, "s": 315, "text": "width: This refers to the maximum length allowed of the wrapped lines. It’s default value is set to 70." }, { "code": null, "e": 588, "s": 419, "text": "expand_tabs: It’s default value is set to TRUE. If the value is equal to true, then, all the tab characters in the sample input is expanded to spaces using this method." }, { "code": null, "e": 793, "s": 588, "text": "tabsize: It’s default value is set to 8. This method expands all tab characters in text to zero or more spaces, depending on the current column and the given tab size, if the value of expand_tabs is TRUE." }, { "code": null, "e": 1101, "s": 793, "text": "replace_whitespace: It’s default value is set to TRUE. If the value is true, after tab expansion but before wrapping, the wrap() method replaces each whitespace character with a single space.These whitespace characters are replaced : tab, newline, vertical tab, formfeed, and carriage return (‘\\t\\n\\v\\f\\r’)." }, { "code": null, "e": 1289, "s": 1101, "text": "drop_whitespace: It’s default value is set to TRUE. The whitespaces at the beginning and ending of every line (after wrapping but before indenting) is dropped if the value is set to TRUE." }, { "code": null, "e": 1413, "s": 1289, "text": "initial_indent: It’s default value is set to’ ‘. This method prepends the given string to the first line of wrapped output." }, { "code": null, "e": 1557, "s": 1413, "text": "subsequent_indent: It’s default value is set to ‘ ‘. This method prepends the given string to all the lines of wrapped output except the first." }, { "code": null, "e": 1696, "s": 1557, "text": "placeholder: It’s default value is set to ‘ [...]’. This method appends the string at the end of the output text if it has been truncated." }, { "code": null, "e": 1868, "s": 1696, "text": "max_lines: It’s default value is set to None. If the value is not None, then the output text contains at most max_lines lines, having placeholder at the end of the output." }, { "code": null, "e": 2155, "s": 1868, "text": "break_long_words: It’s default value is set to True. If TRUE, then words longer than width are broken to fit every line in the given width. If it is FALSE, long words will not be broken and will be put on a line by themselves, in order to minimize the amount by which width is exceeded." }, { "code": null, "e": 2465, "s": 2155, "text": "break_on_hyphens: It’s default value is set to True. If the value is equal to TRUE, wrapping occurs on whitespaces and right after hyphens in compound words. If the value is equal to FALSE, line breaks occur only on whitespaces, but you need to set break_long_words to FALSE if you want truly insecable words." }, { "code": null, "e": 2509, "s": 2465, "text": "Functions provided by the Textwrap module :" }, { "code": null, "e": 6848, "s": 2509, "text": "textwrap.wrap(text, width=70, **kwargs): This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Default width is taken as 70.import textwrap value = \"\"\"This function wraps the input paragraph such that each linein the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.\"\"\" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) word_list = wrapper.wrap(text=value) # Print each line.for element in word_list: print(element)Output :This function wraps the input paragraph such that\neach line in the paragraph is at most width\ncharacters long. The wrap method returns a list of\noutput lines. The returned list is empty if the\nwrapped output has no content.\ntextwrap.fill(text, width=70, **kwargs): The fill() convenience function works similar to textwrap.wrap except it returns the data joined into a single, newline-separated string. This function wraps the input single paragraph in text, and returns a single string containing the wrapped paragraph.import textwrap value = \"\"\"This function returns the answer as STRING and not LIST.\"\"\" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) string = wrapper.fill(text=value) print (string)Output :This function returns the answer as STRING and not LIST.\ntextwrap.dedent(text): This function is used to remove any common leading whitespace from every line in the input text. This allows to use docstrings or embedded multi-line strings line up with the left edge of the display, while removing the formatting of the code itself.Example :import textwrap wrapper = textwrap.TextWrapper(width=50) s = '''\\ hello world '''print(repr(s)) # prints ' hello\\n world\\n ' text = textwrap.dedent(s)print(repr(text)) # prints 'hello\\n world\\n'Output :' hello\\n world\\n '\n'hello\\n world\\n'\ntextwrap.shorten(text, width, **kwargs): This function truncates the input string so that the length of the string becomes equal to the given width. At first, all the whitespaces are collapsed in the string by removing the whitespaces with a single space. If the modified string fits in the given string, then it is returned otherwise, the characters from the end are dropped so that the remaining words plus the placeholder fit within width.import textwrap sample_text = \"\"\"This function wraps the input paragraph such that each linen the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.\"\"\" wrapper = textwrap.TextWrapper(width=50) dedented_text = textwrap.dedent(text=sample_text)original = wrapper.fill(text=dedented_text) print('Original:\\n')print(original) shortened = textwrap.shorten(text=original, width=100)shortened_wrapped = wrapper.fill(text=shortened) print('\\nShortened:\\n')print(shortened_wrapped)Output :Original:\n\nThis function wraps the input paragraph such that\neach line n the paragraph is at most width\ncharacters long. The wrap method returns a list of\noutput lines. The returned list is empty if the\nwrapped output has no content.\n\nShortened:\n\nThis function wraps the input paragraph such that\neach line n the paragraph is at most width [...]\ntextwrap.indent(text, prefix, predicate=None): This function is used to add the given prefix to the beginning of the selected lines of the text. The predicate argument can be used to control which lines are indented.import textwrap s = 'hello\\n\\n \\nworld's1 = textwrap.indent(text=s, prefix=' ') print (s1)print (\"\\n\") s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)print (s2)Output :hello\n\n \nworld\n\n\n+ hello\n+ \n+ \n+ world\nThis article is contributed by Aditi Gupta. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 7785, "s": 6848, "text": "textwrap.wrap(text, width=70, **kwargs): This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content. Default width is taken as 70.import textwrap value = \"\"\"This function wraps the input paragraph such that each linein the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.\"\"\" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) word_list = wrapper.wrap(text=value) # Print each line.for element in word_list: print(element)Output :This function wraps the input paragraph such that\neach line in the paragraph is at most width\ncharacters long. The wrap method returns a list of\noutput lines. The returned list is empty if the\nwrapped output has no content.\n" }, { "code": "import textwrap value = \"\"\"This function wraps the input paragraph such that each linein the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.\"\"\" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) word_list = wrapper.wrap(text=value) # Print each line.for element in word_list: print(element)", "e": 8196, "s": 7785, "text": null }, { "code": null, "e": 8205, "s": 8196, "text": "Output :" }, { "code": null, "e": 8430, "s": 8205, "text": "This function wraps the input paragraph such that\neach line in the paragraph is at most width\ncharacters long. The wrap method returns a list of\noutput lines. The returned list is empty if the\nwrapped output has no content.\n" }, { "code": null, "e": 8989, "s": 8430, "text": "textwrap.fill(text, width=70, **kwargs): The fill() convenience function works similar to textwrap.wrap except it returns the data joined into a single, newline-separated string. This function wraps the input single paragraph in text, and returns a single string containing the wrapped paragraph.import textwrap value = \"\"\"This function returns the answer as STRING and not LIST.\"\"\" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) string = wrapper.fill(text=value) print (string)Output :This function returns the answer as STRING and not LIST.\n" }, { "code": "import textwrap value = \"\"\"This function returns the answer as STRING and not LIST.\"\"\" # Wrap this text.wrapper = textwrap.TextWrapper(width=50) string = wrapper.fill(text=value) print (string)", "e": 9187, "s": 8989, "text": null }, { "code": null, "e": 9196, "s": 9187, "text": "Output :" }, { "code": null, "e": 9254, "s": 9196, "text": "This function returns the answer as STRING and not LIST.\n" }, { "code": null, "e": 9815, "s": 9254, "text": "textwrap.dedent(text): This function is used to remove any common leading whitespace from every line in the input text. This allows to use docstrings or embedded multi-line strings line up with the left edge of the display, while removing the formatting of the code itself.Example :import textwrap wrapper = textwrap.TextWrapper(width=50) s = '''\\ hello world '''print(repr(s)) # prints ' hello\\n world\\n ' text = textwrap.dedent(s)print(repr(text)) # prints 'hello\\n world\\n'Output :' hello\\n world\\n '\n'hello\\n world\\n'\n" }, { "code": null, "e": 9825, "s": 9815, "text": "Example :" }, { "code": "import textwrap wrapper = textwrap.TextWrapper(width=50) s = '''\\ hello world '''print(repr(s)) # prints ' hello\\n world\\n ' text = textwrap.dedent(s)print(repr(text)) # prints 'hello\\n world\\n'", "e": 10046, "s": 9825, "text": null }, { "code": null, "e": 10055, "s": 10046, "text": "Output :" }, { "code": null, "e": 10106, "s": 10055, "text": "' hello\\n world\\n '\n'hello\\n world\\n'\n" }, { "code": null, "e": 11484, "s": 10106, "text": "textwrap.shorten(text, width, **kwargs): This function truncates the input string so that the length of the string becomes equal to the given width. At first, all the whitespaces are collapsed in the string by removing the whitespaces with a single space. If the modified string fits in the given string, then it is returned otherwise, the characters from the end are dropped so that the remaining words plus the placeholder fit within width.import textwrap sample_text = \"\"\"This function wraps the input paragraph such that each linen the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.\"\"\" wrapper = textwrap.TextWrapper(width=50) dedented_text = textwrap.dedent(text=sample_text)original = wrapper.fill(text=dedented_text) print('Original:\\n')print(original) shortened = textwrap.shorten(text=original, width=100)shortened_wrapped = wrapper.fill(text=shortened) print('\\nShortened:\\n')print(shortened_wrapped)Output :Original:\n\nThis function wraps the input paragraph such that\neach line n the paragraph is at most width\ncharacters long. The wrap method returns a list of\noutput lines. The returned list is empty if the\nwrapped output has no content.\n\nShortened:\n\nThis function wraps the input paragraph such that\neach line n the paragraph is at most width [...]\n" }, { "code": "import textwrap sample_text = \"\"\"This function wraps the input paragraph such that each linen the paragraph is at most width characters long. The wrap methodreturns a list of output lines. The returned listis empty if the wrappedoutput has no content.\"\"\" wrapper = textwrap.TextWrapper(width=50) dedented_text = textwrap.dedent(text=sample_text)original = wrapper.fill(text=dedented_text) print('Original:\\n')print(original) shortened = textwrap.shorten(text=original, width=100)shortened_wrapped = wrapper.fill(text=shortened) print('\\nShortened:\\n')print(shortened_wrapped)", "e": 12066, "s": 11484, "text": null }, { "code": null, "e": 12075, "s": 12066, "text": "Output :" }, { "code": null, "e": 12422, "s": 12075, "text": "Original:\n\nThis function wraps the input paragraph such that\neach line n the paragraph is at most width\ncharacters long. The wrap method returns a list of\noutput lines. The returned list is empty if the\nwrapped output has no content.\n\nShortened:\n\nThis function wraps the input paragraph such that\neach line n the paragraph is at most width [...]\n" }, { "code": null, "e": 12873, "s": 12422, "text": "textwrap.indent(text, prefix, predicate=None): This function is used to add the given prefix to the beginning of the selected lines of the text. The predicate argument can be used to control which lines are indented.import textwrap s = 'hello\\n\\n \\nworld's1 = textwrap.indent(text=s, prefix=' ') print (s1)print (\"\\n\") s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)print (s2)Output :hello\n\n \nworld\n\n\n+ hello\n+ \n+ \n+ world\n" }, { "code": "import textwrap s = 'hello\\n\\n \\nworld's1 = textwrap.indent(text=s, prefix=' ') print (s1)print (\"\\n\") s2 = textwrap.indent(text=s, prefix='+ ', predicate=lambda line: True)print (s2)", "e": 13060, "s": 12873, "text": null }, { "code": null, "e": 13069, "s": 13060, "text": "Output :" }, { "code": null, "e": 13110, "s": 13069, "text": "hello\n\n \nworld\n\n\n+ hello\n+ \n+ \n+ world\n" }, { "code": null, "e": 13409, "s": 13110, "text": "This article is contributed by Aditi Gupta. 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": 13534, "s": 13409, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 13549, "s": 13534, "text": "Python-Library" }, { "code": null, "e": 13556, "s": 13549, "text": "Python" } ]
Find the number of jumps to reach X in the number line from zero
09 Jun, 2022 Given an integer X. The task is to find the number of jumps to reach a point X in the number line starting from zero. Note: The first jump made can be of length one unit and each successive jump will be exactly one unit longer than the previous jump in length. It is allowed to go either left or right in each jump. Examples: Input : X = 8 Output : 4 Explanation : 0 -> -1 -> 1 -> 4-> 8 are possible stages. Input : X = 9 Output : 5 Explanation : 0 -> -1 -> -3 -> 0 -> 4-> 9 are possible stages Approach: On observing carefully, it can be said easily that: If you have always jumped in the right direction then after n jumps you will be at the point p = 1 + 2 + 3 + 4 + ... + n. In any of these n jumps, if instead of jumping right, you jumped left in the kth jump (k<=n), you would be at point p – 2k. Moreover, by carefully choosing which jumps to go left and which to go right, after n jumps, you can be at any point between n * (n + 1) / 2 and – (n * (n + 1) / 2) with the same parity as n * (n + 1) / 2. Keeping the above points in mind, what you must do is simulate the jumping process, always jumping to the right, and if at some point, you’ve reached a point that has the same parity as X and is at or beyond X, you’ll have your answer.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the number of jumps// to reach X in the number line from zero #include <bits/stdc++.h>using namespace std; // Utility function to calculate sum// of numbers from 1 to xint getsum(int x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zeroint countJumps(int n){ // First make number positive // Answer will be same either it is // Positive or negative n = abs(n); // To store required answer int ans = 0; // Continue till number is lesser or not in same parity while (getsum(ans) < n or (getsum(ans) - n) & 1) ans++; // Return the required answer return ans;} // Driver codeint main(){ int n = 9; cout << countJumps(n); return 0;} // Java program to find the number of jumps// to reach X in the number line from zero class GFG{ // Utility function to calculate sum// of numbers from 1 to xstatic int getsum(int x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerostatic int countJumps(int n){ // First make number positive // Answer will be same either it is // Positive or negative n = Math.abs(n); // To store required answer int ans = 0; // Continue till number is lesser // or not in same parity while (getsum(ans) < n || ((getsum(ans) - n) & 1) > 0) ans++; // Return the required answer return ans;} // Driver codepublic static void main(String args[]){ int n = 9; System.out.println(countJumps(n));}} // This code is contributed by Ryuga # Python 3 program to find the number of jumps# to reach X in the number line from zero # Utility function to calculate sum# of numbers from 1 to xdef getsum(x): return int((x * (x + 1)) / 2) # Function to find the number of jumps# to reach X in the number line from zerodef countJumps(n): # First make number positive # Answer will be same either it is # Positive or negative n = abs(n) # To store the required answer ans = 0 # Continue till number is lesser # or not in same parity while (getsum(ans) < n or (getsum(ans) - n) & 1): ans += 1 # Return the required answer return ans # Driver codeif __name__ == '__main__': n = 9 print(countJumps(n)) # This code is contributed by# Surendra_Gangwar // C# program to find the number of jumps// to reach X in the number line from zerousing System; class GFG{ // Utility function to calculate sum// of numbers from 1 to xstatic int getsum(int x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerostatic int countJumps(int n){ // First make number positive // Answer will be same either it is // Positive or negative n = Math.Abs(n); // To store required answer int ans = 0; // Continue till number is lesser or not in same parity while (getsum(ans) < n || ((getsum(ans) - n) & 1)>0) ans++; // Return the required answer return ans;} // Driver codestatic void Main(){ int n = 9; Console.WriteLine(countJumps(n));}} // This code is contributed by mits <?php// PHP program to find the number of jumps// to reach X in the number line from zero // Utility function to calculate sum// of numbers from 1 to xfunction getsum($x){ return ($x * ($x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerofunction countJumps($n){ // First make number positive // Answer will be same either it is // Positive or negative $n = abs($n); // To store required answer $ans = 0; // Continue till number is lesser // or not in same parity while (getsum($ans) < $n or (getsum($ans) - $n) & 1) $ans++; // Return the required answer return $ans;} // Driver code$n = 9; echo countJumps($n); // This code is contributed by Akanksha Rai?> <script> // Javascript program to find the number of jumps// to reach X in the number line from zero // Utility function to calculate sum// of numbers from 1 to xfunction getsum(x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerofunction countJumps(n){ // First make number positive // Answer will be same either it is // Positive or negative n = Math.abs(n); // To store required answer let ans = 0; // Continue till number is lesser // or not in same parity while (getsum(ans) < n || ((getsum(ans) - n) & 1) > 0) ans++; // Return the required answer return ans;} // Driver Code let n = 9; document.write(countJumps(n)); </script> 5 Time Complexity: O(n) Auxiliary Space: O(1) Mithun Kumar ankthon SURENDRA_GANGWAR Akanksha_Rai ManasChhabra2 target_2 gabaa406 prashantkumar dhotre sachinsom507 subhamkumarm348 Constructive Algorithms Numbers Greedy Mathematical Greedy Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Fractional Knapsack Problem Job Sequencing Problem Minimum Number of Platforms Required for a Railway/Bus Station Policemen catch thieves Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 382, "s": 54, "text": "Given an integer X. The task is to find the number of jumps to reach a point X in the number line starting from zero. Note: The first jump made can be of length one unit and each successive jump will be exactly one unit longer than the previous jump in length. It is allowed to go either left or right in each jump. Examples: " }, { "code": null, "e": 555, "s": 382, "text": "Input : X = 8\nOutput : 4\nExplanation : \n0 -> -1 -> 1 -> 4-> 8 are possible stages.\n\nInput : X = 9\nOutput : 5\nExplanation : \n0 -> -1 -> -3 -> 0 -> 4-> 9 are \npossible stages" }, { "code": null, "e": 621, "s": 557, "text": "Approach: On observing carefully, it can be said easily that: " }, { "code": null, "e": 743, "s": 621, "text": "If you have always jumped in the right direction then after n jumps you will be at the point p = 1 + 2 + 3 + 4 + ... + n." }, { "code": null, "e": 867, "s": 743, "text": "In any of these n jumps, if instead of jumping right, you jumped left in the kth jump (k<=n), you would be at point p – 2k." }, { "code": null, "e": 1073, "s": 867, "text": "Moreover, by carefully choosing which jumps to go left and which to go right, after n jumps, you can be at any point between n * (n + 1) / 2 and – (n * (n + 1) / 2) with the same parity as n * (n + 1) / 2." }, { "code": null, "e": 1361, "s": 1073, "text": "Keeping the above points in mind, what you must do is simulate the jumping process, always jumping to the right, and if at some point, you’ve reached a point that has the same parity as X and is at or beyond X, you’ll have your answer.Below is the implementation of the above approach: " }, { "code": null, "e": 1365, "s": 1361, "text": "C++" }, { "code": null, "e": 1370, "s": 1365, "text": "Java" }, { "code": null, "e": 1378, "s": 1370, "text": "Python3" }, { "code": null, "e": 1381, "s": 1378, "text": "C#" }, { "code": null, "e": 1385, "s": 1381, "text": "PHP" }, { "code": null, "e": 1396, "s": 1385, "text": "Javascript" }, { "code": "// C++ program to find the number of jumps// to reach X in the number line from zero #include <bits/stdc++.h>using namespace std; // Utility function to calculate sum// of numbers from 1 to xint getsum(int x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zeroint countJumps(int n){ // First make number positive // Answer will be same either it is // Positive or negative n = abs(n); // To store required answer int ans = 0; // Continue till number is lesser or not in same parity while (getsum(ans) < n or (getsum(ans) - n) & 1) ans++; // Return the required answer return ans;} // Driver codeint main(){ int n = 9; cout << countJumps(n); return 0;}", "e": 2160, "s": 1396, "text": null }, { "code": "// Java program to find the number of jumps// to reach X in the number line from zero class GFG{ // Utility function to calculate sum// of numbers from 1 to xstatic int getsum(int x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerostatic int countJumps(int n){ // First make number positive // Answer will be same either it is // Positive or negative n = Math.abs(n); // To store required answer int ans = 0; // Continue till number is lesser // or not in same parity while (getsum(ans) < n || ((getsum(ans) - n) & 1) > 0) ans++; // Return the required answer return ans;} // Driver codepublic static void main(String args[]){ int n = 9; System.out.println(countJumps(n));}} // This code is contributed by Ryuga", "e": 2998, "s": 2160, "text": null }, { "code": "# Python 3 program to find the number of jumps# to reach X in the number line from zero # Utility function to calculate sum# of numbers from 1 to xdef getsum(x): return int((x * (x + 1)) / 2) # Function to find the number of jumps# to reach X in the number line from zerodef countJumps(n): # First make number positive # Answer will be same either it is # Positive or negative n = abs(n) # To store the required answer ans = 0 # Continue till number is lesser # or not in same parity while (getsum(ans) < n or (getsum(ans) - n) & 1): ans += 1 # Return the required answer return ans # Driver codeif __name__ == '__main__': n = 9 print(countJumps(n)) # This code is contributed by# Surendra_Gangwar", "e": 3763, "s": 2998, "text": null }, { "code": "// C# program to find the number of jumps// to reach X in the number line from zerousing System; class GFG{ // Utility function to calculate sum// of numbers from 1 to xstatic int getsum(int x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerostatic int countJumps(int n){ // First make number positive // Answer will be same either it is // Positive or negative n = Math.Abs(n); // To store required answer int ans = 0; // Continue till number is lesser or not in same parity while (getsum(ans) < n || ((getsum(ans) - n) & 1)>0) ans++; // Return the required answer return ans;} // Driver codestatic void Main(){ int n = 9; Console.WriteLine(countJumps(n));}} // This code is contributed by mits", "e": 4574, "s": 3763, "text": null }, { "code": "<?php// PHP program to find the number of jumps// to reach X in the number line from zero // Utility function to calculate sum// of numbers from 1 to xfunction getsum($x){ return ($x * ($x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerofunction countJumps($n){ // First make number positive // Answer will be same either it is // Positive or negative $n = abs($n); // To store required answer $ans = 0; // Continue till number is lesser // or not in same parity while (getsum($ans) < $n or (getsum($ans) - $n) & 1) $ans++; // Return the required answer return $ans;} // Driver code$n = 9; echo countJumps($n); // This code is contributed by Akanksha Rai?>", "e": 5331, "s": 4574, "text": null }, { "code": "<script> // Javascript program to find the number of jumps// to reach X in the number line from zero // Utility function to calculate sum// of numbers from 1 to xfunction getsum(x){ return (x * (x + 1)) / 2;} // Function to find the number of jumps// to reach X in the number line from zerofunction countJumps(n){ // First make number positive // Answer will be same either it is // Positive or negative n = Math.abs(n); // To store required answer let ans = 0; // Continue till number is lesser // or not in same parity while (getsum(ans) < n || ((getsum(ans) - n) & 1) > 0) ans++; // Return the required answer return ans;} // Driver Code let n = 9; document.write(countJumps(n)); </script>", "e": 6116, "s": 5331, "text": null }, { "code": null, "e": 6118, "s": 6116, "text": "5" }, { "code": null, "e": 6142, "s": 6120, "text": "Time Complexity: O(n)" }, { "code": null, "e": 6164, "s": 6142, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6177, "s": 6164, "text": "Mithun Kumar" }, { "code": null, "e": 6185, "s": 6177, "text": "ankthon" }, { "code": null, "e": 6202, "s": 6185, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 6215, "s": 6202, "text": "Akanksha_Rai" }, { "code": null, "e": 6229, "s": 6215, "text": "ManasChhabra2" }, { "code": null, "e": 6238, "s": 6229, "text": "target_2" }, { "code": null, "e": 6247, "s": 6238, "text": "gabaa406" }, { "code": null, "e": 6268, "s": 6247, "text": "prashantkumar dhotre" }, { "code": null, "e": 6281, "s": 6268, "text": "sachinsom507" }, { "code": null, "e": 6297, "s": 6281, "text": "subhamkumarm348" }, { "code": null, "e": 6321, "s": 6297, "text": "Constructive Algorithms" }, { "code": null, "e": 6329, "s": 6321, "text": "Numbers" }, { "code": null, "e": 6336, "s": 6329, "text": "Greedy" }, { "code": null, "e": 6349, "s": 6336, "text": "Mathematical" }, { "code": null, "e": 6356, "s": 6349, "text": "Greedy" }, { "code": null, "e": 6369, "s": 6356, "text": "Mathematical" }, { "code": null, "e": 6377, "s": 6369, "text": "Numbers" }, { "code": null, "e": 6475, "s": 6377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6503, "s": 6475, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 6526, "s": 6503, "text": "Job Sequencing Problem" }, { "code": null, "e": 6589, "s": 6526, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 6613, "s": 6589, "text": "Policemen catch thieves" }, { "code": null, "e": 6694, "s": 6613, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 6724, "s": 6694, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 6767, "s": 6724, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6782, "s": 6767, "text": "C++ Data Types" }, { "code": null, "e": 6806, "s": 6782, "text": "Merge two sorted arrays" } ]
Smallest number k such that the product of digits of k is equal to n
20 May, 2021 Given a non-negative number n. The problem is to find the smallest number k such that the product of digits of k is equal to n. If no such number k can be formed then print “-1”.Examples: Input : 100 Output : 455 4*5*5 = 100 and 455 is the smallest possible number. Input : 26 Output : -1 Source: Asked in Amazon Interview Approach: For each i = 9 to 2, repeatedly divide n by i until it cannot be further divided or the list of numbers from 9 to 2 gets finished. Also, in the process of division push each digit i onto the stack which divides n completely. After the above process gets completed check whether n == 1 or not. If not, then print “-1”, else form the number k using the digits from the stack containing the digits in the same sequence as popped from the stack. C++ Java Python3 C# PHP Javascript // C++ implementation to find smallest number k such that// the product of digits of k is equal to n#include <bits/stdc++.h> using namespace std; // function to find smallest number k such that// the product of digits of k is equal to nlong long int smallestNumber(int n){ // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) return n; // stack the store the digits stack<int> digits; // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (int i=9; i>=2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.push(i); n = n / i; } } // if true, then no number 'k' can be formed if (n != 1) return -1; // pop digits from the stack 'digits' // and add them to 'k' long long int k = 0; while (!digits.empty()) { k = k*10 + digits.top(); digits.pop(); } // required smallest number return k;} // Driver program to test aboveint main(){ int n = 100; cout << smallestNumber(n); return 0;} //Java implementation to find smallest number k such that// the product of digits of k is equal to nimport java.util.Stack; public class GFG { // function to find smallest number k such that// the product of digits of k is equal to n static long smallestNumber(int n) { // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) { return n; } // stack the store the digits Stack<Integer> digits = new Stack<>(); // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (int i = 9; i >= 2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.push(i); n = n / i; } } // if true, then no number 'k' can be formed if (n != 1) { return -1; } // pop digits from the stack 'digits' // and add them to 'k' long k = 0; while (!digits.empty()) { k = k * 10 + digits.peek(); digits.pop(); } // required smallest number return k; } // Driver program to test above static public void main(String[] args) { int n = 100; System.out.println(smallestNumber(n)); }} /*This code is contributed by PrinciRaj1992*/ # Python3 implementation to find smallest# number k such that the product of digits# of k is equal to nimport math as mt # function to find smallest number k such that# the product of digits of k is equal to ndef smallestNumber(n): # if 'n' is a single digit number, then # it is the required number if (n >= 0 and n <= 9): return n # stack the store the digits digits = list() # repeatedly divide 'n' by the numbers # from 9 to 2 until all the numbers are # used or 'n' > 1 for i in range(9,1, -1): while (n % i == 0): # save the digit 'i' that # divides 'n' onto the stack digits.append(i) n = n //i # if true, then no number 'k' # can be formed if (n != 1): return -1 # pop digits from the stack 'digits' # and add them to 'k' k = 0 while (len(digits) != 0): k = k * 10 + digits[-1] digits.pop() # required smallest number return k # Driver Coden = 100print(smallestNumber(n)) # This code is contributed by# Mohit kumar 29 // C# implementation to find smallest number k such that// the product of digits of k is equal to nusing System;using System.Collections.Generic;public class GFG { // function to find smallest number k such that// the product of digits of k is equal to n static long smallestNumber(int n) { // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) { return n; } // stack the store the digits Stack<int> digits = new Stack<int>(); // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (int i = 9; i >= 2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.Push(i); n = n / i; } } // if true, then no number 'k' can be formed if (n != 1) { return -1; } // pop digits from the stack 'digits' // and add them to 'k' long k = 0; while (digits.Count!=0) { k = k * 10 + digits.Peek(); digits.Pop(); } // required smallest number return k; } // Driver program to test above static public void Main() { int n = 100; Console.Write(smallestNumber(n)); }} /*This code is contributed by Rajput-Ji*/ <?php// PHP implementation to find smallest number k such that// the product of digits of k is equal to n // function to find smallest number k such that// the product of digits of k is equal to nfunction smallestNumber($n){ // if 'n' is a single digit number, then // it is the required number if ($n >= 0 && $n <= 9) return $n; // stack the store the digits $digits = array(); // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for ($i = 9; $i >= 2 && $n > 1; $i--) { while ($n % $i == 0) { // save the digit 'i' that divides 'n' // onto the stack array_push($digits,$i); $n =(int)( $n / $i); } } // if true, then no number 'k' can be formed if ($n != 1) return -1; // pop digits from the stack 'digits' // and add them to 'k' $k = 0; while (!empty($digits)) $k = $k * 10 + array_pop($digits); // required smallest number return $k;} // Driver code $n = 100; echo smallestNumber($n); // This code is contributed by mits?> <script> // Javascript implementation to find// smallest number k such that// the product of digits of k is equal to n // function to find smallest number k such that// the product of digits of k is equal to n function smallestNumber(n) { // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) { return n; } // stack the store the digits let digits = []; // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (let i = 9; i >= 2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.push(i); n = Math.floor(n / i); } } // if true, then no number 'k' can be formed if (n != 1) { return -1; } // pop digits from the stack 'digits' // and add them to 'k' let k = 0; while (digits.length!=0) { k = k * 10 + digits[digits.length-1]; digits.pop(); } // required smallest number return k; } // Driver program to test above let n = 100; document.write(smallestNumber(n)); // This code is contributed by patel2127 </script> Output: 455 Time Complexity: O(num), where num is the size of the stack. Space Complexity: O(num), where num is the size of the stack.We can store the required number k in string for large numbers.This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. princiraj1992 Rajput-Ji mohit kumar 29 gfg_sal_gfg Mithun Kumar aditya1050 nidhi_biet patel2127 Amazon number-digits Numbers Mathematical Amazon Mathematical Numbers 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 Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 54, "s": 26, "text": "\n20 May, 2021" }, { "code": null, "e": 244, "s": 54, "text": "Given a non-negative number n. The problem is to find the smallest number k such that the product of digits of k is equal to n. If no such number k can be formed then print “-1”.Examples: " }, { "code": null, "e": 346, "s": 244, "text": "Input : 100\nOutput : 455\n4*5*5 = 100 and 455 is the\nsmallest possible number.\n\nInput : 26\nOutput : -1" }, { "code": null, "e": 381, "s": 346, "text": "Source: Asked in Amazon Interview " }, { "code": null, "e": 835, "s": 381, "text": "Approach: For each i = 9 to 2, repeatedly divide n by i until it cannot be further divided or the list of numbers from 9 to 2 gets finished. Also, in the process of division push each digit i onto the stack which divides n completely. After the above process gets completed check whether n == 1 or not. If not, then print “-1”, else form the number k using the digits from the stack containing the digits in the same sequence as popped from the stack. " }, { "code": null, "e": 839, "s": 835, "text": "C++" }, { "code": null, "e": 844, "s": 839, "text": "Java" }, { "code": null, "e": 852, "s": 844, "text": "Python3" }, { "code": null, "e": 855, "s": 852, "text": "C#" }, { "code": null, "e": 859, "s": 855, "text": "PHP" }, { "code": null, "e": 870, "s": 859, "text": "Javascript" }, { "code": "// C++ implementation to find smallest number k such that// the product of digits of k is equal to n#include <bits/stdc++.h> using namespace std; // function to find smallest number k such that// the product of digits of k is equal to nlong long int smallestNumber(int n){ // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) return n; // stack the store the digits stack<int> digits; // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (int i=9; i>=2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.push(i); n = n / i; } } // if true, then no number 'k' can be formed if (n != 1) return -1; // pop digits from the stack 'digits' // and add them to 'k' long long int k = 0; while (!digits.empty()) { k = k*10 + digits.top(); digits.pop(); } // required smallest number return k;} // Driver program to test aboveint main(){ int n = 100; cout << smallestNumber(n); return 0;}", "e": 2075, "s": 870, "text": null }, { "code": "//Java implementation to find smallest number k such that// the product of digits of k is equal to nimport java.util.Stack; public class GFG { // function to find smallest number k such that// the product of digits of k is equal to n static long smallestNumber(int n) { // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) { return n; } // stack the store the digits Stack<Integer> digits = new Stack<>(); // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (int i = 9; i >= 2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.push(i); n = n / i; } } // if true, then no number 'k' can be formed if (n != 1) { return -1; } // pop digits from the stack 'digits' // and add them to 'k' long k = 0; while (!digits.empty()) { k = k * 10 + digits.peek(); digits.pop(); } // required smallest number return k; } // Driver program to test above static public void main(String[] args) { int n = 100; System.out.println(smallestNumber(n)); }} /*This code is contributed by PrinciRaj1992*/", "e": 3502, "s": 2075, "text": null }, { "code": "# Python3 implementation to find smallest# number k such that the product of digits# of k is equal to nimport math as mt # function to find smallest number k such that# the product of digits of k is equal to ndef smallestNumber(n): # if 'n' is a single digit number, then # it is the required number if (n >= 0 and n <= 9): return n # stack the store the digits digits = list() # repeatedly divide 'n' by the numbers # from 9 to 2 until all the numbers are # used or 'n' > 1 for i in range(9,1, -1): while (n % i == 0): # save the digit 'i' that # divides 'n' onto the stack digits.append(i) n = n //i # if true, then no number 'k' # can be formed if (n != 1): return -1 # pop digits from the stack 'digits' # and add them to 'k' k = 0 while (len(digits) != 0): k = k * 10 + digits[-1] digits.pop() # required smallest number return k # Driver Coden = 100print(smallestNumber(n)) # This code is contributed by# Mohit kumar 29", "e": 4606, "s": 3502, "text": null }, { "code": " // C# implementation to find smallest number k such that// the product of digits of k is equal to nusing System;using System.Collections.Generic;public class GFG { // function to find smallest number k such that// the product of digits of k is equal to n static long smallestNumber(int n) { // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) { return n; } // stack the store the digits Stack<int> digits = new Stack<int>(); // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (int i = 9; i >= 2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.Push(i); n = n / i; } } // if true, then no number 'k' can be formed if (n != 1) { return -1; } // pop digits from the stack 'digits' // and add them to 'k' long k = 0; while (digits.Count!=0) { k = k * 10 + digits.Peek(); digits.Pop(); } // required smallest number return k; } // Driver program to test above static public void Main() { int n = 100; Console.Write(smallestNumber(n)); }} /*This code is contributed by Rajput-Ji*/", "e": 6044, "s": 4606, "text": null }, { "code": "<?php// PHP implementation to find smallest number k such that// the product of digits of k is equal to n // function to find smallest number k such that// the product of digits of k is equal to nfunction smallestNumber($n){ // if 'n' is a single digit number, then // it is the required number if ($n >= 0 && $n <= 9) return $n; // stack the store the digits $digits = array(); // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for ($i = 9; $i >= 2 && $n > 1; $i--) { while ($n % $i == 0) { // save the digit 'i' that divides 'n' // onto the stack array_push($digits,$i); $n =(int)( $n / $i); } } // if true, then no number 'k' can be formed if ($n != 1) return -1; // pop digits from the stack 'digits' // and add them to 'k' $k = 0; while (!empty($digits)) $k = $k * 10 + array_pop($digits); // required smallest number return $k;} // Driver code $n = 100; echo smallestNumber($n); // This code is contributed by mits?>", "e": 7191, "s": 6044, "text": null }, { "code": "<script> // Javascript implementation to find// smallest number k such that// the product of digits of k is equal to n // function to find smallest number k such that// the product of digits of k is equal to n function smallestNumber(n) { // if 'n' is a single digit number, then // it is the required number if (n >= 0 && n <= 9) { return n; } // stack the store the digits let digits = []; // repeatedly divide 'n' by the numbers // from 9 to 2 until all the numbers are // used or 'n' > 1 for (let i = 9; i >= 2 && n > 1; i--) { while (n % i == 0) { // save the digit 'i' that divides 'n' // onto the stack digits.push(i); n = Math.floor(n / i); } } // if true, then no number 'k' can be formed if (n != 1) { return -1; } // pop digits from the stack 'digits' // and add them to 'k' let k = 0; while (digits.length!=0) { k = k * 10 + digits[digits.length-1]; digits.pop(); } // required smallest number return k; } // Driver program to test above let n = 100; document.write(smallestNumber(n)); // This code is contributed by patel2127 </script>", "e": 8564, "s": 7191, "text": null }, { "code": null, "e": 8574, "s": 8564, "text": "Output: " }, { "code": null, "e": 8578, "s": 8574, "text": "455" }, { "code": null, "e": 9185, "s": 8578, "text": "Time Complexity: O(num), where num is the size of the stack. Space Complexity: O(num), where num is the size of the stack.We can store the required number k in string for large numbers.This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 9199, "s": 9185, "text": "princiraj1992" }, { "code": null, "e": 9209, "s": 9199, "text": "Rajput-Ji" }, { "code": null, "e": 9224, "s": 9209, "text": "mohit kumar 29" }, { "code": null, "e": 9236, "s": 9224, "text": "gfg_sal_gfg" }, { "code": null, "e": 9249, "s": 9236, "text": "Mithun Kumar" }, { "code": null, "e": 9260, "s": 9249, "text": "aditya1050" }, { "code": null, "e": 9271, "s": 9260, "text": "nidhi_biet" }, { "code": null, "e": 9281, "s": 9271, "text": "patel2127" }, { "code": null, "e": 9288, "s": 9281, "text": "Amazon" }, { "code": null, "e": 9302, "s": 9288, "text": "number-digits" }, { "code": null, "e": 9310, "s": 9302, "text": "Numbers" }, { "code": null, "e": 9323, "s": 9310, "text": "Mathematical" }, { "code": null, "e": 9330, "s": 9323, "text": "Amazon" }, { "code": null, "e": 9343, "s": 9330, "text": "Mathematical" }, { "code": null, "e": 9351, "s": 9343, "text": "Numbers" }, { "code": null, "e": 9449, "s": 9351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9473, "s": 9449, "text": "Merge two sorted arrays" }, { "code": null, "e": 9494, "s": 9473, "text": "Operators in C / C++" }, { "code": null, "e": 9516, "s": 9494, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 9530, "s": 9516, "text": "Prime Numbers" }, { "code": null, "e": 9572, "s": 9530, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 9609, "s": 9572, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 9652, "s": 9609, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 9684, "s": 9652, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9725, "s": 9684, "text": "Program for Decimal to Binary Conversion" } ]
C# | Remove all elements in a collection from a HashSet
01 Feb, 2019 A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.ExceptWith(IEnumerable) Method is used to remove all elements in the specified collection from the current HashSet object. Syntax: mySet2.ExceptWith(mySet1) Here, mySet1 and mySet2 are the two HashSets and the function returns the elements of mySet2 which are not in mySet1. Exception: This method will give ArgumentNullException if the HashSet is null. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to remove all elements// in a collection from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Inserting elements into HashSet mySet1 for (int i = 0; i < 7; i++) { mySet1.Add(i); } // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting elements into HashSet mySet2 for (int i = 4; i < 11; i++) { mySet2.Add(i); } // Removing all elements in a collection from a HashSet mySet2.ExceptWith(mySet1); // Printing the elements in mySet2 // It only prints the elements which are // in mySet2 and not in mySet1 foreach(int i in mySet2) { Console.WriteLine(i); } }} 7 8 9 10 Example 2: // C# code to remove all elements// in a collection from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet1 = new HashSet<string>(); // Inserting elements into HashSet mySet1 mySet1.Add("Punjab"); mySet1.Add("Haryana"); mySet1.Add("Jammu"); mySet1.Add("Himachal"); mySet1.Add("Delhi"); // Displaying all elements in mySet1 Console.WriteLine("The elements in mySet1 are : "); foreach(string i in mySet1) { Console.WriteLine(i); } // Creating a HashSet of strings HashSet<string> mySet2 = new HashSet<string>(); // Inserting elements into HashSet mySet2 mySet2.Add("Bangalore"); mySet2.Add("Kerala"); mySet2.Add("Uttar Pradesh"); mySet2.Add("Himachal"); mySet2.Add("Delhi"); // Displaying all elements in mySet2 Console.WriteLine("The elements in mySet2 are : "); foreach(string i in mySet2) { Console.WriteLine(i); } // Removing all elements in a collection from a HashSet mySet2.ExceptWith(mySet1); // Printing the elements in mySet2 // It only prints the elements which are // in mySet2 and not in mySet1 Console.WriteLine("The elements in mySet2 are : "); foreach(string i in mySet2) { Console.WriteLine(i); } }} The elements in mySet1 are : Punjab Haryana Jammu Himachal Delhi The elements in mySet2 are : Bangalore Kerala Uttar Pradesh Himachal Delhi The elements in mySet2 are : Bangalore Kerala Uttar Pradesh Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.exceptwith?view=netframework-4.7.2 CSharp-Generic-HashSet CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | Class and Object Extension Method in C# C# | Replace() Method
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Feb, 2019" }, { "code": null, "e": 476, "s": 54, "text": "A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.ExceptWith(IEnumerable) Method is used to remove all elements in the specified collection from the current HashSet object." }, { "code": null, "e": 484, "s": 476, "text": "Syntax:" }, { "code": null, "e": 511, "s": 484, "text": "mySet2.ExceptWith(mySet1)\n" }, { "code": null, "e": 629, "s": 511, "text": "Here, mySet1 and mySet2 are the two HashSets and the function returns the elements of mySet2 which are not in mySet1." }, { "code": null, "e": 708, "s": 629, "text": "Exception: This method will give ArgumentNullException if the HashSet is null." }, { "code": null, "e": 788, "s": 708, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 799, "s": 788, "text": "Example 1:" }, { "code": "// C# code to remove all elements// in a collection from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Inserting elements into HashSet mySet1 for (int i = 0; i < 7; i++) { mySet1.Add(i); } // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting elements into HashSet mySet2 for (int i = 4; i < 11; i++) { mySet2.Add(i); } // Removing all elements in a collection from a HashSet mySet2.ExceptWith(mySet1); // Printing the elements in mySet2 // It only prints the elements which are // in mySet2 and not in mySet1 foreach(int i in mySet2) { Console.WriteLine(i); } }}", "e": 1728, "s": 799, "text": null }, { "code": null, "e": 1738, "s": 1728, "text": "7\n8\n9\n10\n" }, { "code": null, "e": 1749, "s": 1738, "text": "Example 2:" }, { "code": "// C# code to remove all elements// in a collection from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet1 = new HashSet<string>(); // Inserting elements into HashSet mySet1 mySet1.Add(\"Punjab\"); mySet1.Add(\"Haryana\"); mySet1.Add(\"Jammu\"); mySet1.Add(\"Himachal\"); mySet1.Add(\"Delhi\"); // Displaying all elements in mySet1 Console.WriteLine(\"The elements in mySet1 are : \"); foreach(string i in mySet1) { Console.WriteLine(i); } // Creating a HashSet of strings HashSet<string> mySet2 = new HashSet<string>(); // Inserting elements into HashSet mySet2 mySet2.Add(\"Bangalore\"); mySet2.Add(\"Kerala\"); mySet2.Add(\"Uttar Pradesh\"); mySet2.Add(\"Himachal\"); mySet2.Add(\"Delhi\"); // Displaying all elements in mySet2 Console.WriteLine(\"The elements in mySet2 are : \"); foreach(string i in mySet2) { Console.WriteLine(i); } // Removing all elements in a collection from a HashSet mySet2.ExceptWith(mySet1); // Printing the elements in mySet2 // It only prints the elements which are // in mySet2 and not in mySet1 Console.WriteLine(\"The elements in mySet2 are : \"); foreach(string i in mySet2) { Console.WriteLine(i); } }}", "e": 3297, "s": 1749, "text": null }, { "code": null, "e": 3501, "s": 3297, "text": "The elements in mySet1 are : \nPunjab\nHaryana\nJammu\nHimachal\nDelhi\nThe elements in mySet2 are : \nBangalore\nKerala\nUttar Pradesh\nHimachal\nDelhi\nThe elements in mySet2 are : \nBangalore\nKerala\nUttar Pradesh\n" }, { "code": null, "e": 3512, "s": 3501, "text": "Reference:" }, { "code": null, "e": 3628, "s": 3512, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.exceptwith?view=netframework-4.7.2" }, { "code": null, "e": 3651, "s": 3628, "text": "CSharp-Generic-HashSet" }, { "code": null, "e": 3676, "s": 3651, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 3690, "s": 3676, "text": "CSharp-method" }, { "code": null, "e": 3693, "s": 3690, "text": "C#" }, { "code": null, "e": 3791, "s": 3693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3822, "s": 3791, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3837, "s": 3822, "text": "C# | Delegates" }, { "code": null, "e": 3880, "s": 3837, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3929, "s": 3880, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3952, "s": 3929, "text": "C# | Method Overriding" }, { "code": null, "e": 3968, "s": 3952, "text": "C# | Data Types" }, { "code": null, "e": 3986, "s": 3968, "text": "C# | Constructors" }, { "code": null, "e": 4008, "s": 3986, "text": "C# | Class and Object" }, { "code": null, "e": 4031, "s": 4008, "text": "Extension Method in C#" } ]
XOR of all elements of array with set bits equal to K
29 Apr, 2021 Given an array of integers and a number K. The task is to find the XOR of only those elements of the array whose total set bits are equal to K. Examples: Input : arr[] = {1, 22, 3, 10}, K=1 Output : 1 Elements with set bits equal to 1 is 1. So, XOR is also 1. Input : arr[] = {3, 4, 10, 5, 8}, K=2 Output : 12 Approach: Initialize an empty vector.Traverse the array form left to right and check the set bits of each element.Use, C++ inbuilt function __builtin_popcount() to count setbits.Push the elements with K setbits into the vector.Finally find XOR of all the elements of the vector. Initialize an empty vector. Traverse the array form left to right and check the set bits of each element. Use, C++ inbuilt function __builtin_popcount() to count setbits. Push the elements with K setbits into the vector. Finally find XOR of all the elements of the vector. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find Xor// of all elements with set bits// equal to K#include <bits/stdc++.h>using namespace std; // Function to find Xor// of desired elementsint xorGivenSetBits(int arr[], int n, int k){ // Initialize vector vector<int> v; for (int i = 0; i < n; i++) { if (__builtin_popcount(arr[i]) == k) { // push required elements v.push_back(arr[i]); } } // Initialize result with first element of vector int result = v[0]; for (int i = 1; i < v.size(); i++) result = result ^ v[i]; return result;} // Driver codeint main(){ int arr[] = { 2, 13, 1, 19, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << xorGivenSetBits(arr, n, k); return 0;} // Java program to find Xor// of all elements with set bits// equal to Kimport java.util.*; class GFG{ // Function to find Xor // of desired elements static int xorGivenSetBits(int arr[], int n, int k) { // Initialize vector Vector<Integer> v = new Vector<>(); for (int i = 0; i < n; i++) { if (Integer.bitCount(arr[i]) == k) { // push required elements v.add(arr[i]); } } // Initialize result with first element of vector int result = v.get(0); for (int i = 1; i < v.size(); i++) { result = result ^ v.get(i); } return result; } // Driver code public static void main(String[] args) { int arr[] = {2, 13, 1, 19, 7}; int n = arr.length; int k = 3; System.out.println(xorGivenSetBits(arr, n, k)); }} // This code contributed by Rajput-Ji # Python 3 program to find Xor of all# elements with set bits equal to K # Function to find Xor of desired elementsdef xorGivenSetBits(arr, n, k): # Initialize vector v = [] for i in range(0, n, 1): if (bin(arr[i]).count('1') == k): # push required elements v.append(arr[i]) # Initialize result with first # element of vector result = v[0] for i in range(1, len(v), 1): result = result ^ v[i] return result # Driver codeif __name__ == '__main__': arr = [2, 13, 1, 19, 7] n = len(arr) k = 3 print(xorGivenSetBits(arr, n, k)) # This code is contributed by# Surendra_Gangwar // C# program to find Xor// of all elements with set bits// equal to Kusing System;using System.Collections;using System.Linq; class GFG{ // Function to find Xor// of desired elementsstatic int xorGivenSetBits(int []arr, int n, int k){ // Initialize vector ArrayList v=new ArrayList(); for (int i = 0; i < n; i++) { if (Convert.ToString(arr[i], 2).Count(c => c == '1') == k) { // push required elements v.Add(arr[i]); } } // Initialize result with first element of vector int result = (int)v[0]; for (int i = 1; i < v.Count; i++) result = result ^ (int)v[i]; return result;} // Driver codestatic void Main(){ int []arr = { 2, 13, 1, 19, 7 }; int n = arr.Length; int k = 3; Console.WriteLine(xorGivenSetBits(arr, n, k));}} // This code is contributed by mits <script> // Javascript program to find Xor// of all elements with set bits// equal to K // Function to find Xor// of desired elementsfunction xorGivenSetBits(arr, n, k){ // Initialize vector let v = []; for (let i = 0; i < n; i++) { if (bitcount(arr[i]) == k) { // push required elements v.push(arr[i]); } } // Initialize result with first // element of vector let result = v[0]; for (let i = 1; i < v.length; i++) result = result ^ v[i]; return result;} function bitcount(n){ var count = 0; while (n) { count += n & 1; n >>= 1; } return count;} // Driver code let arr = [ 2, 13, 1, 19, 7 ]; let n = arr.length; let k = 3; document.write(xorGivenSetBits(arr, n, k)); </script> 25 SURENDRA_GANGWAR Mithun Kumar Rajput-Ji souravmahato348 Bitwise-XOR setBitCount Arrays Bit Magic Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Next Greater Element 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": 53, "s": 25, "text": "\n29 Apr, 2021" }, { "code": null, "e": 209, "s": 53, "text": "Given an array of integers and a number K. The task is to find the XOR of only those elements of the array whose total set bits are equal to K. Examples: " }, { "code": null, "e": 366, "s": 209, "text": "Input : arr[] = {1, 22, 3, 10}, K=1\nOutput : 1\nElements with set bits equal to 1 is 1.\nSo, XOR is also 1.\n\nInput : arr[] = {3, 4, 10, 5, 8}, K=2\nOutput : 12" }, { "code": null, "e": 380, "s": 368, "text": "Approach: " }, { "code": null, "e": 649, "s": 380, "text": "Initialize an empty vector.Traverse the array form left to right and check the set bits of each element.Use, C++ inbuilt function __builtin_popcount() to count setbits.Push the elements with K setbits into the vector.Finally find XOR of all the elements of the vector." }, { "code": null, "e": 677, "s": 649, "text": "Initialize an empty vector." }, { "code": null, "e": 755, "s": 677, "text": "Traverse the array form left to right and check the set bits of each element." }, { "code": null, "e": 820, "s": 755, "text": "Use, C++ inbuilt function __builtin_popcount() to count setbits." }, { "code": null, "e": 870, "s": 820, "text": "Push the elements with K setbits into the vector." }, { "code": null, "e": 922, "s": 870, "text": "Finally find XOR of all the elements of the vector." }, { "code": null, "e": 975, "s": 922, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 979, "s": 975, "text": "C++" }, { "code": null, "e": 984, "s": 979, "text": "Java" }, { "code": null, "e": 992, "s": 984, "text": "Python3" }, { "code": null, "e": 995, "s": 992, "text": "C#" }, { "code": null, "e": 1006, "s": 995, "text": "Javascript" }, { "code": "// C++ program to find Xor// of all elements with set bits// equal to K#include <bits/stdc++.h>using namespace std; // Function to find Xor// of desired elementsint xorGivenSetBits(int arr[], int n, int k){ // Initialize vector vector<int> v; for (int i = 0; i < n; i++) { if (__builtin_popcount(arr[i]) == k) { // push required elements v.push_back(arr[i]); } } // Initialize result with first element of vector int result = v[0]; for (int i = 1; i < v.size(); i++) result = result ^ v[i]; return result;} // Driver codeint main(){ int arr[] = { 2, 13, 1, 19, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << xorGivenSetBits(arr, n, k); return 0;}", "e": 1756, "s": 1006, "text": null }, { "code": "// Java program to find Xor// of all elements with set bits// equal to Kimport java.util.*; class GFG{ // Function to find Xor // of desired elements static int xorGivenSetBits(int arr[], int n, int k) { // Initialize vector Vector<Integer> v = new Vector<>(); for (int i = 0; i < n; i++) { if (Integer.bitCount(arr[i]) == k) { // push required elements v.add(arr[i]); } } // Initialize result with first element of vector int result = v.get(0); for (int i = 1; i < v.size(); i++) { result = result ^ v.get(i); } return result; } // Driver code public static void main(String[] args) { int arr[] = {2, 13, 1, 19, 7}; int n = arr.length; int k = 3; System.out.println(xorGivenSetBits(arr, n, k)); }} // This code contributed by Rajput-Ji", "e": 2736, "s": 1756, "text": null }, { "code": "# Python 3 program to find Xor of all# elements with set bits equal to K # Function to find Xor of desired elementsdef xorGivenSetBits(arr, n, k): # Initialize vector v = [] for i in range(0, n, 1): if (bin(arr[i]).count('1') == k): # push required elements v.append(arr[i]) # Initialize result with first # element of vector result = v[0] for i in range(1, len(v), 1): result = result ^ v[i] return result # Driver codeif __name__ == '__main__': arr = [2, 13, 1, 19, 7] n = len(arr) k = 3 print(xorGivenSetBits(arr, n, k)) # This code is contributed by# Surendra_Gangwar", "e": 3410, "s": 2736, "text": null }, { "code": "// C# program to find Xor// of all elements with set bits// equal to Kusing System;using System.Collections;using System.Linq; class GFG{ // Function to find Xor// of desired elementsstatic int xorGivenSetBits(int []arr, int n, int k){ // Initialize vector ArrayList v=new ArrayList(); for (int i = 0; i < n; i++) { if (Convert.ToString(arr[i], 2).Count(c => c == '1') == k) { // push required elements v.Add(arr[i]); } } // Initialize result with first element of vector int result = (int)v[0]; for (int i = 1; i < v.Count; i++) result = result ^ (int)v[i]; return result;} // Driver codestatic void Main(){ int []arr = { 2, 13, 1, 19, 7 }; int n = arr.Length; int k = 3; Console.WriteLine(xorGivenSetBits(arr, n, k));}} // This code is contributed by mits", "e": 4266, "s": 3410, "text": null }, { "code": "<script> // Javascript program to find Xor// of all elements with set bits// equal to K // Function to find Xor// of desired elementsfunction xorGivenSetBits(arr, n, k){ // Initialize vector let v = []; for (let i = 0; i < n; i++) { if (bitcount(arr[i]) == k) { // push required elements v.push(arr[i]); } } // Initialize result with first // element of vector let result = v[0]; for (let i = 1; i < v.length; i++) result = result ^ v[i]; return result;} function bitcount(n){ var count = 0; while (n) { count += n & 1; n >>= 1; } return count;} // Driver code let arr = [ 2, 13, 1, 19, 7 ]; let n = arr.length; let k = 3; document.write(xorGivenSetBits(arr, n, k)); </script>", "e": 5041, "s": 4266, "text": null }, { "code": null, "e": 5044, "s": 5041, "text": "25" }, { "code": null, "e": 5063, "s": 5046, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5076, "s": 5063, "text": "Mithun Kumar" }, { "code": null, "e": 5086, "s": 5076, "text": "Rajput-Ji" }, { "code": null, "e": 5102, "s": 5086, "text": "souravmahato348" }, { "code": null, "e": 5114, "s": 5102, "text": "Bitwise-XOR" }, { "code": null, "e": 5126, "s": 5114, "text": "setBitCount" }, { "code": null, "e": 5133, "s": 5126, "text": "Arrays" }, { "code": null, "e": 5143, "s": 5133, "text": "Bit Magic" }, { "code": null, "e": 5150, "s": 5143, "text": "Arrays" }, { "code": null, "e": 5160, "s": 5150, "text": "Bit Magic" }, { "code": null, "e": 5258, "s": 5160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5290, "s": 5258, "text": "Introduction to Data Structures" }, { "code": null, "e": 5315, "s": 5290, "text": "Window Sliding Technique" }, { "code": null, "e": 5362, "s": 5315, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 5426, "s": 5362, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 5447, "s": 5426, "text": "Next Greater Element" }, { "code": null, "e": 5474, "s": 5447, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 5520, "s": 5474, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 5588, "s": 5520, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 5617, "s": 5588, "text": "Count set bits in an integer" } ]
Scheduling Cron Job on Google Cloud
13 Feb, 2022 Python is often called a glue language because it’s a powerful tool for easily combining multiple different systems. Part of this is because Python has great client library support, which lets you interact with lots of APIs, products, and services from the comfort of Python. But it doesn’t just end with the cloud. Python is useful for combining just about anything with anything else. A Cron Job is a Linux command used for scheduling tasks to run on the server. They are most commonly used in automation.In this article we will look into the steps of Scheduling a cron job in python on Google cloud storage. As an example we will be writing a python script that gets the top stories from the Hacker News API, then iterate over every story. If any of their titles match serverless, it’ll send you an email with the links. We’ll use the request library to make an HTTP request to the URL for the API, which happens to be hosted on Firebase, a Google Cloud product. The first step would be writing a Python script, Python3 from request import get api_url = 'https://hacker-news.firbaseio.com/v0/' top_stories_url = api_url + 'topstories.json' item_url = api_url + 'item/{}.json' Then if any of the stories match, we’ll use some custom code to send an email formatted with all of the “serverless” stories. We can put this all in a single Python function as shown below: Python3 # sudo code from utils import send_email def check_serverless_stories(request): top_stories = request.get(top_stories_url).json serverless_stories = [] ... send_email(serverless_stories) if serverless_stories: send_email(serverless_stories) We can then deploy this app to Cloud Functions using the below commands: $ gcloud functions deploy check_serverless_stories \ --runtime python38 --trigger-http After deploying, we get a public URL for our function. So whenever we visit this URL it will email us any new articles on the front page of the Hackernews.com. And the last step is running it on a schedule. For this, we use Cloud Scheduler to create a new job, which runs once a day. Cron jobs are scheduled at recurring intervals specified using the Unix cron format. You can define the schedule so that your job runs multiple times a day, or runs on specific days and months. We’ll schedule our job to run once a day at midnight. We’ll use the gcloud scheduler jobs create command to create a job which calls our function on the schedule as shown below: $ gcloud scheduler jobs create http email_job \ --schedule = "0 0 * * *" \ --uri = https://YOUR-REGION-project.cloudfunctions.net/check_serverless_stories We can use gcloud scheduler jobs list to confirm that our job was created using the below command: $ gcloud scheduler jobs list And we can use gcloud scheduler jobs run to run it once regardless of the schedule as below: $ gcloud scheduler jobs run email_job This gets you any serverless articles delivered right to your inbox every day without you having to do a thing. architgwl2000 sumitgumber28 Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture Fuzzy Logic | Introduction Mounting a Volume Inside Docker Container
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2022" }, { "code": null, "e": 415, "s": 28, "text": "Python is often called a glue language because it’s a powerful tool for easily combining multiple different systems. Part of this is because Python has great client library support, which lets you interact with lots of APIs, products, and services from the comfort of Python. But it doesn’t just end with the cloud. Python is useful for combining just about anything with anything else." }, { "code": null, "e": 641, "s": 415, "text": "A Cron Job is a Linux command used for scheduling tasks to run on the server. They are most commonly used in automation.In this article we will look into the steps of Scheduling a cron job in python on Google cloud storage. " }, { "code": null, "e": 996, "s": 641, "text": "As an example we will be writing a python script that gets the top stories from the Hacker News API, then iterate over every story. If any of their titles match serverless, it’ll send you an email with the links. We’ll use the request library to make an HTTP request to the URL for the API, which happens to be hosted on Firebase, a Google Cloud product." }, { "code": null, "e": 1045, "s": 996, "text": "The first step would be writing a Python script," }, { "code": null, "e": 1053, "s": 1045, "text": "Python3" }, { "code": "from request import get api_url = 'https://hacker-news.firbaseio.com/v0/' top_stories_url = api_url + 'topstories.json' item_url = api_url + 'item/{}.json'", "e": 1209, "s": 1053, "text": null }, { "code": null, "e": 1399, "s": 1209, "text": "Then if any of the stories match, we’ll use some custom code to send an email formatted with all of the “serverless” stories. We can put this all in a single Python function as shown below:" }, { "code": null, "e": 1407, "s": 1399, "text": "Python3" }, { "code": "# sudo code from utils import send_email def check_serverless_stories(request): top_stories = request.get(top_stories_url).json serverless_stories = [] ... send_email(serverless_stories) if serverless_stories: send_email(serverless_stories)", "e": 1664, "s": 1407, "text": null }, { "code": null, "e": 1739, "s": 1664, "text": " We can then deploy this app to Cloud Functions using the below commands:" }, { "code": null, "e": 1830, "s": 1739, "text": "$ gcloud functions deploy check_serverless_stories \\\n --runtime python38\n --trigger-http" }, { "code": null, "e": 1990, "s": 1830, "text": "After deploying, we get a public URL for our function. So whenever we visit this URL it will email us any new articles on the front page of the Hackernews.com." }, { "code": null, "e": 2114, "s": 1990, "text": "And the last step is running it on a schedule. For this, we use Cloud Scheduler to create a new job, which runs once a day." }, { "code": null, "e": 2308, "s": 2114, "text": "Cron jobs are scheduled at recurring intervals specified using the Unix cron format. You can define the schedule so that your job runs multiple times a day, or runs on specific days and months." }, { "code": null, "e": 2489, "s": 2310, "text": " We’ll schedule our job to run once a day at midnight. We’ll use the gcloud scheduler jobs create command to create a job which calls our function on the schedule as shown below:" }, { "code": null, "e": 2648, "s": 2489, "text": "$ gcloud scheduler jobs create http email_job \\\n --schedule = \"0 0 * * *\" \\\n --uri = https://YOUR-REGION-project.cloudfunctions.net/check_serverless_stories" }, { "code": null, "e": 2748, "s": 2648, "text": "We can use gcloud scheduler jobs list to confirm that our job was created using the below command: " }, { "code": null, "e": 2777, "s": 2748, "text": "$ gcloud scheduler jobs list" }, { "code": null, "e": 2870, "s": 2777, "text": "And we can use gcloud scheduler jobs run to run it once regardless of the schedule as below:" }, { "code": null, "e": 2908, "s": 2870, "text": "$ gcloud scheduler jobs run email_job" }, { "code": null, "e": 3020, "s": 2908, "text": "This gets you any serverless articles delivered right to your inbox every day without you having to do a thing." }, { "code": null, "e": 3034, "s": 3020, "text": "architgwl2000" }, { "code": null, "e": 3048, "s": 3034, "text": "sumitgumber28" }, { "code": null, "e": 3074, "s": 3048, "text": "Advanced Computer Subject" }, { "code": null, "e": 3172, "s": 3074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3208, "s": 3172, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3232, "s": 3208, "text": "Markov Decision Process" }, { "code": null, "e": 3268, "s": 3232, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 3312, "s": 3268, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 3347, "s": 3312, "text": "Getting Started with System Design" }, { "code": null, "e": 3388, "s": 3347, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 3436, "s": 3388, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 3477, "s": 3436, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 3504, "s": 3477, "text": "Fuzzy Logic | Introduction" } ]
Random Forest Approach for Regression in R Programming
10 Jul, 2020 Random Forest approach is a supervised learning algorithm. It builds the multiple decision trees which are known as forest and glue them together to urge a more accurate and stable prediction. The random forest approach is similar to the ensemble technique called as Bagging. In this approach, multiple trees are generated by bootstrap samples from training data and then we simply reduce the correlation between the trees. Performing this approach increases the performance of decision trees and helps in avoiding overriding. In this article, let’s learn to use a random forest approach for regression in R programming. Aggregates many decision trees: A random forest is a collection of decision trees and thus, does not rely on a single feature and combines multiple predictions from each decision tree. Prevents overfitting: With multiple decision trees, each tree draws a sample random data giving the random forest more randomness to produce much better accuracy than decision trees. Efficient: Random forests are much more efficient than decision trees while performing on large databases. Highly accurate: Random forests are highly accurate as they are collection of decision trees and each decision tree draws sample random data and in result, random forests produces higher accuracy on prediction. Efficient estimates of the test error: It makes efficient use of all predictive features and maintains accuracy even if the data is missing. Requires different number of levels: Being a collection of decision trees, random forest requires different number of levels for much accurate and biased prediction of the training model. Requires a lot of memory: Training a large set of trees may require higher memory or parallelized memory. The package randomForest in R programming is employed to create random forests. The forest it builds is a collection of decision trees. The function randomForest() is used to create and analyze random forests. Syntax:randomForest(formula, data) Parameters:formula: represents formula describing the model to be fitteddata: represents data frame containing the variables in the model To know about more optional parameters, use command help(“randomForest”) Example: Step 1: Installing the required packages.# Install the required package for functioninstall.packages("randomForest") # Install the required package for functioninstall.packages("randomForest") Step 2: Loading the required package.# Load the librarylibrary(randomForest) # Load the librarylibrary(randomForest) Step 3: In this example, let’s use airquality dataset present in R. Print the data set.# Print the datasetprint(head(airquality))Output: Ozone Solar.R Wind Temp Month Day 1 41 190 7.4 67 5 1 2 36 118 8.0 72 5 2 3 12 149 12.6 74 5 3 4 18 313 11.5 62 5 4 5 NA NA 14.3 56 5 5 6 28 NA 14.9 66 5 6 # Print the datasetprint(head(airquality)) Output: Ozone Solar.R Wind Temp Month Day 1 41 190 7.4 67 5 1 2 36 118 8.0 72 5 2 3 12 149 12.6 74 5 3 4 18 313 11.5 62 5 4 5 NA NA 14.3 56 5 5 6 28 NA 14.9 66 5 6 Step 4: Create random forest for regression# Create random forest for regressionozone.rf <- randomForest(Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit) # Create random forest for regressionozone.rf <- randomForest(Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit) Step 5: Print Regression Models# Print regression modelprint(ozone.rf)Output:Call: randomForest(formula = Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit) Type of random forest: regression Number of trees: 500 No. of variables tried at each split: 3 Mean of squared residuals: 296.4822 % Var explained: 72.98 # Print regression modelprint(ozone.rf) Output: Call: randomForest(formula = Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit) Type of random forest: regression Number of trees: 500 No. of variables tried at each split: 3 Mean of squared residuals: 296.4822 % Var explained: 72.98 Step 6: Plotting the graph between error vs number of trees# Output to be present as PNG file png(file = "randomForestRegression.png") # Plot the error vs the number of trees graphplot(ozone.rf) # Saving the filedev.off()Output: # Output to be present as PNG file png(file = "randomForestRegression.png") # Plot the error vs the number of trees graphplot(ozone.rf) # Saving the filedev.off() Picked R Machine-Learning R regression R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 649, "s": 28, "text": "Random Forest approach is a supervised learning algorithm. It builds the multiple decision trees which are known as forest and glue them together to urge a more accurate and stable prediction. The random forest approach is similar to the ensemble technique called as Bagging. In this approach, multiple trees are generated by bootstrap samples from training data and then we simply reduce the correlation between the trees. Performing this approach increases the performance of decision trees and helps in avoiding overriding. In this article, let’s learn to use a random forest approach for regression in R programming." }, { "code": null, "e": 834, "s": 649, "text": "Aggregates many decision trees: A random forest is a collection of decision trees and thus, does not rely on a single feature and combines multiple predictions from each decision tree." }, { "code": null, "e": 1017, "s": 834, "text": "Prevents overfitting: With multiple decision trees, each tree draws a sample random data giving the random forest more randomness to produce much better accuracy than decision trees." }, { "code": null, "e": 1124, "s": 1017, "text": "Efficient: Random forests are much more efficient than decision trees while performing on large databases." }, { "code": null, "e": 1335, "s": 1124, "text": "Highly accurate: Random forests are highly accurate as they are collection of decision trees and each decision tree draws sample random data and in result, random forests produces higher accuracy on prediction." }, { "code": null, "e": 1476, "s": 1335, "text": "Efficient estimates of the test error: It makes efficient use of all predictive features and maintains accuracy even if the data is missing." }, { "code": null, "e": 1664, "s": 1476, "text": "Requires different number of levels: Being a collection of decision trees, random forest requires different number of levels for much accurate and biased prediction of the training model." }, { "code": null, "e": 1770, "s": 1664, "text": "Requires a lot of memory: Training a large set of trees may require higher memory or parallelized memory." }, { "code": null, "e": 1980, "s": 1770, "text": "The package randomForest in R programming is employed to create random forests. The forest it builds is a collection of decision trees. The function randomForest() is used to create and analyze random forests." }, { "code": null, "e": 2015, "s": 1980, "text": "Syntax:randomForest(formula, data)" }, { "code": null, "e": 2153, "s": 2015, "text": "Parameters:formula: represents formula describing the model to be fitteddata: represents data frame containing the variables in the model" }, { "code": null, "e": 2226, "s": 2153, "text": "To know about more optional parameters, use command help(“randomForest”)" }, { "code": null, "e": 2235, "s": 2226, "text": "Example:" }, { "code": null, "e": 2352, "s": 2235, "text": "Step 1: Installing the required packages.# Install the required package for functioninstall.packages(\"randomForest\")" }, { "code": "# Install the required package for functioninstall.packages(\"randomForest\")", "e": 2428, "s": 2352, "text": null }, { "code": null, "e": 2505, "s": 2428, "text": "Step 2: Loading the required package.# Load the librarylibrary(randomForest)" }, { "code": "# Load the librarylibrary(randomForest)", "e": 2545, "s": 2505, "text": null }, { "code": null, "e": 2935, "s": 2545, "text": "Step 3: In this example, let’s use airquality dataset present in R. Print the data set.# Print the datasetprint(head(airquality))Output: Ozone Solar.R Wind Temp Month Day\n1 41 190 7.4 67 5 1\n2 36 118 8.0 72 5 2\n3 12 149 12.6 74 5 3\n4 18 313 11.5 62 5 4\n5 NA NA 14.3 56 5 5\n6 28 NA 14.9 66 5 6\n" }, { "code": "# Print the datasetprint(head(airquality))", "e": 2978, "s": 2935, "text": null }, { "code": null, "e": 2986, "s": 2978, "text": "Output:" }, { "code": null, "e": 3240, "s": 2986, "text": " Ozone Solar.R Wind Temp Month Day\n1 41 190 7.4 67 5 1\n2 36 118 8.0 72 5 2\n3 12 149 12.6 74 5 3\n4 18 313 11.5 62 5 4\n5 NA NA 14.3 56 5 5\n6 28 NA 14.9 66 5 6\n" }, { "code": null, "e": 3449, "s": 3240, "text": "Step 4: Create random forest for regression# Create random forest for regressionozone.rf <- randomForest(Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit)" }, { "code": "# Create random forest for regressionozone.rf <- randomForest(Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit)", "e": 3615, "s": 3449, "text": null }, { "code": null, "e": 4030, "s": 3615, "text": "Step 5: Print Regression Models# Print regression modelprint(ozone.rf)Output:Call:\n randomForest(formula = Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit) \n Type of random forest: regression\n Number of trees: 500\nNo. of variables tried at each split: 3\n\n Mean of squared residuals: 296.4822\n % Var explained: 72.98\n" }, { "code": "# Print regression modelprint(ozone.rf)", "e": 4070, "s": 4030, "text": null }, { "code": null, "e": 4078, "s": 4070, "text": "Output:" }, { "code": null, "e": 4416, "s": 4078, "text": "Call:\n randomForest(formula = Ozone ~ ., data = airquality, mtry = 3, importance = TRUE, na.action = na.omit) \n Type of random forest: regression\n Number of trees: 500\nNo. of variables tried at each split: 3\n\n Mean of squared residuals: 296.4822\n % Var explained: 72.98\n" }, { "code": null, "e": 4647, "s": 4416, "text": "Step 6: Plotting the graph between error vs number of trees# Output to be present as PNG file png(file = \"randomForestRegression.png\") # Plot the error vs the number of trees graphplot(ozone.rf) # Saving the filedev.off()Output:" }, { "code": "# Output to be present as PNG file png(file = \"randomForestRegression.png\") # Plot the error vs the number of trees graphplot(ozone.rf) # Saving the filedev.off()", "e": 4812, "s": 4647, "text": null }, { "code": null, "e": 4819, "s": 4812, "text": "Picked" }, { "code": null, "e": 4838, "s": 4819, "text": "R Machine-Learning" }, { "code": null, "e": 4851, "s": 4838, "text": "R regression" }, { "code": null, "e": 4862, "s": 4851, "text": "R Language" } ]
JavaScript program to check if a given year is leap year
12 Apr, 2019 Prerequisite:Understanding basic JavaScript codes.A year is leap year if following conditions are satisfied: Year is multiple of 400. Year is multiple of 4 and not multiple of 100. Approach: Get the value of input field by using document.getElementById(“year”).value Check the given year is leap year or not by using JavaScript expression and display its value. Example: <!-- HTML code to implement the given year is leap year or not --><!DOCTYPE html><html> <head> <title> JavaScript to check leap year </title></head> <body> Input Year: <input type="text" id = "year"/> <input type="button" id="button" onClick="isLeapYear()" value="Check Leap Year"> <p id="GFG"></p> <!-- JavaScript code to check given year is leap year or not --> <script> function isLeapYear() { var year= document.getElementById("year").value; document.getElementById("GFG").innerHTML = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); } </script></body> </html> Output: Before input year: After input leap year: After input not leap year: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Apr, 2019" }, { "code": null, "e": 162, "s": 53, "text": "Prerequisite:Understanding basic JavaScript codes.A year is leap year if following conditions are satisfied:" }, { "code": null, "e": 187, "s": 162, "text": "Year is multiple of 400." }, { "code": null, "e": 234, "s": 187, "text": "Year is multiple of 4 and not multiple of 100." }, { "code": null, "e": 244, "s": 234, "text": "Approach:" }, { "code": null, "e": 320, "s": 244, "text": "Get the value of input field by using document.getElementById(“year”).value" }, { "code": null, "e": 415, "s": 320, "text": "Check the given year is leap year or not by using JavaScript expression and display its value." }, { "code": null, "e": 424, "s": 415, "text": "Example:" }, { "code": "<!-- HTML code to implement the given year is leap year or not --><!DOCTYPE html><html> <head> <title> JavaScript to check leap year </title></head> <body> Input Year: <input type=\"text\" id = \"year\"/> <input type=\"button\" id=\"button\" onClick=\"isLeapYear()\" value=\"Check Leap Year\"> <p id=\"GFG\"></p> <!-- JavaScript code to check given year is leap year or not --> <script> function isLeapYear() { var year= document.getElementById(\"year\").value; document.getElementById(\"GFG\").innerHTML = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); } </script></body> </html> ", "e": 1196, "s": 424, "text": null }, { "code": null, "e": 1204, "s": 1196, "text": "Output:" }, { "code": null, "e": 1223, "s": 1204, "text": "Before input year:" }, { "code": null, "e": 1246, "s": 1223, "text": "After input leap year:" }, { "code": null, "e": 1273, "s": 1246, "text": "After input not leap year:" }, { "code": null, "e": 1284, "s": 1273, "text": "JavaScript" }, { "code": null, "e": 1301, "s": 1284, "text": "Web Technologies" }, { "code": null, "e": 1328, "s": 1301, "text": "Web technologies Questions" }, { "code": null, "e": 1426, "s": 1328, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1487, "s": 1426, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1559, "s": 1487, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1599, "s": 1559, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1640, "s": 1599, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1682, "s": 1640, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1715, "s": 1682, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1777, "s": 1715, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1838, "s": 1777, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1888, "s": 1838, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
12 Oct, 2021 There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed hereThere is another interesting method to do the same without using the above methods, using tuples (for returning multiple values ) and pairs (for two values). We can declare the function with return type as pair or tuple (whichever is required) and can pack the values to be returned and return the packed set of values. The returned values can be unpacked in the calling function. Tuple A tuple is an object capable to hold a collection of elements where each element can be of a different type. Class template std::tuple is a fixed-size collection of heterogeneous values Pair This class couples together a pair of values, which may be of different types A pair is a specific case of a std::tuple with two elements Note : Tuple can also be used to return two values instead of using pair . #include<bits/stdc++.h>using namespace std; // A Method that returns multiple values using// tuple in C++.tuple<int, int, char> foo(int n1, int n2){ // Packing values to return a tuple return make_tuple(n2, n1, 'a'); } // A Method returns a pair of values using pairstd::pair<int, int> foo1(int num1, int num2){ // Packing two values to return a pair return std::make_pair(num2, num1); } int main(){ int a,b; char cc; // Unpack the elements returned by foo tie(a, b, cc) = foo(5, 10); // Storing returned values in a pair pair<int, int> p = foo1(5,2); cout << "Values returned by tuple: "; cout << a << " " << b << " " << cc << endl; cout << "Values returned by Pair: "; cout << p.first << " " << p.second; return 0;} Output: Values returned by tuple: 10 5 a Values returned by Pair: 2 5 This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above tanwarsinghvaibhav CPP-Functions STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Oct, 2021" }, { "code": null, "e": 440, "s": 52, "text": "There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed hereThere is another interesting method to do the same without using the above methods, using tuples (for returning multiple values ) and pairs (for two values)." }, { "code": null, "e": 663, "s": 440, "text": "We can declare the function with return type as pair or tuple (whichever is required) and can pack the values to be returned and return the packed set of values. The returned values can be unpacked in the calling function." }, { "code": null, "e": 669, "s": 663, "text": "Tuple" }, { "code": null, "e": 778, "s": 669, "text": "A tuple is an object capable to hold a collection of elements where each element can be of a different type." }, { "code": null, "e": 855, "s": 778, "text": "Class template std::tuple is a fixed-size collection of heterogeneous values" }, { "code": null, "e": 860, "s": 855, "text": "Pair" }, { "code": null, "e": 938, "s": 860, "text": "This class couples together a pair of values, which may be of different types" }, { "code": null, "e": 998, "s": 938, "text": "A pair is a specific case of a std::tuple with two elements" }, { "code": null, "e": 1073, "s": 998, "text": "Note : Tuple can also be used to return two values instead of using pair ." }, { "code": "#include<bits/stdc++.h>using namespace std; // A Method that returns multiple values using// tuple in C++.tuple<int, int, char> foo(int n1, int n2){ // Packing values to return a tuple return make_tuple(n2, n1, 'a'); } // A Method returns a pair of values using pairstd::pair<int, int> foo1(int num1, int num2){ // Packing two values to return a pair return std::make_pair(num2, num1); } int main(){ int a,b; char cc; // Unpack the elements returned by foo tie(a, b, cc) = foo(5, 10); // Storing returned values in a pair pair<int, int> p = foo1(5,2); cout << \"Values returned by tuple: \"; cout << a << \" \" << b << \" \" << cc << endl; cout << \"Values returned by Pair: \"; cout << p.first << \" \" << p.second; return 0;}", "e": 1897, "s": 1073, "text": null }, { "code": null, "e": 1905, "s": 1897, "text": "Output:" }, { "code": null, "e": 1968, "s": 1905, "text": "Values returned by tuple: 10 5 a\nValues returned by Pair: 2 5\n" }, { "code": null, "e": 2235, "s": 1968, "text": "This article is contributed by Mayank Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2359, "s": 2235, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 2378, "s": 2359, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 2392, "s": 2378, "text": "CPP-Functions" }, { "code": null, "e": 2396, "s": 2392, "text": "STL" }, { "code": null, "e": 2407, "s": 2396, "text": "C Language" }, { "code": null, "e": 2411, "s": 2407, "text": "C++" }, { "code": null, "e": 2415, "s": 2411, "text": "STL" }, { "code": null, "e": 2419, "s": 2415, "text": "CPP" }, { "code": null, "e": 2517, "s": 2419, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2534, "s": 2517, "text": "Substring in C++" }, { "code": null, "e": 2556, "s": 2534, "text": "Function Pointer in C" }, { "code": null, "e": 2602, "s": 2556, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2647, "s": 2602, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2672, "s": 2647, "text": "std::string class in C++" }, { "code": null, "e": 2690, "s": 2672, "text": "Vector in C++ STL" }, { "code": null, "e": 2733, "s": 2690, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2779, "s": 2733, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2822, "s": 2779, "text": "Set in C++ Standard Template Library (STL)" } ]
Python PIL | ImageDraw.Draw.text()
05 Sep, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use. ImageDraw.Draw.text() Draws the string at the given position. Syntax:ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”) Parameters:xy – Top left corner of the text.text – Text to be drawn. If it contains any newline characters, the text is passed on to multiline_text()fill – Color to use for the text.font – An ImageFont instance.spacing – If the text is passed on to multiline_text(), the number of pixels between lines.align – If the text is passed on to multiline_text(), “left”, “center” or “right”. Return Type:returns an image with text. Image Used: Code : Using PIL | ImageDraw.Draw.text() # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\rose.jpg') draw = ImageDraw.Draw(image) # specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 20) text = 'LAUGHING IS THE \n BEST MEDICINE' # drawing text sizedraw.text((5, 5), text, font = font, align ="left") image.show() Output: Another Example:Here we changing parameter. Image Used: Code : Using PIL | ImageDraw.Draw.text() # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\flower.jpg') draw = ImageDraw.Draw(image) # specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 20) text = 'LAUGHING IS THE \n BEST MEDICINE' # drawing text sizedraw.text((5, 5), text, fill ="red", font = font, align ="right") image.show() Output: Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Sep, 2019" }, { "code": null, "e": 356, "s": 52, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use." }, { "code": null, "e": 418, "s": 356, "text": "ImageDraw.Draw.text() Draws the string at the given position." }, { "code": null, "e": 515, "s": 418, "text": "Syntax:ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)" }, { "code": null, "e": 900, "s": 515, "text": "Parameters:xy – Top left corner of the text.text – Text to be drawn. If it contains any newline characters, the text is passed on to multiline_text()fill – Color to use for the text.font – An ImageFont instance.spacing – If the text is passed on to multiline_text(), the number of pixels between lines.align – If the text is passed on to multiline_text(), “left”, “center” or “right”." }, { "code": null, "e": 940, "s": 900, "text": "Return Type:returns an image with text." }, { "code": null, "e": 952, "s": 940, "text": "Image Used:" }, { "code": null, "e": 993, "s": 952, "text": "Code : Using PIL | ImageDraw.Draw.text()" }, { "code": " # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw # creating a image object image = Image.open(r'C:\\Users\\System-Pc\\Desktop\\rose.jpg') draw = ImageDraw.Draw(image) # specified font sizefont = ImageFont.truetype(r'C:\\Users\\System-Pc\\Desktop\\arial.ttf', 20) text = 'LAUGHING IS THE \\n BEST MEDICINE' # drawing text sizedraw.text((5, 5), text, font = font, align =\"left\") image.show() ", "e": 1457, "s": 993, "text": null }, { "code": null, "e": 1465, "s": 1457, "text": "Output:" }, { "code": null, "e": 1509, "s": 1465, "text": "Another Example:Here we changing parameter." }, { "code": null, "e": 1521, "s": 1509, "text": "Image Used:" }, { "code": null, "e": 1562, "s": 1521, "text": "Code : Using PIL | ImageDraw.Draw.text()" }, { "code": " # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw # creating a image object image = Image.open(r'C:\\Users\\System-Pc\\Desktop\\flower.jpg') draw = ImageDraw.Draw(image) # specified font sizefont = ImageFont.truetype(r'C:\\Users\\System-Pc\\Desktop\\arial.ttf', 20) text = 'LAUGHING IS THE \\n BEST MEDICINE' # drawing text sizedraw.text((5, 5), text, fill =\"red\", font = font, align =\"right\") image.show() ", "e": 2042, "s": 1562, "text": null }, { "code": null, "e": 2050, "s": 2042, "text": "Output:" }, { "code": null, "e": 2057, "s": 2050, "text": "Python" } ]
How to create a custom listview in android?
Before getting into listview example, we should know about listview, Listview is a collection of items pulled from arraylist, list or any databases. Most uses of listview is a collection of items in vertical format, we can scroll up/down and click on any item. Custom listview works based on customAdapter. In this custom adapter we can pass custom object. We are passing subject data to listview as shown below − Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout 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"> <LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical"> <ListView android:id = "@+id/list" android:layout_width = "wrap_content" android:layout_height = "match_parent" android:divider = "#000" android:dividerHeight = "1dp" android:footerDividersEnabled = "false" android:headerDividersEnabled = "false"/> </LinearLayout> </android.support.constraint.ConstraintLayout> In the above activity_main.xml, we have declared a listview and added divider as shown below. <ListView android:id = "@+id/list" android:layout_width = "wrap_content" android:layout_height = "match_parent" android:divider = "#000" android:dividerHeight = "1dp" android:footerDividersEnabled = "false" android:headerDividersEnabled = "false" /> Step 3 − Add the following code to src/MainActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView list = findViewById(R.id.list); ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>(); arrayList.add(new SubjectData("JAVA", "https://www.tutorialspoint.com/java/", "https://www.tutorialspoint.com/java/images/java-mini-logo.jpg")); arrayList.add(new SubjectData("Python", "https://www.tutorialspoint.com/python/", "https://www.tutorialspoint.com/python/images/python-mini.jpg")); arrayList.add(new SubjectData("Javascript", "https://www.tutorialspoint.com/javascript/", "https://www.tutorialspoint.com/javascript/images/javascript-mini-logo.jpg")); arrayList.add(new SubjectData("Cprogramming", "https://www.tutorialspoint.com/cprogramming/", "https://www.tutorialspoint.com/cprogramming/images/c-mini-logo.jpg")); arrayList.add(new SubjectData("Cplusplus", "https://www.tutorialspoint.com/cplusplus/", "https://www.tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg")); arrayList.add(new SubjectData("Android", "https://www.tutorialspoint.com/android/", "https://www.tutorialspoint.com/android/images/android-mini-logo.jpg")); CustomAdapter customAdapter = new CustomAdapter(this, arrayList); list.setAdapter(customAdapter); } } In the mainActivity, we have declared CustomAdapter and passed SubjectData as shown below − CustomAdapter customAdapter = new CustomAdapter(this, arrayList); list.setAdapter(customAdapter); Step 4 − Create a CustomAdapter class Add the following code to src/ CustomAdapter.java import android.content.Context; import android.database.DataSetObserver; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; class CustomAdapter implements ListAdapter { ArrayList<SubjectData> arrayList; Context context; public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) { this.arrayList=arrayList; this.context=context; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return true; } @Override public void registerDataSetObserver(DataSetObserver observer) { } @Override public void unregisterDataSetObserver(DataSetObserver observer) { } @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int position, View convertView, ViewGroup parent) { SubjectData subjectData=arrayList.get(position); if(convertView==null) { LayoutInflater layoutInflater = LayoutInflater.from(context); convertView=layoutInflater.inflate(R.layout.list_row, null); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); TextView tittle=convertView.findViewById(R.id.title); ImageView imag=convertView.findViewById(R.id.list_image); tittle.setText(subjectData.SubjectName); Picasso.with(context) .load(subjectData.Image) .into(imag); } return convertView; } @Override public int getItemViewType(int position) { return position; } @Override public int getViewTypeCount() { return arrayList.size(); } @Override public boolean isEmpty() { return false; } } Step 5 − Create a SubjectData class, Add the following code to src/ SubjectData.java class SubjectData { String SubjectName; String Link; String Image; public SubjectData(String subjectName, String link, String image) { this.SubjectName = subjectName; this.Link = link; this.Image = image; } } Step 6 − In the CustomAdapter class we have showed internet source image. To show internet source image. we have added picasso library as shown below. Picasso.with(context) .load(subjectData.Image) .into(imag); Step 7 − For picasso library implementation, we have to add picasso library in gradle as shown below apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.myapplication" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' implementation 'com.squareup.picasso:picasso:2.5.1' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Step 8 − To access internet information, we have to give internet permission to manifest file as shown below. <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. Click here to download the project code
[ { "code": null, "e": 1448, "s": 1187, "text": "Before getting into listview example, we should know about listview, Listview is a collection of items pulled from arraylist, list or any databases. Most uses of listview is a collection of items in vertical format, we can scroll up/down and click on any item." }, { "code": null, "e": 1601, "s": 1448, "text": "Custom listview works based on customAdapter. In this custom adapter we can pass custom object. We are passing subject data to listview as shown below −" }, { "code": null, "e": 1730, "s": 1601, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1795, "s": 1730, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2565, "s": 1795, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout\nxmlns:android = \"http://schemas.android.com/apk/res/android\" xmlns:tools = \"http://schemas.android.com/tools\" android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\">\n<LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:orientation = \"vertical\">\n <ListView\n android:id = \"@+id/list\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:divider = \"#000\"\n android:dividerHeight = \"1dp\"\n android:footerDividersEnabled = \"false\"\n android:headerDividersEnabled = \"false\"/>\n</LinearLayout>\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2659, "s": 2565, "text": "In the above activity_main.xml, we have declared a listview and added divider as shown below." }, { "code": null, "e": 2930, "s": 2659, "text": "<ListView\n android:id = \"@+id/list\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:divider = \"#000\"\n android:dividerHeight = \"1dp\"\n android:footerDividersEnabled = \"false\"\n android:headerDividersEnabled = \"false\"\n/>" }, { "code": null, "e": 2987, "s": 2930, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4566, "s": 2987, "text": "import android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ListView;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ListView list = findViewById(R.id.list);\n ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();\n arrayList.add(new SubjectData(\"JAVA\", \"https://www.tutorialspoint.com/java/\", \"https://www.tutorialspoint.com/java/images/java-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Python\", \"https://www.tutorialspoint.com/python/\", \"https://www.tutorialspoint.com/python/images/python-mini.jpg\"));\n arrayList.add(new SubjectData(\"Javascript\", \"https://www.tutorialspoint.com/javascript/\", \"https://www.tutorialspoint.com/javascript/images/javascript-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Cprogramming\", \"https://www.tutorialspoint.com/cprogramming/\", \"https://www.tutorialspoint.com/cprogramming/images/c-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Cplusplus\", \"https://www.tutorialspoint.com/cplusplus/\", \"https://www.tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg\"));\n arrayList.add(new SubjectData(\"Android\", \"https://www.tutorialspoint.com/android/\", \"https://www.tutorialspoint.com/android/images/android-mini-logo.jpg\"));\n CustomAdapter customAdapter = new CustomAdapter(this, arrayList);\n list.setAdapter(customAdapter);\n }\n}" }, { "code": null, "e": 4658, "s": 4566, "text": "In the mainActivity, we have declared CustomAdapter and passed SubjectData as shown below −" }, { "code": null, "e": 4756, "s": 4658, "text": "CustomAdapter customAdapter = new CustomAdapter(this, arrayList);\nlist.setAdapter(customAdapter);" }, { "code": null, "e": 4844, "s": 4756, "text": "Step 4 − Create a CustomAdapter class Add the following code to src/ CustomAdapter.java" }, { "code": null, "e": 7085, "s": 4844, "text": "import android.content.Context;\nimport android.database.DataSetObserver;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.ListAdapter;\nimport android.widget.TextView;\nimport com.squareup.picasso.Picasso;\nimport java.util.ArrayList;\nclass CustomAdapter implements ListAdapter {\n ArrayList<SubjectData> arrayList;\n Context context;\n public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {\n this.arrayList=arrayList;\n this.context=context;\n }\n @Override\n public boolean areAllItemsEnabled() {\n return false;\n }\n @Override\n public boolean isEnabled(int position) {\n return true;\n }\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n }\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n }\n @Override\n public int getCount() {\n return arrayList.size();\n }\n @Override\n public Object getItem(int position) {\n return position;\n }\n @Override\n public long getItemId(int position) {\n return position;\n }\n @Override\n public boolean hasStableIds() {\n return false;\n }\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n SubjectData subjectData=arrayList.get(position);\n if(convertView==null) {\n LayoutInflater layoutInflater = LayoutInflater.from(context);\n convertView=layoutInflater.inflate(R.layout.list_row, null);\n convertView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n }\n });\n TextView tittle=convertView.findViewById(R.id.title);\n ImageView imag=convertView.findViewById(R.id.list_image);\n tittle.setText(subjectData.SubjectName);\n Picasso.with(context)\n .load(subjectData.Image)\n .into(imag);\n }\n return convertView;\n }\n @Override\n public int getItemViewType(int position) {\n return position;\n }\n @Override\n public int getViewTypeCount() {\n return arrayList.size();\n }\n @Override\n public boolean isEmpty() {\n return false;\n }\n}" }, { "code": null, "e": 7170, "s": 7085, "text": "Step 5 − Create a SubjectData class, Add the following code to src/ SubjectData.java" }, { "code": null, "e": 7412, "s": 7170, "text": "class SubjectData {\n String SubjectName;\n String Link;\n String Image;\n public SubjectData(String subjectName, String link, String image) {\n this.SubjectName = subjectName;\n this.Link = link;\n this.Image = image;\n }\n}" }, { "code": null, "e": 7563, "s": 7412, "text": "Step 6 − In the CustomAdapter class we have showed internet source image. To show internet source image. we have added picasso library as shown below." }, { "code": null, "e": 7623, "s": 7563, "text": "Picasso.with(context)\n.load(subjectData.Image)\n.into(imag);" }, { "code": null, "e": 7724, "s": 7623, "text": "Step 7 − For picasso library implementation, we have to add picasso library in gradle as shown below" }, { "code": null, "e": 8681, "s": 7724, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n } \n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n implementation 'com.squareup.picasso:picasso:2.5.1'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 8791, "s": 8681, "text": "Step 8 − To access internet information, we have to give internet permission to manifest file as shown below." }, { "code": null, "e": 9570, "s": 8791, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n<uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9917, "s": 9570, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." }, { "code": null, "e": 9957, "s": 9917, "text": "Click here to download the project code" } ]
Successor Graph
28 Jan, 2021 A Successor Graph is a directed graph in which each vertex has outdegree one, i.e., exactly one edge starts at each node. A successor graph consists of one or more components, each of which contains one cycle and some paths that lead to it. Successor graphs are sometimes called functional graphs. The reason for this is that any successor graph corresponds to a function that defines the edges of the graph. The parameter for the function is a node of the graph, and the function gives the successor of that node. For Example, the function The above function defines the below graph: Since each node of a successor graph has a unique successor, a function succ(x, k) can also be defined that gives the node when a traversal begin at node x and walk k steps forward. For example, in the above graph succ(4, 6) = 2, because node 2 can be reached by walking 6 steps from node 4: A straightforward way to calculate a value of succ(x, k) is to start at node x and walk k steps forward, which takes O(k) time. However, using preprocessing, any value of succ(x, k) can be calculated in only O(logk) time. The idea is to precalculate all values of succ(x, k) where k is a power of two and at most u, where u is the maximum number of steps we will ever walk. This can be efficiently done because we can use the following recursion: Precalculating the values takes O(n*log u) time because O(log u) values are calculated for each node. In the above graph, the first values are as follows: After this, any value of succ(x, k) can be calculated by presenting the number of steps k as a sum of powers of two. For example, if we want to calculate the value of succ(x, 11), we first form the representation 11 = 8 + 2 + 1. Using that For example, in the previous graph Such a representation always consists of O(log k) parts, so calculating a value of succ(x, k) takes O(log k) time. Articles Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2021" }, { "code": null, "e": 269, "s": 28, "text": "A Successor Graph is a directed graph in which each vertex has outdegree one, i.e., exactly one edge starts at each node. A successor graph consists of one or more components, each of which contains one cycle and some paths that lead to it." }, { "code": null, "e": 569, "s": 269, "text": "Successor graphs are sometimes called functional graphs. The reason for this is that any successor graph corresponds to a function that defines the edges of the graph. The parameter for the function is a node of the graph, and the function gives the successor of that node. For Example, the function" }, { "code": null, "e": 613, "s": 569, "text": "The above function defines the below graph:" }, { "code": null, "e": 905, "s": 613, "text": "Since each node of a successor graph has a unique successor, a function succ(x, k) can also be defined that gives the node when a traversal begin at node x and walk k steps forward. For example, in the above graph succ(4, 6) = 2, because node 2 can be reached by walking 6 steps from node 4:" }, { "code": null, "e": 1127, "s": 905, "text": "A straightforward way to calculate a value of succ(x, k) is to start at node x and walk k steps forward, which takes O(k) time. However, using preprocessing, any value of succ(x, k) can be calculated in only O(logk) time." }, { "code": null, "e": 1352, "s": 1127, "text": "The idea is to precalculate all values of succ(x, k) where k is a power of two and at most u, where u is the maximum number of steps we will ever walk. This can be efficiently done because we can use the following recursion:" }, { "code": null, "e": 1507, "s": 1352, "text": "Precalculating the values takes O(n*log u) time because O(log u) values are calculated for each node. In the above graph, the first values are as follows:" }, { "code": null, "e": 1747, "s": 1507, "text": "After this, any value of succ(x, k) can be calculated by presenting the number of steps k as a sum of powers of two. For example, if we want to calculate the value of succ(x, 11), we first form the representation 11 = 8 + 2 + 1. Using that" }, { "code": null, "e": 1782, "s": 1747, "text": "For example, in the previous graph" }, { "code": null, "e": 1898, "s": 1782, "text": "Such a representation always consists of O(log k) parts, so calculating a value of succ(x, k) takes O(log k) time. " }, { "code": null, "e": 1907, "s": 1898, "text": "Articles" }, { "code": null, "e": 1913, "s": 1907, "text": "Graph" }, { "code": null, "e": 1919, "s": 1913, "text": "Graph" } ]
How to Learn Java Collections – A Complete Guide
29 Nov, 2021 In the real world, a collection by definition is a group of articles that have similar properties and attributes. Since Java is an Object-Oriented Language it mimics the real world. In Java, a Collection is a group of multiple objects put together into a single unit. Java Collections is a very vast topic and as a beginner can be difficult to navigate your way while learning it. Here we have everything you need to know while starting off with Java Collections. We have our collection of objects, now we need an organized way to use these collections, therefore we need a framework. The Java Collection Framework, first introduced in JDK 1.2 ( Java Development Kit 1.2 ), is an architecture made up of interfaces and classes. In simple words, it is like a skeletal structure for components that is ready to use for various programming needs. It also offers different data operations like searching, sorting, insertion, deletion, and manipulation. All of the classes and interfaces of the collection framework are bundled into the java.util package. Class Interface Now that we have the basic concepts of what Java collections are made of we will understand each of its components in detail. What are their properties and a few examples of the most used collections? The Iterable interface is the root of the entire collection hierarchy, which means that every class and interface implements it. The primary function of an iterator is to allow the user to traverse through all of the collection class objects as if they were simple sequences of data items. The Collection interface extends the Iterable interface. It has the basic methods required for using all the other collections in the framework to add, delete, and manipulate data. Since it is an interface it only has a method signature ( i.e. <return type> methodName ( ArgumentList ); ) and no definition because every interface or class that implements this interface will have different types of elements to handle. But since they implement this interface there is uniformity and structure to the rest of the collection. The methods of the collection interface are given below, all the interfaces and classes that extend or implement the Collection interface use these methods along with their own added methods specific to them. The List interface extends from the Collection interface. The elements in a list are ordered like a sequence. The user can use the index number to access a particular element in the list, that is to say, the user has complete control over which element is inserted wherein the list. The ArrayList class implements the List interface. The objects of this class are dynamic arrays. The ArrayList is essentially a resizable implementation of List. It implements all of the List methods and allows all elements even null elements. The ArrayList objects have a capacity, which is initially equal to the size but increases dynamically as new elements are added. An ArrayList is unsynchronised, which means multiple threads can access them at the same time. A thread is a unit of sequential flow control that can be processed in the Operating System. Syntax: ArrayList<?> arrayListName = new ArrayList<?>(); Example: Now we will take an example and perform some basic operations on an ArrayList. Here we instantiate an ArrayList named intArr. We use the add() method to add integers to intArr. The Integer class used in declaring intArr is a wrapper class for that basic datatype int. Wrapper classes extend from the Object class and they are used so that basic datatypes are compatible with other classes. Next, we print the ArrayList on the console. We use the remove() method to remove elements from the specified indices. We check if an element, 25 here, exists in intArr and print the appropriate message. Then we retrieve the element at index 1 using the get() method. As you can observe when an element is removed using remove() method the rest of the elements shift in sequence. Java // An example for ArrayList// All of the classes and// interfaces of the collection// framework are bundled into// the java.util packageimport java.util.*; public class BasicArrayList { // main method public static void main(String[] args) { // Instantiate an ArrayList Object // Integer is a wrapper class for // the basic datatype int ArrayList<Integer> intArr = new ArrayList<Integer>(); // Add elements using add() method intArr.add(10); intArr.add(12); intArr.add(25); intArr.add(19); intArr.add(11); intArr.add(3); // Print the ArrayList on the console System.out.println(intArr); // Remove elements at index 1 and 4 intArr.remove(1); intArr.remove(4); // Print the ArrayList on the console System.out.println(intArr); // Check if intArr contains the element 25 if(intArr.contains(25)) { System.out.println("The ArrayList contains 25"); } else { System.out.println("No such element exists"); } // Use get method to get the element at index 1 int elementAt1 = intArr.get(1); System.out.println("The Element at index 1 now is " + elementAt1); } } [10, 12, 25, 19, 11, 3] [10, 25, 19, 11] The ArrayList contains 25 The Element at index 1 now is 25 The vector class implements the List iterator. A Vector instance is a dynamic array, wherein the elements can be accessed with indices. The difference between a Vector an ArrayList is that Vectors are synchronized. Syntax: Vector<?> vectorName = new Vector<?>(); Let us better understand Vector with an example, In the code given below we have declared a Vector named intVector, we use add() to add elements to the Vector. The size() method gives the current number of elements stored in the Vector. The remove() method is used to remove an element at the specified index. Java // An example for Vectorimport java.util.*; public class VectorExample { public static void main(String[] args) { // Instantiate Vector object Vector<Integer> intVector = new Vector<Integer>(); // Print the initial size of the Vector System.out.println("The initial size of the Vector = " + intVector.size()); System.out.println(); // Add elements using add method intVector.add(11); intVector.add(18); intVector.add(1); intVector.add(87); intVector.add(19); intVector.add(11); // Print the Vector on the console System.out.println("The Vector intVector : "); System.out.println(intVector); System.out.println("Size of intVector : " + intVector.size()); System.out.println(); // Remove the element at index 2 intVector.remove(2); // Print the vector again on the console System.out.println("The Vector intVector after removing element at 2 : "); System.out.println(intVector); System.out.println(); // Clear all elements of the Vector and // Print the Vector on the console intVector.clear(); System.out.println("The Vector intVector after using clear : "); System.out.println(intVector); } } The initial size of the Vector = 0 The Vector intVector : [11, 18, 1, 87, 19, 11] Size of intVector : 6 The Vector intVector after removing element at 2 : [11, 18, 87, 19, 11] The Vector intVector after using clear : [] The stack class extends from the Vector class. The Stack is a last-in-first-out ( LIFO ) structure. You can visualize it as a stack of books on a table the book that is kept first has to e retrieved last, and the book that is kept on the stack last has to be retrieved first. The basic methods of the stack class are push, pop, peek, empty, and search. Syntax: Stack<?> stackName = new Stack<?>(); Example: Let us understand Stack better with an example. In the code given below, we first instantiate a Stack named strStack, whose elements are of type String. The elements are added using the push() method. The size() method returns the number of elements present in the Stack. The search() method is used to search an element in the stack. It returns the 1-based position of the element if found else -1 is returned to indicate no such element exists in the Stack. Java // An example to show workings of a Stackimport java.util.*; public class StackExample { public static void main(String[] args) { // Instantiate a Stack named strStack Stack<String> strStack = new Stack<String>(); // Add elements using the push() method strStack.push("Stack"); strStack.push("a"); strStack.push("is"); strStack.push("This"); // The size() method gives the // number of elements in the Stack System.out.println("The size of the Stack is : " + strStack.size()); // The search() method is // used to search an element // it returns the position of // the element int position = strStack.search("a"); System.out.println("\nThe string 'a' is at position " + position); System.out.println("\nThe elements of the stack are : "); String temp; int num = strStack.size(); for(int i = 1; i <= num; i++) { // peek() returns the topmost element temp = strStack.peek(); System.out.print(temp + " "); // pop() removes the topmost element strStack.pop(); } } } The size of the Stack is : 4 The string 'a' is at position 3 The elements of the stack are : This is a Stack The LinkedList class implements the List interface as well as the Deque interface. The LinkedList is the class implementation of the linked list data structure, where every element has a pointer to the next element forming a link. Since each element has an address of the next element, the linked list elements, referred to as nodes, can be stored at non-contiguous locations in memory. Syntax: LinkedList<?> linkedListName = new LinkedList<?>(); Let us take an example to understand LinkedList. In the code given below, we instantiate a LinkedList named strLinkedList. The add() method is used to add elements and remove() method to remove elements. The retrieval of the elements is done using get() method. Java // An example for the LinkedListimport java.util.*; public class LinkedListExample { public static void main(String[] args) { // Instantiate LinkedList named strLinkedList LinkedList<String> strLinkedList = new LinkedList<String>(); // Add elements to the LinkedList using add() strLinkedList.add("This"); strLinkedList.add("is"); strLinkedList.add("a"); strLinkedList.add("LinkedList"); // The elements are retrieved using the get() method System.out.println("The contents of strLinkedList : "); for(int i = 0; i < strLinkedList.size(); i++) { System.out.print(strLinkedList.get(i) + " "); } // The elements are removed using remove() strLinkedList.remove(0); strLinkedList.remove(1); System.out.println("\n\nThe contents of strLinkedList after remove operation : "); for(int i = 0; i < strLinkedList.size(); i++) { System.out.print(strLinkedList.get(i) + " "); } } } The contents of strLinkedList : This is a LinkedList The contents of strLinkedList after remove operation : is LinkedList The Queue interface extends the Collection interface. Queue is the interface implementation of the queue data structure. Since Queue in java is an interface it doesn’t have a definition of the methods only their signatures. Queue is typically a first-in-first-out ( FIFO ) structure, though that is not the case for PriorityQueue. You may visualize it as a queue of people at a counter, the person who enters first gets services first and leaves first. The PriorityQueue class implements the Queue interface. The elements of a PriorityQueue are either ordered in natural order or in an order specified by a Comparator, which depends on the constructor used. The PriorityQueue is unbounded but there is a capacity that dictates the size of the array in which the elements are stored. The initial capacity is equal to the size of the array but as new elements are added it expands dynamically. Syntax: PriorityQueue<?> priorityQueueName = new PriorityQueue<?>(); Let us understand PriorityQueue better with an example. In the code given below we instantiate an object of PriorityQueue named intPriorityQueue, since no Comparator is specified in the constructor the elements of this PriorityQueue will be naturally ordered. The add() method is used to add elements and remove() is used to remove a single instance of the specified element. The peek() method is implemented from the Queue interface and it returns the element at the head of the PriorityQueue. The poll() method however removes the element at the head of the PriorityQueue and returns it. Java // An example for PriorityQueueimport java.util.*; public class PriorityQueueExample { public static void main(String[] args) { // Instantiate PriorityQueue object named intPriorityQueue PriorityQueue<Integer> intPriorityQueue = new PriorityQueue<Integer>(); // Add elements using add() intPriorityQueue.add(17); intPriorityQueue.add(20); intPriorityQueue.add(1); intPriorityQueue.add(13); intPriorityQueue.add(87); // Print the contents of PriorityQueue System.out.println("The contents of intPriorityQueue : "); System.out.println(intPriorityQueue); // The peek() method is used to retrieve // the head of the PriorityQueue System.out.println("\nThe head of the PriorityQueue : " + intPriorityQueue.peek()); // The remove() method is used // to remove a single instance // of the specified object intPriorityQueue.remove(17); // Print the contents of PriorityQueue System.out.println("\nThe contents of intPriorityQueue after removing 17 : "); System.out.println(intPriorityQueue); // The poll() method is used // to retrieve and remove the // element at the head of the PriorityQueue Integer head = intPriorityQueue.poll(); System.out.println("\nThe head of the PriorityQueue was : " + head); // Print the contents of PriorityQueue System.out.println("\nThe contents of intPriorityQueue after poll : "); System.out.println(intPriorityQueue); } } The contents of intPriorityQueue : [1, 13, 17, 20, 87] The head of the PriorityQueue : 1 The contents of intPriorityQueue after removing 17 : [1, 13, 87, 20] The head of the PriorityQueue was : 1 The contents of intPriorityQueue after poll : [13, 20, 87] The Deque interface extends the Queue interface. The Deque is an implementation of the double-ended queue data structure, which is a linear structure where insertion and deletion can be done at both ends of the queue. The Deque interface supports deques that have capacity restrictions, as well as that, have no fixed limit. Deque can be used as a last-in-first-out ( LIFO ) as well as a first-in-first-out ( FIFO ) structure. The ArrayDeque class implements the Deque interface. ArrayDeque is a re-sizable implementation of Deque, it has no fixed capacity but increases as required. The ArrayDeque can be used as a stack, and it is faster compared to the Stack class. ArrayDeque is not thread-safe and it does not allow concurrent access by different threads. Syntax: ArrayDeque<?> arrayDequeName = new ArrayDeque<?>(); The Set interface extends the Collection interface. The Set is a structure that models the mathematical definition of a set. It is a collection of objects and no duplicate objects are allowed. The Set allows at most one null element. The HashSet class implements the Set interface. In a HashSet, the order of the elements may not be the same as the order of insertion. When an element is added into the HashSet a HashCode is calculated and the element is added to the appropriate bucket ( a bucket is a slot in any Hash structure ). A good HashSet algorithm will uniformly distribute the elements so that the time performance of the structure remains constant. A constant-time performance means it takes constant time for basic operations like insert, deletes, and search. LinkedHashSet implements the Set interface. The LinkedHashSet is very similar to the HashSet with the difference being that for every bucket the structure uses to store elements is a doubly-linked list. The LinkedHashSet ordering is better compared to HashSet without any additional costs. Let us take an example to understand HashSet and LinkedHashSet. In the code given below, we instantiate a HashSet named strHashSet, using add() method add elements to the HashSet. The hasNext() method and next() method are methods of the Iterable interface that are used to check if there is the next element and to retrieve the next element respectively in any Collection. Using the constructor of the LinkedHashSet, all of the elements of the HashSet are added to it. An Iterator is created to traverse through it and using it the elements are printed on the console. Java // An example for HashSet and LinkedHashSetimport java.util.*; public class HashSetAndLinkedHashSet { public static void main(String[] args) { /*-----------HashSet-------------*/ // Instantiate a HashSet object named strHashSet HashSet<String> strHashSet = new HashSet<String>(); // Add elements using add() strHashSet.add("This"); strHashSet.add("is"); strHashSet.add("a"); strHashSet.add("HashSet"); // Create an Iterator to traverse through the HashSet Iterator<String> hsIterator = strHashSet.iterator(); // Print all the elements of the HashSet System.out.println("Contents of HashSet : "); while(hsIterator.hasNext()) { System.out.print(hsIterator.next() + " "); } /*---------LinkedHashSet----------*/ // Instantiate an object of LinkedHashSet named strLinkedHashSet // Pass the name of the HashSet created earlier to copy all of the contents // of the HashSet to the LinkedHashSet using a constructor LinkedHashSet<String> strLinkedHashSet = new LinkedHashSet<String>(strHashSet); // Create an Iterator to traverse through the LinkedHashSet Iterator<String> lhsIterator = strLinkedHashSet.iterator(); // Print all the elements of the LinkedHashSet System.out.println("\n\nContents of LinkedHashSet : "); while(lhsIterator.hasNext()) { System.out.print(lhsIterator.next() + " "); } } } Contents of HashSet : a This is HashSet Contents of LinkedHashSet : a This is HashSet The SortedSet interface extends the Set interface. The SortedSet provides a complete ordering of the elements. The default ordering is by Natural order else it is ordered by a Comparator specified at the time of construction. The traversing typically is in ascending order of elements. The NavigableSet interface extends from the SortedSet interface. In addition to the methods of the SortedSet, NavigableSet has navigation methods that give closest matches such as floor, ceiling, lower and higher. A NavigableSet can be traversed in ascending and descending order. Although it allows null element implementations it is discouraged as these implementations can give ambiguous results. The TreeSet class implements the Navigable interface. The TreeSet as the name suggests uses a tree structure to store elements and a set to order the elements. The ordering is either natural ordering or ordering by the Comparator specified at the time construction. The TreeSet is unsynchronized, which is if multiple threads want to access it at the same time we need to synchronize it externally. Syntax: TreeSet<?> treeSetName = new TreeSet<?>(); Let us take an example to understand TreeSet better. In the code given below, we instantiate an object named intTreeSet. As you can observe the order in this TreeSet is natural ordering and no duplicate elements are allowed. The add() method is used to add the elements and remove() method is used to delete elements. Java // An example for TreeSetimport java.util.*; public class TreeSetExample { public static void main(String[] args) { // Instantiate an object of TreeSet named intTreeSet TreeSet<Integer> intTreeSet = new TreeSet<Integer>(); // Add elements using add() intTreeSet.add(18); intTreeSet.add(13); intTreeSet.add(29); intTreeSet.add(56); intTreeSet.add(73); // Try to add a duplicate // Observe output as it will not be added intTreeSet.add(18); // Print the TreeSet on the console System.out.println("The contents of intTreeSet : "); System.out.println(intTreeSet); // Remove 18 using remove() if(intTreeSet.remove(18)) { System.out.println("\nElement 18 has been removed"); } else { System.out.println("\nNo such element exists"); } // Try to remove a non-existent element if(intTreeSet.remove(12)) { System.out.println("\nElement 18 has been removed"); } else { System.out.println("\nNo such element exists"); } System.out.println(); // Print the TreeSet on the console System.out.println("The contents of intTreeSet : "); System.out.println(intTreeSet); } } The contents of intTreeSet : [13, 18, 29, 56, 73] Element 18 has been removed No such element exists The contents of intTreeSet : [13, 29, 56, 73] The Map interface is a structure that maps a key to every value. A Map does not allow duplicate elements as one key cannot have multiple mappings. A Map has three different views, a Set view of the keys, a Set view of key-value mappings, and a Collection view of the values. The methods of the Map interface are given below, every class that implements Map must provide definitions for these methods. The HashMap class implements the Map interface. For every entry in a HashMap, a hashCode is computed and this entry is inserted into the bucket with the hashCode value as its index. Every entry is a key-value pair. A bucket in a HashMap may contain more than one entry. A good HashMap algorithm will try to uniformly distribute the elements in the HashMap. HashMap has constant time performance for basic retrieval, insertion, deletion, and manipulation operations. The two most important factors that affect the performance of a HashMap are initial capacity and load factor. The number of buckets is the capacity and the measure of when to increase this capacity is load factor. The HashMap is faster compared to a HashTable. Syntax: HashMap<? , ?> hashMapName = new HashMap<? , ?>(); The Hashtable class implements the Map interface. The Hashtable has key-value pairs as its elements. For effective implementation of the hashtable, the keys must be unique. A Hashtable is very similar to a Hashtable, but Hashtable is synchronous. A good Hashtable algorithm will try to uniformly distribute the elements in the Hashtable. Hashtable has constant time performance for basic retrieval, insertion, deletion, and manipulation operations. The two most important factors that affect the performance of a Hashtable are initial capacity and load factor. The number of buckets is the capacity and the measure of when to increase this capacity is load factor. Syntax: HashTable<? , ?> hashTableName = new HashTable<? , ?>(); The LinkedHashMap class implements the Map interface. A LinkedHashMap is a hash map linked list implementation of a map. Every entry in the LinkedHashMap has a doubly-linked list running through it. This linked list defines the iteration order that is the order of the keys inserted into the LinkedHashMap. Like all implementations of Map, the elements of the LinkedHashMap are key-value pairs. Syntax: LinkedHashMap<? , ?> linkedHashMapName = new LinkedHashMap<? , ?>(); Let us take an example to understand all of the Map implementations. In the code given below, we add elements using put() method to all of the HashMap, Hashtable, and LinkedHashMap. As put() is a method of the Map interface, therefore, is implemented by all three of these classes. As you can observe the insertion order of Hashtable is not the same as the internal ordering, therefore it is nondeterministic. When we try to insert a duplicate key the old value is replaced in all three. And When we try to insert a duplicate value with a different key it is added as a new entry. Basically this is to depict that we can have duplicate values but not duplicate keys. Java // An example for HashMap,// Hashtable and LinkedHashMapimport java.util.*; public class MapImplementaionExample { public static void main(String[] args) { /*--------------HashMap---------------*/ // Instantiate an object of HashMap named hashMap HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); // Add elements using put() hashMap.put(1, "This"); hashMap.put(2, "is"); hashMap.put(3, "HashMap"); // Print the HashMap contents on the console System.out.println("Contents of hashMap : "); System.out.print(hashMap.entrySet()); // Add a duplicate key hashMap.put(3, "Duplicate"); // Add a duplicate value hashMap.put(4, "This"); // Print the HashMap contents on the console System.out.println("\nContents of hashMap after adding duplicate : "); System.out.print(hashMap.entrySet()); /*--------------Hashtable----------------*/ // Instantiate an object of Hashtable named hashTable Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>(); // Add elements using put() hashTable.put(11, "This"); hashTable.put(12, "is"); hashTable.put(13, "Hashtable"); // Print the Hashtable contents on the console System.out.println("\n\nContents of hashTable : "); System.out.print(hashTable.entrySet()); // Add a duplicate key hashTable.put(11, "Duplicate"); // Add a duplicate value hashTable.put(14, "is"); // Print the Hashtable contents on the console System.out.println("\nContents of hashTable after adding duplicate : "); System.out.print(hashTable.entrySet()); /*---------------LinkedHashMap---------------*/ // Instantiate an object of LinkedHashMap named linkedHashMape LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>(); // Add elements using put() linkedHashMap.put(21, "This"); linkedHashMap.put(22, "is"); linkedHashMap.put(23, "LinkedHashMap"); // Print the LinkedHashMap contents on the console System.out.println("\n\nContents of linkedHashMap : "); System.out.print(linkedHashMap.entrySet()); // Add a duplicate key linkedHashMap.put(22, "Duplicate"); // Add a duplicate value linkedHashMap.put(24, "This"); // Print the LinkedHashMap contents on the console System.out.println("\nContents of linkedHashMap after adding duplicate : "); System.out.print(linkedHashMap.entrySet()); } } Contents of hashMap : [1=This, 2=is, 3=HashMap] Contents of hashMap after adding duplicate : [1=This, 2=is, 3=Duplicate, 4=This] Contents of hashTable : [13=Hashtable, 12=is, 11=This] Contents of hashTable after adding duplicate : [14=is, 13=Hashtable, 12=is, 11=Duplicate] Contents of linkedHashMap : [21=This, 22=is, 23=LinkedHashMap] Contents of linkedHashMap after adding duplicate : [21=This, 22=Duplicate, 23=LinkedHashMap, 24=This] The SortedMap interface extends the Map interface with an added stipulation of a total order of keys. The keys are either ordered by natural ordering or by a Comparator specified at the time of construction, depending on the constructor used. All of the keys must be comparable. The TreeMap class implements the SortedMap interface. The TreeMap class uses a red-black tree structure for storage and a map for ordering the elements. Every element is a key-value pair. This implementation gives a guaranteed log(n) time cost for basic operations. Syntax: TreeMap<? , ?> treeMapName = new TreeMap<? , ?>(); Let us take an example to understand the basics of TreeMap. In the code given below, we instantiate an object of the TreeMap object named treeMap. Add elements using put() method. When we try to add a duplicate key with a different value the older instance is replaced with the new value associated with this key. But when we try to add a duplicate value with a new key it is taken as a different entry. Java // An example of TreeMapimport java.util.*; public class TreeMapExample { public static void main(String[] args) { // Instantiate an object of TreeMap named treeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Add elements using put() treeMap.put(1, "This"); treeMap.put(2, "is"); treeMap.put(3, "TreeMap"); // Print the contents of treeMap on the console System.out.println("The contents of treeMap : "); System.out.println(treeMap); // Add a duplicate key treeMap.put(1, "Duplicate"); // Add a duplicate value treeMap.put(4, "is"); // Print the contents of treeMap on the console System.out.println("\nThe contents of treeMap after adding duplicates : "); System.out.println(treeMap); } } The contents of treeMap : {1=This, 2=is, 3=TreeMap} The contents of treeMap after adding duplicates : {1=Duplicate, 2=is, 3=TreeMap, 4=is} GeeksforGeeks has also prepared a course Fundamentals of Java and Java Collections to teach you the Java concepts in depth. This course will help you to use Collections Framework’s inbuilt classes and functions in order to implement some of the complex data structures easily & efficiently and perform operations on them. Check out this course: prachisoda1234 GFG-Update Java-Collections GBlog Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Learn Data Science in 10 weeks? DSA Sheet by Love Babbar Top Programming Languages For Competitive Programming A Freshers Guide To Programming Writing a Windows batch script Arrays in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Queue Interface In Java
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Nov, 2021" }, { "code": null, "e": 518, "s": 54, "text": "In the real world, a collection by definition is a group of articles that have similar properties and attributes. Since Java is an Object-Oriented Language it mimics the real world. In Java, a Collection is a group of multiple objects put together into a single unit. Java Collections is a very vast topic and as a beginner can be difficult to navigate your way while learning it. Here we have everything you need to know while starting off with Java Collections." }, { "code": null, "e": 1105, "s": 518, "text": "We have our collection of objects, now we need an organized way to use these collections, therefore we need a framework. The Java Collection Framework, first introduced in JDK 1.2 ( Java Development Kit 1.2 ), is an architecture made up of interfaces and classes. In simple words, it is like a skeletal structure for components that is ready to use for various programming needs. It also offers different data operations like searching, sorting, insertion, deletion, and manipulation. All of the classes and interfaces of the collection framework are bundled into the java.util package." }, { "code": null, "e": 1111, "s": 1105, "text": "Class" }, { "code": null, "e": 1121, "s": 1111, "text": "Interface" }, { "code": null, "e": 1322, "s": 1121, "text": "Now that we have the basic concepts of what Java collections are made of we will understand each of its components in detail. What are their properties and a few examples of the most used collections?" }, { "code": null, "e": 1612, "s": 1322, "text": "The Iterable interface is the root of the entire collection hierarchy, which means that every class and interface implements it. The primary function of an iterator is to allow the user to traverse through all of the collection class objects as if they were simple sequences of data items." }, { "code": null, "e": 2346, "s": 1612, "text": "The Collection interface extends the Iterable interface. It has the basic methods required for using all the other collections in the framework to add, delete, and manipulate data. Since it is an interface it only has a method signature ( i.e. <return type> methodName ( ArgumentList ); ) and no definition because every interface or class that implements this interface will have different types of elements to handle. But since they implement this interface there is uniformity and structure to the rest of the collection. The methods of the collection interface are given below, all the interfaces and classes that extend or implement the Collection interface use these methods along with their own added methods specific to them." }, { "code": null, "e": 2629, "s": 2346, "text": "The List interface extends from the Collection interface. The elements in a list are ordered like a sequence. The user can use the index number to access a particular element in the list, that is to say, the user has complete control over which element is inserted wherein the list." }, { "code": null, "e": 3190, "s": 2629, "text": "The ArrayList class implements the List interface. The objects of this class are dynamic arrays. The ArrayList is essentially a resizable implementation of List. It implements all of the List methods and allows all elements even null elements. The ArrayList objects have a capacity, which is initially equal to the size but increases dynamically as new elements are added. An ArrayList is unsynchronised, which means multiple threads can access them at the same time. A thread is a unit of sequential flow control that can be processed in the Operating System." }, { "code": null, "e": 3198, "s": 3190, "text": "Syntax:" }, { "code": null, "e": 3247, "s": 3198, "text": "ArrayList<?> arrayListName = new ArrayList<?>();" }, { "code": null, "e": 4026, "s": 3247, "text": "Example: Now we will take an example and perform some basic operations on an ArrayList. Here we instantiate an ArrayList named intArr. We use the add() method to add integers to intArr. The Integer class used in declaring intArr is a wrapper class for that basic datatype int. Wrapper classes extend from the Object class and they are used so that basic datatypes are compatible with other classes. Next, we print the ArrayList on the console. We use the remove() method to remove elements from the specified indices. We check if an element, 25 here, exists in intArr and print the appropriate message. Then we retrieve the element at index 1 using the get() method. As you can observe when an element is removed using remove() method the rest of the elements shift in sequence." }, { "code": null, "e": 4031, "s": 4026, "text": "Java" }, { "code": "// An example for ArrayList// All of the classes and// interfaces of the collection// framework are bundled into// the java.util packageimport java.util.*; public class BasicArrayList { // main method public static void main(String[] args) { // Instantiate an ArrayList Object // Integer is a wrapper class for // the basic datatype int ArrayList<Integer> intArr = new ArrayList<Integer>(); // Add elements using add() method intArr.add(10); intArr.add(12); intArr.add(25); intArr.add(19); intArr.add(11); intArr.add(3); // Print the ArrayList on the console System.out.println(intArr); // Remove elements at index 1 and 4 intArr.remove(1); intArr.remove(4); // Print the ArrayList on the console System.out.println(intArr); // Check if intArr contains the element 25 if(intArr.contains(25)) { System.out.println(\"The ArrayList contains 25\"); } else { System.out.println(\"No such element exists\"); } // Use get method to get the element at index 1 int elementAt1 = intArr.get(1); System.out.println(\"The Element at index 1 now is \" + elementAt1); } }", "e": 5382, "s": 4031, "text": null }, { "code": null, "e": 5482, "s": 5382, "text": "[10, 12, 25, 19, 11, 3]\n[10, 25, 19, 11]\nThe ArrayList contains 25\nThe Element at index 1 now is 25" }, { "code": null, "e": 5697, "s": 5482, "text": "The vector class implements the List iterator. A Vector instance is a dynamic array, wherein the elements can be accessed with indices. The difference between a Vector an ArrayList is that Vectors are synchronized." }, { "code": null, "e": 5705, "s": 5697, "text": "Syntax:" }, { "code": null, "e": 5745, "s": 5705, "text": "Vector<?> vectorName = new Vector<?>();" }, { "code": null, "e": 6055, "s": 5745, "text": "Let us better understand Vector with an example, In the code given below we have declared a Vector named intVector, we use add() to add elements to the Vector. The size() method gives the current number of elements stored in the Vector. The remove() method is used to remove an element at the specified index." }, { "code": null, "e": 6060, "s": 6055, "text": "Java" }, { "code": "// An example for Vectorimport java.util.*; public class VectorExample { public static void main(String[] args) { // Instantiate Vector object Vector<Integer> intVector = new Vector<Integer>(); // Print the initial size of the Vector System.out.println(\"The initial size of the Vector = \" + intVector.size()); System.out.println(); // Add elements using add method intVector.add(11); intVector.add(18); intVector.add(1); intVector.add(87); intVector.add(19); intVector.add(11); // Print the Vector on the console System.out.println(\"The Vector intVector : \"); System.out.println(intVector); System.out.println(\"Size of intVector : \" + intVector.size()); System.out.println(); // Remove the element at index 2 intVector.remove(2); // Print the vector again on the console System.out.println(\"The Vector intVector after removing element at 2 : \"); System.out.println(intVector); System.out.println(); // Clear all elements of the Vector and // Print the Vector on the console intVector.clear(); System.out.println(\"The Vector intVector after using clear : \"); System.out.println(intVector); } }", "e": 7438, "s": 6060, "text": null }, { "code": null, "e": 7664, "s": 7438, "text": "The initial size of the Vector = 0\n\nThe Vector intVector : \n[11, 18, 1, 87, 19, 11]\nSize of intVector : 6\n\nThe Vector intVector after removing element at 2 : \n[11, 18, 87, 19, 11]\n\nThe Vector intVector after using clear : \n[]" }, { "code": null, "e": 8017, "s": 7664, "text": "The stack class extends from the Vector class. The Stack is a last-in-first-out ( LIFO ) structure. You can visualize it as a stack of books on a table the book that is kept first has to e retrieved last, and the book that is kept on the stack last has to be retrieved first. The basic methods of the stack class are push, pop, peek, empty, and search." }, { "code": null, "e": 8025, "s": 8017, "text": "Syntax:" }, { "code": null, "e": 8062, "s": 8025, "text": "Stack<?> stackName = new Stack<?>();" }, { "code": null, "e": 8531, "s": 8062, "text": "Example: Let us understand Stack better with an example. In the code given below, we first instantiate a Stack named strStack, whose elements are of type String. The elements are added using the push() method. The size() method returns the number of elements present in the Stack. The search() method is used to search an element in the stack. It returns the 1-based position of the element if found else -1 is returned to indicate no such element exists in the Stack." }, { "code": null, "e": 8536, "s": 8531, "text": "Java" }, { "code": "// An example to show workings of a Stackimport java.util.*; public class StackExample { public static void main(String[] args) { // Instantiate a Stack named strStack Stack<String> strStack = new Stack<String>(); // Add elements using the push() method strStack.push(\"Stack\"); strStack.push(\"a\"); strStack.push(\"is\"); strStack.push(\"This\"); // The size() method gives the // number of elements in the Stack System.out.println(\"The size of the Stack is : \" + strStack.size()); // The search() method is // used to search an element // it returns the position of // the element int position = strStack.search(\"a\"); System.out.println(\"\\nThe string 'a' is at position \" + position); System.out.println(\"\\nThe elements of the stack are : \"); String temp; int num = strStack.size(); for(int i = 1; i <= num; i++) { // peek() returns the topmost element temp = strStack.peek(); System.out.print(temp + \" \"); // pop() removes the topmost element strStack.pop(); } } }", "e": 9791, "s": 8536, "text": null }, { "code": null, "e": 9904, "s": 9791, "text": "The size of the Stack is : 4\n\nThe string 'a' is at position 3\n\nThe elements of the stack are : \nThis is a Stack " }, { "code": null, "e": 10291, "s": 9904, "text": "The LinkedList class implements the List interface as well as the Deque interface. The LinkedList is the class implementation of the linked list data structure, where every element has a pointer to the next element forming a link. Since each element has an address of the next element, the linked list elements, referred to as nodes, can be stored at non-contiguous locations in memory." }, { "code": null, "e": 10299, "s": 10291, "text": "Syntax:" }, { "code": null, "e": 10351, "s": 10299, "text": "LinkedList<?> linkedListName = new LinkedList<?>();" }, { "code": null, "e": 10613, "s": 10351, "text": "Let us take an example to understand LinkedList. In the code given below, we instantiate a LinkedList named strLinkedList. The add() method is used to add elements and remove() method to remove elements. The retrieval of the elements is done using get() method." }, { "code": null, "e": 10618, "s": 10613, "text": "Java" }, { "code": "// An example for the LinkedListimport java.util.*; public class LinkedListExample { public static void main(String[] args) { // Instantiate LinkedList named strLinkedList LinkedList<String> strLinkedList = new LinkedList<String>(); // Add elements to the LinkedList using add() strLinkedList.add(\"This\"); strLinkedList.add(\"is\"); strLinkedList.add(\"a\"); strLinkedList.add(\"LinkedList\"); // The elements are retrieved using the get() method System.out.println(\"The contents of strLinkedList : \"); for(int i = 0; i < strLinkedList.size(); i++) { System.out.print(strLinkedList.get(i) + \" \"); } // The elements are removed using remove() strLinkedList.remove(0); strLinkedList.remove(1); System.out.println(\"\\n\\nThe contents of strLinkedList after remove operation : \"); for(int i = 0; i < strLinkedList.size(); i++) { System.out.print(strLinkedList.get(i) + \" \"); } } }", "e": 11707, "s": 10618, "text": null }, { "code": null, "e": 11834, "s": 11707, "text": "The contents of strLinkedList : \nThis is a LinkedList \n\nThe contents of strLinkedList after remove operation : \nis LinkedList " }, { "code": null, "e": 12287, "s": 11834, "text": "The Queue interface extends the Collection interface. Queue is the interface implementation of the queue data structure. Since Queue in java is an interface it doesn’t have a definition of the methods only their signatures. Queue is typically a first-in-first-out ( FIFO ) structure, though that is not the case for PriorityQueue. You may visualize it as a queue of people at a counter, the person who enters first gets services first and leaves first." }, { "code": null, "e": 12726, "s": 12287, "text": "The PriorityQueue class implements the Queue interface. The elements of a PriorityQueue are either ordered in natural order or in an order specified by a Comparator, which depends on the constructor used. The PriorityQueue is unbounded but there is a capacity that dictates the size of the array in which the elements are stored. The initial capacity is equal to the size of the array but as new elements are added it expands dynamically." }, { "code": null, "e": 12734, "s": 12726, "text": "Syntax:" }, { "code": null, "e": 12795, "s": 12734, "text": "PriorityQueue<?> priorityQueueName = new PriorityQueue<?>();" }, { "code": null, "e": 13385, "s": 12795, "text": "Let us understand PriorityQueue better with an example. In the code given below we instantiate an object of PriorityQueue named intPriorityQueue, since no Comparator is specified in the constructor the elements of this PriorityQueue will be naturally ordered. The add() method is used to add elements and remove() is used to remove a single instance of the specified element. The peek() method is implemented from the Queue interface and it returns the element at the head of the PriorityQueue. The poll() method however removes the element at the head of the PriorityQueue and returns it." }, { "code": null, "e": 13390, "s": 13385, "text": "Java" }, { "code": "// An example for PriorityQueueimport java.util.*; public class PriorityQueueExample { public static void main(String[] args) { // Instantiate PriorityQueue object named intPriorityQueue PriorityQueue<Integer> intPriorityQueue = new PriorityQueue<Integer>(); // Add elements using add() intPriorityQueue.add(17); intPriorityQueue.add(20); intPriorityQueue.add(1); intPriorityQueue.add(13); intPriorityQueue.add(87); // Print the contents of PriorityQueue System.out.println(\"The contents of intPriorityQueue : \"); System.out.println(intPriorityQueue); // The peek() method is used to retrieve // the head of the PriorityQueue System.out.println(\"\\nThe head of the PriorityQueue : \" + intPriorityQueue.peek()); // The remove() method is used // to remove a single instance // of the specified object intPriorityQueue.remove(17); // Print the contents of PriorityQueue System.out.println(\"\\nThe contents of intPriorityQueue after removing 17 : \"); System.out.println(intPriorityQueue); // The poll() method is used // to retrieve and remove the // element at the head of the PriorityQueue Integer head = intPriorityQueue.poll(); System.out.println(\"\\nThe head of the PriorityQueue was : \" + head); // Print the contents of PriorityQueue System.out.println(\"\\nThe contents of intPriorityQueue after poll : \"); System.out.println(intPriorityQueue); } }", "e": 15019, "s": 13390, "text": null }, { "code": null, "e": 15281, "s": 15019, "text": "The contents of intPriorityQueue : \n[1, 13, 17, 20, 87]\n\nThe head of the PriorityQueue : 1\n\nThe contents of intPriorityQueue after removing 17 : \n[1, 13, 87, 20]\n\nThe head of the PriorityQueue was : 1\n\nThe contents of intPriorityQueue after poll : \n[13, 20, 87]" }, { "code": null, "e": 15708, "s": 15281, "text": "The Deque interface extends the Queue interface. The Deque is an implementation of the double-ended queue data structure, which is a linear structure where insertion and deletion can be done at both ends of the queue. The Deque interface supports deques that have capacity restrictions, as well as that, have no fixed limit. Deque can be used as a last-in-first-out ( LIFO ) as well as a first-in-first-out ( FIFO ) structure." }, { "code": null, "e": 16042, "s": 15708, "text": "The ArrayDeque class implements the Deque interface. ArrayDeque is a re-sizable implementation of Deque, it has no fixed capacity but increases as required. The ArrayDeque can be used as a stack, and it is faster compared to the Stack class. ArrayDeque is not thread-safe and it does not allow concurrent access by different threads." }, { "code": null, "e": 16050, "s": 16042, "text": "Syntax:" }, { "code": null, "e": 16102, "s": 16050, "text": "ArrayDeque<?> arrayDequeName = new ArrayDeque<?>();" }, { "code": null, "e": 16337, "s": 16102, "text": "The Set interface extends the Collection interface. The Set is a structure that models the mathematical definition of a set. It is a collection of objects and no duplicate objects are allowed. The Set allows at most one null element. " }, { "code": null, "e": 16876, "s": 16337, "text": "The HashSet class implements the Set interface. In a HashSet, the order of the elements may not be the same as the order of insertion. When an element is added into the HashSet a HashCode is calculated and the element is added to the appropriate bucket ( a bucket is a slot in any Hash structure ). A good HashSet algorithm will uniformly distribute the elements so that the time performance of the structure remains constant. A constant-time performance means it takes constant time for basic operations like insert, deletes, and search." }, { "code": null, "e": 17166, "s": 16876, "text": "LinkedHashSet implements the Set interface. The LinkedHashSet is very similar to the HashSet with the difference being that for every bucket the structure uses to store elements is a doubly-linked list. The LinkedHashSet ordering is better compared to HashSet without any additional costs." }, { "code": null, "e": 17736, "s": 17166, "text": "Let us take an example to understand HashSet and LinkedHashSet. In the code given below, we instantiate a HashSet named strHashSet, using add() method add elements to the HashSet. The hasNext() method and next() method are methods of the Iterable interface that are used to check if there is the next element and to retrieve the next element respectively in any Collection. Using the constructor of the LinkedHashSet, all of the elements of the HashSet are added to it. An Iterator is created to traverse through it and using it the elements are printed on the console." }, { "code": null, "e": 17741, "s": 17736, "text": "Java" }, { "code": "// An example for HashSet and LinkedHashSetimport java.util.*; public class HashSetAndLinkedHashSet { public static void main(String[] args) { /*-----------HashSet-------------*/ // Instantiate a HashSet object named strHashSet HashSet<String> strHashSet = new HashSet<String>(); // Add elements using add() strHashSet.add(\"This\"); strHashSet.add(\"is\"); strHashSet.add(\"a\"); strHashSet.add(\"HashSet\"); // Create an Iterator to traverse through the HashSet Iterator<String> hsIterator = strHashSet.iterator(); // Print all the elements of the HashSet System.out.println(\"Contents of HashSet : \"); while(hsIterator.hasNext()) { System.out.print(hsIterator.next() + \" \"); } /*---------LinkedHashSet----------*/ // Instantiate an object of LinkedHashSet named strLinkedHashSet // Pass the name of the HashSet created earlier to copy all of the contents // of the HashSet to the LinkedHashSet using a constructor LinkedHashSet<String> strLinkedHashSet = new LinkedHashSet<String>(strHashSet); // Create an Iterator to traverse through the LinkedHashSet Iterator<String> lhsIterator = strLinkedHashSet.iterator(); // Print all the elements of the LinkedHashSet System.out.println(\"\\n\\nContents of LinkedHashSet : \"); while(lhsIterator.hasNext()) { System.out.print(lhsIterator.next() + \" \"); } } }", "e": 19333, "s": 17741, "text": null }, { "code": null, "e": 19424, "s": 19333, "text": "Contents of HashSet : \na This is HashSet \n\nContents of LinkedHashSet : \na This is HashSet " }, { "code": null, "e": 19710, "s": 19424, "text": "The SortedSet interface extends the Set interface. The SortedSet provides a complete ordering of the elements. The default ordering is by Natural order else it is ordered by a Comparator specified at the time of construction. The traversing typically is in ascending order of elements." }, { "code": null, "e": 20110, "s": 19710, "text": "The NavigableSet interface extends from the SortedSet interface. In addition to the methods of the SortedSet, NavigableSet has navigation methods that give closest matches such as floor, ceiling, lower and higher. A NavigableSet can be traversed in ascending and descending order. Although it allows null element implementations it is discouraged as these implementations can give ambiguous results." }, { "code": null, "e": 20509, "s": 20110, "text": "The TreeSet class implements the Navigable interface. The TreeSet as the name suggests uses a tree structure to store elements and a set to order the elements. The ordering is either natural ordering or ordering by the Comparator specified at the time construction. The TreeSet is unsynchronized, which is if multiple threads want to access it at the same time we need to synchronize it externally." }, { "code": null, "e": 20517, "s": 20509, "text": "Syntax:" }, { "code": null, "e": 20560, "s": 20517, "text": "TreeSet<?> treeSetName = new TreeSet<?>();" }, { "code": null, "e": 20878, "s": 20560, "text": "Let us take an example to understand TreeSet better. In the code given below, we instantiate an object named intTreeSet. As you can observe the order in this TreeSet is natural ordering and no duplicate elements are allowed. The add() method is used to add the elements and remove() method is used to delete elements." }, { "code": null, "e": 20883, "s": 20878, "text": "Java" }, { "code": "// An example for TreeSetimport java.util.*; public class TreeSetExample { public static void main(String[] args) { // Instantiate an object of TreeSet named intTreeSet TreeSet<Integer> intTreeSet = new TreeSet<Integer>(); // Add elements using add() intTreeSet.add(18); intTreeSet.add(13); intTreeSet.add(29); intTreeSet.add(56); intTreeSet.add(73); // Try to add a duplicate // Observe output as it will not be added intTreeSet.add(18); // Print the TreeSet on the console System.out.println(\"The contents of intTreeSet : \"); System.out.println(intTreeSet); // Remove 18 using remove() if(intTreeSet.remove(18)) { System.out.println(\"\\nElement 18 has been removed\"); } else { System.out.println(\"\\nNo such element exists\"); } // Try to remove a non-existent element if(intTreeSet.remove(12)) { System.out.println(\"\\nElement 18 has been removed\"); } else { System.out.println(\"\\nNo such element exists\"); } System.out.println(); // Print the TreeSet on the console System.out.println(\"The contents of intTreeSet : \"); System.out.println(intTreeSet); } }", "e": 22278, "s": 20883, "text": null }, { "code": null, "e": 22430, "s": 22278, "text": "The contents of intTreeSet : \n[13, 18, 29, 56, 73]\n\nElement 18 has been removed\n\nNo such element exists\n\nThe contents of intTreeSet : \n[13, 29, 56, 73]" }, { "code": null, "e": 22831, "s": 22430, "text": "The Map interface is a structure that maps a key to every value. A Map does not allow duplicate elements as one key cannot have multiple mappings. A Map has three different views, a Set view of the keys, a Set view of key-value mappings, and a Collection view of the values. The methods of the Map interface are given below, every class that implements Map must provide definitions for these methods." }, { "code": null, "e": 23558, "s": 22831, "text": "The HashMap class implements the Map interface. For every entry in a HashMap, a hashCode is computed and this entry is inserted into the bucket with the hashCode value as its index. Every entry is a key-value pair. A bucket in a HashMap may contain more than one entry. A good HashMap algorithm will try to uniformly distribute the elements in the HashMap. HashMap has constant time performance for basic retrieval, insertion, deletion, and manipulation operations. The two most important factors that affect the performance of a HashMap are initial capacity and load factor. The number of buckets is the capacity and the measure of when to increase this capacity is load factor. The HashMap is faster compared to a HashTable." }, { "code": null, "e": 23566, "s": 23558, "text": "Syntax:" }, { "code": null, "e": 23617, "s": 23566, "text": "HashMap<? , ?> hashMapName = new HashMap<? , ?>();" }, { "code": null, "e": 24282, "s": 23617, "text": "The Hashtable class implements the Map interface. The Hashtable has key-value pairs as its elements. For effective implementation of the hashtable, the keys must be unique. A Hashtable is very similar to a Hashtable, but Hashtable is synchronous. A good Hashtable algorithm will try to uniformly distribute the elements in the Hashtable. Hashtable has constant time performance for basic retrieval, insertion, deletion, and manipulation operations. The two most important factors that affect the performance of a Hashtable are initial capacity and load factor. The number of buckets is the capacity and the measure of when to increase this capacity is load factor." }, { "code": null, "e": 24290, "s": 24282, "text": "Syntax:" }, { "code": null, "e": 24347, "s": 24290, "text": "HashTable<? , ?> hashTableName = new HashTable<? , ?>();" }, { "code": null, "e": 24742, "s": 24347, "text": "The LinkedHashMap class implements the Map interface. A LinkedHashMap is a hash map linked list implementation of a map. Every entry in the LinkedHashMap has a doubly-linked list running through it. This linked list defines the iteration order that is the order of the keys inserted into the LinkedHashMap. Like all implementations of Map, the elements of the LinkedHashMap are key-value pairs." }, { "code": null, "e": 24750, "s": 24742, "text": "Syntax:" }, { "code": null, "e": 24819, "s": 24750, "text": "LinkedHashMap<? , ?> linkedHashMapName = new LinkedHashMap<? , ?>();" }, { "code": null, "e": 25486, "s": 24819, "text": "Let us take an example to understand all of the Map implementations. In the code given below, we add elements using put() method to all of the HashMap, Hashtable, and LinkedHashMap. As put() is a method of the Map interface, therefore, is implemented by all three of these classes. As you can observe the insertion order of Hashtable is not the same as the internal ordering, therefore it is nondeterministic. When we try to insert a duplicate key the old value is replaced in all three. And When we try to insert a duplicate value with a different key it is added as a new entry. Basically this is to depict that we can have duplicate values but not duplicate keys." }, { "code": null, "e": 25491, "s": 25486, "text": "Java" }, { "code": "// An example for HashMap,// Hashtable and LinkedHashMapimport java.util.*; public class MapImplementaionExample { public static void main(String[] args) { /*--------------HashMap---------------*/ // Instantiate an object of HashMap named hashMap HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); // Add elements using put() hashMap.put(1, \"This\"); hashMap.put(2, \"is\"); hashMap.put(3, \"HashMap\"); // Print the HashMap contents on the console System.out.println(\"Contents of hashMap : \"); System.out.print(hashMap.entrySet()); // Add a duplicate key hashMap.put(3, \"Duplicate\"); // Add a duplicate value hashMap.put(4, \"This\"); // Print the HashMap contents on the console System.out.println(\"\\nContents of hashMap after adding duplicate : \"); System.out.print(hashMap.entrySet()); /*--------------Hashtable----------------*/ // Instantiate an object of Hashtable named hashTable Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>(); // Add elements using put() hashTable.put(11, \"This\"); hashTable.put(12, \"is\"); hashTable.put(13, \"Hashtable\"); // Print the Hashtable contents on the console System.out.println(\"\\n\\nContents of hashTable : \"); System.out.print(hashTable.entrySet()); // Add a duplicate key hashTable.put(11, \"Duplicate\"); // Add a duplicate value hashTable.put(14, \"is\"); // Print the Hashtable contents on the console System.out.println(\"\\nContents of hashTable after adding duplicate : \"); System.out.print(hashTable.entrySet()); /*---------------LinkedHashMap---------------*/ // Instantiate an object of LinkedHashMap named linkedHashMape LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>(); // Add elements using put() linkedHashMap.put(21, \"This\"); linkedHashMap.put(22, \"is\"); linkedHashMap.put(23, \"LinkedHashMap\"); // Print the LinkedHashMap contents on the console System.out.println(\"\\n\\nContents of linkedHashMap : \"); System.out.print(linkedHashMap.entrySet()); // Add a duplicate key linkedHashMap.put(22, \"Duplicate\"); // Add a duplicate value linkedHashMap.put(24, \"This\"); // Print the LinkedHashMap contents on the console System.out.println(\"\\nContents of linkedHashMap after adding duplicate : \"); System.out.print(linkedHashMap.entrySet()); } }", "e": 28288, "s": 25491, "text": null }, { "code": null, "e": 28735, "s": 28288, "text": "Contents of hashMap : \n[1=This, 2=is, 3=HashMap]\nContents of hashMap after adding duplicate : \n[1=This, 2=is, 3=Duplicate, 4=This]\n\nContents of hashTable : \n[13=Hashtable, 12=is, 11=This]\nContents of hashTable after adding duplicate : \n[14=is, 13=Hashtable, 12=is, 11=Duplicate]\n\nContents of linkedHashMap : \n[21=This, 22=is, 23=LinkedHashMap]\nContents of linkedHashMap after adding duplicate : \n[21=This, 22=Duplicate, 23=LinkedHashMap, 24=This]" }, { "code": null, "e": 29015, "s": 28735, "text": "The SortedMap interface extends the Map interface with an added stipulation of a total order of keys. The keys are either ordered by natural ordering or by a Comparator specified at the time of construction, depending on the constructor used. All of the keys must be comparable. " }, { "code": null, "e": 29281, "s": 29015, "text": "The TreeMap class implements the SortedMap interface. The TreeMap class uses a red-black tree structure for storage and a map for ordering the elements. Every element is a key-value pair. This implementation gives a guaranteed log(n) time cost for basic operations." }, { "code": null, "e": 29289, "s": 29281, "text": "Syntax:" }, { "code": null, "e": 29340, "s": 29289, "text": "TreeMap<? , ?> treeMapName = new TreeMap<? , ?>();" }, { "code": null, "e": 29744, "s": 29340, "text": "Let us take an example to understand the basics of TreeMap. In the code given below, we instantiate an object of the TreeMap object named treeMap. Add elements using put() method. When we try to add a duplicate key with a different value the older instance is replaced with the new value associated with this key. But when we try to add a duplicate value with a new key it is taken as a different entry." }, { "code": null, "e": 29749, "s": 29744, "text": "Java" }, { "code": "// An example of TreeMapimport java.util.*; public class TreeMapExample { public static void main(String[] args) { // Instantiate an object of TreeMap named treeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Add elements using put() treeMap.put(1, \"This\"); treeMap.put(2, \"is\"); treeMap.put(3, \"TreeMap\"); // Print the contents of treeMap on the console System.out.println(\"The contents of treeMap : \"); System.out.println(treeMap); // Add a duplicate key treeMap.put(1, \"Duplicate\"); // Add a duplicate value treeMap.put(4, \"is\"); // Print the contents of treeMap on the console System.out.println(\"\\nThe contents of treeMap after adding duplicates : \"); System.out.println(treeMap); } }", "e": 30647, "s": 29749, "text": null }, { "code": null, "e": 30789, "s": 30647, "text": "The contents of treeMap : \n{1=This, 2=is, 3=TreeMap}\n\nThe contents of treeMap after adding duplicates : \n{1=Duplicate, 2=is, 3=TreeMap, 4=is}" }, { "code": null, "e": 31134, "s": 30789, "text": "GeeksforGeeks has also prepared a course Fundamentals of Java and Java Collections to teach you the Java concepts in depth. This course will help you to use Collections Framework’s inbuilt classes and functions in order to implement some of the complex data structures easily & efficiently and perform operations on them. Check out this course:" }, { "code": null, "e": 31149, "s": 31134, "text": "prachisoda1234" }, { "code": null, "e": 31160, "s": 31149, "text": "GFG-Update" }, { "code": null, "e": 31177, "s": 31160, "text": "Java-Collections" }, { "code": null, "e": 31183, "s": 31177, "text": "GBlog" }, { "code": null, "e": 31188, "s": 31183, "text": "Java" }, { "code": null, "e": 31193, "s": 31188, "text": "Java" }, { "code": null, "e": 31210, "s": 31193, "text": "Java-Collections" }, { "code": null, "e": 31308, "s": 31210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31347, "s": 31308, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 31372, "s": 31347, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31426, "s": 31372, "text": "Top Programming Languages For Competitive Programming" }, { "code": null, "e": 31458, "s": 31426, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 31489, "s": 31458, "text": "Writing a Windows batch script" }, { "code": null, "e": 31504, "s": 31489, "text": "Arrays in Java" }, { "code": null, "e": 31540, "s": 31504, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 31565, "s": 31540, "text": "Reverse a string in Java" }, { "code": null, "e": 31609, "s": 31565, "text": "Split() String method in Java with examples" } ]
How SYSDATE function works in PL/SQL
30 Jan, 2019 The PLSQL SYSDATE function will returns current system date and time on your database. There is no any parameter or argument for the SYSDATE function. The SYSDATE function returns a date value. Note that the SYSDATE function return date and time as “YYYY-MM-DD HH:MM:SS” (string) or as YYYYMMDDHHMMSS (numeric). Syntax: SYSDATE Example-1: SELECT Sysdate AS System_dateFROM Dual Explanation:Above example will display current date from system on database. It will execute the Syntax ‘Sysdate’ from dual, which act as dummy table and display date only in default format. In above query ‘System_date’ act as Alias Name i.e., Temporary Name of that specified column. Output: 1. Display both Date and Time – Syntax: SELECT TO_CHAR(Sysdate, Format_Of_Date_and_Time) AS Alias_Name FROM Dual Format_Of_Date_and_Time: DD-MM-YYYY HH:MM:SS MM-DD-YYYY HH:MM:SS YYYY-MM-DD HH:MM:SS DD-MON-YYYY HH:MM:SS MON-DD-YY HH:MM:SS DD-MM-YYYY HH24:MM:SS (For 24hr time Format) Example-2: SELECT TO_CHAR (Sysdate, 'DD-MM-YYYY HH24:MI:SS') AS System_date_timeFROM Dual Output: Example-3: SELECT TO_CHAR (Sysdate, 'YYYY-MON-DD HH24:MI:SS') AS System_date_timeFROM Dual Output: Explanation:In above example, it will display both date as well as time on database in specified format. TO_CHAR() Function is basically helpful to convert System date into date and time of specified format. Here ‘System_date_time’ also act as Alias Name and display both date and time in defined column. 2. Display Consecutive Dates from Current Date using Level – Syntax: SELECT Sysdate+Level-1 FROM Dual CONNECT BY Level<=n Where n is consecutive number of days. Example-4: SELECT Sysdate+Level-1 AS Consecutive_datesFROM DualCONNECT BY Level<=5 Explanation:For display of consecutive number of dates, we can use SYSDATE with LEVEL. Level can be used as hierarchical structure having child nodes like 1 as root then 2 as child then 3. Level have initial value as 1, here Sysdate adds up with Level and act as multilevel structure, then could be helpful to display dates in consecutive manner. Output: SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | Views Difference between DELETE, DROP and TRUNCATE CTE in SQL SQL Trigger | Student Database SQL using Python Difference between DELETE and TRUNCATE SQL | DDL, DML, TCL and DCL SQL Correlated Subqueries Window functions in SQL Difference between DDL and DML in DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2019" }, { "code": null, "e": 340, "s": 28, "text": "The PLSQL SYSDATE function will returns current system date and time on your database. There is no any parameter or argument for the SYSDATE function. The SYSDATE function returns a date value. Note that the SYSDATE function return date and time as “YYYY-MM-DD HH:MM:SS” (string) or as YYYYMMDDHHMMSS (numeric)." }, { "code": null, "e": 348, "s": 340, "text": "Syntax:" }, { "code": null, "e": 357, "s": 348, "text": "SYSDATE\n" }, { "code": null, "e": 368, "s": 357, "text": "Example-1:" }, { "code": "SELECT Sysdate AS System_dateFROM Dual", "e": 407, "s": 368, "text": null }, { "code": null, "e": 692, "s": 407, "text": "Explanation:Above example will display current date from system on database. It will execute the Syntax ‘Sysdate’ from dual, which act as dummy table and display date only in default format. In above query ‘System_date’ act as Alias Name i.e., Temporary Name of that specified column." }, { "code": null, "e": 700, "s": 692, "text": "Output:" }, { "code": null, "e": 732, "s": 700, "text": "1. Display both Date and Time –" }, { "code": null, "e": 740, "s": 732, "text": "Syntax:" }, { "code": null, "e": 986, "s": 740, "text": "SELECT TO_CHAR(Sysdate, Format_Of_Date_and_Time) AS Alias_Name\nFROM Dual \n\nFormat_Of_Date_and_Time:\nDD-MM-YYYY HH:MM:SS\nMM-DD-YYYY HH:MM:SS\nYYYY-MM-DD HH:MM:SS\nDD-MON-YYYY HH:MM:SS\nMON-DD-YY HH:MM:SS\nDD-MM-YYYY HH24:MM:SS (For 24hr time Format) " }, { "code": null, "e": 997, "s": 986, "text": "Example-2:" }, { "code": "SELECT TO_CHAR (Sysdate, 'DD-MM-YYYY HH24:MI:SS') AS System_date_timeFROM Dual", "e": 1076, "s": 997, "text": null }, { "code": null, "e": 1084, "s": 1076, "text": "Output:" }, { "code": null, "e": 1095, "s": 1084, "text": "Example-3:" }, { "code": "SELECT TO_CHAR (Sysdate, 'YYYY-MON-DD HH24:MI:SS') AS System_date_timeFROM Dual", "e": 1175, "s": 1095, "text": null }, { "code": null, "e": 1183, "s": 1175, "text": "Output:" }, { "code": null, "e": 1488, "s": 1183, "text": "Explanation:In above example, it will display both date as well as time on database in specified format. TO_CHAR() Function is basically helpful to convert System date into date and time of specified format. Here ‘System_date_time’ also act as Alias Name and display both date and time in defined column." }, { "code": null, "e": 1549, "s": 1488, "text": "2. Display Consecutive Dates from Current Date using Level –" }, { "code": null, "e": 1557, "s": 1549, "text": "Syntax:" }, { "code": null, "e": 1611, "s": 1557, "text": "SELECT Sysdate+Level-1\nFROM Dual\nCONNECT BY Level<=n " }, { "code": null, "e": 1650, "s": 1611, "text": "Where n is consecutive number of days." }, { "code": null, "e": 1661, "s": 1650, "text": "Example-4:" }, { "code": "SELECT Sysdate+Level-1 AS Consecutive_datesFROM DualCONNECT BY Level<=5", "e": 1733, "s": 1661, "text": null }, { "code": null, "e": 2080, "s": 1733, "text": "Explanation:For display of consecutive number of dates, we can use SYSDATE with LEVEL. Level can be used as hierarchical structure having child nodes like 1 as root then 2 as child then 3. Level have initial value as 1, here Sysdate adds up with Level and act as multilevel structure, then could be helpful to display dates in consecutive manner." }, { "code": null, "e": 2088, "s": 2080, "text": "Output:" }, { "code": null, "e": 2099, "s": 2088, "text": "SQL-PL/SQL" }, { "code": null, "e": 2103, "s": 2099, "text": "SQL" }, { "code": null, "e": 2107, "s": 2103, "text": "SQL" }, { "code": null, "e": 2205, "s": 2107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2217, "s": 2205, "text": "SQL | Views" }, { "code": null, "e": 2262, "s": 2217, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 2273, "s": 2262, "text": "CTE in SQL" }, { "code": null, "e": 2304, "s": 2273, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2321, "s": 2304, "text": "SQL using Python" }, { "code": null, "e": 2360, "s": 2321, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 2388, "s": 2360, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 2414, "s": 2388, "text": "SQL Correlated Subqueries" }, { "code": null, "e": 2438, "s": 2414, "text": "Window functions in SQL" } ]
Recursively remove all adjacent duplicates
23 Jun, 2022 Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See the following examples. Examples: Input: azxxzy Output: ay First “azxxzy” is reduced to “azzy”. The string “azzy” contains duplicates, so it is further reduced to “ay”. Input: geeksforgeeg Output: gksfor First “geeksforgeeg” is reduced to “gksforgg”. The string “gksforgg” contains duplicates, so it is further reduced to “gksfor”. Input: caaabbbaacdddd Output: Empty String Input: acaaabbbacdddd Output: acac The following approach can be followed to remove duplicates in O(N) time: Start from the leftmost character and remove duplicates at left corner if there are any. The first character must be different from its adjacent now. Recur for string of length n-1 (string without first character). Let the string obtained after reducing right substring of length n-1 be rem_str. There are three possible cases If first character of rem_str matches with the first character of original string, remove the first character from rem_str.If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.Else, append the first character of the original string at the beginning of rem_str. If first character of rem_str matches with the first character of original string, remove the first character from rem_str.If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.Else, append the first character of the original string at the beginning of rem_str. If first character of rem_str matches with the first character of original string, remove the first character from rem_str. If remaining string becomes empty and last removed character is same as first character of original string. Return empty string. Else, append the first character of the original string at the beginning of rem_str. Return rem_str. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++14 C Java Python C# Javascript // C++ program to remove all adjacent duplicates from a string#include <bits/stdc++.h>using namespace std; // Recursively removes adjacent duplicates from str and// returns new string. last_removed is a pointer to// last_removed characterchar* removeUtil(char* str, char* last_removed){ // If length of string is 1 or 0 if (str[0] == '\0' || str[1] == '\0') return str; // Remove leftmost same characters and recur for // remaining string if (str[0] == str[1]) { *last_removed = str[0]; while (str[1] && str[0] == str[1]) str++; str++; return removeUtil(str, last_removed); } // At this point, the first character is definitely // different from its adjacent. Ignore first character // and recursively remove characters from remaining // string char* rem_str = removeUtil(str + 1, last_removed); // Check if the first character of the rem_string // matches with the first character of the original // string if (rem_str[0] && rem_str[0] == str[0]) { *last_removed = str[0]; // Remove first character return (rem_str + 1); } // If remaining string becomes empty and last removed // character is same as first character of original // string. This is needed for a string like "acbbcddc" if (rem_str[0] == '\0' && *last_removed == str[0]) return rem_str; // If the two first characters of str and rem_str don't // match, append first character of str before the first // character of rem_str. rem_str--; rem_str[0] = str[0]; return rem_str;} // Function to removechar* remove(char* str){ char last_removed = '\0'; return removeUtil(str, &last_removed);} // Driver program to test above functionsint main(){ char str1[] = "geeksforgeeg"; cout << remove(str1) << endl; char str2[] = "azxxxzy"; cout << remove(str2) << endl; char str3[] = "caaabbbaac"; cout << remove(str3) << endl; char str4[] = "gghhg"; cout << remove(str4) << endl; char str5[] = "aaaacddddcappp"; cout << remove(str5) << endl; char str6[] = "aaaaaaaaaa"; cout << remove(str6) << endl; char str7[] = "qpaaaaadaaaaadprq"; cout << remove(str7) << endl; char str8[] = "acaaabbbacdddd"; cout << remove(str8) << endl; char str9[] = "acbbcddc"; cout << remove(str9) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to remove all adjacent duplicates from a string#include <stdio.h>#include <string.h> // Recursively removes adjacent duplicates from str and// returns new string. last_removed is a pointer to// last_removed characterchar* removeUtil(char* str, char* last_removed){ // If length of string is 1 or 0 if (str[0] == '\0' || str[1] == '\0') return str; // Remove leftmost same characters and recur for // remaining string if (str[0] == str[1]) { *last_removed = str[0]; while (str[1] && str[0] == str[1]) str++; str++; return removeUtil(str, last_removed); } // At this point, the first character is definitely // different from its adjacent. Ignore first character // and recursively remove characters from remaining // string char* rem_str = removeUtil(str + 1, last_removed); // Check if the first character of the rem_string // matches with the first character of the original // string if (rem_str[0] && rem_str[0] == str[0]) { *last_removed = str[0]; // Remove first character return (rem_str + 1); } // If remaining string becomes empty and last removed // character is same as first character of original // string. This is needed for a string like "acbbcddc" if (rem_str[0] == '\0' && *last_removed == str[0]) return rem_str; // If the two first characters of str and rem_str don't // match, append first character of str before the first // character of rem_str. rem_str--; rem_str[0] = str[0]; return rem_str;} // Function to removechar* removes(char* str){ char last_removed = '\0'; return removeUtil(str, &last_removed);} // Driver program to test above functionsint main(){ char str1[] = "geeksforgeeg"; printf("%s\n", removes(str1)); char str2[] = "azxxxzy"; printf("%s\n", removes(str2)); char str3[] = "caaabbbaac"; printf("%s\n", removes(str3)); char str4[] = "gghhg"; printf("%s\n", removes(str4)); char str5[] = "aaaacddddcappp"; printf("%s\n", removes(str5)); char str6[] = "aaaaaaaaaa"; printf("%s\n", removes(str6)); char str7[] = "qpaaaaadaaaaadprq"; printf("%s\n", removes(str7)); char str8[] = "acaaabbbacdddd"; printf("%s\n", removes(str8)); char str9[] = "acbbcddc"; printf("%s\n", removes(str9)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to remove all adjacent duplicates from a// stringimport java.io.*;import java.util.*; class GFG { static char last_removed; //will store the last char removed during recursion // Recursively removes adjacent duplicates from str and // returns new string. last_removed is a pointer to // last_removed character static String removeUtil(String str) { // If length of string is 1 or 0 if (str.length() == 0 || str.length() == 1) return str; // Remove leftmost same characters and recur for // remaining string if (str.charAt(0) == str.charAt(1)) { last_removed = str.charAt(0); while (str.length() > 1 && str.charAt(0) == str.charAt(1)) str = str.substring(1, str.length()); str = str.substring(1, str.length()); return removeUtil(str); } // At this point, the first character is definitely // different from its adjacent. Ignore first // character and recursively remove characters from // remaining string String rem_str = removeUtil(str.substring(1, str.length())); // Check if the first character of the rem_string // matches with the first character of the original // string if (rem_str.length() != 0 && rem_str.charAt(0) == str.charAt(0)) { last_removed = str.charAt(0); // Remove first character return rem_str.substring(1, rem_str.length()); } // If remaining string becomes empty and last // removed character is same as first character of // original string. This is needed for a string like // "acbbcddc" if (rem_str.length() == 0 && last_removed == str.charAt(0)) return rem_str; // If the two first characters of str and rem_str // don't match, append first character of str before // the first character of rem_str return (str.charAt(0) + rem_str); } static String remove(String str) { last_removed = '\0'; return removeUtil(str); } // Driver code public static void main(String args[]) { String str1 = "geeksforgeeg"; System.out.println(remove(str1)); String str2 = "azxxxzy"; System.out.println(remove(str2)); String str3 = "caaabbbaac"; System.out.println(remove(str3)); String str4 = "gghhg"; System.out.println(remove(str4)); String str5 = "aaaacddddcappp"; System.out.println(remove(str5)); String str6 = "aaaaaaaaaa"; System.out.println(remove(str6)); String str7 = "qpaaaaadaaaaadprq"; System.out.println(remove(str7)); String str8 = "acaaabbbacdddd"; System.out.println(remove(str8)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python program to remove# all adjacent duplicates from a string # Recursively removes adjacent# duplicates from str and returns# new string. last_removed is a# pointer to last_removed characterdef removeUtil(string, last_removed): # If length of string is 1 or 0 if len(string) == 0 or len(string) == 1: return string # Remove leftmost same characters # and recur for remaining # string if string[0] == string[1]: last_removed = ord(string[0]) while len(string) > 1 and string[0] == string[1]: string = string[1:] string = string[1:] return removeUtil(string, last_removed) # At this point, the first # character is definitely different # from its adjacent. Ignore first # character and recursively # remove characters from remaining string rem_str = removeUtil(string[1:], last_removed) # Check if the first character # of the rem_string matches # with the first character of # the original string if len(rem_str) != 0 and rem_str[0] == string[0]: last_removed = ord(string[0]) return (rem_str[1:]) # If remaining string becomes # empty and last removed character # is same as first character of # original string. This is needed # for a string like "acbbcddc" if len(rem_str) == 0 and last_removed == ord(string[0]): return rem_str # If the two first characters of # str and rem_str don't match, # append first character of str # before the first character of # rem_str. return ([string[0]] + rem_str) def remove(string): last_removed = 0 return toString(removeUtil(toList(string), last_removed)) # Utility functionsdef toList(string): x = [] for i in string: x.append(i) return x def toString(x): return ''.join(x) # Driver programstring1 = "geeksforgeeg"print remove(string1) string2 = "azxxxzy"print remove(string2) string3 = "caaabbbaac"print remove(string3) string4 = "gghhg"print remove(string4) string5 = "aaaacddddcappp"print remove(string5) string6 = "aaaaaaaaaa"print remove(string6) string7 = "qpaaaaadaaaaadprq"print remove(string7) string8 = "acaaabbbacdddd"print remove(string8) string9 = "acbbcddc"print remove(string9) # This code is contributed by BHAVYA JAIN // C# program to remove// all adjacent duplicates// from a stringusing System; class GFG{ // Recursively removes adjacent // duplicates from str and returns // new string. last_removed is a // pointer to last_removed character static string removeUtil(string str, char last_removed) { // If length of string is 1 or 0 if (str.Length == 0 || str.Length == 1) return str; // Remove leftmost same characters // and recur for remaining // string if (str[0] == str[1]) { last_removed = str[0]; while (str.Length > 1 && str[0] == str[1]) { str = str.Substring(1, str.Length - 1); } str = str.Substring(1, str.Length - 1); return removeUtil(str, last_removed); } // At this point, the first // character is definitely different // from its adjacent. Ignore first // character and recursively // remove characters from remaining string string rem_str = removeUtil(str.Substring( 1,str.Length - 1), last_removed); // Check if the first character of // the rem_string matches with // the first character of the original string if (rem_str.Length != 0 && rem_str[0] == str[0]) { last_removed = str[0]; // Remove first character return rem_str.Substring(1,rem_str.Length - 1); } // If remaining string becomes // empty and last removed character // is same as first character of // original string. This is needed // for a string like "acbbcddc" if (rem_str.Length == 0 && last_removed == str[0]) return rem_str; // If the two first characters // of str and rem_str don't match, // append first character of str // before the first character of // rem_str return (str[0] + rem_str); } static string remove(string str) { char last_removed = '\0'; return removeUtil(str, last_removed); } // Driver code public static void Main() { string str1 = "geeksforgeeg"; Console.Write(remove(str1) + "\n"); string str2 = "azxxxzy"; Console.Write(remove(str2) + "\n"); string str3 = "caaabbbaac"; Console.Write(remove(str3) + "\n"); string str4 = "gghhg"; Console.Write(remove(str4) + "\n"); string str5 = "aaaacddddcappp"; Console.Write(remove(str5) + "\n"); string str6 = "aaaaaaaaaa"; Console.Write(remove(str6) + "\n"); string str7 = "qpaaaaadaaaaadprq"; Console.Write(remove(str7) + "\n"); string str8 = "acaaabbbacdddd"; Console.Write(remove(str8) + "\n"); string str9 = "acbbcdd"; Console.Write(remove(str9) + "\n"); }} // This code is contributed by Samim Hossain Mondal. <script> // Python program to remove// all adjacent duplicates from a string // Recursively removes adjacent// duplicates from str and returns// new string. last_removed is a// pointer to last_removed characterfunction removeUtil(string, last_removed){ // If length of string is 1 or 0 if(string.length == 0 || string.length == 1) return string // Remove leftmost same characters // and recur for remaining // string if(string[0] == string[1]){ last_removed = string.charCodeAt(0) while(string.length > 1 && string[0] == string[1]) string = string.substr(1,) string = string.substr(1,) return removeUtil(string, last_removed) } // At this point, the first // character is functioninitely different // from its adjacent. Ignore first // character and recursively // remove characters from remaining string let rem_str = removeUtil(string.substr(1,), last_removed) // Check if the first character // of the rem_string matches // with the first character of // the original string if(rem_str.length != 0 && rem_str[0] == string[0]){ last_removed = string.charCodeAt(0) return rem_str.substr(1,) } // If remaining string becomes // empty and last removed character // is same as first character of // original string. This is needed // for a string like "acbbcddc" if(rem_str.length == 0 && last_removed == string.charCodeAt(0)) return rem_str // If the two first characters of // str and rem_str don't match, // push first character of str // before the first character of // rem_str. let res = string[0] + rem_str return res} function remove(string){ let last_removed = 0 return removeUtil(string,last_removed)} // Driver programlet string1 = "geeksforgeeg"document.write(remove(string1),"</br>") let string2 = "azxxxzy"document.write(remove(string2),"</br>") let string3 = "caaabbbaac"document.write(remove(string3),"</br>") let string4 = "gghhg"document.write(remove(string4),"</br>") let string5 = "aaaacddddcappp"document.write(remove(string5),"</br>") let string6 = "aaaaaaaaaa"document.write(remove(string6),"</br>") let string7 = "qpaaaaadaaaaadprq"document.write(remove(string7),"</br>") let string8 = "acaaabbbacdddd"document.write(remove(string8),"</br>") let string9 = "acbbcddc"document.write(remove(string9),"</br>") // This code is contributed by shinjanpatra </script> gksfor ay g a qrq acac a Time Complexity: The time complexity of the solution can be written as T(n) = T(n-k) + O(k) where n is length of the input string and k is the number of first characters which are same. Solution of the recurrence is O(n) Thanks to Prachi Bodke for suggesting this problem and initial solution. Another Approach:The idea here is to check whether the String remStr has the repeated character that matches the last char of the parent String. If that is happening then we have to keep removing that character before concatenating string s and string remStr. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ Program for above approach #include <bits/stdc++.h>using namespace std; // Recursively removes adjacent// duplicates from str and// returns new string. las_removed// is a pointer to// last_removed characterstring removeDuplicates(string s, char ch){ // If length of string is 1 or 0 if (s.length() <= 1) { return s; } int i = 0; while (i < s.length()) { if (i + 1 < s.length() && s[i] == s[i + 1]) { int j = i; while (j + 1 < s.length() && s[j] == s[j + 1]) { j++; } char lastChar = i > 0 ? s[i - 1] : ch; string remStr = removeDuplicates( s.substr(j + 1, s.length()), lastChar); s = s.substr(0, i); int k = s.length(), l = 0; // Recursively remove all the adjacent // characters formed by removing the // adjacent characters while (remStr.length() > 0 && s.length() > 0 && remStr[0] == s[s.length() - 1]) { // Have to check whether this is the // repeated character that matches the // last char of the parent String while (remStr.length() > 0 && remStr[0] != ch && remStr[0] == s[s.length() - 1]) { remStr = remStr.substr(1, remStr.length()); } s = s.substr(0, s.length() - 1); } s = s + remStr; i = j; } else { i++; } } return s;} // Driver Codeint main(){ string str1 = "mississipie"; cout << removeDuplicates(str1, ' ') << endl; string str2 = "ocvvcolop"; cout << removeDuplicates(str2, ' ') << endl;} // This code is contributed by nirajgusain5 // Java Program for above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Recursively removes adjacent // duplicates from str and // returns new string. las_removed // is a pointer to // last_removed character private static String removeDuplicates( String s, char ch) { // If length of string is 1 or 0 if (s == null || s.length() <= 1) { return s; } int i = 0; while (i < s.length()) { if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) { int j = i; while (j + 1 < s.length() && s.charAt(j) == s.charAt(j + 1)) { j++; } char lastChar = i > 0 ? s.charAt(i - 1) : ch; String remStr = removeDuplicates( s.substring(j + 1, s.length()), lastChar); s = s.substring(0, i); int k = s.length(), l = 0; // Recursively remove all the adjacent // characters formed by removing the // adjacent characters while (remStr.length() > 0 && s.length() > 0 && remStr.charAt(0) == s.charAt(s.length() - 1)) { // Have to check whether this is the // repeated character that matches the // last char of the parent String while (remStr.length() > 0 && remStr.charAt(0) != ch && remStr.charAt(0) == s.charAt(s.length() - 1)) { remStr = remStr.substring( 1, remStr.length()); } s = s.substring(0, s.length() - 1); } s = s + remStr; i = j; } else { i++; } } return s; } // Driver Code public static void main(String[] args) { String str1 = "mississipie"; System.out.println(removeDuplicates( str1, ' ')); String str2 = "ocvvcolop"; System.out.println(removeDuplicates( str2, ' ')); }} // This code is contributed by Niharika Sahai # Python Program for above approach # Recursively removes adjacent# duplicates from str and# returns new string. las_removed# is a pointer to# last_removed characterdef removeDuplicates(s,ch): # If length of string is 1 or 0 if (len(s) <= 1): return s i = 0 while (i < len(s)): if (i + 1 < len(s) and s[i] == s[i + 1]): j = i while (j + 1 < len(s) and s[j] == s[j + 1]): j += 1 lastChar = s[i - 1] if(i > 0) else ch remStr = removeDuplicates(s[j + 1: len(s)], lastChar) s = s[0: i] k,l = len(s), 0 # Recursively remove all the adjacent # characters formed by removing the # adjacent characters while (len(remStr) > 0 and len(s) > 0 and remStr[0] == s[len(s) - 1]): # Have to check whether this is the # repeated character that matches the # last char of the parent String while (len(remStr) > 0 and remStr[0] != ch and remStr[0] == s[len(s) - 1]): remStr = remStr[1: len(remStr)+1] s = s[0: len(s) - 1] s = s + remStr i = j else: i += 1 return s # Driver Codestr1 = "mississipie"print(removeDuplicates(str1, ' ')) str2 = "ocvvcolop"print(removeDuplicates(str2, ' ')) # This code is contributed by shinjanpatra <script> // JavaScript Program for above approach // Recursively removes adjacent// duplicates from str and// returns new string. las_removed// is a pointer to// last_removed characterfunction removeDuplicates(s,ch){ // If length of string is 1 or 0 if (s.length <= 1) { return s; } let i = 0; while (i < s.length) { if (i + 1 < s.length && s[i] == s[i + 1]) { let j = i; while (j + 1 < s.length && s[j] == s[j + 1]) { j++; } let lastChar = i > 0 ? s[i - 1] : ch; let remStr = removeDuplicates( s.substring(j + 1, s.length), lastChar); s = s.substring(0, i); let k = s.length, l = 0; // Recursively remove all the adjacent // characters formed by removing the // adjacent characters while (remStr.length > 0 && s.length > 0 && remStr[0] == s[s.length - 1]) { // Have to check whether this is the // repeated character that matches the // last char of the parent String while (remStr.length > 0 && remStr[0] != ch && remStr[0] == s[s.length - 1]) { remStr = remStr.substring(1, remStr.length+1); } s = s.substring(0, s.length - 1); } s = s + remStr; i = j; } else { i++; } } return s;} // Driver Code let str1 = "mississipie";console.log(removeDuplicates(str1, ' ')); let str2 = "ocvvcolop";document.write(removeDuplicates(str2, ' '),"</br>"); // This code is contributed by shinjanpatra</script> mpie lop Time Complexity: O(n) pragya29 rachana soma Niharika Sahai adityamutharia nirajgusain5 surinderdawra388 surindertarika1234 samim2000 simmytarika5 shinjanpatra adityakumar129 aryandhakad1 hardikkoriintern Paytm Samsung Arrays Recursion Strings Paytm Samsung Arrays Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Linear Search Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) K'th Smallest/Largest Element in Unsorted Array | Set 1 Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 221, "s": 52, "text": "Given a string, recursively remove adjacent duplicate characters from the string. The output string should not have any adjacent duplicates. See the following examples." }, { "code": null, "e": 232, "s": 221, "text": "Examples: " }, { "code": null, "e": 258, "s": 232, "text": "Input: azxxzy Output: ay " }, { "code": null, "e": 296, "s": 258, "text": "First “azxxzy” is reduced to “azzy”. " }, { "code": null, "e": 336, "s": 296, "text": "The string “azzy” contains duplicates, " }, { "code": null, "e": 370, "s": 336, "text": "so it is further reduced to “ay”." }, { "code": null, "e": 406, "s": 370, "text": "Input: geeksforgeeg Output: gksfor " }, { "code": null, "e": 454, "s": 406, "text": "First “geeksforgeeg” is reduced to “gksforgg”. " }, { "code": null, "e": 498, "s": 454, "text": "The string “gksforgg” contains duplicates, " }, { "code": null, "e": 536, "s": 498, "text": "so it is further reduced to “gksfor”." }, { "code": null, "e": 579, "s": 536, "text": "Input: caaabbbaacdddd Output: Empty String" }, { "code": null, "e": 615, "s": 579, "text": "Input: acaaabbbacdddd Output: acac " }, { "code": null, "e": 690, "s": 615, "text": "The following approach can be followed to remove duplicates in O(N) time: " }, { "code": null, "e": 779, "s": 690, "text": "Start from the leftmost character and remove duplicates at left corner if there are any." }, { "code": null, "e": 905, "s": 779, "text": "The first character must be different from its adjacent now. Recur for string of length n-1 (string without first character)." }, { "code": null, "e": 1353, "s": 905, "text": "Let the string obtained after reducing right substring of length n-1 be rem_str. There are three possible cases If first character of rem_str matches with the first character of original string, remove the first character from rem_str.If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.Else, append the first character of the original string at the beginning of rem_str." }, { "code": null, "e": 1689, "s": 1353, "text": "If first character of rem_str matches with the first character of original string, remove the first character from rem_str.If remaining string becomes empty and last removed character is same as first character of original string. Return empty string.Else, append the first character of the original string at the beginning of rem_str." }, { "code": null, "e": 1813, "s": 1689, "text": "If first character of rem_str matches with the first character of original string, remove the first character from rem_str." }, { "code": null, "e": 1942, "s": 1813, "text": "If remaining string becomes empty and last removed character is same as first character of original string. Return empty string." }, { "code": null, "e": 2027, "s": 1942, "text": "Else, append the first character of the original string at the beginning of rem_str." }, { "code": null, "e": 2043, "s": 2027, "text": "Return rem_str." }, { "code": null, "e": 2091, "s": 2043, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 2142, "s": 2091, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2148, "s": 2142, "text": "C++14" }, { "code": null, "e": 2150, "s": 2148, "text": "C" }, { "code": null, "e": 2155, "s": 2150, "text": "Java" }, { "code": null, "e": 2162, "s": 2155, "text": "Python" }, { "code": null, "e": 2165, "s": 2162, "text": "C#" }, { "code": null, "e": 2176, "s": 2165, "text": "Javascript" }, { "code": "// C++ program to remove all adjacent duplicates from a string#include <bits/stdc++.h>using namespace std; // Recursively removes adjacent duplicates from str and// returns new string. last_removed is a pointer to// last_removed characterchar* removeUtil(char* str, char* last_removed){ // If length of string is 1 or 0 if (str[0] == '\\0' || str[1] == '\\0') return str; // Remove leftmost same characters and recur for // remaining string if (str[0] == str[1]) { *last_removed = str[0]; while (str[1] && str[0] == str[1]) str++; str++; return removeUtil(str, last_removed); } // At this point, the first character is definitely // different from its adjacent. Ignore first character // and recursively remove characters from remaining // string char* rem_str = removeUtil(str + 1, last_removed); // Check if the first character of the rem_string // matches with the first character of the original // string if (rem_str[0] && rem_str[0] == str[0]) { *last_removed = str[0]; // Remove first character return (rem_str + 1); } // If remaining string becomes empty and last removed // character is same as first character of original // string. This is needed for a string like \"acbbcddc\" if (rem_str[0] == '\\0' && *last_removed == str[0]) return rem_str; // If the two first characters of str and rem_str don't // match, append first character of str before the first // character of rem_str. rem_str--; rem_str[0] = str[0]; return rem_str;} // Function to removechar* remove(char* str){ char last_removed = '\\0'; return removeUtil(str, &last_removed);} // Driver program to test above functionsint main(){ char str1[] = \"geeksforgeeg\"; cout << remove(str1) << endl; char str2[] = \"azxxxzy\"; cout << remove(str2) << endl; char str3[] = \"caaabbbaac\"; cout << remove(str3) << endl; char str4[] = \"gghhg\"; cout << remove(str4) << endl; char str5[] = \"aaaacddddcappp\"; cout << remove(str5) << endl; char str6[] = \"aaaaaaaaaa\"; cout << remove(str6) << endl; char str7[] = \"qpaaaaadaaaaadprq\"; cout << remove(str7) << endl; char str8[] = \"acaaabbbacdddd\"; cout << remove(str8) << endl; char str9[] = \"acbbcddc\"; cout << remove(str9) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4612, "s": 2176, "text": null }, { "code": "// C program to remove all adjacent duplicates from a string#include <stdio.h>#include <string.h> // Recursively removes adjacent duplicates from str and// returns new string. last_removed is a pointer to// last_removed characterchar* removeUtil(char* str, char* last_removed){ // If length of string is 1 or 0 if (str[0] == '\\0' || str[1] == '\\0') return str; // Remove leftmost same characters and recur for // remaining string if (str[0] == str[1]) { *last_removed = str[0]; while (str[1] && str[0] == str[1]) str++; str++; return removeUtil(str, last_removed); } // At this point, the first character is definitely // different from its adjacent. Ignore first character // and recursively remove characters from remaining // string char* rem_str = removeUtil(str + 1, last_removed); // Check if the first character of the rem_string // matches with the first character of the original // string if (rem_str[0] && rem_str[0] == str[0]) { *last_removed = str[0]; // Remove first character return (rem_str + 1); } // If remaining string becomes empty and last removed // character is same as first character of original // string. This is needed for a string like \"acbbcddc\" if (rem_str[0] == '\\0' && *last_removed == str[0]) return rem_str; // If the two first characters of str and rem_str don't // match, append first character of str before the first // character of rem_str. rem_str--; rem_str[0] = str[0]; return rem_str;} // Function to removechar* removes(char* str){ char last_removed = '\\0'; return removeUtil(str, &last_removed);} // Driver program to test above functionsint main(){ char str1[] = \"geeksforgeeg\"; printf(\"%s\\n\", removes(str1)); char str2[] = \"azxxxzy\"; printf(\"%s\\n\", removes(str2)); char str3[] = \"caaabbbaac\"; printf(\"%s\\n\", removes(str3)); char str4[] = \"gghhg\"; printf(\"%s\\n\", removes(str4)); char str5[] = \"aaaacddddcappp\"; printf(\"%s\\n\", removes(str5)); char str6[] = \"aaaaaaaaaa\"; printf(\"%s\\n\", removes(str6)); char str7[] = \"qpaaaaadaaaaadprq\"; printf(\"%s\\n\", removes(str7)); char str8[] = \"acaaabbbacdddd\"; printf(\"%s\\n\", removes(str8)); char str9[] = \"acbbcddc\"; printf(\"%s\\n\", removes(str9)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 7049, "s": 4612, "text": null }, { "code": "// Java program to remove all adjacent duplicates from a// stringimport java.io.*;import java.util.*; class GFG { static char last_removed; //will store the last char removed during recursion // Recursively removes adjacent duplicates from str and // returns new string. last_removed is a pointer to // last_removed character static String removeUtil(String str) { // If length of string is 1 or 0 if (str.length() == 0 || str.length() == 1) return str; // Remove leftmost same characters and recur for // remaining string if (str.charAt(0) == str.charAt(1)) { last_removed = str.charAt(0); while (str.length() > 1 && str.charAt(0) == str.charAt(1)) str = str.substring(1, str.length()); str = str.substring(1, str.length()); return removeUtil(str); } // At this point, the first character is definitely // different from its adjacent. Ignore first // character and recursively remove characters from // remaining string String rem_str = removeUtil(str.substring(1, str.length())); // Check if the first character of the rem_string // matches with the first character of the original // string if (rem_str.length() != 0 && rem_str.charAt(0) == str.charAt(0)) { last_removed = str.charAt(0); // Remove first character return rem_str.substring(1, rem_str.length()); } // If remaining string becomes empty and last // removed character is same as first character of // original string. This is needed for a string like // \"acbbcddc\" if (rem_str.length() == 0 && last_removed == str.charAt(0)) return rem_str; // If the two first characters of str and rem_str // don't match, append first character of str before // the first character of rem_str return (str.charAt(0) + rem_str); } static String remove(String str) { last_removed = '\\0'; return removeUtil(str); } // Driver code public static void main(String args[]) { String str1 = \"geeksforgeeg\"; System.out.println(remove(str1)); String str2 = \"azxxxzy\"; System.out.println(remove(str2)); String str3 = \"caaabbbaac\"; System.out.println(remove(str3)); String str4 = \"gghhg\"; System.out.println(remove(str4)); String str5 = \"aaaacddddcappp\"; System.out.println(remove(str5)); String str6 = \"aaaaaaaaaa\"; System.out.println(remove(str6)); String str7 = \"qpaaaaadaaaaadprq\"; System.out.println(remove(str7)); String str8 = \"acaaabbbacdddd\"; System.out.println(remove(str8)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 9963, "s": 7049, "text": null }, { "code": "# Python program to remove# all adjacent duplicates from a string # Recursively removes adjacent# duplicates from str and returns# new string. last_removed is a# pointer to last_removed characterdef removeUtil(string, last_removed): # If length of string is 1 or 0 if len(string) == 0 or len(string) == 1: return string # Remove leftmost same characters # and recur for remaining # string if string[0] == string[1]: last_removed = ord(string[0]) while len(string) > 1 and string[0] == string[1]: string = string[1:] string = string[1:] return removeUtil(string, last_removed) # At this point, the first # character is definitely different # from its adjacent. Ignore first # character and recursively # remove characters from remaining string rem_str = removeUtil(string[1:], last_removed) # Check if the first character # of the rem_string matches # with the first character of # the original string if len(rem_str) != 0 and rem_str[0] == string[0]: last_removed = ord(string[0]) return (rem_str[1:]) # If remaining string becomes # empty and last removed character # is same as first character of # original string. This is needed # for a string like \"acbbcddc\" if len(rem_str) == 0 and last_removed == ord(string[0]): return rem_str # If the two first characters of # str and rem_str don't match, # append first character of str # before the first character of # rem_str. return ([string[0]] + rem_str) def remove(string): last_removed = 0 return toString(removeUtil(toList(string), last_removed)) # Utility functionsdef toList(string): x = [] for i in string: x.append(i) return x def toString(x): return ''.join(x) # Driver programstring1 = \"geeksforgeeg\"print remove(string1) string2 = \"azxxxzy\"print remove(string2) string3 = \"caaabbbaac\"print remove(string3) string4 = \"gghhg\"print remove(string4) string5 = \"aaaacddddcappp\"print remove(string5) string6 = \"aaaaaaaaaa\"print remove(string6) string7 = \"qpaaaaadaaaaadprq\"print remove(string7) string8 = \"acaaabbbacdddd\"print remove(string8) string9 = \"acbbcddc\"print remove(string9) # This code is contributed by BHAVYA JAIN", "e": 12374, "s": 9963, "text": null }, { "code": "// C# program to remove// all adjacent duplicates// from a stringusing System; class GFG{ // Recursively removes adjacent // duplicates from str and returns // new string. last_removed is a // pointer to last_removed character static string removeUtil(string str, char last_removed) { // If length of string is 1 or 0 if (str.Length == 0 || str.Length == 1) return str; // Remove leftmost same characters // and recur for remaining // string if (str[0] == str[1]) { last_removed = str[0]; while (str.Length > 1 && str[0] == str[1]) { str = str.Substring(1, str.Length - 1); } str = str.Substring(1, str.Length - 1); return removeUtil(str, last_removed); } // At this point, the first // character is definitely different // from its adjacent. Ignore first // character and recursively // remove characters from remaining string string rem_str = removeUtil(str.Substring( 1,str.Length - 1), last_removed); // Check if the first character of // the rem_string matches with // the first character of the original string if (rem_str.Length != 0 && rem_str[0] == str[0]) { last_removed = str[0]; // Remove first character return rem_str.Substring(1,rem_str.Length - 1); } // If remaining string becomes // empty and last removed character // is same as first character of // original string. This is needed // for a string like \"acbbcddc\" if (rem_str.Length == 0 && last_removed == str[0]) return rem_str; // If the two first characters // of str and rem_str don't match, // append first character of str // before the first character of // rem_str return (str[0] + rem_str); } static string remove(string str) { char last_removed = '\\0'; return removeUtil(str, last_removed); } // Driver code public static void Main() { string str1 = \"geeksforgeeg\"; Console.Write(remove(str1) + \"\\n\"); string str2 = \"azxxxzy\"; Console.Write(remove(str2) + \"\\n\"); string str3 = \"caaabbbaac\"; Console.Write(remove(str3) + \"\\n\"); string str4 = \"gghhg\"; Console.Write(remove(str4) + \"\\n\"); string str5 = \"aaaacddddcappp\"; Console.Write(remove(str5) + \"\\n\"); string str6 = \"aaaaaaaaaa\"; Console.Write(remove(str6) + \"\\n\"); string str7 = \"qpaaaaadaaaaadprq\"; Console.Write(remove(str7) + \"\\n\"); string str8 = \"acaaabbbacdddd\"; Console.Write(remove(str8) + \"\\n\"); string str9 = \"acbbcdd\"; Console.Write(remove(str9) + \"\\n\"); }} // This code is contributed by Samim Hossain Mondal.", "e": 15054, "s": 12374, "text": null }, { "code": "<script> // Python program to remove// all adjacent duplicates from a string // Recursively removes adjacent// duplicates from str and returns// new string. last_removed is a// pointer to last_removed characterfunction removeUtil(string, last_removed){ // If length of string is 1 or 0 if(string.length == 0 || string.length == 1) return string // Remove leftmost same characters // and recur for remaining // string if(string[0] == string[1]){ last_removed = string.charCodeAt(0) while(string.length > 1 && string[0] == string[1]) string = string.substr(1,) string = string.substr(1,) return removeUtil(string, last_removed) } // At this point, the first // character is functioninitely different // from its adjacent. Ignore first // character and recursively // remove characters from remaining string let rem_str = removeUtil(string.substr(1,), last_removed) // Check if the first character // of the rem_string matches // with the first character of // the original string if(rem_str.length != 0 && rem_str[0] == string[0]){ last_removed = string.charCodeAt(0) return rem_str.substr(1,) } // If remaining string becomes // empty and last removed character // is same as first character of // original string. This is needed // for a string like \"acbbcddc\" if(rem_str.length == 0 && last_removed == string.charCodeAt(0)) return rem_str // If the two first characters of // str and rem_str don't match, // push first character of str // before the first character of // rem_str. let res = string[0] + rem_str return res} function remove(string){ let last_removed = 0 return removeUtil(string,last_removed)} // Driver programlet string1 = \"geeksforgeeg\"document.write(remove(string1),\"</br>\") let string2 = \"azxxxzy\"document.write(remove(string2),\"</br>\") let string3 = \"caaabbbaac\"document.write(remove(string3),\"</br>\") let string4 = \"gghhg\"document.write(remove(string4),\"</br>\") let string5 = \"aaaacddddcappp\"document.write(remove(string5),\"</br>\") let string6 = \"aaaaaaaaaa\"document.write(remove(string6),\"</br>\") let string7 = \"qpaaaaadaaaaadprq\"document.write(remove(string7),\"</br>\") let string8 = \"acaaabbbacdddd\"document.write(remove(string8),\"</br>\") let string9 = \"acbbcddc\"document.write(remove(string9),\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 17515, "s": 15054, "text": null }, { "code": null, "e": 17543, "s": 17515, "text": "gksfor\nay\n\ng\na\n\nqrq\nacac\na\n" }, { "code": null, "e": 17764, "s": 17543, "text": "Time Complexity: The time complexity of the solution can be written as T(n) = T(n-k) + O(k) where n is length of the input string and k is the number of first characters which are same. Solution of the recurrence is O(n)" }, { "code": null, "e": 17838, "s": 17764, "text": "Thanks to Prachi Bodke for suggesting this problem and initial solution. " }, { "code": null, "e": 18098, "s": 17838, "text": "Another Approach:The idea here is to check whether the String remStr has the repeated character that matches the last char of the parent String. If that is happening then we have to keep removing that character before concatenating string s and string remStr." }, { "code": null, "e": 18149, "s": 18098, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 18153, "s": 18149, "text": "C++" }, { "code": null, "e": 18158, "s": 18153, "text": "Java" }, { "code": null, "e": 18166, "s": 18158, "text": "Python3" }, { "code": null, "e": 18177, "s": 18166, "text": "Javascript" }, { "code": "// C++ Program for above approach #include <bits/stdc++.h>using namespace std; // Recursively removes adjacent// duplicates from str and// returns new string. las_removed// is a pointer to// last_removed characterstring removeDuplicates(string s, char ch){ // If length of string is 1 or 0 if (s.length() <= 1) { return s; } int i = 0; while (i < s.length()) { if (i + 1 < s.length() && s[i] == s[i + 1]) { int j = i; while (j + 1 < s.length() && s[j] == s[j + 1]) { j++; } char lastChar = i > 0 ? s[i - 1] : ch; string remStr = removeDuplicates( s.substr(j + 1, s.length()), lastChar); s = s.substr(0, i); int k = s.length(), l = 0; // Recursively remove all the adjacent // characters formed by removing the // adjacent characters while (remStr.length() > 0 && s.length() > 0 && remStr[0] == s[s.length() - 1]) { // Have to check whether this is the // repeated character that matches the // last char of the parent String while (remStr.length() > 0 && remStr[0] != ch && remStr[0] == s[s.length() - 1]) { remStr = remStr.substr(1, remStr.length()); } s = s.substr(0, s.length() - 1); } s = s + remStr; i = j; } else { i++; } } return s;} // Driver Codeint main(){ string str1 = \"mississipie\"; cout << removeDuplicates(str1, ' ') << endl; string str2 = \"ocvvcolop\"; cout << removeDuplicates(str2, ' ') << endl;} // This code is contributed by nirajgusain5", "e": 20000, "s": 18177, "text": null }, { "code": "// Java Program for above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Recursively removes adjacent // duplicates from str and // returns new string. las_removed // is a pointer to // last_removed character private static String removeDuplicates( String s, char ch) { // If length of string is 1 or 0 if (s == null || s.length() <= 1) { return s; } int i = 0; while (i < s.length()) { if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) { int j = i; while (j + 1 < s.length() && s.charAt(j) == s.charAt(j + 1)) { j++; } char lastChar = i > 0 ? s.charAt(i - 1) : ch; String remStr = removeDuplicates( s.substring(j + 1, s.length()), lastChar); s = s.substring(0, i); int k = s.length(), l = 0; // Recursively remove all the adjacent // characters formed by removing the // adjacent characters while (remStr.length() > 0 && s.length() > 0 && remStr.charAt(0) == s.charAt(s.length() - 1)) { // Have to check whether this is the // repeated character that matches the // last char of the parent String while (remStr.length() > 0 && remStr.charAt(0) != ch && remStr.charAt(0) == s.charAt(s.length() - 1)) { remStr = remStr.substring( 1, remStr.length()); } s = s.substring(0, s.length() - 1); } s = s + remStr; i = j; } else { i++; } } return s; } // Driver Code public static void main(String[] args) { String str1 = \"mississipie\"; System.out.println(removeDuplicates( str1, ' ')); String str2 = \"ocvvcolop\"; System.out.println(removeDuplicates( str2, ' ')); }} // This code is contributed by Niharika Sahai", "e": 22048, "s": 20000, "text": null }, { "code": "# Python Program for above approach # Recursively removes adjacent# duplicates from str and# returns new string. las_removed# is a pointer to# last_removed characterdef removeDuplicates(s,ch): # If length of string is 1 or 0 if (len(s) <= 1): return s i = 0 while (i < len(s)): if (i + 1 < len(s) and s[i] == s[i + 1]): j = i while (j + 1 < len(s) and s[j] == s[j + 1]): j += 1 lastChar = s[i - 1] if(i > 0) else ch remStr = removeDuplicates(s[j + 1: len(s)], lastChar) s = s[0: i] k,l = len(s), 0 # Recursively remove all the adjacent # characters formed by removing the # adjacent characters while (len(remStr) > 0 and len(s) > 0 and remStr[0] == s[len(s) - 1]): # Have to check whether this is the # repeated character that matches the # last char of the parent String while (len(remStr) > 0 and remStr[0] != ch and remStr[0] == s[len(s) - 1]): remStr = remStr[1: len(remStr)+1] s = s[0: len(s) - 1] s = s + remStr i = j else: i += 1 return s # Driver Codestr1 = \"mississipie\"print(removeDuplicates(str1, ' ')) str2 = \"ocvvcolop\"print(removeDuplicates(str2, ' ')) # This code is contributed by shinjanpatra", "e": 23550, "s": 22048, "text": null }, { "code": "<script> // JavaScript Program for above approach // Recursively removes adjacent// duplicates from str and// returns new string. las_removed// is a pointer to// last_removed characterfunction removeDuplicates(s,ch){ // If length of string is 1 or 0 if (s.length <= 1) { return s; } let i = 0; while (i < s.length) { if (i + 1 < s.length && s[i] == s[i + 1]) { let j = i; while (j + 1 < s.length && s[j] == s[j + 1]) { j++; } let lastChar = i > 0 ? s[i - 1] : ch; let remStr = removeDuplicates( s.substring(j + 1, s.length), lastChar); s = s.substring(0, i); let k = s.length, l = 0; // Recursively remove all the adjacent // characters formed by removing the // adjacent characters while (remStr.length > 0 && s.length > 0 && remStr[0] == s[s.length - 1]) { // Have to check whether this is the // repeated character that matches the // last char of the parent String while (remStr.length > 0 && remStr[0] != ch && remStr[0] == s[s.length - 1]) { remStr = remStr.substring(1, remStr.length+1); } s = s.substring(0, s.length - 1); } s = s + remStr; i = j; } else { i++; } } return s;} // Driver Code let str1 = \"mississipie\";console.log(removeDuplicates(str1, ' ')); let str2 = \"ocvvcolop\";document.write(removeDuplicates(str2, ' '),\"</br>\"); // This code is contributed by shinjanpatra</script>", "e": 25288, "s": 23550, "text": null }, { "code": null, "e": 25298, "s": 25288, "text": "mpie\nlop\n" }, { "code": null, "e": 25321, "s": 25298, "text": "Time Complexity: O(n) " }, { "code": null, "e": 25330, "s": 25321, "text": "pragya29" }, { "code": null, "e": 25343, "s": 25330, "text": "rachana soma" }, { "code": null, "e": 25358, "s": 25343, "text": "Niharika Sahai" }, { "code": null, "e": 25373, "s": 25358, "text": "adityamutharia" }, { "code": null, "e": 25386, "s": 25373, "text": "nirajgusain5" }, { "code": null, "e": 25403, "s": 25386, "text": "surinderdawra388" }, { "code": null, "e": 25422, "s": 25403, "text": "surindertarika1234" }, { "code": null, "e": 25432, "s": 25422, "text": "samim2000" }, { "code": null, "e": 25445, "s": 25432, "text": "simmytarika5" }, { "code": null, "e": 25458, "s": 25445, "text": "shinjanpatra" }, { "code": null, "e": 25473, "s": 25458, "text": "adityakumar129" }, { "code": null, "e": 25486, "s": 25473, "text": "aryandhakad1" }, { "code": null, "e": 25503, "s": 25486, "text": "hardikkoriintern" }, { "code": null, "e": 25509, "s": 25503, "text": "Paytm" }, { "code": null, "e": 25517, "s": 25509, "text": "Samsung" }, { "code": null, "e": 25524, "s": 25517, "text": "Arrays" }, { "code": null, "e": 25534, "s": 25524, "text": "Recursion" }, { "code": null, "e": 25542, "s": 25534, "text": "Strings" }, { "code": null, "e": 25548, "s": 25542, "text": "Paytm" }, { "code": null, "e": 25556, "s": 25548, "text": "Samsung" }, { "code": null, "e": 25563, "s": 25556, "text": "Arrays" }, { "code": null, "e": 25571, "s": 25563, "text": "Strings" }, { "code": null, "e": 25581, "s": 25571, "text": "Recursion" }, { "code": null, "e": 25679, "s": 25581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25711, "s": 25679, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 25725, "s": 25711, "text": "Linear Search" }, { "code": null, "e": 25748, "s": 25725, "text": "Introduction to Arrays" }, { "code": null, "e": 25833, "s": 25748, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 25889, "s": 25833, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 25949, "s": 25889, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 26034, "s": 25949, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 26044, "s": 26034, "text": "Recursion" }, { "code": null, "e": 26071, "s": 26044, "text": "Program for Tower of Hanoi" } ]