title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Java Collection Tutorial - GeeksforGeeks | 15 Mar, 2021
Java Collection Framework is unlikely any group of individual objects which are represented as a single unit be it of any type is known as the collection of objects. Earlier in Java, there was no such thing defined which holds true for it so there arises a need in the next versions of any such concept. So in JDK 1.2, a separate framework was defined known as “Collection Framework” which holds all the collection classes and interfaces in it.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.
What is a Framework?
A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.
Need for a Separate Collection Framework
Before Collection Framework(or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these collections had no common interface. Therefore, though the main aim of all the collections is the same, the implementation of all these collections was defined independently and had no correlation among them. And also, it is very difficult for the users to remember all the different methods, syntax, and constructors present in every collection class.
Are you confused between Collection, Collection Interface, Collections Class, Collection Framework?
Collection: A group of individual objects that represent a single entity is known as a collection. It is the common word that you used in your daily life. But if we are discussing Java programming language then it will become Java Collection Framework.
Collection Framework: To represent a group of objects as a single entity in the Java programming language we need classes and interfaces defined by the Collection Framework. If are from C++ background that you can compare Collection with Containers and Collection Framework with STL(Standard Template Library).
Collection Interface: Interfaces specify what a class must do and not how. It is the blueprint of the class. It is the root interface of the Collection Framework that defines the most common methods that can be used for any collection objects. Or you can say it represents the individual object as a single entity.
Collections Class: It is present in java.util package and is a member of Collection Framework. This class provides many utility methods for the collection object.
Now you must be wondering why to include such a concept or what difficulties were faced before java version 1.2 that lead birth to the concept of Collection. In order to figure it out, the three main advantages are mentioned below:
Reduces the programming effort as the programmer does not have to worry about designing the Collection class and on the same hand java being object-oriented language advances in achieving abstraction by not writing the Collection class.Increases program speed and quality as the programmer now is not worried about thinking best implementation for a specific data structure as of now for a programmer scope widens up and at the same time is now only worried about the best implementation that can drastically boost the performance of program irrespective of data structure constraints encountered earlier.The API that implements these interfaces are now having common sets of methods be it of any interfaces such as Collection, Set, List, and Map.
Reduces the programming effort as the programmer does not have to worry about designing the Collection class and on the same hand java being object-oriented language advances in achieving abstraction by not writing the Collection class.
Increases program speed and quality as the programmer now is not worried about thinking best implementation for a specific data structure as of now for a programmer scope widens up and at the same time is now only worried about the best implementation that can drastically boost the performance of program irrespective of data structure constraints encountered earlier.
The API that implements these interfaces are now having common sets of methods be it of any interfaces such as Collection, Set, List, and Map.
Note: All these collections can be imported using:
import java.util.*;
However, single classes can also be imported by replacing * with the class name as shown
import java.util.ArrayList;
import java.util.LinkedList;
The following figure illustrates the hierarchy of the collection framework.
Now, discussing and visualizing Collection at the physical level by discussing its hierarchy. The utility package, java.util contains all the classes and interfaces that are required by the collection framework. The collection framework contains an interface named an iterable interface which provides the iterator to iterate through all the collections. This interface is extended by the main collection interface which acts as a root for the collection framework. All the collections extend this collection interface thereby extending the properties of the iterator and the methods of this interface.
Iterable interface is the root interface for the entire collection framework. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections.
The following 6 interfaces are described below first later on been discussed with clean java programs as in implementation.
Collection interface
List interface
Queue interface
Deque interface (Double-ended queue)
Set interface
Map
Collection Interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc. All these methods are implemented in this interface because these methods are implemented by all the classes irrespective of their style of implementation.
It is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collections of the objects. This deals with the index or position-specific functions like getting an element or setting an element. It deals with the arrays and lists types of operations like ArrayList, LinkedList, Vector, and Stack.
1. ArrayList provides us with dynamic arrays in Java. The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection.
Add an Element in an ArrayList
Remove an Element in an ArrayList
Update an Element in an ArrayList
Remove duplicates from an ArrayList
Reverse an ArrayList
Converting ArrayList to String
Getting a sub-list from an ArrayList
For more, go through Java ArrayList
2. LinkedList is class is an implementation of a doubly-linked list data structure.
Access Elements of a LinkedList
Add Elements to a LinkedList
Check if the LinkedList contains the Element
Change Elements of a LinkedList
Remove All Elements from a LinkedList
Iterate over LinkedList using Iterator
For more, go through Java LinkedList
3. Vector provides us with dynamic arrays in Java. This is a legacy class. It is a thread-safe class. This is not recommended being used in a single-threaded environment as it might cause extra overheads. However, to overcome this in Vectors place one can readily use ArrayList.
Adding Elements in Vector
Removing Elements From Vector
Replacing Elements in the Vector
Check if Vector Has Elements or not
Iterating the Vector Elements in Reverse Order
Copying Elements of One Java Vector to Another
Maximum and Minimum Element From Vector
For more, go through Java Vector
4. Stack is a class is based on the basic principle of last-in-first-out. This is a legacy class. This inherits from a Vector class. It is also a thread-safe class. This is not recommended being used in a single-threaded environment as it might cause extra overheads. However, to overcome this in Vectors place one can readily use ArrayDeque.
Check Whether the Stack is Empty or Not
Search Element in Stacks
Access Top Element at the Top of Stack
Add the Element in the Stack
Removing of Element From the Stack
For more, go through Java Stack
5. AbstractList class in Java provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Random Access data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class. It implements the Collection interface and the AbstractCollection class.
6. AbstractSequentialList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “sequential access” data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class. It is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
It is an unordered collection of objects in which duplicate values cannot be stored. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc.
HashSet is an inherent implementation of the hash table data structure or Hashing. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hash code.
Traversing through a HashSet
Printing Elements of a HashSet
Getting Random Element from a HashSet
Finding Maximum and Minimum Element from HashSet
Sorting Elemnets of HashSet
Convert List to HashSet
Convert Array to HashSet
For more, go through Java HashSet
AbstractSet class implements the Collection interface and extends the AbstractCollection class. It provides a skeletal implementation of the Set interface. This class does not override any of the implementations from the AbstractCollection class, but merely adds implementations for equals() and hashCode() method.
CopyOnWriteArraySet uses an internal CopyOnWriteArrayList for all of its operations. It was introduced in JDK 1.5, we can say that it is a thread-safe version of Set. To use this class, we need to import it from ‘java.util.concurrent’ package.
ConcurrentHashMap class is introduced in JDK 1.5 belongs to ‘java.util.concurrent’ package, which implements ConcurrentMap as well as to Serializable interface also. ConcurrentHashMap is an enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance-wise HashMap is not up to the mark.
LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to store the data and retains the ordering of the elements.
Accessing LinkedHashSet elements by Index
Removing elements from a LinkedHashSet
Union of Sets in LinkedHashSets
Difference Between LinkedHashSet, TreeSet, and HashSet
For more go through Java LinkedHashSet
EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type as it extends AbstractSet class and implements Set Interface. It does not allow null objects and is not synchronized resulting in a high-performance Set even faster than HashSet. Also, It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating.
It is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in a sorted manner.
1. TreeSet class is an implementation of the Self-balancing binary tree-like a red-black tree. The ordering of the elements is maintained by a set using their natural ordering.
Difference between EnumSet and TreeSet
Creating a TreeSet with a List
Remove duplicate entries from an array in TreeSet
Getting the Least Value Element From a Set Using Sorting Logic on TreeSet
For more, go through Java TreeSet
2. NavigableSet class inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet.
3. ConcurrentSkipListSet class implements the Collection interface and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java. The implementation of ConcurrentSkipListSet is based on ConcurrentSkipListMap. The elements in ConcurrentSkipListSet are sorted by default in their natural ordering or by a Comparator provided at set creation time, depending on which constructor is used.
Map is a data structure that supports the key-value pair mapping for the data. It is mainly used in the scenarios where Students are needed to be searched or removed or added according to the roll numbers or in item-frequency scenarios where items are stored along with their frequencies.
HashTable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hash table, the objects used as keys must implement the hashCode method and the equals method.
Adding Elements to HashTable
Removing Elements from HashTable
How HashTable Works?
Getting the Size of HashTable
Difference Between HashTable and HashMap
For more, go through Java HashTable
HashMap uses a technique called Hashing. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value in a HashMap, we must know its key.
Add an Element to HashMap
Remove an Element from HashMap
Replace Elements in a HashMap
Sort HashMap by Value
For more, go through Java HashMap
LinkedHashMap is very similar to a HashSet because the primary difference is that this uses a doubly linked list to store the data and retains the ordering of the elements.
Difference between LinkedHashMap vs TreeMap vs HashMap
Hashing in Java
Iterating in a LinkedHashMap
Checking Size of LinkedHashMap
Printing LinkedhashMap Values
Printing LinkedhashMap Keys
Addition of Key-Value Pairs to LinkedHashMap
Sorting LinkedHashMap by Keys
For more, go through Java LinkedHashMap
ConcurrentHashMap class implements ConcurrentMap as well as Serializable interface also. ConcurrentHashMap is an enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance-wise HashMap is not up to the mark.
SortedMap interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). This class implements the TreeMap interface.
NavigableMap interface belongs to ‘java.util‘ package, and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey, and higherKey, and along with this popular navigation method it also provides ways to create a Sub Map from an existing Map in Java. For Example, headMap whose keys are less than the specified key, tailMap whose keys are greater than the specified key, and a subMap that strictly contains keys that fall between toKey and fromKey.
ConcurrentMap interface been introduced in JDK 1.5 represents a Map that is capable of handling concurrent access to it without affecting the consistency of entries in a map. ConcurrentMap interface present in ‘java.util.concurrent package’. It provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map. It has inherited the Nested Interface Map.Entry<K, V>
TreeMap is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the TreeMap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The TreeMap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally.
AbstractMap class directly implements the Map interface to provide a structure to it, by doing so it makes the further implementations easier. As the name suggests AbstractMap is an abstract class by definition, therefore it cannot be used to create objects. The concrete classes that inherit from AbstractMap can be used to create objects.
EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. It belongs to ‘java.util’ package. It is an ordered collection, and they are maintained in the natural order of their keys.
Queue maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter consisting of the PriorityQueue, LinkedList, and ArrayDeque.
ArrayBlockingQueue class is a bounded blocking queue backed by an array. By bounded, it means that the size of the Queue is fixed. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking.
Access the Element from the front of ArrayBlockingQueue
Access Element Sequentially from an ArrayBlockingQueue
Insert the Specified Element to the ArrayBlockingQueue
Insert the Element to the End of an ArrayBlockingQueue
Remove the Element from the Front in ArrayBlockingQueue
Remove specified element in ArrayBlockingQueue
Remove All Elements from ArrayBlockingQueue
Convert ArrayBlockingQueue to an Array
Convert ArrayBlockingQueue to a String
For more, go through Java ArrayBlockingQueue
ArrayDeque is implemented in the collection framework provides us with a way to apply a re-sizable array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue.
Add Elements to ArrayDeque
Access Elements From ArrayDeque
Remove Elements From ArrayDeque
Iterate Through ArrayDeque
For more, go through Java ArrayDeque
AbstractQueue provides skeletal implementations of some queue operations. The implementations in this class are appropriate when the base implementation does not allow null elements. Methods add, remove, and element are based on offer, poll, and peek, respectively, but throw exceptions instead of indicating failure via false or null returns.
BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc. BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either BlockingQueue is full or empty. A thread trying to enqueue an element in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more elements or clearing the queue completely. Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an item. BlockingQueue does not accept a null value. If we try to enqueue the null item, then it throws NullPointerException.
PriorityQueue is based on the priority heap. It is used when the objects are supposed to be processed based on priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority and this class is used in these cases.
To Check the Presence of an Element in a PriorityQueue
Access PriorityQueue using peek() method
Insert Element to PriorityQueue using add() method
Insert Element to PriorityQueue using offer() method
Remove PriorityQueue Elements Using remove() method
Remove PriorityQueue Elements Using poll() method
For more, go through Java PriorityQueue
PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. Since it is unbounded, adding elements may sometimes fail due to resource exhaustion resulting in OutOfMemoryError. This class does not permit null elements.
DelayQueue class belongs to ‘java.util.concurrent’ package implementing the BlockingQueue interface. DelayQueue is a specialized PriorityQueue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired.
ConcurrentLinkedQueue class also belongs to ‘java.util.concurrent’ package. It was introduced in JDK 1.5. It is used to implement Queue with the help of LinkedList concurrently. It is an unbounded thread-safe implementation of Queue which inserts elements at the tail of the Queue in a FIFO(first-in-first-out) fashion. It can be used when an unbounded Queue is shared among many threads. This class does not permit null elements. Iterators are weakly consistent. This class and its iterator implement all of the optional methods of the Queue and Iterator interfaces.
LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue. The tail of this queue is the newest element of the elements of this queue. The newly inserted elements are always inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.
LinkedTransferQueue class again belonging to ‘java.util.concurrent’ package. It implements the TransferQueue and provides an unbounded functionality based on linked nodes. The elements in the LinkedTransferQueue are ordered in FIFO order, with the head pointing to the element that has been on the Queue for the longest time and the tail pointing to the element that has been on the queue for the shortest time. Because of its asynchronous nature, size() traverses the entire collection, so it is not an O(1) time operation. It may also give inaccurate size if this collection is modified during the traversal.
Deque or double-ended queue is a data structure where we can add and remove the elements from both ends of the queue. This interface extends the queue interface. The class which implements this interface namely are LinkedList and ArrayDeque, and Collection class. Here in the Collection class, it has implementation of basic algorithms like binary search, sort(), max(), min(), reverse(), fill(), etc. These algorithms are implemented on the above-mentioned collection frameworks.
ArrayDeque class in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue(Array Deck). This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue.
BlockingDeque interface gets its name because it blocks illegal operations such as insertion into a full queue or deletion from an empty queue, all of these properties are inbuilt into the structure of this interface. Since it is a deque (double-ended queue) that is the insertion, deletion, and traversal operations can be performed from both ends. The BlockingDeque is an interface, so we cannot declare any objects with it.
ConcurrentLinkedDeque class implements the Collection interface and the AbstractCollection class. It belongs to java.util.concurrent package. It is used to implement Deque with the help of LinkedList concurrently. It does not permit null elements and iterators and spliterators are weakly consistent.
Now basic knowledge about the collection to write some basic programs invoking the interfaces with the help of object in the collection is over. It’s time a move a bit deeper down so here a new concept is popularly known as Generics comes into play to jump into. Writing codes with little knowledge is dangerous.
The idea is to allow type (Integer, String, ... etc, and user-defined types) to be a parameter to methods, classes, and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. The generic classes can only be used for Non-primitive types and wrapper classes. Here are the major advantages of Generics in Java:
Write once for any primitive data type as in any generic function code can be written down for computation over non-primitive and later on during compilation these data types are passed in a generic function.It can be class like ArrayList, LinkedList, Stack, Vector, etc. It can be an interface like Set, Map, etc as discussed above, or it can include functions like sort(), max(), min(), etc. Hence, they are extensively used in Collection.They are type-safe as they commit errors at compile time.
Write once for any primitive data type as in any generic function code can be written down for computation over non-primitive and later on during compilation these data types are passed in a generic function.
It can be class like ArrayList, LinkedList, Stack, Vector, etc. It can be an interface like Set, Map, etc as discussed above, or it can include functions like sort(), max(), min(), etc. Hence, they are extensively used in Collection.
They are type-safe as they commit errors at compile time.
Unlike arrays, different instantiations of a generic type is not compatible with each other, not even explicitly. This incompatibility may be softened by the wildcard if ? is used as an actual type parameter.
The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of parameter, field, or local variable; sometimes as a return type.
User cases
Case 1: A simple java program to demonstrate the compile-time errors without the involvement of generics into play. Here ‘ClassCastException‘ is thrown by the program
Case 2: Generic concept been introduced though it will not append output illustrating incompatible type-casting of data types.
Case 3: Working of a generic function.
Case 4: Wildcards been introduced in java but still will throw an exception at the runtime.
Case 5: Wildcard implementation in generics
Example:
Java
Java
Java
Java
Java
Output:
Case 1
Case 2
Case 3
Case 4
Case 5
Wildcard in generics is must Geek
Now jumping to the most important topic along with which most concepts revolve during implementation, yes you guess it right geek Collection interface. The Collection is the root interface for most of the interfaces in the Collection framework in Java
Therefore, Collection has sub-interfaces like Set, List, and Queue which implements the Collection interface which in turn is inherited from the Iterable interface. This is the root interface for the entire collection framework. The Collection interface extends the Iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator. It returns the
Iterator iterator();
Now, dwelling onto different methods present in Collection such as add(), removes(), removeAll(), contains(), containsAll(), stream() and many more. In order to use so, one has to get a clear understanding of the same. Let’s peek out for various functions causing bulk operations namely
containsAll() MethodaddAll() MethodremoveAll() MethodretainAll() Method
containsAll() Method
addAll() Method
removeAll() Method
retainAll() Method
Function 1: containsAll() Method
boolean containsAll(Collection c)
This method takes a collection c and checks whether all the elements of c is present in this Collection or not. The method returns True if all elements in the collection c, are present in this Collection otherwise it returns False.
Function 2: addAll() Method
boolean addAll(Collection c)
This method is used to append all the elements from the collection c passed as a parameter to the end of this collection keeping in mind the order of return by the collection’s iterator. The method returns true if at least one action of append is performed.
Function 3: removeAll() Method
boolean removeAll(Collection c)
This method is used to remove from this collection all of its elements that are contained in the specified collection c. This method returns true if this list changed as a result of the call. This method uses a wildcard character signifying that a collection of any data types can be passed into the removeAll() method. These are the methods been most frequently used.
Function 4: retainAll() Method
This method of ArrayList is used to remove all the array list’s elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method.
public boolean retainAll(Collection C)
Rest there are other methods to been put in the usage such as removeIf() and retainAll(). Do visit them thoroughly in order to get a better understanding of them too before we now finally end up this article with iterating through Collections. Let’s try to implement a few of them to get a better understanding of them.
Examples:
Java
Java
Java
Java
Output:
Method 1:
true
Method 2:
[10, 20, 30, 40, 40, 50]
Method 3:
[30]
Method 4:
[10, 20]
Now lets us discuss all the methods been proposed for iteration are as follows:
Iterators MethodFor-each loop MethodforEach() MethodStreams Method
Iterators Method
For-each loop Method
forEach() Method
Streams Method
There are various ways of traversing through a collection namely:
Method 1: Iterators Method
The Iterable interface provides an iterator() method which implements the Iterator interface. The iterator interface provides 3 functions(hasNext(), next(), remove()) which are used to iterate through the collection and also remove elements from the collection. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator.
Method 2: For-each loop Method
For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList).
for (type var : array)
{
statements using var;
}
Method 3: forEach() is also present in the Iterable interface. Therefore, it can be implemented by all the collections in the framework that extends the Iterable interface. Whenever is needed to traverse over a collection we have to create an Iterator to iterate over the collection, and then we can have our business logic inside a loop for each of the elements inside the collection.
public void forEach(Consumer action)
Method 4: Streams Method is the most recommended method to traverse through a collection or perform any operation of filter or segregation. This was added in Java 8. There are several benefits of using stream:
It can be parallel and infinite.
No storage.
Functions can be pipelined.
The most important benefit of Streams is that we can create them from the collection, arrays, Files Lines, and even from methods in Stream.
Examples:
Java
Java
Java
Output:
Method 1:
10 15 7 20 40
Method 2:
10
15
7
20
40
Method 3:
10 15 7 20 40
20 40
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021 | [
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 27665,
"s": 27219,
"text": "Java Collection Framework is unlikely any group of individual objects which are represented as a single unit be it of any type is known as the collection of objects. Earlier in Java, there was no such thing defined which holds true for it so there arises a need in the next versions of any such concept. So in JDK 1.2, a separate framework was defined known as “Collection Framework” which holds all the collection classes and interfaces in it. "
},
{
"code": null,
"e": 27810,
"s": 27665,
"text": "The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes."
},
{
"code": null,
"e": 27831,
"s": 27810,
"text": "What is a Framework?"
},
{
"code": null,
"e": 28164,
"s": 27831,
"text": "A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task."
},
{
"code": null,
"e": 28205,
"s": 28164,
"text": "Need for a Separate Collection Framework"
},
{
"code": null,
"e": 28737,
"s": 28205,
"text": "Before Collection Framework(or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these collections had no common interface. Therefore, though the main aim of all the collections is the same, the implementation of all these collections was defined independently and had no correlation among them. And also, it is very difficult for the users to remember all the different methods, syntax, and constructors present in every collection class."
},
{
"code": null,
"e": 28837,
"s": 28737,
"text": "Are you confused between Collection, Collection Interface, Collections Class, Collection Framework?"
},
{
"code": null,
"e": 29090,
"s": 28837,
"text": "Collection: A group of individual objects that represent a single entity is known as a collection. It is the common word that you used in your daily life. But if we are discussing Java programming language then it will become Java Collection Framework."
},
{
"code": null,
"e": 29401,
"s": 29090,
"text": "Collection Framework: To represent a group of objects as a single entity in the Java programming language we need classes and interfaces defined by the Collection Framework. If are from C++ background that you can compare Collection with Containers and Collection Framework with STL(Standard Template Library)."
},
{
"code": null,
"e": 29716,
"s": 29401,
"text": "Collection Interface: Interfaces specify what a class must do and not how. It is the blueprint of the class. It is the root interface of the Collection Framework that defines the most common methods that can be used for any collection objects. Or you can say it represents the individual object as a single entity."
},
{
"code": null,
"e": 29879,
"s": 29716,
"text": "Collections Class: It is present in java.util package and is a member of Collection Framework. This class provides many utility methods for the collection object."
},
{
"code": null,
"e": 30111,
"s": 29879,
"text": "Now you must be wondering why to include such a concept or what difficulties were faced before java version 1.2 that lead birth to the concept of Collection. In order to figure it out, the three main advantages are mentioned below:"
},
{
"code": null,
"e": 30859,
"s": 30111,
"text": "Reduces the programming effort as the programmer does not have to worry about designing the Collection class and on the same hand java being object-oriented language advances in achieving abstraction by not writing the Collection class.Increases program speed and quality as the programmer now is not worried about thinking best implementation for a specific data structure as of now for a programmer scope widens up and at the same time is now only worried about the best implementation that can drastically boost the performance of program irrespective of data structure constraints encountered earlier.The API that implements these interfaces are now having common sets of methods be it of any interfaces such as Collection, Set, List, and Map."
},
{
"code": null,
"e": 31096,
"s": 30859,
"text": "Reduces the programming effort as the programmer does not have to worry about designing the Collection class and on the same hand java being object-oriented language advances in achieving abstraction by not writing the Collection class."
},
{
"code": null,
"e": 31466,
"s": 31096,
"text": "Increases program speed and quality as the programmer now is not worried about thinking best implementation for a specific data structure as of now for a programmer scope widens up and at the same time is now only worried about the best implementation that can drastically boost the performance of program irrespective of data structure constraints encountered earlier."
},
{
"code": null,
"e": 31609,
"s": 31466,
"text": "The API that implements these interfaces are now having common sets of methods be it of any interfaces such as Collection, Set, List, and Map."
},
{
"code": null,
"e": 31660,
"s": 31609,
"text": "Note: All these collections can be imported using:"
},
{
"code": null,
"e": 31680,
"s": 31660,
"text": "import java.util.*;"
},
{
"code": null,
"e": 31769,
"s": 31680,
"text": "However, single classes can also be imported by replacing * with the class name as shown"
},
{
"code": null,
"e": 31826,
"s": 31769,
"text": "import java.util.ArrayList;\nimport java.util.LinkedList;"
},
{
"code": null,
"e": 31902,
"s": 31826,
"text": "The following figure illustrates the hierarchy of the collection framework."
},
{
"code": null,
"e": 32506,
"s": 31902,
"text": "Now, discussing and visualizing Collection at the physical level by discussing its hierarchy. The utility package, java.util contains all the classes and interfaces that are required by the collection framework. The collection framework contains an interface named an iterable interface which provides the iterator to iterate through all the collections. This interface is extended by the main collection interface which acts as a root for the collection framework. All the collections extend this collection interface thereby extending the properties of the iterator and the methods of this interface. "
},
{
"code": null,
"e": 32810,
"s": 32506,
"text": "Iterable interface is the root interface for the entire collection framework. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. "
},
{
"code": null,
"e": 32934,
"s": 32810,
"text": "The following 6 interfaces are described below first later on been discussed with clean java programs as in implementation."
},
{
"code": null,
"e": 32955,
"s": 32934,
"text": "Collection interface"
},
{
"code": null,
"e": 32970,
"s": 32955,
"text": "List interface"
},
{
"code": null,
"e": 32986,
"s": 32970,
"text": "Queue interface"
},
{
"code": null,
"e": 33023,
"s": 32986,
"text": "Deque interface (Double-ended queue)"
},
{
"code": null,
"e": 33037,
"s": 33023,
"text": "Set interface"
},
{
"code": null,
"e": 33041,
"s": 33037,
"text": "Map"
},
{
"code": null,
"e": 33361,
"s": 33041,
"text": "Collection Interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc. All these methods are implemented in this interface because these methods are implemented by all the classes irrespective of their style of implementation."
},
{
"code": null,
"e": 33743,
"s": 33361,
"text": "It is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collections of the objects. This deals with the index or position-specific functions like getting an element or setting an element. It deals with the arrays and lists types of operations like ArrayList, LinkedList, Vector, and Stack."
},
{
"code": null,
"e": 33932,
"s": 33743,
"text": "1. ArrayList provides us with dynamic arrays in Java. The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection."
},
{
"code": null,
"e": 33963,
"s": 33932,
"text": "Add an Element in an ArrayList"
},
{
"code": null,
"e": 33997,
"s": 33963,
"text": "Remove an Element in an ArrayList"
},
{
"code": null,
"e": 34031,
"s": 33997,
"text": "Update an Element in an ArrayList"
},
{
"code": null,
"e": 34067,
"s": 34031,
"text": "Remove duplicates from an ArrayList"
},
{
"code": null,
"e": 34088,
"s": 34067,
"text": "Reverse an ArrayList"
},
{
"code": null,
"e": 34119,
"s": 34088,
"text": "Converting ArrayList to String"
},
{
"code": null,
"e": 34156,
"s": 34119,
"text": "Getting a sub-list from an ArrayList"
},
{
"code": null,
"e": 34192,
"s": 34156,
"text": "For more, go through Java ArrayList"
},
{
"code": null,
"e": 34276,
"s": 34192,
"text": "2. LinkedList is class is an implementation of a doubly-linked list data structure."
},
{
"code": null,
"e": 34309,
"s": 34276,
"text": "Access Elements of a LinkedList "
},
{
"code": null,
"e": 34338,
"s": 34309,
"text": "Add Elements to a LinkedList"
},
{
"code": null,
"e": 34384,
"s": 34338,
"text": "Check if the LinkedList contains the Element "
},
{
"code": null,
"e": 34416,
"s": 34384,
"text": "Change Elements of a LinkedList"
},
{
"code": null,
"e": 34455,
"s": 34416,
"text": "Remove All Elements from a LinkedList "
},
{
"code": null,
"e": 34494,
"s": 34455,
"text": "Iterate over LinkedList using Iterator"
},
{
"code": null,
"e": 34531,
"s": 34494,
"text": "For more, go through Java LinkedList"
},
{
"code": null,
"e": 34810,
"s": 34531,
"text": "3. Vector provides us with dynamic arrays in Java. This is a legacy class. It is a thread-safe class. This is not recommended being used in a single-threaded environment as it might cause extra overheads. However, to overcome this in Vectors place one can readily use ArrayList."
},
{
"code": null,
"e": 34836,
"s": 34810,
"text": "Adding Elements in Vector"
},
{
"code": null,
"e": 34866,
"s": 34836,
"text": "Removing Elements From Vector"
},
{
"code": null,
"e": 34899,
"s": 34866,
"text": "Replacing Elements in the Vector"
},
{
"code": null,
"e": 34935,
"s": 34899,
"text": "Check if Vector Has Elements or not"
},
{
"code": null,
"e": 34982,
"s": 34935,
"text": "Iterating the Vector Elements in Reverse Order"
},
{
"code": null,
"e": 35029,
"s": 34982,
"text": "Copying Elements of One Java Vector to Another"
},
{
"code": null,
"e": 35069,
"s": 35029,
"text": "Maximum and Minimum Element From Vector"
},
{
"code": null,
"e": 35102,
"s": 35069,
"text": "For more, go through Java Vector"
},
{
"code": null,
"e": 35445,
"s": 35102,
"text": "4. Stack is a class is based on the basic principle of last-in-first-out. This is a legacy class. This inherits from a Vector class. It is also a thread-safe class. This is not recommended being used in a single-threaded environment as it might cause extra overheads. However, to overcome this in Vectors place one can readily use ArrayDeque."
},
{
"code": null,
"e": 35485,
"s": 35445,
"text": "Check Whether the Stack is Empty or Not"
},
{
"code": null,
"e": 35510,
"s": 35485,
"text": "Search Element in Stacks"
},
{
"code": null,
"e": 35550,
"s": 35510,
"text": "Access Top Element at the Top of Stack "
},
{
"code": null,
"e": 35579,
"s": 35550,
"text": "Add the Element in the Stack"
},
{
"code": null,
"e": 35614,
"s": 35579,
"text": "Removing of Element From the Stack"
},
{
"code": null,
"e": 35646,
"s": 35614,
"text": "For more, go through Java Stack"
},
{
"code": null,
"e": 36042,
"s": 35646,
"text": "5. AbstractList class in Java provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Random Access data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class. It implements the Collection interface and the AbstractCollection class."
},
{
"code": null,
"e": 36517,
"s": 36042,
"text": "6. AbstractSequentialList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “sequential access” data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class. It is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods."
},
{
"code": null,
"e": 36698,
"s": 36517,
"text": "It is an unordered collection of objects in which duplicate values cannot be stored. This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc."
},
{
"code": null,
"e": 36927,
"s": 36698,
"text": "HashSet is an inherent implementation of the hash table data structure or Hashing. The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hash code."
},
{
"code": null,
"e": 36956,
"s": 36927,
"text": "Traversing through a HashSet"
},
{
"code": null,
"e": 36987,
"s": 36956,
"text": "Printing Elements of a HashSet"
},
{
"code": null,
"e": 37025,
"s": 36987,
"text": "Getting Random Element from a HashSet"
},
{
"code": null,
"e": 37074,
"s": 37025,
"text": "Finding Maximum and Minimum Element from HashSet"
},
{
"code": null,
"e": 37102,
"s": 37074,
"text": "Sorting Elemnets of HashSet"
},
{
"code": null,
"e": 37126,
"s": 37102,
"text": "Convert List to HashSet"
},
{
"code": null,
"e": 37152,
"s": 37126,
"text": "Convert Array to HashSet "
},
{
"code": null,
"e": 37186,
"s": 37152,
"text": "For more, go through Java HashSet"
},
{
"code": null,
"e": 37501,
"s": 37186,
"text": "AbstractSet class implements the Collection interface and extends the AbstractCollection class. It provides a skeletal implementation of the Set interface. This class does not override any of the implementations from the AbstractCollection class, but merely adds implementations for equals() and hashCode() method."
},
{
"code": null,
"e": 37745,
"s": 37501,
"text": "CopyOnWriteArraySet uses an internal CopyOnWriteArrayList for all of its operations. It was introduced in JDK 1.5, we can say that it is a thread-safe version of Set. To use this class, we need to import it from ‘java.util.concurrent’ package."
},
{
"code": null,
"e": 38105,
"s": 37745,
"text": "ConcurrentHashMap class is introduced in JDK 1.5 belongs to ‘java.util.concurrent’ package, which implements ConcurrentMap as well as to Serializable interface also. ConcurrentHashMap is an enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance-wise HashMap is not up to the mark."
},
{
"code": null,
"e": 38263,
"s": 38105,
"text": "LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to store the data and retains the ordering of the elements."
},
{
"code": null,
"e": 38305,
"s": 38263,
"text": "Accessing LinkedHashSet elements by Index"
},
{
"code": null,
"e": 38344,
"s": 38305,
"text": "Removing elements from a LinkedHashSet"
},
{
"code": null,
"e": 38376,
"s": 38344,
"text": "Union of Sets in LinkedHashSets"
},
{
"code": null,
"e": 38431,
"s": 38376,
"text": "Difference Between LinkedHashSet, TreeSet, and HashSet"
},
{
"code": null,
"e": 38470,
"s": 38431,
"text": "For more go through Java LinkedHashSet"
},
{
"code": null,
"e": 38887,
"s": 38470,
"text": "EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type as it extends AbstractSet class and implements Set Interface. It does not allow null objects and is not synchronized resulting in a high-performance Set even faster than HashSet. Also, It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating."
},
{
"code": null,
"e": 39210,
"s": 38887,
"text": "It is present in java.util package extends the Set interface present in the collection framework. It is an interface that implements the mathematical set. This interface contains the methods inherited from the Set interface and adds a feature that stores all the elements in this interface to be stored in a sorted manner."
},
{
"code": null,
"e": 39387,
"s": 39210,
"text": "1. TreeSet class is an implementation of the Self-balancing binary tree-like a red-black tree. The ordering of the elements is maintained by a set using their natural ordering."
},
{
"code": null,
"e": 39426,
"s": 39387,
"text": "Difference between EnumSet and TreeSet"
},
{
"code": null,
"e": 39457,
"s": 39426,
"text": "Creating a TreeSet with a List"
},
{
"code": null,
"e": 39507,
"s": 39457,
"text": "Remove duplicate entries from an array in TreeSet"
},
{
"code": null,
"e": 39581,
"s": 39507,
"text": "Getting the Least Value Element From a Set Using Sorting Logic on TreeSet"
},
{
"code": null,
"e": 39615,
"s": 39581,
"text": "For more, go through Java TreeSet"
},
{
"code": null,
"e": 39821,
"s": 39615,
"text": "2. NavigableSet class inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet."
},
{
"code": null,
"e": 40241,
"s": 39821,
"text": "3. ConcurrentSkipListSet class implements the Collection interface and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java. The implementation of ConcurrentSkipListSet is based on ConcurrentSkipListMap. The elements in ConcurrentSkipListSet are sorted by default in their natural ordering or by a Comparator provided at set creation time, depending on which constructor is used."
},
{
"code": null,
"e": 40530,
"s": 40241,
"text": "Map is a data structure that supports the key-value pair mapping for the data. It is mainly used in the scenarios where Students are needed to be searched or removed or added according to the roll numbers or in item-frequency scenarios where items are stored along with their frequencies."
},
{
"code": null,
"e": 40799,
"s": 40530,
"text": "HashTable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hash table, the objects used as keys must implement the hashCode method and the equals method."
},
{
"code": null,
"e": 40828,
"s": 40799,
"text": "Adding Elements to HashTable"
},
{
"code": null,
"e": 40861,
"s": 40828,
"text": "Removing Elements from HashTable"
},
{
"code": null,
"e": 40882,
"s": 40861,
"text": "How HashTable Works?"
},
{
"code": null,
"e": 40912,
"s": 40882,
"text": "Getting the Size of HashTable"
},
{
"code": null,
"e": 40954,
"s": 40912,
"text": "Difference Between HashTable and HashMap "
},
{
"code": null,
"e": 40990,
"s": 40954,
"text": "For more, go through Java HashTable"
},
{
"code": null,
"e": 41194,
"s": 40990,
"text": "HashMap uses a technique called Hashing. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value in a HashMap, we must know its key."
},
{
"code": null,
"e": 41220,
"s": 41194,
"text": "Add an Element to HashMap"
},
{
"code": null,
"e": 41251,
"s": 41220,
"text": "Remove an Element from HashMap"
},
{
"code": null,
"e": 41281,
"s": 41251,
"text": "Replace Elements in a HashMap"
},
{
"code": null,
"e": 41303,
"s": 41281,
"text": "Sort HashMap by Value"
},
{
"code": null,
"e": 41337,
"s": 41303,
"text": "For more, go through Java HashMap"
},
{
"code": null,
"e": 41510,
"s": 41337,
"text": "LinkedHashMap is very similar to a HashSet because the primary difference is that this uses a doubly linked list to store the data and retains the ordering of the elements."
},
{
"code": null,
"e": 41565,
"s": 41510,
"text": "Difference between LinkedHashMap vs TreeMap vs HashMap"
},
{
"code": null,
"e": 41581,
"s": 41565,
"text": "Hashing in Java"
},
{
"code": null,
"e": 41610,
"s": 41581,
"text": "Iterating in a LinkedHashMap"
},
{
"code": null,
"e": 41641,
"s": 41610,
"text": "Checking Size of LinkedHashMap"
},
{
"code": null,
"e": 41671,
"s": 41641,
"text": "Printing LinkedhashMap Values"
},
{
"code": null,
"e": 41699,
"s": 41671,
"text": "Printing LinkedhashMap Keys"
},
{
"code": null,
"e": 41744,
"s": 41699,
"text": "Addition of Key-Value Pairs to LinkedHashMap"
},
{
"code": null,
"e": 41774,
"s": 41744,
"text": "Sorting LinkedHashMap by Keys"
},
{
"code": null,
"e": 41814,
"s": 41774,
"text": "For more, go through Java LinkedHashMap"
},
{
"code": null,
"e": 42097,
"s": 41814,
"text": "ConcurrentHashMap class implements ConcurrentMap as well as Serializable interface also. ConcurrentHashMap is an enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance-wise HashMap is not up to the mark."
},
{
"code": null,
"e": 42287,
"s": 42097,
"text": "SortedMap interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). This class implements the TreeMap interface."
},
{
"code": null,
"e": 42791,
"s": 42287,
"text": "NavigableMap interface belongs to ‘java.util‘ package, and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey, and higherKey, and along with this popular navigation method it also provides ways to create a Sub Map from an existing Map in Java. For Example, headMap whose keys are less than the specified key, tailMap whose keys are greater than the specified key, and a subMap that strictly contains keys that fall between toKey and fromKey."
},
{
"code": null,
"e": 43190,
"s": 42791,
"text": "ConcurrentMap interface been introduced in JDK 1.5 represents a Map that is capable of handling concurrent access to it without affecting the consistency of entries in a map. ConcurrentMap interface present in ‘java.util.concurrent package’. It provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map. It has inherited the Nested Interface Map.Entry<K, V>"
},
{
"code": null,
"e": 43890,
"s": 43190,
"text": "TreeMap is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the TreeMap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The TreeMap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally."
},
{
"code": null,
"e": 44231,
"s": 43890,
"text": "AbstractMap class directly implements the Map interface to provide a structure to it, by doing so it makes the further implementations easier. As the name suggests AbstractMap is an abstract class by definition, therefore it cannot be used to create objects. The concrete classes that inherit from AbstractMap can be used to create objects."
},
{
"code": null,
"e": 44504,
"s": 44231,
"text": "EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. It belongs to ‘java.util’ package. It is an ordered collection, and they are maintained in the natural order of their keys."
},
{
"code": null,
"e": 44747,
"s": 44504,
"text": "Queue maintains the FIFO(First In First Out) order similar to a real-world queue line. This interface is dedicated to storing all the elements where the order of the elements matter consisting of the PriorityQueue, LinkedList, and ArrayDeque."
},
{
"code": null,
"e": 45008,
"s": 44747,
"text": "ArrayBlockingQueue class is a bounded blocking queue backed by an array. By bounded, it means that the size of the Queue is fixed. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking."
},
{
"code": null,
"e": 45064,
"s": 45008,
"text": "Access the Element from the front of ArrayBlockingQueue"
},
{
"code": null,
"e": 45119,
"s": 45064,
"text": "Access Element Sequentially from an ArrayBlockingQueue"
},
{
"code": null,
"e": 45174,
"s": 45119,
"text": "Insert the Specified Element to the ArrayBlockingQueue"
},
{
"code": null,
"e": 45229,
"s": 45174,
"text": "Insert the Element to the End of an ArrayBlockingQueue"
},
{
"code": null,
"e": 45285,
"s": 45229,
"text": "Remove the Element from the Front in ArrayBlockingQueue"
},
{
"code": null,
"e": 45332,
"s": 45285,
"text": "Remove specified element in ArrayBlockingQueue"
},
{
"code": null,
"e": 45376,
"s": 45332,
"text": "Remove All Elements from ArrayBlockingQueue"
},
{
"code": null,
"e": 45415,
"s": 45376,
"text": "Convert ArrayBlockingQueue to an Array"
},
{
"code": null,
"e": 45454,
"s": 45415,
"text": "Convert ArrayBlockingQueue to a String"
},
{
"code": null,
"e": 45499,
"s": 45454,
"text": "For more, go through Java ArrayBlockingQueue"
},
{
"code": null,
"e": 45723,
"s": 45499,
"text": "ArrayDeque is implemented in the collection framework provides us with a way to apply a re-sizable array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue."
},
{
"code": null,
"e": 45750,
"s": 45723,
"text": "Add Elements to ArrayDeque"
},
{
"code": null,
"e": 45782,
"s": 45750,
"text": "Access Elements From ArrayDeque"
},
{
"code": null,
"e": 45814,
"s": 45782,
"text": "Remove Elements From ArrayDeque"
},
{
"code": null,
"e": 45841,
"s": 45814,
"text": "Iterate Through ArrayDeque"
},
{
"code": null,
"e": 45878,
"s": 45841,
"text": "For more, go through Java ArrayDeque"
},
{
"code": null,
"e": 46223,
"s": 45878,
"text": "AbstractQueue provides skeletal implementations of some queue operations. The implementations in this class are appropriate when the base implementation does not allow null elements. Methods add, remove, and element are based on offer, poll, and peek, respectively, but throw exceptions instead of indicating failure via false or null returns. "
},
{
"code": null,
"e": 46950,
"s": 46223,
"text": "BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc. BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either BlockingQueue is full or empty. A thread trying to enqueue an element in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more elements or clearing the queue completely. Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an item. BlockingQueue does not accept a null value. If we try to enqueue the null item, then it throws NullPointerException."
},
{
"code": null,
"e": 47270,
"s": 46950,
"text": "PriorityQueue is based on the priority heap. It is used when the objects are supposed to be processed based on priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority and this class is used in these cases."
},
{
"code": null,
"e": 47325,
"s": 47270,
"text": "To Check the Presence of an Element in a PriorityQueue"
},
{
"code": null,
"e": 47366,
"s": 47325,
"text": "Access PriorityQueue using peek() method"
},
{
"code": null,
"e": 47417,
"s": 47366,
"text": "Insert Element to PriorityQueue using add() method"
},
{
"code": null,
"e": 47470,
"s": 47417,
"text": "Insert Element to PriorityQueue using offer() method"
},
{
"code": null,
"e": 47522,
"s": 47470,
"text": "Remove PriorityQueue Elements Using remove() method"
},
{
"code": null,
"e": 47572,
"s": 47522,
"text": "Remove PriorityQueue Elements Using poll() method"
},
{
"code": null,
"e": 47612,
"s": 47572,
"text": "For more, go through Java PriorityQueue"
},
{
"code": null,
"e": 47924,
"s": 47612,
"text": "PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. Since it is unbounded, adding elements may sometimes fail due to resource exhaustion resulting in OutOfMemoryError. This class does not permit null elements."
},
{
"code": null,
"e": 48201,
"s": 47924,
"text": "DelayQueue class belongs to ‘java.util.concurrent’ package implementing the BlockingQueue interface. DelayQueue is a specialized PriorityQueue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired."
},
{
"code": null,
"e": 48770,
"s": 48201,
"text": "ConcurrentLinkedQueue class also belongs to ‘java.util.concurrent’ package. It was introduced in JDK 1.5. It is used to implement Queue with the help of LinkedList concurrently. It is an unbounded thread-safe implementation of Queue which inserts elements at the tail of the Queue in a FIFO(first-in-first-out) fashion. It can be used when an unbounded Queue is shared among many threads. This class does not permit null elements. Iterators are weakly consistent. This class and its iterator implement all of the optional methods of the Queue and Iterator interfaces. "
},
{
"code": null,
"e": 49444,
"s": 48770,
"text": "LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue. The tail of this queue is the newest element of the elements of this queue. The newly inserted elements are always inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue."
},
{
"code": null,
"e": 50055,
"s": 49444,
"text": "LinkedTransferQueue class again belonging to ‘java.util.concurrent’ package. It implements the TransferQueue and provides an unbounded functionality based on linked nodes. The elements in the LinkedTransferQueue are ordered in FIFO order, with the head pointing to the element that has been on the Queue for the longest time and the tail pointing to the element that has been on the queue for the shortest time. Because of its asynchronous nature, size() traverses the entire collection, so it is not an O(1) time operation. It may also give inaccurate size if this collection is modified during the traversal."
},
{
"code": null,
"e": 50536,
"s": 50055,
"text": "Deque or double-ended queue is a data structure where we can add and remove the elements from both ends of the queue. This interface extends the queue interface. The class which implements this interface namely are LinkedList and ArrayDeque, and Collection class. Here in the Collection class, it has implementation of basic algorithms like binary search, sort(), max(), min(), reverse(), fill(), etc. These algorithms are implemented on the above-mentioned collection frameworks."
},
{
"code": null,
"e": 50835,
"s": 50536,
"text": "ArrayDeque class in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue(Array Deck). This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue."
},
{
"code": null,
"e": 51262,
"s": 50835,
"text": "BlockingDeque interface gets its name because it blocks illegal operations such as insertion into a full queue or deletion from an empty queue, all of these properties are inbuilt into the structure of this interface. Since it is a deque (double-ended queue) that is the insertion, deletion, and traversal operations can be performed from both ends. The BlockingDeque is an interface, so we cannot declare any objects with it."
},
{
"code": null,
"e": 51563,
"s": 51262,
"text": "ConcurrentLinkedDeque class implements the Collection interface and the AbstractCollection class. It belongs to java.util.concurrent package. It is used to implement Deque with the help of LinkedList concurrently. It does not permit null elements and iterators and spliterators are weakly consistent."
},
{
"code": null,
"e": 51877,
"s": 51563,
"text": "Now basic knowledge about the collection to write some basic programs invoking the interfaces with the help of object in the collection is over. It’s time a move a bit deeper down so here a new concept is popularly known as Generics comes into play to jump into. Writing codes with little knowledge is dangerous. "
},
{
"code": null,
"e": 52225,
"s": 51877,
"text": "The idea is to allow type (Integer, String, ... etc, and user-defined types) to be a parameter to methods, classes, and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. The generic classes can only be used for Non-primitive types and wrapper classes. Here are the major advantages of Generics in Java:"
},
{
"code": null,
"e": 52724,
"s": 52225,
"text": "Write once for any primitive data type as in any generic function code can be written down for computation over non-primitive and later on during compilation these data types are passed in a generic function.It can be class like ArrayList, LinkedList, Stack, Vector, etc. It can be an interface like Set, Map, etc as discussed above, or it can include functions like sort(), max(), min(), etc. Hence, they are extensively used in Collection.They are type-safe as they commit errors at compile time."
},
{
"code": null,
"e": 52933,
"s": 52724,
"text": "Write once for any primitive data type as in any generic function code can be written down for computation over non-primitive and later on during compilation these data types are passed in a generic function."
},
{
"code": null,
"e": 53167,
"s": 52933,
"text": "It can be class like ArrayList, LinkedList, Stack, Vector, etc. It can be an interface like Set, Map, etc as discussed above, or it can include functions like sort(), max(), min(), etc. Hence, they are extensively used in Collection."
},
{
"code": null,
"e": 53225,
"s": 53167,
"text": "They are type-safe as they commit errors at compile time."
},
{
"code": null,
"e": 53434,
"s": 53225,
"text": "Unlike arrays, different instantiations of a generic type is not compatible with each other, not even explicitly. This incompatibility may be softened by the wildcard if ? is used as an actual type parameter."
},
{
"code": null,
"e": 53673,
"s": 53434,
"text": "The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of parameter, field, or local variable; sometimes as a return type."
},
{
"code": null,
"e": 53684,
"s": 53673,
"text": "User cases"
},
{
"code": null,
"e": 53851,
"s": 53684,
"text": "Case 1: A simple java program to demonstrate the compile-time errors without the involvement of generics into play. Here ‘ClassCastException‘ is thrown by the program"
},
{
"code": null,
"e": 53978,
"s": 53851,
"text": "Case 2: Generic concept been introduced though it will not append output illustrating incompatible type-casting of data types."
},
{
"code": null,
"e": 54017,
"s": 53978,
"text": "Case 3: Working of a generic function."
},
{
"code": null,
"e": 54109,
"s": 54017,
"text": "Case 4: Wildcards been introduced in java but still will throw an exception at the runtime."
},
{
"code": null,
"e": 54153,
"s": 54109,
"text": "Case 5: Wildcard implementation in generics"
},
{
"code": null,
"e": 54162,
"s": 54153,
"text": "Example:"
},
{
"code": null,
"e": 54167,
"s": 54162,
"text": "Java"
},
{
"code": null,
"e": 54172,
"s": 54167,
"text": "Java"
},
{
"code": null,
"e": 54177,
"s": 54172,
"text": "Java"
},
{
"code": null,
"e": 54182,
"s": 54177,
"text": "Java"
},
{
"code": null,
"e": 54187,
"s": 54182,
"text": "Java"
},
{
"code": null,
"e": 54195,
"s": 54187,
"text": "Output:"
},
{
"code": null,
"e": 54202,
"s": 54195,
"text": "Case 1"
},
{
"code": null,
"e": 54209,
"s": 54202,
"text": "Case 2"
},
{
"code": null,
"e": 54216,
"s": 54209,
"text": "Case 3"
},
{
"code": null,
"e": 54223,
"s": 54216,
"text": "Case 4"
},
{
"code": null,
"e": 54230,
"s": 54223,
"text": "Case 5"
},
{
"code": null,
"e": 54264,
"s": 54230,
"text": "Wildcard in generics is must Geek"
},
{
"code": null,
"e": 54516,
"s": 54264,
"text": "Now jumping to the most important topic along with which most concepts revolve during implementation, yes you guess it right geek Collection interface. The Collection is the root interface for most of the interfaces in the Collection framework in Java"
},
{
"code": null,
"e": 55070,
"s": 54516,
"text": "Therefore, Collection has sub-interfaces like Set, List, and Queue which implements the Collection interface which in turn is inherited from the Iterable interface. This is the root interface for the entire collection framework. The Collection interface extends the Iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator. It returns the "
},
{
"code": null,
"e": 55091,
"s": 55070,
"text": "Iterator iterator();"
},
{
"code": null,
"e": 55378,
"s": 55091,
"text": "Now, dwelling onto different methods present in Collection such as add(), removes(), removeAll(), contains(), containsAll(), stream() and many more. In order to use so, one has to get a clear understanding of the same. Let’s peek out for various functions causing bulk operations namely"
},
{
"code": null,
"e": 55450,
"s": 55378,
"text": "containsAll() MethodaddAll() MethodremoveAll() MethodretainAll() Method"
},
{
"code": null,
"e": 55471,
"s": 55450,
"text": "containsAll() Method"
},
{
"code": null,
"e": 55487,
"s": 55471,
"text": "addAll() Method"
},
{
"code": null,
"e": 55506,
"s": 55487,
"text": "removeAll() Method"
},
{
"code": null,
"e": 55525,
"s": 55506,
"text": "retainAll() Method"
},
{
"code": null,
"e": 55558,
"s": 55525,
"text": "Function 1: containsAll() Method"
},
{
"code": null,
"e": 55592,
"s": 55558,
"text": "boolean containsAll(Collection c)"
},
{
"code": null,
"e": 55824,
"s": 55592,
"text": "This method takes a collection c and checks whether all the elements of c is present in this Collection or not. The method returns True if all elements in the collection c, are present in this Collection otherwise it returns False."
},
{
"code": null,
"e": 55852,
"s": 55824,
"text": "Function 2: addAll() Method"
},
{
"code": null,
"e": 55881,
"s": 55852,
"text": "boolean addAll(Collection c)"
},
{
"code": null,
"e": 56139,
"s": 55881,
"text": "This method is used to append all the elements from the collection c passed as a parameter to the end of this collection keeping in mind the order of return by the collection’s iterator. The method returns true if at least one action of append is performed."
},
{
"code": null,
"e": 56170,
"s": 56139,
"text": "Function 3: removeAll() Method"
},
{
"code": null,
"e": 56202,
"s": 56170,
"text": "boolean removeAll(Collection c)"
},
{
"code": null,
"e": 56571,
"s": 56202,
"text": "This method is used to remove from this collection all of its elements that are contained in the specified collection c. This method returns true if this list changed as a result of the call. This method uses a wildcard character signifying that a collection of any data types can be passed into the removeAll() method. These are the methods been most frequently used."
},
{
"code": null,
"e": 56602,
"s": 56571,
"text": "Function 4: retainAll() Method"
},
{
"code": null,
"e": 56879,
"s": 56602,
"text": "This method of ArrayList is used to remove all the array list’s elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method."
},
{
"code": null,
"e": 56918,
"s": 56879,
"text": "public boolean retainAll(Collection C)"
},
{
"code": null,
"e": 57238,
"s": 56918,
"text": "Rest there are other methods to been put in the usage such as removeIf() and retainAll(). Do visit them thoroughly in order to get a better understanding of them too before we now finally end up this article with iterating through Collections. Let’s try to implement a few of them to get a better understanding of them."
},
{
"code": null,
"e": 57248,
"s": 57238,
"text": "Examples:"
},
{
"code": null,
"e": 57253,
"s": 57248,
"text": "Java"
},
{
"code": null,
"e": 57258,
"s": 57253,
"text": "Java"
},
{
"code": null,
"e": 57263,
"s": 57258,
"text": "Java"
},
{
"code": null,
"e": 57268,
"s": 57263,
"text": "Java"
},
{
"code": null,
"e": 57276,
"s": 57268,
"text": "Output:"
},
{
"code": null,
"e": 57286,
"s": 57276,
"text": "Method 1:"
},
{
"code": null,
"e": 57291,
"s": 57286,
"text": "true"
},
{
"code": null,
"e": 57301,
"s": 57291,
"text": "Method 2:"
},
{
"code": null,
"e": 57326,
"s": 57301,
"text": "[10, 20, 30, 40, 40, 50]"
},
{
"code": null,
"e": 57336,
"s": 57326,
"text": "Method 3:"
},
{
"code": null,
"e": 57341,
"s": 57336,
"text": "[30]"
},
{
"code": null,
"e": 57351,
"s": 57341,
"text": "Method 4:"
},
{
"code": null,
"e": 57360,
"s": 57351,
"text": "[10, 20]"
},
{
"code": null,
"e": 57440,
"s": 57360,
"text": "Now lets us discuss all the methods been proposed for iteration are as follows:"
},
{
"code": null,
"e": 57507,
"s": 57440,
"text": "Iterators MethodFor-each loop MethodforEach() MethodStreams Method"
},
{
"code": null,
"e": 57524,
"s": 57507,
"text": "Iterators Method"
},
{
"code": null,
"e": 57545,
"s": 57524,
"text": "For-each loop Method"
},
{
"code": null,
"e": 57562,
"s": 57545,
"text": "forEach() Method"
},
{
"code": null,
"e": 57577,
"s": 57562,
"text": "Streams Method"
},
{
"code": null,
"e": 57643,
"s": 57577,
"text": "There are various ways of traversing through a collection namely:"
},
{
"code": null,
"e": 57670,
"s": 57643,
"text": "Method 1: Iterators Method"
},
{
"code": null,
"e": 58240,
"s": 57670,
"text": "The Iterable interface provides an iterator() method which implements the Iterator interface. The iterator interface provides 3 functions(hasNext(), next(), remove()) which are used to iterate through the collection and also remove elements from the collection. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator."
},
{
"code": null,
"e": 58271,
"s": 58240,
"text": "Method 2: For-each loop Method"
},
{
"code": null,
"e": 58464,
"s": 58271,
"text": "For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)."
},
{
"code": null,
"e": 58519,
"s": 58464,
"text": "for (type var : array) \n{ \n statements using var;\n}"
},
{
"code": null,
"e": 58905,
"s": 58519,
"text": "Method 3: forEach() is also present in the Iterable interface. Therefore, it can be implemented by all the collections in the framework that extends the Iterable interface. Whenever is needed to traverse over a collection we have to create an Iterator to iterate over the collection, and then we can have our business logic inside a loop for each of the elements inside the collection."
},
{
"code": null,
"e": 58942,
"s": 58905,
"text": "public void forEach(Consumer action)"
},
{
"code": null,
"e": 59152,
"s": 58942,
"text": "Method 4: Streams Method is the most recommended method to traverse through a collection or perform any operation of filter or segregation. This was added in Java 8. There are several benefits of using stream:"
},
{
"code": null,
"e": 59185,
"s": 59152,
"text": "It can be parallel and infinite."
},
{
"code": null,
"e": 59197,
"s": 59185,
"text": "No storage."
},
{
"code": null,
"e": 59226,
"s": 59197,
"text": " Functions can be pipelined."
},
{
"code": null,
"e": 59366,
"s": 59226,
"text": "The most important benefit of Streams is that we can create them from the collection, arrays, Files Lines, and even from methods in Stream."
},
{
"code": null,
"e": 59376,
"s": 59366,
"text": "Examples:"
},
{
"code": null,
"e": 59381,
"s": 59376,
"text": "Java"
},
{
"code": null,
"e": 59386,
"s": 59381,
"text": "Java"
},
{
"code": null,
"e": 59391,
"s": 59386,
"text": "Java"
},
{
"code": null,
"e": 59399,
"s": 59391,
"text": "Output:"
},
{
"code": null,
"e": 59409,
"s": 59399,
"text": "Method 1:"
},
{
"code": null,
"e": 59423,
"s": 59409,
"text": "10 15 7 20 40"
},
{
"code": null,
"e": 59433,
"s": 59423,
"text": "Method 2:"
},
{
"code": null,
"e": 59447,
"s": 59433,
"text": "10\n15\n7\n20\n40"
},
{
"code": null,
"e": 59457,
"s": 59447,
"text": "Method 3:"
},
{
"code": null,
"e": 59477,
"s": 59457,
"text": "10 15 7 20 40\n20 40"
},
{
"code": null,
"e": 59575,
"s": 59477,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 59584,
"s": 59575,
"text": "Comments"
},
{
"code": null,
"e": 59597,
"s": 59584,
"text": "Old Comments"
},
{
"code": null,
"e": 59650,
"s": 59597,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 59709,
"s": 59650,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 59770,
"s": 59709,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 59847,
"s": 59770,
"text": "Find number of rectangles that can be formed from a given set of coordinates"
},
{
"code": null,
"e": 59885,
"s": 59847,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 59947,
"s": 59885,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 59988,
"s": 59947,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 60031,
"s": 59988,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 60067,
"s": 60031,
"text": "How to Read Text Files with Pandas?"
}
]
|
COBOL - Subroutines | Cobol subroutine is a program that can be compiled independently but cannot be executed independently. There are two types of subroutines: internal subroutines like Perform statements and external subroutines like CALL verb.
Call verb is used to transfer the control from one program to another program. The program that contains the CALL verb is the Calling Program and the program being called is known as the Called Program. Calling program execution will halt until the called program finishes the execution. Exit Program statement is used in the Called program to transfer the control back.
Following are the called program requirements −
Linkage section must be defined in the called program. It consists of data elements passed in the program. The data items should not have Value clause. PIC clause must be compatible with the variables passed through the calling program.
Linkage section must be defined in the called program. It consists of data elements passed in the program. The data items should not have Value clause. PIC clause must be compatible with the variables passed through the calling program.
Procedure division using has a list of variables passed from the calling program and the order must be same as mentioned in the Call verb.
Procedure division using has a list of variables passed from the calling program and the order must be same as mentioned in the Call verb.
Exit program statement is used in the called program to transfer the control back. It must be the last statement in the called program.
Exit program statement is used in the called program to transfer the control back. It must be the last statement in the called program.
The parameters can be passed between programs in two ways −
By Reference
By Content
If the values of variables in the called program are modified, then their new values will reflect in the calling program. If BY clause is not specified, then variables are always passed by reference.
Following is the syntax of calling subroutine by reference −
CALL sub-prog-name USING variable-1, variable-2.
Example
Following example is the MAIN calling program and UTIL is the called program −
IDENTIFICATION DIVISION.
PROGRAM-ID. MAIN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-STUDENT-ID PIC 9(4) VALUE 1000.
01 WS-STUDENT-NAME PIC A(15) VALUE 'Tim'.
PROCEDURE DIVISION.
CALL 'UTIL' USING WS-STUDENT-ID, WS-STUDENT-NAME.
DISPLAY 'Student Id : ' WS-STUDENT-ID
DISPLAY 'Student Name : ' WS-STUDENT-NAME
STOP RUN.
IDENTIFICATION DIVISION.
PROGRAM-ID. UTIL.
DATA DIVISION.
LINKAGE SECTION.
01 LS-STUDENT-ID PIC 9(4).
01 LS-STUDENT-NAME PIC A(15).
PROCEDURE DIVISION USING LS-STUDENT-ID, LS-STUDENT-NAME.
DISPLAY 'In Called Program'.
MOVE 1111 TO LS-STUDENT-ID.
EXIT PROGRAM.
JCL to execute the above COBOL program −
//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
//STEP1 EXEC PGM = MAIN
When you compile and execute the above program, it produces the following result −
In Called Program
Student Id : 1111
Student Name : Tim
If the values of variables in the called program are modified, then their new values will not reflect in the calling program.
Following is the syntax of calling subroutine by content −
CALL sub-prog-name USING
BY CONTENT variable-1, BY CONTENT variable-2.
Example
Following example is the MAIN calling program and UTIL is the called program −
IDENTIFICATION DIVISION.
PROGRAM-ID. MAIN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-STUDENT-ID PIC 9(4) VALUE 1000.
01 WS-STUDENT-NAME PIC A(15) VALUE 'Tim'.
PROCEDURE DIVISION.
CALL 'UTIL' USING BY CONTENT WS-STUDENT-ID, BY CONTENT WS-STUDENT-NAME.
DISPLAY 'Student Id : ' WS-STUDENT-ID
DISPLAY 'Student Name : ' WS-STUDENT-NAME
STOP RUN.
IDENTIFICATION DIVISION.
PROGRAM-ID. UTIL.
DATA DIVISION.
LINKAGE SECTION.
01 LS-STUDENT-ID PIC 9(4).
01 LS-STUDENT-NAME PIC A(15).
PROCEDURE DIVISION USING LS-STUDENT-ID, LS-STUDENT-NAME.
DISPLAY 'In Called Program'.
MOVE 1111 TO LS-STUDENT-ID.
EXIT PROGRAM.
JCL to execute the above COBOL program −
//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C
//STEP1 EXEC PGM = MAIN
When you compile and execute the above program, it produces the following result −
In Called Program
Student Id : 1000
Student Name : Tim
There are two types of calls −
Static Call occurs when a program is compiled with the NODYNAM compiler option. A static called program is loaded into storage at compile time.
Static Call occurs when a program is compiled with the NODYNAM compiler option. A static called program is loaded into storage at compile time.
Dynamic Call occurs when a program is compiled with the DYNAM and NODLL compiler option. A dynamic called program is loaded into storage at runtime.
Dynamic Call occurs when a program is compiled with the DYNAM and NODLL compiler option. A dynamic called program is loaded into storage at runtime.
12 Lectures
2.5 hours
Nishant Malik
33 Lectures
3.5 hours
Craig Kenneth Kaercher
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2247,
"s": 2022,
"text": "Cobol subroutine is a program that can be compiled independently but cannot be executed independently. There are two types of subroutines: internal subroutines like Perform statements and external subroutines like CALL verb."
},
{
"code": null,
"e": 2618,
"s": 2247,
"text": "Call verb is used to transfer the control from one program to another program. The program that contains the CALL verb is the Calling Program and the program being called is known as the Called Program. Calling program execution will halt until the called program finishes the execution. Exit Program statement is used in the Called program to transfer the control back."
},
{
"code": null,
"e": 2666,
"s": 2618,
"text": "Following are the called program requirements −"
},
{
"code": null,
"e": 2903,
"s": 2666,
"text": "Linkage section must be defined in the called program. It consists of data elements passed in the program. The data items should not have Value clause. PIC clause must be compatible with the variables passed through the calling program."
},
{
"code": null,
"e": 3140,
"s": 2903,
"text": "Linkage section must be defined in the called program. It consists of data elements passed in the program. The data items should not have Value clause. PIC clause must be compatible with the variables passed through the calling program."
},
{
"code": null,
"e": 3279,
"s": 3140,
"text": "Procedure division using has a list of variables passed from the calling program and the order must be same as mentioned in the Call verb."
},
{
"code": null,
"e": 3418,
"s": 3279,
"text": "Procedure division using has a list of variables passed from the calling program and the order must be same as mentioned in the Call verb."
},
{
"code": null,
"e": 3554,
"s": 3418,
"text": "Exit program statement is used in the called program to transfer the control back. It must be the last statement in the called program."
},
{
"code": null,
"e": 3690,
"s": 3554,
"text": "Exit program statement is used in the called program to transfer the control back. It must be the last statement in the called program."
},
{
"code": null,
"e": 3750,
"s": 3690,
"text": "The parameters can be passed between programs in two ways −"
},
{
"code": null,
"e": 3763,
"s": 3750,
"text": "By Reference"
},
{
"code": null,
"e": 3774,
"s": 3763,
"text": "By Content"
},
{
"code": null,
"e": 3974,
"s": 3774,
"text": "If the values of variables in the called program are modified, then their new values will reflect in the calling program. If BY clause is not specified, then variables are always passed by reference."
},
{
"code": null,
"e": 4035,
"s": 3974,
"text": "Following is the syntax of calling subroutine by reference −"
},
{
"code": null,
"e": 4085,
"s": 4035,
"text": "CALL sub-prog-name USING variable-1, variable-2.\n"
},
{
"code": null,
"e": 4093,
"s": 4085,
"text": "Example"
},
{
"code": null,
"e": 4172,
"s": 4093,
"text": "Following example is the MAIN calling program and UTIL is the called program −"
},
{
"code": null,
"e": 4515,
"s": 4172,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. MAIN.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-STUDENT-ID PIC 9(4) VALUE 1000.\n 01 WS-STUDENT-NAME PIC A(15) VALUE 'Tim'.\n\nPROCEDURE DIVISION.\n CALL 'UTIL' USING WS-STUDENT-ID, WS-STUDENT-NAME.\n DISPLAY 'Student Id : ' WS-STUDENT-ID\n DISPLAY 'Student Name : ' WS-STUDENT-NAME\nSTOP RUN."
},
{
"code": null,
"e": 4792,
"s": 4515,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. UTIL.\n\nDATA DIVISION.\n LINKAGE SECTION.\n 01 LS-STUDENT-ID PIC 9(4).\n 01 LS-STUDENT-NAME PIC A(15).\n\nPROCEDURE DIVISION USING LS-STUDENT-ID, LS-STUDENT-NAME.\n DISPLAY 'In Called Program'.\n MOVE 1111 TO LS-STUDENT-ID.\nEXIT PROGRAM."
},
{
"code": null,
"e": 4833,
"s": 4792,
"text": "JCL to execute the above COBOL program −"
},
{
"code": null,
"e": 4909,
"s": 4833,
"text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = MAIN"
},
{
"code": null,
"e": 4992,
"s": 4909,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 5048,
"s": 4992,
"text": "In Called Program\nStudent Id : 1111\nStudent Name : Tim\n"
},
{
"code": null,
"e": 5174,
"s": 5048,
"text": "If the values of variables in the called program are modified, then their new values will not reflect in the calling program."
},
{
"code": null,
"e": 5233,
"s": 5174,
"text": "Following is the syntax of calling subroutine by content −"
},
{
"code": null,
"e": 5306,
"s": 5233,
"text": "CALL sub-prog-name USING \nBY CONTENT variable-1, BY CONTENT variable-2.\n"
},
{
"code": null,
"e": 5314,
"s": 5306,
"text": "Example"
},
{
"code": null,
"e": 5393,
"s": 5314,
"text": "Following example is the MAIN calling program and UTIL is the called program −"
},
{
"code": null,
"e": 5758,
"s": 5393,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. MAIN.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-STUDENT-ID PIC 9(4) VALUE 1000.\n 01 WS-STUDENT-NAME PIC A(15) VALUE 'Tim'.\n\nPROCEDURE DIVISION.\n CALL 'UTIL' USING BY CONTENT WS-STUDENT-ID, BY CONTENT WS-STUDENT-NAME.\n DISPLAY 'Student Id : ' WS-STUDENT-ID\n DISPLAY 'Student Name : ' WS-STUDENT-NAME\nSTOP RUN."
},
{
"code": null,
"e": 6035,
"s": 5758,
"text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. UTIL.\n\nDATA DIVISION.\n LINKAGE SECTION.\n 01 LS-STUDENT-ID PIC 9(4).\n 01 LS-STUDENT-NAME PIC A(15).\n\nPROCEDURE DIVISION USING LS-STUDENT-ID, LS-STUDENT-NAME.\n DISPLAY 'In Called Program'.\n MOVE 1111 TO LS-STUDENT-ID.\nEXIT PROGRAM."
},
{
"code": null,
"e": 6076,
"s": 6035,
"text": "JCL to execute the above COBOL program −"
},
{
"code": null,
"e": 6152,
"s": 6076,
"text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = MAIN"
},
{
"code": null,
"e": 6235,
"s": 6152,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 6291,
"s": 6235,
"text": "In Called Program\nStudent Id : 1000\nStudent Name : Tim\n"
},
{
"code": null,
"e": 6322,
"s": 6291,
"text": "There are two types of calls −"
},
{
"code": null,
"e": 6466,
"s": 6322,
"text": "Static Call occurs when a program is compiled with the NODYNAM compiler option. A static called program is loaded into storage at compile time."
},
{
"code": null,
"e": 6610,
"s": 6466,
"text": "Static Call occurs when a program is compiled with the NODYNAM compiler option. A static called program is loaded into storage at compile time."
},
{
"code": null,
"e": 6759,
"s": 6610,
"text": "Dynamic Call occurs when a program is compiled with the DYNAM and NODLL compiler option. A dynamic called program is loaded into storage at runtime."
},
{
"code": null,
"e": 6908,
"s": 6759,
"text": "Dynamic Call occurs when a program is compiled with the DYNAM and NODLL compiler option. A dynamic called program is loaded into storage at runtime."
},
{
"code": null,
"e": 6943,
"s": 6908,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6958,
"s": 6943,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6993,
"s": 6958,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7017,
"s": 6993,
"text": " Craig Kenneth Kaercher"
},
{
"code": null,
"e": 7024,
"s": 7017,
"text": " Print"
},
{
"code": null,
"e": 7035,
"s": 7024,
"text": " Add Notes"
}
]
|
How to process a DataFrame with millions of rows in seconds | by Roman Orac | Towards Data Science | Big Data Analysis in Python is having its renaissance. It all started with NumPy, which is also one of the building blocks behind the tool I am presenting in this article.
In 2006, Big Data was a topic that was slowly gaining traction, especially with the release of Hadoop. Pandas followed soon after with its DataFrames. 2014 was the year when Big Data became mainstream, also Apache Spark was released that year. In 2018 came Dask and other libraries for data analytics in Python.
Each month I find a new Data Analytics tool, which I am eager to learn. It is a worthy investment of spending an hour or two on tutorials as it can save you a lot of time in the long run. It’s also important to keep in touch with the latest tech.
While you might expect that this article will be about Dask you are wrong. I found another Python library for data analysis that you should know about.
Like Python, it is equally important that you become proficient in SQL. In case you aren’t familiar with it, and you have some money to spare, check out this course: Master SQL, the core language for Big Data analysis.
Big Data Analysis in Python is having its renaissance
- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]
Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything.
towardsdatascience.com
Vaex is a high-performance Python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets.
It can calculate basic statistics for more than a billion rows per second. It supports multiple visualizations allowing interactive exploration of big data.
Vaex is not similar to Dask but is similar to Dask DataFrames, which are built on top pandas DataFrames. This means that Dask inherits pandas issues, like high memory usage. This is not the case Vaex.
Vaex doesn’t make DataFrame copies so it can process bigger DataFrame on machines with less main memory.
Both Vaex and Dask use lazy processing. The only difference is that Vaex calculates the field when needed, wherewith Dask we need to explicitly use the compute function.
Data needs to be in HDF5 or Apache Arrow format to take full advantage of Vaex.
To install Vaex is as simple as installing any other Python package:
pip install vaex
Let’s create a pandas DataFrame with 1 million rows and 1000 columns to create a big data file.
import vaeximport pandas as pdimport numpy as npn_rows = 1000000n_cols = 1000df = pd.DataFrame(np.random.randint(0, 100, size=(n_rows, n_cols)), columns=['col%d' % i for i in range(n_cols)])df.head()
How much main memory does this DataFrame use?
df.info(memory_usage='deep')
Let’s save it to disk so that we can read it later with Vaex.
file_path = 'big_file.csv'df.to_csv(file_path, index=False)
We wouldn’t gain much by reading the whole CSV directly with Vaex as the speed would be similar to pandas. Both need approximately 85 seconds on my laptop.
We need to convert the CSV to HDF5 (the Hierarchical Data Format version 5) to see the benefit with Vaex. Vaex has a function for conversion, which even supports files bigger than the main memory by converting smaller chunks.
If you cannot open a big file with pandas, because of memory constraints, you can covert it to HDF5 and process it with Vaex.
dv = vaex.from_csv(file_path, convert=True, chunk_size=5_000_000)
This function creates an HDF5 file and persists it to disk.
What’s the datatype of dv?
type(dv)# outputvaex.hdf5.dataset.Hdf5MemoryMapped
Now, let’s read the 7.5 GB dataset with Vaex — We wouldn’t need to read it again as we already have it in dv variable. This is just to test the speed.
dv = vaex.open('big_file.csv.hdf5')
Vaex needed less than 1 second to execute the command above. But Vaex didn’t actually read the file, because of lazy loading, right?
Let’s force to read it by calculating a sum of col1.
suma = dv.col1.sum()suma# Output# array(49486599)
I was really surprised by this one. Vaex needed less than 1 second to calculate the sum. How is that possible?
Opening such data is instantaneous regardless of the file size on disk. Vaex will just memory-map the data instead of reading it in memory. This is the optimal way of working with large datasets that are larger than available RAM.
Vaex is also fast when plotting data. It has special plotting functions plot1d, plot2d and plot2d_contour.
dv.plot1d(dv.col2, figsize=(14, 7))
Vaex creates a virtual column when adding a new column, — a column that doesn’t take the main memory as it is computed on the fly.
dv['col1_plus_col2'] = dv.col1 + dv.col2dv['col1_plus_col2']
Vaex won’t create DataFrame copies when filtering data, which is much more memory efficient.
dvv = dv[dv.col1 > 90]
Aggregations work slightly differently than in pandas, but more importantly, they are blazingly fast.
Let’s add a binary virtual column where col1 ≥ 50.
dv['col1_50'] = dv.col1 >= 50
Vaex combines group by and aggregation in a single command. The command below groups data by the “col1_50” column and calculates the sum of the col3 column.
dv_group = dv.groupby(dv['col1_50'], agg=vaex.agg.sum(dv['col3']))dv_group
Vaex joins data without making memory copies, which saves the main memory. Pandas users will be familiar with the join function:
dv_join = dv.join(dv_group, on=’col1_50')
In the end, you might ask: Should we simply switch from pandas to Vaex? The answer is a big NO.
Pandas is still the best tool for data analysis in Python. It has well-supported functions for the most common data analysis tasks.
When it comes to bigger files, pandas might not be the fastest tool. This is a great place for Vaex to jump in.
Vaex is a tool you should add to your Data Analytics toolbox.
When working on an analysis task where pandas is too slow or simply crashes, pull Vaex out of your toolbox, filter out the most important entries and continue the analysis with pandas.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning. | [
{
"code": null,
"e": 343,
"s": 171,
"text": "Big Data Analysis in Python is having its renaissance. It all started with NumPy, which is also one of the building blocks behind the tool I am presenting in this article."
},
{
"code": null,
"e": 655,
"s": 343,
"text": "In 2006, Big Data was a topic that was slowly gaining traction, especially with the release of Hadoop. Pandas followed soon after with its DataFrames. 2014 was the year when Big Data became mainstream, also Apache Spark was released that year. In 2018 came Dask and other libraries for data analytics in Python."
},
{
"code": null,
"e": 902,
"s": 655,
"text": "Each month I find a new Data Analytics tool, which I am eager to learn. It is a worthy investment of spending an hour or two on tutorials as it can save you a lot of time in the long run. It’s also important to keep in touch with the latest tech."
},
{
"code": null,
"e": 1054,
"s": 902,
"text": "While you might expect that this article will be about Dask you are wrong. I found another Python library for data analysis that you should know about."
},
{
"code": null,
"e": 1273,
"s": 1054,
"text": "Like Python, it is equally important that you become proficient in SQL. In case you aren’t familiar with it, and you have some money to spare, check out this course: Master SQL, the core language for Big Data analysis."
},
{
"code": null,
"e": 1327,
"s": 1273,
"text": "Big Data Analysis in Python is having its renaissance"
},
{
"code": null,
"e": 1505,
"s": 1327,
"text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]"
},
{
"code": null,
"e": 1676,
"s": 1505,
"text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything."
},
{
"code": null,
"e": 1699,
"s": 1676,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1841,
"s": 1699,
"text": "Vaex is a high-performance Python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets."
},
{
"code": null,
"e": 1998,
"s": 1841,
"text": "It can calculate basic statistics for more than a billion rows per second. It supports multiple visualizations allowing interactive exploration of big data."
},
{
"code": null,
"e": 2199,
"s": 1998,
"text": "Vaex is not similar to Dask but is similar to Dask DataFrames, which are built on top pandas DataFrames. This means that Dask inherits pandas issues, like high memory usage. This is not the case Vaex."
},
{
"code": null,
"e": 2304,
"s": 2199,
"text": "Vaex doesn’t make DataFrame copies so it can process bigger DataFrame on machines with less main memory."
},
{
"code": null,
"e": 2474,
"s": 2304,
"text": "Both Vaex and Dask use lazy processing. The only difference is that Vaex calculates the field when needed, wherewith Dask we need to explicitly use the compute function."
},
{
"code": null,
"e": 2554,
"s": 2474,
"text": "Data needs to be in HDF5 or Apache Arrow format to take full advantage of Vaex."
},
{
"code": null,
"e": 2623,
"s": 2554,
"text": "To install Vaex is as simple as installing any other Python package:"
},
{
"code": null,
"e": 2640,
"s": 2623,
"text": "pip install vaex"
},
{
"code": null,
"e": 2736,
"s": 2640,
"text": "Let’s create a pandas DataFrame with 1 million rows and 1000 columns to create a big data file."
},
{
"code": null,
"e": 2936,
"s": 2736,
"text": "import vaeximport pandas as pdimport numpy as npn_rows = 1000000n_cols = 1000df = pd.DataFrame(np.random.randint(0, 100, size=(n_rows, n_cols)), columns=['col%d' % i for i in range(n_cols)])df.head()"
},
{
"code": null,
"e": 2982,
"s": 2936,
"text": "How much main memory does this DataFrame use?"
},
{
"code": null,
"e": 3011,
"s": 2982,
"text": "df.info(memory_usage='deep')"
},
{
"code": null,
"e": 3073,
"s": 3011,
"text": "Let’s save it to disk so that we can read it later with Vaex."
},
{
"code": null,
"e": 3133,
"s": 3073,
"text": "file_path = 'big_file.csv'df.to_csv(file_path, index=False)"
},
{
"code": null,
"e": 3289,
"s": 3133,
"text": "We wouldn’t gain much by reading the whole CSV directly with Vaex as the speed would be similar to pandas. Both need approximately 85 seconds on my laptop."
},
{
"code": null,
"e": 3515,
"s": 3289,
"text": "We need to convert the CSV to HDF5 (the Hierarchical Data Format version 5) to see the benefit with Vaex. Vaex has a function for conversion, which even supports files bigger than the main memory by converting smaller chunks."
},
{
"code": null,
"e": 3641,
"s": 3515,
"text": "If you cannot open a big file with pandas, because of memory constraints, you can covert it to HDF5 and process it with Vaex."
},
{
"code": null,
"e": 3707,
"s": 3641,
"text": "dv = vaex.from_csv(file_path, convert=True, chunk_size=5_000_000)"
},
{
"code": null,
"e": 3767,
"s": 3707,
"text": "This function creates an HDF5 file and persists it to disk."
},
{
"code": null,
"e": 3794,
"s": 3767,
"text": "What’s the datatype of dv?"
},
{
"code": null,
"e": 3845,
"s": 3794,
"text": "type(dv)# outputvaex.hdf5.dataset.Hdf5MemoryMapped"
},
{
"code": null,
"e": 3996,
"s": 3845,
"text": "Now, let’s read the 7.5 GB dataset with Vaex — We wouldn’t need to read it again as we already have it in dv variable. This is just to test the speed."
},
{
"code": null,
"e": 4032,
"s": 3996,
"text": "dv = vaex.open('big_file.csv.hdf5')"
},
{
"code": null,
"e": 4165,
"s": 4032,
"text": "Vaex needed less than 1 second to execute the command above. But Vaex didn’t actually read the file, because of lazy loading, right?"
},
{
"code": null,
"e": 4218,
"s": 4165,
"text": "Let’s force to read it by calculating a sum of col1."
},
{
"code": null,
"e": 4268,
"s": 4218,
"text": "suma = dv.col1.sum()suma# Output# array(49486599)"
},
{
"code": null,
"e": 4379,
"s": 4268,
"text": "I was really surprised by this one. Vaex needed less than 1 second to calculate the sum. How is that possible?"
},
{
"code": null,
"e": 4610,
"s": 4379,
"text": "Opening such data is instantaneous regardless of the file size on disk. Vaex will just memory-map the data instead of reading it in memory. This is the optimal way of working with large datasets that are larger than available RAM."
},
{
"code": null,
"e": 4717,
"s": 4610,
"text": "Vaex is also fast when plotting data. It has special plotting functions plot1d, plot2d and plot2d_contour."
},
{
"code": null,
"e": 4753,
"s": 4717,
"text": "dv.plot1d(dv.col2, figsize=(14, 7))"
},
{
"code": null,
"e": 4884,
"s": 4753,
"text": "Vaex creates a virtual column when adding a new column, — a column that doesn’t take the main memory as it is computed on the fly."
},
{
"code": null,
"e": 4945,
"s": 4884,
"text": "dv['col1_plus_col2'] = dv.col1 + dv.col2dv['col1_plus_col2']"
},
{
"code": null,
"e": 5038,
"s": 4945,
"text": "Vaex won’t create DataFrame copies when filtering data, which is much more memory efficient."
},
{
"code": null,
"e": 5061,
"s": 5038,
"text": "dvv = dv[dv.col1 > 90]"
},
{
"code": null,
"e": 5163,
"s": 5061,
"text": "Aggregations work slightly differently than in pandas, but more importantly, they are blazingly fast."
},
{
"code": null,
"e": 5214,
"s": 5163,
"text": "Let’s add a binary virtual column where col1 ≥ 50."
},
{
"code": null,
"e": 5244,
"s": 5214,
"text": "dv['col1_50'] = dv.col1 >= 50"
},
{
"code": null,
"e": 5401,
"s": 5244,
"text": "Vaex combines group by and aggregation in a single command. The command below groups data by the “col1_50” column and calculates the sum of the col3 column."
},
{
"code": null,
"e": 5476,
"s": 5401,
"text": "dv_group = dv.groupby(dv['col1_50'], agg=vaex.agg.sum(dv['col3']))dv_group"
},
{
"code": null,
"e": 5605,
"s": 5476,
"text": "Vaex joins data without making memory copies, which saves the main memory. Pandas users will be familiar with the join function:"
},
{
"code": null,
"e": 5647,
"s": 5605,
"text": "dv_join = dv.join(dv_group, on=’col1_50')"
},
{
"code": null,
"e": 5743,
"s": 5647,
"text": "In the end, you might ask: Should we simply switch from pandas to Vaex? The answer is a big NO."
},
{
"code": null,
"e": 5875,
"s": 5743,
"text": "Pandas is still the best tool for data analysis in Python. It has well-supported functions for the most common data analysis tasks."
},
{
"code": null,
"e": 5987,
"s": 5875,
"text": "When it comes to bigger files, pandas might not be the fastest tool. This is a great place for Vaex to jump in."
},
{
"code": null,
"e": 6049,
"s": 5987,
"text": "Vaex is a tool you should add to your Data Analytics toolbox."
},
{
"code": null,
"e": 6234,
"s": 6049,
"text": "When working on an analysis task where pandas is too slow or simply crashes, pull Vaex out of your toolbox, filter out the most important entries and continue the analysis with pandas."
}
]
|
Using Panda’s “transform” and “apply” to deal with missing data on a group level | by Fabian Bosler | Towards Data Science | According to an analysis conducted by Businessbroadway, a data professional spends up to 60% of their time gathering, cleaning data, and visualizing data.
A critical aspect of cleaning and visualizing data revolves around how to deal with missing data. Pandas offers some basic functionalities in the form of the fillna method. While fillna works well in the simplest of cases, it falls short as soon as groups within the data or order of the data become relevant. This article is going to discuss techniques to address those more complex cases.
Those cases are typically datasets that consist of different regimes (time-series), groups, and even subgroups. Examples of different regimes are months, quarters (time ranges in general), or a period of heavy rain. An example of groups within the data is gender. Examples of subgroups are age cohorts and ethnicity.
The article is intended as a code-along article. So feel free to boot up a Notebook and dive right in.
Recap of Pandas’ fillnaDealing with missing data, when the order is not relevantDealing with missing data, when the order is relevant
Recap of Pandas’ fillna
Dealing with missing data, when the order is not relevant
Dealing with missing data, when the order is relevant
Pandas has three modes of dealing with missing data via calling fillna():
method='ffill': Ffill or forward-fill propagates the last observed non-null value forward until another non-null value is encountered
method='bfill': Bfill or backward-fill propagates the first observed non-null value backward until another non-null value is met
explicit value: It is also possible to set an exact value to replace all missings. Such a substitution could be -999, for example, to indicate that the value is missing.
Example:
IN:demo = pd.Series(range(6))demo.loc[2:4] = np.nandemoOUT:0 0.01 1.02 NaN3 NaN4 NaN5 5.0dtype: float64# Forward-FillIN:demo.fillna(method='ffill')OUT:0 0.01 1.02 1.03 1.04 1.05 5.0dtype: float64# Backward-FillIN:demo.fillna(method='bfill')OUT:0 0.01 1.02 5.03 5.04 5.05 5.0dtype: float64# Explicit valueIN:demo.fillna(-999)OUT:0 0.01 1.02 -999.03 -999.04 -999.05 5.0dtype: float64
Frequently, when dealing with missing data, the sequencing does not matter, and thus, the values used to replace missing values can be based on the entirety of available data. In such cases, you would typically replace the missing values with your best guess (i.e., mean or medium of the available data)
Let’s quickly go over why you should use this option with care. Let’s assume you survey 1000 boys and 1000 girls for their weights. During the process of collecting the data, unfortunately, some of the data went missing.
# importsimport numpy as np# sample 1000 boys and 1000 girlsboys = np.random.normal(70,5,1000)girls = np.random.normal(50,3,1000)# unfortunately, the intern running the survey on the girls got distracted and lost 100 samplesfor i in range(100): girls[np.random.randint(0,1000)] = np.nan# build DataFrameboys = pd.DataFrame(boys, columns=['weight'])boys['gender'] = 'boy'girls = pd.DataFrame(girls, columns=['weight'])girls['gender'] = 'girl'df = pd.concat([girls,boys],axis=0)df['weight'] = df['weight'].astype(float)
Without giving it much thought, we might fill the missing values with the entire sample’s mean. The results look somewhat strange, though. The girl’s KDE has two humps. One might conclude that there is a subgroup of heavier girls among our sample. Because we built the distributions beforehand, we know this isn’t the case. But if this were real data, we might draw wrong conclusions from this data.
# PLOT CODE:sns.set_style('white')fig, ax = plt.subplots(figsize=(16, 7))mean = df['weight'].mean()sns.distplot( df[df['gender'] == 'girl']['weight'].fillna(mean), kde=True, hist=False, ax=ax, label='girls')sns.distplot( df[df['gender'] == 'boy']['weight'], kde=True, hist=False, ax=ax, label='boys')plt.title('Kernel density estimation of weight for boys and girls')sns.despine()
In such situations, Panda’s transform function comes in handy. Using transform gives a convenient way of fixing the problem on a group level like this:
df['filled_weight'] = df.groupby('gender')['weight'].transform( lambda grp: grp.fillna(np.mean(grp)))
Running the above command and plotting the KDE of the filled_weight values results in:
# PLOT CODE:sns.set_style('white')fig, ax = plt.subplots(figsize=(16, 7))sns.distplot( df[df['gender'] == 'girl']['filled_weight'], kde=True, hist=False, ax=ax, label='girls')sns.distplot( df[df['gender'] == 'boy']['filled_weight'], kde=True, hist=False, ax=ax, label='boys')plt.title('Kernel density estimation of weight for boys and girls')sns.despine()
Let’s use the previous example, but this time, we go a bit further and additionally segment our data into age groups. Let’s create some mock data:
# paramter for the weight distribution (mean, std)param_map = { 'boy':{ '<10':(40,4), '<20':(60,4), '20+':(70,5), }, 'girl':{ '<10':(30,2), '<20':(40,3), '20+':(50,3), }}# generate 10k recordsdf = pd.DataFrame({ 'gender':np.random.choice(['girl','boy'],10000), 'age_cohort':np.random.choice(['<10','<20','20+'],10000)})# set random weight based on parametersdf['weight'] = df.apply( lambda x: np.random.normal( loc=param_map[x['gender']][x['age_cohort']][0], scale=param_map[x['gender']][x['age_cohort']][1] ),axis=1)# set 500 values missingfor i in range(500): df.loc[np.random.randint(0,len(df)),'weight'] = np.nan
Plotting the data reveals somewhat strange bimodal distributions (code below).
# PLOT CODEdf['filled_weight'] = df['weight'].fillna( df['weight'].mean())g = sns.FacetGrid( df, col='age_cohort', row='gender', col_order=['<10','<20','20+'])g.map(sns.kdeplot,'filled_weight')
Now, if we would only replace the missing values with the mean for the respective gender, this would not go far enough as not only boys and girls are different in weight, but also different age groups are quite different in weight.
Luckily, transform can be applied just as before. We would group on both columns instead of only one like this:
df['filled_weight'] = df.groupby(['gender','age_cohort'])['weight'].transform( lambda grp: grp.fillna(np.mean(grp)))
Running the above snippet will generate this much cleaner plot:
Two situations frequently come up when working with time-series data.
Aligning date ranges: Say you look at countries’ GDP, education level, and population growth by year. For some countries, you are missing the very first, some of the later years, or some years in between. Sure, you could ignore them. Still, for visualization purposes, you might want to keep them around and project your first observed value to the beginning, your last observed value to the end of your survey period, and come up with something that makes sense for the values in the middle.Interpolation: Looking at time-series data interpolation and thus ordering becomes very relevant. Replacing missing stock data from 2012 with an average that is calculated based on data up to 2019 is bound to produce some wacky results.
Aligning date ranges: Say you look at countries’ GDP, education level, and population growth by year. For some countries, you are missing the very first, some of the later years, or some years in between. Sure, you could ignore them. Still, for visualization purposes, you might want to keep them around and project your first observed value to the beginning, your last observed value to the end of your survey period, and come up with something that makes sense for the values in the middle.
Interpolation: Looking at time-series data interpolation and thus ordering becomes very relevant. Replacing missing stock data from 2012 with an average that is calculated based on data up to 2019 is bound to produce some wacky results.
We will look at an example based on data from the World Happiness Report 2019, where we address both situations. The World Happiness Report tries to answer which factors influence happiness throughout the world. The report surveys data from the year 2005 to 2018.
# Load the datadf = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/happiness_with_continent.csv')
df.sample(5) as opposed to df.head(5) selects five random rows, thus giving you a more unbiased view of the data.
Let’s take a look at the number of countries per year we have data for.
# PLOT CODE:df.groupby(['Year']).size().plot( kind='bar', title='Number of countries with data', figsize=(10,5))
We can see that, especially for the earlier years, we don’t have many countries with data, and also there is some fluctuation across the entire sample period. To mitigate the effect of missing data, we will do the following:
Group by country and reindex to the whole date rangeInterpolate for years between and extrapolate for years outside the range for which we have observations on a per-country basis
Group by country and reindex to the whole date range
Interpolate for years between and extrapolate for years outside the range for which we have observations on a per-country basis
# Define helper functiondef add_missing_years(grp): _ = grp.set_index('Year') _ = _.reindex(list(range(2005,2019))) del _['Country name'] return _# Group by country name and extenddf = df.groupby('Country name').apply(add_missing_years)df = df.reset_index()
We now have roughly 600 more rows. However, those observations are null right now
# Define helper functiondef fill_missing(grp): res = grp.set_index('Year')\ .interpolate(method='linear',limit=5)\ .fillna(method='ffill')\ .fillna(method='bfill') del res['Country name'] return res# Group by country name and fill missingdf = df.groupby(['Country name']).apply( lambda grp: fill_missing(grp))df = df.reset_index()
The fill_missing function interpolates and extrapolates towards the end and the beginning, resulting in:
Perfect! Now we have data for the years 2005 to 2018 for all countries in our sample. The above methods were quite relevant for me when writing this article about visualizations. Check it out if you want to learn more about the happiness report.
towardsdatascience.com
That’s it for today. In this article, you learned how to use transformand apply to replace missing values with something more meaningful than the previous or subsequent value.
Reach out to me on LinkedIn if you discover some fantastic new visualizations, want to give feedback or have a chat.
If you liked what you’ve read, check out the other articles I wrote on Medium. | [
{
"code": null,
"e": 326,
"s": 171,
"text": "According to an analysis conducted by Businessbroadway, a data professional spends up to 60% of their time gathering, cleaning data, and visualizing data."
},
{
"code": null,
"e": 717,
"s": 326,
"text": "A critical aspect of cleaning and visualizing data revolves around how to deal with missing data. Pandas offers some basic functionalities in the form of the fillna method. While fillna works well in the simplest of cases, it falls short as soon as groups within the data or order of the data become relevant. This article is going to discuss techniques to address those more complex cases."
},
{
"code": null,
"e": 1034,
"s": 717,
"text": "Those cases are typically datasets that consist of different regimes (time-series), groups, and even subgroups. Examples of different regimes are months, quarters (time ranges in general), or a period of heavy rain. An example of groups within the data is gender. Examples of subgroups are age cohorts and ethnicity."
},
{
"code": null,
"e": 1137,
"s": 1034,
"text": "The article is intended as a code-along article. So feel free to boot up a Notebook and dive right in."
},
{
"code": null,
"e": 1271,
"s": 1137,
"text": "Recap of Pandas’ fillnaDealing with missing data, when the order is not relevantDealing with missing data, when the order is relevant"
},
{
"code": null,
"e": 1295,
"s": 1271,
"text": "Recap of Pandas’ fillna"
},
{
"code": null,
"e": 1353,
"s": 1295,
"text": "Dealing with missing data, when the order is not relevant"
},
{
"code": null,
"e": 1407,
"s": 1353,
"text": "Dealing with missing data, when the order is relevant"
},
{
"code": null,
"e": 1481,
"s": 1407,
"text": "Pandas has three modes of dealing with missing data via calling fillna():"
},
{
"code": null,
"e": 1615,
"s": 1481,
"text": "method='ffill': Ffill or forward-fill propagates the last observed non-null value forward until another non-null value is encountered"
},
{
"code": null,
"e": 1744,
"s": 1615,
"text": "method='bfill': Bfill or backward-fill propagates the first observed non-null value backward until another non-null value is met"
},
{
"code": null,
"e": 1914,
"s": 1744,
"text": "explicit value: It is also possible to set an exact value to replace all missings. Such a substitution could be -999, for example, to indicate that the value is missing."
},
{
"code": null,
"e": 1923,
"s": 1914,
"text": "Example:"
},
{
"code": null,
"e": 2380,
"s": 1923,
"text": "IN:demo = pd.Series(range(6))demo.loc[2:4] = np.nandemoOUT:0 0.01 1.02 NaN3 NaN4 NaN5 5.0dtype: float64# Forward-FillIN:demo.fillna(method='ffill')OUT:0 0.01 1.02 1.03 1.04 1.05 5.0dtype: float64# Backward-FillIN:demo.fillna(method='bfill')OUT:0 0.01 1.02 5.03 5.04 5.05 5.0dtype: float64# Explicit valueIN:demo.fillna(-999)OUT:0 0.01 1.02 -999.03 -999.04 -999.05 5.0dtype: float64"
},
{
"code": null,
"e": 2684,
"s": 2380,
"text": "Frequently, when dealing with missing data, the sequencing does not matter, and thus, the values used to replace missing values can be based on the entirety of available data. In such cases, you would typically replace the missing values with your best guess (i.e., mean or medium of the available data)"
},
{
"code": null,
"e": 2905,
"s": 2684,
"text": "Let’s quickly go over why you should use this option with care. Let’s assume you survey 1000 boys and 1000 girls for their weights. During the process of collecting the data, unfortunately, some of the data went missing."
},
{
"code": null,
"e": 3426,
"s": 2905,
"text": "# importsimport numpy as np# sample 1000 boys and 1000 girlsboys = np.random.normal(70,5,1000)girls = np.random.normal(50,3,1000)# unfortunately, the intern running the survey on the girls got distracted and lost 100 samplesfor i in range(100): girls[np.random.randint(0,1000)] = np.nan# build DataFrameboys = pd.DataFrame(boys, columns=['weight'])boys['gender'] = 'boy'girls = pd.DataFrame(girls, columns=['weight'])girls['gender'] = 'girl'df = pd.concat([girls,boys],axis=0)df['weight'] = df['weight'].astype(float)"
},
{
"code": null,
"e": 3826,
"s": 3426,
"text": "Without giving it much thought, we might fill the missing values with the entire sample’s mean. The results look somewhat strange, though. The girl’s KDE has two humps. One might conclude that there is a subgroup of heavier girls among our sample. Because we built the distributions beforehand, we know this isn’t the case. But if this were real data, we might draw wrong conclusions from this data."
},
{
"code": null,
"e": 4237,
"s": 3826,
"text": "# PLOT CODE:sns.set_style('white')fig, ax = plt.subplots(figsize=(16, 7))mean = df['weight'].mean()sns.distplot( df[df['gender'] == 'girl']['weight'].fillna(mean), kde=True, hist=False, ax=ax, label='girls')sns.distplot( df[df['gender'] == 'boy']['weight'], kde=True, hist=False, ax=ax, label='boys')plt.title('Kernel density estimation of weight for boys and girls')sns.despine()"
},
{
"code": null,
"e": 4389,
"s": 4237,
"text": "In such situations, Panda’s transform function comes in handy. Using transform gives a convenient way of fixing the problem on a group level like this:"
},
{
"code": null,
"e": 4494,
"s": 4389,
"text": "df['filled_weight'] = df.groupby('gender')['weight'].transform( lambda grp: grp.fillna(np.mean(grp)))"
},
{
"code": null,
"e": 4581,
"s": 4494,
"text": "Running the above command and plotting the KDE of the filled_weight values results in:"
},
{
"code": null,
"e": 4967,
"s": 4581,
"text": "# PLOT CODE:sns.set_style('white')fig, ax = plt.subplots(figsize=(16, 7))sns.distplot( df[df['gender'] == 'girl']['filled_weight'], kde=True, hist=False, ax=ax, label='girls')sns.distplot( df[df['gender'] == 'boy']['filled_weight'], kde=True, hist=False, ax=ax, label='boys')plt.title('Kernel density estimation of weight for boys and girls')sns.despine()"
},
{
"code": null,
"e": 5114,
"s": 4967,
"text": "Let’s use the previous example, but this time, we go a bit further and additionally segment our data into age groups. Let’s create some mock data:"
},
{
"code": null,
"e": 5814,
"s": 5114,
"text": "# paramter for the weight distribution (mean, std)param_map = { 'boy':{ '<10':(40,4), '<20':(60,4), '20+':(70,5), }, 'girl':{ '<10':(30,2), '<20':(40,3), '20+':(50,3), }}# generate 10k recordsdf = pd.DataFrame({ 'gender':np.random.choice(['girl','boy'],10000), 'age_cohort':np.random.choice(['<10','<20','20+'],10000)})# set random weight based on parametersdf['weight'] = df.apply( lambda x: np.random.normal( loc=param_map[x['gender']][x['age_cohort']][0], scale=param_map[x['gender']][x['age_cohort']][1] ),axis=1)# set 500 values missingfor i in range(500): df.loc[np.random.randint(0,len(df)),'weight'] = np.nan"
},
{
"code": null,
"e": 5893,
"s": 5814,
"text": "Plotting the data reveals somewhat strange bimodal distributions (code below)."
},
{
"code": null,
"e": 6102,
"s": 5893,
"text": "# PLOT CODEdf['filled_weight'] = df['weight'].fillna( df['weight'].mean())g = sns.FacetGrid( df, col='age_cohort', row='gender', col_order=['<10','<20','20+'])g.map(sns.kdeplot,'filled_weight')"
},
{
"code": null,
"e": 6334,
"s": 6102,
"text": "Now, if we would only replace the missing values with the mean for the respective gender, this would not go far enough as not only boys and girls are different in weight, but also different age groups are quite different in weight."
},
{
"code": null,
"e": 6446,
"s": 6334,
"text": "Luckily, transform can be applied just as before. We would group on both columns instead of only one like this:"
},
{
"code": null,
"e": 6566,
"s": 6446,
"text": "df['filled_weight'] = df.groupby(['gender','age_cohort'])['weight'].transform( lambda grp: grp.fillna(np.mean(grp)))"
},
{
"code": null,
"e": 6630,
"s": 6566,
"text": "Running the above snippet will generate this much cleaner plot:"
},
{
"code": null,
"e": 6700,
"s": 6630,
"text": "Two situations frequently come up when working with time-series data."
},
{
"code": null,
"e": 7429,
"s": 6700,
"text": "Aligning date ranges: Say you look at countries’ GDP, education level, and population growth by year. For some countries, you are missing the very first, some of the later years, or some years in between. Sure, you could ignore them. Still, for visualization purposes, you might want to keep them around and project your first observed value to the beginning, your last observed value to the end of your survey period, and come up with something that makes sense for the values in the middle.Interpolation: Looking at time-series data interpolation and thus ordering becomes very relevant. Replacing missing stock data from 2012 with an average that is calculated based on data up to 2019 is bound to produce some wacky results."
},
{
"code": null,
"e": 7922,
"s": 7429,
"text": "Aligning date ranges: Say you look at countries’ GDP, education level, and population growth by year. For some countries, you are missing the very first, some of the later years, or some years in between. Sure, you could ignore them. Still, for visualization purposes, you might want to keep them around and project your first observed value to the beginning, your last observed value to the end of your survey period, and come up with something that makes sense for the values in the middle."
},
{
"code": null,
"e": 8159,
"s": 7922,
"text": "Interpolation: Looking at time-series data interpolation and thus ordering becomes very relevant. Replacing missing stock data from 2012 with an average that is calculated based on data up to 2019 is bound to produce some wacky results."
},
{
"code": null,
"e": 8423,
"s": 8159,
"text": "We will look at an example based on data from the World Happiness Report 2019, where we address both situations. The World Happiness Report tries to answer which factors influence happiness throughout the world. The report surveys data from the year 2005 to 2018."
},
{
"code": null,
"e": 8554,
"s": 8423,
"text": "# Load the datadf = pd.read_csv('https://raw.githubusercontent.com/FBosler/you-datascientist/master/happiness_with_continent.csv')"
},
{
"code": null,
"e": 8668,
"s": 8554,
"text": "df.sample(5) as opposed to df.head(5) selects five random rows, thus giving you a more unbiased view of the data."
},
{
"code": null,
"e": 8740,
"s": 8668,
"text": "Let’s take a look at the number of countries per year we have data for."
},
{
"code": null,
"e": 8862,
"s": 8740,
"text": "# PLOT CODE:df.groupby(['Year']).size().plot( kind='bar', title='Number of countries with data', figsize=(10,5))"
},
{
"code": null,
"e": 9087,
"s": 8862,
"text": "We can see that, especially for the earlier years, we don’t have many countries with data, and also there is some fluctuation across the entire sample period. To mitigate the effect of missing data, we will do the following:"
},
{
"code": null,
"e": 9267,
"s": 9087,
"text": "Group by country and reindex to the whole date rangeInterpolate for years between and extrapolate for years outside the range for which we have observations on a per-country basis"
},
{
"code": null,
"e": 9320,
"s": 9267,
"text": "Group by country and reindex to the whole date range"
},
{
"code": null,
"e": 9448,
"s": 9320,
"text": "Interpolate for years between and extrapolate for years outside the range for which we have observations on a per-country basis"
},
{
"code": null,
"e": 9718,
"s": 9448,
"text": "# Define helper functiondef add_missing_years(grp): _ = grp.set_index('Year') _ = _.reindex(list(range(2005,2019))) del _['Country name'] return _# Group by country name and extenddf = df.groupby('Country name').apply(add_missing_years)df = df.reset_index()"
},
{
"code": null,
"e": 9800,
"s": 9718,
"text": "We now have roughly 600 more rows. However, those observations are null right now"
},
{
"code": null,
"e": 10152,
"s": 9800,
"text": "# Define helper functiondef fill_missing(grp): res = grp.set_index('Year')\\ .interpolate(method='linear',limit=5)\\ .fillna(method='ffill')\\ .fillna(method='bfill') del res['Country name'] return res# Group by country name and fill missingdf = df.groupby(['Country name']).apply( lambda grp: fill_missing(grp))df = df.reset_index()"
},
{
"code": null,
"e": 10257,
"s": 10152,
"text": "The fill_missing function interpolates and extrapolates towards the end and the beginning, resulting in:"
},
{
"code": null,
"e": 10503,
"s": 10257,
"text": "Perfect! Now we have data for the years 2005 to 2018 for all countries in our sample. The above methods were quite relevant for me when writing this article about visualizations. Check it out if you want to learn more about the happiness report."
},
{
"code": null,
"e": 10526,
"s": 10503,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10702,
"s": 10526,
"text": "That’s it for today. In this article, you learned how to use transformand apply to replace missing values with something more meaningful than the previous or subsequent value."
},
{
"code": null,
"e": 10819,
"s": 10702,
"text": "Reach out to me on LinkedIn if you discover some fantastic new visualizations, want to give feedback or have a chat."
}
]
|
Ruby on Rails - Routes | The routing module provides URL rewriting in native Ruby. It's a way to redirect incoming requests to controllers and actions. It replaces the mod_rewrite rules. Best of all, Rails' Routing works with any web server. Routes are defined in app/config/routes.rb.
Think of creating routes as drawing a map for your requests. The map tells them where to go based on some predefined pattern −
Rails.application.routes.draw do
Pattern 1 tells some request to go to one place
Pattern 2 tell them to go to another
...
end
Let us consider our library management application contains a controller called BookController. We have to define the routes for those actions which are defined as methods in the BookController class.
Open routes.rb file in library/config/ directory and edit it with the following content.
Rails.application.routes.draw do
get 'book/list'
get 'book/new'
post 'book/create'
patch 'book/update'
get 'book/list'
get 'book/show'
get 'book/edit'
get 'book/delete'
get 'book/update'
get 'book/show_subjects'
end
The routes.rb file defines the actions available in the applications and the type of action such as get, post, and patch.
Use the following command to list all your defined routes, which are useful for tracking down routing problems in your application, or giving you a good overview of the URLs in an application you're trying to get familiar with.
library> rake routes
Next, we will create the code to generate screens to display data and to take input from the user.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2364,
"s": 2103,
"text": "The routing module provides URL rewriting in native Ruby. It's a way to redirect incoming requests to controllers and actions. It replaces the mod_rewrite rules. Best of all, Rails' Routing works with any web server. Routes are defined in app/config/routes.rb."
},
{
"code": null,
"e": 2491,
"s": 2364,
"text": "Think of creating routes as drawing a map for your requests. The map tells them where to go based on some predefined pattern −"
},
{
"code": null,
"e": 2627,
"s": 2491,
"text": "Rails.application.routes.draw do\n Pattern 1 tells some request to go to one place\n Pattern 2 tell them to go to another\n ...\nend\n"
},
{
"code": null,
"e": 2828,
"s": 2627,
"text": "Let us consider our library management application contains a controller called BookController. We have to define the routes for those actions which are defined as methods in the BookController class."
},
{
"code": null,
"e": 2917,
"s": 2828,
"text": "Open routes.rb file in library/config/ directory and edit it with the following content."
},
{
"code": null,
"e": 3164,
"s": 2917,
"text": "Rails.application.routes.draw do\n get 'book/list'\n get 'book/new'\n post 'book/create'\n patch 'book/update'\n get 'book/list'\n get 'book/show'\n get 'book/edit'\n get 'book/delete'\n get 'book/update'\n get 'book/show_subjects'\nend\n"
},
{
"code": null,
"e": 3286,
"s": 3164,
"text": "The routes.rb file defines the actions available in the applications and the type of action such as get, post, and patch."
},
{
"code": null,
"e": 3514,
"s": 3286,
"text": "Use the following command to list all your defined routes, which are useful for tracking down routing problems in your application, or giving you a good overview of the URLs in an application you're trying to get familiar with."
},
{
"code": null,
"e": 3536,
"s": 3514,
"text": "library> rake routes\n"
},
{
"code": null,
"e": 3635,
"s": 3536,
"text": "Next, we will create the code to generate screens to display data and to take input from the user."
},
{
"code": null,
"e": 3642,
"s": 3635,
"text": " Print"
},
{
"code": null,
"e": 3653,
"s": 3642,
"text": " Add Notes"
}
]
|
C# Enum Format Method | The Format method converts value of a specified enumerated type to its equivalent string representation. Here you can also set the format i.e. d for Decimal, x for HexaDecimal, etc.
We have the following enumeration.
enum Stock { PenDrive, Keyboard, Speakers };
The default value gets assigned (initialize).
PenDrive = 0
Keyboard = 1
Speakers = 2
Now, let’s say you want the value of “Keyboard” name.
Stock st = Stock.Keyboard;
For that, try the following and get the constant value for Keyboard name.
Enum.Format(typeof(Stock), st, "d")
The following is the entire example.
Live Demo
using System;
class Demo {
enum Stock { PenDrive, Keyboard, Speakers };
static void Main() {
Stock st = Stock.Keyboard;
Console.WriteLine("Product I need is {0}", st);
Console.WriteLine("Product value: {0}", Enum.Format(typeof(Stock), st, "d"));
}
}
Product I need is Keyboard
Product value: 1 | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "The Format method converts value of a specified enumerated type to its equivalent string representation. Here you can also set the format i.e. d for Decimal, x for HexaDecimal, etc."
},
{
"code": null,
"e": 1279,
"s": 1244,
"text": "We have the following enumeration."
},
{
"code": null,
"e": 1324,
"s": 1279,
"text": "enum Stock { PenDrive, Keyboard, Speakers };"
},
{
"code": null,
"e": 1370,
"s": 1324,
"text": "The default value gets assigned (initialize)."
},
{
"code": null,
"e": 1409,
"s": 1370,
"text": "PenDrive = 0\nKeyboard = 1\nSpeakers = 2"
},
{
"code": null,
"e": 1463,
"s": 1409,
"text": "Now, let’s say you want the value of “Keyboard” name."
},
{
"code": null,
"e": 1490,
"s": 1463,
"text": "Stock st = Stock.Keyboard;"
},
{
"code": null,
"e": 1564,
"s": 1490,
"text": "For that, try the following and get the constant value for Keyboard name."
},
{
"code": null,
"e": 1600,
"s": 1564,
"text": "Enum.Format(typeof(Stock), st, \"d\")"
},
{
"code": null,
"e": 1637,
"s": 1600,
"text": "The following is the entire example."
},
{
"code": null,
"e": 1648,
"s": 1637,
"text": " Live Demo"
},
{
"code": null,
"e": 1925,
"s": 1648,
"text": "using System;\nclass Demo {\n enum Stock { PenDrive, Keyboard, Speakers };\n static void Main() {\n Stock st = Stock.Keyboard;\n Console.WriteLine(\"Product I need is {0}\", st);\n Console.WriteLine(\"Product value: {0}\", Enum.Format(typeof(Stock), st, \"d\"));\n }\n}"
},
{
"code": null,
"e": 1969,
"s": 1925,
"text": "Product I need is Keyboard\nProduct value: 1"
}
]
|
How to create dynamic breadcrumbs using JavaScript? - GeeksforGeeks | 01 Oct, 2021
In this article, we will see how to create dynamic breadcrumbs using JavaScript.
A dynamic breadcrumb allows us to navigate to different pages within the navigational hierarchy, and thus we can organize various pages of the website in a hierarchical manner just like a folder-like structure.
Approach:
The following example is implemented using HTML and JavaScript.
HTML lists like <ol>,<ul>,<li> are used to create the navigation links.
Breadcrumbs dynamic navigation is implemented using various JavaScript functions like jQuery prepend(),clone() and click() methods. On click of each navigation link <a> , the child nodes are appended to its parent along with the “GeeksforGeeks /” link in the bottom div with the class display. This whole navigation hierarchy is shown in the last HTML div using jQuery html() method.
Example: The following code demonstrates the above approach.
HTML
<!DOCTYPE HTML><html><head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> </head><style> body{ background-color:white; } .display{ background-color:red; } </style><body> <h2 style="color:green;">GeeksforGeeks</h2> <div class="topics"> <ol> <li><a href="#"><b>Searching</b></a> <ul> <li><a href="#">Linear Search</a></li> <li><a href="#">Binary Serach</a></li> </ul> </li> <li><a href="#"><b>Sorting</b></a> <ul> <li><a href="#">Bubble Sort</a></li> <li><a href="#">Merge Sort</a> <ul> <li><a href="#"><i>Recursive Merge Sort</i></a></li> <li><a href="#"><i>Iterative Merge Sort</i></a></li> </ul> </li> <li><a href="#">Selection Sort</a></li> <li><a href="#">Insertion Sort</a> </ul> </li> <li><a href="#"><b>Tree</b></a> <ul> <li><a href="#">Binary Tree</a></li> <li><a href=" #">Binary Search Tree</a></li> </ul> </li> </ol></div> <div class="display"> <div class="syllabus"> <a href="#">GeeksforGeeks / </a> </div> </div> <script type="text/javascript"> $('.topics a').on('click', function() { //selecting the syllabus class $select = $('<div class="syllabus"></div>'); $(this).parents('li').each(function(n, li) { //Adding / to each anchor tag of li $select.prepend(' / ',$(li).children('a').clone()); }); // Displaying the hierarchical order of pages. $('.display').html( $select.prepend('<a href="#syllabus">GeeksforGeeks</a>')); }) </script></body> </html>
Output:
Before execute:
After execute:
anikakapoor
JavaScript-Methods
JavaScript-Questions
Picked
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 filter object array based on attributes?
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": 25398,
"s": 25370,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 25479,
"s": 25398,
"text": "In this article, we will see how to create dynamic breadcrumbs using JavaScript."
},
{
"code": null,
"e": 25691,
"s": 25479,
"text": " A dynamic breadcrumb allows us to navigate to different pages within the navigational hierarchy, and thus we can organize various pages of the website in a hierarchical manner just like a folder-like structure."
},
{
"code": null,
"e": 25701,
"s": 25691,
"text": "Approach:"
},
{
"code": null,
"e": 25765,
"s": 25701,
"text": "The following example is implemented using HTML and JavaScript."
},
{
"code": null,
"e": 25838,
"s": 25765,
"text": "HTML lists like <ol>,<ul>,<li> are used to create the navigation links. "
},
{
"code": null,
"e": 26222,
"s": 25838,
"text": "Breadcrumbs dynamic navigation is implemented using various JavaScript functions like jQuery prepend(),clone() and click() methods. On click of each navigation link <a> , the child nodes are appended to its parent along with the “GeeksforGeeks /” link in the bottom div with the class display. This whole navigation hierarchy is shown in the last HTML div using jQuery html() method."
},
{
"code": null,
"e": 26283,
"s": 26222,
"text": "Example: The following code demonstrates the above approach."
},
{
"code": null,
"e": 26288,
"s": 26283,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html><head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> </head><style> body{ background-color:white; } .display{ background-color:red; } </style><body> <h2 style=\"color:green;\">GeeksforGeeks</h2> <div class=\"topics\"> <ol> <li><a href=\"#\"><b>Searching</b></a> <ul> <li><a href=\"#\">Linear Search</a></li> <li><a href=\"#\">Binary Serach</a></li> </ul> </li> <li><a href=\"#\"><b>Sorting</b></a> <ul> <li><a href=\"#\">Bubble Sort</a></li> <li><a href=\"#\">Merge Sort</a> <ul> <li><a href=\"#\"><i>Recursive Merge Sort</i></a></li> <li><a href=\"#\"><i>Iterative Merge Sort</i></a></li> </ul> </li> <li><a href=\"#\">Selection Sort</a></li> <li><a href=\"#\">Insertion Sort</a> </ul> </li> <li><a href=\"#\"><b>Tree</b></a> <ul> <li><a href=\"#\">Binary Tree</a></li> <li><a href=\" #\">Binary Search Tree</a></li> </ul> </li> </ol></div> <div class=\"display\"> <div class=\"syllabus\"> <a href=\"#\">GeeksforGeeks / </a> </div> </div> <script type=\"text/javascript\"> $('.topics a').on('click', function() { //selecting the syllabus class $select = $('<div class=\"syllabus\"></div>'); $(this).parents('li').each(function(n, li) { //Adding / to each anchor tag of li $select.prepend(' / ',$(li).children('a').clone()); }); // Displaying the hierarchical order of pages. $('.display').html( $select.prepend('<a href=\"#syllabus\">GeeksforGeeks</a>')); }) </script></body> </html>",
"e": 28045,
"s": 26288,
"text": null
},
{
"code": null,
"e": 28053,
"s": 28045,
"text": "Output:"
},
{
"code": null,
"e": 28069,
"s": 28053,
"text": "Before execute:"
},
{
"code": null,
"e": 28084,
"s": 28069,
"text": "After execute:"
},
{
"code": null,
"e": 28096,
"s": 28084,
"text": "anikakapoor"
},
{
"code": null,
"e": 28115,
"s": 28096,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 28136,
"s": 28115,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28143,
"s": 28136,
"text": "Picked"
},
{
"code": null,
"e": 28154,
"s": 28143,
"text": "JavaScript"
},
{
"code": null,
"e": 28171,
"s": 28154,
"text": "Web Technologies"
},
{
"code": null,
"e": 28269,
"s": 28171,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28309,
"s": 28269,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28370,
"s": 28309,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28411,
"s": 28370,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28433,
"s": 28411,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28481,
"s": 28433,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28521,
"s": 28481,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28554,
"s": 28521,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28597,
"s": 28554,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28647,
"s": 28597,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Soft and Hard links in Unix/Linux - GeeksforGeeks | 31 Jan, 2021
A link in UNIX is a pointer to a file. Like pointers in any programming languages, links in UNIX are pointers pointing to a file or a directory. Creating links is a kind of shortcuts to access a file. Links allow more than one file name to refer to the same file, elsewhere.
There are two types of links :
Soft Link or Symbolic linksHard Links
Soft Link or Symbolic links
Hard Links
These links behave differently when the source of the link (what is being linked to) is moved or removed. Symbolic links are not updated (they merely contain a string which is the path name of its target); hard links always refer to the source, even if moved or removed.
For example, if we have a file a.txt. If we create a hard link to the file and then delete the file, we can still access the file using hard link. But if we create a soft link of the file and then delete the file, we can’t access the file through soft link and soft link becomes dangling. Basically hard link increases reference count of a location while soft links work as a shortcut (like in Windows)
1. Hard Links
Each hard linked file is assigned the same Inode value as the original, therefore they reference the same physical file location. Hard links more flexible and remain linked even if the original or linked files are moved throughout the file system, although hard links are unable to cross different file systems.
ls -l command shows all the links with the link column shows number of links.
Links have actual file contents
Removing any link, just reduces the link count, but doesn’t affect other links.
Even if we change the filename of the original file then also the hard links properly work.
We cannot create a hard link for a directory to avoid recursive loops.
If original file is removed then the link will still show the content of the file.
The size of any of the hard link file is same as the original file and if we change the content in any of the hard links then size of all hard link files are updated.
The disadvantage of hard links is that it cannot be created for files on different file systems and it cannot be created for special files or directories.
Command to create a hard link is:
$ ln [original filename] [link name]
2. Soft Links
A soft link is similar to the file shortcut feature which is used in Windows Operating systems. Each soft linked file contains a separate Inode value that points to the original file. As similar to hard links, any changes to the data in either file is reflected in the other. Soft links can be linked across different file systems, although if the original file is deleted or moved, the soft linked file will not work correctly (called hanging link).
ls -l command shows all links with first column value l? and the link points to original file.
Soft Link contains the path for original file and not the contents.
Removing soft link doesn’t affect anything but removing original file, the link becomes “dangling” link which points to nonexistent file.
A soft link can link to a directory.
Size of a soft link is equal to the name of the file for which the soft link is created. E.g If name of file is file1 then size of it’s soft link will be 5 bytes which is equal to size of name of original file.
If we change the name of the original file then all the soft links for that file become dangling i.e. they are worthless now.
Link across file systems: If you want to link files across the file systems, you can only use symlinks/soft links.
Command to create a Soft link is:
$ ln -s [original filename] [link name]
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akash Gajjar
ankitshuklatiwari1
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
diff command in Linux with examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples | [
{
"code": null,
"e": 24644,
"s": 24616,
"text": "\n31 Jan, 2021"
},
{
"code": null,
"e": 24920,
"s": 24644,
"text": "A link in UNIX is a pointer to a file. Like pointers in any programming languages, links in UNIX are pointers pointing to a file or a directory. Creating links is a kind of shortcuts to access a file. Links allow more than one file name to refer to the same file, elsewhere. "
},
{
"code": null,
"e": 24951,
"s": 24920,
"text": "There are two types of links :"
},
{
"code": null,
"e": 24989,
"s": 24951,
"text": "Soft Link or Symbolic linksHard Links"
},
{
"code": null,
"e": 25017,
"s": 24989,
"text": "Soft Link or Symbolic links"
},
{
"code": null,
"e": 25028,
"s": 25017,
"text": "Hard Links"
},
{
"code": null,
"e": 25300,
"s": 25028,
"text": "These links behave differently when the source of the link (what is being linked to) is moved or removed. Symbolic links are not updated (they merely contain a string which is the path name of its target); hard links always refer to the source, even if moved or removed. "
},
{
"code": null,
"e": 25704,
"s": 25300,
"text": "For example, if we have a file a.txt. If we create a hard link to the file and then delete the file, we can still access the file using hard link. But if we create a soft link of the file and then delete the file, we can’t access the file through soft link and soft link becomes dangling. Basically hard link increases reference count of a location while soft links work as a shortcut (like in Windows) "
},
{
"code": null,
"e": 25720,
"s": 25704,
"text": "1. Hard Links "
},
{
"code": null,
"e": 26032,
"s": 25720,
"text": "Each hard linked file is assigned the same Inode value as the original, therefore they reference the same physical file location. Hard links more flexible and remain linked even if the original or linked files are moved throughout the file system, although hard links are unable to cross different file systems."
},
{
"code": null,
"e": 26110,
"s": 26032,
"text": "ls -l command shows all the links with the link column shows number of links."
},
{
"code": null,
"e": 26142,
"s": 26110,
"text": "Links have actual file contents"
},
{
"code": null,
"e": 26222,
"s": 26142,
"text": "Removing any link, just reduces the link count, but doesn’t affect other links."
},
{
"code": null,
"e": 26314,
"s": 26222,
"text": "Even if we change the filename of the original file then also the hard links properly work."
},
{
"code": null,
"e": 26385,
"s": 26314,
"text": "We cannot create a hard link for a directory to avoid recursive loops."
},
{
"code": null,
"e": 26468,
"s": 26385,
"text": "If original file is removed then the link will still show the content of the file."
},
{
"code": null,
"e": 26635,
"s": 26468,
"text": "The size of any of the hard link file is same as the original file and if we change the content in any of the hard links then size of all hard link files are updated."
},
{
"code": null,
"e": 26790,
"s": 26635,
"text": "The disadvantage of hard links is that it cannot be created for files on different file systems and it cannot be created for special files or directories."
},
{
"code": null,
"e": 26826,
"s": 26790,
"text": "Command to create a hard link is: "
},
{
"code": null,
"e": 26868,
"s": 26826,
"text": "$ ln [original filename] [link name] \n\n\n"
},
{
"code": null,
"e": 26886,
"s": 26870,
"text": "2. Soft Links "
},
{
"code": null,
"e": 27337,
"s": 26886,
"text": "A soft link is similar to the file shortcut feature which is used in Windows Operating systems. Each soft linked file contains a separate Inode value that points to the original file. As similar to hard links, any changes to the data in either file is reflected in the other. Soft links can be linked across different file systems, although if the original file is deleted or moved, the soft linked file will not work correctly (called hanging link)."
},
{
"code": null,
"e": 27432,
"s": 27337,
"text": "ls -l command shows all links with first column value l? and the link points to original file."
},
{
"code": null,
"e": 27500,
"s": 27432,
"text": "Soft Link contains the path for original file and not the contents."
},
{
"code": null,
"e": 27638,
"s": 27500,
"text": "Removing soft link doesn’t affect anything but removing original file, the link becomes “dangling” link which points to nonexistent file."
},
{
"code": null,
"e": 27675,
"s": 27638,
"text": "A soft link can link to a directory."
},
{
"code": null,
"e": 27886,
"s": 27675,
"text": "Size of a soft link is equal to the name of the file for which the soft link is created. E.g If name of file is file1 then size of it’s soft link will be 5 bytes which is equal to size of name of original file."
},
{
"code": null,
"e": 28012,
"s": 27886,
"text": "If we change the name of the original file then all the soft links for that file become dangling i.e. they are worthless now."
},
{
"code": null,
"e": 28127,
"s": 28012,
"text": "Link across file systems: If you want to link files across the file systems, you can only use symlinks/soft links."
},
{
"code": null,
"e": 28163,
"s": 28127,
"text": "Command to create a Soft link is: "
},
{
"code": null,
"e": 28208,
"s": 28163,
"text": "$ ln -s [original filename] [link name] \n\n\n"
},
{
"code": null,
"e": 28511,
"s": 28210,
"text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 28637,
"s": 28511,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28650,
"s": 28637,
"text": "Akash Gajjar"
},
{
"code": null,
"e": 28669,
"s": 28650,
"text": "ankitshuklatiwari1"
},
{
"code": null,
"e": 28683,
"s": 28669,
"text": "linux-command"
},
{
"code": null,
"e": 28694,
"s": 28683,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28792,
"s": 28694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28827,
"s": 28792,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28863,
"s": 28827,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 28901,
"s": 28863,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28937,
"s": 28901,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 28973,
"s": 28937,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 29006,
"s": 28973,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 29044,
"s": 29006,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29079,
"s": 29044,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 29116,
"s": 29079,
"text": "touch command in Linux with Examples"
}
]
|
Accelerate your training and inference running on Tensorflow | by Ranjeet Singh | Towards Data Science | Tensorflow comes with default settings to be compatible with as many CPUs/GPUs as it can. You can easily optimize it to use the full capabilities of your CPU such as AVX or of your GPU such as Tensor Cores leading to up to a 3x accelerated code.
Similarily If you are a startup, you might not have unlimited access to GPUs or the case might be to deploy a model on CPU, you can still optimize your Tensorflow code to reduce its size for faster inference on any device. Below I’m going to discuss several ways to accelerate your Training or Inference or both.
The most popular way to install Tensorflow in via pip but such an installation is pretty slow. Why?
The default builds from pip install tensorflow are intended to be compatible with as many CPUs as possible. If you ever have seen logs in your console while running your Tensorflow program, you must have seen such a warning- “Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA”
What does this warning mean? Modern CPUs provide a lot of extensions to low-level instruction set such as SSE2, SSE4, AVX, etc
If you have a GPU, you shouldn’t care about AVX support, because most expensive ops will be dispatched on a GPU device (unless explicitly set not to)
Building it from the source itself might speed up your Tensorflow program significantly. TensorFlow actually warns you about doing just. You should build TensorFlow from the source optimized for your CPU with AVX, AVX2, and FMA enabled whichever your CPU supports.
Accelerated Linear Algebra, XLA is a domain-specific compiler for matrix operations. It can accelerate TensorFlow models with no changes in the source code.
When a TensorFlow program is run, all of the operations are executed individually by the TensorFlow executor. Each TensorFlow operation has a pre-compiled GPU kernel implementation that the executor dispatches to.
XLA provides an alternative mode of running models: it compiles the TensorFlow graph into a sequence of computation kernels generated specifically for the given model. Because these kernels are unique to the model, they can exploit model-specific information for optimization. Along with many others, Fusion is XLA’s single most important optimization which I will discuss later in this post in detail.
The results are improvements in speed and memory usage: most internal benchmarks run ~1.15x faster after XLA is enabled.
Enabling XLA is quite easy-
import tensorflow as tftf.config.optimizer.set_jit(True)# ... the rest of your program ..
Try XLA example in Colab here
Mixed precision training offers significant computational speedup by performing operations in the half-precision format while storing minimal information in single-precision to retain as much information as possible in critical parts of the network.
There are numerous benefits to using numerical formats with lower precision than 32-bit floating-point. First, they require less memory, enabling the training and deployment of larger neural networks. Second, they require less memory bandwidth, thereby speeding up data transfer operations. Third, math operations run much faster in reduced precision, especially on GPUs with Tensor Core support for that precision. It does so by identifying the steps that require full precision and using 32-bit floating-point for only those steps while using 16-bit floating-point everywhere else.
Speeds up math-intensive operations, such as linear and convolution layers, by using Tensor Cores.
Speeds up memory-limited operations by accessing half the bytes compared to single-precision.
Reduces memory requirements for training models, enabling larger models or larger mini-batches.
Among NVIDIA GPUs, those with compute capability 7.0 or higher will see the greatest performance benefit from mixed-precision because they have special hardware units, called Tensor Cores, to accelerate float16 matrix multiplications and convolutions.
Mix Precision in Tensorflow
The mixed precision API is available in TensorFlow 2.1 with Keras interface. To use mixed precision in Keras, you need to create, typically referred to as a dtype policy. Dtype policies specify the dtypes layers will run in. This will cause subsequently created layers to use mixed precision with a mix of float16 and float32.
from tensorflow.keras.mixed_precision import experimental as mixed_precisionpolicy = mixed_precision.Policy('mixed_float16')mixed_precision.set_policy(policy)# Now design your model and train it
Imp. note- Tensor Cores which provide mix precision, requires certain dimensions of tensors such as dimensions of your dense layer, number of filters in Conv layers, number of units in RNN layer to be a multiple of 8.
To compare the performance of mixed-precision with float32, change the policy from mixed_float16 to float32. The Expected performance improvement is up to 3x.
I already have covered this concept in one of my previous blogs. In very brief how pruning works-
If you could rank the neurons or the connection in between them according to how much they contribute, you could then remove the low ranking neurons or connections from the network, resulting in a smaller and faster network.
Pruning in Tensorflow
Tensorflow provides Model Optimization Toolkit for pruning and other post-training optimizations. To use it in your code, here is a simple example-
import tensorflow_model_optimization as tfmotmodel = build_your_model() pruning_schedule = tfmot.sparsity.keras.PolynomialDecay( initial_sparsity=0.0, final_sparsity=0.5, begin_step=1000, end_step=3000)model_for_pruning = tfmot.sparsity.keras.prune_low_magnitude(model, pruning_schedule=pruning_schedule)... model_for_pruning.fit(...)
Normally when you run a TensorFlow graph, all of the operations are executed individually by the TensorFlow graph executor. Each op has a pre-compiled GPU kernel implementation. Fused Ops combine operations into a single kernel for improved performance.
For example-
def model_fn(x, y, z): return tf.reduce_sum(x + y * z)
Without fusion, without XLA, the graph launches three kernels: one for the multiplication, one for the addition and one for the reduction.
With op fusion, you can compute the result in a single kernel launch. It does this by “fusing” the addition, multiplication, and reduction into a single GPU kernel.
Fusion with Tensorflow 2.x
Newer Tensorflow versions come with XLA which does fusion along with other optimizations for us.
from tensorflow.contrib.compiler import xladef model_fn(x, y, z): return tf.reduce_sum(x + y * z)def create_and_run_graph(): with tf.Session() as sess: x = tf.placeholder(tf.float32, name='x') y = tf.placeholder(tf.float32, name='y') z = tf.placeholder(tf.float32, name='z') result = xla.compile(computation=model_fn, inputs=(x, y, z))[0] # `result` is a normal Tensor (albeit one that is computed by an XLA # compiled executable) and can be used like any other Tensor. result = tf.add(result, result) return sess.run(result, feed_dict={ ... })
Examples of patterns fused:
■ Conv2D + BiasAdd + <Activation>
■ Conv2D + FusedBatchNorm + <Activation>
■ Conv2D + Squeeze + BiasAdd
■ MatMul + BiasAdd + <Activation>
Fusing ops together provides several performance advantages:
○ Completely eliminates Op scheduling overhead (big win for cheap ops)
○ Increases opportunities for ILP, vectorization etc.
○ Improves temporal and spatial locality of data access
E.g. MatMul is computed block-wise and bias and activation function can be applied while data is still “hot” in cache.
Fusion with Tensorflow 1.x
In Tf 1.x, layers compatible with fused ops have ‘fused’ argument which needs to be set to True to use fusion for faster implementation.
For example-
#Using TF1.x in TF2.xb1 = tf.layers.batch_normalization( input_layer, fused=True, data_format='NCHW') #Or in pure TF1.xb1 = tf.layers.batch_normalization | [
{
"code": null,
"e": 417,
"s": 171,
"text": "Tensorflow comes with default settings to be compatible with as many CPUs/GPUs as it can. You can easily optimize it to use the full capabilities of your CPU such as AVX or of your GPU such as Tensor Cores leading to up to a 3x accelerated code."
},
{
"code": null,
"e": 730,
"s": 417,
"text": "Similarily If you are a startup, you might not have unlimited access to GPUs or the case might be to deploy a model on CPU, you can still optimize your Tensorflow code to reduce its size for faster inference on any device. Below I’m going to discuss several ways to accelerate your Training or Inference or both."
},
{
"code": null,
"e": 830,
"s": 730,
"text": "The most popular way to install Tensorflow in via pip but such an installation is pretty slow. Why?"
},
{
"code": null,
"e": 1150,
"s": 830,
"text": "The default builds from pip install tensorflow are intended to be compatible with as many CPUs as possible. If you ever have seen logs in your console while running your Tensorflow program, you must have seen such a warning- “Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA”"
},
{
"code": null,
"e": 1277,
"s": 1150,
"text": "What does this warning mean? Modern CPUs provide a lot of extensions to low-level instruction set such as SSE2, SSE4, AVX, etc"
},
{
"code": null,
"e": 1427,
"s": 1277,
"text": "If you have a GPU, you shouldn’t care about AVX support, because most expensive ops will be dispatched on a GPU device (unless explicitly set not to)"
},
{
"code": null,
"e": 1692,
"s": 1427,
"text": "Building it from the source itself might speed up your Tensorflow program significantly. TensorFlow actually warns you about doing just. You should build TensorFlow from the source optimized for your CPU with AVX, AVX2, and FMA enabled whichever your CPU supports."
},
{
"code": null,
"e": 1849,
"s": 1692,
"text": "Accelerated Linear Algebra, XLA is a domain-specific compiler for matrix operations. It can accelerate TensorFlow models with no changes in the source code."
},
{
"code": null,
"e": 2063,
"s": 1849,
"text": "When a TensorFlow program is run, all of the operations are executed individually by the TensorFlow executor. Each TensorFlow operation has a pre-compiled GPU kernel implementation that the executor dispatches to."
},
{
"code": null,
"e": 2466,
"s": 2063,
"text": "XLA provides an alternative mode of running models: it compiles the TensorFlow graph into a sequence of computation kernels generated specifically for the given model. Because these kernels are unique to the model, they can exploit model-specific information for optimization. Along with many others, Fusion is XLA’s single most important optimization which I will discuss later in this post in detail."
},
{
"code": null,
"e": 2587,
"s": 2466,
"text": "The results are improvements in speed and memory usage: most internal benchmarks run ~1.15x faster after XLA is enabled."
},
{
"code": null,
"e": 2615,
"s": 2587,
"text": "Enabling XLA is quite easy-"
},
{
"code": null,
"e": 2705,
"s": 2615,
"text": "import tensorflow as tftf.config.optimizer.set_jit(True)# ... the rest of your program .."
},
{
"code": null,
"e": 2735,
"s": 2705,
"text": "Try XLA example in Colab here"
},
{
"code": null,
"e": 2985,
"s": 2735,
"text": "Mixed precision training offers significant computational speedup by performing operations in the half-precision format while storing minimal information in single-precision to retain as much information as possible in critical parts of the network."
},
{
"code": null,
"e": 3569,
"s": 2985,
"text": "There are numerous benefits to using numerical formats with lower precision than 32-bit floating-point. First, they require less memory, enabling the training and deployment of larger neural networks. Second, they require less memory bandwidth, thereby speeding up data transfer operations. Third, math operations run much faster in reduced precision, especially on GPUs with Tensor Core support for that precision. It does so by identifying the steps that require full precision and using 32-bit floating-point for only those steps while using 16-bit floating-point everywhere else."
},
{
"code": null,
"e": 3668,
"s": 3569,
"text": "Speeds up math-intensive operations, such as linear and convolution layers, by using Tensor Cores."
},
{
"code": null,
"e": 3762,
"s": 3668,
"text": "Speeds up memory-limited operations by accessing half the bytes compared to single-precision."
},
{
"code": null,
"e": 3858,
"s": 3762,
"text": "Reduces memory requirements for training models, enabling larger models or larger mini-batches."
},
{
"code": null,
"e": 4110,
"s": 3858,
"text": "Among NVIDIA GPUs, those with compute capability 7.0 or higher will see the greatest performance benefit from mixed-precision because they have special hardware units, called Tensor Cores, to accelerate float16 matrix multiplications and convolutions."
},
{
"code": null,
"e": 4138,
"s": 4110,
"text": "Mix Precision in Tensorflow"
},
{
"code": null,
"e": 4465,
"s": 4138,
"text": "The mixed precision API is available in TensorFlow 2.1 with Keras interface. To use mixed precision in Keras, you need to create, typically referred to as a dtype policy. Dtype policies specify the dtypes layers will run in. This will cause subsequently created layers to use mixed precision with a mix of float16 and float32."
},
{
"code": null,
"e": 4660,
"s": 4465,
"text": "from tensorflow.keras.mixed_precision import experimental as mixed_precisionpolicy = mixed_precision.Policy('mixed_float16')mixed_precision.set_policy(policy)# Now design your model and train it"
},
{
"code": null,
"e": 4878,
"s": 4660,
"text": "Imp. note- Tensor Cores which provide mix precision, requires certain dimensions of tensors such as dimensions of your dense layer, number of filters in Conv layers, number of units in RNN layer to be a multiple of 8."
},
{
"code": null,
"e": 5037,
"s": 4878,
"text": "To compare the performance of mixed-precision with float32, change the policy from mixed_float16 to float32. The Expected performance improvement is up to 3x."
},
{
"code": null,
"e": 5135,
"s": 5037,
"text": "I already have covered this concept in one of my previous blogs. In very brief how pruning works-"
},
{
"code": null,
"e": 5360,
"s": 5135,
"text": "If you could rank the neurons or the connection in between them according to how much they contribute, you could then remove the low ranking neurons or connections from the network, resulting in a smaller and faster network."
},
{
"code": null,
"e": 5382,
"s": 5360,
"text": "Pruning in Tensorflow"
},
{
"code": null,
"e": 5530,
"s": 5382,
"text": "Tensorflow provides Model Optimization Toolkit for pruning and other post-training optimizations. To use it in your code, here is a simple example-"
},
{
"code": null,
"e": 5912,
"s": 5530,
"text": "import tensorflow_model_optimization as tfmotmodel = build_your_model() pruning_schedule = tfmot.sparsity.keras.PolynomialDecay( initial_sparsity=0.0, final_sparsity=0.5, begin_step=1000, end_step=3000)model_for_pruning = tfmot.sparsity.keras.prune_low_magnitude(model, pruning_schedule=pruning_schedule)... model_for_pruning.fit(...)"
},
{
"code": null,
"e": 6166,
"s": 5912,
"text": "Normally when you run a TensorFlow graph, all of the operations are executed individually by the TensorFlow graph executor. Each op has a pre-compiled GPU kernel implementation. Fused Ops combine operations into a single kernel for improved performance."
},
{
"code": null,
"e": 6179,
"s": 6166,
"text": "For example-"
},
{
"code": null,
"e": 6236,
"s": 6179,
"text": "def model_fn(x, y, z): return tf.reduce_sum(x + y * z)"
},
{
"code": null,
"e": 6375,
"s": 6236,
"text": "Without fusion, without XLA, the graph launches three kernels: one for the multiplication, one for the addition and one for the reduction."
},
{
"code": null,
"e": 6540,
"s": 6375,
"text": "With op fusion, you can compute the result in a single kernel launch. It does this by “fusing” the addition, multiplication, and reduction into a single GPU kernel."
},
{
"code": null,
"e": 6567,
"s": 6540,
"text": "Fusion with Tensorflow 2.x"
},
{
"code": null,
"e": 6664,
"s": 6567,
"text": "Newer Tensorflow versions come with XLA which does fusion along with other optimizations for us."
},
{
"code": null,
"e": 7235,
"s": 6664,
"text": "from tensorflow.contrib.compiler import xladef model_fn(x, y, z): return tf.reduce_sum(x + y * z)def create_and_run_graph(): with tf.Session() as sess: x = tf.placeholder(tf.float32, name='x') y = tf.placeholder(tf.float32, name='y') z = tf.placeholder(tf.float32, name='z') result = xla.compile(computation=model_fn, inputs=(x, y, z))[0] # `result` is a normal Tensor (albeit one that is computed by an XLA # compiled executable) and can be used like any other Tensor. result = tf.add(result, result) return sess.run(result, feed_dict={ ... })"
},
{
"code": null,
"e": 7263,
"s": 7235,
"text": "Examples of patterns fused:"
},
{
"code": null,
"e": 7297,
"s": 7263,
"text": "■ Conv2D + BiasAdd + <Activation>"
},
{
"code": null,
"e": 7338,
"s": 7297,
"text": "■ Conv2D + FusedBatchNorm + <Activation>"
},
{
"code": null,
"e": 7367,
"s": 7338,
"text": "■ Conv2D + Squeeze + BiasAdd"
},
{
"code": null,
"e": 7401,
"s": 7367,
"text": "■ MatMul + BiasAdd + <Activation>"
},
{
"code": null,
"e": 7462,
"s": 7401,
"text": "Fusing ops together provides several performance advantages:"
},
{
"code": null,
"e": 7533,
"s": 7462,
"text": "○ Completely eliminates Op scheduling overhead (big win for cheap ops)"
},
{
"code": null,
"e": 7587,
"s": 7533,
"text": "○ Increases opportunities for ILP, vectorization etc."
},
{
"code": null,
"e": 7643,
"s": 7587,
"text": "○ Improves temporal and spatial locality of data access"
},
{
"code": null,
"e": 7762,
"s": 7643,
"text": "E.g. MatMul is computed block-wise and bias and activation function can be applied while data is still “hot” in cache."
},
{
"code": null,
"e": 7789,
"s": 7762,
"text": "Fusion with Tensorflow 1.x"
},
{
"code": null,
"e": 7926,
"s": 7789,
"text": "In Tf 1.x, layers compatible with fused ops have ‘fused’ argument which needs to be set to True to use fusion for faster implementation."
},
{
"code": null,
"e": 7939,
"s": 7926,
"text": "For example-"
}
]
|
How to get the lifecycle of a S3 bucket using Boto3 and AWS Client? | Problem Statement: Use boto3 library in Python to get lifecycle of a S3 bucket. For example, find the lifecycle of Bucket_1 in S3.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − bucket_name is the parameter in the function.
Step 3 − Create an AWS session using boto3 library.
Step 4 − Create an AWS client for S3.
Step 5 − Now, use the function get_bucket_lifecycle_configuration and pass the bucket name.
Step 6 − It returns the dictionary containing the details about S3.
Step 7 − Handle the generic exception if something went wrong while deleting the file.
Use the following code to get the bucket lifecycle −
import boto3
from botocore.exceptions import ClientError
def get_bucket_lifecycle_of_s3(bucket_name):
session = boto3.session.Session()
s3_client = session.client('s3')
try:
result = s3_client.get_bucket_lifecycle_configuration(Bucket=bucket_name,)
except ClientError as e:
raise Exception( "boto3 client error in get_bucket_lifecycle_of_s3 function: " + e.__str__())
except Exception as e:
raise Exception( "Unexpected error in get_bucket_lifecycle_of_s3 function: " + e.__str__())
return result
print(get_bucket_lifecycle_of_s3("Bucket_1"))
{
'Rules': [
{
'ID': 'Rule for TaxDocs/',
'Prefix': 'TaxDocs',
'Status': 'Enabled',
'Transitions': [
{
'Days': 365,
'StorageClass': 'STANDARD_IA',
},
],
},
],
'ResponseMetadata': {
'...': '...',
},
} | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Problem Statement: Use boto3 library in Python to get lifecycle of a S3 bucket. For example, find the lifecycle of Bucket_1 in S3."
},
{
"code": null,
"e": 1261,
"s": 1193,
"text": "Step 1 − Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1316,
"s": 1261,
"text": "Step 2 − bucket_name is the parameter in the function."
},
{
"code": null,
"e": 1368,
"s": 1316,
"text": "Step 3 − Create an AWS session using boto3 library."
},
{
"code": null,
"e": 1406,
"s": 1368,
"text": "Step 4 − Create an AWS client for S3."
},
{
"code": null,
"e": 1498,
"s": 1406,
"text": "Step 5 − Now, use the function get_bucket_lifecycle_configuration and pass the bucket name."
},
{
"code": null,
"e": 1566,
"s": 1498,
"text": "Step 6 − It returns the dictionary containing the details about S3."
},
{
"code": null,
"e": 1653,
"s": 1566,
"text": "Step 7 − Handle the generic exception if something went wrong while deleting the file."
},
{
"code": null,
"e": 1706,
"s": 1653,
"text": "Use the following code to get the bucket lifecycle −"
},
{
"code": null,
"e": 2284,
"s": 1706,
"text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_bucket_lifecycle_of_s3(bucket_name):\n session = boto3.session.Session()\n s3_client = session.client('s3')\n try:\n result = s3_client.get_bucket_lifecycle_configuration(Bucket=bucket_name,)\n except ClientError as e:\n raise Exception( \"boto3 client error in get_bucket_lifecycle_of_s3 function: \" + e.__str__())\n except Exception as e:\n raise Exception( \"Unexpected error in get_bucket_lifecycle_of_s3 function: \" + e.__str__())\nreturn result\n\nprint(get_bucket_lifecycle_of_s3(\"Bucket_1\"))"
},
{
"code": null,
"e": 2613,
"s": 2284,
"text": "{\n 'Rules': [\n {\n 'ID': 'Rule for TaxDocs/',\n 'Prefix': 'TaxDocs',\n 'Status': 'Enabled',\n 'Transitions': [\n {\n 'Days': 365,\n 'StorageClass': 'STANDARD_IA',\n },\n ],\n },\n ],\n 'ResponseMetadata': {\n '...': '...',\n },\n}"
}
]
|
Calculate Correlation Matrix Only for Numeric Columns in R - GeeksforGeeks | 29 Jun, 2021
A correlation matrix is a tabular representation of the relation between numeric attributes of a dataframe. The values present in the table are correlation coefficients between the attributes.
Dataset used: bestsellers
To create a correlation matrix cor() function is called with the dataframe as an argument.
Syntax: cor(dataframe)
Example:
R
df<-read.csv("bestsellers.csv") cor(df)
Output:
Error in cor(df) : 'x' must be numeric
This function fails when the dataframe consists of values apart from numeric values. Creating a correlation matrix in such a situation can be done by any of the methods given below.
Here cor() is called as above in the dataframe but this time only numeric columns are given to it. To filter out numeric columns, an operation to check numeric values is applied on the data frame using sapply().
sapply() function in R Language takes to list, vector, or data frame as input and gives output in a vector or matrix. It is useful for operations on list objects and returns a list object of the same length as the original set.
Syntax: sapply(X, FUN)
Parameters:
X: A vector or an object
FUN: Function applied to each element of x
Example:
R
df<-read.csv("bestsellers.csv") cor(df[sapply(df,is.numeric)])
Output:
Similarly, lapply can also be applied to filter out the numeric values. lapply() function R Language is used to apply a function over a list of elements.
Syntax: lapply(list, func)
Parameters:
list: list of elements
func: operation to be applied
After the required data is selected, the list is converted to a vector using unlist(), and then this dataframe is passed to cor() to produce a correlation matrix.
unlist() function in R Language is used to convert a list to a vector. It simplifies to produce a vector by preserving all components.
Syntax: unlist(list)
Parameters:list: It is a list or Vectoruse.name: Boolean value to prserve or not the position names
Example:
R
df<-read.csv("bestsellers.csv") cor(df[, unlist(lapply(df, is.numeric))])
Output:
Picked
R-Matrix
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Logistic Regression in R Programming
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
How to change the order of bars in bar chart in R ?
R - if statement
Replace Specific Characters in String in R | [
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 25436,
"s": 25242,
"text": "A correlation matrix is a tabular representation of the relation between numeric attributes of a dataframe. The values present in the table are correlation coefficients between the attributes. "
},
{
"code": null,
"e": 25462,
"s": 25436,
"text": "Dataset used: bestsellers"
},
{
"code": null,
"e": 25553,
"s": 25462,
"text": "To create a correlation matrix cor() function is called with the dataframe as an argument."
},
{
"code": null,
"e": 25576,
"s": 25553,
"text": "Syntax: cor(dataframe)"
},
{
"code": null,
"e": 25585,
"s": 25576,
"text": "Example:"
},
{
"code": null,
"e": 25587,
"s": 25585,
"text": "R"
},
{
"code": "df<-read.csv(\"bestsellers.csv\") cor(df)",
"e": 25628,
"s": 25587,
"text": null
},
{
"code": null,
"e": 25636,
"s": 25628,
"text": "Output:"
},
{
"code": null,
"e": 25675,
"s": 25636,
"text": "Error in cor(df) : 'x' must be numeric"
},
{
"code": null,
"e": 25857,
"s": 25675,
"text": "This function fails when the dataframe consists of values apart from numeric values. Creating a correlation matrix in such a situation can be done by any of the methods given below."
},
{
"code": null,
"e": 26069,
"s": 25857,
"text": "Here cor() is called as above in the dataframe but this time only numeric columns are given to it. To filter out numeric columns, an operation to check numeric values is applied on the data frame using sapply()."
},
{
"code": null,
"e": 26297,
"s": 26069,
"text": "sapply() function in R Language takes to list, vector, or data frame as input and gives output in a vector or matrix. It is useful for operations on list objects and returns a list object of the same length as the original set."
},
{
"code": null,
"e": 26320,
"s": 26297,
"text": "Syntax: sapply(X, FUN)"
},
{
"code": null,
"e": 26332,
"s": 26320,
"text": "Parameters:"
},
{
"code": null,
"e": 26357,
"s": 26332,
"text": "X: A vector or an object"
},
{
"code": null,
"e": 26400,
"s": 26357,
"text": "FUN: Function applied to each element of x"
},
{
"code": null,
"e": 26409,
"s": 26400,
"text": "Example:"
},
{
"code": null,
"e": 26411,
"s": 26409,
"text": "R"
},
{
"code": "df<-read.csv(\"bestsellers.csv\") cor(df[sapply(df,is.numeric)])",
"e": 26475,
"s": 26411,
"text": null
},
{
"code": null,
"e": 26483,
"s": 26475,
"text": "Output:"
},
{
"code": null,
"e": 26637,
"s": 26483,
"text": "Similarly, lapply can also be applied to filter out the numeric values. lapply() function R Language is used to apply a function over a list of elements."
},
{
"code": null,
"e": 26664,
"s": 26637,
"text": "Syntax: lapply(list, func)"
},
{
"code": null,
"e": 26676,
"s": 26664,
"text": "Parameters:"
},
{
"code": null,
"e": 26699,
"s": 26676,
"text": "list: list of elements"
},
{
"code": null,
"e": 26729,
"s": 26699,
"text": "func: operation to be applied"
},
{
"code": null,
"e": 26892,
"s": 26729,
"text": "After the required data is selected, the list is converted to a vector using unlist(), and then this dataframe is passed to cor() to produce a correlation matrix."
},
{
"code": null,
"e": 27027,
"s": 26892,
"text": "unlist() function in R Language is used to convert a list to a vector. It simplifies to produce a vector by preserving all components."
},
{
"code": null,
"e": 27048,
"s": 27027,
"text": "Syntax: unlist(list)"
},
{
"code": null,
"e": 27148,
"s": 27048,
"text": "Parameters:list: It is a list or Vectoruse.name: Boolean value to prserve or not the position names"
},
{
"code": null,
"e": 27157,
"s": 27148,
"text": "Example:"
},
{
"code": null,
"e": 27159,
"s": 27157,
"text": "R"
},
{
"code": "df<-read.csv(\"bestsellers.csv\") cor(df[, unlist(lapply(df, is.numeric))])",
"e": 27234,
"s": 27159,
"text": null
},
{
"code": null,
"e": 27242,
"s": 27234,
"text": "Output:"
},
{
"code": null,
"e": 27249,
"s": 27242,
"text": "Picked"
},
{
"code": null,
"e": 27258,
"s": 27249,
"text": "R-Matrix"
},
{
"code": null,
"e": 27271,
"s": 27258,
"text": "R-Statistics"
},
{
"code": null,
"e": 27282,
"s": 27271,
"text": "R Language"
},
{
"code": null,
"e": 27380,
"s": 27282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27389,
"s": 27380,
"text": "Comments"
},
{
"code": null,
"e": 27402,
"s": 27389,
"text": "Old Comments"
},
{
"code": null,
"e": 27454,
"s": 27402,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27492,
"s": 27454,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27527,
"s": 27492,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27585,
"s": 27527,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27622,
"s": 27585,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 27659,
"s": 27622,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27708,
"s": 27659,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27760,
"s": 27708,
"text": "How to change the order of bars in bar chart in R ?"
},
{
"code": null,
"e": 27777,
"s": 27760,
"text": "R - if statement"
}
]
|
Count Derangements (Permutation such that no element appears in its original position) - GeeksforGeeks | 13 Mar, 2022
A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0}.Given a number n, find the total number of Derangements of a set of n elements.
Examples :
Input: n = 2
Output: 1
For two elements say {0, 1}, there is only one
possible derangement {1, 0}
Input: n = 3
Output: 2
For three elements say {0, 1, 2}, there are two
possible derangements {2, 0, 1} and {1, 2, 0}
Input: n = 4
Output: 9
For four elements say {0, 1, 2, 3}, there are 9
possible derangements {1, 0, 3, 2} {1, 2, 3, 0}
{1, 3, 0, 2}, {2, 3, 0, 1}, {2, 0, 3, 1}, {2, 3,
1, 0}, {3, 0, 1, 2}, {3, 2, 0, 1} and {3, 2, 1, 0}
Let countDer(n) be count of derangements for n elements. Below is the recursive relation to it.
countDer(n) = (n - 1) * [countDer(n - 1) + countDer(n - 2)]
How does above recursive relation work?
There are n – 1 way for element 0 (this explains multiplication with n – 1). Let 0 be placed at index i. There are now two possibilities, depending on whether or not element i is placed at 0 in return.
i is placed at 0: This case is equivalent to solving the problem for n-2 elements as two elements have just swapped their positions.i is not placed at 0: This case is equivalent to solving the problem for n-1 elements as now there are n-1 elements, n-1 positions and every element has n-2 choices
i is placed at 0: This case is equivalent to solving the problem for n-2 elements as two elements have just swapped their positions.
i is not placed at 0: This case is equivalent to solving the problem for n-1 elements as now there are n-1 elements, n-1 positions and every element has n-2 choices
Below is the simple solution based on the above recursive formula:
C++
Java
Python3
C#
PHP
Javascript
// A Naive Recursive C++ program// to count derangements#include <bits/stdc++.h>using namespace std; int countDer(int n){ // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2));} // Driver Codeint main(){ int n = 4; cout << "Count of Derangements is " << countDer(n); return 0;}
// A Naive Recursive java// program to count derangementsimport java.io.*; class GFG{ // Function to count // derangements static int countDer(int n) { // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)); } // Driver Code public static void main (String[] args) { int n = 4; System.out.println( "Count of Derangements is " +countDer(n)); }} // This code is contributed by vt_m
# A Naive Recursive Python3# program to count derangements def countDer(n): # Base cases if (n == 1): return 0 if (n == 2): return 1 # countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)) # Driver Coden = 4print("Count of Derangements is ", countDer(n)) # This code is contributed by Azkia Anam.
// A Naive Recursive C#// program to count derangementsusing System; class GFG{ // Function to count // derangements static int countDer(int n) { // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)); } // Driver Code public static void Main () { int n = 4; Console.Write( "Count of Derangements is " + countDer(n)); }} // This code is contributed by nitin mittal.
<?php// A Naive Recursive PHP program// to count derangements function countDer($n){ // Base cases if ($n == 1) return 0; if ($n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + // der(n-2)] return ($n - 1) * (countDer($n - 1) + countDer($n - 2));} // Driver Code $n = 4; echo "Count of Derangements is ", countDer($n); // This code is contributed by nitin mittal.?>
<script> // A Naive Recursive Javascript // program to count derangements // Function to count // derangements function countDer(n) { // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)); } let n = 4; document.write("Count of Derangements is " + countDer(n)); </script>
Count of Derangements is 9
Time Complexity: O(2^n) since T(n) = T(n-1) + T(n-2) which is exponential.
Auxiliary Space: O(h) where h= log n is the maximum height of the tree.
We can observe that this implementation does repetitive work. For example, see recursion tree for countDer(5), countDer(3) is being evaluated twice.
cdr() ==> countDer()
cdr(5)
/ \
cdr(4) cdr(3)
/ \ / \
cdr(3) cdr(2) cdr(2) cdr(1)
An Efficient Solution is to use Dynamic Programming to store results of subproblems in an array and build the array in bottom-up manner.
C++
Java
Python3
C#
PHP
Javascript
// A Dynamic programming based C++// program to count derangements#include <bits/stdc++.h>using namespace std; int countDer(int n){ // Create an array to store // counts for subproblems int der[n + 1] = {0}; // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up manner // using above recursive formula for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n];} // Driver codeint main(){ int n = 4; cout << "Count of Derangements is " << countDer(n); return 0;}
// A Dynamic programming based// java program to count derangementsimport java.io.*; class GFG{ // Function to count // derangements static int countDer(int n) { // Create an array to store // counts for subproblems int der[] = new int[n + 1]; // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up // manner using above recursive // formula for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n]; } // Driver program public static void main (String[] args) { int n = 4; System.out.println("Count of Derangements is " + countDer(n)); }} // This code is contributed by vt_m
# A Dynamic programming based Python3# program to count derangements def countDer(n): # Create an array to store # counts for subproblems der = [0 for i in range(n + 1)] # Base cases der[1] = 0 der[2] = 1 # Fill der[0..n] in bottom up manner # using above recursive formula for i in range(3, n + 1): der[i] = (i - 1) * (der[i - 1] + der[i - 2]) # Return result for n return der[n] # Driver Coden = 4print("Count of Derangements is ", countDer(n)) # This code is contributed by Azkia Anam.
// A Dynamic programming based// C# program to count derangementsusing System; class GFG{ // Function to count // derangements static int countDer(int n) { // Create an array to store // counts for subproblems int []der = new int[n + 1]; // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up // manner using above recursive // formula for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n]; } // Driver code public static void Main () { int n = 4; Console.Write("Count of Derangements is " + countDer(n)); }} // This code is contributed by nitin mittal
<?php// A Dynamic programming based PHP// program to count derangements function countDer($n){ // Create an array to store // counts for subproblems // Base cases $der[1] = 0; $der[2] = 1; // Fill der[0..n] in bottom up manner // using above recursive formula for ($i = 3; $i <= $n; ++$i) $der[$i] = ($i - 1) * ($der[$i - 1] + $der[$i - 2]); // Return result for n return $der[$n];} // Driver code$n = 4;echo "Count of Derangements is ", countDer($n); // This code is contributed by aj_36?>
<script> // A Dynamic programming based // javascript program to count // derangements // Function to count // derangements function countDer(n) { // Create an array to store // counts for subproblems let der = new Array(n + 1); // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up // manner using above recursive // formula for (let i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n]; } let n = 4; document.write( "Count of Derangements is " + countDer(n) ); </script>
Count of Derangements is 9
Time Complexity : O(n) Auxiliary Space : O(n)Thanks to Utkarsh Trivedi for suggesting the above solution.
A More Efficient Solution Without using Extra Space.
As we only need to remember only two previous values So, instead of Storing the values in an array two variables can be used to just store the required previous only.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above// approach #include <iostream>using namespace std; int countDer(int n){ // base case if (n == 1 or n == 2) { return n - 1; } // Variable for just storing // previous values int a = 0; int b = 1; // using above recursive formula for (int i = 3; i <= n; ++i) { int cur = (i - 1) * (a + b); a = b; b = cur; } // Return result for n return b;} // Driver Codeint main(){ cout << "Count of Dearrangements is " << countDer(4); return 0;} // Code contributed by skagnihotri
// Java implementation of the// above approach import java.io.*; class GFG { // Function to count derangements static int countDer(int n) { // Base case if(n == 1 || n == 2) { return n-1; } // Variable for storing prev values int a = 0; int b = 1; // manner using above recursive formula for (int i = 3; i <= n; ++i) { int cur = (i-1)*(a+b); a = b; b = cur; } // Return result for n return b; } // Driver Code public static void main (String[] args) { int n = 4; System.out.println("Count of Dearrangements is " + countDer(n)); } // Code contributed by skagnihotri}
# Python program to count derangements def countDer(n): # Base Case if n == 1 or n == 2: return n-1; # Variables for storing previous values a = 0 b = 1 # using above recursive formula for i in range(3, n + 1): cur = (i-1)*(a+b) a = b b = cur # Return result for n return b # Driver Coden = 4print("Count of Dearrangements is ", countDer(n))# Code contributed by skagnihotri
// C# implementation of the above// approachusing System; class GFG{ // Function to count// derangementsstatic int countDer(int n){ // Base case if (n == 1 || n == 2) { return n - 1; } // Variable for just storing // previous values int a = 0; int b = 1; // Using above recursive formula for(int i = 3; i <= n; ++i) { int cur = (i - 1) * (a + b); a = b; b = cur; } // Return result for n return b;} // Driver codepublic static void Main(){ Console.Write("Count of Dearrangements is " + countDer(4));}} // This code is contributed by koulick_sadhu
<script> // Javascript implementation // of the above approach // Function to count // derangements function countDer(n) { // Base case if (n == 1 || n == 2) { return n - 1; } // Variable for just storing // previous values let a = 0; let b = 1; // Using above recursive formula for(let i = 3; i <= n; ++i) { let cur = (i - 1) * (a + b); a = b; b = cur; } // Return result for n return b; } document.write("Count of Derangements is " + countDer(4)); </script>
Count of Derangements is 9
Time Complexity: O(n) Auxiliary Space: O(1)
Thanks to Shubham Kumar for suggesting the above solution.
References: https://en.wikipedia.org/wiki/Derangement
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
skagnihotri1
koulick_sadhu
decode2207
rameshtravel07
divyesh072019
adnanirshad158
amartyaghoshgfg
prophet1999
Combinatorial
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count ways to reach the nth stair using step 1, 2 or 3
Combinational Sum
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Print all subsets of given size of a set
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 25180,
"s": 25152,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 25420,
"s": 25180,
"text": "A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0}.Given a number n, find the total number of Derangements of a set of n elements."
},
{
"code": null,
"e": 25432,
"s": 25420,
"text": "Examples : "
},
{
"code": null,
"e": 25870,
"s": 25432,
"text": "Input: n = 2\nOutput: 1\nFor two elements say {0, 1}, there is only one \npossible derangement {1, 0}\n\nInput: n = 3\nOutput: 2\nFor three elements say {0, 1, 2}, there are two \npossible derangements {2, 0, 1} and {1, 2, 0}\n\nInput: n = 4\nOutput: 9\nFor four elements say {0, 1, 2, 3}, there are 9\npossible derangements {1, 0, 3, 2} {1, 2, 3, 0}\n{1, 3, 0, 2}, {2, 3, 0, 1}, {2, 0, 3, 1}, {2, 3,\n1, 0}, {3, 0, 1, 2}, {3, 2, 0, 1} and {3, 2, 1, 0}"
},
{
"code": null,
"e": 25968,
"s": 25870,
"text": "Let countDer(n) be count of derangements for n elements. Below is the recursive relation to it. "
},
{
"code": null,
"e": 26028,
"s": 25968,
"text": "countDer(n) = (n - 1) * [countDer(n - 1) + countDer(n - 2)]"
},
{
"code": null,
"e": 26069,
"s": 26028,
"text": "How does above recursive relation work? "
},
{
"code": null,
"e": 26272,
"s": 26069,
"text": "There are n – 1 way for element 0 (this explains multiplication with n – 1). Let 0 be placed at index i. There are now two possibilities, depending on whether or not element i is placed at 0 in return. "
},
{
"code": null,
"e": 26569,
"s": 26272,
"text": "i is placed at 0: This case is equivalent to solving the problem for n-2 elements as two elements have just swapped their positions.i is not placed at 0: This case is equivalent to solving the problem for n-1 elements as now there are n-1 elements, n-1 positions and every element has n-2 choices"
},
{
"code": null,
"e": 26702,
"s": 26569,
"text": "i is placed at 0: This case is equivalent to solving the problem for n-2 elements as two elements have just swapped their positions."
},
{
"code": null,
"e": 26867,
"s": 26702,
"text": "i is not placed at 0: This case is equivalent to solving the problem for n-1 elements as now there are n-1 elements, n-1 positions and every element has n-2 choices"
},
{
"code": null,
"e": 26934,
"s": 26867,
"text": "Below is the simple solution based on the above recursive formula:"
},
{
"code": null,
"e": 26938,
"s": 26934,
"text": "C++"
},
{
"code": null,
"e": 26943,
"s": 26938,
"text": "Java"
},
{
"code": null,
"e": 26951,
"s": 26943,
"text": "Python3"
},
{
"code": null,
"e": 26954,
"s": 26951,
"text": "C#"
},
{
"code": null,
"e": 26958,
"s": 26954,
"text": "PHP"
},
{
"code": null,
"e": 26969,
"s": 26958,
"text": "Javascript"
},
{
"code": "// A Naive Recursive C++ program// to count derangements#include <bits/stdc++.h>using namespace std; int countDer(int n){ // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2));} // Driver Codeint main(){ int n = 4; cout << \"Count of Derangements is \" << countDer(n); return 0;}",
"e": 27376,
"s": 26969,
"text": null
},
{
"code": "// A Naive Recursive java// program to count derangementsimport java.io.*; class GFG{ // Function to count // derangements static int countDer(int n) { // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)); } // Driver Code public static void main (String[] args) { int n = 4; System.out.println( \"Count of Derangements is \" +countDer(n)); }} // This code is contributed by vt_m",
"e": 28010,
"s": 27376,
"text": null
},
{
"code": "# A Naive Recursive Python3# program to count derangements def countDer(n): # Base cases if (n == 1): return 0 if (n == 2): return 1 # countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)) # Driver Coden = 4print(\"Count of Derangements is \", countDer(n)) # This code is contributed by Azkia Anam.",
"e": 28399,
"s": 28010,
"text": null
},
{
"code": "// A Naive Recursive C#// program to count derangementsusing System; class GFG{ // Function to count // derangements static int countDer(int n) { // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)); } // Driver Code public static void Main () { int n = 4; Console.Write( \"Count of Derangements is \" + countDer(n)); }} // This code is contributed by nitin mittal.",
"e": 29014,
"s": 28399,
"text": null
},
{
"code": "<?php// A Naive Recursive PHP program// to count derangements function countDer($n){ // Base cases if ($n == 1) return 0; if ($n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + // der(n-2)] return ($n - 1) * (countDer($n - 1) + countDer($n - 2));} // Driver Code $n = 4; echo \"Count of Derangements is \", countDer($n); // This code is contributed by nitin mittal.?>",
"e": 29461,
"s": 29014,
"text": null
},
{
"code": "<script> // A Naive Recursive Javascript // program to count derangements // Function to count // derangements function countDer(n) { // Base cases if (n == 1) return 0; if (n == 2) return 1; // countDer(n) = (n-1)[countDer(n-1) + der(n-2)] return (n - 1) * (countDer(n - 1) + countDer(n - 2)); } let n = 4; document.write(\"Count of Derangements is \" + countDer(n)); </script>",
"e": 29925,
"s": 29461,
"text": null
},
{
"code": null,
"e": 29952,
"s": 29925,
"text": "Count of Derangements is 9"
},
{
"code": null,
"e": 30027,
"s": 29952,
"text": "Time Complexity: O(2^n) since T(n) = T(n-1) + T(n-2) which is exponential."
},
{
"code": null,
"e": 30099,
"s": 30027,
"text": "Auxiliary Space: O(h) where h= log n is the maximum height of the tree."
},
{
"code": null,
"e": 30249,
"s": 30099,
"text": "We can observe that this implementation does repetitive work. For example, see recursion tree for countDer(5), countDer(3) is being evaluated twice. "
},
{
"code": null,
"e": 30452,
"s": 30249,
"text": "cdr() ==> countDer()\n\n cdr(5) \n / \\ \n cdr(4) cdr(3) \n / \\ / \\\n cdr(3) cdr(2) cdr(2) cdr(1)"
},
{
"code": null,
"e": 30590,
"s": 30452,
"text": "An Efficient Solution is to use Dynamic Programming to store results of subproblems in an array and build the array in bottom-up manner. "
},
{
"code": null,
"e": 30594,
"s": 30590,
"text": "C++"
},
{
"code": null,
"e": 30599,
"s": 30594,
"text": "Java"
},
{
"code": null,
"e": 30607,
"s": 30599,
"text": "Python3"
},
{
"code": null,
"e": 30610,
"s": 30607,
"text": "C#"
},
{
"code": null,
"e": 30614,
"s": 30610,
"text": "PHP"
},
{
"code": null,
"e": 30625,
"s": 30614,
"text": "Javascript"
},
{
"code": "// A Dynamic programming based C++// program to count derangements#include <bits/stdc++.h>using namespace std; int countDer(int n){ // Create an array to store // counts for subproblems int der[n + 1] = {0}; // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up manner // using above recursive formula for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n];} // Driver codeint main(){ int n = 4; cout << \"Count of Derangements is \" << countDer(n); return 0;}",
"e": 31243,
"s": 30625,
"text": null
},
{
"code": "// A Dynamic programming based// java program to count derangementsimport java.io.*; class GFG{ // Function to count // derangements static int countDer(int n) { // Create an array to store // counts for subproblems int der[] = new int[n + 1]; // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up // manner using above recursive // formula for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n]; } // Driver program public static void main (String[] args) { int n = 4; System.out.println(\"Count of Derangements is \" + countDer(n)); }} // This code is contributed by vt_m",
"e": 32111,
"s": 31243,
"text": null
},
{
"code": "# A Dynamic programming based Python3# program to count derangements def countDer(n): # Create an array to store # counts for subproblems der = [0 for i in range(n + 1)] # Base cases der[1] = 0 der[2] = 1 # Fill der[0..n] in bottom up manner # using above recursive formula for i in range(3, n + 1): der[i] = (i - 1) * (der[i - 1] + der[i - 2]) # Return result for n return der[n] # Driver Coden = 4print(\"Count of Derangements is \", countDer(n)) # This code is contributed by Azkia Anam.",
"e": 32691,
"s": 32111,
"text": null
},
{
"code": "// A Dynamic programming based// C# program to count derangementsusing System; class GFG{ // Function to count // derangements static int countDer(int n) { // Create an array to store // counts for subproblems int []der = new int[n + 1]; // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up // manner using above recursive // formula for (int i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n]; } // Driver code public static void Main () { int n = 4; Console.Write(\"Count of Derangements is \" + countDer(n)); }} // This code is contributed by nitin mittal",
"e": 33535,
"s": 32691,
"text": null
},
{
"code": "<?php// A Dynamic programming based PHP// program to count derangements function countDer($n){ // Create an array to store // counts for subproblems // Base cases $der[1] = 0; $der[2] = 1; // Fill der[0..n] in bottom up manner // using above recursive formula for ($i = 3; $i <= $n; ++$i) $der[$i] = ($i - 1) * ($der[$i - 1] + $der[$i - 2]); // Return result for n return $der[$n];} // Driver code$n = 4;echo \"Count of Derangements is \", countDer($n); // This code is contributed by aj_36?>",
"e": 34115,
"s": 33535,
"text": null
},
{
"code": "<script> // A Dynamic programming based // javascript program to count // derangements // Function to count // derangements function countDer(n) { // Create an array to store // counts for subproblems let der = new Array(n + 1); // Base cases der[1] = 0; der[2] = 1; // Fill der[0..n] in bottom up // manner using above recursive // formula for (let i = 3; i <= n; ++i) der[i] = (i - 1) * (der[i - 1] + der[i - 2]); // Return result for n return der[n]; } let n = 4; document.write( \"Count of Derangements is \" + countDer(n) ); </script>",
"e": 34848,
"s": 34115,
"text": null
},
{
"code": null,
"e": 34875,
"s": 34848,
"text": "Count of Derangements is 9"
},
{
"code": null,
"e": 34981,
"s": 34875,
"text": "Time Complexity : O(n) Auxiliary Space : O(n)Thanks to Utkarsh Trivedi for suggesting the above solution."
},
{
"code": null,
"e": 35034,
"s": 34981,
"text": "A More Efficient Solution Without using Extra Space."
},
{
"code": null,
"e": 35201,
"s": 35034,
"text": "As we only need to remember only two previous values So, instead of Storing the values in an array two variables can be used to just store the required previous only."
},
{
"code": null,
"e": 35252,
"s": 35201,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 35256,
"s": 35252,
"text": "C++"
},
{
"code": null,
"e": 35261,
"s": 35256,
"text": "Java"
},
{
"code": null,
"e": 35269,
"s": 35261,
"text": "Python3"
},
{
"code": null,
"e": 35272,
"s": 35269,
"text": "C#"
},
{
"code": null,
"e": 35283,
"s": 35272,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above// approach #include <iostream>using namespace std; int countDer(int n){ // base case if (n == 1 or n == 2) { return n - 1; } // Variable for just storing // previous values int a = 0; int b = 1; // using above recursive formula for (int i = 3; i <= n; ++i) { int cur = (i - 1) * (a + b); a = b; b = cur; } // Return result for n return b;} // Driver Codeint main(){ cout << \"Count of Dearrangements is \" << countDer(4); return 0;} // Code contributed by skagnihotri",
"e": 35860,
"s": 35283,
"text": null
},
{
"code": "// Java implementation of the// above approach import java.io.*; class GFG { // Function to count derangements static int countDer(int n) { // Base case if(n == 1 || n == 2) { return n-1; } // Variable for storing prev values int a = 0; int b = 1; // manner using above recursive formula for (int i = 3; i <= n; ++i) { int cur = (i-1)*(a+b); a = b; b = cur; } // Return result for n return b; } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(\"Count of Dearrangements is \" + countDer(n)); } // Code contributed by skagnihotri}",
"e": 36666,
"s": 35860,
"text": null
},
{
"code": "# Python program to count derangements def countDer(n): # Base Case if n == 1 or n == 2: return n-1; # Variables for storing previous values a = 0 b = 1 # using above recursive formula for i in range(3, n + 1): cur = (i-1)*(a+b) a = b b = cur # Return result for n return b # Driver Coden = 4print(\"Count of Dearrangements is \", countDer(n))# Code contributed by skagnihotri",
"e": 37128,
"s": 36666,
"text": null
},
{
"code": "// C# implementation of the above// approachusing System; class GFG{ // Function to count// derangementsstatic int countDer(int n){ // Base case if (n == 1 || n == 2) { return n - 1; } // Variable for just storing // previous values int a = 0; int b = 1; // Using above recursive formula for(int i = 3; i <= n; ++i) { int cur = (i - 1) * (a + b); a = b; b = cur; } // Return result for n return b;} // Driver codepublic static void Main(){ Console.Write(\"Count of Dearrangements is \" + countDer(4));}} // This code is contributed by koulick_sadhu",
"e": 37778,
"s": 37128,
"text": null
},
{
"code": "<script> // Javascript implementation // of the above approach // Function to count // derangements function countDer(n) { // Base case if (n == 1 || n == 2) { return n - 1; } // Variable for just storing // previous values let a = 0; let b = 1; // Using above recursive formula for(let i = 3; i <= n; ++i) { let cur = (i - 1) * (a + b); a = b; b = cur; } // Return result for n return b; } document.write(\"Count of Derangements is \" + countDer(4)); </script>",
"e": 38422,
"s": 37778,
"text": null
},
{
"code": null,
"e": 38449,
"s": 38422,
"text": "Count of Derangements is 9"
},
{
"code": null,
"e": 38493,
"s": 38449,
"text": "Time Complexity: O(n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 38552,
"s": 38493,
"text": "Thanks to Shubham Kumar for suggesting the above solution."
},
{
"code": null,
"e": 38606,
"s": 38552,
"text": "References: https://en.wikipedia.org/wiki/Derangement"
},
{
"code": null,
"e": 38731,
"s": 38606,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 38744,
"s": 38731,
"text": "nitin mittal"
},
{
"code": null,
"e": 38750,
"s": 38744,
"text": "jit_t"
},
{
"code": null,
"e": 38763,
"s": 38750,
"text": "skagnihotri1"
},
{
"code": null,
"e": 38777,
"s": 38763,
"text": "koulick_sadhu"
},
{
"code": null,
"e": 38788,
"s": 38777,
"text": "decode2207"
},
{
"code": null,
"e": 38803,
"s": 38788,
"text": "rameshtravel07"
},
{
"code": null,
"e": 38817,
"s": 38803,
"text": "divyesh072019"
},
{
"code": null,
"e": 38832,
"s": 38817,
"text": "adnanirshad158"
},
{
"code": null,
"e": 38848,
"s": 38832,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 38860,
"s": 38848,
"text": "prophet1999"
},
{
"code": null,
"e": 38874,
"s": 38860,
"text": "Combinatorial"
},
{
"code": null,
"e": 38894,
"s": 38874,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38907,
"s": 38894,
"text": "Mathematical"
},
{
"code": null,
"e": 38927,
"s": 38907,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38940,
"s": 38927,
"text": "Mathematical"
},
{
"code": null,
"e": 38954,
"s": 38940,
"text": "Combinatorial"
},
{
"code": null,
"e": 39052,
"s": 38954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39061,
"s": 39052,
"text": "Comments"
},
{
"code": null,
"e": 39074,
"s": 39061,
"text": "Old Comments"
},
{
"code": null,
"e": 39129,
"s": 39074,
"text": "Count ways to reach the nth stair using step 1, 2 or 3"
},
{
"code": null,
"e": 39147,
"s": 39129,
"text": "Combinational Sum"
},
{
"code": null,
"e": 39184,
"s": 39147,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 39241,
"s": 39184,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 39282,
"s": 39241,
"text": "Print all subsets of given size of a set"
},
{
"code": null,
"e": 39311,
"s": 39282,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 39341,
"s": 39311,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 39373,
"s": 39341,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 39404,
"s": 39373,
"text": "Bellman–Ford Algorithm | DP-23"
}
]
|
p5.js | createFileInput() Function - GeeksforGeeks | 26 Feb, 2020
The createFileInput() function is used to create an input element with the type of ‘file’ that can be used by the user to select local files to be used in the sketch. It also supports the selection of multiple files if required.
Syntax:
createFileInput(callback, multiple)
Parameters: This function accepts two parameters as mentioned above and described below:
callback: It is the callback function that would be used when the file is loaded. It is an optional parameter.
multiple: It is a string which specifies if multiple files are allowed to be selected at once. It can be set to “true” or “false”. It is an optional parameter.
Return Value: It returns a pointer to the p5.Element holding the created file object.
Below examples illustrate the createFileInput() function in p5.js:
Example 1: In this example, we will take one file as an input.
function setup() { createCanvas(400, 200); textSize(18); text("Click on the file input and select a file.", 20, 20); inputbtn = createFileInput(processFile); inputbtn.position(30, 40);} function processFile(file) { console.log(file); text("The name of the file selected is: "+ file.name, 20, 80); text("The extension of the file selected is: "+ file.subtype, 20, 100); text("The type of the file selected is: "+ file.type, 20, 120); text("The size of the file selected is: "+ file.size, 20, 140);}
Output:
Example 2: In this example, we will take multiple files as an input.
let i = 0; function setup() { createCanvas(500, 200); textSize(18); text("The file input below allows"+ " selecting of multiple files.", 20, 20); inputBtn = createFileInput(processFiles, "true"); inputBtn.position(30, 60);} function processFiles(file) { text("The name of the file selected is: " + file.name, 20, 120 + i); i = i + 20;}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/createFileInput
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25382,
"s": 25354,
"text": "\n26 Feb, 2020"
},
{
"code": null,
"e": 25611,
"s": 25382,
"text": "The createFileInput() function is used to create an input element with the type of ‘file’ that can be used by the user to select local files to be used in the sketch. It also supports the selection of multiple files if required."
},
{
"code": null,
"e": 25619,
"s": 25611,
"text": "Syntax:"
},
{
"code": null,
"e": 25655,
"s": 25619,
"text": "createFileInput(callback, multiple)"
},
{
"code": null,
"e": 25744,
"s": 25655,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25855,
"s": 25744,
"text": "callback: It is the callback function that would be used when the file is loaded. It is an optional parameter."
},
{
"code": null,
"e": 26015,
"s": 25855,
"text": "multiple: It is a string which specifies if multiple files are allowed to be selected at once. It can be set to “true” or “false”. It is an optional parameter."
},
{
"code": null,
"e": 26101,
"s": 26015,
"text": "Return Value: It returns a pointer to the p5.Element holding the created file object."
},
{
"code": null,
"e": 26168,
"s": 26101,
"text": "Below examples illustrate the createFileInput() function in p5.js:"
},
{
"code": null,
"e": 26231,
"s": 26168,
"text": "Example 1: In this example, we will take one file as an input."
},
{
"code": "function setup() { createCanvas(400, 200); textSize(18); text(\"Click on the file input and select a file.\", 20, 20); inputbtn = createFileInput(processFile); inputbtn.position(30, 40);} function processFile(file) { console.log(file); text(\"The name of the file selected is: \"+ file.name, 20, 80); text(\"The extension of the file selected is: \"+ file.subtype, 20, 100); text(\"The type of the file selected is: \"+ file.type, 20, 120); text(\"The size of the file selected is: \"+ file.size, 20, 140);}",
"e": 26873,
"s": 26231,
"text": null
},
{
"code": null,
"e": 26881,
"s": 26873,
"text": "Output:"
},
{
"code": null,
"e": 26950,
"s": 26881,
"text": "Example 2: In this example, we will take multiple files as an input."
},
{
"code": "let i = 0; function setup() { createCanvas(500, 200); textSize(18); text(\"The file input below allows\"+ \" selecting of multiple files.\", 20, 20); inputBtn = createFileInput(processFiles, \"true\"); inputBtn.position(30, 60);} function processFiles(file) { text(\"The name of the file selected is: \" + file.name, 20, 120 + i); i = i + 20;}",
"e": 27337,
"s": 26950,
"text": null
},
{
"code": null,
"e": 27345,
"s": 27337,
"text": "Output:"
},
{
"code": null,
"e": 27385,
"s": 27345,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 27483,
"s": 27385,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 27542,
"s": 27483,
"text": "Reference: https://p5js.org/reference/#/p5/createFileInput"
},
{
"code": null,
"e": 27559,
"s": 27542,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27570,
"s": 27559,
"text": "JavaScript"
},
{
"code": null,
"e": 27587,
"s": 27570,
"text": "Web Technologies"
},
{
"code": null,
"e": 27685,
"s": 27587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27694,
"s": 27685,
"text": "Comments"
},
{
"code": null,
"e": 27707,
"s": 27694,
"text": "Old Comments"
},
{
"code": null,
"e": 27768,
"s": 27707,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27809,
"s": 27768,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27863,
"s": 27809,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27916,
"s": 27863,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 27978,
"s": 27916,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28020,
"s": 27978,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28053,
"s": 28020,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28115,
"s": 28053,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28158,
"s": 28115,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
What are the steps of SQL Query processing in DBMS? | Query Processing is a translation of high-level queries into low-level expression. It is a step wise process that can be used at the physical level of the file system, query optimization and actual execution of the query to get the result.
It requires the basic concepts of relational algebra and file structure. It refers to the range of activities that are involved in extracting data from the database. It includes translation of queries in high-level database languages into expressions that can be implemented at the physical level of the file system.
Given below is the diagram that shows the steps of the structured query language (SQL) query processing −
Steps for SQL processing in database management system (DBMS) are as follows −
Parser − While parsing, the database performs the checks like, Syntax check, Semantic check and Shared pool check, after converting the query into relational algebra.
The syntax check concludes SQL is syntactically correct or not, that means it checks SQL syntactic validity.
The syntax check concludes SQL is syntactically correct or not, that means it checks SQL syntactic validity.
The syntax for parser to do syntax check is −
SELCT * FROM student;
The output is as follows −
error
Here error of wrong spelling of SELECT is given by this check.
Semantic check It determines whether the statement has meaning or not. Example: query contains a table name which does not exist is checked by this check.
Semantic check It determines whether the statement has meaning or not. Example: query contains a table name which does not exist is checked by this check.
Shared Pool check This check determines existence of written hash code in shared pool, suppose if code exists in shared pool then database will not take additional steps for optimization and execution because every query possess a hash code during its execution
Shared Pool check This check determines existence of written hash code in shared pool, suppose if code exists in shared pool then database will not take additional steps for optimization and execution because every query possess a hash code during its execution
Optimizer − In this stage, the database has to perform a hard parse at least for one unique DML statement and it has to do optimization during this parse. This database never optimizes DDL unless it includes a DML component.
It is a process where multiple query execution plans for satisfying a query are examined and the most efficient query plan is satisfied for execution.
Database catalogue stores the execution plans and then optimizer passes the lowest cost plan for execution.
Row Source Generation − The Row Source Generation is software which receives an optimal execution plan from the optimizer and produces an iterative execution plan which is used by the rest of the database. The iterative plan is the binary program that when executed by the sql engine produces the result set.
Execution Engine − Execution engine is helpful to run the query and display the required result. | [
{
"code": null,
"e": 1302,
"s": 1062,
"text": "Query Processing is a translation of high-level queries into low-level expression. It is a step wise process that can be used at the physical level of the file system, query optimization and actual execution of the query to get the result."
},
{
"code": null,
"e": 1619,
"s": 1302,
"text": "It requires the basic concepts of relational algebra and file structure. It refers to the range of activities that are involved in extracting data from the database. It includes translation of queries in high-level database languages into expressions that can be implemented at the physical level of the file system."
},
{
"code": null,
"e": 1725,
"s": 1619,
"text": "Given below is the diagram that shows the steps of the structured query language (SQL) query processing −"
},
{
"code": null,
"e": 1804,
"s": 1725,
"text": "Steps for SQL processing in database management system (DBMS) are as follows −"
},
{
"code": null,
"e": 1971,
"s": 1804,
"text": "Parser − While parsing, the database performs the checks like, Syntax check, Semantic check and Shared pool check, after converting the query into relational algebra."
},
{
"code": null,
"e": 2080,
"s": 1971,
"text": "The syntax check concludes SQL is syntactically correct or not, that means it checks SQL syntactic validity."
},
{
"code": null,
"e": 2189,
"s": 2080,
"text": "The syntax check concludes SQL is syntactically correct or not, that means it checks SQL syntactic validity."
},
{
"code": null,
"e": 2235,
"s": 2189,
"text": "The syntax for parser to do syntax check is −"
},
{
"code": null,
"e": 2257,
"s": 2235,
"text": "SELCT * FROM student;"
},
{
"code": null,
"e": 2284,
"s": 2257,
"text": "The output is as follows −"
},
{
"code": null,
"e": 2290,
"s": 2284,
"text": "error"
},
{
"code": null,
"e": 2353,
"s": 2290,
"text": "Here error of wrong spelling of SELECT is given by this check."
},
{
"code": null,
"e": 2508,
"s": 2353,
"text": "Semantic check It determines whether the statement has meaning or not. Example: query contains a table name which does not exist is checked by this check."
},
{
"code": null,
"e": 2663,
"s": 2508,
"text": "Semantic check It determines whether the statement has meaning or not. Example: query contains a table name which does not exist is checked by this check."
},
{
"code": null,
"e": 2925,
"s": 2663,
"text": "Shared Pool check This check determines existence of written hash code in shared pool, suppose if code exists in shared pool then database will not take additional steps for optimization and execution because every query possess a hash code during its execution"
},
{
"code": null,
"e": 3187,
"s": 2925,
"text": "Shared Pool check This check determines existence of written hash code in shared pool, suppose if code exists in shared pool then database will not take additional steps for optimization and execution because every query possess a hash code during its execution"
},
{
"code": null,
"e": 3412,
"s": 3187,
"text": "Optimizer − In this stage, the database has to perform a hard parse at least for one unique DML statement and it has to do optimization during this parse. This database never optimizes DDL unless it includes a DML component."
},
{
"code": null,
"e": 3563,
"s": 3412,
"text": "It is a process where multiple query execution plans for satisfying a query are examined and the most efficient query plan is satisfied for execution."
},
{
"code": null,
"e": 3671,
"s": 3563,
"text": "Database catalogue stores the execution plans and then optimizer passes the lowest cost plan for execution."
},
{
"code": null,
"e": 3980,
"s": 3671,
"text": "Row Source Generation − The Row Source Generation is software which receives an optimal execution plan from the optimizer and produces an iterative execution plan which is used by the rest of the database. The iterative plan is the binary program that when executed by the sql engine produces the result set."
},
{
"code": null,
"e": 4077,
"s": 3980,
"text": "Execution Engine − Execution engine is helpful to run the query and display the required result."
}
]
|
Create list of numbers with given range in Python | Python can handle any requirement in data manipulation through its wide variety of libraries and methods. When we need to generate all the numbers between a pair of given numbers, we can use python’s inbuilt functions as well as some of the libraries. This article describes such approaches.
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 ending at a specified number. We can of curse change the starting, ending as well as increment steps to suit our need.
Live Demo
def getnums(s, e,i):
return list(range(s, e,i))
# Driver Code
start, end, intval = -3, 6,2
print(getnums(start, end,intval))
Running the above code gives us the following result −
[-3, -1, 1, 3, 5]
The random module can also generate a random number between in a similar way as above. It involves calling the randrange method and supplying the parameters for start, end and interval values.
Live Demo
import random
def getnums(s, e,i):
return (random.randrange(s, e,i))
# Driver Code
start, end, intval = 3, 16,2
print(getnums(start, end,intval))
Running the above code gives us the following result −
7
The numpy library also provides a very wide range of functions for these requirements. We use arrange function which will also take the required parameters and give the output as a list.
Live Demo
import numpy as np
def getnums(s, e,i):
return (np.arange(s, e,i))
# Driver Code
start, end, intval = 3, 16,2
print(getnums(start, end,intval))
Running the above code gives us the following result −
[ 3 5 7 9 11 13 15] | [
{
"code": null,
"e": 1354,
"s": 1062,
"text": "Python can handle any requirement in data manipulation through its wide variety of libraries and methods. When we need to generate all the numbers between a pair of given numbers, we can use python’s inbuilt functions as well as some of the libraries. This article describes such approaches."
},
{
"code": null,
"e": 1573,
"s": 1354,
"text": "The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 ending at a specified number. We can of curse change the starting, ending as well as increment steps to suit our need."
},
{
"code": null,
"e": 1584,
"s": 1573,
"text": " Live Demo"
},
{
"code": null,
"e": 1713,
"s": 1584,
"text": "def getnums(s, e,i):\n return list(range(s, e,i))\n\n# Driver Code\nstart, end, intval = -3, 6,2\nprint(getnums(start, end,intval))"
},
{
"code": null,
"e": 1768,
"s": 1713,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1786,
"s": 1768,
"text": "[-3, -1, 1, 3, 5]"
},
{
"code": null,
"e": 1979,
"s": 1786,
"text": "The random module can also generate a random number between in a similar way as above. It involves calling the randrange method and supplying the parameters for start, end and interval values."
},
{
"code": null,
"e": 1990,
"s": 1979,
"text": " Live Demo"
},
{
"code": null,
"e": 2140,
"s": 1990,
"text": "import random\ndef getnums(s, e,i):\n return (random.randrange(s, e,i))\n\n# Driver Code\nstart, end, intval = 3, 16,2\nprint(getnums(start, end,intval))"
},
{
"code": null,
"e": 2195,
"s": 2140,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2197,
"s": 2195,
"text": "7"
},
{
"code": null,
"e": 2384,
"s": 2197,
"text": "The numpy library also provides a very wide range of functions for these requirements. We use arrange function which will also take the required parameters and give the output as a list."
},
{
"code": null,
"e": 2395,
"s": 2384,
"text": " Live Demo"
},
{
"code": null,
"e": 2543,
"s": 2395,
"text": "import numpy as np\ndef getnums(s, e,i):\n return (np.arange(s, e,i))\n\n# Driver Code\nstart, end, intval = 3, 16,2\nprint(getnums(start, end,intval))"
},
{
"code": null,
"e": 2598,
"s": 2543,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2618,
"s": 2598,
"text": "[ 3 5 7 9 11 13 15]"
}
]
|
PostgreSQL - MAX Function | PostgreSQL MAX function is used to find out the record with maximum value among a record set.
To understand the MAX function, consider the table COMPANY having records as follows −
testdb# select * from COMPANY;
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
(7 rows)
Now, based on the above table, suppose you want to fetch maximum value of SALARY, then you can do so by simply using the following command −
testdb=# SELECT MAX(salary) FROM COMPANY;
The above given PostgreSQL statement will produce the following result −
max
-------
85000
(1 row)
You can find all the records with maximum value for each name using the GROUP BY clause as follows −
testdb=# SELECT id, name, MAX(salary) FROM COMPANY GROUP BY id, name;
The above given PostgreSQL statement will produce the following result −
id | name | max
----+-------+-------
4 | Mark | 65000
7 | James | 10000
6 | Kim | 45000
3 | Teddy | 20000
2 | Allen | 15000
5 | David | 85000
1 | Paul | 20000
You can use the MIN Function along with the MAX function to find out minimum value as well. Try out the following example −
testdb=# SELECT MIN(salary), MAX(salary) max FROM company;
The above given PostgreSQL statement will produce the following result −
min | max
-------+-------
10000 | 85000
(1 row)
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": 2919,
"s": 2825,
"text": "PostgreSQL MAX function is used to find out the record with maximum value among a record set."
},
{
"code": null,
"e": 3006,
"s": 2919,
"text": "To understand the MAX function, consider the table COMPANY having records as follows −"
},
{
"code": null,
"e": 3398,
"s": 3006,
"text": "testdb# select * from COMPANY;\n 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\n(7 rows)"
},
{
"code": null,
"e": 3539,
"s": 3398,
"text": "Now, based on the above table, suppose you want to fetch maximum value of SALARY, then you can do so by simply using the following command −"
},
{
"code": null,
"e": 3581,
"s": 3539,
"text": "testdb=# SELECT MAX(salary) FROM COMPANY;"
},
{
"code": null,
"e": 3654,
"s": 3581,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 3684,
"s": 3654,
"text": " max\n-------\n 85000\n(1 row)\n"
},
{
"code": null,
"e": 3785,
"s": 3684,
"text": "You can find all the records with maximum value for each name using the GROUP BY clause as follows −"
},
{
"code": null,
"e": 3855,
"s": 3785,
"text": "testdb=# SELECT id, name, MAX(salary) FROM COMPANY GROUP BY id, name;"
},
{
"code": null,
"e": 3928,
"s": 3855,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 4109,
"s": 3928,
"text": " id | name | max\n----+-------+-------\n 4 | Mark | 65000\n 7 | James | 10000\n 6 | Kim | 45000\n 3 | Teddy | 20000\n 2 | Allen | 15000\n 5 | David | 85000\n 1 | Paul | 20000\n"
},
{
"code": null,
"e": 4233,
"s": 4109,
"text": "You can use the MIN Function along with the MAX function to find out minimum value as well. Try out the following example −"
},
{
"code": null,
"e": 4292,
"s": 4233,
"text": "testdb=# SELECT MIN(salary), MAX(salary) max FROM company;"
},
{
"code": null,
"e": 4365,
"s": 4292,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 4419,
"s": 4365,
"text": " min | max\n-------+-------\n 10000 | 85000\n(1 row)\n"
},
{
"code": null,
"e": 4454,
"s": 4419,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4466,
"s": 4454,
"text": " John Elder"
},
{
"code": null,
"e": 4501,
"s": 4466,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4517,
"s": 4501,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 4554,
"s": 4517,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4576,
"s": 4554,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4609,
"s": 4576,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4623,
"s": 4609,
"text": " Karthikeya T"
},
{
"code": null,
"e": 4654,
"s": 4623,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 4667,
"s": 4654,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4698,
"s": 4667,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 4711,
"s": 4698,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4718,
"s": 4711,
"text": " Print"
},
{
"code": null,
"e": 4729,
"s": 4718,
"text": " Add Notes"
}
]
|
Regular Expression "\Z" Metacharacter in Java | The subexpression/metacharacter “\Z” matches the end of the entire string except allowable final line terminator.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "Tutorialspoint\\z";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}
Number of matches: 1
The following Java program verifies whether the given input text ends with a digit.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Data {
public static void main( String args[] ) {
String regex = "[0-9]\\z";
String input = "Hi how are you \n this is sample text \n this is third line 554";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("Given input ends with a digit");
} else {
System.out.println("Given input doesn’t end with a digit");
}
}
}
Given input ends with a digit | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "The subexpression/metacharacter “\\Z” matches the end of the entire string except allowable final line terminator."
},
{
"code": null,
"e": 1632,
"s": 1176,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexExample {\n public static void main( String args[] ) {\n String regex = \"Tutorialspoint\\\\z\";\n String input = \"Hi how are you welcome to Tutorialspoint\";\n Pattern p = Pattern.compile(regex);\n Matcher m = p.matcher(input);\n int count = 0;\n while(m.find()) {\n count++;\n }\n System.out.println(\"Number of matches: \"+count);\n }\n}"
},
{
"code": null,
"e": 1653,
"s": 1632,
"text": "Number of matches: 1"
},
{
"code": null,
"e": 1737,
"s": 1653,
"text": "The following Java program verifies whether the given input text ends with a digit."
},
{
"code": null,
"e": 2248,
"s": 1737,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Data {\n public static void main( String args[] ) {\n String regex = \"[0-9]\\\\z\";\n String input = \"Hi how are you \\n this is sample text \\n this is third line 554\";\n Pattern p = Pattern.compile(regex);\n Matcher m = p.matcher(input);\n if(m.find()) {\n System.out.println(\"Given input ends with a digit\");\n } else {\n System.out.println(\"Given input doesn’t end with a digit\");\n }\n }\n}"
},
{
"code": null,
"e": 2278,
"s": 2248,
"text": "Given input ends with a digit"
}
]
|
4 Must-Know Special Methods for Python | by Soner Yıldırım | Towards Data Science | Everything in Python is an object and we define objects through classes. When we define an object, we actually create an instance of a class. Thus, class is the most fundamental piece in Python.
Classes have:
Data attributes: Define what is needed to create an instance of a class
Methods (i.e. procedural attributes): Define how to interact with the instances of a class
We can create our own classes using data and procedural attributes. It is our playground so we can implement various functions to customize a class.
In addition to the user-defined functions, it is possible to use built-in Python function within user-defined classes. This is what special (or magic) methods are for.
Special methods allow for using the built-in Python functions to enrich user-defined classes. Consider the print function which is one of the most commonly used Python function. If you use it to print an instance of your class, it will print out something like the following:
<__main__.Book object at 0x7f9ed5b1d590>
It displays the name of the class (Book) and the memory location of the object which is not a proper use of the print function. We can customize its behavior by implementing the __str__ special method in our class.
In this article, we will go over 4 special methods that you will be likely to use in your classes.
The __init__ special method is automatically executed when an instance of class is created. It is also called class constructor. The parameters of the __init__ represent the data attributes of a class.
Let’s create a class called Book.
class Book(): def __init__(self, name, writer, pages): self.name = name self.writer = writer self.pages = pages
The self refers to the instance itself. The Book class has 3 data attributes that need to be specified when creating a Book instance.
b = Book("Moby Dick", "Herman Melville", "378")type(b)__main__.Book
The variable b is an instance of the Book class.
We use the __str__ special method to implement the built-in print function within our class. Without the __str__, here is what print function does.
print(b)<__main__.Book object at 0x7f9ed5b1d590>
Let’s define the __str__ method in our class definition.
def __str__(self): return f"The title of the book is {self.name}"
Now the print function will return the title of the name. It accesses the name of the book through the name attribute. You can customize it in any way you’d like.
print(b)The title of the book is Moby Dick
The len function returns the length of an object. For strings, it returns the number of characters. For a Pandas data frame, it returns the number of row.
We can customize its behavior by implementing the __len__ special method in our class definition. Let’s make it to return the number of pages of a book object.
If the __len__ is not implemented in the class definition, you will get an error if you try to use it on an object of your class. It does not have a default behavior like the print function.
def __len__(self): return int(self.pages)len(b)378
Please note that each time you add a new function to your class, you need to recreate the object to be able to use the new functions.
The __eq__ special method allows for comparing two instances of a class. If it is defined in our class, we can check if an instance is equal to another instance. The equality condition is specified using the __eq__ method.
In our case, we can declare two books being equal if the names and writers of the book are the same. They might have different number of pages.
def __eq__(self, other): return (self.name == other.name) & (self.writer == other.writer)
The “==” operator will return True if both names and writes are the same for two instances. Let’s create two books and check if they are equal.
b = Book("Moby Dick", "Herman Melville", "378")a = Book("Moby Dick", "Herman Melville", "410")b == aTrue
If either names or writes is different, the equality operator returns False.
b = Book("Moby Dick", "Herman Melville", "378")a = Book("Moby Dick", "Melville", "410")b == aFalse
Objects are at the core of Python so creating robust, function, and well-designed classes are of crucial importance. We have covered 4 special methods that you will need to implement in your own classes.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 367,
"s": 172,
"text": "Everything in Python is an object and we define objects through classes. When we define an object, we actually create an instance of a class. Thus, class is the most fundamental piece in Python."
},
{
"code": null,
"e": 381,
"s": 367,
"text": "Classes have:"
},
{
"code": null,
"e": 453,
"s": 381,
"text": "Data attributes: Define what is needed to create an instance of a class"
},
{
"code": null,
"e": 544,
"s": 453,
"text": "Methods (i.e. procedural attributes): Define how to interact with the instances of a class"
},
{
"code": null,
"e": 693,
"s": 544,
"text": "We can create our own classes using data and procedural attributes. It is our playground so we can implement various functions to customize a class."
},
{
"code": null,
"e": 861,
"s": 693,
"text": "In addition to the user-defined functions, it is possible to use built-in Python function within user-defined classes. This is what special (or magic) methods are for."
},
{
"code": null,
"e": 1137,
"s": 861,
"text": "Special methods allow for using the built-in Python functions to enrich user-defined classes. Consider the print function which is one of the most commonly used Python function. If you use it to print an instance of your class, it will print out something like the following:"
},
{
"code": null,
"e": 1178,
"s": 1137,
"text": "<__main__.Book object at 0x7f9ed5b1d590>"
},
{
"code": null,
"e": 1393,
"s": 1178,
"text": "It displays the name of the class (Book) and the memory location of the object which is not a proper use of the print function. We can customize its behavior by implementing the __str__ special method in our class."
},
{
"code": null,
"e": 1492,
"s": 1393,
"text": "In this article, we will go over 4 special methods that you will be likely to use in your classes."
},
{
"code": null,
"e": 1694,
"s": 1492,
"text": "The __init__ special method is automatically executed when an instance of class is created. It is also called class constructor. The parameters of the __init__ represent the data attributes of a class."
},
{
"code": null,
"e": 1728,
"s": 1694,
"text": "Let’s create a class called Book."
},
{
"code": null,
"e": 1861,
"s": 1728,
"text": "class Book(): def __init__(self, name, writer, pages): self.name = name self.writer = writer self.pages = pages"
},
{
"code": null,
"e": 1995,
"s": 1861,
"text": "The self refers to the instance itself. The Book class has 3 data attributes that need to be specified when creating a Book instance."
},
{
"code": null,
"e": 2063,
"s": 1995,
"text": "b = Book(\"Moby Dick\", \"Herman Melville\", \"378\")type(b)__main__.Book"
},
{
"code": null,
"e": 2112,
"s": 2063,
"text": "The variable b is an instance of the Book class."
},
{
"code": null,
"e": 2260,
"s": 2112,
"text": "We use the __str__ special method to implement the built-in print function within our class. Without the __str__, here is what print function does."
},
{
"code": null,
"e": 2309,
"s": 2260,
"text": "print(b)<__main__.Book object at 0x7f9ed5b1d590>"
},
{
"code": null,
"e": 2366,
"s": 2309,
"text": "Let’s define the __str__ method in our class definition."
},
{
"code": null,
"e": 2434,
"s": 2366,
"text": "def __str__(self): return f\"The title of the book is {self.name}\""
},
{
"code": null,
"e": 2597,
"s": 2434,
"text": "Now the print function will return the title of the name. It accesses the name of the book through the name attribute. You can customize it in any way you’d like."
},
{
"code": null,
"e": 2640,
"s": 2597,
"text": "print(b)The title of the book is Moby Dick"
},
{
"code": null,
"e": 2795,
"s": 2640,
"text": "The len function returns the length of an object. For strings, it returns the number of characters. For a Pandas data frame, it returns the number of row."
},
{
"code": null,
"e": 2955,
"s": 2795,
"text": "We can customize its behavior by implementing the __len__ special method in our class definition. Let’s make it to return the number of pages of a book object."
},
{
"code": null,
"e": 3146,
"s": 2955,
"text": "If the __len__ is not implemented in the class definition, you will get an error if you try to use it on an object of your class. It does not have a default behavior like the print function."
},
{
"code": null,
"e": 3199,
"s": 3146,
"text": "def __len__(self): return int(self.pages)len(b)378"
},
{
"code": null,
"e": 3333,
"s": 3199,
"text": "Please note that each time you add a new function to your class, you need to recreate the object to be able to use the new functions."
},
{
"code": null,
"e": 3556,
"s": 3333,
"text": "The __eq__ special method allows for comparing two instances of a class. If it is defined in our class, we can check if an instance is equal to another instance. The equality condition is specified using the __eq__ method."
},
{
"code": null,
"e": 3700,
"s": 3556,
"text": "In our case, we can declare two books being equal if the names and writers of the book are the same. They might have different number of pages."
},
{
"code": null,
"e": 3792,
"s": 3700,
"text": "def __eq__(self, other): return (self.name == other.name) & (self.writer == other.writer)"
},
{
"code": null,
"e": 3936,
"s": 3792,
"text": "The “==” operator will return True if both names and writes are the same for two instances. Let’s create two books and check if they are equal."
},
{
"code": null,
"e": 4041,
"s": 3936,
"text": "b = Book(\"Moby Dick\", \"Herman Melville\", \"378\")a = Book(\"Moby Dick\", \"Herman Melville\", \"410\")b == aTrue"
},
{
"code": null,
"e": 4118,
"s": 4041,
"text": "If either names or writes is different, the equality operator returns False."
},
{
"code": null,
"e": 4217,
"s": 4118,
"text": "b = Book(\"Moby Dick\", \"Herman Melville\", \"378\")a = Book(\"Moby Dick\", \"Melville\", \"410\")b == aFalse"
},
{
"code": null,
"e": 4421,
"s": 4217,
"text": "Objects are at the core of Python so creating robust, function, and well-designed classes are of crucial importance. We have covered 4 special methods that you will need to implement in your own classes."
}
]
|
Draw a circle in using Tkinter Python | Tkinter Canvas are generally used for creating shapes such as arc, rectangle, triangle, freeform shapes, etc. All these shapes can be drawn using the inbuilt function available in tkinter library.
In this example, we will create a Circle using the create_oval(x0,y0,x1,y1) method by passing the following values of coordinates (x0,y0, x1, y1)
#Import the library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of window
win.geometry("600x400")
#Create a canvas object
c= Canvas(win,width=400, height=400)
c.pack()
#Draw an Oval in the canvas
c.create_oval(60,60,210,210)
win.mainloop()
Running the above code will draw a circle in the canvas. In this example, we have defined the coordinates for (x0, y0, x1, y1) as (60,60,210,210). Thus, it will draw and display a circle in the window. | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "Tkinter Canvas are generally used for creating shapes such as arc, rectangle, triangle, freeform shapes, etc. All these shapes can be drawn using the inbuilt function available in tkinter library."
},
{
"code": null,
"e": 1405,
"s": 1259,
"text": "In this example, we will create a Circle using the create_oval(x0,y0,x1,y1) method by passing the following values of coordinates (x0,y0, x1, y1)"
},
{
"code": null,
"e": 1696,
"s": 1405,
"text": "#Import the library\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Define the geometry of window\nwin.geometry(\"600x400\")\n\n#Create a canvas object\nc= Canvas(win,width=400, height=400)\nc.pack()\n\n#Draw an Oval in the canvas\nc.create_oval(60,60,210,210)\n\nwin.mainloop()"
},
{
"code": null,
"e": 1898,
"s": 1696,
"text": "Running the above code will draw a circle in the canvas. In this example, we have defined the coordinates for (x0, y0, x1, y1) as (60,60,210,210). Thus, it will draw and display a circle in the window."
}
]
|
4 Ways To Improve Your Plotly Graphs | by Dylan Castillo | Towards Data Science | Note: after publishing, I noticed that there are some issues with Plotly’s embeds in Medium. So you’ll need to click on the links to see how the graphs look. For a better reading experience, see the original version on my site.
These last weeks I've been working on an application using Dash and Plotly. These tools are great if you want to get something out quickly. But, as usual, there's no magical make_beautiful_graphs parameter you can set to True by default.
If you want to have beautiful and customized visualizations in your application, you'll need to spend some time playing around Plotly's extensive list of figures' attributes. I wanted to have something better than the default looks, so I went through Plotly's documentation, old code snippets I had, and Stack Overflow questions.
This is not the first time I found myself doing that. However, this time I decided to keep track of the things I frequently do when making graphs with Plotly. That way, I wouldn't need to read the same documentation or browse the same Stack Overflow questions next time.
In this article, I'm compiling a list of things I frequently do when building data visualizations using Plotly. Rest assured, I've been working in data-related positions for a while, so you will not find outrageous things like how to make 3D pie charts. Although these improvements are based on a sample of one, I've frequently seen others applying similar ideas.
I'm focusing on practical and simple improvements that apply to most of the basic charts: scatter plots, line charts, bar charts, and some statistical charts. Here you will find things like removing gridlines and not things like selecting the best colors for your 4D contour plot.
First, I'll do a brief introduction on how you build graphs using Plotly. Next, I'll provide a list of improvements and the reasoning behind them. Last, I'll give additional recommendations I've found useful when working with Plotly and other plotting libraries.
There are three things you need to know about the inner workings of Plotly:
First, making a graph in Plotly is essentially populating a Python dictionary. This dictionary is usually referred to as figure.
Second, there are two keys in the figure dictionary: layout and data. In layout, you define the looks of your graph like the typography, titles, and axes. In the data key, you set the values and information of the traces you'll be plotting. That could be something like [1, 2, 3] for X, [5, 3, 9] for Y and bar chart type.
Finally, once you populate the figure dictionary, it is serialized (transformed) into a JSON structure. This resulting data structure is then used by the Plotly JavaScript library to plot your chart.
That's it.
So, how do you make a figure?
There are multiple ways to do it. The lowest-level approach is to use Python dictionaries, and the highest-level one is using the Plotly Express interface. I tend to use a mid-level interface called Figure Constructor. It's easier to debug than using Python dictionaries, and it's more flexible than Plotly Express.
The code for making a graph using the Figure Constructor looks as follows:
import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns = np.random.normal(0.01, 0.2, 100)price = 100 * np.exp(returns.cumsum())time = np.arange(100)# Generate graph using Figure Constructorlayout = go.Layout( title="Historic Prices", xaxis_title="time", yaxis_title="price")fig = go.Figure( data=go.Scatter(x=time, y=price), layout=layout) fig.show()
This is the resulting graph:
chart-studio.plotly.com
Here's the list of things I usually do to improve Plotly graphs:
#1: Remove gridlines and background color
#2: Keep consistent colors across graphs
#3: Use spikelines to compare data points
#4: Remove floating menu, disable zoom and adjust click behavior
Gridlines are lines that cross the chart to show axis divisions. They help the viewer visualize the value represented by an unlabeled data point fast. However, gridlines are not very useful when working with interactive graphs. You can hover over a data point and see its value. So more often than not, I remove gridlines when working with Plotly.
Here's how you can do it:
import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns = np.random.normal(0.01, 0.2, 100)price = 100 * np.exp(returns.cumsum())time = np.arange(100)layout = go.Layout( title="Historic Prices", plot_bgcolor="#FFF", # Sets background color to white xaxis=dict( title="time", linecolor="#BCCCDC", # Sets color of X-axis line showgrid=False # Removes X-axis grid lines ), yaxis=dict( title="price", linecolor="#BCCCDC", # Sets color of Y-axis line showgrid=False, # Removes Y-axis grid lines ))fig = go.Figure( data=go.Scatter(x=time, y=price), layout=layout) fig.show()
And this is how it looks:
plotly.com
When working with categories, there are two things people usually like to do. First, they want to assign some specific colors to each group. For instance, if you are analyzing electoral results in the US, you probably want to use particular blue and red variations to identify the Democratic and Republican parties.
Second, you want this color to remain consistent across all the graphs you do. For example, if you are analyzing some real-world companies, you may want to use their distinctive colors to plot their prices but also when you analyze their returns.
Here's how you can do that using Plotly:
import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = ["A"] * 100 + ["B"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({ "company": companies, "time": time, "price": prices, "returns": returns})# Build graphCOLORS_MAPPER = { "A": "#38BEC9", "B": "#D64545"}layout = go.Layout( title="Performance of A vs. B", plot_bgcolor="#FFFFFF", barmode="stack", xaxis=dict( domain=[0, 0.5], title="time", linecolor="#BCCCDC", ), yaxis=dict( title="price", linecolor="#BCCCDC" ), xaxis2=dict( domain=[0.6, 1], title="returns", linecolor="#BCCCDC", ), yaxis2=dict( anchor="x2", linecolor="#BCCCDC" ))data = []for company,col in COLORS_MAPPER.items(): time = df.loc[df.company == company, "time"] price = df.loc[df.company == company, "price"] returns = df.loc[df.company == company, "returns"] line_chart = go.Scatter( x=time, y=price, marker_color=col, # Defines specific color for a trace legendgroup=company, # Groups traces belonging to the same group in the legend name=company ) histogram = go.Histogram( x=returns, marker_color=col, # Defines specific color for a trace legendgroup=company, # Groups traces belonging to the same group in the legend xaxis="x2", yaxis="y2", showlegend=False ) data.append(line_chart) data.append(histogram)fig = go.Figure(data=data, layout=layout)fig.show()
The snippet above allows you to keep consistent colors when working with multiple graphs that share the same categories. The critical part is the COLOR_MAPPER dictionary and its use when adding new traces. This dictionary is the mapping of the categories and colors you'll be using across your charts.
Whenever you add a trace to a graph, you can assign the right color to the marker_color attribute by getting it from the COLOR_MAPPER dictionary.
The resulting graph looks as follows:
plotly.com
A spike line is a vertical or horizontal line that appears when hovering on data. It's useful for comparing values in line charts and scatter plots. This is how you can add those using Plotly:
import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = ["A"] * 100 + ["B"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({ "company": companies, "time": time, "price": prices, "returns": returns})# Build graphlayout = go.Layout( title="Performance of A vs. B", plot_bgcolor="#FFFFFF", hovermode="x", hoverdistance=100, # Distance to show hover label of data point spikedistance=1000, # Distance to show spike xaxis=dict( title="time", linecolor="#BCCCDC", showspikes=True, # Show spike line for X-axis # Format spike spikethickness=2, spikedash="dot", spikecolor="#999999", spikemode="across", ), yaxis=dict( title="price", linecolor="#BCCCDC" ))data = []for company in ["A", "B"]: time = df.loc[df.company == company, "time"] price = df.loc[df.company == company, "price"] returns = df.loc[df.company == company, "returns"] line_chart = go.Scatter( x=time, y=price, name=company ) data.append(line_chart)fig = go.Figure(data=data, layout=layout)fig.show()
This is the resulting graph:
plotly.com
I'm not too fond of the floating menu that Plotly adds to your chart by default. It makes graphs look cool, but I've rarely seen people using it. It has so many options that it's just confusing for someone looking at a graph for the first time. Usually, I remove it.
Also, I like to re-define two other user interaction parameters. I prefer to limit the users' ability to zoom in and change the behavior of clicking on a trace in the legend. In Plotly, by default, if you want to inspect a trace on its own, you have to double-click on the trace, instead of just clicking on it. That's not very intuitive, so I tend to invert that behavior.
This is how you can apply those changes:
import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = ["A"] * 100 + ["B"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({ "company": companies, "time": time, "price": prices, "returns": returns})# Build graphlayout = go.Layout( title="Performance of A vs. B", plot_bgcolor="#FFFFFF", legend=dict( # Adjust click behavior itemclick="toggleothers", itemdoubleclick="toggle", ), xaxis=dict( title="time", linecolor="#BCCCDC", ), yaxis=dict( title="price", linecolor="#BCCCDC" ))data = []for company in ["A", "B"]: time = df.loc[df.company == company, "time"] price = df.loc[df.company == company, "price"] returns = df.loc[df.company == company, "returns"] line_chart = go.Scatter( x=time, y=price, name=company ) data.append(line_chart)fig = go.Figure(data=data, layout=layout)fig.show(config={"displayModeBar": False, "showTips": False}) # Remove floating menu and unnecesary dialog box
This is the resulting graph:
plotly.com
There are three things that I've found useful for learning how to make better data visualizations:
Get feedback from your audience: This is not always possible. But if you can do it, always prioritize getting input from those who will use your data visualizations. If you are working on a dashboard, the first thing you should do is understand what problem your dashboard solves. Then see users interacting with it. That has the highest ROI for your time.Check out Storytelling with Data by Cole Knaflic: It's a great book if you want to level-up your data visualization design skills. It provides a lot of practical advice and compelling use cases.Ploty's Figure Reference: Get used to Plotly's Figure Reference and Plotly's documentation. You'll be using it a lot. In general, Plotly's documentation is excellent.
Get feedback from your audience: This is not always possible. But if you can do it, always prioritize getting input from those who will use your data visualizations. If you are working on a dashboard, the first thing you should do is understand what problem your dashboard solves. Then see users interacting with it. That has the highest ROI for your time.
Check out Storytelling with Data by Cole Knaflic: It's a great book if you want to level-up your data visualization design skills. It provides a lot of practical advice and compelling use cases.
Ploty's Figure Reference: Get used to Plotly's Figure Reference and Plotly's documentation. You'll be using it a lot. In general, Plotly's documentation is excellent.
I hope you found these ideas useful. There might be some things that do not resonate with you, or others that you feel are missing. If that's the case, please let me know in the comments below. I'll be happy to update this and add other valuable advice.
You can find other articles I’ve authored here Or if you want to keep up-to-date with what I’m doing you can follow me on Twitter or LinkedIn.
This article was originally published in my blog. | [
{
"code": null,
"e": 400,
"s": 172,
"text": "Note: after publishing, I noticed that there are some issues with Plotly’s embeds in Medium. So you’ll need to click on the links to see how the graphs look. For a better reading experience, see the original version on my site."
},
{
"code": null,
"e": 638,
"s": 400,
"text": "These last weeks I've been working on an application using Dash and Plotly. These tools are great if you want to get something out quickly. But, as usual, there's no magical make_beautiful_graphs parameter you can set to True by default."
},
{
"code": null,
"e": 968,
"s": 638,
"text": "If you want to have beautiful and customized visualizations in your application, you'll need to spend some time playing around Plotly's extensive list of figures' attributes. I wanted to have something better than the default looks, so I went through Plotly's documentation, old code snippets I had, and Stack Overflow questions."
},
{
"code": null,
"e": 1239,
"s": 968,
"text": "This is not the first time I found myself doing that. However, this time I decided to keep track of the things I frequently do when making graphs with Plotly. That way, I wouldn't need to read the same documentation or browse the same Stack Overflow questions next time."
},
{
"code": null,
"e": 1603,
"s": 1239,
"text": "In this article, I'm compiling a list of things I frequently do when building data visualizations using Plotly. Rest assured, I've been working in data-related positions for a while, so you will not find outrageous things like how to make 3D pie charts. Although these improvements are based on a sample of one, I've frequently seen others applying similar ideas."
},
{
"code": null,
"e": 1884,
"s": 1603,
"text": "I'm focusing on practical and simple improvements that apply to most of the basic charts: scatter plots, line charts, bar charts, and some statistical charts. Here you will find things like removing gridlines and not things like selecting the best colors for your 4D contour plot."
},
{
"code": null,
"e": 2147,
"s": 1884,
"text": "First, I'll do a brief introduction on how you build graphs using Plotly. Next, I'll provide a list of improvements and the reasoning behind them. Last, I'll give additional recommendations I've found useful when working with Plotly and other plotting libraries."
},
{
"code": null,
"e": 2223,
"s": 2147,
"text": "There are three things you need to know about the inner workings of Plotly:"
},
{
"code": null,
"e": 2352,
"s": 2223,
"text": "First, making a graph in Plotly is essentially populating a Python dictionary. This dictionary is usually referred to as figure."
},
{
"code": null,
"e": 2675,
"s": 2352,
"text": "Second, there are two keys in the figure dictionary: layout and data. In layout, you define the looks of your graph like the typography, titles, and axes. In the data key, you set the values and information of the traces you'll be plotting. That could be something like [1, 2, 3] for X, [5, 3, 9] for Y and bar chart type."
},
{
"code": null,
"e": 2875,
"s": 2675,
"text": "Finally, once you populate the figure dictionary, it is serialized (transformed) into a JSON structure. This resulting data structure is then used by the Plotly JavaScript library to plot your chart."
},
{
"code": null,
"e": 2886,
"s": 2875,
"text": "That's it."
},
{
"code": null,
"e": 2916,
"s": 2886,
"text": "So, how do you make a figure?"
},
{
"code": null,
"e": 3232,
"s": 2916,
"text": "There are multiple ways to do it. The lowest-level approach is to use Python dictionaries, and the highest-level one is using the Plotly Express interface. I tend to use a mid-level interface called Figure Constructor. It's easier to debug than using Python dictionaries, and it's more flexible than Plotly Express."
},
{
"code": null,
"e": 3307,
"s": 3232,
"text": "The code for making a graph using the Figure Constructor looks as follows:"
},
{
"code": null,
"e": 3712,
"s": 3307,
"text": "import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns = np.random.normal(0.01, 0.2, 100)price = 100 * np.exp(returns.cumsum())time = np.arange(100)# Generate graph using Figure Constructorlayout = go.Layout( title=\"Historic Prices\", xaxis_title=\"time\", yaxis_title=\"price\")fig = go.Figure( data=go.Scatter(x=time, y=price), layout=layout) fig.show()"
},
{
"code": null,
"e": 3741,
"s": 3712,
"text": "This is the resulting graph:"
},
{
"code": null,
"e": 3765,
"s": 3741,
"text": "chart-studio.plotly.com"
},
{
"code": null,
"e": 3830,
"s": 3765,
"text": "Here's the list of things I usually do to improve Plotly graphs:"
},
{
"code": null,
"e": 3872,
"s": 3830,
"text": "#1: Remove gridlines and background color"
},
{
"code": null,
"e": 3913,
"s": 3872,
"text": "#2: Keep consistent colors across graphs"
},
{
"code": null,
"e": 3955,
"s": 3913,
"text": "#3: Use spikelines to compare data points"
},
{
"code": null,
"e": 4020,
"s": 3955,
"text": "#4: Remove floating menu, disable zoom and adjust click behavior"
},
{
"code": null,
"e": 4370,
"s": 4020,
"text": "Gridlines are lines that cross the chart to show axis divisions. They help the viewer visualize the value represented by an unlabeled data point fast. However, gridlines are not very useful when working with interactive graphs. You can hover over a data point and see its value. So more often than not, I remove gridlines when working with Plotly."
},
{
"code": null,
"e": 4396,
"s": 4370,
"text": "Here's how you can do it:"
},
{
"code": null,
"e": 5079,
"s": 4396,
"text": "import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns = np.random.normal(0.01, 0.2, 100)price = 100 * np.exp(returns.cumsum())time = np.arange(100)layout = go.Layout( title=\"Historic Prices\", plot_bgcolor=\"#FFF\", # Sets background color to white xaxis=dict( title=\"time\", linecolor=\"#BCCCDC\", # Sets color of X-axis line showgrid=False # Removes X-axis grid lines ), yaxis=dict( title=\"price\", linecolor=\"#BCCCDC\", # Sets color of Y-axis line showgrid=False, # Removes Y-axis grid lines ))fig = go.Figure( data=go.Scatter(x=time, y=price), layout=layout) fig.show()"
},
{
"code": null,
"e": 5106,
"s": 5079,
"text": "And this is how it looks:"
},
{
"code": null,
"e": 5117,
"s": 5106,
"text": "plotly.com"
},
{
"code": null,
"e": 5433,
"s": 5117,
"text": "When working with categories, there are two things people usually like to do. First, they want to assign some specific colors to each group. For instance, if you are analyzing electoral results in the US, you probably want to use particular blue and red variations to identify the Democratic and Republican parties."
},
{
"code": null,
"e": 5680,
"s": 5433,
"text": "Second, you want this color to remain consistent across all the graphs you do. For example, if you are analyzing some real-world companies, you may want to use their distinctive colors to plot their prices but also when you analyze their returns."
},
{
"code": null,
"e": 5721,
"s": 5680,
"text": "Here's how you can do that using Plotly:"
},
{
"code": null,
"e": 7560,
"s": 5721,
"text": "import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = [\"A\"] * 100 + [\"B\"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({ \"company\": companies, \"time\": time, \"price\": prices, \"returns\": returns})# Build graphCOLORS_MAPPER = { \"A\": \"#38BEC9\", \"B\": \"#D64545\"}layout = go.Layout( title=\"Performance of A vs. B\", plot_bgcolor=\"#FFFFFF\", barmode=\"stack\", xaxis=dict( domain=[0, 0.5], title=\"time\", linecolor=\"#BCCCDC\", ), yaxis=dict( title=\"price\", linecolor=\"#BCCCDC\" ), xaxis2=dict( domain=[0.6, 1], title=\"returns\", linecolor=\"#BCCCDC\", ), yaxis2=dict( anchor=\"x2\", linecolor=\"#BCCCDC\" ))data = []for company,col in COLORS_MAPPER.items(): time = df.loc[df.company == company, \"time\"] price = df.loc[df.company == company, \"price\"] returns = df.loc[df.company == company, \"returns\"] line_chart = go.Scatter( x=time, y=price, marker_color=col, # Defines specific color for a trace legendgroup=company, # Groups traces belonging to the same group in the legend name=company ) histogram = go.Histogram( x=returns, marker_color=col, # Defines specific color for a trace legendgroup=company, # Groups traces belonging to the same group in the legend xaxis=\"x2\", yaxis=\"y2\", showlegend=False ) data.append(line_chart) data.append(histogram)fig = go.Figure(data=data, layout=layout)fig.show()"
},
{
"code": null,
"e": 7862,
"s": 7560,
"text": "The snippet above allows you to keep consistent colors when working with multiple graphs that share the same categories. The critical part is the COLOR_MAPPER dictionary and its use when adding new traces. This dictionary is the mapping of the categories and colors you'll be using across your charts."
},
{
"code": null,
"e": 8008,
"s": 7862,
"text": "Whenever you add a trace to a graph, you can assign the right color to the marker_color attribute by getting it from the COLOR_MAPPER dictionary."
},
{
"code": null,
"e": 8047,
"s": 8008,
"text": "The resulting graph looks as follows:"
},
{
"code": null,
"e": 8058,
"s": 8047,
"text": "plotly.com"
},
{
"code": null,
"e": 8251,
"s": 8058,
"text": "A spike line is a vertical or horizontal line that appears when hovering on data. It's useful for comparing values in line charts and scatter plots. This is how you can add those using Plotly:"
},
{
"code": null,
"e": 9679,
"s": 8251,
"text": "import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = [\"A\"] * 100 + [\"B\"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({ \"company\": companies, \"time\": time, \"price\": prices, \"returns\": returns})# Build graphlayout = go.Layout( title=\"Performance of A vs. B\", plot_bgcolor=\"#FFFFFF\", hovermode=\"x\", hoverdistance=100, # Distance to show hover label of data point spikedistance=1000, # Distance to show spike xaxis=dict( title=\"time\", linecolor=\"#BCCCDC\", showspikes=True, # Show spike line for X-axis # Format spike spikethickness=2, spikedash=\"dot\", spikecolor=\"#999999\", spikemode=\"across\", ), yaxis=dict( title=\"price\", linecolor=\"#BCCCDC\" ))data = []for company in [\"A\", \"B\"]: time = df.loc[df.company == company, \"time\"] price = df.loc[df.company == company, \"price\"] returns = df.loc[df.company == company, \"returns\"] line_chart = go.Scatter( x=time, y=price, name=company ) data.append(line_chart)fig = go.Figure(data=data, layout=layout)fig.show()"
},
{
"code": null,
"e": 9708,
"s": 9679,
"text": "This is the resulting graph:"
},
{
"code": null,
"e": 9719,
"s": 9708,
"text": "plotly.com"
},
{
"code": null,
"e": 9986,
"s": 9719,
"text": "I'm not too fond of the floating menu that Plotly adds to your chart by default. It makes graphs look cool, but I've rarely seen people using it. It has so many options that it's just confusing for someone looking at a graph for the first time. Usually, I remove it."
},
{
"code": null,
"e": 10360,
"s": 9986,
"text": "Also, I like to re-define two other user interaction parameters. I prefer to limit the users' ability to zoom in and change the behavior of clicking on a trace in the legend. In Plotly, by default, if you want to inspect a trace on its own, you have to double-click on the trace, instead of just clicking on it. That's not very intuitive, so I tend to invert that behavior."
},
{
"code": null,
"e": 10401,
"s": 10360,
"text": "This is how you can apply those changes:"
},
{
"code": null,
"e": 11735,
"s": 10401,
"text": "import plotly.graph_objects as goimport numpy as npnp.random.seed(42)# Simulate datareturns_A = np.random.normal(0.01, 0.2, 100)returns_B = np.random.normal(0.01, 0.2, 100)returns = np.append(returns_A, returns_B)prices_A = 100 * np.exp(returns_A.cumsum())prices_B = 100 * np.exp(returns_B.cumsum())prices = np.append(prices_A, prices_B)companies = [\"A\"] * 100 + [\"B\"] * 100time = np.append(np.arange(100), np.arange(100))df = pd.DataFrame({ \"company\": companies, \"time\": time, \"price\": prices, \"returns\": returns})# Build graphlayout = go.Layout( title=\"Performance of A vs. B\", plot_bgcolor=\"#FFFFFF\", legend=dict( # Adjust click behavior itemclick=\"toggleothers\", itemdoubleclick=\"toggle\", ), xaxis=dict( title=\"time\", linecolor=\"#BCCCDC\", ), yaxis=dict( title=\"price\", linecolor=\"#BCCCDC\" ))data = []for company in [\"A\", \"B\"]: time = df.loc[df.company == company, \"time\"] price = df.loc[df.company == company, \"price\"] returns = df.loc[df.company == company, \"returns\"] line_chart = go.Scatter( x=time, y=price, name=company ) data.append(line_chart)fig = go.Figure(data=data, layout=layout)fig.show(config={\"displayModeBar\": False, \"showTips\": False}) # Remove floating menu and unnecesary dialog box"
},
{
"code": null,
"e": 11764,
"s": 11735,
"text": "This is the resulting graph:"
},
{
"code": null,
"e": 11775,
"s": 11764,
"text": "plotly.com"
},
{
"code": null,
"e": 11874,
"s": 11775,
"text": "There are three things that I've found useful for learning how to make better data visualizations:"
},
{
"code": null,
"e": 12591,
"s": 11874,
"text": "Get feedback from your audience: This is not always possible. But if you can do it, always prioritize getting input from those who will use your data visualizations. If you are working on a dashboard, the first thing you should do is understand what problem your dashboard solves. Then see users interacting with it. That has the highest ROI for your time.Check out Storytelling with Data by Cole Knaflic: It's a great book if you want to level-up your data visualization design skills. It provides a lot of practical advice and compelling use cases.Ploty's Figure Reference: Get used to Plotly's Figure Reference and Plotly's documentation. You'll be using it a lot. In general, Plotly's documentation is excellent."
},
{
"code": null,
"e": 12948,
"s": 12591,
"text": "Get feedback from your audience: This is not always possible. But if you can do it, always prioritize getting input from those who will use your data visualizations. If you are working on a dashboard, the first thing you should do is understand what problem your dashboard solves. Then see users interacting with it. That has the highest ROI for your time."
},
{
"code": null,
"e": 13143,
"s": 12948,
"text": "Check out Storytelling with Data by Cole Knaflic: It's a great book if you want to level-up your data visualization design skills. It provides a lot of practical advice and compelling use cases."
},
{
"code": null,
"e": 13310,
"s": 13143,
"text": "Ploty's Figure Reference: Get used to Plotly's Figure Reference and Plotly's documentation. You'll be using it a lot. In general, Plotly's documentation is excellent."
},
{
"code": null,
"e": 13564,
"s": 13310,
"text": "I hope you found these ideas useful. There might be some things that do not resonate with you, or others that you feel are missing. If that's the case, please let me know in the comments below. I'll be happy to update this and add other valuable advice."
},
{
"code": null,
"e": 13707,
"s": 13564,
"text": "You can find other articles I’ve authored here Or if you want to keep up-to-date with what I’m doing you can follow me on Twitter or LinkedIn."
}
]
|
Java program to find all duplicate characters in a string | The duplicate characters in a string are those that occur more than once. These characters can be found using a nested for loop. An example of this is given as follows −
String = Apple
In the above string, p is a duplicate character as it occurs more than once.
A program that demonstrates this is given as follows.
Live Demo
public class Example {
public static void main(String argu[]) {
String str = "beautiful beach";
char[] carray = str.toCharArray();
System.out.println("The string is:" + str);
System.out.print("Duplicate Characters in above string are: ");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (carray[i] == carray[j]) {
System.out.print(carray[j] + " ");
break;
}
}
}
}
}
The string is:beautiful beach
Duplicate Characters in above string are: b e a u
Now let us understand the above program.
First, the string str is defined. Then, str.toCharArray() converts the string into a sequence of characters. The original string is displayed. The code snippet that demonstrates this is given as follows −
String str = "beautiful beach";
char[] carray = str.toCharArray();
System.out.println("The string is:" + str);
The duplicate characters are found in the string using a nested for loop. Then these characters are displayed. The code snippet that demonstrates this is given as follows.
System.out.print("Duplicate Characters in above string are: ");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (carray[i] == carray[j]) {
System.out.print(carray[j] + " ");
break;
}
}
} | [
{
"code": null,
"e": 1232,
"s": 1062,
"text": "The duplicate characters in a string are those that occur more than once. These characters can be found using a nested for loop. An example of this is given as follows −"
},
{
"code": null,
"e": 1248,
"s": 1232,
"text": "String = Apple\n"
},
{
"code": null,
"e": 1325,
"s": 1248,
"text": "In the above string, p is a duplicate character as it occurs more than once."
},
{
"code": null,
"e": 1379,
"s": 1325,
"text": "A program that demonstrates this is given as follows."
},
{
"code": null,
"e": 1390,
"s": 1379,
"text": " Live Demo"
},
{
"code": null,
"e": 1911,
"s": 1390,
"text": "public class Example {\n public static void main(String argu[]) {\n String str = \"beautiful beach\";\n char[] carray = str.toCharArray();\n System.out.println(\"The string is:\" + str);\n System.out.print(\"Duplicate Characters in above string are: \");\n for (int i = 0; i < str.length(); i++) {\n for (int j = i + 1; j < str.length(); j++) {\n if (carray[i] == carray[j]) {\n System.out.print(carray[j] + \" \");\n break;\n }\n }\n }\n }\n}"
},
{
"code": null,
"e": 1992,
"s": 1911,
"text": "The string is:beautiful beach\nDuplicate Characters in above string are: b e a u\n"
},
{
"code": null,
"e": 2033,
"s": 1992,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2238,
"s": 2033,
"text": "First, the string str is defined. Then, str.toCharArray() converts the string into a sequence of characters. The original string is displayed. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2350,
"s": 2238,
"text": "String str = \"beautiful beach\";\nchar[] carray = str.toCharArray();\nSystem.out.println(\"The string is:\" + str);\n"
},
{
"code": null,
"e": 2522,
"s": 2350,
"text": "The duplicate characters are found in the string using a nested for loop. Then these characters are displayed. The code snippet that demonstrates this is given as follows."
},
{
"code": null,
"e": 2786,
"s": 2522,
"text": "System.out.print(\"Duplicate Characters in above string are: \");\nfor (int i = 0; i < str.length(); i++) {\n for (int j = i + 1; j < str.length(); j++) {\n if (carray[i] == carray[j]) {\n System.out.print(carray[j] + \" \");\n break;\n }\n }\n}"
}
]
|
Parsing and Formatting a Byte Array into Binary in Java | Set a BigInteger object.
BigInteger one;
Now, create a ByteArray.
byte byteArr[] = new byte[] { 0x1, 0x00, 0x00 };
one = new BigInteger(byteArr);
For Binary, we have used 2 as the toString() method parameter.
String strResult = one.toString(2);
The following is an example −
Live Demo
import java.math.*;
public class Demo {
public static void main(String[] args) {
// BigInteger object
BigInteger one;
byte byteArr[] = new byte[] { 0x1, 0x00, 0x00 };
one = new BigInteger(byteArr);
String strResult = one.toString(2);
System.out.println("ByteArray to Binary = "+strResult);
}
}
ByteArray to Binary = 10000000000000000 | [
{
"code": null,
"e": 1087,
"s": 1062,
"text": "Set a BigInteger object."
},
{
"code": null,
"e": 1103,
"s": 1087,
"text": "BigInteger one;"
},
{
"code": null,
"e": 1128,
"s": 1103,
"text": "Now, create a ByteArray."
},
{
"code": null,
"e": 1208,
"s": 1128,
"text": "byte byteArr[] = new byte[] { 0x1, 0x00, 0x00 };\none = new BigInteger(byteArr);"
},
{
"code": null,
"e": 1271,
"s": 1208,
"text": "For Binary, we have used 2 as the toString() method parameter."
},
{
"code": null,
"e": 1307,
"s": 1271,
"text": "String strResult = one.toString(2);"
},
{
"code": null,
"e": 1337,
"s": 1307,
"text": "The following is an example −"
},
{
"code": null,
"e": 1348,
"s": 1337,
"text": " Live Demo"
},
{
"code": null,
"e": 1684,
"s": 1348,
"text": "import java.math.*;\npublic class Demo {\n public static void main(String[] args) {\n // BigInteger object\n BigInteger one;\n byte byteArr[] = new byte[] { 0x1, 0x00, 0x00 };\n one = new BigInteger(byteArr);\n String strResult = one.toString(2);\n System.out.println(\"ByteArray to Binary = \"+strResult);\n }\n}"
},
{
"code": null,
"e": 1724,
"s": 1684,
"text": "ByteArray to Binary = 10000000000000000"
}
]
|
A Complete Yet Simple Guide to Move from Excel to Python | by Frank Andrade | Towards Data Science | As someone who has been working with Excel for many years, I know that the idea of learning things you can already do in Excel/VBA in a completely new environment like Python doesn’t sound so exciting. However, all the benefits that the Python environment offers make this worth it. For this reason, I came up with a useful and simple guide I wish I had when I switched from Excel to Python.
In this article, we’ll use Python’s Pandas and Numpy library to replace many Excel functions you probably used in the past.
Table of Contents1. The Dataset2. Sum, Average, Max, Min, Count - Columns (e.g. sum a column) - Rows (e.g. sum a row)3. IF - Replace IF with np.where - Replace nested IF with np.select4. SumIf, CountIf, AverageIf - One condition (select a column with square brackets [ ] ) - Two or more conditions (select columns and use & or |)5. Basic Data Cleaning - Change the case of text with .str.lower, .str.upper or .str.title - Extract text in a column with .str.extract - Identify whether a cell is empty with the .isnull method6. Vlookup - Find an element with .loc[ ] - Merge two tables with pd.merge or pd.concat7. Pivot Table - Use the .pivot_table method8. Replace Excel Graphs with Python’s Matplotlib or Seaborn
In this guide, we’ll use an Excel file that has a .csv format, which is typically used when working with datasets. The dataset consists of the marks secured by students in various subjects and will help us easily switch from Excel spreadsheets to Python’s dataframes. You can download this data on Kaggle or on my Github (check the datasets folder).
To start with this guide, let’s import the Pandas and Numpy libraries.
import pandas as pdimport numpy as np
Note: If you don’t have those libraries installed in Python, you can easily install them by writing pip install pandas and pip install numpyon your terminal or command prompt.
With this, we can take a first look at the data. To do so, we use pd.read_csv(). Make sure that the CSV and your Python script are located in the same place (same path).
df_excel = pd.read_csv('StudentsPerformance.csv')df_excel
Once we read this CSV file, we give it a name. In this case, I named it df_excel. df stands for dataframe and it’s the typical name given after reading a CSV file. After running the code below, we obtain the following output.
This looks similar to an Excel spreadsheet, but in this format, it’ll be easier to wrangle the data. Now I’ll show you in Python how to do some common functions you probably used in Excel.
Excel’s popular functions can be easily replaced with Pandas methods. Let’s take a look.
If we want to get most of the functions listed above, we use the .describe() method.
df_excel.describe()
As you can see, with this we get the count, mean, max, and min values of all numerical columns.
However, if we want to select a specific row, we first select with square brackets [ ] and then use the method we need (.sum(), .mean(), etc.). For example, let’s calculate the average of math scores.
In [1]: df_excel['math score'].mean()Out [1]: 66.089
These are some of the other methods you can use.
df_excel['math score'].mean()df_excel['math score'].max()df_excel['math score'].min()df_excel['math score'].count()
Now let’s say we want to calculate the average of the 3 marks (math, reading, and writing). Those values are within different columns, so we have 2 options. We can either sum each column
df_excel['average'] = (df_excel['math score'] + df_excel['reading score'] + df_excel['writing score'])/3
Or use the method we used before to sum values within a column, but in this case, we add axis=1
df_excel['average'] = df_excel.mean(axis=1)
We also added a new column [‘average’] when calculating the average. We’ll use this new column for the next section (IF).
Keep in mind that in this example we could use the second option because the only numerical values are within the desired columns ( (math, reading, and writing scores). If there was an additional column we don’t want to consider in the sum, we should only use the first option.
In case we want to count the number of specific data within a column, we can use the .value_counts() method
In [2]: df_excel['gender'].value_counts()Out [2]: female 518male 482
We can easily replace Excel’s IF function by using Numpy.
Let’s imagine we want to know whether a student has passed or failed an exam and create a new column with that information. We can easily do that with the following code.
df_excel['pass/fail'] = np.where(df_excel['average'] > 70, 'Pass', 'Fail')
As you can see np.where() needs 3 arguments — the condition, the value if the condition is True, and the value if the condition is False.
Let’s imagine we want to give grades from A to F based on the scores obtained. In this case, we have more than 2 values, so we use np.select()
np.select() needs to arguments — a list of conditions and a list of values. A list in Python is represented by the square brackets [ ]
conditions = [ (df_excel['average']>=90), (df_excel['average']>=80) & (df_excel['average']<90), (df_excel['average']>=70) & (df_excel['average']<80), (df_excel['average']>=60) & (df_excel['average']<70), (df_excel['average']>=50) & (df_excel['average']<60), (df_excel['average']<50),]values = ['A', 'B', 'C', 'D', 'E', 'F']
Keep in mind that each condition should be within parenthesis. Now we use the .select() method and assign it to a new [‘grades’] column.
df_excel['grades'] = np.select(conditions, values)
Now the first 5 rows of the output should look like this.
We picked these 3 columns with double square brackets df_excel[[‘average’, ‘pass/fail’, ‘grades’]] and the first 5 rows can be displayed with the .head() method.
medium.datadriveninvestor.com
To sum, count, or calculate the average based on a condition, in Python, we first filter out values and then make the calculation.
Let’s imagine we want to sum the scores for only the female gender. To do so, first, we write the condition df_excel[‘gender’] == ‘female’ and then. we select that condition inside the df_excel frame by using square brackets [ ]
df_female = df_excel[df_excel['gender'] == 'female']
We selected only the female gender and placed it in a dataframe called df_female. Now we can perform any calculation we saw in the “Sum, Average, Max, Min, Count” section.
If we have two or more conditions, the code will look similar to the one above, but with some changes. Let’s imagine we want to calculate the score of females within Group B (‘race/ethnicity’)
df_sumifs = df_excel[(df_excel['gender'] == 'female') & (df_excel['race/ethnicity'] == 'group B')]
Since there are 2 conditions we could use & | that represents and/or respectively. Keep in mind that each condition should be within parenthesis.
Now let’s sum the scores.
df_sumifs = df_sumifs.assign(sumifs = df_sumifs['math score'] + df_sumifs['reading score'] + df_sumifs['writing score'])
In this case, I used the .assign() method to show you another way to create a new column while doing calculations.
We’re going to check a few methods used for data cleaning. In case you want to know all the methods used for cleaning data, check the complete guide I wrote on how to clean and prepare data in Python.
towardsdatascience.com
We’ll continue using the df_excel frame we defined before.
To access the strings contained in a column, we use .str Then we can change the case of text with the following
df_excel['gender'].str.title()df_excel['gender'].str.upper()df_excel['gender'].str.title()
To save the values we can overwrite a column like in the code below.
df_excel['gender'] = df_excel['gender'].str.title()
But in this case, we’ll leave the values as it is.
We can easily extract text from a column with .str.extract. In addition to that, if we want to extract specific patterns of a text we can use regular expressions.
Let’s imagine we want to extract only the words in upper case within the column ‘race/ethnicity’ (e.g., “B” from “Group B”). To do so, we write the following code.
df_excel['race/ethnicity'].str.extract(r'([A-Z])')
In this case, we used the regular expression r'([A-Z])’ where [A-Z] indicate words in upper case, while the parenthesis () is necessary to pick the desired pattern. Regular expressions might look intimidating, but they’re simpler than you think. In the link below, you’ll find a simple guide I made to easily learn regular expressions.
towardsdatascience.com
To replace Excel’s COUNTA, in Python we can use .isnull() to find empty values.
df_excel[df_excel['gender'].isnull()]
In this case, there are no empty values so the result will be an empty dataframe.
To find elements as Vlookup does in Excel, we’re going to use .loc[], .merge() or .concat() based on the problem we want to solve.
Only for these examples, we’re going to work with 2 Excel spreadsheets. The first is the same “StudentsPerformance” we’ve been working with so far, while the second is a CSV file named “LanguageScore” that I created with random id and language score values (you can find this file on my Github). Let’s read both files with pd.read_csv() as we did before.
excel_1 = 'StudentsPerformance.csv'excel_2 = 'LanguageScore.csv'df_excel_1 = pd.read_csv(excel_1)df_excel_2 = pd.read_csv(excel_2)
Now we’re going to create an id column on df_excel_1 so it has a column in common with df_excel_2. To do so, we run the following code.
df_excel_1 = df_excel_1.reset_index()df_excel_1 = df_excel_1.rename(columns={'index':'id'})
As you can see, I made an id column based on the index. reset_index() gets rid of the index by adding it as a column. You can drop the index doing .reset_index(drop=True) but in this case, I’ll rename this new index column by using the .rename() method. With this, we have a new id column.
Finding an element using Pandas is as easy as writing .loc[] . Inside [] we have to include the row and column label. Ler’s find the information related to row 100.
In [3]: df_excel_1.loc[100, ]Out [3]:id 100gender malerace/ethnicity group Bparental level of education some collegelunch standardtest preparation course nonemath score 79reading score 67writing score 67
We can also set conditions. For example, we want to get the math score for the student with id equal to 100.
In [3]: df_excel_1.loc[df_excel_1['id']==100, 'math score']Out [3]:100 79Name: math score, dtype: int64
This means that the student with id 100 got score 79 in math.
Let’s imagine you want to add the language score of all students who gave the exam. In this case, we use pd.merge(). This requires that 2 tables have 1 common column. In this case, this column is the id column.
df_excel_3 = pd.merge(df_excel_1, df_excel_2, on='id', how='left')df_excel_3['language score'].fillna('0', inplace=True)
Above you can see that another argument is needed (how). This indicates how the merge is performed. Left and right will havedf_excel_1 and df_excel_2 as a reference for the final result, while inner will only give the common data inside the id column.
You can also use pd.concat() for the same purposes, but you have to set the id as index before concatenating frames and include the frames as lists (within brackets [])
df_excel_3 = pd.concat( [df_excel_1.set_index('id'), df_excel_2.set_index('id')], axis=1)df_excel_3['language score'].fillna('0', inplace=True)df_excel_3
All the values that don’t match will receive a NaN, but we can replace it with any value by using the.fillna() method.
The Pandas’ pivot_table method works similarly to the one you find in Excel.
Let’s imagine we want to obtain the math and writing score of all the groups inside the race/ethnicity column.
df_excel = pd.read_csv('StudentsPerformance.csv')df_pivot = df_excel.pivot_table(index='race/ethnicity', values=['math score', 'writing score'], aggfunc='mean')df_pivot
The index argument will group the ‘race/ethnicity’ column, while the values argument will take the numerical values to show. Finally, the calculations are made by the aggfunc. In this case, we pick the mean. As a result, we obtain the following pivot table.
Python contains different libraries to make visualizations as good as those Excel offers.
Let’s make a simple barplot based on the results of df_pivot we created above. First, we import matplotlib and then we use plt.bar()
import matplotlib.pyplot as pltdf_plot = df_pivot.reset_index()plt.bar(df_plot['race/ethnicity'], df_plot['math score'])plt.show()
The first argument of plt.bar() is the label and the second is the numeric value. Then we display the results with plt.show()
There are many things you can do in a Python plot such as adding labels to the graph, titles, customizing the size of the figure and colors, but that’s a whole new topic. I already made a guide to make beautiful visualizations in Python which includes lineplots, barplot, piecharts, histograms, boxplots, etc. Check it out in the link below.
towardsdatascience.com
That’s it! Now you’re ready to take advantage of all the benefits Python and Pandas offers! All the code used in this article is available on my Github.
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF).
Here’s a list of books I read to learn Python.
betterprogramming.pub
Here are some of the projects you can start once you master Pandas.
medium.datadriveninvestor.com
medium.datadriveninvestor.com
towardsdatascience.com
I also made a guide to help you build your first machine learning model. | [
{
"code": null,
"e": 563,
"s": 171,
"text": "As someone who has been working with Excel for many years, I know that the idea of learning things you can already do in Excel/VBA in a completely new environment like Python doesn’t sound so exciting. However, all the benefits that the Python environment offers make this worth it. For this reason, I came up with a useful and simple guide I wish I had when I switched from Excel to Python."
},
{
"code": null,
"e": 687,
"s": 563,
"text": "In this article, we’ll use Python’s Pandas and Numpy library to replace many Excel functions you probably used in the past."
},
{
"code": null,
"e": 1401,
"s": 687,
"text": "Table of Contents1. The Dataset2. Sum, Average, Max, Min, Count - Columns (e.g. sum a column) - Rows (e.g. sum a row)3. IF - Replace IF with np.where - Replace nested IF with np.select4. SumIf, CountIf, AverageIf - One condition (select a column with square brackets [ ] ) - Two or more conditions (select columns and use & or |)5. Basic Data Cleaning - Change the case of text with .str.lower, .str.upper or .str.title - Extract text in a column with .str.extract - Identify whether a cell is empty with the .isnull method6. Vlookup - Find an element with .loc[ ] - Merge two tables with pd.merge or pd.concat7. Pivot Table - Use the .pivot_table method8. Replace Excel Graphs with Python’s Matplotlib or Seaborn"
},
{
"code": null,
"e": 1751,
"s": 1401,
"text": "In this guide, we’ll use an Excel file that has a .csv format, which is typically used when working with datasets. The dataset consists of the marks secured by students in various subjects and will help us easily switch from Excel spreadsheets to Python’s dataframes. You can download this data on Kaggle or on my Github (check the datasets folder)."
},
{
"code": null,
"e": 1822,
"s": 1751,
"text": "To start with this guide, let’s import the Pandas and Numpy libraries."
},
{
"code": null,
"e": 1860,
"s": 1822,
"text": "import pandas as pdimport numpy as np"
},
{
"code": null,
"e": 2036,
"s": 1860,
"text": "Note: If you don’t have those libraries installed in Python, you can easily install them by writing pip install pandas and pip install numpyon your terminal or command prompt."
},
{
"code": null,
"e": 2206,
"s": 2036,
"text": "With this, we can take a first look at the data. To do so, we use pd.read_csv(). Make sure that the CSV and your Python script are located in the same place (same path)."
},
{
"code": null,
"e": 2264,
"s": 2206,
"text": "df_excel = pd.read_csv('StudentsPerformance.csv')df_excel"
},
{
"code": null,
"e": 2490,
"s": 2264,
"text": "Once we read this CSV file, we give it a name. In this case, I named it df_excel. df stands for dataframe and it’s the typical name given after reading a CSV file. After running the code below, we obtain the following output."
},
{
"code": null,
"e": 2679,
"s": 2490,
"text": "This looks similar to an Excel spreadsheet, but in this format, it’ll be easier to wrangle the data. Now I’ll show you in Python how to do some common functions you probably used in Excel."
},
{
"code": null,
"e": 2768,
"s": 2679,
"text": "Excel’s popular functions can be easily replaced with Pandas methods. Let’s take a look."
},
{
"code": null,
"e": 2853,
"s": 2768,
"text": "If we want to get most of the functions listed above, we use the .describe() method."
},
{
"code": null,
"e": 2873,
"s": 2853,
"text": "df_excel.describe()"
},
{
"code": null,
"e": 2969,
"s": 2873,
"text": "As you can see, with this we get the count, mean, max, and min values of all numerical columns."
},
{
"code": null,
"e": 3170,
"s": 2969,
"text": "However, if we want to select a specific row, we first select with square brackets [ ] and then use the method we need (.sum(), .mean(), etc.). For example, let’s calculate the average of math scores."
},
{
"code": null,
"e": 3223,
"s": 3170,
"text": "In [1]: df_excel['math score'].mean()Out [1]: 66.089"
},
{
"code": null,
"e": 3272,
"s": 3223,
"text": "These are some of the other methods you can use."
},
{
"code": null,
"e": 3388,
"s": 3272,
"text": "df_excel['math score'].mean()df_excel['math score'].max()df_excel['math score'].min()df_excel['math score'].count()"
},
{
"code": null,
"e": 3575,
"s": 3388,
"text": "Now let’s say we want to calculate the average of the 3 marks (math, reading, and writing). Those values are within different columns, so we have 2 options. We can either sum each column"
},
{
"code": null,
"e": 3680,
"s": 3575,
"text": "df_excel['average'] = (df_excel['math score'] + df_excel['reading score'] + df_excel['writing score'])/3"
},
{
"code": null,
"e": 3776,
"s": 3680,
"text": "Or use the method we used before to sum values within a column, but in this case, we add axis=1"
},
{
"code": null,
"e": 3820,
"s": 3776,
"text": "df_excel['average'] = df_excel.mean(axis=1)"
},
{
"code": null,
"e": 3942,
"s": 3820,
"text": "We also added a new column [‘average’] when calculating the average. We’ll use this new column for the next section (IF)."
},
{
"code": null,
"e": 4220,
"s": 3942,
"text": "Keep in mind that in this example we could use the second option because the only numerical values are within the desired columns ( (math, reading, and writing scores). If there was an additional column we don’t want to consider in the sum, we should only use the first option."
},
{
"code": null,
"e": 4328,
"s": 4220,
"text": "In case we want to count the number of specific data within a column, we can use the .value_counts() method"
},
{
"code": null,
"e": 4405,
"s": 4328,
"text": "In [2]: df_excel['gender'].value_counts()Out [2]: female 518male 482"
},
{
"code": null,
"e": 4463,
"s": 4405,
"text": "We can easily replace Excel’s IF function by using Numpy."
},
{
"code": null,
"e": 4634,
"s": 4463,
"text": "Let’s imagine we want to know whether a student has passed or failed an exam and create a new column with that information. We can easily do that with the following code."
},
{
"code": null,
"e": 4709,
"s": 4634,
"text": "df_excel['pass/fail'] = np.where(df_excel['average'] > 70, 'Pass', 'Fail')"
},
{
"code": null,
"e": 4847,
"s": 4709,
"text": "As you can see np.where() needs 3 arguments — the condition, the value if the condition is True, and the value if the condition is False."
},
{
"code": null,
"e": 4990,
"s": 4847,
"text": "Let’s imagine we want to give grades from A to F based on the scores obtained. In this case, we have more than 2 values, so we use np.select()"
},
{
"code": null,
"e": 5125,
"s": 4990,
"text": "np.select() needs to arguments — a list of conditions and a list of values. A list in Python is represented by the square brackets [ ]"
},
{
"code": null,
"e": 5467,
"s": 5125,
"text": "conditions = [ (df_excel['average']>=90), (df_excel['average']>=80) & (df_excel['average']<90), (df_excel['average']>=70) & (df_excel['average']<80), (df_excel['average']>=60) & (df_excel['average']<70), (df_excel['average']>=50) & (df_excel['average']<60), (df_excel['average']<50),]values = ['A', 'B', 'C', 'D', 'E', 'F']"
},
{
"code": null,
"e": 5604,
"s": 5467,
"text": "Keep in mind that each condition should be within parenthesis. Now we use the .select() method and assign it to a new [‘grades’] column."
},
{
"code": null,
"e": 5655,
"s": 5604,
"text": "df_excel['grades'] = np.select(conditions, values)"
},
{
"code": null,
"e": 5713,
"s": 5655,
"text": "Now the first 5 rows of the output should look like this."
},
{
"code": null,
"e": 5875,
"s": 5713,
"text": "We picked these 3 columns with double square brackets df_excel[[‘average’, ‘pass/fail’, ‘grades’]] and the first 5 rows can be displayed with the .head() method."
},
{
"code": null,
"e": 5905,
"s": 5875,
"text": "medium.datadriveninvestor.com"
},
{
"code": null,
"e": 6036,
"s": 5905,
"text": "To sum, count, or calculate the average based on a condition, in Python, we first filter out values and then make the calculation."
},
{
"code": null,
"e": 6265,
"s": 6036,
"text": "Let’s imagine we want to sum the scores for only the female gender. To do so, first, we write the condition df_excel[‘gender’] == ‘female’ and then. we select that condition inside the df_excel frame by using square brackets [ ]"
},
{
"code": null,
"e": 6318,
"s": 6265,
"text": "df_female = df_excel[df_excel['gender'] == 'female']"
},
{
"code": null,
"e": 6490,
"s": 6318,
"text": "We selected only the female gender and placed it in a dataframe called df_female. Now we can perform any calculation we saw in the “Sum, Average, Max, Min, Count” section."
},
{
"code": null,
"e": 6683,
"s": 6490,
"text": "If we have two or more conditions, the code will look similar to the one above, but with some changes. Let’s imagine we want to calculate the score of females within Group B (‘race/ethnicity’)"
},
{
"code": null,
"e": 6782,
"s": 6683,
"text": "df_sumifs = df_excel[(df_excel['gender'] == 'female') & (df_excel['race/ethnicity'] == 'group B')]"
},
{
"code": null,
"e": 6928,
"s": 6782,
"text": "Since there are 2 conditions we could use & | that represents and/or respectively. Keep in mind that each condition should be within parenthesis."
},
{
"code": null,
"e": 6954,
"s": 6928,
"text": "Now let’s sum the scores."
},
{
"code": null,
"e": 7075,
"s": 6954,
"text": "df_sumifs = df_sumifs.assign(sumifs = df_sumifs['math score'] + df_sumifs['reading score'] + df_sumifs['writing score'])"
},
{
"code": null,
"e": 7190,
"s": 7075,
"text": "In this case, I used the .assign() method to show you another way to create a new column while doing calculations."
},
{
"code": null,
"e": 7391,
"s": 7190,
"text": "We’re going to check a few methods used for data cleaning. In case you want to know all the methods used for cleaning data, check the complete guide I wrote on how to clean and prepare data in Python."
},
{
"code": null,
"e": 7414,
"s": 7391,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7473,
"s": 7414,
"text": "We’ll continue using the df_excel frame we defined before."
},
{
"code": null,
"e": 7585,
"s": 7473,
"text": "To access the strings contained in a column, we use .str Then we can change the case of text with the following"
},
{
"code": null,
"e": 7676,
"s": 7585,
"text": "df_excel['gender'].str.title()df_excel['gender'].str.upper()df_excel['gender'].str.title()"
},
{
"code": null,
"e": 7745,
"s": 7676,
"text": "To save the values we can overwrite a column like in the code below."
},
{
"code": null,
"e": 7797,
"s": 7745,
"text": "df_excel['gender'] = df_excel['gender'].str.title()"
},
{
"code": null,
"e": 7848,
"s": 7797,
"text": "But in this case, we’ll leave the values as it is."
},
{
"code": null,
"e": 8011,
"s": 7848,
"text": "We can easily extract text from a column with .str.extract. In addition to that, if we want to extract specific patterns of a text we can use regular expressions."
},
{
"code": null,
"e": 8175,
"s": 8011,
"text": "Let’s imagine we want to extract only the words in upper case within the column ‘race/ethnicity’ (e.g., “B” from “Group B”). To do so, we write the following code."
},
{
"code": null,
"e": 8226,
"s": 8175,
"text": "df_excel['race/ethnicity'].str.extract(r'([A-Z])')"
},
{
"code": null,
"e": 8562,
"s": 8226,
"text": "In this case, we used the regular expression r'([A-Z])’ where [A-Z] indicate words in upper case, while the parenthesis () is necessary to pick the desired pattern. Regular expressions might look intimidating, but they’re simpler than you think. In the link below, you’ll find a simple guide I made to easily learn regular expressions."
},
{
"code": null,
"e": 8585,
"s": 8562,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8665,
"s": 8585,
"text": "To replace Excel’s COUNTA, in Python we can use .isnull() to find empty values."
},
{
"code": null,
"e": 8703,
"s": 8665,
"text": "df_excel[df_excel['gender'].isnull()]"
},
{
"code": null,
"e": 8785,
"s": 8703,
"text": "In this case, there are no empty values so the result will be an empty dataframe."
},
{
"code": null,
"e": 8916,
"s": 8785,
"text": "To find elements as Vlookup does in Excel, we’re going to use .loc[], .merge() or .concat() based on the problem we want to solve."
},
{
"code": null,
"e": 9271,
"s": 8916,
"text": "Only for these examples, we’re going to work with 2 Excel spreadsheets. The first is the same “StudentsPerformance” we’ve been working with so far, while the second is a CSV file named “LanguageScore” that I created with random id and language score values (you can find this file on my Github). Let’s read both files with pd.read_csv() as we did before."
},
{
"code": null,
"e": 9402,
"s": 9271,
"text": "excel_1 = 'StudentsPerformance.csv'excel_2 = 'LanguageScore.csv'df_excel_1 = pd.read_csv(excel_1)df_excel_2 = pd.read_csv(excel_2)"
},
{
"code": null,
"e": 9538,
"s": 9402,
"text": "Now we’re going to create an id column on df_excel_1 so it has a column in common with df_excel_2. To do so, we run the following code."
},
{
"code": null,
"e": 9630,
"s": 9538,
"text": "df_excel_1 = df_excel_1.reset_index()df_excel_1 = df_excel_1.rename(columns={'index':'id'})"
},
{
"code": null,
"e": 9920,
"s": 9630,
"text": "As you can see, I made an id column based on the index. reset_index() gets rid of the index by adding it as a column. You can drop the index doing .reset_index(drop=True) but in this case, I’ll rename this new index column by using the .rename() method. With this, we have a new id column."
},
{
"code": null,
"e": 10085,
"s": 9920,
"text": "Finding an element using Pandas is as easy as writing .loc[] . Inside [] we have to include the row and column label. Ler’s find the information related to row 100."
},
{
"code": null,
"e": 10510,
"s": 10085,
"text": "In [3]: df_excel_1.loc[100, ]Out [3]:id 100gender malerace/ethnicity group Bparental level of education some collegelunch standardtest preparation course nonemath score 79reading score 67writing score 67"
},
{
"code": null,
"e": 10619,
"s": 10510,
"text": "We can also set conditions. For example, we want to get the math score for the student with id equal to 100."
},
{
"code": null,
"e": 10726,
"s": 10619,
"text": "In [3]: df_excel_1.loc[df_excel_1['id']==100, 'math score']Out [3]:100 79Name: math score, dtype: int64"
},
{
"code": null,
"e": 10788,
"s": 10726,
"text": "This means that the student with id 100 got score 79 in math."
},
{
"code": null,
"e": 10999,
"s": 10788,
"text": "Let’s imagine you want to add the language score of all students who gave the exam. In this case, we use pd.merge(). This requires that 2 tables have 1 common column. In this case, this column is the id column."
},
{
"code": null,
"e": 11120,
"s": 10999,
"text": "df_excel_3 = pd.merge(df_excel_1, df_excel_2, on='id', how='left')df_excel_3['language score'].fillna('0', inplace=True)"
},
{
"code": null,
"e": 11372,
"s": 11120,
"text": "Above you can see that another argument is needed (how). This indicates how the merge is performed. Left and right will havedf_excel_1 and df_excel_2 as a reference for the final result, while inner will only give the common data inside the id column."
},
{
"code": null,
"e": 11541,
"s": 11372,
"text": "You can also use pd.concat() for the same purposes, but you have to set the id as index before concatenating frames and include the frames as lists (within brackets [])"
},
{
"code": null,
"e": 11695,
"s": 11541,
"text": "df_excel_3 = pd.concat( [df_excel_1.set_index('id'), df_excel_2.set_index('id')], axis=1)df_excel_3['language score'].fillna('0', inplace=True)df_excel_3"
},
{
"code": null,
"e": 11814,
"s": 11695,
"text": "All the values that don’t match will receive a NaN, but we can replace it with any value by using the.fillna() method."
},
{
"code": null,
"e": 11891,
"s": 11814,
"text": "The Pandas’ pivot_table method works similarly to the one you find in Excel."
},
{
"code": null,
"e": 12002,
"s": 11891,
"text": "Let’s imagine we want to obtain the math and writing score of all the groups inside the race/ethnicity column."
},
{
"code": null,
"e": 12171,
"s": 12002,
"text": "df_excel = pd.read_csv('StudentsPerformance.csv')df_pivot = df_excel.pivot_table(index='race/ethnicity', values=['math score', 'writing score'], aggfunc='mean')df_pivot"
},
{
"code": null,
"e": 12429,
"s": 12171,
"text": "The index argument will group the ‘race/ethnicity’ column, while the values argument will take the numerical values to show. Finally, the calculations are made by the aggfunc. In this case, we pick the mean. As a result, we obtain the following pivot table."
},
{
"code": null,
"e": 12519,
"s": 12429,
"text": "Python contains different libraries to make visualizations as good as those Excel offers."
},
{
"code": null,
"e": 12652,
"s": 12519,
"text": "Let’s make a simple barplot based on the results of df_pivot we created above. First, we import matplotlib and then we use plt.bar()"
},
{
"code": null,
"e": 12783,
"s": 12652,
"text": "import matplotlib.pyplot as pltdf_plot = df_pivot.reset_index()plt.bar(df_plot['race/ethnicity'], df_plot['math score'])plt.show()"
},
{
"code": null,
"e": 12909,
"s": 12783,
"text": "The first argument of plt.bar() is the label and the second is the numeric value. Then we display the results with plt.show()"
},
{
"code": null,
"e": 13251,
"s": 12909,
"text": "There are many things you can do in a Python plot such as adding labels to the graph, titles, customizing the size of the figure and colors, but that’s a whole new topic. I already made a guide to make beautiful visualizations in Python which includes lineplots, barplot, piecharts, histograms, boxplots, etc. Check it out in the link below."
},
{
"code": null,
"e": 13274,
"s": 13251,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 13427,
"s": 13274,
"text": "That’s it! Now you’re ready to take advantage of all the benefits Python and Pandas offers! All the code used in this article is available on my Github."
},
{
"code": null,
"e": 13546,
"s": 13427,
"text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)."
},
{
"code": null,
"e": 13593,
"s": 13546,
"text": "Here’s a list of books I read to learn Python."
},
{
"code": null,
"e": 13615,
"s": 13593,
"text": "betterprogramming.pub"
},
{
"code": null,
"e": 13683,
"s": 13615,
"text": "Here are some of the projects you can start once you master Pandas."
},
{
"code": null,
"e": 13713,
"s": 13683,
"text": "medium.datadriveninvestor.com"
},
{
"code": null,
"e": 13743,
"s": 13713,
"text": "medium.datadriveninvestor.com"
},
{
"code": null,
"e": 13766,
"s": 13743,
"text": "towardsdatascience.com"
}
]
|
Count rows/columns with sum equals to diagonal sum in C++ | We are given a matrix which is a 2-D array having rows and columns and the task is to calculate the count of sum of all the rows and columns such that it is equal to the sum of either principal or secondary matrix.
Input −
int arr[row][col] = {
{ 4, 1, 7 },
{ 10, 3, 5 },
{ 2, 2, 11}
}
Output − Count of rows/columns with sum equals to diagonal sum are &mins; 2
Explanation −
sum of principal diagonal is: 4 + 3 + 11 = 18 and sum of secondary diagonal is: 7 + 3 + 2 = 12. Sum of rows are 4 + 1 + 7 = 12(TRUE), 10 + 3 + 5 = 18(TRUE), 2 + 2 + 11 = 15(FALSE) and sum of columns are: 4 + 10 + 2 = 16(FALSE), 1 + 3 + 2 = 6(FALSE), 7 + 5 + 11 = 23(FALSE). Therefore, the count of rows/columns matching with the sum of principal diagonal and secondary diagonal are − 2
Input −
int arr[row][col] = {
{ 1, 2, 3 },
{ 4, 5, 2 },
{ 7, 9, 10}
}
Output − Count of rows/columns with sum equals to diagonal sum are − 2
Explanation −
sum of principal diagonal is: 1 + 5 + 10 = 16 and sum of secondary diagonal is: 7 + 3 + 5 = 15. Sum of rows are 1 + 2 + 3 = 6(FALSE), 4 + 5 + 2 = 11(FALSE), 7 + 9 + 10 = 26(FALSE) and sum of columns are: 7 + 4 + 1 = 12(FALSE), 9 + 5 + 2 = 16(TRUE), 3 + 2 + 10 = 15(TRUE). Therefore, the count of rows/columns matching with the sum of principal diagonal and secondary diagonal are − 2
Create a 2-D array to form a matrix of row size and column size
Create a 2-D array to form a matrix of row size and column size
Create variable for principal and secondary matrix. Also, a count variable to store the count
Create variable for principal and secondary matrix. Also, a count variable to store the count
Start loop FOR from i to 0 till col and j from col - 1 till col, increment the i and decrement the j
Start loop FOR from i to 0 till col and j from col - 1 till col, increment the i and decrement the j
Inside the loop, set principal as principal + matrix[i][i] and secondary as secondary + matrix[i][j]
Inside the loop, set principal as principal + matrix[i][i] and secondary as secondary + matrix[i][j]
Start loop FOR from i to 0 till col
Start loop FOR from i to 0 till col
Inside the loop, set row to 0 and col to 0 and inside the loop, start another loop FOR from j to 0 till col
Inside the loop, set row to 0 and col to 0 and inside the loop, start another loop FOR from j to 0 till col
Inside the loops, set row as row + matrix[i][j]
Inside the loops, set row as row + matrix[i][j]
Inside the loop, start another loop FOR from j to 0 till colInside the loop, col to col + matrix[j][i]
Inside the loop, start another loop FOR from j to 0 till col
Inside the loop, check IF (row == principal) || (row == secondary) then increment the count by 1
Inside the loop, check IF (row == principal) || (row == secondary) then increment the count by 1
Inside the loop, check IF (col == principal) || (col == secondary) then increment the count by 1
Inside the loop, check IF (col == principal) || (col == secondary) then increment the count by 1
Return the count
Return the count
Print the result.
Print the result.
Live Demo
#include <iostream>
#define row 3
#define col 3
using namespace std;
int diagonal_sum(int matrix[row][col]){
int principal = 0;
int secondary = 0;
int r = 0;
int c = 0;
int count = 0;
int i = 0, j = 0;
for (i = 0, j = col - 1; i < col; i++, j--){
principal += matrix[i][i];
secondary += matrix[i][j];
}
for (int i = 0; i < col; i++){
r = 0;
c = 0;
for (int j = 0; j < col; j++){
r += matrix[i][j];
}
for (int j = 0; j < col; j++){
c += matrix[j][i];
}
if ((r == principal) || (r == secondary)){
count++;
}
if ((c == principal) || (c == secondary)){
count++;
}
}
return count;
}
int main(){
int matrix[row][col] = {
{ 4, 1, 7 },
{ 10, 3, 5 },
{ 2, 2, 11}};
cout<<"Count of rows/columns with sum equals to diagonal sum are: "<<diagonal_sum(matrix);
return 0;
}
If we run the above code it will generate the following output −
Count of rows/columns with sum equals to diagonal sum are: 2 | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "We are given a matrix which is a 2-D array having rows and columns and the task is to calculate the count of sum of all the rows and columns such that it is equal to the sum of either principal or secondary matrix."
},
{
"code": null,
"e": 1285,
"s": 1277,
"text": "Input −"
},
{
"code": null,
"e": 1357,
"s": 1285,
"text": "int arr[row][col] = {\n { 4, 1, 7 },\n { 10, 3, 5 },\n { 2, 2, 11}\n}"
},
{
"code": null,
"e": 1433,
"s": 1357,
"text": "Output − Count of rows/columns with sum equals to diagonal sum are &mins; 2"
},
{
"code": null,
"e": 1447,
"s": 1433,
"text": "Explanation −"
},
{
"code": null,
"e": 1833,
"s": 1447,
"text": "sum of principal diagonal is: 4 + 3 + 11 = 18 and sum of secondary diagonal is: 7 + 3 + 2 = 12. Sum of rows are 4 + 1 + 7 = 12(TRUE), 10 + 3 + 5 = 18(TRUE), 2 + 2 + 11 = 15(FALSE) and sum of columns are: 4 + 10 + 2 = 16(FALSE), 1 + 3 + 2 = 6(FALSE), 7 + 5 + 11 = 23(FALSE). Therefore, the count of rows/columns matching with the sum of principal diagonal and secondary diagonal are − 2"
},
{
"code": null,
"e": 1841,
"s": 1833,
"text": "Input −"
},
{
"code": null,
"e": 1912,
"s": 1841,
"text": "int arr[row][col] = {\n { 1, 2, 3 },\n { 4, 5, 2 },\n { 7, 9, 10}\n}"
},
{
"code": null,
"e": 1983,
"s": 1912,
"text": "Output − Count of rows/columns with sum equals to diagonal sum are − 2"
},
{
"code": null,
"e": 1997,
"s": 1983,
"text": "Explanation −"
},
{
"code": null,
"e": 2381,
"s": 1997,
"text": "sum of principal diagonal is: 1 + 5 + 10 = 16 and sum of secondary diagonal is: 7 + 3 + 5 = 15. Sum of rows are 1 + 2 + 3 = 6(FALSE), 4 + 5 + 2 = 11(FALSE), 7 + 9 + 10 = 26(FALSE) and sum of columns are: 7 + 4 + 1 = 12(FALSE), 9 + 5 + 2 = 16(TRUE), 3 + 2 + 10 = 15(TRUE). Therefore, the count of rows/columns matching with the sum of principal diagonal and secondary diagonal are − 2"
},
{
"code": null,
"e": 2445,
"s": 2381,
"text": "Create a 2-D array to form a matrix of row size and column size"
},
{
"code": null,
"e": 2509,
"s": 2445,
"text": "Create a 2-D array to form a matrix of row size and column size"
},
{
"code": null,
"e": 2603,
"s": 2509,
"text": "Create variable for principal and secondary matrix. Also, a count variable to store the count"
},
{
"code": null,
"e": 2697,
"s": 2603,
"text": "Create variable for principal and secondary matrix. Also, a count variable to store the count"
},
{
"code": null,
"e": 2798,
"s": 2697,
"text": "Start loop FOR from i to 0 till col and j from col - 1 till col, increment the i and decrement the j"
},
{
"code": null,
"e": 2899,
"s": 2798,
"text": "Start loop FOR from i to 0 till col and j from col - 1 till col, increment the i and decrement the j"
},
{
"code": null,
"e": 3000,
"s": 2899,
"text": "Inside the loop, set principal as principal + matrix[i][i] and secondary as secondary + matrix[i][j]"
},
{
"code": null,
"e": 3101,
"s": 3000,
"text": "Inside the loop, set principal as principal + matrix[i][i] and secondary as secondary + matrix[i][j]"
},
{
"code": null,
"e": 3137,
"s": 3101,
"text": "Start loop FOR from i to 0 till col"
},
{
"code": null,
"e": 3173,
"s": 3137,
"text": "Start loop FOR from i to 0 till col"
},
{
"code": null,
"e": 3281,
"s": 3173,
"text": "Inside the loop, set row to 0 and col to 0 and inside the loop, start another loop FOR from j to 0 till col"
},
{
"code": null,
"e": 3389,
"s": 3281,
"text": "Inside the loop, set row to 0 and col to 0 and inside the loop, start another loop FOR from j to 0 till col"
},
{
"code": null,
"e": 3437,
"s": 3389,
"text": "Inside the loops, set row as row + matrix[i][j]"
},
{
"code": null,
"e": 3485,
"s": 3437,
"text": "Inside the loops, set row as row + matrix[i][j]"
},
{
"code": null,
"e": 3588,
"s": 3485,
"text": "Inside the loop, start another loop FOR from j to 0 till colInside the loop, col to col + matrix[j][i]"
},
{
"code": null,
"e": 3649,
"s": 3588,
"text": "Inside the loop, start another loop FOR from j to 0 till col"
},
{
"code": null,
"e": 3746,
"s": 3649,
"text": "Inside the loop, check IF (row == principal) || (row == secondary) then increment the count by 1"
},
{
"code": null,
"e": 3843,
"s": 3746,
"text": "Inside the loop, check IF (row == principal) || (row == secondary) then increment the count by 1"
},
{
"code": null,
"e": 3940,
"s": 3843,
"text": "Inside the loop, check IF (col == principal) || (col == secondary) then increment the count by 1"
},
{
"code": null,
"e": 4037,
"s": 3940,
"text": "Inside the loop, check IF (col == principal) || (col == secondary) then increment the count by 1"
},
{
"code": null,
"e": 4054,
"s": 4037,
"text": "Return the count"
},
{
"code": null,
"e": 4071,
"s": 4054,
"text": "Return the count"
},
{
"code": null,
"e": 4089,
"s": 4071,
"text": "Print the result."
},
{
"code": null,
"e": 4107,
"s": 4089,
"text": "Print the result."
},
{
"code": null,
"e": 4118,
"s": 4107,
"text": " Live Demo"
},
{
"code": null,
"e": 5045,
"s": 4118,
"text": "#include <iostream>\n#define row 3\n#define col 3\nusing namespace std;\nint diagonal_sum(int matrix[row][col]){\n int principal = 0;\n int secondary = 0;\n int r = 0;\n int c = 0;\n int count = 0;\n int i = 0, j = 0;\n for (i = 0, j = col - 1; i < col; i++, j--){\n principal += matrix[i][i];\n secondary += matrix[i][j];\n }\n for (int i = 0; i < col; i++){\n r = 0;\n c = 0;\n for (int j = 0; j < col; j++){\n r += matrix[i][j];\n }\n for (int j = 0; j < col; j++){\n c += matrix[j][i];\n }\n if ((r == principal) || (r == secondary)){\n count++;\n }\n if ((c == principal) || (c == secondary)){\n count++;\n }\n }\n return count;\n}\nint main(){\n int matrix[row][col] = {\n { 4, 1, 7 },\n { 10, 3, 5 },\n { 2, 2, 11}};\n cout<<\"Count of rows/columns with sum equals to diagonal sum are: \"<<diagonal_sum(matrix);\n return 0;\n}"
},
{
"code": null,
"e": 5110,
"s": 5045,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 5171,
"s": 5110,
"text": "Count of rows/columns with sum equals to diagonal sum are: 2"
}
]
|
Print system time in C++ | The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program.
There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer.
The structure type tm holds the date and time in the form of a C structure having the following elements -
struct tm {
int tm_sec; // seconds of minutes from 0 to 61
int tm_min; // minutes of hour from 0 to 59
int tm_hour; // hours of day from 0 to 24
int tm_mday; // day of month from 1 to 31
int tm_mon; // month of year from 0 to 11
int tm_year; // year since 1900
int tm_wday; // days since sunday
int tm_yday; // days since January 1st
int tm_isdst; // hours of daylight savings time
}
Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same –
Live Demo
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
char* dt = ctime(&now); // convert now to string form
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}
The local date and time is: Fri Mar 22 13:07:39 2019
The UTC date and time is:Fri Mar 22 07:37:39 2019 | [
{
"code": null,
"e": 1327,
"s": 1062,
"text": "The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program."
},
{
"code": null,
"e": 1512,
"s": 1327,
"text": "There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer."
},
{
"code": null,
"e": 1619,
"s": 1512,
"text": "The structure type tm holds the date and time in the form of a C structure having the following elements -"
},
{
"code": null,
"e": 2030,
"s": 1619,
"text": "struct tm {\n int tm_sec; // seconds of minutes from 0 to 61\n int tm_min; // minutes of hour from 0 to 59\n int tm_hour; // hours of day from 0 to 24\n int tm_mday; // day of month from 1 to 31\n int tm_mon; // month of year from 0 to 11\n int tm_year; // year since 1900\n int tm_wday; // days since sunday\n int tm_yday; // days since January 1st\n int tm_isdst; // hours of daylight savings time\n}"
},
{
"code": null,
"e": 2205,
"s": 2030,
"text": "Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same –"
},
{
"code": null,
"e": 2216,
"s": 2205,
"text": " Live Demo"
},
{
"code": null,
"e": 2619,
"s": 2216,
"text": "#include <iostream>\n#include <ctime>\nusing namespace std;\nint main() {\n // current date/time based on current system\n time_t now = time(0);\n char* dt = ctime(&now); // convert now to string form\n cout << \"The local date and time is: \" << dt << endl;\n // convert now to tm struct for UTC\n tm *gmtm = gmtime(&now);\n dt = asctime(gmtm);\n cout << \"The UTC date and time is:\"<< dt << endl;\n}"
},
{
"code": null,
"e": 2722,
"s": 2619,
"text": "The local date and time is: Fri Mar 22 13:07:39 2019\nThe UTC date and time is:Fri Mar 22 07:37:39 2019"
}
]
|
Java Examples - Adding Element to Linked List | How to add an element at first and last position of a linked list ?
Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.addFirst("0");
System.out.println(lList);
lList.addLast("6");
System.out.println(lList);
}
}
The above code sample will produce the following result.
1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6
The following is an another sample example to add an element at first and last position of a linked list?
import java.util.LinkedList;
public class Demo {
public static final void main(String[] args) {
LinkedList lList = new LinkedList();
System.out.println("Number of items in the list: " + lList.size());
String item1 = "foo";
String item2 = "bar";
String item3 = "sai";
String item4 = "prasad";
lList.add(item1);
lList.add(item2);
lList.addFirst(item3);
System.out.println(lList);
lList.addLast(item4);
System.out.println(lList);
System.out.println("Number of items in the list: " + lList.size());
}
}
The above code sample will produce the following result.
Number of items in the list: 0
[sai, foo, bar]
[sai, foo, bar, prasad]
Number of items in the list: 4
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2136,
"s": 2068,
"text": "How to add an element at first and last position of a linked list ?"
},
{
"code": null,
"e": 2293,
"s": 2136,
"text": "Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class."
},
{
"code": null,
"e": 2729,
"s": 2293,
"text": "import java.util.LinkedList;\n\npublic class Main {\n public static void main(String[] args) {\n LinkedList<String> lList = new LinkedList<String>();\n lList.add(\"1\");\n lList.add(\"2\");\n lList.add(\"3\");\n lList.add(\"4\");\n lList.add(\"5\");\n System.out.println(lList);\n \n lList.addFirst(\"0\");\n System.out.println(lList);\n \n lList.addLast(\"6\");\n System.out.println(lList);\n }\n}"
},
{
"code": null,
"e": 2786,
"s": 2729,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2838,
"s": 2786,
"text": "1, 2, 3, 4, 5\n0, 1, 2, 3, 4, 5\n0, 1, 2, 3, 4, 5, 6\n"
},
{
"code": null,
"e": 2944,
"s": 2838,
"text": "The following is an another sample example to add an element at first and last position of a linked list?"
},
{
"code": null,
"e": 3536,
"s": 2944,
"text": "import java.util.LinkedList;\n\npublic class Demo {\n public static final void main(String[] args) {\n LinkedList lList = new LinkedList();\n System.out.println(\"Number of items in the list: \" + lList.size());\n String item1 = \"foo\";\n String item2 = \"bar\";\n String item3 = \"sai\";\n String item4 = \"prasad\";\n \n lList.add(item1);\n lList.add(item2);\n lList.addFirst(item3);\n System.out.println(lList);\n lList.addLast(item4);\n System.out.println(lList);\n System.out.println(\"Number of items in the list: \" + lList.size());\n } \n}"
},
{
"code": null,
"e": 3593,
"s": 3536,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3696,
"s": 3593,
"text": "Number of items in the list: 0\n[sai, foo, bar]\n[sai, foo, bar, prasad]\nNumber of items in the list: 4\n"
},
{
"code": null,
"e": 3703,
"s": 3696,
"text": " Print"
},
{
"code": null,
"e": 3714,
"s": 3703,
"text": " Add Notes"
}
]
|
Data Analysis: From Data to Dashboard with Python, Dash, and Plotly | by Brad Bartram | Towards Data Science | Way back in 1998, I was working at a growing startup and my boss came to me with a task, which was to provide a set of client reports for some of our partners. As a project manager with very little formal training, this was new to me and forced me on this path of trying to be better. Decades later, I’m still working through it and trying to teach what I’ve learned along the way.
If you’re like me, you will likely scream if you see one more project involving the stock datasets. Gapminder is nice but by now it’s played out. Seeing one more dashboard built on Covid data doesn’t really give much value.
That’s what drove the process behind this project and article. But, that’s not all.
I regularly use economic data in my projects. My previous article focused on commodity reports, but there’s a whole store of other data provided by the United States Federal Reserve’s FRED system that we can also use. Here is a link to the previous article if you’re so inclined — though I will say some of that previous article tends to inform this one:
towardsdatascience.com
For me, this project began as a refactor of existing code. I use this data regularly, but when I first approached it, I took a very simple and non-intuitive approach. I wanted to get it done so it lacked a lot of the features I wanted. I decided to re-work it from the ground up, which also gave the opportunity for a teachable moment.
This is what we’re going to create today, which is 100% python using the Dash framework:
Without further belaboring the narrative, let’s get started.
If you’re reading through this top to bottom, here is what you can expect to get out of this article:
Learn to build a professional quality data analysis dashboard, completely in python using the Dash / Plotly frameworks using a non-standard data set.Obtaining the data.Understanding the data and the challenges it will pose.Methods used to manipulate the data in various forms.Construction of the dashboard framework to view and analyze the data.Developing several distinct chart types using plotly libraries to visualize the data in different ways.
Learn to build a professional quality data analysis dashboard, completely in python using the Dash / Plotly frameworks using a non-standard data set.
Obtaining the data.
Understanding the data and the challenges it will pose.
Methods used to manipulate the data in various forms.
Construction of the dashboard framework to view and analyze the data.
Developing several distinct chart types using plotly libraries to visualize the data in different ways.
I know some people find these articles from searches in trying to solve a specific problem. For you, you can get some useful insights and code that may move you further down your specific path.
In total, I have about 30 hours spent in putting this system together. Most of that time was spent mining through docs and references and blogs trying to get around key challenges. Throughout, I will call out many of these concepts since some are not well documented or in easy to find locations.
To work through this article, you will need several things that are all easily avialable:
Computer that can run Python (at least version 3.7 though I developed this using python 3.9)
The modules listed in the “requirements.txt” file
The code from my repository:
github.com
Some nice-to-haves, but not specifically required is a Fed API Key for updating the data using the pull_fed_data.py script.
In the past, I wrote an entire article about obtaining this data. If interested, check it out:
towardsdatascience.com
As is my style with an article such as this, I wrote the code in a highly iterative and logical format so almost any skill level can understand it. I have deliberately avoided any nuanced structures or complex methods specifically to keep approachability high. As a result, some of the code can be a bit slower and go through extraneous steps, so there is opportunity to refactor on your own for practice and skill development.
The first step in any analysis project is to know and understand the data you will work with. This is no different. In fact, this data is specifically a little more challenging, so it does require some understanding of what’s going on.
A sample data file is located in the repository directory named data/fed_data.csv:
The core of this data is a simple arrangement of the fields report_date, data, report_name, hash, and release_date. But they do bear some explaining.
The report_date field is the date of the specific report. It, along with report_name create what could be considered the unique identifier. Well, in theory, but I’ll cover that soon enough.
The data field is relatively self-explanatory. This is the numeric data for the report_name associated with the report_date.
The report_name is the code the FRED system uses to reference a specific report. It is cryptic and not really human-readable unless you memorize them all. In total, there are over 200,000 reports available, so good luck with that.
The hash is a function output from my database to provide a unique key for each distinct data record. It is ignored in this application.
The release_date is where things get tricky with the data. You see, on a regular basis, the Fed releases economic data on specific dates during the month, but from time to time they will revise the data with updated information. The release_date tells us the updates for the data. So, the true unique key is report_date, report_name, and release_date, which will have a distinct data field.
If we only cared about the most recent data, our schema would be narrow and tall with distinct records on each row covering multiple reports. That would be very similar to other analysis data sets we commonly work with in practice. Adding the release_date gives us a different dimension however. It makes this exercise a bit more challenging and allows us to stretch our data analysis muscles a little more.
We know that we need to read in our data and probably do some formatting. We also know that we are going to output this to a dashboard for use. Let’s set that up.
Much like in my commodities dashboard (linked in the intro) I started with a basic framework all included in the repository:
main.py — this is the layout file and driver for the dash dashboard. More on that later.
business_logic.py — this is the file that is called by main.py and sets up some of our global dataframes and constructs.
support_functions.py — this is the workhorse for processing and functional logic.
layout_configs.py — this is a container file to organize various layouts and visual elements for charts.
For these initial steps, we will concern ourselves with the support_functions.py file.
We have a basic understanding of the format of our data, so our first task is to get it into the system in a manner that we can readily work with. For this, we read the whole data file into a Pandas dataframe.
# Base retrieval function - reads from CSVdef get_fed_data(): file_path = base_path + "fed_data.csv" # file_path = base_path + "fed_dump.csv" df = pd.read_csv(file_path, na_values="x") df.rename( {"data": "report_data", "hash": "report_hash"}, axis=1, inplace=True, ) df["report_date"] = df["report_date"].values.astype("datetime64[D]") df["release_date"] = df["release_date"].values.astype("datetime64[D]") return df
This function is pretty straightforward. We pull the configurable base_path variable (not shown) into a format for file_path, which is fed into the read_csv pandas function to create dataframe “df”. From there, we simply rename some columns for consistency and ensure data types are correct for the dates. Then we return the processed data frame.
All simple so far.
However, we can’t just plunk this raw dataframe into a chart and let the magic algorithms do their thing. We need to think about what we need to do with that data individually.
Here lies a challenge with a project like this. No one gave me a spec sheet or instructions for what I needed to get out of it. I had to figure it out myself. The horror...
When faced with ambiguous requirements, you often have to think in generic terms. That’s where I started this stage.
I knew I would need to extract the data based on various criteria and formats, so I began creating some helper functions that could be called individually or as part of a larger process to filter and refine.
I won’t go through all of them, but this is the general template:
# function to pull specific reportdef get_report_from_fed_data(df1, report_name): df = df1.copy() df = df[df["report_name"] == report_name] df.sort_values(by=["report_date"], inplace=True) df.reset_index(drop=True, inplace=True) return df
This specific function is defined to pull all rows of an input dataframe based on a report name that is passed in.
I first begin by making a copy of the dataframe. I do this because if you modify data within a dataframe slice, you will get warnings from pandas. I HATE warnings like that.
The next line simply does the filter on the copy of the passed-in dataframe. This line is mostly what changes from helper function to helper function through this section of code.
I finally sort the resulting data frame appropriately and logically based on what the function is designed to do and then reset the index. The last step is so that the returned dataframe has a consistent index that only encompasses that rows returned.
I have helper functions for filtering to an exact report_date or a report_date greater than or equal to a passed in date as well as similar functions for release_date. All in all, these cover most of the conditions I could see being used to create charts.
Taking the time now to plan out what is possibly needed is ultimately much more efficient than trying to do it on the fly. Thinking about the underlying data and anticipating use cases provides a better contextual understanding and can often save time down the road.
As I began to think more about my end results, I realized I had an annoying gap that I should fix. It goes back to that pesky report_name value and the cryptic nature of it.
To be more user friendly, I should provide a long name that can be referenced. So, I created another function. This is abbreviated here just for sake of brevity, but the core is intact:
def add_report_long_names(df1): df = df1.copy() if df.loc[index, "report_name"] == "AMDMUO": df.loc[ index, "report_long_name" ] = "Manufacturers Unfilled Orders: Durable Goods" df.loc[index, "category"] = "Production" return df
The snippet code above relates to the header image I provided on the data. In this, I simply examine the report_name filed and if it is equal to “AMDMUO” I set a report_long_name value equal to “Manufacturers Unfilled Orders: Durable Goods”. I also take the opportunity to put in a category of “Production”.
At the time I did this, I had no direct idea in mind for the category, but I did know that I probably wanted to do something with it.
Something that is not usually obvious to new analysts working with this type of data is figuring out a method for direct comparison between two wildly different values. How do we normalize that so we can plot a comparison directly on a chart and have it make sense?
A practical way to describe it is how do you plot comparative performance of something like Amazon and Walmart on a chart using stock data? The easiest method is to define the comparison based on rates of change.
The same process works here. And, I do it quite often with type of data.
Luckily, pandas makes short work of it:
def period_change(df): df["period_change"] = df.report_data.pct_change() df["relative_change"] = 1 - df.iloc[0].report_data / df.report_data return df
This function is designed to sit at the end of a filtering chain. It expects that the dataframe fed in will be a distinct report, filtered to a single date and ordered by that date.
The function adds two fields, one for the period change, which is the rate of change from the prior row. The other is the baseline change, which is the percent change from the first row of the dataframe.
But, for this to work, we need that absolute unique, last value:
def get_latest_data(df1): df = df1.copy() df = df.sort_values("release_date").groupby("report_date").tail(1) df.sort_values(by=["report_date"], inplace=True) df.reset_index(drop=True, inplace=True) return df
Again, this is the same template as the other helpers, but in this case, the filter takes the raw dataframe, sorts by release_date, groups by report_date, and pulls the newest entry in the grouped list. As new releases are added, this function makes sure the newest data is used. Simple and effective and allows us to easily feed a clean dataframe into the period_change function.
As soon as I added the category field, I knew I wanted to use it. I still wasn’t sure how specifically, but I did need a means of getting all relevant data from a category and not a report.
Unlike the other helper functions that build upon each other, this function would have to work on the main data frame. That didn’t thrill me, but it’s the way it has to be.
def get_category_data_from_fed_data(df1, report_name, report_date): df = df1.copy() master_list = df["report_name"].unique() master_list = pd.DataFrame(master_list, columns=["report_name"]) master_list = add_report_long_names(master_list) filtered_list = master_list[master_list["report_name"] == report_name] filtered_list = master_list[ master_list["category"] == filtered_list.category.iloc[0] ] df_out = pd.DataFrame() for index, row in filtered_list.iterrows(): temp_df = get_report_from_fed_data(df, row.report_name) temp_df = get_report_after_date_fed_data(temp_df, report_date) temp_df = get_latest_data(temp_df) temp_df = period_change(temp_df) temp_df = add_report_long_names(temp_df) df_out = df_out.append( temp_df, ignore_index=True, ) df_out["period_change"] = df_out["period_change"].fillna(0) return df_out
This took a little bit of processing gymnastics, so I’ll step through it.
For inputs, we take the master dataframe along with a specific target report to use as a base to determine category. We also pass in the report_date as a starting point to limit our scope.
Like the other helpers, we create a copy to work on. Again, let’s avoid those warnings.
Our first step is to create a unique list of the reports, which is then converted from an array back to a dataframe. This allows us to feed that list of reports into the add_report_long_names function to give us the long names and categories for each.
We then create a filtered list of just the report name we’re interested in. Ideally, this should only be one row, but I was a bit paranoid so I assumed there might be a condition where more than one row existed. That explains the second level filter to just get the first row’s category.
Finally, we create an empty data frame to hold our results and loop through the rows of the filtered_list against the main dataframe. This loop shows the waterfall filtering in action. For each row, we get the matching report, we then filter the result to get just the dates after the start date, we then take that result and pull just the latest data, we take that result and add the period change fields, then we run that result through the add_report_long_names function to add additional descriptors. At the bottom of the waterfall, we take the result and add it to the output dataframe.
This leaves us with a clean set of report data matching on the category descriptor.
And that’s the data processing portion of our program. We are now ready to put this data to use.
Like my commodities report dashboard, I started with a clean slate. I won’t belabor the discussion on that here, but if interested check out the article linked in the introduction.
After much debate and determining what I really wanted to see displayed on a regular basis, I settled on a pretty simple arrangement and design.
The layout is a basic grid as provided by the dash-bootstrap-components module with the CYBORG bootstrap theme applied. I like dark colors for my dashboards.
Note that in order to get my charts to match, I used the plotly template.default setting of “plotly_dark”.
Here is how I set up my layout:
Row 1: Header and title.
Row2: Report Selector with Start Date selector.
Row 3: Information bar showing latest report date, latest release date, and latest data value.
Row 4: Raw Data scatter chart.
Row 5: Line charts on periodic changes from last value and from the baseline start date.
Row 6: Header
Row 7: Surface Charts on Category comparison for change from last value and from baseline start.
This gives me a total of five charts. Let’s build those.
The value of this chart to me is that it allows me to not only see the trend based on report_date, but also shows the revision history based on release_date. The image above is Consumer Price Index, which does not have significant revisions, but other charts have major value revisions, which is interesting.
Because this is a scatter chart, I applied the built in LOWESS regression line to get a general idea of linear trend. Also on this chart is the side color bar, which allows color on the chart to be used as a cue on the age of the data point.
Using plotly express, this is a simple chart to construct:
def basic_chart(df, long_name): df["release_int"] = (df.release_date - pd.Timestamp("1970-01-01")) // pd.Timedelta( "1s" ) fig = px.scatter( df, x="report_date", y="report_data", trendline="lowess", color="release_int", color_continuous_scale=px.colors.sequential.YlOrRd_r, hover_name="report_long_name", hover_data={ "release_int": False, "release_date": "| %b %d, %Y", "category": True, }, ) fig.update_layout( newshape=dict(line_color="yellow"), title=(long_name + " Raw Data"), xaxis_title="", yaxis_title="", coloraxis_colorbar=dict( title="Release Date<br> -", thicknessmode="pixels", thickness=50, tickmode="array", tickvals=df.release_int, ticktext=df.release_date.dt.strftime("%m/%d/%Y"), ticks="inside", ), ) # fig.show() return fig
The major function needing to be performed is adding a column for the color bar. Plotly requires color data to be a numeric format. Since I am trying to apply it based on the release_date, it’s just using the built-in pandas time functions to convert the date field to the unix time. Now we have a reference column to define the color bar and markers.
After that, the format of the chart itself is almost completely stock. The hurdles I faced was in modifying the colorbar to use the date for the labels vs. using the integer values. This is laid out in the ticktext line in the update_layout function.
Note, since I define most of my charts as functions to be called by callbacks, I leave the fig.show() line commented in the code. This allows me to troubleshoot and design without having the overhead of the entire Dash app. Running it is as simple as adding a function call at the bottom of the file and running the file.
Because of our earlier work, the callback is similarly easy to decipher.
@app.callback( dash.dependencies.Output("basic-chart", "figure"), [ dash.dependencies.Input("report", "value"), dash.dependencies.Input("start-date", "date"), ],)def basic_report(report, init_date): # set the date from the picker if init_date is not None: date_object = date.fromisoformat(init_date) date_string = date_object.strftime("%Y-%m-%d") # Filter to the report level df = sf.get_report_from_fed_data(bl.fed_df, report) df1 = sf.get_report_after_date_fed_data(df, date_string) # Filter again to the release df2 = sf.get_release_after_date_fed_data(df1, date_string) # Assign long names df2 = sf.add_report_long_names(df2) long_name = df2.report_long_name.iloc[0] fig = sf.basic_chart(df2, long_name) return fig
For input, the app sends the report name and the start date to the callback function. Now we take those values and feed them into the body of the callback function.
The first if statement ensures the date is not empty, which it never should be and formats it into a string that we can use in our helper functions.
The function then calls the get_report function feeding in the main dataframe, it filters it in to get the relevant dates, then filters to get releases after the start date. Finally, it adds the long names since those are used in the title of the chart and grabs one for a variable to be fed into the basic_chart function shown above.
The function creates the chart and returns it as a figure object to the basic-chart id that is held in row 4 of the application.
basic_data = dbc.Row( [ dbc.Col( dcc.Graph( id="basic-chart", style={"height": "70vh"}, config=lc.tool_config, ), md=12, ), ])
Of course, this is the basic row layout. Here we can see the config parameter references the layout_config.py file and applies the tool_config parameters to add the drawing tools I like. The value “md-12” is the configuration for the theme in bootstrap that sets the chart to take up the whole row.
The periodic charts are essentially similar to each other and are called in similar fashion to the basic scatter. I won’t spend a lot of time on them here, but as always, if you have questions — please reach out.
def baseline_change_chart(df, long_name): fig = go.Figure(layout=lc.layout) fig.add_traces( go.Scatter( x=df.report_date, y=df.relative_change, name="Baseline", line_width=2, fill="tozeroy", ) ) fig.add_hline(y=0, line_color="white") fig.update_layout( newshape=dict(line_color="yellow"), title=(long_name + " Change from Baseline"), xaxis_title="", yaxis_title="", ) # fig.show() return fig
Above is the code for the baseline chart and is constructed with the plotly go.Figure methods. I opted for this over the plotly express functions because even at this stage I wasn’t completely certain how I wanted to construct my charts.
However, this chart type gives an additional example, so it works out well.
This, like the other chart type, is almost perfectly text book. The major diversions here are the application of styles from the layout_configs file, the addition of a horizontal line, and the filltozeroy parameter.
In the Main.py file, the callback does similar chained filtering to get to the correct final dataframe. Since the data is only using distinct most recent dates, one more helper function is used.
Over the past few months, I have come to love surface charts for some things. I discovered that while line charts over a longer period can show change adequately, seeing it laid out as a topographical surface in 3d reinforces not only the change, but the interplay between distinct categories.
The downside is that these charts required a bit of pondering to work out. If I were designing a one-off or with defined data that’s nicely packaged, the chart can be built easily. That’s the situation I found while adding a surface chart to my commodities report data. Here, we have a different situation.
The surface charts are designed to compare the relative movements of n+1 reports within a category. That makes creating a flexible template a bit more interesting.
If you’ve stuck with this article for this long, here’s one of the big payoffs. I have not seen this covered elsewhere in my internet journey.
Like the other examples, we’ll define a function to generate a chart based off the processed dataframe:
def category_chart_baseline(df1, report_name, report_date): df = get_category_data_from_fed_data(df1, report_name, report_date) x_data = df["report_date"].unique() y_data = df["report_long_name"].unique() z_data = [] for i in y_data: z_data.append(df[df["report_long_name"] == i]["relative_change"] * 100) fig = go.Figure( go.Surface( contours={ "z": { "show": True, "start": -0.01, "end": 0.01, "size": 0.05, "width": 1, "color": "black", }, }, x=x_data, y=y_data, z=z_data, ) ) category = df.category.iloc[0] begin_date = np.datetime_as_string(x_data.min(), unit="D") end_date = np.datetime_as_string(x_data.max(), unit="D") fig.update_layout( title=category + " Report Baseline Comparison (% Change): <br>" + begin_date + " - " + end_date, scene={ "xaxis_title": "", "yaxis_title": "", "zaxis_title": "", "camera_eye": {"x": 1, "y": -1, "z": 0.75}, "aspectratio": {"x": 0.75, "y": 0.75, "z": 0.5}, }, margin=dict( b=10, l=10, r=10, ), ) # fig.show() return fig
Because we’re using the get_category_data function, the data frame passed in has to be the master dataframe. But, along with that, we also pass in the report and the start date — both provided from the callback as determined by the application. That makes the first part simple.
Next, we generate an array of unique dates for our x-axis and a unique list of reports using the long_report_name for our y-axis. For our z-axis, we loop over the data frame by long report name and feed the report_data values into an array of arrays of percentage values.
Since everything maintains the same sort order, the Y and Z axes will align.
The rest of the function is just setting up the layout and defining the aspects and camera angles by preference. There’s also setting up the title section variables as well, but by now those should be pretty obvious and old hat.
And remember I said the callback was simple?
# Period [email protected]( dash.dependencies.Output("category-baseline-chart", "figure"), [ dash.dependencies.Input("report", "value"), dash.dependencies.Input("start-date", "date"), ],)def category_baseline_report(report, init_date): if init_date is not None: date_object = date.fromisoformat(init_date) date_string = date_object.strftime("%Y-%m-%d") fig = sf.category_chart_baseline(bl.fed_df, report, date_string) return fig
Because we went through the trouble of defining our logic functionally upfront, this complex chart comes down to effectively just one line aside from the boilerplate.
Probably the coolest chart type becomes one of the easiest to actually implement.
The hard stuff is done. By now, you have a good idea on working with a somewhat challenging data set and an app that can run it for analyzing broad categories of economic data. That’s a big accomplishment. But, there are a few items that I want to address.
In the repository, I have included an assets directory that includes my stylesheet. This styles the dropdown selector as well as the date selector. Some of this took a while to hunt down and figure out (again, I’m not really a front-end guy). It’s a good resource for figuring out how this app lays out.
For me, this is a work in progress. There were a few things I deliberately left off that I thought would make a cool challenge for someone trying to practice some of the concepts.
Add a range slider to the charts to view windows of time.Refactor some of the logic into a class-based approach.Add a layout config to the layout_configs file to style the surface charts.Configure the period line charts to add an arbitrary second or third report.Link up the application to have a database backend instead of a CSV file.
Add a range slider to the charts to view windows of time.
Refactor some of the logic into a class-based approach.
Add a layout config to the layout_configs file to style the surface charts.
Configure the period line charts to add an arbitrary second or third report.
Link up the application to have a database backend instead of a CSV file.
There are others, but try to find new ways to challenge your skills. Learning and growing is never wasted effort.
This about does it for this article. I hope you found it informative, educational, or at least somewhat valuable.
I encourage you to find ways to test your analysis skills. Dig into Dash and Plotly more. I am constantly amazed by the depth and capability of the work these developers have put into it.
While I said it before, it bears repeating. I love to teach and explain. If you have gone through this whole article and don’t understand something or just want a different example, please reach out. I’m more than happy to respond and help however I can. | [
{
"code": null,
"e": 547,
"s": 165,
"text": "Way back in 1998, I was working at a growing startup and my boss came to me with a task, which was to provide a set of client reports for some of our partners. As a project manager with very little formal training, this was new to me and forced me on this path of trying to be better. Decades later, I’m still working through it and trying to teach what I’ve learned along the way."
},
{
"code": null,
"e": 771,
"s": 547,
"text": "If you’re like me, you will likely scream if you see one more project involving the stock datasets. Gapminder is nice but by now it’s played out. Seeing one more dashboard built on Covid data doesn’t really give much value."
},
{
"code": null,
"e": 855,
"s": 771,
"text": "That’s what drove the process behind this project and article. But, that’s not all."
},
{
"code": null,
"e": 1210,
"s": 855,
"text": "I regularly use economic data in my projects. My previous article focused on commodity reports, but there’s a whole store of other data provided by the United States Federal Reserve’s FRED system that we can also use. Here is a link to the previous article if you’re so inclined — though I will say some of that previous article tends to inform this one:"
},
{
"code": null,
"e": 1233,
"s": 1210,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1569,
"s": 1233,
"text": "For me, this project began as a refactor of existing code. I use this data regularly, but when I first approached it, I took a very simple and non-intuitive approach. I wanted to get it done so it lacked a lot of the features I wanted. I decided to re-work it from the ground up, which also gave the opportunity for a teachable moment."
},
{
"code": null,
"e": 1658,
"s": 1569,
"text": "This is what we’re going to create today, which is 100% python using the Dash framework:"
},
{
"code": null,
"e": 1719,
"s": 1658,
"text": "Without further belaboring the narrative, let’s get started."
},
{
"code": null,
"e": 1821,
"s": 1719,
"text": "If you’re reading through this top to bottom, here is what you can expect to get out of this article:"
},
{
"code": null,
"e": 2270,
"s": 1821,
"text": "Learn to build a professional quality data analysis dashboard, completely in python using the Dash / Plotly frameworks using a non-standard data set.Obtaining the data.Understanding the data and the challenges it will pose.Methods used to manipulate the data in various forms.Construction of the dashboard framework to view and analyze the data.Developing several distinct chart types using plotly libraries to visualize the data in different ways."
},
{
"code": null,
"e": 2420,
"s": 2270,
"text": "Learn to build a professional quality data analysis dashboard, completely in python using the Dash / Plotly frameworks using a non-standard data set."
},
{
"code": null,
"e": 2440,
"s": 2420,
"text": "Obtaining the data."
},
{
"code": null,
"e": 2496,
"s": 2440,
"text": "Understanding the data and the challenges it will pose."
},
{
"code": null,
"e": 2550,
"s": 2496,
"text": "Methods used to manipulate the data in various forms."
},
{
"code": null,
"e": 2620,
"s": 2550,
"text": "Construction of the dashboard framework to view and analyze the data."
},
{
"code": null,
"e": 2724,
"s": 2620,
"text": "Developing several distinct chart types using plotly libraries to visualize the data in different ways."
},
{
"code": null,
"e": 2918,
"s": 2724,
"text": "I know some people find these articles from searches in trying to solve a specific problem. For you, you can get some useful insights and code that may move you further down your specific path."
},
{
"code": null,
"e": 3215,
"s": 2918,
"text": "In total, I have about 30 hours spent in putting this system together. Most of that time was spent mining through docs and references and blogs trying to get around key challenges. Throughout, I will call out many of these concepts since some are not well documented or in easy to find locations."
},
{
"code": null,
"e": 3305,
"s": 3215,
"text": "To work through this article, you will need several things that are all easily avialable:"
},
{
"code": null,
"e": 3398,
"s": 3305,
"text": "Computer that can run Python (at least version 3.7 though I developed this using python 3.9)"
},
{
"code": null,
"e": 3448,
"s": 3398,
"text": "The modules listed in the “requirements.txt” file"
},
{
"code": null,
"e": 3477,
"s": 3448,
"text": "The code from my repository:"
},
{
"code": null,
"e": 3488,
"s": 3477,
"text": "github.com"
},
{
"code": null,
"e": 3612,
"s": 3488,
"text": "Some nice-to-haves, but not specifically required is a Fed API Key for updating the data using the pull_fed_data.py script."
},
{
"code": null,
"e": 3707,
"s": 3612,
"text": "In the past, I wrote an entire article about obtaining this data. If interested, check it out:"
},
{
"code": null,
"e": 3730,
"s": 3707,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4158,
"s": 3730,
"text": "As is my style with an article such as this, I wrote the code in a highly iterative and logical format so almost any skill level can understand it. I have deliberately avoided any nuanced structures or complex methods specifically to keep approachability high. As a result, some of the code can be a bit slower and go through extraneous steps, so there is opportunity to refactor on your own for practice and skill development."
},
{
"code": null,
"e": 4394,
"s": 4158,
"text": "The first step in any analysis project is to know and understand the data you will work with. This is no different. In fact, this data is specifically a little more challenging, so it does require some understanding of what’s going on."
},
{
"code": null,
"e": 4477,
"s": 4394,
"text": "A sample data file is located in the repository directory named data/fed_data.csv:"
},
{
"code": null,
"e": 4627,
"s": 4477,
"text": "The core of this data is a simple arrangement of the fields report_date, data, report_name, hash, and release_date. But they do bear some explaining."
},
{
"code": null,
"e": 4817,
"s": 4627,
"text": "The report_date field is the date of the specific report. It, along with report_name create what could be considered the unique identifier. Well, in theory, but I’ll cover that soon enough."
},
{
"code": null,
"e": 4942,
"s": 4817,
"text": "The data field is relatively self-explanatory. This is the numeric data for the report_name associated with the report_date."
},
{
"code": null,
"e": 5173,
"s": 4942,
"text": "The report_name is the code the FRED system uses to reference a specific report. It is cryptic and not really human-readable unless you memorize them all. In total, there are over 200,000 reports available, so good luck with that."
},
{
"code": null,
"e": 5310,
"s": 5173,
"text": "The hash is a function output from my database to provide a unique key for each distinct data record. It is ignored in this application."
},
{
"code": null,
"e": 5701,
"s": 5310,
"text": "The release_date is where things get tricky with the data. You see, on a regular basis, the Fed releases economic data on specific dates during the month, but from time to time they will revise the data with updated information. The release_date tells us the updates for the data. So, the true unique key is report_date, report_name, and release_date, which will have a distinct data field."
},
{
"code": null,
"e": 6109,
"s": 5701,
"text": "If we only cared about the most recent data, our schema would be narrow and tall with distinct records on each row covering multiple reports. That would be very similar to other analysis data sets we commonly work with in practice. Adding the release_date gives us a different dimension however. It makes this exercise a bit more challenging and allows us to stretch our data analysis muscles a little more."
},
{
"code": null,
"e": 6272,
"s": 6109,
"text": "We know that we need to read in our data and probably do some formatting. We also know that we are going to output this to a dashboard for use. Let’s set that up."
},
{
"code": null,
"e": 6397,
"s": 6272,
"text": "Much like in my commodities dashboard (linked in the intro) I started with a basic framework all included in the repository:"
},
{
"code": null,
"e": 6486,
"s": 6397,
"text": "main.py — this is the layout file and driver for the dash dashboard. More on that later."
},
{
"code": null,
"e": 6607,
"s": 6486,
"text": "business_logic.py — this is the file that is called by main.py and sets up some of our global dataframes and constructs."
},
{
"code": null,
"e": 6689,
"s": 6607,
"text": "support_functions.py — this is the workhorse for processing and functional logic."
},
{
"code": null,
"e": 6794,
"s": 6689,
"text": "layout_configs.py — this is a container file to organize various layouts and visual elements for charts."
},
{
"code": null,
"e": 6881,
"s": 6794,
"text": "For these initial steps, we will concern ourselves with the support_functions.py file."
},
{
"code": null,
"e": 7091,
"s": 6881,
"text": "We have a basic understanding of the format of our data, so our first task is to get it into the system in a manner that we can readily work with. For this, we read the whole data file into a Pandas dataframe."
},
{
"code": null,
"e": 7554,
"s": 7091,
"text": "# Base retrieval function - reads from CSVdef get_fed_data(): file_path = base_path + \"fed_data.csv\" # file_path = base_path + \"fed_dump.csv\" df = pd.read_csv(file_path, na_values=\"x\") df.rename( {\"data\": \"report_data\", \"hash\": \"report_hash\"}, axis=1, inplace=True, ) df[\"report_date\"] = df[\"report_date\"].values.astype(\"datetime64[D]\") df[\"release_date\"] = df[\"release_date\"].values.astype(\"datetime64[D]\") return df"
},
{
"code": null,
"e": 7901,
"s": 7554,
"text": "This function is pretty straightforward. We pull the configurable base_path variable (not shown) into a format for file_path, which is fed into the read_csv pandas function to create dataframe “df”. From there, we simply rename some columns for consistency and ensure data types are correct for the dates. Then we return the processed data frame."
},
{
"code": null,
"e": 7920,
"s": 7901,
"text": "All simple so far."
},
{
"code": null,
"e": 8097,
"s": 7920,
"text": "However, we can’t just plunk this raw dataframe into a chart and let the magic algorithms do their thing. We need to think about what we need to do with that data individually."
},
{
"code": null,
"e": 8270,
"s": 8097,
"text": "Here lies a challenge with a project like this. No one gave me a spec sheet or instructions for what I needed to get out of it. I had to figure it out myself. The horror..."
},
{
"code": null,
"e": 8387,
"s": 8270,
"text": "When faced with ambiguous requirements, you often have to think in generic terms. That’s where I started this stage."
},
{
"code": null,
"e": 8595,
"s": 8387,
"text": "I knew I would need to extract the data based on various criteria and formats, so I began creating some helper functions that could be called individually or as part of a larger process to filter and refine."
},
{
"code": null,
"e": 8661,
"s": 8595,
"text": "I won’t go through all of them, but this is the general template:"
},
{
"code": null,
"e": 8915,
"s": 8661,
"text": "# function to pull specific reportdef get_report_from_fed_data(df1, report_name): df = df1.copy() df = df[df[\"report_name\"] == report_name] df.sort_values(by=[\"report_date\"], inplace=True) df.reset_index(drop=True, inplace=True) return df"
},
{
"code": null,
"e": 9030,
"s": 8915,
"text": "This specific function is defined to pull all rows of an input dataframe based on a report name that is passed in."
},
{
"code": null,
"e": 9204,
"s": 9030,
"text": "I first begin by making a copy of the dataframe. I do this because if you modify data within a dataframe slice, you will get warnings from pandas. I HATE warnings like that."
},
{
"code": null,
"e": 9384,
"s": 9204,
"text": "The next line simply does the filter on the copy of the passed-in dataframe. This line is mostly what changes from helper function to helper function through this section of code."
},
{
"code": null,
"e": 9636,
"s": 9384,
"text": "I finally sort the resulting data frame appropriately and logically based on what the function is designed to do and then reset the index. The last step is so that the returned dataframe has a consistent index that only encompasses that rows returned."
},
{
"code": null,
"e": 9892,
"s": 9636,
"text": "I have helper functions for filtering to an exact report_date or a report_date greater than or equal to a passed in date as well as similar functions for release_date. All in all, these cover most of the conditions I could see being used to create charts."
},
{
"code": null,
"e": 10159,
"s": 9892,
"text": "Taking the time now to plan out what is possibly needed is ultimately much more efficient than trying to do it on the fly. Thinking about the underlying data and anticipating use cases provides a better contextual understanding and can often save time down the road."
},
{
"code": null,
"e": 10333,
"s": 10159,
"text": "As I began to think more about my end results, I realized I had an annoying gap that I should fix. It goes back to that pesky report_name value and the cryptic nature of it."
},
{
"code": null,
"e": 10519,
"s": 10333,
"text": "To be more user friendly, I should provide a long name that can be referenced. So, I created another function. This is abbreviated here just for sake of brevity, but the core is intact:"
},
{
"code": null,
"e": 10809,
"s": 10519,
"text": "def add_report_long_names(df1): df = df1.copy() if df.loc[index, \"report_name\"] == \"AMDMUO\": df.loc[ index, \"report_long_name\" ] = \"Manufacturers Unfilled Orders: Durable Goods\" df.loc[index, \"category\"] = \"Production\" return df"
},
{
"code": null,
"e": 11117,
"s": 10809,
"text": "The snippet code above relates to the header image I provided on the data. In this, I simply examine the report_name filed and if it is equal to “AMDMUO” I set a report_long_name value equal to “Manufacturers Unfilled Orders: Durable Goods”. I also take the opportunity to put in a category of “Production”."
},
{
"code": null,
"e": 11251,
"s": 11117,
"text": "At the time I did this, I had no direct idea in mind for the category, but I did know that I probably wanted to do something with it."
},
{
"code": null,
"e": 11517,
"s": 11251,
"text": "Something that is not usually obvious to new analysts working with this type of data is figuring out a method for direct comparison between two wildly different values. How do we normalize that so we can plot a comparison directly on a chart and have it make sense?"
},
{
"code": null,
"e": 11730,
"s": 11517,
"text": "A practical way to describe it is how do you plot comparative performance of something like Amazon and Walmart on a chart using stock data? The easiest method is to define the comparison based on rates of change."
},
{
"code": null,
"e": 11803,
"s": 11730,
"text": "The same process works here. And, I do it quite often with type of data."
},
{
"code": null,
"e": 11843,
"s": 11803,
"text": "Luckily, pandas makes short work of it:"
},
{
"code": null,
"e": 12003,
"s": 11843,
"text": "def period_change(df): df[\"period_change\"] = df.report_data.pct_change() df[\"relative_change\"] = 1 - df.iloc[0].report_data / df.report_data return df"
},
{
"code": null,
"e": 12185,
"s": 12003,
"text": "This function is designed to sit at the end of a filtering chain. It expects that the dataframe fed in will be a distinct report, filtered to a single date and ordered by that date."
},
{
"code": null,
"e": 12389,
"s": 12185,
"text": "The function adds two fields, one for the period change, which is the rate of change from the prior row. The other is the baseline change, which is the percent change from the first row of the dataframe."
},
{
"code": null,
"e": 12454,
"s": 12389,
"text": "But, for this to work, we need that absolute unique, last value:"
},
{
"code": null,
"e": 12677,
"s": 12454,
"text": "def get_latest_data(df1): df = df1.copy() df = df.sort_values(\"release_date\").groupby(\"report_date\").tail(1) df.sort_values(by=[\"report_date\"], inplace=True) df.reset_index(drop=True, inplace=True) return df"
},
{
"code": null,
"e": 13058,
"s": 12677,
"text": "Again, this is the same template as the other helpers, but in this case, the filter takes the raw dataframe, sorts by release_date, groups by report_date, and pulls the newest entry in the grouped list. As new releases are added, this function makes sure the newest data is used. Simple and effective and allows us to easily feed a clean dataframe into the period_change function."
},
{
"code": null,
"e": 13248,
"s": 13058,
"text": "As soon as I added the category field, I knew I wanted to use it. I still wasn’t sure how specifically, but I did need a means of getting all relevant data from a category and not a report."
},
{
"code": null,
"e": 13421,
"s": 13248,
"text": "Unlike the other helper functions that build upon each other, this function would have to work on the main data frame. That didn’t thrill me, but it’s the way it has to be."
},
{
"code": null,
"e": 14355,
"s": 13421,
"text": "def get_category_data_from_fed_data(df1, report_name, report_date): df = df1.copy() master_list = df[\"report_name\"].unique() master_list = pd.DataFrame(master_list, columns=[\"report_name\"]) master_list = add_report_long_names(master_list) filtered_list = master_list[master_list[\"report_name\"] == report_name] filtered_list = master_list[ master_list[\"category\"] == filtered_list.category.iloc[0] ] df_out = pd.DataFrame() for index, row in filtered_list.iterrows(): temp_df = get_report_from_fed_data(df, row.report_name) temp_df = get_report_after_date_fed_data(temp_df, report_date) temp_df = get_latest_data(temp_df) temp_df = period_change(temp_df) temp_df = add_report_long_names(temp_df) df_out = df_out.append( temp_df, ignore_index=True, ) df_out[\"period_change\"] = df_out[\"period_change\"].fillna(0) return df_out"
},
{
"code": null,
"e": 14429,
"s": 14355,
"text": "This took a little bit of processing gymnastics, so I’ll step through it."
},
{
"code": null,
"e": 14618,
"s": 14429,
"text": "For inputs, we take the master dataframe along with a specific target report to use as a base to determine category. We also pass in the report_date as a starting point to limit our scope."
},
{
"code": null,
"e": 14706,
"s": 14618,
"text": "Like the other helpers, we create a copy to work on. Again, let’s avoid those warnings."
},
{
"code": null,
"e": 14958,
"s": 14706,
"text": "Our first step is to create a unique list of the reports, which is then converted from an array back to a dataframe. This allows us to feed that list of reports into the add_report_long_names function to give us the long names and categories for each."
},
{
"code": null,
"e": 15246,
"s": 14958,
"text": "We then create a filtered list of just the report name we’re interested in. Ideally, this should only be one row, but I was a bit paranoid so I assumed there might be a condition where more than one row existed. That explains the second level filter to just get the first row’s category."
},
{
"code": null,
"e": 15838,
"s": 15246,
"text": "Finally, we create an empty data frame to hold our results and loop through the rows of the filtered_list against the main dataframe. This loop shows the waterfall filtering in action. For each row, we get the matching report, we then filter the result to get just the dates after the start date, we then take that result and pull just the latest data, we take that result and add the period change fields, then we run that result through the add_report_long_names function to add additional descriptors. At the bottom of the waterfall, we take the result and add it to the output dataframe."
},
{
"code": null,
"e": 15922,
"s": 15838,
"text": "This leaves us with a clean set of report data matching on the category descriptor."
},
{
"code": null,
"e": 16019,
"s": 15922,
"text": "And that’s the data processing portion of our program. We are now ready to put this data to use."
},
{
"code": null,
"e": 16200,
"s": 16019,
"text": "Like my commodities report dashboard, I started with a clean slate. I won’t belabor the discussion on that here, but if interested check out the article linked in the introduction."
},
{
"code": null,
"e": 16345,
"s": 16200,
"text": "After much debate and determining what I really wanted to see displayed on a regular basis, I settled on a pretty simple arrangement and design."
},
{
"code": null,
"e": 16503,
"s": 16345,
"text": "The layout is a basic grid as provided by the dash-bootstrap-components module with the CYBORG bootstrap theme applied. I like dark colors for my dashboards."
},
{
"code": null,
"e": 16610,
"s": 16503,
"text": "Note that in order to get my charts to match, I used the plotly template.default setting of “plotly_dark”."
},
{
"code": null,
"e": 16642,
"s": 16610,
"text": "Here is how I set up my layout:"
},
{
"code": null,
"e": 16667,
"s": 16642,
"text": "Row 1: Header and title."
},
{
"code": null,
"e": 16715,
"s": 16667,
"text": "Row2: Report Selector with Start Date selector."
},
{
"code": null,
"e": 16810,
"s": 16715,
"text": "Row 3: Information bar showing latest report date, latest release date, and latest data value."
},
{
"code": null,
"e": 16841,
"s": 16810,
"text": "Row 4: Raw Data scatter chart."
},
{
"code": null,
"e": 16930,
"s": 16841,
"text": "Row 5: Line charts on periodic changes from last value and from the baseline start date."
},
{
"code": null,
"e": 16944,
"s": 16930,
"text": "Row 6: Header"
},
{
"code": null,
"e": 17041,
"s": 16944,
"text": "Row 7: Surface Charts on Category comparison for change from last value and from baseline start."
},
{
"code": null,
"e": 17098,
"s": 17041,
"text": "This gives me a total of five charts. Let’s build those."
},
{
"code": null,
"e": 17407,
"s": 17098,
"text": "The value of this chart to me is that it allows me to not only see the trend based on report_date, but also shows the revision history based on release_date. The image above is Consumer Price Index, which does not have significant revisions, but other charts have major value revisions, which is interesting."
},
{
"code": null,
"e": 17649,
"s": 17407,
"text": "Because this is a scatter chart, I applied the built in LOWESS regression line to get a general idea of linear trend. Also on this chart is the side color bar, which allows color on the chart to be used as a cue on the age of the data point."
},
{
"code": null,
"e": 17708,
"s": 17649,
"text": "Using plotly express, this is a simple chart to construct:"
},
{
"code": null,
"e": 18697,
"s": 17708,
"text": "def basic_chart(df, long_name): df[\"release_int\"] = (df.release_date - pd.Timestamp(\"1970-01-01\")) // pd.Timedelta( \"1s\" ) fig = px.scatter( df, x=\"report_date\", y=\"report_data\", trendline=\"lowess\", color=\"release_int\", color_continuous_scale=px.colors.sequential.YlOrRd_r, hover_name=\"report_long_name\", hover_data={ \"release_int\": False, \"release_date\": \"| %b %d, %Y\", \"category\": True, }, ) fig.update_layout( newshape=dict(line_color=\"yellow\"), title=(long_name + \" Raw Data\"), xaxis_title=\"\", yaxis_title=\"\", coloraxis_colorbar=dict( title=\"Release Date<br> -\", thicknessmode=\"pixels\", thickness=50, tickmode=\"array\", tickvals=df.release_int, ticktext=df.release_date.dt.strftime(\"%m/%d/%Y\"), ticks=\"inside\", ), ) # fig.show() return fig"
},
{
"code": null,
"e": 19049,
"s": 18697,
"text": "The major function needing to be performed is adding a column for the color bar. Plotly requires color data to be a numeric format. Since I am trying to apply it based on the release_date, it’s just using the built-in pandas time functions to convert the date field to the unix time. Now we have a reference column to define the color bar and markers."
},
{
"code": null,
"e": 19300,
"s": 19049,
"text": "After that, the format of the chart itself is almost completely stock. The hurdles I faced was in modifying the colorbar to use the date for the labels vs. using the integer values. This is laid out in the ticktext line in the update_layout function."
},
{
"code": null,
"e": 19622,
"s": 19300,
"text": "Note, since I define most of my charts as functions to be called by callbacks, I leave the fig.show() line commented in the code. This allows me to troubleshoot and design without having the overhead of the entire Dash app. Running it is as simple as adding a function call at the bottom of the file and running the file."
},
{
"code": null,
"e": 19695,
"s": 19622,
"text": "Because of our earlier work, the callback is similarly easy to decipher."
},
{
"code": null,
"e": 20487,
"s": 19695,
"text": "@app.callback( dash.dependencies.Output(\"basic-chart\", \"figure\"), [ dash.dependencies.Input(\"report\", \"value\"), dash.dependencies.Input(\"start-date\", \"date\"), ],)def basic_report(report, init_date): # set the date from the picker if init_date is not None: date_object = date.fromisoformat(init_date) date_string = date_object.strftime(\"%Y-%m-%d\") # Filter to the report level df = sf.get_report_from_fed_data(bl.fed_df, report) df1 = sf.get_report_after_date_fed_data(df, date_string) # Filter again to the release df2 = sf.get_release_after_date_fed_data(df1, date_string) # Assign long names df2 = sf.add_report_long_names(df2) long_name = df2.report_long_name.iloc[0] fig = sf.basic_chart(df2, long_name) return fig"
},
{
"code": null,
"e": 20652,
"s": 20487,
"text": "For input, the app sends the report name and the start date to the callback function. Now we take those values and feed them into the body of the callback function."
},
{
"code": null,
"e": 20801,
"s": 20652,
"text": "The first if statement ensures the date is not empty, which it never should be and formats it into a string that we can use in our helper functions."
},
{
"code": null,
"e": 21136,
"s": 20801,
"text": "The function then calls the get_report function feeding in the main dataframe, it filters it in to get the relevant dates, then filters to get releases after the start date. Finally, it adds the long names since those are used in the title of the chart and grabs one for a variable to be fed into the basic_chart function shown above."
},
{
"code": null,
"e": 21265,
"s": 21136,
"text": "The function creates the chart and returns it as a figure object to the basic-chart id that is held in row 4 of the application."
},
{
"code": null,
"e": 21490,
"s": 21265,
"text": "basic_data = dbc.Row( [ dbc.Col( dcc.Graph( id=\"basic-chart\", style={\"height\": \"70vh\"}, config=lc.tool_config, ), md=12, ), ])"
},
{
"code": null,
"e": 21789,
"s": 21490,
"text": "Of course, this is the basic row layout. Here we can see the config parameter references the layout_config.py file and applies the tool_config parameters to add the drawing tools I like. The value “md-12” is the configuration for the theme in bootstrap that sets the chart to take up the whole row."
},
{
"code": null,
"e": 22002,
"s": 21789,
"text": "The periodic charts are essentially similar to each other and are called in similar fashion to the basic scatter. I won’t spend a lot of time on them here, but as always, if you have questions — please reach out."
},
{
"code": null,
"e": 22515,
"s": 22002,
"text": "def baseline_change_chart(df, long_name): fig = go.Figure(layout=lc.layout) fig.add_traces( go.Scatter( x=df.report_date, y=df.relative_change, name=\"Baseline\", line_width=2, fill=\"tozeroy\", ) ) fig.add_hline(y=0, line_color=\"white\") fig.update_layout( newshape=dict(line_color=\"yellow\"), title=(long_name + \" Change from Baseline\"), xaxis_title=\"\", yaxis_title=\"\", ) # fig.show() return fig"
},
{
"code": null,
"e": 22753,
"s": 22515,
"text": "Above is the code for the baseline chart and is constructed with the plotly go.Figure methods. I opted for this over the plotly express functions because even at this stage I wasn’t completely certain how I wanted to construct my charts."
},
{
"code": null,
"e": 22829,
"s": 22753,
"text": "However, this chart type gives an additional example, so it works out well."
},
{
"code": null,
"e": 23045,
"s": 22829,
"text": "This, like the other chart type, is almost perfectly text book. The major diversions here are the application of styles from the layout_configs file, the addition of a horizontal line, and the filltozeroy parameter."
},
{
"code": null,
"e": 23240,
"s": 23045,
"text": "In the Main.py file, the callback does similar chained filtering to get to the correct final dataframe. Since the data is only using distinct most recent dates, one more helper function is used."
},
{
"code": null,
"e": 23534,
"s": 23240,
"text": "Over the past few months, I have come to love surface charts for some things. I discovered that while line charts over a longer period can show change adequately, seeing it laid out as a topographical surface in 3d reinforces not only the change, but the interplay between distinct categories."
},
{
"code": null,
"e": 23841,
"s": 23534,
"text": "The downside is that these charts required a bit of pondering to work out. If I were designing a one-off or with defined data that’s nicely packaged, the chart can be built easily. That’s the situation I found while adding a surface chart to my commodities report data. Here, we have a different situation."
},
{
"code": null,
"e": 24005,
"s": 23841,
"text": "The surface charts are designed to compare the relative movements of n+1 reports within a category. That makes creating a flexible template a bit more interesting."
},
{
"code": null,
"e": 24148,
"s": 24005,
"text": "If you’ve stuck with this article for this long, here’s one of the big payoffs. I have not seen this covered elsewhere in my internet journey."
},
{
"code": null,
"e": 24252,
"s": 24148,
"text": "Like the other examples, we’ll define a function to generate a chart based off the processed dataframe:"
},
{
"code": null,
"e": 25629,
"s": 24252,
"text": "def category_chart_baseline(df1, report_name, report_date): df = get_category_data_from_fed_data(df1, report_name, report_date) x_data = df[\"report_date\"].unique() y_data = df[\"report_long_name\"].unique() z_data = [] for i in y_data: z_data.append(df[df[\"report_long_name\"] == i][\"relative_change\"] * 100) fig = go.Figure( go.Surface( contours={ \"z\": { \"show\": True, \"start\": -0.01, \"end\": 0.01, \"size\": 0.05, \"width\": 1, \"color\": \"black\", }, }, x=x_data, y=y_data, z=z_data, ) ) category = df.category.iloc[0] begin_date = np.datetime_as_string(x_data.min(), unit=\"D\") end_date = np.datetime_as_string(x_data.max(), unit=\"D\") fig.update_layout( title=category + \" Report Baseline Comparison (% Change): <br>\" + begin_date + \" - \" + end_date, scene={ \"xaxis_title\": \"\", \"yaxis_title\": \"\", \"zaxis_title\": \"\", \"camera_eye\": {\"x\": 1, \"y\": -1, \"z\": 0.75}, \"aspectratio\": {\"x\": 0.75, \"y\": 0.75, \"z\": 0.5}, }, margin=dict( b=10, l=10, r=10, ), ) # fig.show() return fig"
},
{
"code": null,
"e": 25908,
"s": 25629,
"text": "Because we’re using the get_category_data function, the data frame passed in has to be the master dataframe. But, along with that, we also pass in the report and the start date — both provided from the callback as determined by the application. That makes the first part simple."
},
{
"code": null,
"e": 26180,
"s": 25908,
"text": "Next, we generate an array of unique dates for our x-axis and a unique list of reports using the long_report_name for our y-axis. For our z-axis, we loop over the data frame by long report name and feed the report_data values into an array of arrays of percentage values."
},
{
"code": null,
"e": 26257,
"s": 26180,
"text": "Since everything maintains the same sort order, the Y and Z axes will align."
},
{
"code": null,
"e": 26486,
"s": 26257,
"text": "The rest of the function is just setting up the layout and defining the aspects and camera angles by preference. There’s also setting up the title section variables as well, but by now those should be pretty obvious and old hat."
},
{
"code": null,
"e": 26531,
"s": 26486,
"text": "And remember I said the callback was simple?"
},
{
"code": null,
"e": 27007,
"s": 26531,
"text": "# Period [email protected]( dash.dependencies.Output(\"category-baseline-chart\", \"figure\"), [ dash.dependencies.Input(\"report\", \"value\"), dash.dependencies.Input(\"start-date\", \"date\"), ],)def category_baseline_report(report, init_date): if init_date is not None: date_object = date.fromisoformat(init_date) date_string = date_object.strftime(\"%Y-%m-%d\") fig = sf.category_chart_baseline(bl.fed_df, report, date_string) return fig"
},
{
"code": null,
"e": 27174,
"s": 27007,
"text": "Because we went through the trouble of defining our logic functionally upfront, this complex chart comes down to effectively just one line aside from the boilerplate."
},
{
"code": null,
"e": 27256,
"s": 27174,
"text": "Probably the coolest chart type becomes one of the easiest to actually implement."
},
{
"code": null,
"e": 27513,
"s": 27256,
"text": "The hard stuff is done. By now, you have a good idea on working with a somewhat challenging data set and an app that can run it for analyzing broad categories of economic data. That’s a big accomplishment. But, there are a few items that I want to address."
},
{
"code": null,
"e": 27817,
"s": 27513,
"text": "In the repository, I have included an assets directory that includes my stylesheet. This styles the dropdown selector as well as the date selector. Some of this took a while to hunt down and figure out (again, I’m not really a front-end guy). It’s a good resource for figuring out how this app lays out."
},
{
"code": null,
"e": 27997,
"s": 27817,
"text": "For me, this is a work in progress. There were a few things I deliberately left off that I thought would make a cool challenge for someone trying to practice some of the concepts."
},
{
"code": null,
"e": 28334,
"s": 27997,
"text": "Add a range slider to the charts to view windows of time.Refactor some of the logic into a class-based approach.Add a layout config to the layout_configs file to style the surface charts.Configure the period line charts to add an arbitrary second or third report.Link up the application to have a database backend instead of a CSV file."
},
{
"code": null,
"e": 28392,
"s": 28334,
"text": "Add a range slider to the charts to view windows of time."
},
{
"code": null,
"e": 28448,
"s": 28392,
"text": "Refactor some of the logic into a class-based approach."
},
{
"code": null,
"e": 28524,
"s": 28448,
"text": "Add a layout config to the layout_configs file to style the surface charts."
},
{
"code": null,
"e": 28601,
"s": 28524,
"text": "Configure the period line charts to add an arbitrary second or third report."
},
{
"code": null,
"e": 28675,
"s": 28601,
"text": "Link up the application to have a database backend instead of a CSV file."
},
{
"code": null,
"e": 28789,
"s": 28675,
"text": "There are others, but try to find new ways to challenge your skills. Learning and growing is never wasted effort."
},
{
"code": null,
"e": 28903,
"s": 28789,
"text": "This about does it for this article. I hope you found it informative, educational, or at least somewhat valuable."
},
{
"code": null,
"e": 29091,
"s": 28903,
"text": "I encourage you to find ways to test your analysis skills. Dig into Dash and Plotly more. I am constantly amazed by the depth and capability of the work these developers have put into it."
}
]
|
Jackson - Data Binding With Generics | In simple data binding, we've used Map class which use String as key and Object as a value object. Instead we can have concrete java object and type cast it to be used in JSON binding.
Consider the following example with a class UserData, a class to hold user specific data.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
Map<String, UserData> userDataMap = new HashMap<String, UserData>();
UserData studentData = new UserData();
int[] marks = {1,2,3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentData.setStudent(student);
// JAVA String
studentData.setName("Mahesh Kumar");
// JAVA Boolean
studentData.setVerified(Boolean.FALSE);
// Array
studentData.setMarks(marks);
TypeReference ref = new TypeReference<Map<String,UserData>>() { };
userDataMap.put("studentData1", studentData);
mapper.writeValue(new File("student.json"), userDataMap);
//{
// "studentData1":
// {
// "student":
// {
// "name":"Mahesh",
// "age":10
// },
// "name":"Mahesh Kumar",
// "verified":false,
// "marks":[1,2,3]
// }
//}
userDataMap = mapper.readValue(new File("student.json"), ref);
System.out.println(userDataMap.get("studentData1").getStudent());
System.out.println(userDataMap.get("studentData1").getName());
System.out.println(userDataMap.get("studentData1").getVerified());
System.out.println(Arrays.toString(userDataMap.get("studentData1").getMarks()));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
class UserData {
private Student student;
private String name;
private Boolean verified;
private int[] marks;
public UserData(){}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public int[] getMarks() {
return marks;
}
public void setMarks(int[] marks) {
this.marks = marks;
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
Student [ name: Mahesh, age: 10 ]
Mahesh Kumar
false
[1, 2, 3]
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1938,
"s": 1753,
"text": "In simple data binding, we've used Map class which use String as key and Object as a value object. Instead we can have concrete java object and type cast it to be used in JSON binding."
},
{
"code": null,
"e": 2028,
"s": 1938,
"text": "Consider the following example with a class UserData, a class to hold user specific data."
},
{
"code": null,
"e": 2099,
"s": 2028,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 2124,
"s": 2099,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 5499,
"s": 2124,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n ObjectMapper mapper = new ObjectMapper();\n\n Map<String, UserData> userDataMap = new HashMap<String, UserData>();\n UserData studentData = new UserData(); \n int[] marks = {1,2,3};\n\n Student student = new Student();\n student.setAge(10);\n student.setName(\"Mahesh\");\n // JAVA Object\n studentData.setStudent(student);\n // JAVA String\n studentData.setName(\"Mahesh Kumar\");\n // JAVA Boolean\n studentData.setVerified(Boolean.FALSE);\n // Array\n studentData.setMarks(marks);\n TypeReference ref = new TypeReference<Map<String,UserData>>() { };\n userDataMap.put(\"studentData1\", studentData);\n mapper.writeValue(new File(\"student.json\"), userDataMap);\n //{\n // \"studentData1\":\n //\t {\n //\t\t\"student\":\n //\t\t{\n //\t\t\t\"name\":\"Mahesh\",\n //\t\t\t\"age\":10\n // },\n // \"name\":\"Mahesh Kumar\",\n // \"verified\":false,\n // \"marks\":[1,2,3]\n // }\n //}\n userDataMap = mapper.readValue(new File(\"student.json\"), ref);\n\n System.out.println(userDataMap.get(\"studentData1\").getStudent());\n System.out.println(userDataMap.get(\"studentData1\").getName());\n System.out.println(userDataMap.get(\"studentData1\").getVerified());\n System.out.println(Arrays.toString(userDataMap.get(\"studentData1\").getMarks()));\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\t\n}\n\nclass UserData {\n private Student student;\n private String name;\n private Boolean verified;\n private int[] marks;\n\n public UserData(){}\n\n public Student getStudent() {\n return student;\n }\n public void setStudent(Student student) {\n this.student = student;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public Boolean getVerified() {\n return verified;\n }\n public void setVerified(Boolean verified) {\n this.verified = verified;\n }\n public int[] getMarks() {\n return marks;\n }\n public void setMarks(int[] marks) {\n this.marks = marks;\n }\t\t\n}"
},
{
"code": null,
"e": 5517,
"s": 5499,
"text": "Verify the result"
},
{
"code": null,
"e": 5570,
"s": 5517,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 5616,
"s": 5570,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 5661,
"s": 5616,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 5701,
"s": 5661,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 5719,
"s": 5701,
"text": "Verify the Output"
},
{
"code": null,
"e": 5783,
"s": 5719,
"text": "Student [ name: Mahesh, age: 10 ]\nMahesh Kumar\nfalse\n[1, 2, 3]\n"
},
{
"code": null,
"e": 5790,
"s": 5783,
"text": " Print"
},
{
"code": null,
"e": 5801,
"s": 5790,
"text": " Add Notes"
}
]
|
How to clear screen using python? | When we work with python interactive shell/terminal, we continuously get the output and the window looks very much clumsy, not to see any output clearly, most of the time we use ctrl+lto clear the screen.
But if we want to clear the screen while running a python script we have to do something for that because there’s no built-in keyword or function/method to clear the screen. So, we have to write some code for that.
So, we have to follow some steps
Step 1 − First we have to write from os import system.
Step 2 − Next Define a function.
Step 3 − Then make a system call with 'clear' in Linux and 'cls' in Windows as an argument.
Step 4 − Next we have to store the returned value in an underscore or whatever variable we want (an underscore is used because python shell always stores its last output in an underscore).
Step 6 − Lastly call the function.
from os import system, name
from time import sleep
# define our clear function
def screen_clear():
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# print out some text
print('Hi !! I am Python\n'*10)
sleep(2)
# now call function we defined above
screen_clear()
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
import os
from subprocess import call
from time import sleep
def screen_clear():
_ = call('clear' if os.name =='posix' else 'cls')
print('Hi !! I am Python\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call the function we defined above
screen_clear()
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "When we work with python interactive shell/terminal, we continuously get the output and the window looks very much clumsy, not to see any output clearly, most of the time we use ctrl+lto clear the screen."
},
{
"code": null,
"e": 1482,
"s": 1267,
"text": "But if we want to clear the screen while running a python script we have to do something for that because there’s no built-in keyword or function/method to clear the screen. So, we have to write some code for that."
},
{
"code": null,
"e": 1515,
"s": 1482,
"text": "So, we have to follow some steps"
},
{
"code": null,
"e": 1920,
"s": 1515,
"text": "Step 1 − First we have to write from os import system.\nStep 2 − Next Define a function.\nStep 3 − Then make a system call with 'clear' in Linux and 'cls' in Windows as an argument.\nStep 4 − Next we have to store the returned value in an underscore or whatever variable we want (an underscore is used because python shell always stores its last output in an underscore).\nStep 6 − Lastly call the function.\n"
},
{
"code": null,
"e": 2262,
"s": 1920,
"text": "from os import system, name\nfrom time import sleep\n# define our clear function\ndef screen_clear():\n if name == 'nt':\n _ = system('cls')\n # for mac and linux(here, os.name is 'posix')\n else:\n _ = system('clear')\n# print out some text\nprint('Hi !! I am Python\\n'*10)\nsleep(2)\n# now call function we defined above\nscreen_clear()"
},
{
"code": null,
"e": 2443,
"s": 2262,
"text": "Hi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\n"
},
{
"code": null,
"e": 2718,
"s": 2443,
"text": "import os\nfrom subprocess import call\nfrom time import sleep\ndef screen_clear():\n _ = call('clear' if os.name =='posix' else 'cls')\nprint('Hi !! I am Python\\n'*10)\n# sleep for 2 seconds after printing output\nsleep(2)\n# now call the function we defined above\nscreen_clear()"
},
{
"code": null,
"e": 2899,
"s": 2718,
"text": "Hi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\nHi !! I am Python\n"
}
]
|
Farthest distance of a 0 from the center of a 2-D matrix - GeeksforGeeks | 30 Apr, 2021
Given a matrix of odd order mat, the task is to find the farthest distance of a 0 from the center of the matrix. Distance between two elements at locations (i1, j1) and (i2, j2) of the matrix is calculated as |i1- i2| + |j1-j2|. If no 0 occurs in the matrix then print 0 as the result.Examples:
Input: mat[][] = {{2, 3, 0}, {0, 2, 0}, {0, 1, 1}} Output: 2Input: mat[][] = {{2, 3, 4, {0, 2, 0}, {6, 1, 1}} Output: 1
Approach: The center of any matrix with odd order is at index i = j = floor(n/2). Now for finding the farthest distance of any 0 from the center, calculate the distance of each 0 from the center of the matrix as |i-n/2| + |j-n/2| and update the maximum distance as result. Print the result in the end or if the matrix doesn’t contain any 0 then print 0.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the farthest distance// of a 0 from the center of the matrix#include <bits/stdc++.h>#define n 3using namespace std; // function to return farthest distance// of zero from center of the matrixint farthestDistance(int matrix[][n]){ int result = 0; // traverse the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) result = max(result , abs(i - n/2) + abs(j - n/2)); } } // return result return result;} // driver programint main(){ int matrix[n][n] = { { 1, 2, 3 } , { 0, 1, 1 } , { 0, 0, 0 } }; cout << farthestDistance(matrix); return 0;}
// Java program to find the farthest distance// of a 0 from the center of the matrix import java.io.*; class GFG { static int n = 3; // function to return farthest distance// of zero from center of the matrixstatic int farthestDistance(int matrix[][]){ int result = 0; // traverse the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) result = Math.max(result , Math.abs(i - n/2) + Math.abs(j - n/2)); } } // return result return result;} // driver program public static void main (String[] args) { int matrix[][] = { { 1, 2, 3 } , { 0, 1, 1 } , { 0, 0, 0 } }; System.out.print(farthestDistance(matrix)); }}// This code is contributed by anuj_67..
# Python3 program to find the farthest distance# of a 0 from the center of the matrix n = 3 # function to return farthest distance# of zero from center of the matrixdef farthestDistance(matrix): result = 0 # traverse the matrix for i in range (0, n): for j in range (0, n): if (matrix[i][j] == 0): result = max(result, abs(i - n // 2) + abs(j - n//2)) # return result return result # Driver Codematrix = [[1, 2, 3], [0, 1, 1], [0, 0, 0]] print(farthestDistance(matrix)) # This code is contributed by# Archana_kumari
// C# program to find the farthest distance// of a 0 from the center of the matrixusing System; class GFG{ static int n = 3; // function to return farthest distance// of zero from center of the matrixstatic int farthestDistance(int [,]matrix){ int result = 0; // traverse the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i,j] == 0) result = Math.Max(result , Math.Abs(i - n / 2) + Math.Abs(j - n / 2)); } } // return result return result;} // Driver Codestatic public void Main (){ int [,]matrix = {{ 1, 2, 3 }, { 0, 1, 1 }, { 0, 0, 0 }}; Console.WriteLine(farthestDistance(matrix));}} // This code is contributed by Sachin
<?php// PHP program to find the farthest distance// of a 0 from the center of the matrix$n = 3; // function to return farthest distance// of zero from center of the matrixfunction farthestDistance($matrix){ global $n; $result = 0; // traverse the matrix for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if (($matrix[$i][$j] == 0) > 0) $result = max($result, abs($i - $n / 2) + abs($j - $n / 2)); } } // return result return $result;} // Driver Code$matrix = array(array( 1, 2, 3 ), array( 0, 1, 1 ), array( 0, 0, 0 )); echo farthestDistance($matrix); // This code is contributed by Sach_code?>
<script> // Javascript program to find the farthest distance// of a 0 from the center of the matrixvar n = 3; // function to return farthest distance// of zero from center of the matrixfunction farthestDistance(matrix){ var result = 0; // traverse the matrix for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if (matrix[i][j] == 0) result = Math.max(result , Math.abs(i - n/2) + Math.abs(j - n/2)); } } // return result return result;} // driver programvar matrix = [ [ 1, 2, 3 ] , [ 0, 1, 1 ] , [ 0, 0, 0 ] ];document.write( farthestDistance(matrix)); </script>
2
vt_m
Sach_Code
archana_kumari
itsok
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flood fill Algorithm - how to implement fill() in paint?
Program to find the Sum of each Row and each Column of a Matrix
Multiplication of Matrix using threads
Mathematics | L U Decomposition of a System of Linear Equations
Python program to add two Matrices
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24816,
"s": 24788,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25113,
"s": 24816,
"text": "Given a matrix of odd order mat, the task is to find the farthest distance of a 0 from the center of the matrix. Distance between two elements at locations (i1, j1) and (i2, j2) of the matrix is calculated as |i1- i2| + |j1-j2|. If no 0 occurs in the matrix then print 0 as the result.Examples: "
},
{
"code": null,
"e": 25235,
"s": 25113,
"text": "Input: mat[][] = {{2, 3, 0}, {0, 2, 0}, {0, 1, 1}} Output: 2Input: mat[][] = {{2, 3, 4, {0, 2, 0}, {6, 1, 1}} Output: 1 "
},
{
"code": null,
"e": 25643,
"s": 25237,
"text": "Approach: The center of any matrix with odd order is at index i = j = floor(n/2). Now for finding the farthest distance of any 0 from the center, calculate the distance of each 0 from the center of the matrix as |i-n/2| + |j-n/2| and update the maximum distance as result. Print the result in the end or if the matrix doesn’t contain any 0 then print 0.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25647,
"s": 25643,
"text": "C++"
},
{
"code": null,
"e": 25652,
"s": 25647,
"text": "Java"
},
{
"code": null,
"e": 25660,
"s": 25652,
"text": "Python3"
},
{
"code": null,
"e": 25663,
"s": 25660,
"text": "C#"
},
{
"code": null,
"e": 25667,
"s": 25663,
"text": "PHP"
},
{
"code": null,
"e": 25678,
"s": 25667,
"text": "Javascript"
},
{
"code": "// C++ program to find the farthest distance// of a 0 from the center of the matrix#include <bits/stdc++.h>#define n 3using namespace std; // function to return farthest distance// of zero from center of the matrixint farthestDistance(int matrix[][n]){ int result = 0; // traverse the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) result = max(result , abs(i - n/2) + abs(j - n/2)); } } // return result return result;} // driver programint main(){ int matrix[n][n] = { { 1, 2, 3 } , { 0, 1, 1 } , { 0, 0, 0 } }; cout << farthestDistance(matrix); return 0;}",
"e": 26421,
"s": 25678,
"text": null
},
{
"code": "// Java program to find the farthest distance// of a 0 from the center of the matrix import java.io.*; class GFG { static int n = 3; // function to return farthest distance// of zero from center of the matrixstatic int farthestDistance(int matrix[][]){ int result = 0; // traverse the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) result = Math.max(result , Math.abs(i - n/2) + Math.abs(j - n/2)); } } // return result return result;} // driver program public static void main (String[] args) { int matrix[][] = { { 1, 2, 3 } , { 0, 1, 1 } , { 0, 0, 0 } }; System.out.print(farthestDistance(matrix)); }}// This code is contributed by anuj_67..",
"e": 27259,
"s": 26421,
"text": null
},
{
"code": "# Python3 program to find the farthest distance# of a 0 from the center of the matrix n = 3 # function to return farthest distance# of zero from center of the matrixdef farthestDistance(matrix): result = 0 # traverse the matrix for i in range (0, n): for j in range (0, n): if (matrix[i][j] == 0): result = max(result, abs(i - n // 2) + abs(j - n//2)) # return result return result # Driver Codematrix = [[1, 2, 3], [0, 1, 1], [0, 0, 0]] print(farthestDistance(matrix)) # This code is contributed by# Archana_kumari",
"e": 27887,
"s": 27259,
"text": null
},
{
"code": "// C# program to find the farthest distance// of a 0 from the center of the matrixusing System; class GFG{ static int n = 3; // function to return farthest distance// of zero from center of the matrixstatic int farthestDistance(int [,]matrix){ int result = 0; // traverse the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matrix[i,j] == 0) result = Math.Max(result , Math.Abs(i - n / 2) + Math.Abs(j - n / 2)); } } // return result return result;} // Driver Codestatic public void Main (){ int [,]matrix = {{ 1, 2, 3 }, { 0, 1, 1 }, { 0, 0, 0 }}; Console.WriteLine(farthestDistance(matrix));}} // This code is contributed by Sachin",
"e": 28714,
"s": 27887,
"text": null
},
{
"code": "<?php// PHP program to find the farthest distance// of a 0 from the center of the matrix$n = 3; // function to return farthest distance// of zero from center of the matrixfunction farthestDistance($matrix){ global $n; $result = 0; // traverse the matrix for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if (($matrix[$i][$j] == 0) > 0) $result = max($result, abs($i - $n / 2) + abs($j - $n / 2)); } } // return result return $result;} // Driver Code$matrix = array(array( 1, 2, 3 ), array( 0, 1, 1 ), array( 0, 0, 0 )); echo farthestDistance($matrix); // This code is contributed by Sach_code?>",
"e": 29480,
"s": 28714,
"text": null
},
{
"code": "<script> // Javascript program to find the farthest distance// of a 0 from the center of the matrixvar n = 3; // function to return farthest distance// of zero from center of the matrixfunction farthestDistance(matrix){ var result = 0; // traverse the matrix for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if (matrix[i][j] == 0) result = Math.max(result , Math.abs(i - n/2) + Math.abs(j - n/2)); } } // return result return result;} // driver programvar matrix = [ [ 1, 2, 3 ] , [ 0, 1, 1 ] , [ 0, 0, 0 ] ];document.write( farthestDistance(matrix)); </script>",
"e": 30176,
"s": 29480,
"text": null
},
{
"code": null,
"e": 30178,
"s": 30176,
"text": "2"
},
{
"code": null,
"e": 30185,
"s": 30180,
"text": "vt_m"
},
{
"code": null,
"e": 30195,
"s": 30185,
"text": "Sach_Code"
},
{
"code": null,
"e": 30210,
"s": 30195,
"text": "archana_kumari"
},
{
"code": null,
"e": 30216,
"s": 30210,
"text": "itsok"
},
{
"code": null,
"e": 30223,
"s": 30216,
"text": "Matrix"
},
{
"code": null,
"e": 30242,
"s": 30223,
"text": "School Programming"
},
{
"code": null,
"e": 30249,
"s": 30242,
"text": "Matrix"
},
{
"code": null,
"e": 30347,
"s": 30249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30356,
"s": 30347,
"text": "Comments"
},
{
"code": null,
"e": 30369,
"s": 30356,
"text": "Old Comments"
},
{
"code": null,
"e": 30426,
"s": 30369,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 30490,
"s": 30426,
"text": "Program to find the Sum of each Row and each Column of a Matrix"
},
{
"code": null,
"e": 30529,
"s": 30490,
"text": "Multiplication of Matrix using threads"
},
{
"code": null,
"e": 30593,
"s": 30529,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 30628,
"s": 30593,
"text": "Python program to add two Matrices"
},
{
"code": null,
"e": 30646,
"s": 30628,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30662,
"s": 30646,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30681,
"s": 30662,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30706,
"s": 30681,
"text": "Reverse a string in Java"
}
]
|
Use cases of mouse programming in C/C++ - GeeksforGeeks | 28 Nov, 2021
In this article, we will discuss some use cases of Mouse Programming:
For displaying the Mouse Pointer, first enable the graphic mode using initgraph() function, if it is successfully initialized than it calls initMouse() function to check mouse is available or not, If initMouse() function returns not equal 0 means it will return ffffh then it calls the showMouse() function and display the cursor on the console window in graphic mode. Below are the functions used:
initMouse(): use to initialized mouse.
showMouse(): shows the mouse pointer on the output screen.
Below is the program for the same:
C
C++
// C program to display Mouse// pointer in Graphics Mode#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to display the mouse// pointervoid showMouse(){ // Set service AX = 1 for // displaying mouse in.x.ax = 1; int86(0X33, &in, &out);} // Function to initialize the mouse// pointerint initMouse(){ // Set service AX = 0 for // detecting mouse in.x.ax = 0; int86(0x33, &in, &out); return out.x.ax;} // Driver Codevoid main(){ int status, gd = DETECT, gm; clrscr(); initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Get the status of mouse pointer status = initMouse(); // Check mouse is available or not if (status == 0) printf("Mouse support not" " available.\n"); else { printf("Display mouse"); showMouse(); } getch(); // Close the graphics closegraph();}
// C++ program to display Mouse// pointer in Graphics Mode#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>using namespace std;union REGS in, out; // Function to display the mouse// pointervoid showMouse(){ // Set service AX = 1 for // displaying mouse in.x.ax = 1; int86(0X33, &in, &out);} // Function to initialize the mouse// pointerint initMouse(){ // Set service AX = 0 for // detecting mouse in.x.ax = 0; int86(0x33, &in, &out); return out.x.ax;} // Driver Codevoid main(){ int status, gd = DETECT, gm; clrscr(); initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Get the status of mouse pointer status = initMouse(); // Check if mouse is available or not if (status == 0) cout << "Mouse support not" << " available.\n"; else { cout << "Display mouse"; showMouse(); } getch(); // Close the graphics closegraph();}
Output:
For hiding the mouse pointer, first check the status of mouse if it is available than simply control will enter in for loop make delay of 500 millisecond then the mouse will appear, then disappear after 500 milliseconds and will show again after 500 millisecond. This sequence will continue until the loop ends. The delay function has been used to show you the impact of hidemouse() function .
initmouse(): use to initialized mouse.
showmouse(): shows the mouse pointer on the output screen.
hidemouse(): hides the mouse pointer
Below is the program for the same:
C
C++
// C program for hiding Mouse Pointer#include <conio.h>#include <dos.h>#include <graphics.h> union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to hide the mouse// pointer using graphicsvoid hideMouse(){ // Set AX=2 to hide mouse in.x.ax = 2; int86(0X33, &in, &out);} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) printf("Mouse support " "not available.\n"); else { for (i = 0; i <= 10; i++) { // Pause execution for .5 sec delay(500); showMouse(); delay(500); hideMouse(); } } getch(); // Close the graphics closegraph();}
// C++ program for hiding Mouse Pointer#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>using namespace std; union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to hide the mouse// pointer using graphicsvoid hideMouse(){ // Set AX=2 to hide mouse in.x.ax = 2; int86(0X33, &in, &out);} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) cout << "Mouse support " << "not available.\n"; else { for (i = 0; i <= 10; i++) { // Pause execution for .5 sec delay(500); showMouse(); delay(500); hideMouse(); } } getch(); // Close the graphics closegraph();}
Output:
In this program, the current location of the mouse is printed as well as which key of the mouse is being clicked at which location using the below functions:
initmouse(): use to initialized mouse.
showmouse(): shows the mouse cursor on the output screen.
getmouseposition(): fetches the mouse coordinate & which key is being pressed in BX, CX, DX register respectively.If BX = 1 left key clickedIf BX = 2 Right key clicked.If BX = 3 Center Button is PressedCX = Mouse X CoordinateDX = Mouse Y Coordinate
If BX = 1 left key clicked
If BX = 2 Right key clicked.
If BX = 3 Center Button is Pressed
CX = Mouse X Coordinate
DX = Mouse Y Coordinate
Below is the program for the same:
C
C++
// C program to determine the current// mouse position and button clicked#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to get the current clicked// mouse position on the screenvoid getMousePosition(int* click, int* x, int* y){ in.x.ax = 3; int86(0X33, &in, &out); // Get the coordinates *click = out.x.bx; // Update the x and y coordinates *x = out.x.cx; *y = out.x.dx;} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) printf("Mouse support " "not available.\n"); else { showMouse(); // Get the current mouse position getMousePosition(&click, &x, &y); while (!kbhit()) { getMousePosition(&click, &x, &y); gotoxy(1, 1); printf("X = %d, Y = %d", x, y); if (click == 1) printf("\nLeft click at " "position = %d, %d\t", x, y); if (click == 2) printf("\nRight click at " "position = %d, %d\t", x, y); } } getch(); // Close the graphics closegraph();}
// C program to determine the current// mouse position and button clicked#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>using namespace std;union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to get the current clicked// mouse position on the screenvoid getMousePosition(int* click, int* x, int* y){ in.x.ax = 3; int86(0X33, &in, &out); // Get the coordinates *click = out.x.bx; // Update the x and y coordinates *x = out.x.cx; *y = out.x.dx;} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) printf("Mouse support " "not available.\n"); else { showMouse(); // Get the current mouse position getMousePosition(&click, &x, &y); while (!kbhit()) { getMousePosition(&click, &x, &y); gotoxy(1, 1); printf("X = %d, Y = %d", x, y); if (click == 1) cout << "\nLeft click at " << "position = " << x << ", " << y; if (click == 2) cout << "\nRight click at " << "position = " << x << ", " << y; } } getch(); // Close the graphics closegraph();}
Output:
surindertarika1234
C-programming
Articles
C Language
C Programs
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Min Heap and Max Heap
SQL | Date functions
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++ | [
{
"code": null,
"e": 24031,
"s": 24003,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 24101,
"s": 24031,
"text": "In this article, we will discuss some use cases of Mouse Programming:"
},
{
"code": null,
"e": 24501,
"s": 24101,
"text": "For displaying the Mouse Pointer, first enable the graphic mode using initgraph() function, if it is successfully initialized than it calls initMouse() function to check mouse is available or not, If initMouse() function returns not equal 0 means it will return ffffh then it calls the showMouse() function and display the cursor on the console window in graphic mode. Below are the functions used: "
},
{
"code": null,
"e": 24540,
"s": 24501,
"text": "initMouse(): use to initialized mouse."
},
{
"code": null,
"e": 24599,
"s": 24540,
"text": "showMouse(): shows the mouse pointer on the output screen."
},
{
"code": null,
"e": 24634,
"s": 24599,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 24636,
"s": 24634,
"text": "C"
},
{
"code": null,
"e": 24640,
"s": 24636,
"text": "C++"
},
{
"code": "// C program to display Mouse// pointer in Graphics Mode#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to display the mouse// pointervoid showMouse(){ // Set service AX = 1 for // displaying mouse in.x.ax = 1; int86(0X33, &in, &out);} // Function to initialize the mouse// pointerint initMouse(){ // Set service AX = 0 for // detecting mouse in.x.ax = 0; int86(0x33, &in, &out); return out.x.ax;} // Driver Codevoid main(){ int status, gd = DETECT, gm; clrscr(); initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Get the status of mouse pointer status = initMouse(); // Check mouse is available or not if (status == 0) printf(\"Mouse support not\" \" available.\\n\"); else { printf(\"Display mouse\"); showMouse(); } getch(); // Close the graphics closegraph();}",
"e": 25573,
"s": 24640,
"text": null
},
{
"code": "// C++ program to display Mouse// pointer in Graphics Mode#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>using namespace std;union REGS in, out; // Function to display the mouse// pointervoid showMouse(){ // Set service AX = 1 for // displaying mouse in.x.ax = 1; int86(0X33, &in, &out);} // Function to initialize the mouse// pointerint initMouse(){ // Set service AX = 0 for // detecting mouse in.x.ax = 0; int86(0x33, &in, &out); return out.x.ax;} // Driver Codevoid main(){ int status, gd = DETECT, gm; clrscr(); initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Get the status of mouse pointer status = initMouse(); // Check if mouse is available or not if (status == 0) cout << \"Mouse support not\" << \" available.\\n\"; else { cout << \"Display mouse\"; showMouse(); } getch(); // Close the graphics closegraph();}",
"e": 26545,
"s": 25573,
"text": null
},
{
"code": null,
"e": 26557,
"s": 26549,
"text": "Output:"
},
{
"code": null,
"e": 26960,
"s": 26563,
"text": "For hiding the mouse pointer, first check the status of mouse if it is available than simply control will enter in for loop make delay of 500 millisecond then the mouse will appear, then disappear after 500 milliseconds and will show again after 500 millisecond. This sequence will continue until the loop ends. The delay function has been used to show you the impact of hidemouse() function . "
},
{
"code": null,
"e": 27001,
"s": 26962,
"text": "initmouse(): use to initialized mouse."
},
{
"code": null,
"e": 27060,
"s": 27001,
"text": "showmouse(): shows the mouse pointer on the output screen."
},
{
"code": null,
"e": 27097,
"s": 27060,
"text": "hidemouse(): hides the mouse pointer"
},
{
"code": null,
"e": 27134,
"s": 27099,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 27138,
"s": 27136,
"text": "C"
},
{
"code": null,
"e": 27142,
"s": 27138,
"text": "C++"
},
{
"code": "// C program for hiding Mouse Pointer#include <conio.h>#include <dos.h>#include <graphics.h> union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to hide the mouse// pointer using graphicsvoid hideMouse(){ // Set AX=2 to hide mouse in.x.ax = 2; int86(0X33, &in, &out);} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) printf(\"Mouse support \" \"not available.\\n\"); else { for (i = 0; i <= 10; i++) { // Pause execution for .5 sec delay(500); showMouse(); delay(500); hideMouse(); } } getch(); // Close the graphics closegraph();}",
"e": 28246,
"s": 27142,
"text": null
},
{
"code": "// C++ program for hiding Mouse Pointer#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>using namespace std; union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to hide the mouse// pointer using graphicsvoid hideMouse(){ // Set AX=2 to hide mouse in.x.ax = 2; int86(0X33, &in, &out);} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) cout << \"Mouse support \" << \"not available.\\n\"; else { for (i = 0; i <= 10; i++) { // Pause execution for .5 sec delay(500); showMouse(); delay(500); hideMouse(); } } getch(); // Close the graphics closegraph();}",
"e": 29397,
"s": 28246,
"text": null
},
{
"code": null,
"e": 29409,
"s": 29401,
"text": "Output:"
},
{
"code": null,
"e": 29569,
"s": 29411,
"text": "In this program, the current location of the mouse is printed as well as which key of the mouse is being clicked at which location using the below functions:"
},
{
"code": null,
"e": 29610,
"s": 29571,
"text": "initmouse(): use to initialized mouse."
},
{
"code": null,
"e": 29668,
"s": 29610,
"text": "showmouse(): shows the mouse cursor on the output screen."
},
{
"code": null,
"e": 29917,
"s": 29668,
"text": "getmouseposition(): fetches the mouse coordinate & which key is being pressed in BX, CX, DX register respectively.If BX = 1 left key clickedIf BX = 2 Right key clicked.If BX = 3 Center Button is PressedCX = Mouse X CoordinateDX = Mouse Y Coordinate"
},
{
"code": null,
"e": 29944,
"s": 29917,
"text": "If BX = 1 left key clicked"
},
{
"code": null,
"e": 29973,
"s": 29944,
"text": "If BX = 2 Right key clicked."
},
{
"code": null,
"e": 30008,
"s": 29973,
"text": "If BX = 3 Center Button is Pressed"
},
{
"code": null,
"e": 30032,
"s": 30008,
"text": "CX = Mouse X Coordinate"
},
{
"code": null,
"e": 30056,
"s": 30032,
"text": "DX = Mouse Y Coordinate"
},
{
"code": null,
"e": 30093,
"s": 30058,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 30097,
"s": 30095,
"text": "C"
},
{
"code": null,
"e": 30101,
"s": 30097,
"text": "C++"
},
{
"code": "// C program to determine the current// mouse position and button clicked#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to get the current clicked// mouse position on the screenvoid getMousePosition(int* click, int* x, int* y){ in.x.ax = 3; int86(0X33, &in, &out); // Get the coordinates *click = out.x.bx; // Update the x and y coordinates *x = out.x.cx; *y = out.x.dx;} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) printf(\"Mouse support \" \"not available.\\n\"); else { showMouse(); // Get the current mouse position getMousePosition(&click, &x, &y); while (!kbhit()) { getMousePosition(&click, &x, &y); gotoxy(1, 1); printf(\"X = %d, Y = %d\", x, y); if (click == 1) printf(\"\\nLeft click at \" \"position = %d, %d\\t\", x, y); if (click == 2) printf(\"\\nRight click at \" \"position = %d, %d\\t\", x, y); } } getch(); // Close the graphics closegraph();}",
"e": 31786,
"s": 30101,
"text": null
},
{
"code": "// C program to determine the current// mouse position and button clicked#include <bits/stdc++.h>#include <conio.h>#include <dos.h>#include <graphics.h>#include <stdio.h>using namespace std;union REGS in, out; // Function to initialize the mouse// pointer using graphicsint initMouse(){ in.x.ax = 0; int86(0X33, &in, &out); return out.x.ax;} // Function to display the mouse// pointer using graphicsvoid showMouse(){ in.x.ax = 1; int86(0X33, &in, &out);} // Function to get the current clicked// mouse position on the screenvoid getMousePosition(int* click, int* x, int* y){ in.x.ax = 3; int86(0X33, &in, &out); // Get the coordinates *click = out.x.bx; // Update the x and y coordinates *x = out.x.cx; *y = out.x.dx;} // Driver Codevoid main(){ int status, i, gd = DETECT, gm; // Initialize graphics initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Get the status of the mouse status = initMouse(); // Check if mouse is available or not if (status == 0) printf(\"Mouse support \" \"not available.\\n\"); else { showMouse(); // Get the current mouse position getMousePosition(&click, &x, &y); while (!kbhit()) { getMousePosition(&click, &x, &y); gotoxy(1, 1); printf(\"X = %d, Y = %d\", x, y); if (click == 1) cout << \"\\nLeft click at \" << \"position = \" << x << \", \" << y; if (click == 2) cout << \"\\nRight click at \" << \"position = \" << x << \", \" << y; } } getch(); // Close the graphics closegraph();}",
"e": 33523,
"s": 31786,
"text": null
},
{
"code": null,
"e": 33535,
"s": 33527,
"text": "Output:"
},
{
"code": null,
"e": 33558,
"s": 33539,
"text": "surindertarika1234"
},
{
"code": null,
"e": 33572,
"s": 33558,
"text": "C-programming"
},
{
"code": null,
"e": 33581,
"s": 33572,
"text": "Articles"
},
{
"code": null,
"e": 33592,
"s": 33581,
"text": "C Language"
},
{
"code": null,
"e": 33603,
"s": 33592,
"text": "C Programs"
},
{
"code": null,
"e": 33607,
"s": 33603,
"text": "C++"
},
{
"code": null,
"e": 33620,
"s": 33607,
"text": "C++ Programs"
},
{
"code": null,
"e": 33624,
"s": 33620,
"text": "CPP"
},
{
"code": null,
"e": 33722,
"s": 33624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33731,
"s": 33722,
"text": "Comments"
},
{
"code": null,
"e": 33744,
"s": 33731,
"text": "Old Comments"
},
{
"code": null,
"e": 33781,
"s": 33744,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 33807,
"s": 33781,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 33854,
"s": 33807,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 33895,
"s": 33854,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 33916,
"s": 33895,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 33994,
"s": 33916,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 34010,
"s": 33994,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34033,
"s": 34010,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 34060,
"s": 34033,
"text": "Bitwise Operators in C/C++"
}
]
|
How to declare nullable type in TypeScript ? - GeeksforGeeks | 29 Jun, 2020
In vanilla JavaScript, there are two primary data types, null and undefined. Previously in TypeScript, it was not possible to explicitly name these types as “null” and “undefined”. However, it can now be used regardless of the type checking mode.
To assign “undefined” to any property, the –strictNullChecks flag has to be turned off. Keeping this flag on won’t allow to assign “undefined” to members that has no nullable operator.
The below example represents what happens if the –strictNullChecks flag is enabled and the following code is executed.
interface Student { name:string; age:number;} let s: Student = { name:'Ajay', age:null}
It will throw the below error:
Type 'null' is not assignable to type 'number'
This error won’t appear if we have –strictNullChecks flag turned off. The strictNullChecks flag protects from referencing nulls or undefined values in the code. It can be enabled by adding the -–strictNullChecks flag as an option to the command-line compiler or adding it to the tsconfig.json file.
There is a difference between the Nullable type and “optional”. In “optional”, we provide some default value to the member or let it not be considered as a member. However if any member is assigned optional and then still assigned a value as “null” or “undefined”, then it will throw an error.
interface Student { name:string; age?:number;} let s: Student = { name:'Ajay', age:null}
JavaScript-Misc
Picked
TypeScript
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24001,
"s": 23973,
"text": "\n29 Jun, 2020"
},
{
"code": null,
"e": 24248,
"s": 24001,
"text": "In vanilla JavaScript, there are two primary data types, null and undefined. Previously in TypeScript, it was not possible to explicitly name these types as “null” and “undefined”. However, it can now be used regardless of the type checking mode."
},
{
"code": null,
"e": 24434,
"s": 24248,
"text": "To assign “undefined” to any property, the –strictNullChecks flag has to be turned off. Keeping this flag on won’t allow to assign “undefined” to members that has no nullable operator. "
},
{
"code": null,
"e": 24554,
"s": 24434,
"text": "The below example represents what happens if the –strictNullChecks flag is enabled and the following code is executed. "
},
{
"code": "interface Student { name:string; age:number;} let s: Student = { name:'Ajay', age:null}",
"e": 24643,
"s": 24554,
"text": null
},
{
"code": null,
"e": 24674,
"s": 24643,
"text": "It will throw the below error:"
},
{
"code": null,
"e": 24722,
"s": 24674,
"text": "Type 'null' is not assignable to type 'number'\n"
},
{
"code": null,
"e": 25022,
"s": 24722,
"text": "This error won’t appear if we have –strictNullChecks flag turned off. The strictNullChecks flag protects from referencing nulls or undefined values in the code. It can be enabled by adding the -–strictNullChecks flag as an option to the command-line compiler or adding it to the tsconfig.json file. "
},
{
"code": null,
"e": 25316,
"s": 25022,
"text": "There is a difference between the Nullable type and “optional”. In “optional”, we provide some default value to the member or let it not be considered as a member. However if any member is assigned optional and then still assigned a value as “null” or “undefined”, then it will throw an error."
},
{
"code": "interface Student { name:string; age?:number;} let s: Student = { name:'Ajay', age:null}",
"e": 25406,
"s": 25316,
"text": null
},
{
"code": null,
"e": 25422,
"s": 25406,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 25429,
"s": 25422,
"text": "Picked"
},
{
"code": null,
"e": 25440,
"s": 25429,
"text": "TypeScript"
},
{
"code": null,
"e": 25451,
"s": 25440,
"text": "JavaScript"
},
{
"code": null,
"e": 25468,
"s": 25451,
"text": "Web Technologies"
},
{
"code": null,
"e": 25495,
"s": 25468,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25593,
"s": 25495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25602,
"s": 25593,
"text": "Comments"
},
{
"code": null,
"e": 25615,
"s": 25602,
"text": "Old Comments"
},
{
"code": null,
"e": 25676,
"s": 25615,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 25721,
"s": 25676,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25793,
"s": 25721,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 25845,
"s": 25793,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 25891,
"s": 25845,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 25947,
"s": 25891,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 25980,
"s": 25947,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26042,
"s": 25980,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26085,
"s": 26042,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Currying Function in Python | 07 Feb, 2019
In problem solving and functional programming, currying is the practice of simplifying the execution of a function that takes multiple arguments into executing sequential single-argument functions. In simple terms, Currying is used to transform multiple-argument function into single argument function by evaluating incremental nesting of function arguments. Currying also mends one argument to another forms a relative pattern while execution.
Mathematical Illustration of Currying:In general currying of functions takes up any number of calculations and data to single real function that returns an expected output. Here we take,
f(x, y) = (x*x*x) + (y*y*y)
h(x) = (x*x*x)
h(y) = (y*y*y)
h(x)(y) = h(x)+h(y)
f(x, y) = h(x)(y)
Curry f = h(x)(y)
For example, we will take chaining the composition of function.
a(x) = b(c(d(x)))
def change(b, c, d): def a(x): return b(c(d(x))) return a
v(a, b, c, d, e) = w(x(y(z(a, b, c, d, e))))
# Currying in Python - Many to Single Argument def change(a): def w(b): def x(c): def y(d): def z(e): print(a, b, c, d, e) return z return y return x return w change(10)(20)(30)(40)(50)
Output:
10 20 30 40 50
Here, the concept is nesting of one function to another function and hence the result of one function gets recorded in the chain of functions. There by simplifying one huge block of manipulation to simpler sequential blocks.
Code #1: Change kilometer to meter and meter to centimeter.
# Demonstrate Currying of composition of functiondef change(b, c, d): def a(x): return b(c(d(x))) return a def kilometer2meter(dist): """ Function that converts km to m. """ return dist * 1000 def meter2centimeter(dist): """ Function that converts m to cm. """ return dist * 100 def centimeter2feet(dist): """ Function that converts cm to ft. """ return dist / 30.48 if __name__ == '__main__': transform = change(centimeter2feet, meter2centimeter, kilometer2meter ) e = transform(565) print(e)
Output:
1853674.5406824148
Code #2:
# Demonstrate Currying of composition of function def change(b, c, d): def a(x): return b(c(d(x))) return a def daystohour(time): """ Function that converts days to hours. """ return time * 24 def hourstominutes(time): """ Function that converts hours to minutes. """ return time * 60 def minutestoseconds(time): """ Function that converts minutes to seconds. """ return time * 60 if __name__ == '__main__': transform = change(minutestoseconds, hourstominutes, daystohour) e = transform(10) print(e)
Output:
864000
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Feb, 2019"
},
{
"code": null,
"e": 497,
"s": 52,
"text": "In problem solving and functional programming, currying is the practice of simplifying the execution of a function that takes multiple arguments into executing sequential single-argument functions. In simple terms, Currying is used to transform multiple-argument function into single argument function by evaluating incremental nesting of function arguments. Currying also mends one argument to another forms a relative pattern while execution."
},
{
"code": null,
"e": 684,
"s": 497,
"text": "Mathematical Illustration of Currying:In general currying of functions takes up any number of calculations and data to single real function that returns an expected output. Here we take,"
},
{
"code": null,
"e": 798,
"s": 684,
"text": "f(x, y) = (x*x*x) + (y*y*y)\nh(x) = (x*x*x)\nh(y) = (y*y*y)\nh(x)(y) = h(x)+h(y)\nf(x, y) = h(x)(y)\nCurry f = h(x)(y)"
},
{
"code": null,
"e": 862,
"s": 798,
"text": "For example, we will take chaining the composition of function."
},
{
"code": null,
"e": 880,
"s": 862,
"text": "a(x) = b(c(d(x)))"
},
{
"code": "def change(b, c, d): def a(x): return b(c(d(x))) return a",
"e": 951,
"s": 880,
"text": null
},
{
"code": null,
"e": 996,
"s": 951,
"text": "v(a, b, c, d, e) = w(x(y(z(a, b, c, d, e))))"
},
{
"code": "# Currying in Python - Many to Single Argument def change(a): def w(b): def x(c): def y(d): def z(e): print(a, b, c, d, e) return z return y return x return w change(10)(20)(30)(40)(50)",
"e": 1275,
"s": 996,
"text": null
},
{
"code": null,
"e": 1283,
"s": 1275,
"text": "Output:"
},
{
"code": null,
"e": 1298,
"s": 1283,
"text": "10 20 30 40 50"
},
{
"code": null,
"e": 1523,
"s": 1298,
"text": "Here, the concept is nesting of one function to another function and hence the result of one function gets recorded in the chain of functions. There by simplifying one huge block of manipulation to simpler sequential blocks."
},
{
"code": null,
"e": 1583,
"s": 1523,
"text": "Code #1: Change kilometer to meter and meter to centimeter."
},
{
"code": "# Demonstrate Currying of composition of functiondef change(b, c, d): def a(x): return b(c(d(x))) return a def kilometer2meter(dist): \"\"\" Function that converts km to m. \"\"\" return dist * 1000 def meter2centimeter(dist): \"\"\" Function that converts m to cm. \"\"\" return dist * 100 def centimeter2feet(dist): \"\"\" Function that converts cm to ft. \"\"\" return dist / 30.48 if __name__ == '__main__': transform = change(centimeter2feet, meter2centimeter, kilometer2meter ) e = transform(565) print(e) ",
"e": 2144,
"s": 1583,
"text": null
},
{
"code": null,
"e": 2152,
"s": 2144,
"text": "Output:"
},
{
"code": null,
"e": 2171,
"s": 2152,
"text": "1853674.5406824148"
},
{
"code": null,
"e": 2181,
"s": 2171,
"text": " Code #2:"
},
{
"code": "# Demonstrate Currying of composition of function def change(b, c, d): def a(x): return b(c(d(x))) return a def daystohour(time): \"\"\" Function that converts days to hours. \"\"\" return time * 24 def hourstominutes(time): \"\"\" Function that converts hours to minutes. \"\"\" return time * 60 def minutestoseconds(time): \"\"\" Function that converts minutes to seconds. \"\"\" return time * 60 if __name__ == '__main__': transform = change(minutestoseconds, hourstominutes, daystohour) e = transform(10) print(e) ",
"e": 2749,
"s": 2181,
"text": null
},
{
"code": null,
"e": 2757,
"s": 2749,
"text": "Output:"
},
{
"code": null,
"e": 2764,
"s": 2757,
"text": "864000"
},
{
"code": null,
"e": 2781,
"s": 2764,
"text": "Python-Functions"
},
{
"code": null,
"e": 2788,
"s": 2781,
"text": "Python"
},
{
"code": null,
"e": 2886,
"s": 2788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2904,
"s": 2886,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2946,
"s": 2904,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2968,
"s": 2946,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3003,
"s": 2968,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3029,
"s": 3003,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3061,
"s": 3029,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3090,
"s": 3061,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3117,
"s": 3090,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3147,
"s": 3117,
"text": "Iterate over a list in Python"
}
]
|
How to Update Multiple Columns in Single Update Statement in SQL? | 28 Oct, 2021
In this article, we will see, how to update multiple columns in a single statement in SQL. We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required.
UPDATE for multiple columns
Syntax:
UPDATE table_name
SET column_name1= value1, column_name2= value2
WHERE condition;
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have the following demo_table in our geek’s database.
Query:
CREATE TABLE demo_table(
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );
Step 4: Insert data into a table
Query:
INSERT INTO demo_table VALUES
('ROMY KUMARI', 22, 'NEW DELHI'),
('PUSHKAR JHA',23, 'NEW DELHI'),
('AKANKSHA GUPTA',22, 'PUNJAB'),
('SUJATA JHA', 30,'PATNA'),
('PREETI GIRI', 26,'BANGLORE'),
('PREM GUPTA',31,'PUNE'),
('RAM KAPOOR', 34,'PUNE'),
('SHEETAL AWASTHI',32, 'RAJASTHAN');
Step 5: View data of the table
Query:
SELECT * FROM demo_table;
Output:
Step 6: Update multiple columns
For the purpose of demonstration let’s update AGE value to be 30 and CITY value to be PUNJAB where CITY value is ‘NEW DELHI’.
Query:
UPDATE demo_table
SET AGE=30, CITY='PUNJAB'
WHERE CITY='NEW DELHI';
Output:
view content of table demo_table
We can see that the table is updated now with the desired value.
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 366,
"s": 52,
"text": "In this article, we will see, how to update multiple columns in a single statement in SQL. We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required."
},
{
"code": null,
"e": 394,
"s": 366,
"text": "UPDATE for multiple columns"
},
{
"code": null,
"e": 402,
"s": 394,
"text": "Syntax:"
},
{
"code": null,
"e": 484,
"s": 402,
"text": "UPDATE table_name\nSET column_name1= value1, column_name2= value2\nWHERE condition;"
},
{
"code": null,
"e": 535,
"s": 484,
"text": "Now, for the demonstration follow the below steps:"
},
{
"code": null,
"e": 561,
"s": 535,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 629,
"s": 561,
"text": "we can use the following command to create a database called geeks."
},
{
"code": null,
"e": 636,
"s": 629,
"text": "Query:"
},
{
"code": null,
"e": 659,
"s": 636,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 680,
"s": 659,
"text": "Step 2: Use database"
},
{
"code": null,
"e": 749,
"s": 680,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 756,
"s": 749,
"text": "Query:"
},
{
"code": null,
"e": 767,
"s": 756,
"text": "USE geeks;"
},
{
"code": null,
"e": 792,
"s": 767,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 849,
"s": 792,
"text": "We have the following demo_table in our geek’s database."
},
{
"code": null,
"e": 856,
"s": 849,
"text": "Query:"
},
{
"code": null,
"e": 928,
"s": 856,
"text": "CREATE TABLE demo_table(\nNAME VARCHAR(20),\nAGE INT,\nCITY VARCHAR(20) );"
},
{
"code": null,
"e": 961,
"s": 928,
"text": "Step 4: Insert data into a table"
},
{
"code": null,
"e": 968,
"s": 961,
"text": "Query:"
},
{
"code": null,
"e": 1248,
"s": 968,
"text": "INSERT INTO demo_table VALUES\n('ROMY KUMARI', 22, 'NEW DELHI'),\n('PUSHKAR JHA',23, 'NEW DELHI'),\n('AKANKSHA GUPTA',22, 'PUNJAB'),\n('SUJATA JHA', 30,'PATNA'),\n('PREETI GIRI', 26,'BANGLORE'),\n('PREM GUPTA',31,'PUNE'),\n('RAM KAPOOR', 34,'PUNE'),\n('SHEETAL AWASTHI',32, 'RAJASTHAN');"
},
{
"code": null,
"e": 1279,
"s": 1248,
"text": "Step 5: View data of the table"
},
{
"code": null,
"e": 1286,
"s": 1279,
"text": "Query:"
},
{
"code": null,
"e": 1312,
"s": 1286,
"text": "SELECT * FROM demo_table;"
},
{
"code": null,
"e": 1320,
"s": 1312,
"text": "Output:"
},
{
"code": null,
"e": 1352,
"s": 1320,
"text": "Step 6: Update multiple columns"
},
{
"code": null,
"e": 1478,
"s": 1352,
"text": "For the purpose of demonstration let’s update AGE value to be 30 and CITY value to be PUNJAB where CITY value is ‘NEW DELHI’."
},
{
"code": null,
"e": 1485,
"s": 1478,
"text": "Query:"
},
{
"code": null,
"e": 1553,
"s": 1485,
"text": "UPDATE demo_table\nSET AGE=30, CITY='PUNJAB'\nWHERE CITY='NEW DELHI';"
},
{
"code": null,
"e": 1561,
"s": 1553,
"text": "Output:"
},
{
"code": null,
"e": 1594,
"s": 1561,
"text": "view content of table demo_table"
},
{
"code": null,
"e": 1659,
"s": 1594,
"text": "We can see that the table is updated now with the desired value."
},
{
"code": null,
"e": 1666,
"s": 1659,
"text": "Picked"
},
{
"code": null,
"e": 1677,
"s": 1666,
"text": "SQL-Server"
},
{
"code": null,
"e": 1681,
"s": 1677,
"text": "SQL"
},
{
"code": null,
"e": 1685,
"s": 1681,
"text": "SQL"
}
]
|
p5.Table getRowCount() Method | 08 Jul, 2020
The getRowCount() method of p5.Table in p5.js is used to return the total number of rows in a table object.
Syntax:
getRowCount()
Parameters: This function does not accept any parameters.
Return Value: It returns an integer value which specifies the number of rows in the table.
Below example illustrates the getRowCount() method in p5.js:
Example:
let rowCount = 1; function setup() { createCanvas(500, 400); textSize(16); addRowBtn = createButton("Add Row"); addRowBtn.position(30, 50); addRowBtn.mouseClicked(addOneRow); removeRowBtn = createButton("Clear Last Row"); removeRowBtn.position(160, 50); removeRowBtn.mouseClicked(clearLastRow); // Create the table table = new p5.Table(); // Add columns table.addColumn("book"); table.addColumn("price"); // Display the table showTable();} function addOneRow() { let newRow = table.addRow(); newRow.set('book', "Book " + rowCount); newRow.set('price', "Price " + (rowCount * random(1, 10)).toFixed(1)); rowCount++; showTable();} function clearLastRow() { let lastRow = table.getRowCount() - 1; if (lastRow >= 0) table.removeRow(lastRow); showTable();} function showTable() { clear(); text("Click on the buttons to change" + " the number of rows in the table", 20, 20); // Get the number of rows in the table let rowCount = table.getRowCount(); // Display the total rows // present in the table text("There are " + rowCount + " rows in the table", 20, 100); // Show all the rows currently // present in the table for (let r = 0; r < rowCount; r++) { let currRow = table.rows[r].arr.toString(); currRow = currRow.split(", ").join(" "); text(currRow, 30, 140 + r * 20); }}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Table/getRowCount
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
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": 28,
"s": 0,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "The getRowCount() method of p5.Table in p5.js is used to return the total number of rows in a table object."
},
{
"code": null,
"e": 144,
"s": 136,
"text": "Syntax:"
},
{
"code": null,
"e": 158,
"s": 144,
"text": "getRowCount()"
},
{
"code": null,
"e": 216,
"s": 158,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 307,
"s": 216,
"text": "Return Value: It returns an integer value which specifies the number of rows in the table."
},
{
"code": null,
"e": 368,
"s": 307,
"text": "Below example illustrates the getRowCount() method in p5.js:"
},
{
"code": null,
"e": 377,
"s": 368,
"text": "Example:"
},
{
"code": "let rowCount = 1; function setup() { createCanvas(500, 400); textSize(16); addRowBtn = createButton(\"Add Row\"); addRowBtn.position(30, 50); addRowBtn.mouseClicked(addOneRow); removeRowBtn = createButton(\"Clear Last Row\"); removeRowBtn.position(160, 50); removeRowBtn.mouseClicked(clearLastRow); // Create the table table = new p5.Table(); // Add columns table.addColumn(\"book\"); table.addColumn(\"price\"); // Display the table showTable();} function addOneRow() { let newRow = table.addRow(); newRow.set('book', \"Book \" + rowCount); newRow.set('price', \"Price \" + (rowCount * random(1, 10)).toFixed(1)); rowCount++; showTable();} function clearLastRow() { let lastRow = table.getRowCount() - 1; if (lastRow >= 0) table.removeRow(lastRow); showTable();} function showTable() { clear(); text(\"Click on the buttons to change\" + \" the number of rows in the table\", 20, 20); // Get the number of rows in the table let rowCount = table.getRowCount(); // Display the total rows // present in the table text(\"There are \" + rowCount + \" rows in the table\", 20, 100); // Show all the rows currently // present in the table for (let r = 0; r < rowCount; r++) { let currRow = table.rows[r].arr.toString(); currRow = currRow.split(\", \").join(\" \"); text(currRow, 30, 140 + r * 20); }}",
"e": 1747,
"s": 377,
"text": null
},
{
"code": null,
"e": 1755,
"s": 1747,
"text": "Output:"
},
{
"code": null,
"e": 1795,
"s": 1755,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 1893,
"s": 1795,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 1954,
"s": 1893,
"text": "Reference: https://p5js.org/reference/#/p5.Table/getRowCount"
},
{
"code": null,
"e": 1971,
"s": 1954,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1982,
"s": 1971,
"text": "JavaScript"
},
{
"code": null,
"e": 1999,
"s": 1982,
"text": "Web Technologies"
},
{
"code": null,
"e": 2097,
"s": 1999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2158,
"s": 2097,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2230,
"s": 2158,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2270,
"s": 2230,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2311,
"s": 2270,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2357,
"s": 2311,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2390,
"s": 2357,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2452,
"s": 2390,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2513,
"s": 2452,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2563,
"s": 2513,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to add text on an image using pillow in Python ? | 17 Dec, 2020
Prerequisites: PIL
In this article we’ll see how we can add text on an image using the pillow library in Python. Python Imaging Library (PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aids in editing, creating and saving images. Pillow supports numerous image file formats including BMP, PNG, JPEG, and TIFF.
Syntax:
ImageDraw.Draw.text((x, y),"Text",(r,g,b))
Import module
Import image
Add text
Save image
Image in use:
Example 1:
Python3
from PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # importing the imageimg = Image.open("gfg.png")draw = ImageDraw.Draw(img) # specifying coordinates and colour of textdraw.text((50, 90), "Sample Text", (255, 255, 255)) # saving the imageimg.save('sample.jpg')
Output:
Example 2: Writing text in a specific font
To write the text in a specific font, we need to download the font file for the required font. In the example given below we have used Comic Sans and it can be downloaded from : https://www.wfonts.com/font/comic-sans-ms
Python3
from PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # importing the imageimg = Image.open("gfg.png")draw = ImageDraw.Draw(img) # loading the font and providing the sizefont = ImageFont.truetype("ComicSansMS3.ttf", 30) # specifying coordinates and colour of textdraw.text((50, 90), "Hello World!", (255, 255, 255), font=font) # saving the imageimg.save('sample.jpg')
Output:
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 47,
"s": 28,
"text": "Prerequisites: PIL"
},
{
"code": null,
"e": 414,
"s": 47,
"text": "In this article we’ll see how we can add text on an image using the pillow library in Python. Python Imaging Library (PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aids in editing, creating and saving images. Pillow supports numerous image file formats including BMP, PNG, JPEG, and TIFF. "
},
{
"code": null,
"e": 422,
"s": 414,
"text": "Syntax:"
},
{
"code": null,
"e": 465,
"s": 422,
"text": "ImageDraw.Draw.text((x, y),\"Text\",(r,g,b))"
},
{
"code": null,
"e": 479,
"s": 465,
"text": "Import module"
},
{
"code": null,
"e": 492,
"s": 479,
"text": "Import image"
},
{
"code": null,
"e": 502,
"s": 492,
"text": "Add text "
},
{
"code": null,
"e": 513,
"s": 502,
"text": "Save image"
},
{
"code": null,
"e": 527,
"s": 513,
"text": "Image in use:"
},
{
"code": null,
"e": 538,
"s": 527,
"text": "Example 1:"
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Python3"
},
{
"code": "from PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # importing the imageimg = Image.open(\"gfg.png\")draw = ImageDraw.Draw(img) # specifying coordinates and colour of textdraw.text((50, 90), \"Sample Text\", (255, 255, 255)) # saving the imageimg.save('sample.jpg')",
"e": 832,
"s": 546,
"text": null
},
{
"code": null,
"e": 840,
"s": 832,
"text": "Output:"
},
{
"code": null,
"e": 883,
"s": 840,
"text": "Example 2: Writing text in a specific font"
},
{
"code": null,
"e": 1103,
"s": 883,
"text": "To write the text in a specific font, we need to download the font file for the required font. In the example given below we have used Comic Sans and it can be downloaded from : https://www.wfonts.com/font/comic-sans-ms"
},
{
"code": null,
"e": 1111,
"s": 1103,
"text": "Python3"
},
{
"code": "from PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # importing the imageimg = Image.open(\"gfg.png\")draw = ImageDraw.Draw(img) # loading the font and providing the sizefont = ImageFont.truetype(\"ComicSansMS3.ttf\", 30) # specifying coordinates and colour of textdraw.text((50, 90), \"Hello World!\", (255, 255, 255), font=font) # saving the imageimg.save('sample.jpg')",
"e": 1501,
"s": 1111,
"text": null
},
{
"code": null,
"e": 1509,
"s": 1501,
"text": "Output:"
},
{
"code": null,
"e": 1516,
"s": 1509,
"text": "Picked"
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": "Python-pil"
},
{
"code": null,
"e": 1534,
"s": 1527,
"text": "Python"
},
{
"code": null,
"e": 1632,
"s": 1534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1664,
"s": 1632,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1691,
"s": 1664,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1712,
"s": 1691,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1735,
"s": 1712,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1791,
"s": 1735,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1822,
"s": 1791,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1864,
"s": 1822,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1906,
"s": 1864,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1945,
"s": 1906,
"text": "Python | datetime.timedelta() function"
}
]
|
Hensel’s Lemma | 07 Jul, 2021
Hensel’s Lemma is a result that stipulates conditions for roots of polynomials modulo powers of primes to be “lifted” to roots modulo higher powers. The lifting method outlined in the proof is reminiscent of Newton’s Method for solving equations. Say the equations of the below type is to be solved:
The idea is to use Hensel’s Lemma to solve this type of congruence. It is also known as Hensel’s “lifting” lemma, which is a result of modular arithmetic. If f is a polynomial function and p is a Prime Number, then if f(a1) = 0 (mod p) and [f'(a1)] mod p != 0, then it’s possible to “lift” this solution to the solution for f(x) = 0 (mod pk) by using the below recursion. Note that the [f'(a1)]-1 refers to the modular inverse of f ‘(a1) modulo p.
Example 1:
First, solve for (x = 2 is the solution for mod 5)
=> => => => => =>
Example 2:
This has no solution as (x3 – 3) % mod 7 = 0 has no solution
Below is the implementation of Hensel’s Lemma:
C++
Java
Python3
C#
Javascript
// C++ program to illustrate the// Hensel's Lemma#include <bits/stdc++.h>using namespace std; // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mint inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)int derivative(int x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.int Image(int x, int k){ return x * x * x - k;} // Function to find the next power// of the numberint next_power(int a_t, int t, int a1, int prime, int k){ // Next power of prime for which // solution is to be found int power_p = (int)pow(prime, t + 1); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime int next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primeint powerOfPrime(int prime, int power, int k, int a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { int a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for (int p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Codeint main(){ int prime = 7, a1 = 3; int power = 2, k = 3; // Function Call cout << powerOfPrime(prime, power, k, a1); return 0;}
// Java program to illustrate the// Hensel's Lemmaimport java.util.*; class GFG{ // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mstatic int inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)static int derivative(int x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.static int Image(int x, int k){ return x * x * x - k;} // Function to find the next power// of the numberstatic int next_power(int a_t, int t, int a1, int prime, int k){ // Next power of prime for which // solution is to be found int power_p = (int)Math.pow(prime, t + 1); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime int next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primestatic int powerOfPrime(int prime, int power, int k, int a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { int a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for(int p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Codepublic static void main(String []args){ int prime = 7, a1 = 3; int power = 2, k = 3; // Function Call System.out.print(powerOfPrime(prime, power, k, a1));}} // This code is contributed by rutvik_56
# Python3 program to illustrate the# Hensel's Lemma # Consider f(x) = x ^ 3 - k,# where k is a constant # Function to find the modular# inverse of a modulo mdef inv(a, m): m0 = m x0 = 0 x1 = 1 if (m == 1): return 0 # Apply the Euclidean algorithm, # to find the modular inverse while (a > 1): q = a // m t = m m = a % m a = t t = x0 x0 = x1 - q * x0 x1 = t if (x1 < 0): x1 += m0 return x1 # Function to find the derivative of# f(x) and f'(x) = 3 * (x ^ 2)def derivative(x): return 3 * x * x # Function to find the image of# x in f(x) = x ^ 3 - k.def Image(x, k): return x * x * x - k # Function to find the next power# of the numberdef next_power(a_t, t, a1, prime, k): # Next power of prime for which # solution is to be found power_p = int(pow(prime, t + 1)) # Using Hensel's recursion to # find the solution(next_a) for # next power of prime next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p # If next_a < 0 return equivalent # positive remainder modulo p if (next_a < 0): next_a += power_p return next_a # Return the next power of a return next_a # Function to find the solution of# the required exponent of primedef powerOfPrime(prime, power, k, a1): # The lemma does not work for # derivative of f(x) at a1 if (derivative(a1) != 0): a_t = a1 # Looping from 1 to power # of prime whose solution # is to be found for p in range(1, power): a_t = next_power(a_t, p, a1, prime, k) # Final answer after evaluating # all the exponents up till # the required exponent return a_t return -1 # Driver Codeprime = 7a1 = 3power = 2k = 3 # Function Callprint(powerOfPrime(prime, power, k, a1)) # This code is contributed by amreshkumar3
// C# program to illustrate the// Hensel's Lemmausing System;class GFG{ // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mstatic int inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)static int derivative(int x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.static int Image(int x, int k){ return x * x * x - k;} // Function to find the next power// of the numberstatic int next_power(int a_t, int t, int a1, int prime, int k){ // Next power of prime for which // solution is to be found int power_p = (int)Math.Pow(prime, t + 1); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime int next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primestatic int powerOfPrime(int prime, int power, int k, int a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { int a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for(int p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Codepublic static void Main(string []args){ int prime = 7, a1 = 3; int power = 2, k = 3; // Function Call Console.Write(powerOfPrime(prime, power, k, a1));}} // This code is contributed by pratham76.
<script>// Javascript program to illustrate the// Hensel's Lemma // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mfunction inv(a, m){ let m0 = m, t, q; let x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = Math.floor(a / m); t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)function derivative(x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.function Image(x, k){ return x * x * x - k;} // Function to find the next power// of the numberfunction next_power(a_t, t, a1, prime, k){ // Next power of prime for which // solution is to be found let power_p = Math.floor(Math.pow(prime, t + 1)); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime let next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primefunction powerOfPrime(prime, power, k, a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { let a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for(let p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Code let prime = 7, a1 = 3; let power = 2, k = 3; // Function Call document.write(powerOfPrime(prime, power, k, a1)); // This code is contributed by target_2. </script>
6
Time Complexity: O(log N)Auxiliary Space: O(1)
rutvik_56
pratham76
target_2
amreshkumar3
HCF
Modular Arithmetic
Prime Number
Mathematical
Mathematical
Prime Number
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Product of Array except itself | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Hensel’s Lemma is a result that stipulates conditions for roots of polynomials modulo powers of primes to be “lifted” to roots modulo higher powers. The lifting method outlined in the proof is reminiscent of Newton’s Method for solving equations. Say the equations of the below type is to be solved:"
},
{
"code": null,
"e": 776,
"s": 328,
"text": "The idea is to use Hensel’s Lemma to solve this type of congruence. It is also known as Hensel’s “lifting” lemma, which is a result of modular arithmetic. If f is a polynomial function and p is a Prime Number, then if f(a1) = 0 (mod p) and [f'(a1)] mod p != 0, then it’s possible to “lift” this solution to the solution for f(x) = 0 (mod pk) by using the below recursion. Note that the [f'(a1)]-1 refers to the modular inverse of f ‘(a1) modulo p."
},
{
"code": null,
"e": 788,
"s": 776,
"text": "Example 1: "
},
{
"code": null,
"e": 840,
"s": 788,
"text": "First, solve for (x = 2 is the solution for mod 5) "
},
{
"code": null,
"e": 860,
"s": 840,
"text": "=> => => => => => "
},
{
"code": null,
"e": 872,
"s": 860,
"text": "Example 2: "
},
{
"code": null,
"e": 933,
"s": 872,
"text": "This has no solution as (x3 – 3) % mod 7 = 0 has no solution"
},
{
"code": null,
"e": 981,
"s": 933,
"text": "Below is the implementation of Hensel’s Lemma: "
},
{
"code": null,
"e": 985,
"s": 981,
"text": "C++"
},
{
"code": null,
"e": 990,
"s": 985,
"text": "Java"
},
{
"code": null,
"e": 998,
"s": 990,
"text": "Python3"
},
{
"code": null,
"e": 1001,
"s": 998,
"text": "C#"
},
{
"code": null,
"e": 1012,
"s": 1001,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate the// Hensel's Lemma#include <bits/stdc++.h>using namespace std; // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mint inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)int derivative(int x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.int Image(int x, int k){ return x * x * x - k;} // Function to find the next power// of the numberint next_power(int a_t, int t, int a1, int prime, int k){ // Next power of prime for which // solution is to be found int power_p = (int)pow(prime, t + 1); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime int next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primeint powerOfPrime(int prime, int power, int k, int a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { int a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for (int p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Codeint main(){ int prime = 7, a1 = 3; int power = 2, k = 3; // Function Call cout << powerOfPrime(prime, power, k, a1); return 0;}",
"e": 3275,
"s": 1012,
"text": null
},
{
"code": "// Java program to illustrate the// Hensel's Lemmaimport java.util.*; class GFG{ // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mstatic int inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)static int derivative(int x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.static int Image(int x, int k){ return x * x * x - k;} // Function to find the next power// of the numberstatic int next_power(int a_t, int t, int a1, int prime, int k){ // Next power of prime for which // solution is to be found int power_p = (int)Math.pow(prime, t + 1); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime int next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primestatic int powerOfPrime(int prime, int power, int k, int a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { int a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for(int p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Codepublic static void main(String []args){ int prime = 7, a1 = 3; int power = 2, k = 3; // Function Call System.out.print(powerOfPrime(prime, power, k, a1));}} // This code is contributed by rutvik_56",
"e": 5642,
"s": 3275,
"text": null
},
{
"code": "# Python3 program to illustrate the# Hensel's Lemma # Consider f(x) = x ^ 3 - k,# where k is a constant # Function to find the modular# inverse of a modulo mdef inv(a, m): m0 = m x0 = 0 x1 = 1 if (m == 1): return 0 # Apply the Euclidean algorithm, # to find the modular inverse while (a > 1): q = a // m t = m m = a % m a = t t = x0 x0 = x1 - q * x0 x1 = t if (x1 < 0): x1 += m0 return x1 # Function to find the derivative of# f(x) and f'(x) = 3 * (x ^ 2)def derivative(x): return 3 * x * x # Function to find the image of# x in f(x) = x ^ 3 - k.def Image(x, k): return x * x * x - k # Function to find the next power# of the numberdef next_power(a_t, t, a1, prime, k): # Next power of prime for which # solution is to be found power_p = int(pow(prime, t + 1)) # Using Hensel's recursion to # find the solution(next_a) for # next power of prime next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p # If next_a < 0 return equivalent # positive remainder modulo p if (next_a < 0): next_a += power_p return next_a # Return the next power of a return next_a # Function to find the solution of# the required exponent of primedef powerOfPrime(prime, power, k, a1): # The lemma does not work for # derivative of f(x) at a1 if (derivative(a1) != 0): a_t = a1 # Looping from 1 to power # of prime whose solution # is to be found for p in range(1, power): a_t = next_power(a_t, p, a1, prime, k) # Final answer after evaluating # all the exponents up till # the required exponent return a_t return -1 # Driver Codeprime = 7a1 = 3power = 2k = 3 # Function Callprint(powerOfPrime(prime, power, k, a1)) # This code is contributed by amreshkumar3",
"e": 7599,
"s": 5642,
"text": null
},
{
"code": "// C# program to illustrate the// Hensel's Lemmausing System;class GFG{ // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mstatic int inv(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)static int derivative(int x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.static int Image(int x, int k){ return x * x * x - k;} // Function to find the next power// of the numberstatic int next_power(int a_t, int t, int a1, int prime, int k){ // Next power of prime for which // solution is to be found int power_p = (int)Math.Pow(prime, t + 1); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime int next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primestatic int powerOfPrime(int prime, int power, int k, int a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { int a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for(int p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Codepublic static void Main(string []args){ int prime = 7, a1 = 3; int power = 2, k = 3; // Function Call Console.Write(powerOfPrime(prime, power, k, a1));}} // This code is contributed by pratham76.",
"e": 9949,
"s": 7599,
"text": null
},
{
"code": "<script>// Javascript program to illustrate the// Hensel's Lemma // Consider f(x) = x ^ 3 - k,// where k is a constant // Function to find the modular// inverse of a modulo mfunction inv(a, m){ let m0 = m, t, q; let x0 = 0, x1 = 1; if (m == 1) return 0; // Apply the Euclidean algorithm, // to find the modular inverse while (a > 1) { q = Math.floor(a / m); t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1;} // Function to find the derivative of// f(x) and f'(x) = 3 * (x ^ 2)function derivative(x){ return 3 * x * x;} // Function to find the image of// x in f(x) = x ^ 3 - k.function Image(x, k){ return x * x * x - k;} // Function to find the next power// of the numberfunction next_power(a_t, t, a1, prime, k){ // Next power of prime for which // solution is to be found let power_p = Math.floor(Math.pow(prime, t + 1)); // Using Hensel's recursion to // find the solution (next_a) for // next power of prime let next_a = (a_t - Image(a_t, k) * inv(derivative(a1), prime)) % power_p; // If next_a < 0 return equivalent // positive remainder modulo p if (next_a < 0) return next_a += power_p; // Return the next power of a return next_a;} // Function to find the solution of// the required exponent of primefunction powerOfPrime(prime, power, k, a1){ // The lemma does not work for // derivative of f(x) at a1 if (derivative(a1) != 0) { let a_t = a1; // Looping from 1 to power // of prime whose solution // is to be found for(let p = 1; p < power; p++) { a_t = next_power(a_t, p, a1, prime, k); } // Final answer after evaluating // all the exponents up till // the required exponent return a_t; } return -1;} // Driver Code let prime = 7, a1 = 3; let power = 2, k = 3; // Function Call document.write(powerOfPrime(prime, power, k, a1)); // This code is contributed by target_2. </script>",
"e": 12268,
"s": 9949,
"text": null
},
{
"code": null,
"e": 12270,
"s": 12268,
"text": "6"
},
{
"code": null,
"e": 12319,
"s": 12272,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12329,
"s": 12319,
"text": "rutvik_56"
},
{
"code": null,
"e": 12339,
"s": 12329,
"text": "pratham76"
},
{
"code": null,
"e": 12348,
"s": 12339,
"text": "target_2"
},
{
"code": null,
"e": 12361,
"s": 12348,
"text": "amreshkumar3"
},
{
"code": null,
"e": 12365,
"s": 12361,
"text": "HCF"
},
{
"code": null,
"e": 12384,
"s": 12365,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 12397,
"s": 12384,
"text": "Prime Number"
},
{
"code": null,
"e": 12410,
"s": 12397,
"text": "Mathematical"
},
{
"code": null,
"e": 12423,
"s": 12410,
"text": "Mathematical"
},
{
"code": null,
"e": 12436,
"s": 12423,
"text": "Prime Number"
},
{
"code": null,
"e": 12455,
"s": 12436,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 12553,
"s": 12455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12585,
"s": 12553,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 12631,
"s": 12585,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 12675,
"s": 12631,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 12724,
"s": 12675,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 12766,
"s": 12724,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 12798,
"s": 12766,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 12833,
"s": 12798,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 12858,
"s": 12833,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 12929,
"s": 12858,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
]
|
Software Engineering | Control Flow Graph (CFG) | 15 May, 2019
A Control Flow Graph (CFG) is the graphical representation of control flow or computation during the execution of programs or applications. Control flow graphs are mostly used in static analysis as well as compiler applications, as they can accurately represent the flow inside of a program unit. The control flow graph was originally developed by Frances E. Allen.
Characteristics of Control Flow Graph:
Control flow graph is process oriented.
Control flow graph shows all the paths that can be traversed during a program execution.
Control flow graph is a directed graph.
Edges in CFG portray control flow paths and the nodes in CFG portray basic blocks.
There exist 2 designated blocks in Control Flow Graph:
Entry Block:Entry block allows the control to enter into the control flow graph.Exit Block:Control flow leaves through the exit block.
Entry Block:Entry block allows the control to enter into the control flow graph.
Exit Block:Control flow leaves through the exit block.
Hence, the control flow graph is comprised of all the building blocks involved in a flow diagram such as the start node, end node and flows between the nodes.
General Control Flow Graphs:Control Flow Graph is represented differently for all statements and loops. Following images describe it:
1. If-else:
2. while:
3. do-while:
4. for:
Example:
if A = 10 then
if B > C
A = B
else A = C
endif
endif
print A, B, C
Flowchart of above example will be:
Control Flow Graph of above example will be:
Advantage of CFG:There are many advantages of a control flow graph. It can easily encapsulate the information per each basic block. It can easily locate inaccessible codes of a program and syntactic structures such as loops are easy to find in a control flow graph.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 418,
"s": 52,
"text": "A Control Flow Graph (CFG) is the graphical representation of control flow or computation during the execution of programs or applications. Control flow graphs are mostly used in static analysis as well as compiler applications, as they can accurately represent the flow inside of a program unit. The control flow graph was originally developed by Frances E. Allen."
},
{
"code": null,
"e": 457,
"s": 418,
"text": "Characteristics of Control Flow Graph:"
},
{
"code": null,
"e": 497,
"s": 457,
"text": "Control flow graph is process oriented."
},
{
"code": null,
"e": 586,
"s": 497,
"text": "Control flow graph shows all the paths that can be traversed during a program execution."
},
{
"code": null,
"e": 626,
"s": 586,
"text": "Control flow graph is a directed graph."
},
{
"code": null,
"e": 709,
"s": 626,
"text": "Edges in CFG portray control flow paths and the nodes in CFG portray basic blocks."
},
{
"code": null,
"e": 764,
"s": 709,
"text": "There exist 2 designated blocks in Control Flow Graph:"
},
{
"code": null,
"e": 899,
"s": 764,
"text": "Entry Block:Entry block allows the control to enter into the control flow graph.Exit Block:Control flow leaves through the exit block."
},
{
"code": null,
"e": 980,
"s": 899,
"text": "Entry Block:Entry block allows the control to enter into the control flow graph."
},
{
"code": null,
"e": 1035,
"s": 980,
"text": "Exit Block:Control flow leaves through the exit block."
},
{
"code": null,
"e": 1194,
"s": 1035,
"text": "Hence, the control flow graph is comprised of all the building blocks involved in a flow diagram such as the start node, end node and flows between the nodes."
},
{
"code": null,
"e": 1328,
"s": 1194,
"text": "General Control Flow Graphs:Control Flow Graph is represented differently for all statements and loops. Following images describe it:"
},
{
"code": null,
"e": 1340,
"s": 1328,
"text": "1. If-else:"
},
{
"code": null,
"e": 1350,
"s": 1340,
"text": "2. while:"
},
{
"code": null,
"e": 1363,
"s": 1350,
"text": "3. do-while:"
},
{
"code": null,
"e": 1371,
"s": 1363,
"text": "4. for:"
},
{
"code": null,
"e": 1380,
"s": 1371,
"text": "Example:"
},
{
"code": null,
"e": 1462,
"s": 1380,
"text": "if A = 10 then\n if B > C\n A = B\n else A = C\n endif\n endif\nprint A, B, C "
},
{
"code": null,
"e": 1498,
"s": 1462,
"text": "Flowchart of above example will be:"
},
{
"code": null,
"e": 1543,
"s": 1498,
"text": "Control Flow Graph of above example will be:"
},
{
"code": null,
"e": 1809,
"s": 1543,
"text": "Advantage of CFG:There are many advantages of a control flow graph. It can easily encapsulate the information per each basic block. It can easily locate inaccessible codes of a program and syntactic structures such as loops are easy to find in a control flow graph."
},
{
"code": null,
"e": 1830,
"s": 1809,
"text": "Software Engineering"
}
]
|
Polymorphism in GoLang | 07 Jul, 2021
Polymorphism is the ability of a message to be displayed in more than one form. Polymorphism is considered as one of the important features of Object-Oriented Programming and can be achieved during either at runtime or compile time. Golang is a light-Object Oriented language and supports polymorphism through interfaces only. Let us first understand the interfaces by the following example:Example 1:
C
// Golang program to illustrate the// concept of interfacespackage main import ( "fmt") // defining an interfacetype Figure interface{ Area() float64} // declaring a structtype Rectangle struct{ // declaring struct variables length float64 width float64} // declaring a structtype Square struct{ // declaring struct variable side float64} // function to calculate// area of a rectanglefunc (rect Rectangle) Area() float64{ // Area of rectangle = l * b area := rect.length * rect.width return area} // function to calculate// area of a squarefunc (sq Square) Area() float64{ // Area of square = a * a area := sq.side * sq.side return area} // main functionfunc main() { // declaring a rectangle instance rectangle := Rectangle{ length: 10.5, width: 12.25, } // declaring a square instance square := Square{ side: 15.0, } // printing the calculated result fmt.Printf("Area of rectangle: %.3f unit sq.\n", rectangle.Area()) fmt.Printf("Area of square: %.3f unit sq.\n", square.Area())}
Output:
Area of rectangle: 128.625 unit sq.
Area of square: 225.000 unit sq.
Objects of different types are treated in a consistent way, as long as they stick to a single interface, which is the essence of polymorphism. Variable declared in an interface are of interface type. They can take whichever value which implements the interface which helps interfaces to achieve polymorphism in the Golang. The following example explains the concept of polymorphism:Example 2:
C
// Golang program to illustrate the// concept of polymorphismpackage main import ( "fmt") // defining an interfacetype Reading interface{ // declaring interface method reading_time() int} // declaring a structtype Book struct{ // declaring struct variables name string page_count int} // declaring a structtype Newspaper struct{ // declaring struct variables name string page_count int} // declaring a structtype Magazine struct{ // declaring struct variables name string page_count int} // function to calculate reading// time for bookfunc (book Book) reading_time() int { // taking average speed // of 10 mins per page read_time := 10 * book.page_count return read_time} // function to calculate reading// time for newspaperfunc (newspaper Newspaper) reading_time() int { // taking average speed // of 30 mins per page read_time := 30 * newspaper.page_count return read_time} // function to calculate reading// time for magazinefunc (magazine Magazine) reading_time() int { // taking average speed // of 5 mins per page read_time := 5 * magazine.page_count return read_time} // function to calculate reading timefunc calcReadingTime(ReadingTime []Reading) int { totalTime := 0 // looping through elements // of the Reading array for _, t := range ReadingTime { // run time polymorphism, call to // method depends on object being // referred at run time totalTime += t.reading_time() } return totalTime} // main functionfunc main() { // declaring a book instance book1 := Book{ name: "Goosebumps", page_count: 150, } // declaring a newspaper instance newspaper1 := Newspaper{ name: "TOI", page_count: 12, } // declaring a magazine instance magazine1 := Magazine{ name: "Forbes", page_count: 40, } // array of type Reading interface ReadingTime := []Reading{book1, newspaper1, magazine1} // total reading time calculated totalTime := calcReadingTime(ReadingTime) // Printing total time for reading fmt.Printf("Total Time is %d minutes.\n", totalTime)}
Output:
Total Time is 2060 minutes.
sagar0719kumar
Golang-Interfaces
Golang-OOPs
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
Loops in Go Language
How to iterate over an Array using for loop in Golang?
Structures in Golang
Strings in Golang
Go Variables
time.Parse() Function in Golang With Examples
Class and Object in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 431,
"s": 28,
"text": "Polymorphism is the ability of a message to be displayed in more than one form. Polymorphism is considered as one of the important features of Object-Oriented Programming and can be achieved during either at runtime or compile time. Golang is a light-Object Oriented language and supports polymorphism through interfaces only. Let us first understand the interfaces by the following example:Example 1: "
},
{
"code": null,
"e": 433,
"s": 431,
"text": "C"
},
{
"code": "// Golang program to illustrate the// concept of interfacespackage main import ( \"fmt\") // defining an interfacetype Figure interface{ Area() float64} // declaring a structtype Rectangle struct{ // declaring struct variables length float64 width float64} // declaring a structtype Square struct{ // declaring struct variable side float64} // function to calculate// area of a rectanglefunc (rect Rectangle) Area() float64{ // Area of rectangle = l * b area := rect.length * rect.width return area} // function to calculate// area of a squarefunc (sq Square) Area() float64{ // Area of square = a * a area := sq.side * sq.side return area} // main functionfunc main() { // declaring a rectangle instance rectangle := Rectangle{ length: 10.5, width: 12.25, } // declaring a square instance square := Square{ side: 15.0, } // printing the calculated result fmt.Printf(\"Area of rectangle: %.3f unit sq.\\n\", rectangle.Area()) fmt.Printf(\"Area of square: %.3f unit sq.\\n\", square.Area())}",
"e": 1545,
"s": 433,
"text": null
},
{
"code": null,
"e": 1555,
"s": 1545,
"text": "Output: "
},
{
"code": null,
"e": 1624,
"s": 1555,
"text": "Area of rectangle: 128.625 unit sq.\nArea of square: 225.000 unit sq."
},
{
"code": null,
"e": 2018,
"s": 1624,
"text": "Objects of different types are treated in a consistent way, as long as they stick to a single interface, which is the essence of polymorphism. Variable declared in an interface are of interface type. They can take whichever value which implements the interface which helps interfaces to achieve polymorphism in the Golang. The following example explains the concept of polymorphism:Example 2: "
},
{
"code": null,
"e": 2020,
"s": 2018,
"text": "C"
},
{
"code": "// Golang program to illustrate the// concept of polymorphismpackage main import ( \"fmt\") // defining an interfacetype Reading interface{ // declaring interface method reading_time() int} // declaring a structtype Book struct{ // declaring struct variables name string page_count int} // declaring a structtype Newspaper struct{ // declaring struct variables name string page_count int} // declaring a structtype Magazine struct{ // declaring struct variables name string page_count int} // function to calculate reading// time for bookfunc (book Book) reading_time() int { // taking average speed // of 10 mins per page read_time := 10 * book.page_count return read_time} // function to calculate reading// time for newspaperfunc (newspaper Newspaper) reading_time() int { // taking average speed // of 30 mins per page read_time := 30 * newspaper.page_count return read_time} // function to calculate reading// time for magazinefunc (magazine Magazine) reading_time() int { // taking average speed // of 5 mins per page read_time := 5 * magazine.page_count return read_time} // function to calculate reading timefunc calcReadingTime(ReadingTime []Reading) int { totalTime := 0 // looping through elements // of the Reading array for _, t := range ReadingTime { // run time polymorphism, call to // method depends on object being // referred at run time totalTime += t.reading_time() } return totalTime} // main functionfunc main() { // declaring a book instance book1 := Book{ name: \"Goosebumps\", page_count: 150, } // declaring a newspaper instance newspaper1 := Newspaper{ name: \"TOI\", page_count: 12, } // declaring a magazine instance magazine1 := Magazine{ name: \"Forbes\", page_count: 40, } // array of type Reading interface ReadingTime := []Reading{book1, newspaper1, magazine1} // total reading time calculated totalTime := calcReadingTime(ReadingTime) // Printing total time for reading fmt.Printf(\"Total Time is %d minutes.\\n\", totalTime)}",
"e": 4277,
"s": 2020,
"text": null
},
{
"code": null,
"e": 4287,
"s": 4277,
"text": "Output: "
},
{
"code": null,
"e": 4315,
"s": 4287,
"text": "Total Time is 2060 minutes."
},
{
"code": null,
"e": 4332,
"s": 4317,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4350,
"s": 4332,
"text": "Golang-Interfaces"
},
{
"code": null,
"e": 4362,
"s": 4350,
"text": "Golang-OOPs"
},
{
"code": null,
"e": 4374,
"s": 4362,
"text": "Go Language"
},
{
"code": null,
"e": 4472,
"s": 4374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4501,
"s": 4472,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 4524,
"s": 4501,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 4549,
"s": 4524,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 4570,
"s": 4549,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 4625,
"s": 4570,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 4646,
"s": 4625,
"text": "Structures in Golang"
},
{
"code": null,
"e": 4664,
"s": 4646,
"text": "Strings in Golang"
},
{
"code": null,
"e": 4677,
"s": 4664,
"text": "Go Variables"
},
{
"code": null,
"e": 4723,
"s": 4677,
"text": "time.Parse() Function in Golang With Examples"
}
]
|
How to automatically close all collapsible elements inside of the accordion when closing the accordion? | 22 Jun, 2020
The Collapse plugin provides a quick way of revealing and hiding content. It flip the perceivability of content over program with a couple of classes and Bootstrap 4 JavaScript plugins.
Flipping(toggling) of content requires to connect with the href attribute, or a button with the data-target property. In both cases, the data-toggle=”collapse” is required.
Syntax:
Link with the href attribute.
<a data-toggle="collapse" href="#collapseExample" ...>
<!--Write your link name -->
</a>
OR
Button with the data-target property.
<button class="btn btn-primary" type="button"
data-toggle="collapse"
data-target="#collapseExample" ...>
<!--Write your button name-->
</button>
To display card:
<div class="collapse" id="collapseExample">
<div class="card card-body">
<h5 class="card-title"><!--Write title name--></h5>
<!--Write content here -->
</div>
</div>
Example:
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title> How to automatically close all collapsible elements inside of the accordion when closing the accordion? </title></head> <body> <center> <h4><a class="text-success" style="text-decoration: none;" href="#"> Geeksforgeeks </a> </h4><br> <a class="text-success" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Connect with href </a> <br /><br /> <button class="btn btn-success" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Button with data-target </button> <div class="collapse" id="collapseExample"> <div class="card card-body"> <h5 class="card-title"> Basic Example </h5> <p> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. </p> </div> </div> </center></body> </html>
Output:
**Note: Here the content is placed at center if you don’t want it then remove <center> tag.
Multiple targets: Multiple <button> or <a> element can display or hide the component in case they reference it with their href or data-target attribute. The <button> or <a> can show and hide multiple elements by referencing them with a jQuery selector in its href or data-target attribute.
Example:
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title>Multiple Collapse</title></head> <body> <center> <h4><a class="text-success" style="text-decoration: none;" href="#"> Geeksforgeeks </a> </h4><br> <a class="text-success" data-toggle="collapse" href="#multiCollapseExample1" aria-expanded="false" aria-controls="multiCollapseExample1"> Flip first card </a> <button class="btn btn-success" type="button" data-toggle="collapse" data-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2"> Flip second card </button> <button class="btn btn-success" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2"> Flip third card </button> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1"> <div class="card card-body text-success"> <h5 class="card-title"> Multiple collapse </h5> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2"> <div class="card card-body text-success"> <h5 class="card-title"> Multiple collapse </h5> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. </div> </div> </div> </div> </center></body> </html>
Output:
Accordion: Utilizing the card component, you’ll be able to extend the default collapse behavior to form an accordion.
Example:
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title>Accordion</title></head> <body> <center> <h4><a class="text-success" style="text-decoration: none;" href="#"> Geeksforgeeks </a> </h4><br> <div id="accordion"> <div class="card"> <div class="card-header text-white mb-3 bg-success" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-success" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> #1MyCollapsible </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <b> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </b> </div> </div> </div> <div class="card"> <div class="card-header text-white mb-3 bg-success" id="headingTwo"> <h5 class="mb-0"> <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> #2MyCollapsible </button> </h5> </div> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion"> <div class="card-body"> <b> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </b> </div> </div> </div> <div class="card"> <div class="card-header text-white mb-3 bg-success" id="headingThree"> <h5 class="mb-0"> <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> #3MyCollapsible </button> </h5> </div> <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion"> <div class="card-body"> <b> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </b> </div> </div> </div> </div> </center></body> </html>
Output:
How to automatically close all collapsible elements inside of the accordion when closing the accordion?
Example:
HTML
<!doctype html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title>Accordion</title></head> <body> <center> <h4><a class="text-success" style="text-decoration: none;" href="#"> Geeksforgeeks </a> </h4><br> <div id="accordion"> <div class="card"> <div class="card-header text-white mb-3 bg-success" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-success" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> #1MyCollapsible </button> </h5> </div> <div id="collapseOne" class="main collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <div id="accordionRecommendation"> <div class="card-header border text-white mb-3 bg-success" id="headingRecommendation"> <h5 class="mb-0"> <button class= "btn btn-success collapsed" data-toggle="collapse" data-target="#collapseOne1" aria-expanded="false" aria-controls="collapseOne1"> Inner #1MyCollapsible </button> <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#collapseTwo1" aria-expanded="false" aria-controls="collapseTwo1"> Inner #2MyCollapsible </button> <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#collapseThree1" aria-expanded="false" aria-controls="collapseThree1"> Inner #3MyCollapsible </button> </h5> </div> <div class="karte"> <div id="collapseOne1" class="collapse" aria-labelledby="headingRecommendation" data-parent="#accordionRecommendation"> <div class="card-body"> <b>Some Content of First One</b> </div> </div> </div> <div class="karte"> <div id="collapseTwo1" class="collapse" aria-labelledby="headingRecommendation" data-parent="#accordionRecommendation"> <div class="card-body"> <b>Some Content of First Two</b> </div> </div> </div> <div class="karte"> <div id="collapseThree1" class="collapse" aria-labelledby="headingRecommendation" data-parent="#accordionRecommendation"> <div class="card-body"> <b>Some Content of First Three</b> </div> </div> </div> </div> </div> </div> </div> <div class="card"> <div class="card-header text-white mb-3 bg-success" id="headingTwo"> <h5 class="mb-0"> <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> #2MyCollapsible </button> </h5> </div> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion"> <div class="card-body"> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </div> </div> </div> <div class="card"> <div class="card-header text-white mb-3 bg-success" id="headingThree"> <h5 class="mb-0"> <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> #3MyCollapsible </button> </h5> </div> <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion"> <div class="card-body"> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </div> </div> </div> </div> </center></body> </html>
Output:
Why do we use aria-expanded and aria-controls?
Add aria-expanded to the control component. This quality unequivocally (explicitly) passes on the current state of the collapsible component tied to the control to screen perusers (readers) and comparable assistive technologies. On the off chance that the collapsible component is closed by default, the property on the control component ought to have a esteem of(set) aria-expanded=”false”. In the event that you’ve set the collapsible component to be open by default utilizing the show class, then set aria-expanded=”true” on the control instep. The plugin will consequently flip(toggle) this trait on the control based on whether or not the collapsible component has been opened or closed (by means of JavaScript, or since the client activated another control component too tied to the same collapsible component). On the off chance that the control element’s HTML component isn’t a button (e.g. an <a> or <div>), the attribute role=”button” should be included to the component.
On the off chance that your control component is focusing on a single collapsible component – i.e. the data-target attribute is indicating to an id selector – you ought to include the aria-controls attribute to the control component, containing the id of the collapsible component. Advanced screen perusers and comparative assistive advances(technologies) make utilize of this trait to supply clients with extra alternate routes to explore straightforwardly to the collapsible component itself.
We can use Collapse and Accordion via data attributes or via javascript.
Through data attributes: The collapse plugin utilizes a number of classes to handle the overwhelming lifting:
.collapse covers up the content
.collapse.show appears the content
.collapsing is included when the transition begins, and expelled when it wraps up.
Add data-toggle=”collapse” and a data-target to the component to naturally allot control of one or more collapsible components. The data-target attribute acknowledges a CSS selector to apply the collapse. Be beyond any doubt to include the class collapse to the collapsible component. On the off chance that you’d like it to default open, include the extra class show.
To include accordion-like gather administration to a collapsible range, include the information attribute data-parent=”#selector”.
Through JavaScript:
$('.collapse').collapse()
Methods:
.collapse(options): Enacts your content as a collapsible component. Acknowledges an optional alternatives object. Options are parent and toggle. Ex. $(‘#myCollapsible’).collapse({toggle: false})
.collapse(‘toggle’): Flips a collapsible component to appeared or covered up.
.collapse(‘show’): Appears a collapsible component.
.collapse(‘hide’): Covers up a collapsible component.
.collapse(‘dispose’): Devastates an component’s collapse.
Bootstrap-4
Bootstrap-Misc
Picked
Bootstrap
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
How to set the default value for an HTML <select> element ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "The Collapse plugin provides a quick way of revealing and hiding content. It flip the perceivability of content over program with a couple of classes and Bootstrap 4 JavaScript plugins."
},
{
"code": null,
"e": 387,
"s": 214,
"text": "Flipping(toggling) of content requires to connect with the href attribute, or a button with the data-target property. In both cases, the data-toggle=”collapse” is required."
},
{
"code": null,
"e": 396,
"s": 387,
"text": "Syntax: "
},
{
"code": null,
"e": 426,
"s": 396,
"text": "Link with the href attribute."
},
{
"code": null,
"e": 520,
"s": 426,
"text": "<a data-toggle=\"collapse\" href=\"#collapseExample\" ...>\n <!--Write your link name -->\n</a>\n"
},
{
"code": null,
"e": 523,
"s": 520,
"text": "OR"
},
{
"code": null,
"e": 561,
"s": 523,
"text": "Button with the data-target property."
},
{
"code": null,
"e": 721,
"s": 561,
"text": "<button class=\"btn btn-primary\" type=\"button\" \n data-toggle=\"collapse\" \n data-target=\"#collapseExample\" ...>\n <!--Write your button name-->\n</button>\n"
},
{
"code": null,
"e": 740,
"s": 723,
"text": "To display card:"
},
{
"code": null,
"e": 931,
"s": 740,
"text": "<div class=\"collapse\" id=\"collapseExample\">\n <div class=\"card card-body\">\n <h5 class=\"card-title\"><!--Write title name--></h5>\n <!--Write content here -->\n </div>\n</div>\n"
},
{
"code": null,
"e": 940,
"s": 931,
"text": "Example:"
},
{
"code": null,
"e": 945,
"s": 940,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title> How to automatically close all collapsible elements inside of the accordion when closing the accordion? </title></head> <body> <center> <h4><a class=\"text-success\" style=\"text-decoration: none;\" href=\"#\"> Geeksforgeeks </a> </h4><br> <a class=\"text-success\" data-toggle=\"collapse\" href=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\"> Connect with href </a> <br /><br /> <button class=\"btn btn-success\" type=\"button\" data-toggle=\"collapse\" data-target=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\"> Button with data-target </button> <div class=\"collapse\" id=\"collapseExample\"> <div class=\"card card-body\"> <h5 class=\"card-title\"> Basic Example </h5> <p> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. </p> </div> </div> </center></body> </html>",
"e": 3624,
"s": 945,
"text": null
},
{
"code": null,
"e": 3632,
"s": 3624,
"text": "Output:"
},
{
"code": null,
"e": 3724,
"s": 3632,
"text": "**Note: Here the content is placed at center if you don’t want it then remove <center> tag."
},
{
"code": null,
"e": 4015,
"s": 3724,
"text": "Multiple targets: Multiple <button> or <a> element can display or hide the component in case they reference it with their href or data-target attribute. The <button> or <a> can show and hide multiple elements by referencing them with a jQuery selector in its href or data-target attribute. "
},
{
"code": null,
"e": 4024,
"s": 4015,
"text": "Example:"
},
{
"code": null,
"e": 4029,
"s": 4024,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title>Multiple Collapse</title></head> <body> <center> <h4><a class=\"text-success\" style=\"text-decoration: none;\" href=\"#\"> Geeksforgeeks </a> </h4><br> <a class=\"text-success\" data-toggle=\"collapse\" href=\"#multiCollapseExample1\" aria-expanded=\"false\" aria-controls=\"multiCollapseExample1\"> Flip first card </a> <button class=\"btn btn-success\" type=\"button\" data-toggle=\"collapse\" data-target=\"#multiCollapseExample2\" aria-expanded=\"false\" aria-controls=\"multiCollapseExample2\"> Flip second card </button> <button class=\"btn btn-success\" type=\"button\" data-toggle=\"collapse\" data-target=\".multi-collapse\" aria-expanded=\"false\" aria-controls=\"multiCollapseExample1 multiCollapseExample2\"> Flip third card </button> <div class=\"row\"> <div class=\"col\"> <div class=\"collapse multi-collapse\" id=\"multiCollapseExample1\"> <div class=\"card card-body text-success\"> <h5 class=\"card-title\"> Multiple collapse </h5> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. </div> </div> </div> <div class=\"col\"> <div class=\"collapse multi-collapse\" id=\"multiCollapseExample2\"> <div class=\"card card-body text-success\"> <h5 class=\"card-title\"> Multiple collapse </h5> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. </div> </div> </div> </div> </center></body> </html>",
"e": 7763,
"s": 4029,
"text": null
},
{
"code": null,
"e": 7771,
"s": 7763,
"text": "Output:"
},
{
"code": null,
"e": 7889,
"s": 7771,
"text": "Accordion: Utilizing the card component, you’ll be able to extend the default collapse behavior to form an accordion."
},
{
"code": null,
"e": 7898,
"s": 7889,
"text": "Example:"
},
{
"code": null,
"e": 7903,
"s": 7898,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title>Accordion</title></head> <body> <center> <h4><a class=\"text-success\" style=\"text-decoration: none;\" href=\"#\"> Geeksforgeeks </a> </h4><br> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header text-white mb-3 bg-success\" id=\"headingOne\"> <h5 class=\"mb-0\"> <button class=\"btn btn-success\" data-toggle=\"collapse\" data-target=\"#collapseOne\" aria-expanded=\"true\" aria-controls=\"collapseOne\"> #1MyCollapsible </button> </h5> </div> <div id=\"collapseOne\" class=\"collapse show\" aria-labelledby=\"headingOne\" data-parent=\"#accordion\"> <div class=\"card-body\"> <b> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </b> </div> </div> </div> <div class=\"card\"> <div class=\"card-header text-white mb-3 bg-success\" id=\"headingTwo\"> <h5 class=\"mb-0\"> <button class=\"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseTwo\" aria-expanded=\"false\" aria-controls=\"collapseTwo\"> #2MyCollapsible </button> </h5> </div> <div id=\"collapseTwo\" class=\"collapse\" aria-labelledby=\"headingTwo\" data-parent=\"#accordion\"> <div class=\"card-body\"> <b> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </b> </div> </div> </div> <div class=\"card\"> <div class=\"card-header text-white mb-3 bg-success\" id=\"headingThree\"> <h5 class=\"mb-0\"> <button class=\"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseThree\" aria-expanded=\"false\" aria-controls=\"collapseThree\"> #3MyCollapsible </button> </h5> </div> <div id=\"collapseThree\" class=\"collapse\" aria-labelledby=\"headingThree\" data-parent=\"#accordion\"> <div class=\"card-body\"> <b> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </b> </div> </div> </div> </div> </center></body> </html>",
"e": 13685,
"s": 7903,
"text": null
},
{
"code": null,
"e": 13693,
"s": 13685,
"text": "Output:"
},
{
"code": null,
"e": 13797,
"s": 13693,
"text": "How to automatically close all collapsible elements inside of the accordion when closing the accordion?"
},
{
"code": null,
"e": 13806,
"s": 13797,
"text": "Example:"
},
{
"code": null,
"e": 13811,
"s": 13806,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title>Accordion</title></head> <body> <center> <h4><a class=\"text-success\" style=\"text-decoration: none;\" href=\"#\"> Geeksforgeeks </a> </h4><br> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header text-white mb-3 bg-success\" id=\"headingOne\"> <h5 class=\"mb-0\"> <button class=\"btn btn-success\" data-toggle=\"collapse\" data-target=\"#collapseOne\" aria-expanded=\"true\" aria-controls=\"collapseOne\"> #1MyCollapsible </button> </h5> </div> <div id=\"collapseOne\" class=\"main collapse show\" aria-labelledby=\"headingOne\" data-parent=\"#accordion\"> <div class=\"card-body\"> <div id=\"accordionRecommendation\"> <div class=\"card-header border text-white mb-3 bg-success\" id=\"headingRecommendation\"> <h5 class=\"mb-0\"> <button class= \"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseOne1\" aria-expanded=\"false\" aria-controls=\"collapseOne1\"> Inner #1MyCollapsible </button> <button class=\"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseTwo1\" aria-expanded=\"false\" aria-controls=\"collapseTwo1\"> Inner #2MyCollapsible </button> <button class=\"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseThree1\" aria-expanded=\"false\" aria-controls=\"collapseThree1\"> Inner #3MyCollapsible </button> </h5> </div> <div class=\"karte\"> <div id=\"collapseOne1\" class=\"collapse\" aria-labelledby=\"headingRecommendation\" data-parent=\"#accordionRecommendation\"> <div class=\"card-body\"> <b>Some Content of First One</b> </div> </div> </div> <div class=\"karte\"> <div id=\"collapseTwo1\" class=\"collapse\" aria-labelledby=\"headingRecommendation\" data-parent=\"#accordionRecommendation\"> <div class=\"card-body\"> <b>Some Content of First Two</b> </div> </div> </div> <div class=\"karte\"> <div id=\"collapseThree1\" class=\"collapse\" aria-labelledby=\"headingRecommendation\" data-parent=\"#accordionRecommendation\"> <div class=\"card-body\"> <b>Some Content of First Three</b> </div> </div> </div> </div> </div> </div> </div> <div class=\"card\"> <div class=\"card-header text-white mb-3 bg-success\" id=\"headingTwo\"> <h5 class=\"mb-0\"> <button class=\"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseTwo\" aria-expanded=\"false\" aria-controls=\"collapseTwo\"> #2MyCollapsible </button> </h5> </div> <div id=\"collapseTwo\" class=\"collapse\" aria-labelledby=\"headingTwo\" data-parent=\"#accordion\"> <div class=\"card-body\"> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </div> </div> </div> <div class=\"card\"> <div class=\"card-header text-white mb-3 bg-success\" id=\"headingThree\"> <h5 class=\"mb-0\"> <button class=\"btn btn-success collapsed\" data-toggle=\"collapse\" data-target=\"#collapseThree\" aria-expanded=\"false\" aria-controls=\"collapseThree\"> #3MyCollapsible </button> </h5> </div> <div id=\"collapseThree\" class=\"collapse\" aria-labelledby=\"headingThree\" data-parent=\"#accordion\"> <div class=\"card-body\"> Collapse plugin provides a quick way of revealing and hiding content. It toggle the visibility of content across your program project with a few classes and Bootstrap4 JavaScript plugins. Using the card component, you can extend the default collapse behavior to create an accordion. </div> </div> </div> </div> </center></body> </html>",
"e": 22102,
"s": 13811,
"text": null
},
{
"code": null,
"e": 22110,
"s": 22102,
"text": "Output:"
},
{
"code": null,
"e": 22157,
"s": 22110,
"text": "Why do we use aria-expanded and aria-controls?"
},
{
"code": null,
"e": 23139,
"s": 22157,
"text": "Add aria-expanded to the control component. This quality unequivocally (explicitly) passes on the current state of the collapsible component tied to the control to screen perusers (readers) and comparable assistive technologies. On the off chance that the collapsible component is closed by default, the property on the control component ought to have a esteem of(set) aria-expanded=”false”. In the event that you’ve set the collapsible component to be open by default utilizing the show class, then set aria-expanded=”true” on the control instep. The plugin will consequently flip(toggle) this trait on the control based on whether or not the collapsible component has been opened or closed (by means of JavaScript, or since the client activated another control component too tied to the same collapsible component). On the off chance that the control element’s HTML component isn’t a button (e.g. an <a> or <div>), the attribute role=”button” should be included to the component."
},
{
"code": null,
"e": 23634,
"s": 23139,
"text": "On the off chance that your control component is focusing on a single collapsible component – i.e. the data-target attribute is indicating to an id selector – you ought to include the aria-controls attribute to the control component, containing the id of the collapsible component. Advanced screen perusers and comparative assistive advances(technologies) make utilize of this trait to supply clients with extra alternate routes to explore straightforwardly to the collapsible component itself."
},
{
"code": null,
"e": 23708,
"s": 23634,
"text": "We can use Collapse and Accordion via data attributes or via javascript. "
},
{
"code": null,
"e": 23818,
"s": 23708,
"text": "Through data attributes: The collapse plugin utilizes a number of classes to handle the overwhelming lifting:"
},
{
"code": null,
"e": 23850,
"s": 23818,
"text": ".collapse covers up the content"
},
{
"code": null,
"e": 23885,
"s": 23850,
"text": ".collapse.show appears the content"
},
{
"code": null,
"e": 23968,
"s": 23885,
"text": ".collapsing is included when the transition begins, and expelled when it wraps up."
},
{
"code": null,
"e": 24337,
"s": 23968,
"text": "Add data-toggle=”collapse” and a data-target to the component to naturally allot control of one or more collapsible components. The data-target attribute acknowledges a CSS selector to apply the collapse. Be beyond any doubt to include the class collapse to the collapsible component. On the off chance that you’d like it to default open, include the extra class show."
},
{
"code": null,
"e": 24469,
"s": 24337,
"text": "To include accordion-like gather administration to a collapsible range, include the information attribute data-parent=”#selector”. "
},
{
"code": null,
"e": 24489,
"s": 24469,
"text": "Through JavaScript:"
},
{
"code": null,
"e": 24516,
"s": 24489,
"text": "$('.collapse').collapse()\n"
},
{
"code": null,
"e": 24525,
"s": 24516,
"text": "Methods:"
},
{
"code": null,
"e": 24720,
"s": 24525,
"text": ".collapse(options): Enacts your content as a collapsible component. Acknowledges an optional alternatives object. Options are parent and toggle. Ex. $(‘#myCollapsible’).collapse({toggle: false})"
},
{
"code": null,
"e": 24798,
"s": 24720,
"text": ".collapse(‘toggle’): Flips a collapsible component to appeared or covered up."
},
{
"code": null,
"e": 24850,
"s": 24798,
"text": ".collapse(‘show’): Appears a collapsible component."
},
{
"code": null,
"e": 24904,
"s": 24850,
"text": ".collapse(‘hide’): Covers up a collapsible component."
},
{
"code": null,
"e": 24962,
"s": 24904,
"text": ".collapse(‘dispose’): Devastates an component’s collapse."
},
{
"code": null,
"e": 24974,
"s": 24962,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 24989,
"s": 24974,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 24996,
"s": 24989,
"text": "Picked"
},
{
"code": null,
"e": 25006,
"s": 24996,
"text": "Bootstrap"
},
{
"code": null,
"e": 25011,
"s": 25006,
"text": "HTML"
},
{
"code": null,
"e": 25028,
"s": 25011,
"text": "Web Technologies"
},
{
"code": null,
"e": 25055,
"s": 25028,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25060,
"s": 25055,
"text": "HTML"
},
{
"code": null,
"e": 25158,
"s": 25060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25199,
"s": 25158,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 25240,
"s": 25199,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 25303,
"s": 25240,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 25336,
"s": 25303,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 25383,
"s": 25336,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 25431,
"s": 25383,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25493,
"s": 25431,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25543,
"s": 25493,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25567,
"s": 25543,
"text": "REST API (Introduction)"
}
]
|
PyQt5 – How to change style and size of text Progress Bar ? | 22 Apr, 2020
In this article we will see how to change the font style and the size of data which is inside the progress bar. We can set the text in progress bar using setFormat method. In order to change the font and the size we will use setFont method which take QFont object as argument and font and size will be changes.
Syntax : bar.setFont(QFont(font_name, size))
Argument : It takes QFont object as argument.
Action performed : This will change the font and size of the text.
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar1 = QProgressBar(self) # setting geometry to progress bar bar1.setGeometry(200, 100, 200, 30) # setting the value bar1.setValue(70) # setting alignment to center bar1.setAlignment(Qt.AlignCenter) # setting font and the size bar1.setFont(QFont('Arial', 15)) # creating progress bar bar2 = QProgressBar(self) # setting geometry to progress bar bar2.setGeometry(200, 200, 200, 30) # setting the value bar2.setValue(20) # adding text using setFormat bar2.setFormat("Hello Geeks") # setting alignment to center bar2.setAlignment(Qt.AlignCenter) # setting font and the size bar2.setFont(QFont('Times', 7)) App = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "In this article we will see how to change the font style and the size of data which is inside the progress bar. We can set the text in progress bar using setFormat method. In order to change the font and the size we will use setFont method which take QFont object as argument and font and size will be changes."
},
{
"code": null,
"e": 384,
"s": 339,
"text": "Syntax : bar.setFont(QFont(font_name, size))"
},
{
"code": null,
"e": 430,
"s": 384,
"text": "Argument : It takes QFont object as argument."
},
{
"code": null,
"e": 497,
"s": 430,
"text": "Action performed : This will change the font and size of the text."
},
{
"code": null,
"e": 526,
"s": 497,
"text": "Below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar1 = QProgressBar(self) # setting geometry to progress bar bar1.setGeometry(200, 100, 200, 30) # setting the value bar1.setValue(70) # setting alignment to center bar1.setAlignment(Qt.AlignCenter) # setting font and the size bar1.setFont(QFont('Arial', 15)) # creating progress bar bar2 = QProgressBar(self) # setting geometry to progress bar bar2.setGeometry(200, 200, 200, 30) # setting the value bar2.setValue(20) # adding text using setFormat bar2.setFormat(\"Hello Geeks\") # setting alignment to center bar2.setAlignment(Qt.AlignCenter) # setting font and the size bar2.setFont(QFont('Times', 7)) App = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1972,
"s": 526,
"text": null
},
{
"code": null,
"e": 1981,
"s": 1972,
"text": "Output :"
},
{
"code": null,
"e": 1992,
"s": 1981,
"text": "Python-gui"
},
{
"code": null,
"e": 2004,
"s": 1992,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2011,
"s": 2004,
"text": "Python"
}
]
|
Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part 4 | 24 Jun, 2022
In Manacher’s Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. In Part 3, we implemented the same. Here we will review the four cases again and try to see it differently and implement the same. All four cases depends on LPS length value at currentLeftPosition (L[iMirror]) and value of (centerRightPosition – currentRightPosition), i.e. (R – i). These two information are know before which helps us to reuse previous available information and avoid unnecessary character comparison.
If we look at all four cases, we will see that we 1st set minimum of L[iMirror] and R-i to L[i] and then we try to expand the palindrome in whichever case it can expand.Above observation may look more intuitive, easier to understand and implement, given that one understands LPS length array, position, index, symmetry property etc.
Implementation:
C++
Java
Python3
C#
Javascript
// A C program to implement Manacher’s Algorithm#include <stdio.h>#include <string.h> char text[100];int min(int a, int b){ int res = a; if(b < a) res = b; return res;} void findLongestPalindromicString(){ int N = strlen(text); if(N == 0) return; N = 2*N + 1; //Position count int L[N]; //LPS Length Array L[0] = 0; L[1] = 1; int C = 1; //centerPosition int R = 2; //centerRightPosition int i = 0; //currentRightPosition int iMirror; //currentLeftPosition int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; //Uncomment it to print LPS Length array //printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { //get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i; L[i] = 0; diff = R - i; //If currentRightPosition i is within centerRightPosition R if(diff > 0) L[i] = min(L[iMirror], diff); //Attempt to expand palindrome centered at currentRightPosition i //Here for odd positions, we compare characters and //if match then increment LPS Length by ONE //If even position, we just increment LPS by ONE without //any character comparison while ( ((i + L[i]) < N && (i - L[i]) > 0) && ( ((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] ))) { L[i]++; } if(L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } //If palindrome centered at currentRightPosition i //expand beyond centerRightPosition R, //adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //printf("%d ", L[i]); } //printf("\n"); start = (maxLPSCenterPosition - maxLPSLength)/2; end = start + maxLPSLength - 1; printf("LPS of string is %s : ", text); for(i=start; i<=end; i++) printf("%c", text[i]); printf("\n");} int main(int argc, char *argv[]){ strcpy(text, "babcbabcbaccba"); findLongestPalindromicString(); strcpy(text, "abaaba"); findLongestPalindromicString(); strcpy(text, "abababa"); findLongestPalindromicString(); strcpy(text, "abcbabcbabcba"); findLongestPalindromicString(); strcpy(text, "forgeeksskeegfor"); findLongestPalindromicString(); strcpy(text, "caba"); findLongestPalindromicString(); strcpy(text, "abacdfgdcaba"); findLongestPalindromicString(); strcpy(text, "abacdfgdcabba"); findLongestPalindromicString(); strcpy(text, "abacdedcaba"); findLongestPalindromicString(); return 0;}
// Java program to implement Manacher's Algorithmimport java.util.*; class GFG{ static void findLongestPalindromicString(String text) { int N = text.length(); if (N == 0) return; N = 2 * N + 1; // Position count int[] L = new int[N + 1]; // LPS Length Array L[0] = 0; L[1] = 1; int C = 1; // centerPosition int R = 2; // centerRightPosition int i = 0; // currentRightPosition int iMirror; // currentLeftPosition int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; // Uncomment it to print LPS Length array // printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { // get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; L[i] = 0; diff = R - i; // If currentRightPosition i is within // centerRightPosition R if (diff > 0) L[i] = Math.min(L[iMirror], diff); // Attempt to expand palindrome centered at // currentRightPosition i. Here for odd positions, // we compare characters and if match then // increment LPS Length by ONE. If even position, // we just increment LPS by ONE without // any character comparison while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text.charAt((i + L[i] + 1) / 2) == text.charAt((i - L[i] - 1) / 2)))) { L[i]++; } if (L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } // Uncomment it to print LPS Length array // printf("%d ", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; System.out.printf("LPS of string is %s : ", text); for (i = start; i <= end; i++) System.out.print(text.charAt(i)); System.out.println(); } // Driver Code public static void main(String[] args) { String text = "babcbabcbaccba"; findLongestPalindromicString(text); text = "abaaba"; findLongestPalindromicString(text); text = "abababa"; findLongestPalindromicString(text); text = "abcbabcbabcba"; findLongestPalindromicString(text); text = "forgeeksskeegfor"; findLongestPalindromicString(text); text = "caba"; findLongestPalindromicString(text); text = "abacdfgdcaba"; findLongestPalindromicString(text); text = "abacdfgdcabba"; findLongestPalindromicString(text); text = "abacdedcaba"; findLongestPalindromicString(text); }} // This code is contributed by// sanjeev2552
# Python program to implement Manacher's Algorithm def findLongestPalindromicString(text): N = len(text) if N == 0: return N = 2*N+1 # Position count L = [0] * N L[0] = 0 L[1] = 1 C = 1 # centerPosition R = 2 # centerRightPosition i = 0 # currentRightPosition iMirror = 0 # currentLeftPosition maxLPSLength = 0 maxLPSCenterPosition = 0 start = -1 end = -1 diff = -1 # Uncomment it to print LPS Length array # printf("%d %d ", L[0], L[1]); for i in range(2,N): # get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i L[i] = 0 diff = R - i # If currentRightPosition i is within centerRightPosition R if diff > 0: L[i] = min(L[iMirror], diff) # Attempt to expand palindrome centered at currentRightPosition i # Here for odd positions, we compare characters and # if match then increment LPS Length by ONE # If even position, we just increment LPS by ONE without # any character comparison try: while ((i + L[i]) < N and (i - L[i]) > 0) and \ (((i + L[i] + 1) % 2 == 0) or \ (text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])): L[i]+=1 except Exception as e: pass if L[i] > maxLPSLength: # Track maxLPSLength maxLPSLength = L[i] maxLPSCenterPosition = i # If palindrome centered at currentRightPosition i # expand beyond centerRightPosition R, # adjust centerPosition C based on expanded palindrome. if i + L[i] > R: C = i R = i + L[i] # Uncomment it to print LPS Length array # printf("%d ", L[i]); start = (maxLPSCenterPosition - maxLPSLength) // 2 end = start + maxLPSLength - 1 print ("LPS of string is " + text + " : ",text[start:end+1]) # Driver programtext1 = "babcbabcbaccba"findLongestPalindromicString(text1) text2 = "abaaba"findLongestPalindromicString(text2) text3 = "abababa"findLongestPalindromicString(text3) text4 = "abcbabcbabcba"findLongestPalindromicString(text4) text5 = "forgeeksskeegfor"findLongestPalindromicString(text5) text6 = "caba"findLongestPalindromicString(text6) text7 = "abacdfgdcaba"findLongestPalindromicString(text7) text8 = "abacdfgdcabba"findLongestPalindromicString(text8) text9 = "abacdedcaba"findLongestPalindromicString(text9) # This code is contributed by BHAVYA JAIN
// C# program to implement Manacher's Algorithmusing System; class GFG{ static void findLongestPalindromicString(String text) { int N = text.Length; if (N == 0) return; N = 2 * N + 1; // Position count int[] L = new int[N + 1]; // LPS Length Array L[0] = 0; L[1] = 1; int C = 1; // centerPosition int R = 2; // centerRightPosition int i = 0; // currentRightPosition int iMirror; // currentLeftPosition int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; // Uncomment it to print LPS Length array // printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { // get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; L[i] = 0; diff = R - i; // If currentRightPosition i is within // centerRightPosition R if (diff > 0) L[i] = Math.Min(L[iMirror], diff); // Attempt to expand palindrome centered at // currentRightPosition i. Here for odd positions, // we compare characters and if match then // increment LPS Length by ONE. If even position, // we just increment LPS by ONE without // any character comparison while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2]))) { L[i]++; } if (L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } // Uncomment it to print LPS Length array // printf("%d ", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; Console.Write("LPS of string is {0} : ", text); for (i = start; i <= end; i++) Console.Write(text[i]); Console.WriteLine(); } // Driver Code public static void Main(String[] args) { String text = "babcbabcbaccba"; findLongestPalindromicString(text); text = "abaaba"; findLongestPalindromicString(text); text = "abababa"; findLongestPalindromicString(text); text = "abcbabcbabcba"; findLongestPalindromicString(text); text = "forgeeksskeegfor"; findLongestPalindromicString(text); text = "caba"; findLongestPalindromicString(text); text = "abacdfgdcaba"; findLongestPalindromicString(text); text = "abacdfgdcabba"; findLongestPalindromicString(text); text = "abacdedcaba"; findLongestPalindromicString(text); }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to implement Manacher's Algorithm function findLongestPalindromicString(text){ let N = text.length; if (N == 0) return; N = 2 * N + 1; // Position count let L = new Array(N + 1); // LPS Length Array L[0] = 0; L[1] = 1; let C = 1; // centerPosition let R = 2; // centerRightPosition let i = 0; // currentRightPosition let iMirror; // currentLeftPosition let maxLPSLength = 0; let maxLPSCenterPosition = 0; let start = -1; let end = -1; let diff = -1; // Uncomment it to print LPS Length array // printf("%d %d ", L[0], L[1]); for (i = 2; i < N; i++) { // get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; L[i] = 0; diff = R - i; // If currentRightPosition i is within // centerRightPosition R if (diff > 0) L[i] = Math.min(L[iMirror], diff); // Attempt to expand palindrome centered at // currentRightPosition i. Here for odd positions, // we compare characters and if match then // increment LPS Length by ONE. If even position, // we just increment LPS by ONE without // any character comparison while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[Math.floor((i + L[i] + 1) / 2)] == text[Math.floor((i - L[i] - 1) / 2)]))) { L[i]++; } if (L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } // Uncomment it to print LPS Length array // printf("%d ", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; document.write("LPS of string is "+text+" : "); for (i = start; i <= end; i++) document.write(text[i]); document.write("<br>");} // Driver Code let text = "babcbabcbaccba";findLongestPalindromicString(text); text = "abaaba";findLongestPalindromicString(text); text = "abababa";findLongestPalindromicString(text); text = "abcbabcbabcba";findLongestPalindromicString(text); text = "forgeeksskeegfor";findLongestPalindromicString(text); text = "caba";findLongestPalindromicString(text); text = "abacdfgdcaba";findLongestPalindromicString(text); text = "abacdfgdcabba";findLongestPalindromicString(text); text = "abacdedcaba";findLongestPalindromicString(text); // This code is contributed by unknown2108</script>
LPS of string is babcbabcbaccba : abcbabcba
LPS of string is abaaba : abaaba
LPS of string is abababa : abababa
LPS of string is abcbabcbabcba : abcbabcbabcba
LPS of string is forgeeksskeegfor : geeksskeeg
LPS of string is caba : aba
LPS of string is abacdfgdcaba : aba
LPS of string is abacdfgdcabba : abba
LPS of string is abacdedcaba : abacdedcaba
Time Complexity: O(n)Auxiliary Space: O(n)
Other Approaches:We have discussed two approaches here. One in Part 3 and other in current article. In both approaches, we worked on given string. Here we had to handle even and odd positions differently while comparing characters for expansion (because even positions do not represent any character in string).To avoid this different handling of even and odd positions, we need to make even positions also to represent some character (actually all even positions should represent SAME character because they MUST match while character comparison). One way to do this is to set some character at all even positions by modifying given string or create a new copy of given string. For example, if input string is “abcb”, new string should be “#a#b#c#b#” if we add # as unique character at even positions.The two approaches discussed already can be modified a bit to work on modified string where different handling of even and odd positions will not be needed. We may also add two DIFFERENT characters (not yet used anywhere in string at even and odd positions) at start and end of string as sentinels to avoid bound check. With these changes string “abcb” will look like “^#a#b#c#b#$” where ^ and $ are sentinels. This implementation may look cleaner with the cost of more memory.We are not implementing these here as it’s a simple change in given implementations.
Implementation of approach discussed in current article on a modified string can be found at Longest Palindromic Substring Part II and a Java Translation of the same by Princeton.
sanjeev2552
princiraj1992
unknown2108
amartyaghoshgfg
geekygirl2001
hardikkoriintern
palindrome
Pattern Searching
Strings
Strings
palindrome
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Check if an URL is valid or not using Regular Expression
Search a Word in a 2D Grid of characters
Naive algorithm for Pattern Searching
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 639,
"s": 54,
"text": "In Manacher’s Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. In Part 3, we implemented the same. Here we will review the four cases again and try to see it differently and implement the same. All four cases depends on LPS length value at currentLeftPosition (L[iMirror]) and value of (centerRightPosition – currentRightPosition), i.e. (R – i). These two information are know before which helps us to reuse previous available information and avoid unnecessary character comparison. "
},
{
"code": null,
"e": 973,
"s": 639,
"text": "If we look at all four cases, we will see that we 1st set minimum of L[iMirror] and R-i to L[i] and then we try to expand the palindrome in whichever case it can expand.Above observation may look more intuitive, easier to understand and implement, given that one understands LPS length array, position, index, symmetry property etc. "
},
{
"code": null,
"e": 989,
"s": 973,
"text": "Implementation:"
},
{
"code": null,
"e": 993,
"s": 989,
"text": "C++"
},
{
"code": null,
"e": 998,
"s": 993,
"text": "Java"
},
{
"code": null,
"e": 1006,
"s": 998,
"text": "Python3"
},
{
"code": null,
"e": 1009,
"s": 1006,
"text": "C#"
},
{
"code": null,
"e": 1020,
"s": 1009,
"text": "Javascript"
},
{
"code": "// A C program to implement Manacher’s Algorithm#include <stdio.h>#include <string.h> char text[100];int min(int a, int b){ int res = a; if(b < a) res = b; return res;} void findLongestPalindromicString(){ int N = strlen(text); if(N == 0) return; N = 2*N + 1; //Position count int L[N]; //LPS Length Array L[0] = 0; L[1] = 1; int C = 1; //centerPosition int R = 2; //centerRightPosition int i = 0; //currentRightPosition int iMirror; //currentLeftPosition int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; //Uncomment it to print LPS Length array //printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { //get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i; L[i] = 0; diff = R - i; //If currentRightPosition i is within centerRightPosition R if(diff > 0) L[i] = min(L[iMirror], diff); //Attempt to expand palindrome centered at currentRightPosition i //Here for odd positions, we compare characters and //if match then increment LPS Length by ONE //If even position, we just increment LPS by ONE without //any character comparison while ( ((i + L[i]) < N && (i - L[i]) > 0) && ( ((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] ))) { L[i]++; } if(L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } //If palindrome centered at currentRightPosition i //expand beyond centerRightPosition R, //adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } //Uncomment it to print LPS Length array //printf(\"%d \", L[i]); } //printf(\"\\n\"); start = (maxLPSCenterPosition - maxLPSLength)/2; end = start + maxLPSLength - 1; printf(\"LPS of string is %s : \", text); for(i=start; i<=end; i++) printf(\"%c\", text[i]); printf(\"\\n\");} int main(int argc, char *argv[]){ strcpy(text, \"babcbabcbaccba\"); findLongestPalindromicString(); strcpy(text, \"abaaba\"); findLongestPalindromicString(); strcpy(text, \"abababa\"); findLongestPalindromicString(); strcpy(text, \"abcbabcbabcba\"); findLongestPalindromicString(); strcpy(text, \"forgeeksskeegfor\"); findLongestPalindromicString(); strcpy(text, \"caba\"); findLongestPalindromicString(); strcpy(text, \"abacdfgdcaba\"); findLongestPalindromicString(); strcpy(text, \"abacdfgdcabba\"); findLongestPalindromicString(); strcpy(text, \"abacdedcaba\"); findLongestPalindromicString(); return 0;}",
"e": 3856,
"s": 1020,
"text": null
},
{
"code": "// Java program to implement Manacher's Algorithmimport java.util.*; class GFG{ static void findLongestPalindromicString(String text) { int N = text.length(); if (N == 0) return; N = 2 * N + 1; // Position count int[] L = new int[N + 1]; // LPS Length Array L[0] = 0; L[1] = 1; int C = 1; // centerPosition int R = 2; // centerRightPosition int i = 0; // currentRightPosition int iMirror; // currentLeftPosition int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; // Uncomment it to print LPS Length array // printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { // get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; L[i] = 0; diff = R - i; // If currentRightPosition i is within // centerRightPosition R if (diff > 0) L[i] = Math.min(L[iMirror], diff); // Attempt to expand palindrome centered at // currentRightPosition i. Here for odd positions, // we compare characters and if match then // increment LPS Length by ONE. If even position, // we just increment LPS by ONE without // any character comparison while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text.charAt((i + L[i] + 1) / 2) == text.charAt((i - L[i] - 1) / 2)))) { L[i]++; } if (L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } // Uncomment it to print LPS Length array // printf(\"%d \", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; System.out.printf(\"LPS of string is %s : \", text); for (i = start; i <= end; i++) System.out.print(text.charAt(i)); System.out.println(); } // Driver Code public static void main(String[] args) { String text = \"babcbabcbaccba\"; findLongestPalindromicString(text); text = \"abaaba\"; findLongestPalindromicString(text); text = \"abababa\"; findLongestPalindromicString(text); text = \"abcbabcbabcba\"; findLongestPalindromicString(text); text = \"forgeeksskeegfor\"; findLongestPalindromicString(text); text = \"caba\"; findLongestPalindromicString(text); text = \"abacdfgdcaba\"; findLongestPalindromicString(text); text = \"abacdfgdcabba\"; findLongestPalindromicString(text); text = \"abacdedcaba\"; findLongestPalindromicString(text); }} // This code is contributed by// sanjeev2552",
"e": 7156,
"s": 3856,
"text": null
},
{
"code": "# Python program to implement Manacher's Algorithm def findLongestPalindromicString(text): N = len(text) if N == 0: return N = 2*N+1 # Position count L = [0] * N L[0] = 0 L[1] = 1 C = 1 # centerPosition R = 2 # centerRightPosition i = 0 # currentRightPosition iMirror = 0 # currentLeftPosition maxLPSLength = 0 maxLPSCenterPosition = 0 start = -1 end = -1 diff = -1 # Uncomment it to print LPS Length array # printf(\"%d %d \", L[0], L[1]); for i in range(2,N): # get currentLeftPosition iMirror for currentRightPosition i iMirror = 2*C-i L[i] = 0 diff = R - i # If currentRightPosition i is within centerRightPosition R if diff > 0: L[i] = min(L[iMirror], diff) # Attempt to expand palindrome centered at currentRightPosition i # Here for odd positions, we compare characters and # if match then increment LPS Length by ONE # If even position, we just increment LPS by ONE without # any character comparison try: while ((i + L[i]) < N and (i - L[i]) > 0) and \\ (((i + L[i] + 1) % 2 == 0) or \\ (text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])): L[i]+=1 except Exception as e: pass if L[i] > maxLPSLength: # Track maxLPSLength maxLPSLength = L[i] maxLPSCenterPosition = i # If palindrome centered at currentRightPosition i # expand beyond centerRightPosition R, # adjust centerPosition C based on expanded palindrome. if i + L[i] > R: C = i R = i + L[i] # Uncomment it to print LPS Length array # printf(\"%d \", L[i]); start = (maxLPSCenterPosition - maxLPSLength) // 2 end = start + maxLPSLength - 1 print (\"LPS of string is \" + text + \" : \",text[start:end+1]) # Driver programtext1 = \"babcbabcbaccba\"findLongestPalindromicString(text1) text2 = \"abaaba\"findLongestPalindromicString(text2) text3 = \"abababa\"findLongestPalindromicString(text3) text4 = \"abcbabcbabcba\"findLongestPalindromicString(text4) text5 = \"forgeeksskeegfor\"findLongestPalindromicString(text5) text6 = \"caba\"findLongestPalindromicString(text6) text7 = \"abacdfgdcaba\"findLongestPalindromicString(text7) text8 = \"abacdfgdcabba\"findLongestPalindromicString(text8) text9 = \"abacdedcaba\"findLongestPalindromicString(text9) # This code is contributed by BHAVYA JAIN",
"e": 9674,
"s": 7156,
"text": null
},
{
"code": "// C# program to implement Manacher's Algorithmusing System; class GFG{ static void findLongestPalindromicString(String text) { int N = text.Length; if (N == 0) return; N = 2 * N + 1; // Position count int[] L = new int[N + 1]; // LPS Length Array L[0] = 0; L[1] = 1; int C = 1; // centerPosition int R = 2; // centerRightPosition int i = 0; // currentRightPosition int iMirror; // currentLeftPosition int maxLPSLength = 0; int maxLPSCenterPosition = 0; int start = -1; int end = -1; int diff = -1; // Uncomment it to print LPS Length array // printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { // get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; L[i] = 0; diff = R - i; // If currentRightPosition i is within // centerRightPosition R if (diff > 0) L[i] = Math.Min(L[iMirror], diff); // Attempt to expand palindrome centered at // currentRightPosition i. Here for odd positions, // we compare characters and if match then // increment LPS Length by ONE. If even position, // we just increment LPS by ONE without // any character comparison while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2]))) { L[i]++; } if (L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } // Uncomment it to print LPS Length array // printf(\"%d \", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; Console.Write(\"LPS of string is {0} : \", text); for (i = start; i <= end; i++) Console.Write(text[i]); Console.WriteLine(); } // Driver Code public static void Main(String[] args) { String text = \"babcbabcbaccba\"; findLongestPalindromicString(text); text = \"abaaba\"; findLongestPalindromicString(text); text = \"abababa\"; findLongestPalindromicString(text); text = \"abcbabcbabcba\"; findLongestPalindromicString(text); text = \"forgeeksskeegfor\"; findLongestPalindromicString(text); text = \"caba\"; findLongestPalindromicString(text); text = \"abacdfgdcaba\"; findLongestPalindromicString(text); text = \"abacdfgdcabba\"; findLongestPalindromicString(text); text = \"abacdedcaba\"; findLongestPalindromicString(text); }} // This code is contributed by PrinciRaj1992",
"e": 12940,
"s": 9674,
"text": null
},
{
"code": "<script>// Javascript program to implement Manacher's Algorithm function findLongestPalindromicString(text){ let N = text.length; if (N == 0) return; N = 2 * N + 1; // Position count let L = new Array(N + 1); // LPS Length Array L[0] = 0; L[1] = 1; let C = 1; // centerPosition let R = 2; // centerRightPosition let i = 0; // currentRightPosition let iMirror; // currentLeftPosition let maxLPSLength = 0; let maxLPSCenterPosition = 0; let start = -1; let end = -1; let diff = -1; // Uncomment it to print LPS Length array // printf(\"%d %d \", L[0], L[1]); for (i = 2; i < N; i++) { // get currentLeftPosition iMirror // for currentRightPosition i iMirror = 2 * C - i; L[i] = 0; diff = R - i; // If currentRightPosition i is within // centerRightPosition R if (diff > 0) L[i] = Math.min(L[iMirror], diff); // Attempt to expand palindrome centered at // currentRightPosition i. Here for odd positions, // we compare characters and if match then // increment LPS Length by ONE. If even position, // we just increment LPS by ONE without // any character comparison while (((i + L[i]) + 1 < N && (i - L[i]) > 0) && (((i + L[i] + 1) % 2 == 0) || (text[Math.floor((i + L[i] + 1) / 2)] == text[Math.floor((i - L[i] - 1) / 2)]))) { L[i]++; } if (L[i] > maxLPSLength) // Track maxLPSLength { maxLPSLength = L[i]; maxLPSCenterPosition = i; } // If palindrome centered at currentRightPosition i // expand beyond centerRightPosition R, // adjust centerPosition C based on expanded palindrome. if (i + L[i] > R) { C = i; R = i + L[i]; } // Uncomment it to print LPS Length array // printf(\"%d \", L[i]); } start = (maxLPSCenterPosition - maxLPSLength) / 2; end = start + maxLPSLength - 1; document.write(\"LPS of string is \"+text+\" : \"); for (i = start; i <= end; i++) document.write(text[i]); document.write(\"<br>\");} // Driver Code let text = \"babcbabcbaccba\";findLongestPalindromicString(text); text = \"abaaba\";findLongestPalindromicString(text); text = \"abababa\";findLongestPalindromicString(text); text = \"abcbabcbabcba\";findLongestPalindromicString(text); text = \"forgeeksskeegfor\";findLongestPalindromicString(text); text = \"caba\";findLongestPalindromicString(text); text = \"abacdfgdcaba\";findLongestPalindromicString(text); text = \"abacdfgdcabba\";findLongestPalindromicString(text); text = \"abacdedcaba\";findLongestPalindromicString(text); // This code is contributed by unknown2108</script>",
"e": 16018,
"s": 12940,
"text": null
},
{
"code": null,
"e": 16369,
"s": 16018,
"text": "LPS of string is babcbabcbaccba : abcbabcba\nLPS of string is abaaba : abaaba\nLPS of string is abababa : abababa\nLPS of string is abcbabcbabcba : abcbabcbabcba\nLPS of string is forgeeksskeegfor : geeksskeeg\nLPS of string is caba : aba\nLPS of string is abacdfgdcaba : aba\nLPS of string is abacdfgdcabba : abba\nLPS of string is abacdedcaba : abacdedcaba"
},
{
"code": null,
"e": 16412,
"s": 16369,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 17776,
"s": 16412,
"text": "Other Approaches:We have discussed two approaches here. One in Part 3 and other in current article. In both approaches, we worked on given string. Here we had to handle even and odd positions differently while comparing characters for expansion (because even positions do not represent any character in string).To avoid this different handling of even and odd positions, we need to make even positions also to represent some character (actually all even positions should represent SAME character because they MUST match while character comparison). One way to do this is to set some character at all even positions by modifying given string or create a new copy of given string. For example, if input string is “abcb”, new string should be “#a#b#c#b#” if we add # as unique character at even positions.The two approaches discussed already can be modified a bit to work on modified string where different handling of even and odd positions will not be needed. We may also add two DIFFERENT characters (not yet used anywhere in string at even and odd positions) at start and end of string as sentinels to avoid bound check. With these changes string “abcb” will look like “^#a#b#c#b#$” where ^ and $ are sentinels. This implementation may look cleaner with the cost of more memory.We are not implementing these here as it’s a simple change in given implementations."
},
{
"code": null,
"e": 17957,
"s": 17776,
"text": "Implementation of approach discussed in current article on a modified string can be found at Longest Palindromic Substring Part II and a Java Translation of the same by Princeton. "
},
{
"code": null,
"e": 17969,
"s": 17957,
"text": "sanjeev2552"
},
{
"code": null,
"e": 17983,
"s": 17969,
"text": "princiraj1992"
},
{
"code": null,
"e": 17995,
"s": 17983,
"text": "unknown2108"
},
{
"code": null,
"e": 18011,
"s": 17995,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 18025,
"s": 18011,
"text": "geekygirl2001"
},
{
"code": null,
"e": 18042,
"s": 18025,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 18053,
"s": 18042,
"text": "palindrome"
},
{
"code": null,
"e": 18071,
"s": 18053,
"text": "Pattern Searching"
},
{
"code": null,
"e": 18079,
"s": 18071,
"text": "Strings"
},
{
"code": null,
"e": 18087,
"s": 18079,
"text": "Strings"
},
{
"code": null,
"e": 18098,
"s": 18087,
"text": "palindrome"
},
{
"code": null,
"e": 18116,
"s": 18098,
"text": "Pattern Searching"
},
{
"code": null,
"e": 18214,
"s": 18116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18257,
"s": 18214,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 18299,
"s": 18257,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 18356,
"s": 18299,
"text": "Check if an URL is valid or not using Regular Expression"
},
{
"code": null,
"e": 18397,
"s": 18356,
"text": "Search a Word in a 2D Grid of characters"
},
{
"code": null,
"e": 18435,
"s": 18397,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 18481,
"s": 18435,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 18506,
"s": 18481,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 18566,
"s": 18506,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 18581,
"s": 18566,
"text": "C++ Data Types"
}
]
|
re.fullmatch() function in Python | 16 Mar, 2021
re.fullmatch() returns a match object if and only if the entire string matches the pattern. Otherwise, it will return None. The flag at the end is optional and can be used to ignore cases etc.
Syntax: re.fullmatch(pattern, string, flags=0)
Parameters:
pattern: the regular expression pattern that you want to match.
string: the string which you want to search for the pattern.
flags (optional argument): a more advanced modifier that allows you to customize the behavior of the function.
Example 1:
Python3
import re string = 'geeks'pattern = 'g...s' print(re.fullmatch(pattern, string))
<_sre.SRE_Match object; span=(0, 5), match='geeks'>
re.fullmatch() and re.match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. Both functions attempt to match at the beginning of the string. But the difference between re.match() and re.fullmatch() is that re.match() matches only at the beginning but re.fullmatch() tries to match at the end as well.
Example:
Python3
import re string = "Geeks for geeks"pattern = "Geeks" print(re.match(pattern, string))print(re.fullmatch(pattern, string))
<_sre.SRE_Match object; span=(0, 5), match='Geeks'>
None
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 222,
"s": 28,
"text": "re.fullmatch() returns a match object if and only if the entire string matches the pattern. Otherwise, it will return None. The flag at the end is optional and can be used to ignore cases etc. "
},
{
"code": null,
"e": 269,
"s": 222,
"text": "Syntax: re.fullmatch(pattern, string, flags=0)"
},
{
"code": null,
"e": 281,
"s": 269,
"text": "Parameters:"
},
{
"code": null,
"e": 345,
"s": 281,
"text": "pattern: the regular expression pattern that you want to match."
},
{
"code": null,
"e": 406,
"s": 345,
"text": "string: the string which you want to search for the pattern."
},
{
"code": null,
"e": 518,
"s": 406,
"text": "flags (optional argument): a more advanced modifier that allows you to customize the behavior of the function. "
},
{
"code": null,
"e": 529,
"s": 518,
"text": "Example 1:"
},
{
"code": null,
"e": 537,
"s": 529,
"text": "Python3"
},
{
"code": "import re string = 'geeks'pattern = 'g...s' print(re.fullmatch(pattern, string))",
"e": 622,
"s": 537,
"text": null
},
{
"code": null,
"e": 674,
"s": 622,
"text": "<_sre.SRE_Match object; span=(0, 5), match='geeks'>"
},
{
"code": null,
"e": 1042,
"s": 674,
"text": "re.fullmatch() and re.match() both are functions of re module in python. These functions are very efficient and fast for searching in strings. Both functions attempt to match at the beginning of the string. But the difference between re.match() and re.fullmatch() is that re.match() matches only at the beginning but re.fullmatch() tries to match at the end as well."
},
{
"code": null,
"e": 1051,
"s": 1042,
"text": "Example:"
},
{
"code": null,
"e": 1059,
"s": 1051,
"text": "Python3"
},
{
"code": "import re string = \"Geeks for geeks\"pattern = \"Geeks\" print(re.match(pattern, string))print(re.fullmatch(pattern, string))",
"e": 1186,
"s": 1059,
"text": null
},
{
"code": null,
"e": 1243,
"s": 1186,
"text": "<_sre.SRE_Match object; span=(0, 5), match='Geeks'>\nNone"
},
{
"code": null,
"e": 1256,
"s": 1243,
"text": "python-regex"
},
{
"code": null,
"e": 1263,
"s": 1256,
"text": "Python"
},
{
"code": null,
"e": 1361,
"s": 1263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1393,
"s": 1361,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1420,
"s": 1393,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1451,
"s": 1420,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1474,
"s": 1451,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1495,
"s": 1474,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1551,
"s": 1495,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1593,
"s": 1551,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1635,
"s": 1593,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1674,
"s": 1635,
"text": "Python | Get unique values from a list"
}
]
|
Different ways to convert String to Integer in C# | 05 Sep, 2019
Like other programming languages, in C# we can convert string to int. There are three ways to convert it and they are as follows:
Using the Parse Method
Using the TryParse Method
Using the Convert Method from (System.Convert class)
The input string can be anything like “10”, “10.10”, “10GeeksforGeeks”, “” (Your string can be number, a combination of characters or an Empty String).When a given string is number or floating-point number then we can use directly any of above-listed methods to convert it from string to int but the combination of characters and an empty string will throw an error which needs to catch using exceptional handling.
Here, we are calculating the area of a circle but the given input length is in string format and hence used Int32.Parse() method to convert the length from string to int (32-bit signed integer equivalent).
// C# program to convert string to // integer using Parse Methodusing System; namespace GeeksforGeeks { class GFG{ // Main Method public static void Main(string[] args) { // Taking a string string l = "10"; // using the Method int length = Int32.Parse(l); // Finding the area of a square int aofs = length * length; Console.WriteLine("Area of a circle is: {0}", aofs); }}}
Output:
Area of a circle is: 100
When we have a value greater than Integer: If you assign the value big value to string then it will through an OverflowException as int data type can’t handle the large values (It very much depends upon the range of data types).
string l="10000000000";
The output will be System.OverflowException: Value was either too large or too small for an Int32.
When we have Empty String: If you keep string blank then it will through an exception System Format Exception as the input is blank.
string l="";
The output will be: System.FormatException: Input string was not in a correct format.
Here, we have used TryParse() method, the difference in Parse() and TryParse() method is only that TryParse() method always return the value it will never throw an exception. If you closely look at the value of an input, then it clearly shows that it will throw an exception but TryParse() will never throw an exception. Hence the output is Zero.
// C# program to convert string to // integer using TryParse Methodusing System; namespace GeeksforGeeks { class GFG{ // Main Method public static void Main(string[] args) { // Taking a string string l = "10000000000"; int length = 0; // using the method Int32.TryParse(l, out length); // Finding the area of a square int aofs = length * length; Console.WriteLine("Area of a circle is: {0}", aofs); }}}
Output:
Area of a circle is: 0
Here, we have used Convert.ToInt32() method, the difference in Parse() and Convert.ToInt32() method is only that Convert.ToInt32() method always accept the null value return it. Hence the output is Zero. We have used exceptional handling in this example so, try block will throw the exception if occurred and catch block will accept the exception and write whatever exception occurred.
// C# program to convert string to // integer using Convert Methodusing System; namespace GeeksforGeeks { class GFG { // Main Method public static void Main(string[] args) { // Taking a string string l = null; try { int length = Convert.ToInt32(l); // Finding the area of a square int aofs = length * length; Console.WriteLine("Area of a circle is: {0}", aofs); } catch (Exception e) { Console.WriteLine("Unable to convert:Exception:" + e.Message); } }}}
Output:
Area of a circle is: 0
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Constructors
C# | Class and Object
C# | Replace() Method
Extension Method in C#
Difference between Ref and Out keywords in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "Like other programming languages, in C# we can convert string to int. There are three ways to convert it and they are as follows:"
},
{
"code": null,
"e": 181,
"s": 158,
"text": "Using the Parse Method"
},
{
"code": null,
"e": 207,
"s": 181,
"text": "Using the TryParse Method"
},
{
"code": null,
"e": 260,
"s": 207,
"text": "Using the Convert Method from (System.Convert class)"
},
{
"code": null,
"e": 675,
"s": 260,
"text": "The input string can be anything like “10”, “10.10”, “10GeeksforGeeks”, “” (Your string can be number, a combination of characters or an Empty String).When a given string is number or floating-point number then we can use directly any of above-listed methods to convert it from string to int but the combination of characters and an empty string will throw an error which needs to catch using exceptional handling."
},
{
"code": null,
"e": 881,
"s": 675,
"text": "Here, we are calculating the area of a circle but the given input length is in string format and hence used Int32.Parse() method to convert the length from string to int (32-bit signed integer equivalent)."
},
{
"code": "// C# program to convert string to // integer using Parse Methodusing System; namespace GeeksforGeeks { class GFG{ // Main Method public static void Main(string[] args) { // Taking a string string l = \"10\"; // using the Method int length = Int32.Parse(l); // Finding the area of a square int aofs = length * length; Console.WriteLine(\"Area of a circle is: {0}\", aofs); }}}",
"e": 1328,
"s": 881,
"text": null
},
{
"code": null,
"e": 1336,
"s": 1328,
"text": "Output:"
},
{
"code": null,
"e": 1362,
"s": 1336,
"text": "Area of a circle is: 100\n"
},
{
"code": null,
"e": 1591,
"s": 1362,
"text": "When we have a value greater than Integer: If you assign the value big value to string then it will through an OverflowException as int data type can’t handle the large values (It very much depends upon the range of data types)."
},
{
"code": null,
"e": 1615,
"s": 1591,
"text": "string l=\"10000000000\";"
},
{
"code": null,
"e": 1714,
"s": 1615,
"text": "The output will be System.OverflowException: Value was either too large or too small for an Int32."
},
{
"code": null,
"e": 1847,
"s": 1714,
"text": "When we have Empty String: If you keep string blank then it will through an exception System Format Exception as the input is blank."
},
{
"code": null,
"e": 1860,
"s": 1847,
"text": "string l=\"\";"
},
{
"code": null,
"e": 1946,
"s": 1860,
"text": "The output will be: System.FormatException: Input string was not in a correct format."
},
{
"code": null,
"e": 2293,
"s": 1946,
"text": "Here, we have used TryParse() method, the difference in Parse() and TryParse() method is only that TryParse() method always return the value it will never throw an exception. If you closely look at the value of an input, then it clearly shows that it will throw an exception but TryParse() will never throw an exception. Hence the output is Zero."
},
{
"code": "// C# program to convert string to // integer using TryParse Methodusing System; namespace GeeksforGeeks { class GFG{ // Main Method public static void Main(string[] args) { // Taking a string string l = \"10000000000\"; int length = 0; // using the method Int32.TryParse(l, out length); // Finding the area of a square int aofs = length * length; Console.WriteLine(\"Area of a circle is: {0}\", aofs); }}}",
"e": 2777,
"s": 2293,
"text": null
},
{
"code": null,
"e": 2785,
"s": 2777,
"text": "Output:"
},
{
"code": null,
"e": 2808,
"s": 2785,
"text": "Area of a circle is: 0"
},
{
"code": null,
"e": 3194,
"s": 2808,
"text": "Here, we have used Convert.ToInt32() method, the difference in Parse() and Convert.ToInt32() method is only that Convert.ToInt32() method always accept the null value return it. Hence the output is Zero. We have used exceptional handling in this example so, try block will throw the exception if occurred and catch block will accept the exception and write whatever exception occurred."
},
{
"code": "// C# program to convert string to // integer using Convert Methodusing System; namespace GeeksforGeeks { class GFG { // Main Method public static void Main(string[] args) { // Taking a string string l = null; try { int length = Convert.ToInt32(l); // Finding the area of a square int aofs = length * length; Console.WriteLine(\"Area of a circle is: {0}\", aofs); } catch (Exception e) { Console.WriteLine(\"Unable to convert:Exception:\" + e.Message); } }}}",
"e": 3781,
"s": 3194,
"text": null
},
{
"code": null,
"e": 3789,
"s": 3781,
"text": "Output:"
},
{
"code": null,
"e": 3813,
"s": 3789,
"text": "Area of a circle is: 0\n"
},
{
"code": null,
"e": 3827,
"s": 3813,
"text": "CSharp-string"
},
{
"code": null,
"e": 3830,
"s": 3827,
"text": "C#"
},
{
"code": null,
"e": 3928,
"s": 3830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3971,
"s": 3928,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4002,
"s": 3971,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4017,
"s": 4002,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4066,
"s": 4017,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4082,
"s": 4066,
"text": "C# | Data Types"
},
{
"code": null,
"e": 4100,
"s": 4082,
"text": "C# | Constructors"
},
{
"code": null,
"e": 4122,
"s": 4100,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 4144,
"s": 4122,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 4167,
"s": 4144,
"text": "Extension Method in C#"
}
]
|
Decode the string encoded with the given algorithm | 31 May, 2021
Given a decoded string str which was decoded with the following encoding algorithm: Write down the middle character of the string then delete it and repeat the process until there are no characters left. For example, “abba” will be encoded as “bbaa”. Note that the middle character is the first character of the two middle characters when the length of the string is even.Examples:
Input: "ofrsgkeeeekgs"
Output: geeksforgeeks
Input: str = "bbaa"
Output: abba
Approach: It can be observed that while decoding the string, the first letter of the encoded string becomes the median of the decoded string. So first, write the very first character of the encoded string and remove it from the encoded string then start adding the first character of the encoded string first to the left and then to the right of the decoded string and do this task repeatedly till the encoded string becomes empty.For example:
Encoded String Decoded String
ofrsgkeeeekgs o
frsgkeeeekgs fo
rsgkeeeekgs for
sgkeeeekgs sfor
gkeeeekgs sforg
keeeekgs ksforg
eeeekgs ksforge
eeekgs eksforge
eekgs eksforgee
ekgs eeksforgee
kgs eeksforgeek
gs geeksgorgeek
s geeksforgeeks
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to decode and print// the original stringvoid decodeStr(string str, int len){ // To store the decoded string char c[len] = ""; int med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = len / 2; else med = len / 2 - 1; // Storing the first element of the // string at the median position c[med] = str[0]; // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str[1]; // k represents the number of characters // that are already stored in the c[] if (len & 1) k = 1; else k = 2; for (int i = k; i < len; i += 2) { c[med - pos] = str[i]; // If string length is odd if (len % 2 == 1) c[med + pos] = str[i + 1]; // If it is even else c[med + pos + 1] = str[i + 1]; pos++; } // Print the decoded string for (int i = 0; i < len; i++) cout << c[i];} // Driver codeint main(){ string str = "ofrsgkeeeekgs"; int len = str.length(); decodeStr(str, len); return 0;}
// Java implementation of the approachclass GFG{ // Function to decode and print// the original Stringstatic void decodeStr(String str, int len){ // To store the decoded String char []c = new char[len]; int med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = len / 2; else med = len / 2 - 1; // Storing the first element of the // String at the median position c[med] = str.charAt(0); // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str.charAt(1); // k represents the number of characters // that are already stored in the c[] if (len % 2 == 1) k = 1; else k = 2; for(int i = k; i < len; i += 2) { c[med - pos] = str.charAt(i); // If String length is odd if (len % 2 == 1) c[med + pos] = str.charAt(i + 1); // If it is even else c[med + pos + 1] = str.charAt(i + 1); pos++; } // Print the decoded String for (int i = 0; i < len; i++) System.out.print(c[i]);} // Driver codepublic static void main(String[] args){ String str = "ofrsgkeeeekgs"; int len = str.length(); decodeStr(str, len);}} // This code is contributed by 29AjayKumar
# Python3 implementation of the# above approach # Function to decode and print# the original stringdef decodeStr(str, len): # To store the decoded string c = ["" for i in range(len)] pos = 1 # Getting the mid element if(len % 2 == 1): med = int(len / 2) else: med = int(len / 2 - 1) # Storing the first element # of the string at the # median position c[med] = str[0] # If the length is even # then store the second # element also if(len % 2 == 0): c[med + 1] = str[1] # k represents the number # of characters that are # already stored in the c[] if(len & 1): k = 1 else: k = 2 for i in range(k, len, 2): c[med - pos] = str[i] # If string length is odd if(len % 2 == 1): c[med + pos] = str[i + 1] # If it is even else: c[med + pos + 1] = str[i + 1] pos += 1 # Print the decoded string print(*c, sep = "") # Driver codestr = "ofrsgkeeeekgs"len = len(str)decodeStr(str, len) # This code is contributed by avanitrachhadiya2155
// C# implementation of the approachusing System; class GFG{ // Function to decode and print// the original Stringstatic void decodeStr(String str, int len){ // To store the decoded String char []c = new char[len]; int med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = len / 2; else med = len / 2 - 1; // Storing the first element of the // String at the median position c[med] = str[0]; // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str[1]; // k represents the number of characters // that are already stored in the c[] if (len % 2 == 1) k = 1; else k = 2; for(int i = k; i < len; i += 2) { c[med - pos] = str[i]; // If String length is odd if (len % 2 == 1) c[med + pos] = str[i + 1]; // If it is even else c[med + pos + 1] = str[i + 1]; pos++; } // Print the decoded String for(int i = 0; i < len; i++) Console.Write(c[i]);} // Driver codepublic static void Main(String[] args){ String str = "ofrsgkeeeekgs"; int len = str.Length; decodeStr(str, len);}} // This code is contributed by sapnasingh4991
<script> // JavaScript implementation of the approach // Function to decode and print// the original stringfunction decodeStr(str, len){ // To store the decoded string var c = Array(len).fill(""); var med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = parseInt(len / 2); else med = parseInt(len / 2) - 1; // Storing the first element of the // string at the median position c[med] = str[0]; // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str[1]; // k represents the number of characters // that are already stored in the c[] if (len & 1) k = 1; else k = 2; for (var i = k; i < len; i += 2) { c[med - pos] = str[i]; // If string length is odd if (len % 2 == 1) c[med + pos] = str[i + 1]; // If it is even else c[med + pos + 1] = str[i + 1]; pos++; } // Print the decoded string for (var i = 0; i < len; i++) { document.write(c[i]); }} // Driver codevar str = "ofrsgkeeeekgs";var len = str.length;decodeStr(str, len); </script>
geeksforgeeks
The Complexity: O(n)
29AjayKumar
sapnasingh4991
avanitrachhadiya2155
rutvik_56
encoding-decoding
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 435,
"s": 53,
"text": "Given a decoded string str which was decoded with the following encoding algorithm: Write down the middle character of the string then delete it and repeat the process until there are no characters left. For example, “abba” will be encoded as “bbaa”. Note that the middle character is the first character of the two middle characters when the length of the string is even.Examples:"
},
{
"code": null,
"e": 514,
"s": 435,
"text": "Input: \"ofrsgkeeeekgs\"\nOutput: geeksforgeeks\n\nInput: str = \"bbaa\"\nOutput: abba"
},
{
"code": null,
"e": 959,
"s": 514,
"text": "Approach: It can be observed that while decoding the string, the first letter of the encoded string becomes the median of the decoded string. So first, write the very first character of the encoded string and remove it from the encoded string then start adding the first character of the encoded string first to the left and then to the right of the decoded string and do this task repeatedly till the encoded string becomes empty.For example: "
},
{
"code": null,
"e": 1435,
"s": 959,
"text": "Encoded String Decoded String\nofrsgkeeeekgs o\nfrsgkeeeekgs fo\nrsgkeeeekgs for\nsgkeeeekgs sfor\ngkeeeekgs sforg\nkeeeekgs ksforg\neeeekgs ksforge\neeekgs eksforge\neekgs eksforgee\nekgs eeksforgee\nkgs eeksforgeek\ngs geeksgorgeek\ns geeksforgeeks "
},
{
"code": null,
"e": 1488,
"s": 1435,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1492,
"s": 1488,
"text": "C++"
},
{
"code": null,
"e": 1497,
"s": 1492,
"text": "Java"
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Python3"
},
{
"code": null,
"e": 1508,
"s": 1505,
"text": "C#"
},
{
"code": null,
"e": 1519,
"s": 1508,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to decode and print// the original stringvoid decodeStr(string str, int len){ // To store the decoded string char c[len] = \"\"; int med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = len / 2; else med = len / 2 - 1; // Storing the first element of the // string at the median position c[med] = str[0]; // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str[1]; // k represents the number of characters // that are already stored in the c[] if (len & 1) k = 1; else k = 2; for (int i = k; i < len; i += 2) { c[med - pos] = str[i]; // If string length is odd if (len % 2 == 1) c[med + pos] = str[i + 1]; // If it is even else c[med + pos + 1] = str[i + 1]; pos++; } // Print the decoded string for (int i = 0; i < len; i++) cout << c[i];} // Driver codeint main(){ string str = \"ofrsgkeeeekgs\"; int len = str.length(); decodeStr(str, len); return 0;}",
"e": 2710,
"s": 1519,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to decode and print// the original Stringstatic void decodeStr(String str, int len){ // To store the decoded String char []c = new char[len]; int med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = len / 2; else med = len / 2 - 1; // Storing the first element of the // String at the median position c[med] = str.charAt(0); // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str.charAt(1); // k represents the number of characters // that are already stored in the c[] if (len % 2 == 1) k = 1; else k = 2; for(int i = k; i < len; i += 2) { c[med - pos] = str.charAt(i); // If String length is odd if (len % 2 == 1) c[med + pos] = str.charAt(i + 1); // If it is even else c[med + pos + 1] = str.charAt(i + 1); pos++; } // Print the decoded String for (int i = 0; i < len; i++) System.out.print(c[i]);} // Driver codepublic static void main(String[] args){ String str = \"ofrsgkeeeekgs\"; int len = str.length(); decodeStr(str, len);}} // This code is contributed by 29AjayKumar",
"e": 4003,
"s": 2710,
"text": null
},
{
"code": "# Python3 implementation of the# above approach # Function to decode and print# the original stringdef decodeStr(str, len): # To store the decoded string c = [\"\" for i in range(len)] pos = 1 # Getting the mid element if(len % 2 == 1): med = int(len / 2) else: med = int(len / 2 - 1) # Storing the first element # of the string at the # median position c[med] = str[0] # If the length is even # then store the second # element also if(len % 2 == 0): c[med + 1] = str[1] # k represents the number # of characters that are # already stored in the c[] if(len & 1): k = 1 else: k = 2 for i in range(k, len, 2): c[med - pos] = str[i] # If string length is odd if(len % 2 == 1): c[med + pos] = str[i + 1] # If it is even else: c[med + pos + 1] = str[i + 1] pos += 1 # Print the decoded string print(*c, sep = \"\") # Driver codestr = \"ofrsgkeeeekgs\"len = len(str)decodeStr(str, len) # This code is contributed by avanitrachhadiya2155",
"e": 5103,
"s": 4003,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to decode and print// the original Stringstatic void decodeStr(String str, int len){ // To store the decoded String char []c = new char[len]; int med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = len / 2; else med = len / 2 - 1; // Storing the first element of the // String at the median position c[med] = str[0]; // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str[1]; // k represents the number of characters // that are already stored in the c[] if (len % 2 == 1) k = 1; else k = 2; for(int i = k; i < len; i += 2) { c[med - pos] = str[i]; // If String length is odd if (len % 2 == 1) c[med + pos] = str[i + 1]; // If it is even else c[med + pos + 1] = str[i + 1]; pos++; } // Print the decoded String for(int i = 0; i < len; i++) Console.Write(c[i]);} // Driver codepublic static void Main(String[] args){ String str = \"ofrsgkeeeekgs\"; int len = str.Length; decodeStr(str, len);}} // This code is contributed by sapnasingh4991",
"e": 6370,
"s": 5103,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to decode and print// the original stringfunction decodeStr(str, len){ // To store the decoded string var c = Array(len).fill(\"\"); var med, pos = 1, k; // Getting the mid element if (len % 2 == 1) med = parseInt(len / 2); else med = parseInt(len / 2) - 1; // Storing the first element of the // string at the median position c[med] = str[0]; // If the length is even then store // the second element also if (len % 2 == 0) c[med + 1] = str[1]; // k represents the number of characters // that are already stored in the c[] if (len & 1) k = 1; else k = 2; for (var i = k; i < len; i += 2) { c[med - pos] = str[i]; // If string length is odd if (len % 2 == 1) c[med + pos] = str[i + 1]; // If it is even else c[med + pos + 1] = str[i + 1]; pos++; } // Print the decoded string for (var i = 0; i < len; i++) { document.write(c[i]); }} // Driver codevar str = \"ofrsgkeeeekgs\";var len = str.length;decodeStr(str, len); </script>",
"e": 7542,
"s": 6370,
"text": null
},
{
"code": null,
"e": 7556,
"s": 7542,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 7580,
"s": 7558,
"text": "The Complexity: O(n) "
},
{
"code": null,
"e": 7592,
"s": 7580,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7607,
"s": 7592,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 7628,
"s": 7607,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 7638,
"s": 7628,
"text": "rutvik_56"
},
{
"code": null,
"e": 7656,
"s": 7638,
"text": "encoding-decoding"
},
{
"code": null,
"e": 7664,
"s": 7656,
"text": "Strings"
},
{
"code": null,
"e": 7672,
"s": 7664,
"text": "Strings"
}
]
|
Python – Itertools.cycle() | 19 Feb, 2020
Iterator is defined as object types which contains values that can be accessed or iterated using a loop. There are different iterators that come built-in with Python such as lists, sets, etc. Itertools is the Python module that contains some inbuilt functions for generating sequences using iterators. This module provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
There are different types of Iterators
Infinite Iterators: These type of iterators produce infinite sequences.Short sequence iterators: These iterators produces the sequences which terminate after certain iterations.Combinatorics generator functions: These generators produce the sequences in combinations related to the input arguments.
Infinite Iterators: These type of iterators produce infinite sequences.
Short sequence iterators: These iterators produces the sequences which terminate after certain iterations.
Combinatorics generator functions: These generators produce the sequences in combinations related to the input arguments.
The Function takes only one argument as input it can be like list, String, tuple, etc
The Function returns the iterator object type
In the implementation of the function the return type is yield which suspends the function execution without destroying the local variables. It is used by the generators which produce intermediate results
It iterates through each element in the input argument and yields it and repeats the cycle and produces an infinite sequence of the argument
The below-mentioned Python program illustrates the functioning of the cycle function. It takes string type as an argument and produces the infinite sequence.
import itertools # String for sequence generationInputstring ="Geeks" # Calling the function Cycle from# itertools and passing string as #an argument and the function returns# the iterator objectStringBuffer = itertools.cycle(Inputstring)SequenceRepeation = 0SequenceStart = 0SequenceEnd = len(Inputstring) for output in StringBuffer: if(SequenceStart == 0): print("Sequence % d"%(SequenceRepeation + 1)) # Cycle function iterates through each # element and produces the sequence # and repeats it the sequence print(output, end =" ") # Checks the End of the Sequence according # to the give input argument if(SequenceStart == SequenceEnd-1): if(SequenceRepeation>= 2): break else: SequenceRepeation+= 1 SequenceStart = 0 print("\n") else: SequenceStart+= 1
Output:
Sequence 1
G e e k s
Sequence 2
G e e k s
Sequence 3
G e e k s
The itertools.cycle function also works with the Python Lists. The below-mentioned Python program illustrates the functioning. It takes the Python list as an argument and produces the infinite sequence.
import itertools # List for sequence generationInputlist = [1, 2, 3] # Calling the function Cycle from# itertools and passing list as # an argument and the function # returns the iterator objectListBuffer = itertools.cycle(Inputlist)SequenceRepeation = 0SequenceStart = 0SequenceEnd = len(Inputlist) for output in ListBuffer: if(SequenceStart == 0): print("Sequence % d"%(SequenceRepeation + 1)) # Cycle function iterates through # each element and produces the # sequence and repeats it the sequence print(output, end =" ") # Checks the End of the Sequence according # to the give input argument if(SequenceStart == SequenceEnd-1): if(SequenceRepeation>= 2): break else: SequenceRepeation+= 1 SequenceStart = 0 print("\n") else: SequenceStart+= 1
Output:
Sequence 1
1 2 3
Sequence 2
1 2 3
Sequence 3
1 2 3
Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 575,
"s": 52,
"text": "Iterator is defined as object types which contains values that can be accessed or iterated using a loop. There are different iterators that come built-in with Python such as lists, sets, etc. Itertools is the Python module that contains some inbuilt functions for generating sequences using iterators. This module provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra."
},
{
"code": null,
"e": 614,
"s": 575,
"text": "There are different types of Iterators"
},
{
"code": null,
"e": 913,
"s": 614,
"text": "Infinite Iterators: These type of iterators produce infinite sequences.Short sequence iterators: These iterators produces the sequences which terminate after certain iterations.Combinatorics generator functions: These generators produce the sequences in combinations related to the input arguments."
},
{
"code": null,
"e": 985,
"s": 913,
"text": "Infinite Iterators: These type of iterators produce infinite sequences."
},
{
"code": null,
"e": 1092,
"s": 985,
"text": "Short sequence iterators: These iterators produces the sequences which terminate after certain iterations."
},
{
"code": null,
"e": 1214,
"s": 1092,
"text": "Combinatorics generator functions: These generators produce the sequences in combinations related to the input arguments."
},
{
"code": null,
"e": 1300,
"s": 1214,
"text": "The Function takes only one argument as input it can be like list, String, tuple, etc"
},
{
"code": null,
"e": 1346,
"s": 1300,
"text": "The Function returns the iterator object type"
},
{
"code": null,
"e": 1551,
"s": 1346,
"text": "In the implementation of the function the return type is yield which suspends the function execution without destroying the local variables. It is used by the generators which produce intermediate results"
},
{
"code": null,
"e": 1692,
"s": 1551,
"text": "It iterates through each element in the input argument and yields it and repeats the cycle and produces an infinite sequence of the argument"
},
{
"code": null,
"e": 1850,
"s": 1692,
"text": "The below-mentioned Python program illustrates the functioning of the cycle function. It takes string type as an argument and produces the infinite sequence."
},
{
"code": "import itertools # String for sequence generationInputstring =\"Geeks\" # Calling the function Cycle from# itertools and passing string as #an argument and the function returns# the iterator objectStringBuffer = itertools.cycle(Inputstring)SequenceRepeation = 0SequenceStart = 0SequenceEnd = len(Inputstring) for output in StringBuffer: if(SequenceStart == 0): print(\"Sequence % d\"%(SequenceRepeation + 1)) # Cycle function iterates through each # element and produces the sequence # and repeats it the sequence print(output, end =\" \") # Checks the End of the Sequence according # to the give input argument if(SequenceStart == SequenceEnd-1): if(SequenceRepeation>= 2): break else: SequenceRepeation+= 1 SequenceStart = 0 print(\"\\n\") else: SequenceStart+= 1",
"e": 2727,
"s": 1850,
"text": null
},
{
"code": null,
"e": 2735,
"s": 2727,
"text": "Output:"
},
{
"code": null,
"e": 2806,
"s": 2735,
"text": "Sequence 1\nG e e k s \n\nSequence 2\nG e e k s \n\nSequence 3\nG e e k s\n"
},
{
"code": null,
"e": 3009,
"s": 2806,
"text": "The itertools.cycle function also works with the Python Lists. The below-mentioned Python program illustrates the functioning. It takes the Python list as an argument and produces the infinite sequence."
},
{
"code": "import itertools # List for sequence generationInputlist = [1, 2, 3] # Calling the function Cycle from# itertools and passing list as # an argument and the function # returns the iterator objectListBuffer = itertools.cycle(Inputlist)SequenceRepeation = 0SequenceStart = 0SequenceEnd = len(Inputlist) for output in ListBuffer: if(SequenceStart == 0): print(\"Sequence % d\"%(SequenceRepeation + 1)) # Cycle function iterates through # each element and produces the # sequence and repeats it the sequence print(output, end =\" \") # Checks the End of the Sequence according # to the give input argument if(SequenceStart == SequenceEnd-1): if(SequenceRepeation>= 2): break else: SequenceRepeation+= 1 SequenceStart = 0 print(\"\\n\") else: SequenceStart+= 1",
"e": 3877,
"s": 3009,
"text": null
},
{
"code": null,
"e": 3885,
"s": 3877,
"text": "Output:"
},
{
"code": null,
"e": 3945,
"s": 3885,
"text": "Sequence 1\n1 2 3 \n\nSequence 2\n1 2 3 \n\nSequence 3\n1 2 3 \n"
},
{
"code": null,
"e": 3962,
"s": 3945,
"text": "Python-itertools"
},
{
"code": null,
"e": 3969,
"s": 3962,
"text": "Python"
},
{
"code": null,
"e": 4067,
"s": 3969,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4085,
"s": 4067,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4127,
"s": 4085,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4149,
"s": 4127,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4184,
"s": 4149,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4210,
"s": 4184,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4242,
"s": 4210,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4271,
"s": 4242,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4298,
"s": 4271,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4328,
"s": 4298,
"text": "Iterate over a list in Python"
}
]
|
Special Keys in Selenium Python | 23 Aug, 2021
Selenium’s Python Module is built to perform automated testing with Python. Special Keys is an exclusive feature of Selenium in python, that allows pressing keys through keyboard such as ctrl+f, or shift+c+v, etc. class selenium.webdriver.common.keys.Keys handles all Keys in Selenium Python. It contains huge number of key methods one can use in Selenium Python.
To demonstrate, Special Keys, let’s use key_up method of Action Chains in Selenium Python. This bot visits https://www.geeksforgeeks.org/ and press ctrl+f to open search bar.Program –
Python3
# import webdriverfrom selenium import webdriver # import Action chainsfrom selenium.webdriver.common.action_chains import ActionChains # import KEYSfrom selenium.webdriver.common.keys import Keys # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # create action chain objectaction = ActionChains(driver) # perform the operationaction.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perform()
Output –
Various keys that can be used in Selenium Python are –
varshagumber28
surinderdawra388
surindertarika1234
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 393,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Special Keys is an exclusive feature of Selenium in python, that allows pressing keys through keyboard such as ctrl+f, or shift+c+v, etc. class selenium.webdriver.common.keys.Keys handles all Keys in Selenium Python. It contains huge number of key methods one can use in Selenium Python. "
},
{
"code": null,
"e": 579,
"s": 393,
"text": "To demonstrate, Special Keys, let’s use key_up method of Action Chains in Selenium Python. This bot visits https://www.geeksforgeeks.org/ and press ctrl+f to open search bar.Program – "
},
{
"code": null,
"e": 587,
"s": 579,
"text": "Python3"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chainsfrom selenium.webdriver.common.action_chains import ActionChains # import KEYSfrom selenium.webdriver.common.keys import Keys # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # create action chain objectaction = ActionChains(driver) # perform the operationaction.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perform()",
"e": 1063,
"s": 587,
"text": null
},
{
"code": null,
"e": 1074,
"s": 1063,
"text": "Output – "
},
{
"code": null,
"e": 1133,
"s": 1076,
"text": "Various keys that can be used in Selenium Python are – "
},
{
"code": null,
"e": 1150,
"s": 1135,
"text": "varshagumber28"
},
{
"code": null,
"e": 1167,
"s": 1150,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1186,
"s": 1167,
"text": "surindertarika1234"
},
{
"code": null,
"e": 1202,
"s": 1186,
"text": "Python-selenium"
},
{
"code": null,
"e": 1211,
"s": 1202,
"text": "selenium"
},
{
"code": null,
"e": 1218,
"s": 1211,
"text": "Python"
},
{
"code": null,
"e": 1316,
"s": 1218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1334,
"s": 1316,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1376,
"s": 1334,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1398,
"s": 1376,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1430,
"s": 1398,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1456,
"s": 1430,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1485,
"s": 1456,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1512,
"s": 1485,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1533,
"s": 1512,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1556,
"s": 1533,
"text": "Introduction To PYTHON"
}
]
|
How to copy files into a directory in C#? | To Copy a file, C# provides a method File. Copy
File. Copy has 2 overloads
Copy(String, String) -Copies an existing file to a new file. Overwriting a file of the same name is not allowed.
Copy(String, String, Boolean) Copies an existing file to a new file. Overwriting a file of the same name is allowed.
Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories.
static void Main (string[] args) {
string rootPath = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1";
var searchSourceFolder = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly);
Console.WriteLine("-------------Source Folder-------------");
foreach (string file in searchSourceFolder){
Console.WriteLine(file);
}
string destinationFolder = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\";
var destinationFolderFiles = Directory.GetFiles(destinationFolder, "*.*", SearchOption.TopDirectoryOnly);
Console.WriteLine("-------------Destination Folder Before Copying-------------");
foreach (string file in destinationFolderFiles){
Console.WriteLine(file);
}
string[] files = Directory.GetFiles(rootPath);
foreach (string file in files){
File.Copy(file, $"{destinationFolder}{ Path.GetFileName(file) }");
}
Console.WriteLine("-------------After Copying-------------");
var destinationFolderAfterCopyingFiles = Directory.GetFiles(destinationFolder, "*.*", SearchOption.TopDirectoryOnly);
foreach (string file in destinationFolderAfterCopyingFiles){
Console.WriteLine(file);
}
Console.ReadLine ();
}
-------------Source Folder-------------
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1\TestFolderMain1.txt
-------------Destination Folder Before Copying-------------
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt
-------------After Copying-------------
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain1.txt
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt | [
{
"code": null,
"e": 1235,
"s": 1187,
"text": "To Copy a file, C# provides a method File. Copy"
},
{
"code": null,
"e": 1262,
"s": 1235,
"text": "File. Copy has 2 overloads"
},
{
"code": null,
"e": 1375,
"s": 1262,
"text": "Copy(String, String) -Copies an existing file to a new file. Overwriting a file of the same name is not allowed."
},
{
"code": null,
"e": 1492,
"s": 1375,
"text": "Copy(String, String, Boolean) Copies an existing file to a new file. Overwriting a file of the same name is allowed."
},
{
"code": null,
"e": 1651,
"s": 1492,
"text": "Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories."
},
{
"code": null,
"e": 2865,
"s": 1651,
"text": "static void Main (string[] args) {\n string rootPath = @\"C:\\Users\\Koushik\\Desktop\\TestFolder\\TestFolderMain1\";\n\n var searchSourceFolder = Directory.GetFiles(rootPath, \"*.*\", SearchOption.TopDirectoryOnly);\n Console.WriteLine(\"-------------Source Folder-------------\");\n foreach (string file in searchSourceFolder){\n Console.WriteLine(file);\n }\n\n string destinationFolder = @\"C:\\Users\\Koushik\\Desktop\\TestFolder\\TestFolderMain2\\\";\n\n var destinationFolderFiles = Directory.GetFiles(destinationFolder, \"*.*\", SearchOption.TopDirectoryOnly);\n Console.WriteLine(\"-------------Destination Folder Before Copying-------------\");\n foreach (string file in destinationFolderFiles){\n Console.WriteLine(file);\n }\n\n string[] files = Directory.GetFiles(rootPath);\n\n foreach (string file in files){\n File.Copy(file, $\"{destinationFolder}{ Path.GetFileName(file) }\");\n }\n Console.WriteLine(\"-------------After Copying-------------\");\n\n var destinationFolderAfterCopyingFiles = Directory.GetFiles(destinationFolder, \"*.*\", SearchOption.TopDirectoryOnly);\n\n foreach (string file in destinationFolderAfterCopyingFiles){\n Console.WriteLine(file);\n }\n Console.ReadLine ();\n}"
},
{
"code": null,
"e": 3293,
"s": 2865,
"text": "-------------Source Folder-------------\nC:\\Users\\Koushik\\Desktop\\TestFolder\\TestFolderMain1\\TestFolderMain1.txt\n-------------Destination Folder Before Copying-------------\nC:\\Users\\Koushik\\Desktop\\TestFolder\\TestFolderMain2\\TestFolderMain2.txt\n-------------After Copying-------------\nC:\\Users\\Koushik\\Desktop\\TestFolder\\TestFolderMain2\\TestFolderMain1.txt\nC:\\Users\\Koushik\\Desktop\\TestFolder\\TestFolderMain2\\TestFolderMain2.txt"
}
]
|
Number of pairs with Pandigital Concatenation | 13 Jun, 2022
A pair of strings when concatenated is said to be a ‘Pandigital Concatenation’ if their concatenation consists of all digits from (0 – 9) in any order at least once.The task is, given N strings, compute the number of pairs resulting in a ‘Pandigital Concatenation’.
Examples:
Input : num[] = {"123567", "098234", "14765", "19804"}
Output : 3
The pairs, 1st and 2nd giving
(123567098234),1st and 4rd giving(12356719804) and
2nd and 3rd giving (09823414765),
on concatenation result in Pandigital Concatenations.
Input : num[] = {"56789", "098345", "1234"}
Output : 0
None of the pairs on concatenation result in Pandigital
Concatenations.
Method 1 (Brute Force): A possible brute-force solution is to form all possible concatenations by forming all pairs in O(n2 and using a frequency array for digits (0 – 9), we check if each digit exists at least once in each concatenation formed for every pair.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find all// Pandigital concatenations// of two strings.#include <bits/stdc++.h>using namespace std; // Checks if a given// string is Pandigitalbool isPanDigital(string s){ bool digits[10] = {false}; for (int i = 0; i < s.length(); i++) digits[s[i] - '0'] = true; // digit i is not present // thus not pandigital for (int i = 0; i <= 9; i++) if (digits[i] == false) return false; return true;} // Returns number of pairs// of strings resulting in// Pandigital Concatenationsint countPandigitalPairs(vector<string> &v){ // iterate over all // pair of strings int pairs = 0; for (int i = 0; i < v.size(); i++) for (int j = i + 1; j < v.size(); j++) if (isPanDigital(v[i] + v[j])) pairs++; return pairs;} // Driver codeint main(){ vector<string> v = {"123567", "098234", "14765", "19804"}; cout << countPandigitalPairs(v) << endl; return 0;}
// Java program to find all// Pandigital concatenations// of two strings.import java.io.*;import java.util.*; class GFG{ static ArrayList<String> v = new ArrayList<String>(); // Checks if a given // string is Pandigital static int isPanDigital(String s) { int digits[] = new int[10]; for (int i = 0; i < s.length(); i++) digits[s.charAt(i) - (int)'0'] = 1; // digit i is not present // thus not pandigital for (int i = 0; i <= 9; i++) if (digits[i] == 0) return 0; return 1; } // Returns number of pairs // of strings resulting in // Pandigital Concatenations static int countPandigitalPairs() { // iterate over all // pair of strings int pairs = 0; for (int i = 0; i < v.size(); i++) for (int j = i + 1; j < v.size(); j++) if (isPanDigital(v.get(i) + v.get(j)) == 1) pairs++; return pairs; } // Driver code public static void main(String args[]) { v.add("123567"); v.add("098234"); v.add("14765"); v.add("19804"); System.out.print(countPandigitalPairs()); }} // This code is contributed// by Manish Shaw(manishshaw1)
# Python3 program to find all# Pandigital concatenations# of two strings. # Checks if a given# is Pandigitaldef isPanDigital(s) : digits = [False] * 10; for i in range(0, len(s)) : digits[int(s[i]) - int('0')] = True # digit i is not present # thus not pandigital for i in range(0, 10) : if (digits[i] == False) : return False return True # Returns number of pairs# of strings resulting in# Pandigital Concatenationsdef countPandigitalPairs(v) : # iterate over all # pair of strings pairs = 0 for i in range(0, len(v)) : for j in range (i + 1, len(v)) : if (isPanDigital(v[i] + v[j])) : pairs = pairs + 1 return pairs # Driver codev = ["123567", "098234", "14765", "19804"] print (countPandigitalPairs(v)) # This code is contributed by# Manish Shaw(manishshaw1)
// C# program to find all Pandigital// concatenations of two strings.using System;using System.Collections.Generic; class GFG{ // Checks if a given // string is Pandigital static int isPanDigital(string s) { int []digits = new int[10]; Array.Clear(digits, 0, 10); for (int i = 0; i < s.Length; i++) digits[s[i] - (int)'0'] = 1; // digit i is not present // thus not pandigital for (int i = 0; i <= 9; i++) if (digits[i] == 0) return 0; return 1; } // Returns number of pairs // of strings resulting in // Pandigital Concatenations static int countPandigitalPairs(ref List<string> v) { // iterate over all // pair of strings int pairs = 0; for (int i = 0; i < v.Count; i++) for (int j = i + 1; j < v.Count; j++) if (isPanDigital(v[i] + v[j]) == 1) pairs++; return pairs; } // Driver code static void Main() { List<string> v = new List<string>{"123567", "098234", "14765", "19804"}; Console.WriteLine(countPandigitalPairs(ref v)); }} // This code is contributed// by Manish Shaw(manishshaw1)
<?php// PHP program to find all// Pandigital concatenations// of two strings. // Checks if a given// $is Pandigitalfunction isPanDigital($s){ $digits = array(); $digits = array_fill(0, 10, false); for ($i = 0; $i < strlen($s); $i++) $digits[ord($s[$i]) - ord('0')] = true; // digit i is not present // thus not pandigital for ($i = 0; $i <= 9; $i++) if ($digits[$i] == false) return false; return true;} // Returns number of pairs// of strings resulting in// Pandigital Concatenationsfunction countPandigitalPairs(&$v){ // iterate over all // pair of strings $pairs = 0; for ($i = 0; $i < count($v); $i++) { for ($j = $i + 1; $j < count($v); $j++) { if (isPanDigital($v[$i].$v[$j])) { $pairs++; } } } return $pairs;} // Driver code$v = array("123567", "098234", "14765", "19804"); echo (countPandigitalPairs($v)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // Javascript program to find all// Pandigital concatenations// of two strings. // Checks if a given// is Pandigitalfunction isPanDigital(s){ let digits = new Array(10).fill(false); for(let i = 0; i < s.length; i++) digits[s[i].charCodeAt(0) - '0'.charCodeAt(0)] = true; // digit i is not present // thus not pandigital for(let i = 0; i <= 9; i++) if (digits[i] == false) return false; return true;} // Returns number of pairs// of strings resulting in// Pandigital Concatenationsfunction countPandigitalPairs(v){ // Iterate over all // pair of strings let pairs = 0; for(let i = 0; i < v.length; i++) { for(let j = i + 1; j < v.length; j++) { if (isPanDigital(v[i] + v[j])) { pairs++; } } } return pairs;} // Driver codelet v = [ "123567", "098234", "14765", "19804" ]; document.write(countPandigitalPairs(v)); // This code is contributed by gfgking </script>
Output:
3
Method 2 (Efficient): Now we look for something better than the brute-force discussed above. Careful analysis suggests that, for every digit 0 – 9 to be present we have a mask as 1111111111 (i.e. all numbers 0-9 exist in the array of numbers
Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask - 1 1 1 1 1 1 1 1 1 1
Here 1 denotes that the corresponding digits
exists at-least once thus for all such Pandigital
Concatenations, this relationship should hold.
So we can represent 11...11 as a valid mask for
pandigital concatenations.
So now the approach is to represent every string as a mask of 10 bits where the ith bit is set if the ith digit exists in the string.
E.g., "11405" can be represented as
Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask for 11405 - 1 1 0 0 1 1 0 0 0 0
The approach though may look complete is still not efficient as we still have to iterate over all pairs and check if the OR of these two strings results in the mask of a valid Pandigital Concatenation.
If we analyze the possible masks of all possible strings we can understand that every single string would be only comprised of digits 0 – 9, so every number can at max contain all digits 0 to 9 at least once thus the mask of such a number would be 1111111111 (1023 in decimal). Thus, in the decimal system all masks exit in (0 – 1023].
Now we just have to maintain a frequency array to store the number of times a mask exists in the array of strings.
Let two masks be i and j with frequencies freqi and freqj respectively,If (i OR j) = Maskpandigital concatenation Then, Number of Pairs = freqi * freqj
C++
Java
Python3
C#
Javascript
// C++ program to count PanDigital pairs#include <bits/stdc++.h>using namespace std; const int pandigitalMask = ((1 << 10) - 1); void computeMaskFrequencies(vector<string> v, map<int, int>& freq){ for (int i = 0; i < v.size(); i++) { int mask = 0; // Stores digits present in string v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) unordered_set<int> digits; for (int j = 0; j < v[i].size(); j++) digits.insert(v[i][j] - '0'); // Calculate the mask by considering all digits // existing atleast once for (auto it = digits.begin(); it != digits.end(); it++) { int digit = (*it); mask += (1 << digit); } // Increment the frequency of this mask freq[mask]++; }} // Returns number of pairs of strings resulting// in Pandigital Concatenationsint pandigitalConcatenations(map<int, int> freq){ int ans = 0; // All possible strings lie between 1 and 1023 // so we iterate over every possible mask for (int i = 1; i <= 1023; i++) { for (int j = 1; j <= 1023; j++) { // if the concatenation results in mask of // Pandigital Concatenation, calculate all // pairs formed with Masks i and j if ((i | j) == pandigitalMask) { if (i == j) ans += (freq[i] * (freq[i] - 1)); else ans += (freq[i] * freq[j]); } } } // since every pair is considers twice, // we get rid of half of these return ans/2;} int countPandigitalPairs(vector<string> v){ // Find frequencies of all masks in // given vector of strings map<int, int> freq; computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codeint main(){ vector<string> v = {"123567", "098234", "14765", "19804"}; cout << countPandigitalPairs(v) << endl; return 0;}
// Java program to count PanDigital pairsimport java.util.*; class GFG{ static int pandigitalMask = ((1 << 10) - 1); static void computeMaskFrequencies(Vector<String> v, HashMap<Integer, Integer> freq){ for(int i = 0; i < v.size(); i++) { int mask = 0; // Stores digits present in String v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) HashSet<Integer> digits = new HashSet<>(); for(int j = 0; j < v.get(i).length(); j++) digits.add(v.get(i).charAt(j) - '0'); // Calculate the mask by considering // all digits existing atleast once for(int it :digits) { int digit = (it); mask += (1 << digit); } // Increment the frequency of // this mask if (freq.containsKey(mask)) { freq.put(mask, freq.get(mask) + 1); } else { freq.put(mask, 1); } }} // Returns number of pairs of Strings// resulting in Pandigital Concatenationsstatic int pandigitalConcatenations( HashMap<Integer, Integer> freq){ int ans = 0; // All possible Strings lie between // 1 and 1023 so we iterate over every // possible mask for(int i = 1; i <= 1023; i++) { for(int j = 1; j <= 1023; j++) { // If the concatenation results in mask of // Pandigital Concatenation, calculate all // pairs formed with Masks i and j if ((i | j) == pandigitalMask && freq.containsKey(j) && freq.containsKey(i)) { if (i == j) ans += (freq.get(i) * (freq.get(i) - 1)); else ans += (freq.get(i) * freq.get(j)); } } } // Since every pair is considers twice, // we get rid of half of these return ans / 2;} static int countPandigitalPairs(Vector<String> v){ // Find frequencies of all masks in // given vector of Strings HashMap<Integer,Integer> freq = new HashMap<>(); computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codepublic static void main(String[] args){ Vector<String> v = new Vector<>(); v.add("123567"); v.add("098234"); v.add("14765"); v.add("19804"); System.out.print(countPandigitalPairs(v) + "\n");}} // This code is contributed by Amit Katiyar
# Python program to count PanDigital pairspandigitalMask = ((1 << 10) - 1)freq = dict() def computeMaskFrequencies(v): global freq for i in range(len(v)): mask = 0 # Stores digits present in string v[i] # atleast once. We use a set as we only # need digits which exist only once # (irrespective of reputation) digits = set() for j in range(len(v[i])): digits.add(int(v[i][j])) # Calculate the mask by considering # all digits existing atleast once for it in digits: digit = it mask += (1 << digit) # Increment the frequency of this mask if mask in freq: freq[mask] += 1 else: freq[mask] = 1 # Returns number of pairs of strings resulting# in Pandigital Concatenationsdef pandigitalConcatenations(): global freq ans = 0 # All possible strings lie between 1 and 1023 # so we iterate over every possible mask for i in range(1, 1024): for j in range(1, 1024): # if the concatenation results in mask of # Pandigital Concatenation, calculate all # pairs formed with Masks i and j if ((i | j) == pandigitalMask and i in freq and j in freq): if (i == j): ans += (freq[i] * (freq[i] - 1)) else: ans += (freq[i] * freq[j]) # Since every pair is considers twice, # we get rid of half of these return ans // 2 def countPandigitalPairs(v): # Find frequencies of all masks in # given vector of strings computeMaskFrequencies(v) # Return all possible concatenations. return pandigitalConcatenations() # Driver codev = ["123567", "098234", "14765", "19804"]print(countPandigitalPairs(v)) # This code is contributed by phasing17
// C# program to count// PanDigital pairsusing System;using System.Collections.Generic;class GFG{ static int pandigitalMask = ((1 << 10) - 1); static void computeMaskFrequencies(List<String> v, Dictionary<int, int> freq){ for(int i = 0; i < v.Count; i++) { int mask = 0; // Stores digits present in String v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) HashSet<int> digits = new HashSet<int>(); for(int j = 0; j < v[i].Length; j++) digits.Add(v[i][j] - '0'); // Calculate the mask by considering // all digits existing atleast once foreach(int it in digits) { int digit = (it); mask += (1 << digit); } // Increment the frequency of // this mask if (freq.ContainsKey(mask)) { freq[mask]++; } else { freq.Add(mask, 1); } }} // Returns number of pairs of// Strings resulting in Pandigital// Concatenationsstatic int pandigitalConcatenations(Dictionary<int, int> freq){ int ans = 0; // All possible Strings lie between // 1 and 1023 so we iterate over every // possible mask for(int i = 1; i <= 1023; i++) { for(int j = 1; j <= 1023; j++) { // If the concatenation results in // mask of Pandigital Concatenation, // calculate all pairs formed with // Masks i and j if ((i | j) == pandigitalMask && freq.ContainsKey(j) && freq.ContainsKey(i)) { if (i == j) ans += (freq[i] * (freq[i] - 1)); else ans += (freq[i] * freq[j]); } } } // Since every pair is considers // twice, we get rid of half of // these return ans / 2;} static int countPandigitalPairs(List<String> v){ // Find frequencies of all masks in // given vector of Strings Dictionary<int, int> freq = new Dictionary<int, int>(); computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codepublic static void Main(String[] args){ List<String> v = new List<String>(); v.Add("123567"); v.Add("098234"); v.Add("14765"); v.Add("19804"); Console.Write(countPandigitalPairs(v) + "\n");}} // This code is contributed by 29AjayKumar
<script> // Javascript program to count PanDigital pairsconst pandigitalMask = ((1 << 10) - 1); function computeMaskFrequencies(v, freq){ for(let i = 0; i < v.length; i++) { let mask = 0; // Stores digits present in string v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) let digits = new Set(); for(let j = 0; j < v[i].length; j++) digits.add((v[i][j]).charCodeAt(0) - '0'.charCodeAt(0)); // Calculate the mask by considering // all digits existing atleast once for(let it of digits) { let digit = it; mask += (1 << digit); } // Increment the frequency of this mask if (freq.has(mask)) { freq.set(mask, freq.get(mask) + 1) } else { freq.set(mask, 1) } }} // Returns number of pairs of strings resulting// in Pandigital Concatenationsfunction pandigitalConcatenations(freq){ let ans = 0; // All possible strings lie between 1 and 1023 // so we iterate over every possible mask for(let i = 1; i <= 1023; i++) { for(let j = 1; j <= 1023; j++) { // if the concatenation results in mask of // Pandigital Concatenation, calculate all // pairs formed with Masks i and j if ((i | j) == pandigitalMask && freq.has(i) && freq.has(j)) { if (i == j) ans += (freq.get(i) * (freq.get(i) - 1)); else ans += (freq.get(i) * freq.get(j)); } } } // Since every pair is considers twice, // we get rid of half of these return Math.floor(ans / 2);} function countPandigitalPairs(v){ // Find frequencies of all masks in // given vector of strings let freq = new Map(); computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codelet v = [ "123567", "098234", "14765", "19804" ];document.write(countPandigitalPairs(v) + "<br>"); // This code is contributed by gfgking </script>
Output:
3
Complexity : O(N * |s| + 1023 * 1023) where |s| gives length of strings in the array
manishshaw1
amit143katiyar
29AjayKumar
gfgking
surinderdawra388
phasing17
cpp-unordered_set
cpp-vector
Bit Magic
Strings
Technical Scripter
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 321,
"s": 54,
"text": "A pair of strings when concatenated is said to be a ‘Pandigital Concatenation’ if their concatenation consists of all digits from (0 – 9) in any order at least once.The task is, given N strings, compute the number of pairs resulting in a ‘Pandigital Concatenation’. "
},
{
"code": null,
"e": 332,
"s": 321,
"text": "Examples: "
},
{
"code": null,
"e": 701,
"s": 332,
"text": "Input : num[] = {\"123567\", \"098234\", \"14765\", \"19804\"}\nOutput : 3\nThe pairs, 1st and 2nd giving \n(123567098234),1st and 4rd giving(12356719804) and \n2nd and 3rd giving (09823414765),\non concatenation result in Pandigital Concatenations. \n\nInput : num[] = {\"56789\", \"098345\", \"1234\"}\nOutput : 0\nNone of the pairs on concatenation result in Pandigital \nConcatenations."
},
{
"code": null,
"e": 963,
"s": 701,
"text": "Method 1 (Brute Force): A possible brute-force solution is to form all possible concatenations by forming all pairs in O(n2 and using a frequency array for digits (0 – 9), we check if each digit exists at least once in each concatenation formed for every pair. "
},
{
"code": null,
"e": 967,
"s": 963,
"text": "C++"
},
{
"code": null,
"e": 972,
"s": 967,
"text": "Java"
},
{
"code": null,
"e": 980,
"s": 972,
"text": "Python3"
},
{
"code": null,
"e": 983,
"s": 980,
"text": "C#"
},
{
"code": null,
"e": 987,
"s": 983,
"text": "PHP"
},
{
"code": null,
"e": 998,
"s": 987,
"text": "Javascript"
},
{
"code": "// C++ program to find all// Pandigital concatenations// of two strings.#include <bits/stdc++.h>using namespace std; // Checks if a given// string is Pandigitalbool isPanDigital(string s){ bool digits[10] = {false}; for (int i = 0; i < s.length(); i++) digits[s[i] - '0'] = true; // digit i is not present // thus not pandigital for (int i = 0; i <= 9; i++) if (digits[i] == false) return false; return true;} // Returns number of pairs// of strings resulting in// Pandigital Concatenationsint countPandigitalPairs(vector<string> &v){ // iterate over all // pair of strings int pairs = 0; for (int i = 0; i < v.size(); i++) for (int j = i + 1; j < v.size(); j++) if (isPanDigital(v[i] + v[j])) pairs++; return pairs;} // Driver codeint main(){ vector<string> v = {\"123567\", \"098234\", \"14765\", \"19804\"}; cout << countPandigitalPairs(v) << endl; return 0;}",
"e": 1978,
"s": 998,
"text": null
},
{
"code": "// Java program to find all// Pandigital concatenations// of two strings.import java.io.*;import java.util.*; class GFG{ static ArrayList<String> v = new ArrayList<String>(); // Checks if a given // string is Pandigital static int isPanDigital(String s) { int digits[] = new int[10]; for (int i = 0; i < s.length(); i++) digits[s.charAt(i) - (int)'0'] = 1; // digit i is not present // thus not pandigital for (int i = 0; i <= 9; i++) if (digits[i] == 0) return 0; return 1; } // Returns number of pairs // of strings resulting in // Pandigital Concatenations static int countPandigitalPairs() { // iterate over all // pair of strings int pairs = 0; for (int i = 0; i < v.size(); i++) for (int j = i + 1; j < v.size(); j++) if (isPanDigital(v.get(i) + v.get(j)) == 1) pairs++; return pairs; } // Driver code public static void main(String args[]) { v.add(\"123567\"); v.add(\"098234\"); v.add(\"14765\"); v.add(\"19804\"); System.out.print(countPandigitalPairs()); }} // This code is contributed// by Manish Shaw(manishshaw1)",
"e": 3378,
"s": 1978,
"text": null
},
{
"code": "# Python3 program to find all# Pandigital concatenations# of two strings. # Checks if a given# is Pandigitaldef isPanDigital(s) : digits = [False] * 10; for i in range(0, len(s)) : digits[int(s[i]) - int('0')] = True # digit i is not present # thus not pandigital for i in range(0, 10) : if (digits[i] == False) : return False return True # Returns number of pairs# of strings resulting in# Pandigital Concatenationsdef countPandigitalPairs(v) : # iterate over all # pair of strings pairs = 0 for i in range(0, len(v)) : for j in range (i + 1, len(v)) : if (isPanDigital(v[i] + v[j])) : pairs = pairs + 1 return pairs # Driver codev = [\"123567\", \"098234\", \"14765\", \"19804\"] print (countPandigitalPairs(v)) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 4318,
"s": 3378,
"text": null
},
{
"code": "// C# program to find all Pandigital// concatenations of two strings.using System;using System.Collections.Generic; class GFG{ // Checks if a given // string is Pandigital static int isPanDigital(string s) { int []digits = new int[10]; Array.Clear(digits, 0, 10); for (int i = 0; i < s.Length; i++) digits[s[i] - (int)'0'] = 1; // digit i is not present // thus not pandigital for (int i = 0; i <= 9; i++) if (digits[i] == 0) return 0; return 1; } // Returns number of pairs // of strings resulting in // Pandigital Concatenations static int countPandigitalPairs(ref List<string> v) { // iterate over all // pair of strings int pairs = 0; for (int i = 0; i < v.Count; i++) for (int j = i + 1; j < v.Count; j++) if (isPanDigital(v[i] + v[j]) == 1) pairs++; return pairs; } // Driver code static void Main() { List<string> v = new List<string>{\"123567\", \"098234\", \"14765\", \"19804\"}; Console.WriteLine(countPandigitalPairs(ref v)); }} // This code is contributed// by Manish Shaw(manishshaw1)",
"e": 5594,
"s": 4318,
"text": null
},
{
"code": "<?php// PHP program to find all// Pandigital concatenations// of two strings. // Checks if a given// $is Pandigitalfunction isPanDigital($s){ $digits = array(); $digits = array_fill(0, 10, false); for ($i = 0; $i < strlen($s); $i++) $digits[ord($s[$i]) - ord('0')] = true; // digit i is not present // thus not pandigital for ($i = 0; $i <= 9; $i++) if ($digits[$i] == false) return false; return true;} // Returns number of pairs// of strings resulting in// Pandigital Concatenationsfunction countPandigitalPairs(&$v){ // iterate over all // pair of strings $pairs = 0; for ($i = 0; $i < count($v); $i++) { for ($j = $i + 1; $j < count($v); $j++) { if (isPanDigital($v[$i].$v[$j])) { $pairs++; } } } return $pairs;} // Driver code$v = array(\"123567\", \"098234\", \"14765\", \"19804\"); echo (countPandigitalPairs($v)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 6652,
"s": 5594,
"text": null
},
{
"code": "<script> // Javascript program to find all// Pandigital concatenations// of two strings. // Checks if a given// is Pandigitalfunction isPanDigital(s){ let digits = new Array(10).fill(false); for(let i = 0; i < s.length; i++) digits[s[i].charCodeAt(0) - '0'.charCodeAt(0)] = true; // digit i is not present // thus not pandigital for(let i = 0; i <= 9; i++) if (digits[i] == false) return false; return true;} // Returns number of pairs// of strings resulting in// Pandigital Concatenationsfunction countPandigitalPairs(v){ // Iterate over all // pair of strings let pairs = 0; for(let i = 0; i < v.length; i++) { for(let j = i + 1; j < v.length; j++) { if (isPanDigital(v[i] + v[j])) { pairs++; } } } return pairs;} // Driver codelet v = [ \"123567\", \"098234\", \"14765\", \"19804\" ]; document.write(countPandigitalPairs(v)); // This code is contributed by gfgking </script>",
"e": 7702,
"s": 6652,
"text": null
},
{
"code": null,
"e": 7711,
"s": 7702,
"text": "Output: "
},
{
"code": null,
"e": 7713,
"s": 7711,
"text": "3"
},
{
"code": null,
"e": 7955,
"s": 7713,
"text": "Method 2 (Efficient): Now we look for something better than the brute-force discussed above. Careful analysis suggests that, for every digit 0 – 9 to be present we have a mask as 1111111111 (i.e. all numbers 0-9 exist in the array of numbers"
},
{
"code": null,
"e": 8292,
"s": 7955,
"text": "Digits - 0 1 2 3 4 5 6 7 8 9\n | | | | | | | | | |\nMask - 1 1 1 1 1 1 1 1 1 1 \n\nHere 1 denotes that the corresponding digits\nexists at-least once thus for all such Pandigital \nConcatenations, this relationship should hold.\nSo we can represent 11...11 as a valid mask for\npandigital concatenations."
},
{
"code": null,
"e": 8427,
"s": 8292,
"text": "So now the approach is to represent every string as a mask of 10 bits where the ith bit is set if the ith digit exists in the string. "
},
{
"code": null,
"e": 8607,
"s": 8427,
"text": "E.g., \"11405\" can be represented as\nDigits - 0 1 2 3 4 5 6 7 8 9\n | | | | | | | | | |\nMask for 11405 - 1 1 0 0 1 1 0 0 0 0"
},
{
"code": null,
"e": 8810,
"s": 8607,
"text": "The approach though may look complete is still not efficient as we still have to iterate over all pairs and check if the OR of these two strings results in the mask of a valid Pandigital Concatenation. "
},
{
"code": null,
"e": 9147,
"s": 8810,
"text": "If we analyze the possible masks of all possible strings we can understand that every single string would be only comprised of digits 0 – 9, so every number can at max contain all digits 0 to 9 at least once thus the mask of such a number would be 1111111111 (1023 in decimal). Thus, in the decimal system all masks exit in (0 – 1023]. "
},
{
"code": null,
"e": 9262,
"s": 9147,
"text": "Now we just have to maintain a frequency array to store the number of times a mask exists in the array of strings."
},
{
"code": null,
"e": 9416,
"s": 9262,
"text": "Let two masks be i and j with frequencies freqi and freqj respectively,If (i OR j) = Maskpandigital concatenation Then, Number of Pairs = freqi * freqj "
},
{
"code": null,
"e": 9420,
"s": 9416,
"text": "C++"
},
{
"code": null,
"e": 9425,
"s": 9420,
"text": "Java"
},
{
"code": null,
"e": 9433,
"s": 9425,
"text": "Python3"
},
{
"code": null,
"e": 9436,
"s": 9433,
"text": "C#"
},
{
"code": null,
"e": 9447,
"s": 9436,
"text": "Javascript"
},
{
"code": "// C++ program to count PanDigital pairs#include <bits/stdc++.h>using namespace std; const int pandigitalMask = ((1 << 10) - 1); void computeMaskFrequencies(vector<string> v, map<int, int>& freq){ for (int i = 0; i < v.size(); i++) { int mask = 0; // Stores digits present in string v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) unordered_set<int> digits; for (int j = 0; j < v[i].size(); j++) digits.insert(v[i][j] - '0'); // Calculate the mask by considering all digits // existing atleast once for (auto it = digits.begin(); it != digits.end(); it++) { int digit = (*it); mask += (1 << digit); } // Increment the frequency of this mask freq[mask]++; }} // Returns number of pairs of strings resulting// in Pandigital Concatenationsint pandigitalConcatenations(map<int, int> freq){ int ans = 0; // All possible strings lie between 1 and 1023 // so we iterate over every possible mask for (int i = 1; i <= 1023; i++) { for (int j = 1; j <= 1023; j++) { // if the concatenation results in mask of // Pandigital Concatenation, calculate all // pairs formed with Masks i and j if ((i | j) == pandigitalMask) { if (i == j) ans += (freq[i] * (freq[i] - 1)); else ans += (freq[i] * freq[j]); } } } // since every pair is considers twice, // we get rid of half of these return ans/2;} int countPandigitalPairs(vector<string> v){ // Find frequencies of all masks in // given vector of strings map<int, int> freq; computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codeint main(){ vector<string> v = {\"123567\", \"098234\", \"14765\", \"19804\"}; cout << countPandigitalPairs(v) << endl; return 0;}",
"e": 11563,
"s": 9447,
"text": null
},
{
"code": "// Java program to count PanDigital pairsimport java.util.*; class GFG{ static int pandigitalMask = ((1 << 10) - 1); static void computeMaskFrequencies(Vector<String> v, HashMap<Integer, Integer> freq){ for(int i = 0; i < v.size(); i++) { int mask = 0; // Stores digits present in String v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) HashSet<Integer> digits = new HashSet<>(); for(int j = 0; j < v.get(i).length(); j++) digits.add(v.get(i).charAt(j) - '0'); // Calculate the mask by considering // all digits existing atleast once for(int it :digits) { int digit = (it); mask += (1 << digit); } // Increment the frequency of // this mask if (freq.containsKey(mask)) { freq.put(mask, freq.get(mask) + 1); } else { freq.put(mask, 1); } }} // Returns number of pairs of Strings// resulting in Pandigital Concatenationsstatic int pandigitalConcatenations( HashMap<Integer, Integer> freq){ int ans = 0; // All possible Strings lie between // 1 and 1023 so we iterate over every // possible mask for(int i = 1; i <= 1023; i++) { for(int j = 1; j <= 1023; j++) { // If the concatenation results in mask of // Pandigital Concatenation, calculate all // pairs formed with Masks i and j if ((i | j) == pandigitalMask && freq.containsKey(j) && freq.containsKey(i)) { if (i == j) ans += (freq.get(i) * (freq.get(i) - 1)); else ans += (freq.get(i) * freq.get(j)); } } } // Since every pair is considers twice, // we get rid of half of these return ans / 2;} static int countPandigitalPairs(Vector<String> v){ // Find frequencies of all masks in // given vector of Strings HashMap<Integer,Integer> freq = new HashMap<>(); computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codepublic static void main(String[] args){ Vector<String> v = new Vector<>(); v.add(\"123567\"); v.add(\"098234\"); v.add(\"14765\"); v.add(\"19804\"); System.out.print(countPandigitalPairs(v) + \"\\n\");}} // This code is contributed by Amit Katiyar",
"e": 14212,
"s": 11563,
"text": null
},
{
"code": "# Python program to count PanDigital pairspandigitalMask = ((1 << 10) - 1)freq = dict() def computeMaskFrequencies(v): global freq for i in range(len(v)): mask = 0 # Stores digits present in string v[i] # atleast once. We use a set as we only # need digits which exist only once # (irrespective of reputation) digits = set() for j in range(len(v[i])): digits.add(int(v[i][j])) # Calculate the mask by considering # all digits existing atleast once for it in digits: digit = it mask += (1 << digit) # Increment the frequency of this mask if mask in freq: freq[mask] += 1 else: freq[mask] = 1 # Returns number of pairs of strings resulting# in Pandigital Concatenationsdef pandigitalConcatenations(): global freq ans = 0 # All possible strings lie between 1 and 1023 # so we iterate over every possible mask for i in range(1, 1024): for j in range(1, 1024): # if the concatenation results in mask of # Pandigital Concatenation, calculate all # pairs formed with Masks i and j if ((i | j) == pandigitalMask and i in freq and j in freq): if (i == j): ans += (freq[i] * (freq[i] - 1)) else: ans += (freq[i] * freq[j]) # Since every pair is considers twice, # we get rid of half of these return ans // 2 def countPandigitalPairs(v): # Find frequencies of all masks in # given vector of strings computeMaskFrequencies(v) # Return all possible concatenations. return pandigitalConcatenations() # Driver codev = [\"123567\", \"098234\", \"14765\", \"19804\"]print(countPandigitalPairs(v)) # This code is contributed by phasing17",
"e": 16069,
"s": 14212,
"text": null
},
{
"code": "// C# program to count// PanDigital pairsusing System;using System.Collections.Generic;class GFG{ static int pandigitalMask = ((1 << 10) - 1); static void computeMaskFrequencies(List<String> v, Dictionary<int, int> freq){ for(int i = 0; i < v.Count; i++) { int mask = 0; // Stores digits present in String v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) HashSet<int> digits = new HashSet<int>(); for(int j = 0; j < v[i].Length; j++) digits.Add(v[i][j] - '0'); // Calculate the mask by considering // all digits existing atleast once foreach(int it in digits) { int digit = (it); mask += (1 << digit); } // Increment the frequency of // this mask if (freq.ContainsKey(mask)) { freq[mask]++; } else { freq.Add(mask, 1); } }} // Returns number of pairs of// Strings resulting in Pandigital// Concatenationsstatic int pandigitalConcatenations(Dictionary<int, int> freq){ int ans = 0; // All possible Strings lie between // 1 and 1023 so we iterate over every // possible mask for(int i = 1; i <= 1023; i++) { for(int j = 1; j <= 1023; j++) { // If the concatenation results in // mask of Pandigital Concatenation, // calculate all pairs formed with // Masks i and j if ((i | j) == pandigitalMask && freq.ContainsKey(j) && freq.ContainsKey(i)) { if (i == j) ans += (freq[i] * (freq[i] - 1)); else ans += (freq[i] * freq[j]); } } } // Since every pair is considers // twice, we get rid of half of // these return ans / 2;} static int countPandigitalPairs(List<String> v){ // Find frequencies of all masks in // given vector of Strings Dictionary<int, int> freq = new Dictionary<int, int>(); computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codepublic static void Main(String[] args){ List<String> v = new List<String>(); v.Add(\"123567\"); v.Add(\"098234\"); v.Add(\"14765\"); v.Add(\"19804\"); Console.Write(countPandigitalPairs(v) + \"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 18524,
"s": 16069,
"text": null
},
{
"code": "<script> // Javascript program to count PanDigital pairsconst pandigitalMask = ((1 << 10) - 1); function computeMaskFrequencies(v, freq){ for(let i = 0; i < v.length; i++) { let mask = 0; // Stores digits present in string v[i] // atleast once. We use a set as we only // need digits which exist only once // (irrespective of reputation) let digits = new Set(); for(let j = 0; j < v[i].length; j++) digits.add((v[i][j]).charCodeAt(0) - '0'.charCodeAt(0)); // Calculate the mask by considering // all digits existing atleast once for(let it of digits) { let digit = it; mask += (1 << digit); } // Increment the frequency of this mask if (freq.has(mask)) { freq.set(mask, freq.get(mask) + 1) } else { freq.set(mask, 1) } }} // Returns number of pairs of strings resulting// in Pandigital Concatenationsfunction pandigitalConcatenations(freq){ let ans = 0; // All possible strings lie between 1 and 1023 // so we iterate over every possible mask for(let i = 1; i <= 1023; i++) { for(let j = 1; j <= 1023; j++) { // if the concatenation results in mask of // Pandigital Concatenation, calculate all // pairs formed with Masks i and j if ((i | j) == pandigitalMask && freq.has(i) && freq.has(j)) { if (i == j) ans += (freq.get(i) * (freq.get(i) - 1)); else ans += (freq.get(i) * freq.get(j)); } } } // Since every pair is considers twice, // we get rid of half of these return Math.floor(ans / 2);} function countPandigitalPairs(v){ // Find frequencies of all masks in // given vector of strings let freq = new Map(); computeMaskFrequencies(v, freq); // Return all possible concatenations. return pandigitalConcatenations(freq);} // Driver codelet v = [ \"123567\", \"098234\", \"14765\", \"19804\" ];document.write(countPandigitalPairs(v) + \"<br>\"); // This code is contributed by gfgking </script>",
"e": 20828,
"s": 18524,
"text": null
},
{
"code": null,
"e": 20838,
"s": 20828,
"text": "Output: "
},
{
"code": null,
"e": 20840,
"s": 20838,
"text": "3"
},
{
"code": null,
"e": 20926,
"s": 20840,
"text": "Complexity : O(N * |s| + 1023 * 1023) where |s| gives length of strings in the array "
},
{
"code": null,
"e": 20938,
"s": 20926,
"text": "manishshaw1"
},
{
"code": null,
"e": 20953,
"s": 20938,
"text": "amit143katiyar"
},
{
"code": null,
"e": 20965,
"s": 20953,
"text": "29AjayKumar"
},
{
"code": null,
"e": 20973,
"s": 20965,
"text": "gfgking"
},
{
"code": null,
"e": 20990,
"s": 20973,
"text": "surinderdawra388"
},
{
"code": null,
"e": 21000,
"s": 20990,
"text": "phasing17"
},
{
"code": null,
"e": 21018,
"s": 21000,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 21029,
"s": 21018,
"text": "cpp-vector"
},
{
"code": null,
"e": 21039,
"s": 21029,
"text": "Bit Magic"
},
{
"code": null,
"e": 21047,
"s": 21039,
"text": "Strings"
},
{
"code": null,
"e": 21066,
"s": 21047,
"text": "Technical Scripter"
},
{
"code": null,
"e": 21074,
"s": 21066,
"text": "Strings"
},
{
"code": null,
"e": 21084,
"s": 21074,
"text": "Bit Magic"
}
]
|
Import Text Files Into Numpy Arrays | 16 Mar, 2021
Numpy is an acronym for ‘Numerical Python’. It is a library in python for supporting n-dimensional arrays. But have you ever wondered about loading data into NumPy from text files. Don’t worry we will discuss the same in this article. To import Text files into Numpy Arrays, we have two functions in Numpy:
numpy.loadtxt( ) – Used to load text file datanumpy.genfromtxt( ) – Used to load data from a text file, with missing values handled as defined.
numpy.loadtxt( ) – Used to load text file data
numpy.genfromtxt( ) – Used to load data from a text file, with missing values handled as defined.
Note: numpy.loadtxt( ) is equivalent function to numpy.genfromtxt( ) when no data is missing.
Method 1 : numpy.loadtxt()
Syntax :
numpy.loadtxt(fname, dtype = float, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=’bytes’, max_rows=None, *, like= None)
The default data type(dtype) parameter for numpy.loadtxt( ) is float.
Example 1: Importing Text file into Numpy arrays
The following ‘example1.txt’ text file is considered in this example.
Python3
import numpy as np # Text file data converted to integer data typeFile_data = np.loadtxt("example1.txt", dtype=int)print(File_data)
Output :
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
Example 2: Importing text file into NumPy array by skipping first row
Python3
import numpy as np # skipping first row# converting file data to stringdata = np.loadtxt("example2.txt", skiprows=1, dtype='str')print(data)
Output :
[['2' 'Bunty']
['3' 'Tinku']
['4' 'Rina']]
Example 3: Importing only the first column(Names) of text file into numpy arrays
The indexing in NumPy arrays starts from 0. Hence, the Roll column in the text file is the 0th column, Names column is the 1st column and the Marks are the 2nd column in the text file ‘example3.txt’.
Python3
import numpy as np # only column1 data is imported into numpy# array from text filedata = np.loadtxt("example3.txt", usecols=1, skiprows=1, dtype='str') for each in data: print(each)
Output :
Ankit
Bunty
Tinku
Rina
Rajesh
Method 2 : numpy.genfromtxt()
Syntax :
numpy.genfromtxt(fname, dtype=float, comments=’#’, delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None,excludelist=None, deletechars=” !#$%&'()*+, -./:;<=>?@[\\]^{|}~”, replace_space=’_’, autostrip=False, case_sensitive=True, defaultfmt=’f%i’, unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding=’bytes’, *, like=None)
Except the fname(filename) in numpy.genfromtxt( ), all the other parameters are optional.
Example 1:
Python3
import numpy as np Data = np.genfromtxt("example4.txt", dtype=str, encoding=None, delimiter=",")print(Data)
Output :
[['a' 'b' 'c' 'd']
['e' 'f' 'g' 'h']]
Example 2: Importing text file into numpy arrays by skipping last row
Python3
import numpy as np # skipping last line in the fileData = np.genfromtxt("example5.txt", dtype=str, encoding=None, skip_footer=1)print(Data)
Output :
[['This' 'is' 'GeeksForGeeks' 'Website']
['How' 'are' 'You' 'Geeks?']
['Geeks' 'for' 'Geeks' 'GFG']]
Picked
Python numpy-io
Python-numpy
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 362,
"s": 54,
"text": "Numpy is an acronym for ‘Numerical Python’. It is a library in python for supporting n-dimensional arrays. But have you ever wondered about loading data into NumPy from text files. Don’t worry we will discuss the same in this article. To import Text files into Numpy Arrays, we have two functions in Numpy: "
},
{
"code": null,
"e": 506,
"s": 362,
"text": "numpy.loadtxt( ) – Used to load text file datanumpy.genfromtxt( ) – Used to load data from a text file, with missing values handled as defined."
},
{
"code": null,
"e": 553,
"s": 506,
"text": "numpy.loadtxt( ) – Used to load text file data"
},
{
"code": null,
"e": 651,
"s": 553,
"text": "numpy.genfromtxt( ) – Used to load data from a text file, with missing values handled as defined."
},
{
"code": null,
"e": 745,
"s": 651,
"text": "Note: numpy.loadtxt( ) is equivalent function to numpy.genfromtxt( ) when no data is missing."
},
{
"code": null,
"e": 772,
"s": 745,
"text": "Method 1 : numpy.loadtxt()"
},
{
"code": null,
"e": 781,
"s": 772,
"text": "Syntax :"
},
{
"code": null,
"e": 961,
"s": 781,
"text": "numpy.loadtxt(fname, dtype = float, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=’bytes’, max_rows=None, *, like= None)"
},
{
"code": null,
"e": 1031,
"s": 961,
"text": "The default data type(dtype) parameter for numpy.loadtxt( ) is float."
},
{
"code": null,
"e": 1080,
"s": 1031,
"text": "Example 1: Importing Text file into Numpy arrays"
},
{
"code": null,
"e": 1152,
"s": 1080,
"text": "The following ‘example1.txt’ text file is considered in this example. "
},
{
"code": null,
"e": 1160,
"s": 1152,
"text": "Python3"
},
{
"code": "import numpy as np # Text file data converted to integer data typeFile_data = np.loadtxt(\"example1.txt\", dtype=int)print(File_data)",
"e": 1295,
"s": 1160,
"text": null
},
{
"code": null,
"e": 1304,
"s": 1295,
"text": "Output :"
},
{
"code": null,
"e": 1346,
"s": 1304,
"text": "[[ 1 2]\n[ 3 4]\n[ 5 6]\n[ 7 8]\n[ 9 10]]"
},
{
"code": null,
"e": 1417,
"s": 1346,
"text": "Example 2: Importing text file into NumPy array by skipping first row "
},
{
"code": null,
"e": 1425,
"s": 1417,
"text": "Python3"
},
{
"code": "import numpy as np # skipping first row# converting file data to stringdata = np.loadtxt(\"example2.txt\", skiprows=1, dtype='str')print(data)",
"e": 1569,
"s": 1425,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1569,
"text": "Output :"
},
{
"code": null,
"e": 1621,
"s": 1578,
"text": "[['2' 'Bunty']\n['3' 'Tinku']\n['4' 'Rina']]"
},
{
"code": null,
"e": 1702,
"s": 1621,
"text": "Example 3: Importing only the first column(Names) of text file into numpy arrays"
},
{
"code": null,
"e": 1902,
"s": 1702,
"text": "The indexing in NumPy arrays starts from 0. Hence, the Roll column in the text file is the 0th column, Names column is the 1st column and the Marks are the 2nd column in the text file ‘example3.txt’."
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Python3"
},
{
"code": "import numpy as np # only column1 data is imported into numpy# array from text filedata = np.loadtxt(\"example3.txt\", usecols=1, skiprows=1, dtype='str') for each in data: print(each)",
"e": 2100,
"s": 1910,
"text": null
},
{
"code": null,
"e": 2109,
"s": 2100,
"text": "Output :"
},
{
"code": null,
"e": 2139,
"s": 2109,
"text": "Ankit\nBunty\nTinku\nRina\nRajesh"
},
{
"code": null,
"e": 2169,
"s": 2139,
"text": "Method 2 : numpy.genfromtxt()"
},
{
"code": null,
"e": 2178,
"s": 2169,
"text": "Syntax :"
},
{
"code": null,
"e": 2607,
"s": 2178,
"text": "numpy.genfromtxt(fname, dtype=float, comments=’#’, delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None,excludelist=None, deletechars=” !#$%&'()*+, -./:;<=>?@[\\\\]^{|}~”, replace_space=’_’, autostrip=False, case_sensitive=True, defaultfmt=’f%i’, unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding=’bytes’, *, like=None)"
},
{
"code": null,
"e": 2697,
"s": 2607,
"text": "Except the fname(filename) in numpy.genfromtxt( ), all the other parameters are optional."
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": "Example 1:"
},
{
"code": null,
"e": 2716,
"s": 2708,
"text": "Python3"
},
{
"code": "import numpy as np Data = np.genfromtxt(\"example4.txt\", dtype=str, encoding=None, delimiter=\",\")print(Data)",
"e": 2845,
"s": 2716,
"text": null
},
{
"code": null,
"e": 2854,
"s": 2845,
"text": "Output :"
},
{
"code": null,
"e": 2892,
"s": 2854,
"text": "[['a' 'b' 'c' 'd']\n['e' 'f' 'g' 'h']]"
},
{
"code": null,
"e": 2963,
"s": 2892,
"text": "Example 2: Importing text file into numpy arrays by skipping last row "
},
{
"code": null,
"e": 2971,
"s": 2963,
"text": "Python3"
},
{
"code": "import numpy as np # skipping last line in the fileData = np.genfromtxt(\"example5.txt\", dtype=str, encoding=None, skip_footer=1)print(Data)",
"e": 3134,
"s": 2971,
"text": null
},
{
"code": null,
"e": 3143,
"s": 3134,
"text": "Output :"
},
{
"code": null,
"e": 3244,
"s": 3143,
"text": "[['This' 'is' 'GeeksForGeeks' 'Website']\n['How' 'are' 'You' 'Geeks?']\n['Geeks' 'for' 'Geeks' 'GFG']]"
},
{
"code": null,
"e": 3251,
"s": 3244,
"text": "Picked"
},
{
"code": null,
"e": 3267,
"s": 3251,
"text": "Python numpy-io"
},
{
"code": null,
"e": 3280,
"s": 3267,
"text": "Python-numpy"
},
{
"code": null,
"e": 3304,
"s": 3280,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3311,
"s": 3304,
"text": "Python"
},
{
"code": null,
"e": 3330,
"s": 3311,
"text": "Technical Scripter"
}
]
|
Why is colspan not a known native attribute in Angular 2? | 26 Jun, 2020
In order to understand it, we need to have a clear in-depth knowledge between Document Object Model(DOM) and HyperText Markup Language(HTML).Basically, DOM is a model of objects and is a logical tree representation of the document whereas HTML is a markup language that we used to build web-pages.Every HTML attributes have one to one mapping to properties of DOM objects.
Example: First Name
<label for="fname">First Name </label><input type="text" id="fname" name="fname" disabled >
So, The above example contains two tags label and input. As we can observe, there is an attribute defined inside the input tag which is “disabled”.Similarly, if you talk about DOM properties, disabled is also present inside the input object.But they are cases where some attributes of HTML tags are not available inside the DOM. Example: colspan. Like colspan, So when you try to use them for attribute binding in Angular 2+, you will get an error which says “can’t bind to colspan since it isn’t a known property of ‘td’ “.Similarly, we have some properties which are defined in DOM but are not present in HTML.
Example:
<h2 [textContent]="title"></h1>
Solution:In order to use them for attribute binding you need to use the following syntax “[attr.colspan]”.
import {Component} from '@angular/core'; @Component({ selector:'app-colspan',template:`<h4> Colspan Usage </h4><table> <tr> <td [attr.colspan]="colSpan">First Item </td> </tr> <tr> <td>Second Item</td> <td>Third Item </td> </tr></table>`,styles:[` table, tr, td{border: 1px solid black;border-collapse:collapse;}`]}) export class ColSpanComponent{ colSpan="2" }
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
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": 28,
"s": 0,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 401,
"s": 28,
"text": "In order to understand it, we need to have a clear in-depth knowledge between Document Object Model(DOM) and HyperText Markup Language(HTML).Basically, DOM is a model of objects and is a logical tree representation of the document whereas HTML is a markup language that we used to build web-pages.Every HTML attributes have one to one mapping to properties of DOM objects."
},
{
"code": null,
"e": 421,
"s": 401,
"text": "Example: First Name"
},
{
"code": "<label for=\"fname\">First Name </label><input type=\"text\" id=\"fname\" name=\"fname\" disabled >",
"e": 513,
"s": 421,
"text": null
},
{
"code": null,
"e": 1126,
"s": 513,
"text": "So, The above example contains two tags label and input. As we can observe, there is an attribute defined inside the input tag which is “disabled”.Similarly, if you talk about DOM properties, disabled is also present inside the input object.But they are cases where some attributes of HTML tags are not available inside the DOM. Example: colspan. Like colspan, So when you try to use them for attribute binding in Angular 2+, you will get an error which says “can’t bind to colspan since it isn’t a known property of ‘td’ “.Similarly, we have some properties which are defined in DOM but are not present in HTML."
},
{
"code": null,
"e": 1135,
"s": 1126,
"text": "Example:"
},
{
"code": "<h2 [textContent]=\"title\"></h1>",
"e": 1167,
"s": 1135,
"text": null
},
{
"code": null,
"e": 1274,
"s": 1167,
"text": "Solution:In order to use them for attribute binding you need to use the following syntax “[attr.colspan]”."
},
{
"code": "import {Component} from '@angular/core'; @Component({ selector:'app-colspan',template:`<h4> Colspan Usage </h4><table> <tr> <td [attr.colspan]=\"colSpan\">First Item </td> </tr> <tr> <td>Second Item</td> <td>Third Item </td> </tr></table>`,styles:[` table, tr, td{border: 1px solid black;border-collapse:collapse;}`]}) export class ColSpanComponent{ colSpan=\"2\" }",
"e": 1656,
"s": 1274,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1656,
"text": "Output:"
},
{
"code": null,
"e": 1679,
"s": 1664,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 1686,
"s": 1679,
"text": "Picked"
},
{
"code": null,
"e": 1696,
"s": 1686,
"text": "AngularJS"
},
{
"code": null,
"e": 1713,
"s": 1696,
"text": "Web Technologies"
},
{
"code": null,
"e": 1811,
"s": 1713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1842,
"s": 1811,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 1866,
"s": 1842,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 1911,
"s": 1866,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 1953,
"s": 1911,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 1988,
"s": 1953,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2021,
"s": 1988,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2083,
"s": 2021,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2144,
"s": 2083,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2194,
"s": 2144,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
sympy.integrals.transforms.fourier_transform() in python | 10 Jul, 2020
With the help of fourier_transform() method, we can compute the Fourier transformation and it will return the transformed function.
Fourier transformation function
Syntax : fourier_transform(f, x, k, **hints)
Return : Return the transformed function.
Example #1 :
In this example we can see that by using fourier_transform() method, we are able to compute the Fourier transformation and return the transeformed function.
Python3
# import fourier_transformfrom sympy import fourier_transform, expfrom sympy.abc import x, k # Using fourier_transform() methodgfg = fourier_transform(exp(-x**2), x, k) print(gfg)
Output :
sqrt(pi)*exp(-pi**2*k**2)
Example #2 :
Python3
# import fourier_transformfrom sympy import fourier_transform, expfrom sympy.abc import x, k # Using fourier_transform() methodgfg = fourier_transform(exp(-x**2), x, 4) print(gfg)
Output :
sqrt(pi)*exp(-16*pi**2)
Python SymPy-Stats
SymPy
Programming Language
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of Object Oriented Programming
Difference between for and while loop in C, C++, Java
Which Programming Language Should I Choose as a Beginner?
Learn C++ Programming Step by Step - A 20 Day Curriculum!
7 Highest Paying Programming Languages For Freelancers in 2022
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "With the help of fourier_transform() method, we can compute the Fourier transformation and it will return the transformed function."
},
{
"code": null,
"e": 192,
"s": 160,
"text": "Fourier transformation function"
},
{
"code": null,
"e": 237,
"s": 192,
"text": "Syntax : fourier_transform(f, x, k, **hints)"
},
{
"code": null,
"e": 279,
"s": 237,
"text": "Return : Return the transformed function."
},
{
"code": null,
"e": 292,
"s": 279,
"text": "Example #1 :"
},
{
"code": null,
"e": 449,
"s": 292,
"text": "In this example we can see that by using fourier_transform() method, we are able to compute the Fourier transformation and return the transeformed function."
},
{
"code": null,
"e": 457,
"s": 449,
"text": "Python3"
},
{
"code": "# import fourier_transformfrom sympy import fourier_transform, expfrom sympy.abc import x, k # Using fourier_transform() methodgfg = fourier_transform(exp(-x**2), x, k) print(gfg)",
"e": 639,
"s": 457,
"text": null
},
{
"code": null,
"e": 648,
"s": 639,
"text": "Output :"
},
{
"code": null,
"e": 674,
"s": 648,
"text": "sqrt(pi)*exp(-pi**2*k**2)"
},
{
"code": null,
"e": 687,
"s": 674,
"text": "Example #2 :"
},
{
"code": null,
"e": 695,
"s": 687,
"text": "Python3"
},
{
"code": "# import fourier_transformfrom sympy import fourier_transform, expfrom sympy.abc import x, k # Using fourier_transform() methodgfg = fourier_transform(exp(-x**2), x, 4) print(gfg)",
"e": 877,
"s": 695,
"text": null
},
{
"code": null,
"e": 886,
"s": 877,
"text": "Output :"
},
{
"code": null,
"e": 910,
"s": 886,
"text": "sqrt(pi)*exp(-16*pi**2)"
},
{
"code": null,
"e": 929,
"s": 910,
"text": "Python SymPy-Stats"
},
{
"code": null,
"e": 935,
"s": 929,
"text": "SymPy"
},
{
"code": null,
"e": 956,
"s": 935,
"text": "Programming Language"
},
{
"code": null,
"e": 963,
"s": 956,
"text": "Python"
},
{
"code": null,
"e": 1061,
"s": 963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1105,
"s": 1061,
"text": "Introduction of Object Oriented Programming"
},
{
"code": null,
"e": 1159,
"s": 1105,
"text": "Difference between for and while loop in C, C++, Java"
},
{
"code": null,
"e": 1217,
"s": 1159,
"text": "Which Programming Language Should I Choose as a Beginner?"
},
{
"code": null,
"e": 1275,
"s": 1217,
"text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!"
},
{
"code": null,
"e": 1338,
"s": 1275,
"text": "7 Highest Paying Programming Languages For Freelancers in 2022"
},
{
"code": null,
"e": 1366,
"s": 1338,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1388,
"s": 1366,
"text": "Python map() function"
},
{
"code": null,
"e": 1438,
"s": 1388,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1456,
"s": 1438,
"text": "Python Dictionary"
}
]
|
Program to find sum of first n natural numbers | 20 Feb, 2022
Given a number n, find the sum of first natural numbers.
Examples :
Input : n = 3
Output : 6
Explanation :
Note that 1 + 2 + 3 = 6
Input : 5
Output : 15
Explanation :
Note that 1 + 2 + 3 + 4 + 5 = 15
A simple solution is to do the following.
1) Initialize : sum = 0
2) Run a loop from x = 1 to n and
do following in loop.
sum = sum + x
C++
Java
Python
C#
PHP
Javascript
// CPP program to find sum of first// n natural numbers.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ int sum = 0; for (int x=1; x<=n; x++) sum = sum + x; return sum;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}
// JAVA program to find sum of first// n natural numbers.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Nikita Tiwari.
# PYTHON program to find sum of first# n natural numbers. # Returns sum of first n natural# numbersdef findSum(n) : sum = 0 x = 1 while x <=n : sum = sum + x x = x + 1 return sum # Driver code n = 5print findSum(n) # This code is contributed by Nikita Tiwari.
// C# program to find sum of first// n natural numbers.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} // This code is contributed by vt_m.
<?php// PHP program to find sum of first// n natural numbers. // Returns sum of first n natural// numbersfunction findSum($n){$sum = 0;for ($x = 1; $x <= $n; $x++) $sum = $sum + $x;return $sum;} // Driver code$n = 5;echo findSum($n); // This code is contributed by Sam007?>
<script>// Javascript program to find sum of first// n natural numbers. // Returns sum of first n natural// numbersfunction findSum(n){ let sum = 0; for (let x = 1; x <= n; x++) sum = sum + x; return sum;} // Driver codelet n = 5;document.write(findSum(n)); // This code is contributed by rishavmahato348.</script>
Output :
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
15
Time Complexity: O(n)
Auxiliary Space: O(1)An efficient solution is to use the below formula.
How does this work?
We can prove this formula using induction.
It is true for n = 1 and n = 2
For n = 1, sum = 1 * (1 + 1)/2 = 1
For n = 2, sum = 2 * (2 + 1)/2 = 3
Let it be true for k = n-1.
Sum of k numbers = (k * (k+1))/2
Putting k = n-1, we get
Sum of k numbers = ((n-1) * (n-1+1))/2
= (n - 1) * n / 2
If we add n, we get,
Sum of n numbers = n + (n - 1) * n / 2
= (2n + n2 - n)/2
= n * (n + 1)/2
C++
Java
Python
C#
php
Javascript
// Efficient CPP program to find sum of first// n natural numbers.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ return n * (n + 1) / 2;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}
// Efficient JAVA program to find sum// of first n natural numbers.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { return n * (n + 1) / 2; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Nikita Tiwari.
# Efficient CPP program to find sum# of first n natural numbers. # Returns sum of first n natural# numbersdef findSum(n) : return n * (n + 1) / 2 # Driver coden = 5print findSum(n) # This code is contributed by Nikita Tiwari.
// Efficient C# program to find sum// of first n natural numbers.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { return n * (n + 1) / 2; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} // This code is contributed by vt_m.
<?php// Efficient PHP program to find sum// of first n natural numbers. // Returns sum of first n natural// numbersfunction findSum($n){ return ($n * ($n + 1) / 2);} // Driver code$n = 5;echo findSum($n); // This code is contributed by Sam007?>
<script>// javascript Program to find the average// of sum of first n natural numbers // Return the average of sum// of first n even numbersfunction findSum(n){ return n * (n + 1) / 2;}var n = 5;document.write(findSum(n)); // This code is contributed by sravan kumar</script>
Output:
15
Time Complexity: O(1)
Auxiliary Space: O(1)The above program causes overflow, even if the result is not beyond the integer limit. We can avoid overflow up to some extent by dividing first.
C++
Java
Python
C#
PHP
Javascript
// Efficient CPP program to find sum of first// n natural numbers that avoids overflow if// result is going to be within limits.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ if (n % 2 == 0) return (n/2) * 1LL * (n+1); // Here multiplying by 1LL help to perform calculations in long long, so that answer should not be overflowed // If n is odd, (n+1) must be even else return ((n + 1) / 2) * 1LL * n; // Here multiplying by 1LL help to perform calculations in long long, so that answer should not be overflowed} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}
// Efficient JAVA program to find sum of first// n natural numbers that avoids overflow if// result is going to be within limits.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { if (n % 2 == 0) return (n / 2) * (n + 1); // If n is odd, (n+1) must be even else return ((n + 1) / 2) * n; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} //This code is contributed by Nikita Tiwari.
# Efficient Python program to find the sum # of first n natural numbers that avoid# overflow if the result is going to be# within limits. # Returns sum of first n natural# numbersdef findSum(n) : if (n % 2 == 0) : return (n / 2) * (n + 1) # If n is odd, (n+1) must be even else : return ((n + 1) / 2) * n # Driver coden = 5print findSum(n) # This code is contributed by Nikita Tiwari.
// Efficient C# program to find the sum of first// n natural numbers that avoid overflow if// result is going to be within limits.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { if (n % 2 == 0) return (n / 2) * (n + 1); // If n is odd, (n+1) must be even else return ((n + 1) / 2) * n; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} // This code is contributed by vt_m.
<?php// Efficient php program to find sum of first// n natural numbers that avoids overflow if// result is going to be within limits. // Returns sum of first n natural// numbersfunction findSum($n){ if ($n % 2 == 0) return ($n / 2) * ($n + 1); // If n is odd, (n+1) must be even else return (($n + 1) / 2) * $n;} // Driver code$n = 5;echo findSum($n); // This code is contributed by Sam007?>
<script>//efficient approach using javascript to find the average// of sum of first n natural numbers // Return the average of sum// of first n even numbersfunction findSum(n){ if (n % 2 == 0) return (n / 2) * (n + 1) // If n is odd, (n+1) must be even else return ((n + 1) / 2) * n }var n = 5;document.write(findSum(n)); // This code is contributed by sravan kumar</script>
Output:
15
Time Complexity: O(1)
Auxiliary Space: O(1)This article is contributed by Tapesh (tapeshdua420). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
Akanksha_Rai
rishavmahato348
sravankumar8128
tapeshdua420
number-theory
series
Mathematical
School Programming
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Feb, 2022"
},
{
"code": null,
"e": 110,
"s": 53,
"text": "Given a number n, find the sum of first natural numbers."
},
{
"code": null,
"e": 122,
"s": 110,
"text": "Examples : "
},
{
"code": null,
"e": 257,
"s": 122,
"text": "Input : n = 3\nOutput : 6\nExplanation :\nNote that 1 + 2 + 3 = 6\n\nInput : 5\nOutput : 15 \nExplanation :\nNote that 1 + 2 + 3 + 4 + 5 = 15"
},
{
"code": null,
"e": 300,
"s": 257,
"text": "A simple solution is to do the following. "
},
{
"code": null,
"e": 404,
"s": 300,
"text": "1) Initialize : sum = 0\n2) Run a loop from x = 1 to n and \n do following in loop.\n sum = sum + x "
},
{
"code": null,
"e": 408,
"s": 404,
"text": "C++"
},
{
"code": null,
"e": 413,
"s": 408,
"text": "Java"
},
{
"code": null,
"e": 420,
"s": 413,
"text": "Python"
},
{
"code": null,
"e": 423,
"s": 420,
"text": "C#"
},
{
"code": null,
"e": 427,
"s": 423,
"text": "PHP"
},
{
"code": null,
"e": 438,
"s": 427,
"text": "Javascript"
},
{
"code": "// CPP program to find sum of first// n natural numbers.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ int sum = 0; for (int x=1; x<=n; x++) sum = sum + x; return sum;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}",
"e": 743,
"s": 438,
"text": null
},
{
"code": "// JAVA program to find sum of first// n natural numbers.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Nikita Tiwari.",
"e": 1196,
"s": 743,
"text": null
},
{
"code": "# PYTHON program to find sum of first# n natural numbers. # Returns sum of first n natural# numbersdef findSum(n) : sum = 0 x = 1 while x <=n : sum = sum + x x = x + 1 return sum # Driver code n = 5print findSum(n) # This code is contributed by Nikita Tiwari.",
"e": 1483,
"s": 1196,
"text": null
},
{
"code": "// C# program to find sum of first// n natural numbers.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} // This code is contributed by vt_m.",
"e": 1903,
"s": 1483,
"text": null
},
{
"code": "<?php// PHP program to find sum of first// n natural numbers. // Returns sum of first n natural// numbersfunction findSum($n){$sum = 0;for ($x = 1; $x <= $n; $x++) $sum = $sum + $x;return $sum;} // Driver code$n = 5;echo findSum($n); // This code is contributed by Sam007?>",
"e": 2180,
"s": 1903,
"text": null
},
{
"code": "<script>// Javascript program to find sum of first// n natural numbers. // Returns sum of first n natural// numbersfunction findSum(n){ let sum = 0; for (let x = 1; x <= n; x++) sum = sum + x; return sum;} // Driver codelet n = 5;document.write(findSum(n)); // This code is contributed by rishavmahato348.</script>",
"e": 2505,
"s": 2180,
"text": null
},
{
"code": null,
"e": 2515,
"s": 2505,
"text": "Output : "
},
{
"code": null,
"e": 2524,
"s": 2515,
"text": "Chapters"
},
{
"code": null,
"e": 2551,
"s": 2524,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 2601,
"s": 2551,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 2624,
"s": 2601,
"text": "captions off, selected"
},
{
"code": null,
"e": 2632,
"s": 2624,
"text": "English"
},
{
"code": null,
"e": 2650,
"s": 2632,
"text": "default, selected"
},
{
"code": null,
"e": 2674,
"s": 2650,
"text": "This is a modal window."
},
{
"code": null,
"e": 2743,
"s": 2674,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 2765,
"s": 2743,
"text": "End of dialog window."
},
{
"code": null,
"e": 2768,
"s": 2765,
"text": "15"
},
{
"code": null,
"e": 2790,
"s": 2768,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 2863,
"s": 2790,
"text": "Auxiliary Space: O(1)An efficient solution is to use the below formula. "
},
{
"code": null,
"e": 2883,
"s": 2863,
"text": "How does this work?"
},
{
"code": null,
"e": 3318,
"s": 2883,
"text": "We can prove this formula using induction.\n\nIt is true for n = 1 and n = 2\nFor n = 1, sum = 1 * (1 + 1)/2 = 1\nFor n = 2, sum = 2 * (2 + 1)/2 = 3\n\nLet it be true for k = n-1.\n\nSum of k numbers = (k * (k+1))/2\nPutting k = n-1, we get\nSum of k numbers = ((n-1) * (n-1+1))/2\n = (n - 1) * n / 2\n\nIf we add n, we get,\nSum of n numbers = n + (n - 1) * n / 2\n = (2n + n2 - n)/2\n = n * (n + 1)/2"
},
{
"code": null,
"e": 3322,
"s": 3318,
"text": "C++"
},
{
"code": null,
"e": 3327,
"s": 3322,
"text": "Java"
},
{
"code": null,
"e": 3334,
"s": 3327,
"text": "Python"
},
{
"code": null,
"e": 3337,
"s": 3334,
"text": "C#"
},
{
"code": null,
"e": 3341,
"s": 3337,
"text": "php"
},
{
"code": null,
"e": 3352,
"s": 3341,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to find sum of first// n natural numbers.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ return n * (n + 1) / 2;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}",
"e": 3618,
"s": 3352,
"text": null
},
{
"code": "// Efficient JAVA program to find sum// of first n natural numbers.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { return n * (n + 1) / 2; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} // This code is contributed by Nikita Tiwari.",
"e": 4015,
"s": 3618,
"text": null
},
{
"code": "# Efficient CPP program to find sum# of first n natural numbers. # Returns sum of first n natural# numbersdef findSum(n) : return n * (n + 1) / 2 # Driver coden = 5print findSum(n) # This code is contributed by Nikita Tiwari.",
"e": 4248,
"s": 4015,
"text": null
},
{
"code": "// Efficient C# program to find sum// of first n natural numbers.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { return n * (n + 1) / 2; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} // This code is contributed by vt_m.",
"e": 4612,
"s": 4248,
"text": null
},
{
"code": "<?php// Efficient PHP program to find sum// of first n natural numbers. // Returns sum of first n natural// numbersfunction findSum($n){ return ($n * ($n + 1) / 2);} // Driver code$n = 5;echo findSum($n); // This code is contributed by Sam007?>",
"e": 4860,
"s": 4612,
"text": null
},
{
"code": "<script>// javascript Program to find the average// of sum of first n natural numbers // Return the average of sum// of first n even numbersfunction findSum(n){ return n * (n + 1) / 2;}var n = 5;document.write(findSum(n)); // This code is contributed by sravan kumar</script>",
"e": 5139,
"s": 4860,
"text": null
},
{
"code": null,
"e": 5149,
"s": 5139,
"text": "Output: "
},
{
"code": null,
"e": 5152,
"s": 5149,
"text": "15"
},
{
"code": null,
"e": 5174,
"s": 5152,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 5342,
"s": 5174,
"text": "Auxiliary Space: O(1)The above program causes overflow, even if the result is not beyond the integer limit. We can avoid overflow up to some extent by dividing first. "
},
{
"code": null,
"e": 5346,
"s": 5342,
"text": "C++"
},
{
"code": null,
"e": 5351,
"s": 5346,
"text": "Java"
},
{
"code": null,
"e": 5358,
"s": 5351,
"text": "Python"
},
{
"code": null,
"e": 5361,
"s": 5358,
"text": "C#"
},
{
"code": null,
"e": 5365,
"s": 5361,
"text": "PHP"
},
{
"code": null,
"e": 5376,
"s": 5365,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to find sum of first// n natural numbers that avoids overflow if// result is going to be within limits.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ if (n % 2 == 0) return (n/2) * 1LL * (n+1); // Here multiplying by 1LL help to perform calculations in long long, so that answer should not be overflowed // If n is odd, (n+1) must be even else return ((n + 1) / 2) * 1LL * n; // Here multiplying by 1LL help to perform calculations in long long, so that answer should not be overflowed} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}",
"e": 6035,
"s": 5376,
"text": null
},
{
"code": "// Efficient JAVA program to find sum of first// n natural numbers that avoids overflow if// result is going to be within limits.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { if (n % 2 == 0) return (n / 2) * (n + 1); // If n is odd, (n+1) must be even else return ((n + 1) / 2) * n; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} //This code is contributed by Nikita Tiwari.",
"e": 6610,
"s": 6035,
"text": null
},
{
"code": "# Efficient Python program to find the sum # of first n natural numbers that avoid# overflow if the result is going to be# within limits. # Returns sum of first n natural# numbersdef findSum(n) : if (n % 2 == 0) : return (n / 2) * (n + 1) # If n is odd, (n+1) must be even else : return ((n + 1) / 2) * n # Driver coden = 5print findSum(n) # This code is contributed by Nikita Tiwari.",
"e": 7026,
"s": 6610,
"text": null
},
{
"code": "// Efficient C# program to find the sum of first// n natural numbers that avoid overflow if// result is going to be within limits.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { if (n % 2 == 0) return (n / 2) * (n + 1); // If n is odd, (n+1) must be even else return ((n + 1) / 2) * n; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} // This code is contributed by vt_m.",
"e": 7572,
"s": 7026,
"text": null
},
{
"code": "<?php// Efficient php program to find sum of first// n natural numbers that avoids overflow if// result is going to be within limits. // Returns sum of first n natural// numbersfunction findSum($n){ if ($n % 2 == 0) return ($n / 2) * ($n + 1); // If n is odd, (n+1) must be even else return (($n + 1) / 2) * $n;} // Driver code$n = 5;echo findSum($n); // This code is contributed by Sam007?>",
"e": 8006,
"s": 7572,
"text": null
},
{
"code": "<script>//efficient approach using javascript to find the average// of sum of first n natural numbers // Return the average of sum// of first n even numbersfunction findSum(n){ if (n % 2 == 0) return (n / 2) * (n + 1) // If n is odd, (n+1) must be even else return ((n + 1) / 2) * n }var n = 5;document.write(findSum(n)); // This code is contributed by sravan kumar</script>",
"e": 8406,
"s": 8006,
"text": null
},
{
"code": null,
"e": 8415,
"s": 8406,
"text": "Output: "
},
{
"code": null,
"e": 8418,
"s": 8415,
"text": "15"
},
{
"code": null,
"e": 8440,
"s": 8418,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 8891,
"s": 8440,
"text": "Auxiliary Space: O(1)This article is contributed by Tapesh (tapeshdua420). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8898,
"s": 8891,
"text": "Sam007"
},
{
"code": null,
"e": 8911,
"s": 8898,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8927,
"s": 8911,
"text": "rishavmahato348"
},
{
"code": null,
"e": 8943,
"s": 8927,
"text": "sravankumar8128"
},
{
"code": null,
"e": 8956,
"s": 8943,
"text": "tapeshdua420"
},
{
"code": null,
"e": 8970,
"s": 8956,
"text": "number-theory"
},
{
"code": null,
"e": 8977,
"s": 8970,
"text": "series"
},
{
"code": null,
"e": 8990,
"s": 8977,
"text": "Mathematical"
},
{
"code": null,
"e": 9009,
"s": 8990,
"text": "School Programming"
},
{
"code": null,
"e": 9023,
"s": 9009,
"text": "number-theory"
},
{
"code": null,
"e": 9036,
"s": 9023,
"text": "Mathematical"
},
{
"code": null,
"e": 9043,
"s": 9036,
"text": "series"
}
]
|
How to create shapes using CSS ? | 21 Jun, 2021
In this article, we will design some different types of shapes using CSS. CSS is capable of making all types of shapes.
Creating a square:
html
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .square { height: 50px; width: 50px; background-color: green; } </style></head> <body> <div class="square"></div></body> </html>
Output:
Creating Triangle Upward:
Upward:
html
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .triangle { width: 0; height: 0; border-left: 25px solid transparent; border-right: 25px solid transparent; border-bottom: 50px solid green; } </style></head> <body> <div class="triangle"></div></body> </html>
Output:
Downward:
html
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .triangle { width: 0; height: 0; border-left: 25px solid transparent; border-right: 25px solid transparent; border-top: 50px solid green; } </style></head> <body> <div class="triangle"></div></body> </html>
Output:
Creating a circle:
html
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .circle { height: 70px; width: 70px; background-color: green; border-radius: 50%; } </style></head> <body> <div class="circle"></div></body> </html>
Output:
Creating a rectangle:
html
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .rectangle { height: 50px; width: 80px; background-color: green; } </style></head> <body> <div class="rectangle"></div></body> </html>
Output:
Creating a parallelogram:
html
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .parallelogram { width: 120px; height: 60px; transform: skew(24deg); background: green; } </style></head> <body> <div class="parallelogram"></div></body> </html>
Output:
Creating oval:
HTML
<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .oval { height: 200px; width: 400px; border-radius: 50%; background-color: green; } </style></head> <body> <div class="oval"></div></body> </html>
Output:
imsushant12
CoderSaty
CSS-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
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?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 175,
"s": 53,
"text": "In this article, we will design some different types of shapes using CSS. CSS is capable of making all types of shapes. "
},
{
"code": null,
"e": 196,
"s": 175,
"text": "Creating a square: "
},
{
"code": null,
"e": 201,
"s": 196,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .square { height: 50px; width: 50px; background-color: green; } </style></head> <body> <div class=\"square\"></div></body> </html>",
"e": 452,
"s": 201,
"text": null
},
{
"code": null,
"e": 462,
"s": 452,
"text": "Output: "
},
{
"code": null,
"e": 490,
"s": 462,
"text": "Creating Triangle Upward: "
},
{
"code": null,
"e": 500,
"s": 490,
"text": "Upward: "
},
{
"code": null,
"e": 505,
"s": 500,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .triangle { width: 0; height: 0; border-left: 25px solid transparent; border-right: 25px solid transparent; border-bottom: 50px solid green; } </style></head> <body> <div class=\"triangle\"></div></body> </html>",
"e": 859,
"s": 505,
"text": null
},
{
"code": null,
"e": 869,
"s": 859,
"text": "Output: "
},
{
"code": null,
"e": 881,
"s": 869,
"text": "Downward: "
},
{
"code": null,
"e": 886,
"s": 881,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .triangle { width: 0; height: 0; border-left: 25px solid transparent; border-right: 25px solid transparent; border-top: 50px solid green; } </style></head> <body> <div class=\"triangle\"></div></body> </html>",
"e": 1237,
"s": 886,
"text": null
},
{
"code": null,
"e": 1247,
"s": 1237,
"text": "Output: "
},
{
"code": null,
"e": 1268,
"s": 1247,
"text": "Creating a circle: "
},
{
"code": null,
"e": 1273,
"s": 1268,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .circle { height: 70px; width: 70px; background-color: green; border-radius: 50%; } </style></head> <body> <div class=\"circle\"></div></body> </html>",
"e": 1555,
"s": 1273,
"text": null
},
{
"code": null,
"e": 1565,
"s": 1555,
"text": "Output: "
},
{
"code": null,
"e": 1589,
"s": 1565,
"text": "Creating a rectangle: "
},
{
"code": null,
"e": 1594,
"s": 1589,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .rectangle { height: 50px; width: 80px; background-color: green; } </style></head> <body> <div class=\"rectangle\"></div></body> </html>",
"e": 1851,
"s": 1594,
"text": null
},
{
"code": null,
"e": 1860,
"s": 1851,
"text": "Output: "
},
{
"code": null,
"e": 1890,
"s": 1862,
"text": "Creating a parallelogram: "
},
{
"code": null,
"e": 1895,
"s": 1890,
"text": "html"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .parallelogram { width: 120px; height: 60px; transform: skew(24deg); background: green; } </style></head> <body> <div class=\"parallelogram\"></div></body> </html>",
"e": 2190,
"s": 1895,
"text": null
},
{
"code": null,
"e": 2200,
"s": 2190,
"text": "Output: "
},
{
"code": null,
"e": 2215,
"s": 2200,
"text": "Creating oval:"
},
{
"code": null,
"e": 2220,
"s": 2215,
"text": "HTML"
},
{
"code": "<!-- Write HTML code here --><!DOCTYPE html><html> <head> <style> .oval { height: 200px; width: 400px; border-radius: 50%; background-color: green; } </style></head> <body> <div class=\"oval\"></div></body> </html>",
"e": 2498,
"s": 2220,
"text": null
},
{
"code": null,
"e": 2506,
"s": 2498,
"text": "Output:"
},
{
"code": null,
"e": 2518,
"s": 2506,
"text": "imsushant12"
},
{
"code": null,
"e": 2528,
"s": 2518,
"text": "CoderSaty"
},
{
"code": null,
"e": 2537,
"s": 2528,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2541,
"s": 2537,
"text": "CSS"
},
{
"code": null,
"e": 2546,
"s": 2541,
"text": "HTML"
},
{
"code": null,
"e": 2563,
"s": 2546,
"text": "Web Technologies"
},
{
"code": null,
"e": 2568,
"s": 2563,
"text": "HTML"
},
{
"code": null,
"e": 2666,
"s": 2568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2714,
"s": 2666,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2776,
"s": 2714,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2826,
"s": 2776,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2884,
"s": 2826,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2934,
"s": 2884,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2982,
"s": 2934,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3044,
"s": 2982,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3094,
"s": 3044,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3118,
"s": 3094,
"text": "REST API (Introduction)"
}
]
|
GATE | GATE CS 1996 | Question 63 | 30 Jul, 2019
Insert the characters of the string K R P C S N Y T J M into a hash table of size 10.Use the hash function
h(x) = ( ord(x) – ord("a") + 1 ) mod10
If linear probing is used to resolve collisions, then the following insertion causes collision(A) Y(B) C(C) M(D) PAnswer: (C)Explanation:(a) The hash table with size 10 will have index from 0 to 9.hash function = h(x) = ((ord(x) – ord(A) + 1)) mod 10So for string K R P C S N Y T J M:K will be inserted at index : (11-1+1) mod 10 = 1R at index: (18-1+1) mod 10 = 8P at index: (16-1+1) mod 10 = 6C at index: (3-1+1) mod 10 = 3S at index: (19-1+1) mod 10 = 9N at index: (14-1+1) mod 10 = 4Y at index (25-1+1) mod 10 = 5T at index (20-1+1) mod 10 = 0J at index (10-1+1) mod 10 = 0 // first collision occurs.M at index (13-1+1) mod 10 = 3 //second collision occurs.
Only J and M are causing the collision.
(b) Final Hash table will be:
0 T
1 K
2 J
3 C
4 N
5 Y
6 P
7 M
8 R
9 S
Quiz of this Question
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 38 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 161,
"s": 54,
"text": "Insert the characters of the string K R P C S N Y T J M into a hash table of size 10.Use the hash function"
},
{
"code": null,
"e": 200,
"s": 161,
"text": "h(x) = ( ord(x) – ord(\"a\") + 1 ) mod10"
},
{
"code": null,
"e": 862,
"s": 200,
"text": "If linear probing is used to resolve collisions, then the following insertion causes collision(A) Y(B) C(C) M(D) PAnswer: (C)Explanation:(a) The hash table with size 10 will have index from 0 to 9.hash function = h(x) = ((ord(x) – ord(A) + 1)) mod 10So for string K R P C S N Y T J M:K will be inserted at index : (11-1+1) mod 10 = 1R at index: (18-1+1) mod 10 = 8P at index: (16-1+1) mod 10 = 6C at index: (3-1+1) mod 10 = 3S at index: (19-1+1) mod 10 = 9N at index: (14-1+1) mod 10 = 4Y at index (25-1+1) mod 10 = 5T at index (20-1+1) mod 10 = 0J at index (10-1+1) mod 10 = 0 // first collision occurs.M at index (13-1+1) mod 10 = 3 //second collision occurs."
},
{
"code": null,
"e": 902,
"s": 862,
"text": "Only J and M are causing the collision."
},
{
"code": null,
"e": 932,
"s": 902,
"text": "(b) Final Hash table will be:"
},
{
"code": null,
"e": 1002,
"s": 932,
"text": "0 T\n1 K\n2 J\n3 C\n4 N\n5 Y\n6 P\n7 M\n8 R\n9 S"
},
{
"code": null,
"e": 1024,
"s": 1002,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1037,
"s": 1024,
"text": "GATE CS 1996"
},
{
"code": null,
"e": 1055,
"s": 1037,
"text": "GATE-GATE CS 1996"
},
{
"code": null,
"e": 1060,
"s": 1055,
"text": "GATE"
},
{
"code": null,
"e": 1158,
"s": 1060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1200,
"s": 1158,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1262,
"s": 1200,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1304,
"s": 1262,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 1338,
"s": 1304,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1372,
"s": 1338,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1414,
"s": 1372,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1456,
"s": 1414,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 1490,
"s": 1456,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 1524,
"s": 1490,
"text": "GATE | GATE-CS-2004 | Question 31"
}
]
|
Find (a^b)%m where ‘b’ is very large | 02 Feb, 2022
Given three numbers a, b and m where 1<=a, m<=10^6. Given very large ‘b’ containing up to 10^6 digits and m is a prime number, the task is to find (a^b)%m.Examples:
Input: a = 2, b = 3, m = 17 Output: 8 2 ^ 3 % 17 = 8Input: a = 3, b = 100000000000000000000000000, m = 1000000007 Output: 835987331
Iterative Approach: According to Fermat’s little theorem and Modular Exponentiation,
a^(p-1) mod p = 1, When p is prime.
From this, as of the problem, M is prime, express A^B mod M as follows:
A^B mod M = ( A^(M-1) * A^(M-1) *.......* A^(M-1) * A^(x) ) mod M
Where x is B mod M-1 and A ^ (M-1) continues B/(M-1) timesNow, from Fermat’s Little Theorem,
A ^ (M-1) mod M = 1.
Hence,
A^B mod M = ( 1 * 1 * ....... * 1 * A^(x) ) mod M
Hence mod B with M-1 to reduce the number to a smaller one and then use power() method to compute (a^b)%m. Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
// C++ program to find// (a^b)%m for b very large.#include <bits/stdc++.h>#define ll long long intusing namespace std; // Function to find powerll power(ll x, ll y, ll p){ ll res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with the result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;}// Driver Codeint main(){ ll a = 3; // String input as b is very large string b = "100000000000000000000000000"; ll remainderB = 0; ll MOD = 1000000007; // Reduce the number B to a small number // using Fermat Little for (int i = 0; i < b.length(); i++) remainderB = (remainderB * 10 + b[i] - '0') % (MOD - 1); cout << power(a, remainderB, MOD) << endl; return 0;}
// Java program to find// (a^b)%m for b very large.import java.io.*; class GFG{ // Function to find powerstatic long power(long x, long y, long p){ long res = 1; // Initialize result // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with the result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Driver Codepublic static void main (String[] args){long a = 3; // String input as// b is very largeString b = "100000000000000000000000000"; long remainderB = 0;long MOD = 1000000007; // Reduce the number B to a small// number using Fermat Littlefor (int i = 0; i < b.length(); i++) remainderB = (remainderB * 10 + b.charAt(i) - '0') % (MOD - 1); System.out.println(power(a, remainderB, MOD));}} // This code is contributed by anuj_67.
# Python3 program to find# (a^b)%m for b very large. # Function to find powerdef power(x, y, p): res = 1 # Initialize result # Update x if it is # more than or equal to p x = x % p while (y > 0): # If y is odd, multiply # x with the result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Driver Codea = 3 # String input as b# is very largeb = "100000000000000000000000000" remainderB = 0MOD = 1000000007 # Reduce the number B# to a small number# using Fermat Littlefor i in range(len(b)): remainderB = ((remainderB * 10 + ord(b[i]) - 48) % (MOD - 1)) print(power(a, remainderB, MOD)) # This code is contributed by mits
// C# program to find// (a^b)%m for b very large.using System; class GFG{ // Function to find powerstatic long power(long x, long y, long p){ // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with the result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Driver Codepublic static void Main (){ long a = 3; // String input as // b is very large string b = "100000000000000000000000000"; long remainderB = 0; long MOD = 1000000007; // Reduce the number B to // a small number using // Fermat Little for (int i = 0; i < b.Length; i++) remainderB = (remainderB * 10 + b[i] - '0') % (MOD - 1); Console.WriteLine(power(a, remainderB, MOD));}} // This code is contributed by anuj_67.
<?php// PHP program to find// (a^b)%m for b very large. // Function to find powerfunction power($x, $y, $p){ $res = 1; // Initialize result // Update x if it is // more than or equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with the result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Driver Code$a = 3; // String input as b// is very large$b = "100000000000000000000000000"; $remainderB = 0;$MOD = 1000000007; // Reduce the number B// to a small number// using Fermat Littlefor ($i = 0; $i < strlen($b); $i++) $remainderB = ($remainderB * 10 + $b[$i] - '0') % ($MOD - 1); echo power($a, $remainderB, $MOD); // This code is contributed by mits?>
835987331
Time Complexity: O(len(b)+log b)
Auxiliary Space: O(1)
Recursive Approach: It is same to the above implementation except the fact that we have to pass each subproblem result to the backtracking recursion stack.
C++14
#include <bits/stdc++.h>using namespace std;typedef long long ll; // Reduce the number B to a small number // using Fermat Littlell MOD(string num,int mod){ ll res=0; for(int i=0;i<num.length();i++) res=(res*10+num[i]-'0')%(mod-1); return res;} ll ModExponent(ll a,ll b,ll m){ ll result; if(a==0) return 0; else if(b==0) return 1; else if(b&1) { result=a%m; result=result*ModExponent(a,b-1,m); } else{ result=ModExponent(a,b/2,m); result=((result%m)*(result%m))%m; } return (result%m+m)%m;} int main(){ ll a = 3; // String input as b is very large string b = "100000000000000000000000000"; ll m = 1000000007; ll remainderB = MOD(b,m); cout << ModExponent(a, remainderB, m) << endl; return 0;}
835987331
Time Complexity: O(len(b)+log b)
Auxiliary Space: O(log b)
vt_m
Mithun Kumar
arvindtraj2001
prophet1999
math
Modular Arithmetic
number-theory
Competitive Programming
Mathematical
number-theory
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "Given three numbers a, b and m where 1<=a, m<=10^6. Given very large ‘b’ containing up to 10^6 digits and m is a prime number, the task is to find (a^b)%m.Examples: "
},
{
"code": null,
"e": 350,
"s": 218,
"text": "Input: a = 2, b = 3, m = 17 Output: 8 2 ^ 3 % 17 = 8Input: a = 3, b = 100000000000000000000000000, m = 1000000007 Output: 835987331"
},
{
"code": null,
"e": 435,
"s": 350,
"text": "Iterative Approach: According to Fermat’s little theorem and Modular Exponentiation,"
},
{
"code": null,
"e": 471,
"s": 435,
"text": "a^(p-1) mod p = 1, When p is prime."
},
{
"code": null,
"e": 544,
"s": 471,
"text": "From this, as of the problem, M is prime, express A^B mod M as follows: "
},
{
"code": null,
"e": 610,
"s": 544,
"text": "A^B mod M = ( A^(M-1) * A^(M-1) *.......* A^(M-1) * A^(x) ) mod M"
},
{
"code": null,
"e": 705,
"s": 610,
"text": "Where x is B mod M-1 and A ^ (M-1) continues B/(M-1) timesNow, from Fermat’s Little Theorem, "
},
{
"code": null,
"e": 726,
"s": 705,
"text": "A ^ (M-1) mod M = 1."
},
{
"code": null,
"e": 734,
"s": 726,
"text": "Hence, "
},
{
"code": null,
"e": 784,
"s": 734,
"text": "A^B mod M = ( 1 * 1 * ....... * 1 * A^(x) ) mod M"
},
{
"code": null,
"e": 944,
"s": 784,
"text": "Hence mod B with M-1 to reduce the number to a smaller one and then use power() method to compute (a^b)%m. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 948,
"s": 944,
"text": "C++"
},
{
"code": null,
"e": 953,
"s": 948,
"text": "Java"
},
{
"code": null,
"e": 961,
"s": 953,
"text": "Python3"
},
{
"code": null,
"e": 964,
"s": 961,
"text": "C#"
},
{
"code": null,
"e": 968,
"s": 964,
"text": "PHP"
},
{
"code": "// C++ program to find// (a^b)%m for b very large.#include <bits/stdc++.h>#define ll long long intusing namespace std; // Function to find powerll power(ll x, ll y, ll p){ ll res = 1; // Initialize result // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with the result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;}// Driver Codeint main(){ ll a = 3; // String input as b is very large string b = \"100000000000000000000000000\"; ll remainderB = 0; ll MOD = 1000000007; // Reduce the number B to a small number // using Fermat Little for (int i = 0; i < b.length(); i++) remainderB = (remainderB * 10 + b[i] - '0') % (MOD - 1); cout << power(a, remainderB, MOD) << endl; return 0;}",
"e": 1914,
"s": 968,
"text": null
},
{
"code": "// Java program to find// (a^b)%m for b very large.import java.io.*; class GFG{ // Function to find powerstatic long power(long x, long y, long p){ long res = 1; // Initialize result // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with the result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Driver Codepublic static void main (String[] args){long a = 3; // String input as// b is very largeString b = \"100000000000000000000000000\"; long remainderB = 0;long MOD = 1000000007; // Reduce the number B to a small// number using Fermat Littlefor (int i = 0; i < b.length(); i++) remainderB = (remainderB * 10 + b.charAt(i) - '0') % (MOD - 1); System.out.println(power(a, remainderB, MOD));}} // This code is contributed by anuj_67.",
"e": 2909,
"s": 1914,
"text": null
},
{
"code": "# Python3 program to find# (a^b)%m for b very large. # Function to find powerdef power(x, y, p): res = 1 # Initialize result # Update x if it is # more than or equal to p x = x % p while (y > 0): # If y is odd, multiply # x with the result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Driver Codea = 3 # String input as b# is very largeb = \"100000000000000000000000000\" remainderB = 0MOD = 1000000007 # Reduce the number B# to a small number# using Fermat Littlefor i in range(len(b)): remainderB = ((remainderB * 10 + ord(b[i]) - 48) % (MOD - 1)) print(power(a, remainderB, MOD)) # This code is contributed by mits",
"e": 3714,
"s": 2909,
"text": null
},
{
"code": "// C# program to find// (a^b)%m for b very large.using System; class GFG{ // Function to find powerstatic long power(long x, long y, long p){ // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply // x with the result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Driver Codepublic static void Main (){ long a = 3; // String input as // b is very large string b = \"100000000000000000000000000\"; long remainderB = 0; long MOD = 1000000007; // Reduce the number B to // a small number using // Fermat Little for (int i = 0; i < b.Length; i++) remainderB = (remainderB * 10 + b[i] - '0') % (MOD - 1); Console.WriteLine(power(a, remainderB, MOD));}} // This code is contributed by anuj_67.",
"e": 4769,
"s": 3714,
"text": null
},
{
"code": "<?php// PHP program to find// (a^b)%m for b very large. // Function to find powerfunction power($x, $y, $p){ $res = 1; // Initialize result // Update x if it is // more than or equal to p $x = $x % $p; while ($y > 0) { // If y is odd, multiply // x with the result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Driver Code$a = 3; // String input as b// is very large$b = \"100000000000000000000000000\"; $remainderB = 0;$MOD = 1000000007; // Reduce the number B// to a small number// using Fermat Littlefor ($i = 0; $i < strlen($b); $i++) $remainderB = ($remainderB * 10 + $b[$i] - '0') % ($MOD - 1); echo power($a, $remainderB, $MOD); // This code is contributed by mits?>",
"e": 5637,
"s": 4769,
"text": null
},
{
"code": null,
"e": 5648,
"s": 5637,
"text": "835987331\n"
},
{
"code": null,
"e": 5681,
"s": 5648,
"text": "Time Complexity: O(len(b)+log b)"
},
{
"code": null,
"e": 5703,
"s": 5681,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5859,
"s": 5703,
"text": "Recursive Approach: It is same to the above implementation except the fact that we have to pass each subproblem result to the backtracking recursion stack."
},
{
"code": null,
"e": 5865,
"s": 5859,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h>using namespace std;typedef long long ll; // Reduce the number B to a small number // using Fermat Littlell MOD(string num,int mod){ ll res=0; for(int i=0;i<num.length();i++) res=(res*10+num[i]-'0')%(mod-1); return res;} ll ModExponent(ll a,ll b,ll m){ ll result; if(a==0) return 0; else if(b==0) return 1; else if(b&1) { result=a%m; result=result*ModExponent(a,b-1,m); } else{ result=ModExponent(a,b/2,m); result=((result%m)*(result%m))%m; } return (result%m+m)%m;} int main(){ ll a = 3; // String input as b is very large string b = \"100000000000000000000000000\"; ll m = 1000000007; ll remainderB = MOD(b,m); cout << ModExponent(a, remainderB, m) << endl; return 0;}",
"e": 6672,
"s": 5865,
"text": null
},
{
"code": null,
"e": 6683,
"s": 6672,
"text": "835987331\n"
},
{
"code": null,
"e": 6716,
"s": 6683,
"text": "Time Complexity: O(len(b)+log b)"
},
{
"code": null,
"e": 6742,
"s": 6716,
"text": "Auxiliary Space: O(log b)"
},
{
"code": null,
"e": 6747,
"s": 6742,
"text": "vt_m"
},
{
"code": null,
"e": 6760,
"s": 6747,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6775,
"s": 6760,
"text": "arvindtraj2001"
},
{
"code": null,
"e": 6787,
"s": 6775,
"text": "prophet1999"
},
{
"code": null,
"e": 6792,
"s": 6787,
"text": "math"
},
{
"code": null,
"e": 6811,
"s": 6792,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 6825,
"s": 6811,
"text": "number-theory"
},
{
"code": null,
"e": 6849,
"s": 6825,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6862,
"s": 6849,
"text": "Mathematical"
},
{
"code": null,
"e": 6876,
"s": 6862,
"text": "number-theory"
},
{
"code": null,
"e": 6889,
"s": 6876,
"text": "Mathematical"
},
{
"code": null,
"e": 6908,
"s": 6889,
"text": "Modular Arithmetic"
}
]
|
Python map() function | 07 Jul, 2022
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.iter : It is a iterable which is to be mapped.
NOTE : You can pass one or more iterable to the map() function.
Returns :
Returns a list of the results after applying the given function
to each item of a given iterable (list, tuple etc.)
NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) . CODE 1
# Python program to demonstrate working# of map. # Return double of ndef addition(n): return n + n # We double all numbers using map()numbers = (1, 2, 3, 4)result = map(addition, numbers)print(list(result))
Output :
[2, 4, 6, 8]
CODE 2We can also use lambda expressions with map to achieve above result.
# Double all numbers using map and lambda numbers = (1, 2, 3, 4)result = map(lambda x: x + x, numbers)print(list(result))
Output :
[2, 4, 6, 8]
CODE 3
# Add two lists using map and lambda numbers1 = [1, 2, 3]numbers2 = [4, 5, 6] result = map(lambda x, y: x + y, numbers1, numbers2)print(list(result))
Output :
[5, 7, 9]
CODE 4
# List of stringsl = ['sat', 'bat', 'cat', 'mat'] # map() can listify the list of strings individuallytest = list(map(list, l))print(test)
Output :
[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
link111
piyushkhanna30
python-list
python-list-functions
python-map
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 211,
"s": 52,
"text": "map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)"
},
{
"code": null,
"e": 220,
"s": 211,
"text": "Syntax :"
},
{
"code": null,
"e": 236,
"s": 220,
"text": "map(fun, iter)\n"
},
{
"code": null,
"e": 249,
"s": 236,
"text": "Parameters :"
},
{
"code": null,
"e": 370,
"s": 249,
"text": "fun : It is a function to which map passes each element of given iterable.iter : It is a iterable which is to be mapped."
},
{
"code": null,
"e": 434,
"s": 370,
"text": "NOTE : You can pass one or more iterable to the map() function."
},
{
"code": null,
"e": 444,
"s": 434,
"text": "Returns :"
},
{
"code": null,
"e": 564,
"s": 444,
"text": "Returns a list of the results after applying the given function \nto each item of a given iterable (list, tuple etc.) \n"
},
{
"code": null,
"e": 712,
"s": 564,
"text": " NOTE : The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) . CODE 1"
},
{
"code": "# Python program to demonstrate working# of map. # Return double of ndef addition(n): return n + n # We double all numbers using map()numbers = (1, 2, 3, 4)result = map(addition, numbers)print(list(result))",
"e": 924,
"s": 712,
"text": null
},
{
"code": null,
"e": 933,
"s": 924,
"text": "Output :"
},
{
"code": null,
"e": 947,
"s": 933,
"text": "[2, 4, 6, 8]\n"
},
{
"code": null,
"e": 1023,
"s": 947,
"text": " CODE 2We can also use lambda expressions with map to achieve above result."
},
{
"code": "# Double all numbers using map and lambda numbers = (1, 2, 3, 4)result = map(lambda x: x + x, numbers)print(list(result))",
"e": 1146,
"s": 1023,
"text": null
},
{
"code": null,
"e": 1155,
"s": 1146,
"text": "Output :"
},
{
"code": null,
"e": 1169,
"s": 1155,
"text": "[2, 4, 6, 8]\n"
},
{
"code": null,
"e": 1177,
"s": 1169,
"text": " CODE 3"
},
{
"code": "# Add two lists using map and lambda numbers1 = [1, 2, 3]numbers2 = [4, 5, 6] result = map(lambda x, y: x + y, numbers1, numbers2)print(list(result))",
"e": 1329,
"s": 1177,
"text": null
},
{
"code": null,
"e": 1338,
"s": 1329,
"text": "Output :"
},
{
"code": null,
"e": 1349,
"s": 1338,
"text": "[5, 7, 9]\n"
},
{
"code": null,
"e": 1357,
"s": 1349,
"text": " CODE 4"
},
{
"code": "# List of stringsl = ['sat', 'bat', 'cat', 'mat'] # map() can listify the list of strings individuallytest = list(map(list, l))print(test)",
"e": 1497,
"s": 1357,
"text": null
},
{
"code": null,
"e": 1506,
"s": 1497,
"text": "Output :"
},
{
"code": null,
"e": 1575,
"s": 1506,
"text": "[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]"
},
{
"code": null,
"e": 1583,
"s": 1575,
"text": "link111"
},
{
"code": null,
"e": 1598,
"s": 1583,
"text": "piyushkhanna30"
},
{
"code": null,
"e": 1610,
"s": 1598,
"text": "python-list"
},
{
"code": null,
"e": 1632,
"s": 1610,
"text": "python-list-functions"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": "python-map"
},
{
"code": null,
"e": 1650,
"s": 1643,
"text": "Python"
},
{
"code": null,
"e": 1662,
"s": 1650,
"text": "python-list"
},
{
"code": null,
"e": 1760,
"s": 1662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1792,
"s": 1760,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1821,
"s": 1792,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1848,
"s": 1821,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1869,
"s": 1848,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1892,
"s": 1869,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1928,
"s": 1892,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1959,
"s": 1928,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1996,
"s": 1959,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 2052,
"s": 1996,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
]
|
Queries to count numbers from given range which are divisible by all its digits | 21 Apr, 2021
Given a 2D array arr[][] with each row of the form of a query { L, R }, the task is to count the numbers in the range [L, R] such that the number is divisible by all of its non-zero digit.
Examples:
Input: arr[][] ={ {1, 5}, {12, 14} } Output: 5 1 Explanation: Query1: All the numbers in the range [1, 5] are divisible by their digits. Query2: Numbers in the range [12, 14] which are divisible by all of its digits is 12 only.
Input: arr[][] = { {1, 20} } Output:14 Explanation: Numbers in the range [1, 20] which are divisible by all of its non-zero digits are: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20}
Naive Approach: The simplest approach to solve this problem is to traverse the array arr[][] and for every ith row of the array, iterate over the range [L, R]. For every element in the range, check if the number is divisible by all of its non-zero digits or not. If found to be true, then increment the count. Finally, print the count obtained. Time Complexity: O(N * (R – L)), where N is the count of rows Auxiliary Space: O(1)
Efficient approach: The above approach can be optimized by finding the maximum possible value of arr[i][1] and precompute the count of numbers which is divisible by its non-zero digits using Prefix Sum technique. Follow the steps below to solve the problem:
Initialize a variable, say Max, to store the maximum possible value of arr[i][1].
Initialize an array, say prefCntDiv[], where prefCntDiv[i] stores the count of numbers from the range [1, i] which is divisible by its non-zero digits.
Iterate over the range [1, Max]. For every ith iteration, check if i is divisible by all of its non-zero digits or not. If found to be true, then update prefCntDiv[i] = prefCntDiv[i – 1] + 1.
Otherwise, update prefCntDiv[i] = prefCntDiv[i – 1].
Traverse the array arr[]. For every ith row of the array, print prefCntDiv[arr[i][1]] – prefCntDiv[arr[i][0] – 1].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std;#define Max 1000005 // Function to check if a number is divisible// by all of its non-zero digits or notbool CheckDivByAllDigits(int number){ // Stores the number int n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10) // If number is not divisible // by its current digit if (number % (n % 10)) { return false; } // Update n n /= 10; } return true;} // Function to count of numbers which are// divisible by all of its non-zero// digits in the range [1, i]void cntNumInRang(int arr[][2], int N){ // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] int prefCntDiv[Max] = { 0 }; // Iterate over the range [1, Max] for (int i = 1; i <= Max; i++) { // Update prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i)); } // Traverse the array, arr[] for (int i = 0; i < N; i++) cout << (prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1]) << " ";} // Driver Codeint main(){ int arr[][2] = { { 1, 5 }, { 12, 14 } }; int N = sizeof(arr) / sizeof(arr[0]); cntNumInRang(arr, N); return 0;}
// Java program to implement// the above approachimport java.io.*;class GFG{ public static int Max = 1000005; // Function to check if a number is divisible // by all of its non-zero digits or not static boolean CheckDivByAllDigits(int number) { // Stores the number int n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10 != 0) // If number is not divisible // by its current digit if (number % (n % 10) != 0) { return false; } // Update n n /= 10; } return true; } // Function to count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] static void cntNumInRang(int arr[][], int N) { // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] int prefCntDiv[] = new int[Max + 1]; // Iterate over the range [1, Max] for (int i = 1; i <= Max; i++) { int ans = 0; if (CheckDivByAllDigits(i)) ans = 1; // Update prefCntDiv[i] = prefCntDiv[i - 1] + ans; } // Traverse the array, arr[] for (int i = 0; i < N; i++) System.out.print((prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1]) + " "); } // Driver Code public static void main(String[] args) { int arr[][] = { { 1, 5 }, { 12, 14 } }; int N = arr.length; cntNumInRang(arr, N); }} // This code is contributed by Dharanendra L V
# Python3 program to implement# the above approach # Function to check if a number is divisible# by all of its non-zero digits or notdef CheckDivByAllDigits(number): # Stores the number n = number # Iterate over the digits # of the numbers while (n > 0): # If digit of number # is non-zero if (n % 10): # If number is not divisible # by its current digit if (number % (n % 10)): return False # Update n n //= 10 return True # Function to count of numbers which are# divisible by all of its non-zero# digits in the range [1, i]def cntNumInRang(arr, N): global Max # Stores count of numbers which are # divisible by all of its non-zero # digits in the range [1, i] prefCntDiv = [0]*Max # Iterate over the range [1, Max] for i in range(1, Max): # Update prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i)) # Traverse the array, arr[] for i in range(N): print(prefCntDiv[arr[i][1]]- prefCntDiv[arr[i][0] - 1], end = " ") # Driver Codeif __name__ == '__main__': arr =[ [ 1, 5 ], [12, 14]] Max = 1000005 N = len(arr) cntNumInRang(arr, N) # This code is contributed by mohit kumar 29.
// C# program to implement// the above approachusing System;class GFG{ public static int Max = 1000005; // Function to check if a number is divisible // by all of its non-zero digits or not static bool CheckDivByAllDigits(int number) { // Stores the number int n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10 != 0) // If number is not divisible // by its current digit if (number % (n % 10) != 0) { return false; } // Update n n /= 10; } return true; } // Function to count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] static void cntNumInRang(int[, ] arr, int N) { // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] int[] prefCntDiv = new int[Max + 1]; // Iterate over the range [1, Max] for (int i = 1; i <= Max; i++) { int ans = 0; if (CheckDivByAllDigits(i)) ans = 1; // Update prefCntDiv[i] = prefCntDiv[i - 1] + ans; } // Traverse the array, arr[] for (int i = 0; i < N; i++) Console.Write((prefCntDiv[arr[i, 1]] - prefCntDiv[arr[i, 0] - 1]) + " "); } // Driver Code public static void Main(string[] args) { int[, ] arr = { { 1, 5 }, { 12, 14 } }; int N = arr.GetLength(0); cntNumInRang(arr, N); }} // This code is contributed by chitranayal.
<script>// Javascript program to implement// the above approach const Max = 1000005; // Function to check if a number is divisible// by all of its non-zero digits or notfunction CheckDivByAllDigits(number){ // Stores the number let n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10) // If number is not divisible // by its current digit if (number % (n % 10)) { return false; } // Update n n = parseInt(n / 10); } return true;} // Function to count of numbers which are// divisible by all of its non-zero// digits in the range [1, i]function cntNumInRang(arr, N){ // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] let prefCntDiv = new Array(Max).fill(0); // Iterate over the range [1, Max] for (let i = 1; i <= Max; i++) { // Update prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i)); } // Traverse the array, arr[] for (let i = 0; i < N; i++) document.write((prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1]) + " ");} // Driver Code let arr = [ [ 1, 5 ], [ 12, 14 ] ]; let N = arr.length; cntNumInRang(arr, N); </script>
5 1
Time Complexity: O(N + Max), where Max is the maximum value of arr[i][1]Auxiliary Space: O(N)
mohit kumar 29
dharanendralv23
ukasp
rishavmahato348
array-range-queries
divisibility
number-digits
prefix-sum
Greedy
Mathematical
Searching
Technical Scripter
prefix-sum
Searching
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "Given a 2D array arr[][] with each row of the form of a query { L, R }, the task is to count the numbers in the range [L, R] such that the number is divisible by all of its non-zero digit."
},
{
"code": null,
"e": 227,
"s": 217,
"text": "Examples:"
},
{
"code": null,
"e": 455,
"s": 227,
"text": "Input: arr[][] ={ {1, 5}, {12, 14} } Output: 5 1 Explanation: Query1: All the numbers in the range [1, 5] are divisible by their digits. Query2: Numbers in the range [12, 14] which are divisible by all of its digits is 12 only."
},
{
"code": null,
"e": 640,
"s": 455,
"text": "Input: arr[][] = { {1, 20} } Output:14 Explanation: Numbers in the range [1, 20] which are divisible by all of its non-zero digits are: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20}"
},
{
"code": null,
"e": 1069,
"s": 640,
"text": "Naive Approach: The simplest approach to solve this problem is to traverse the array arr[][] and for every ith row of the array, iterate over the range [L, R]. For every element in the range, check if the number is divisible by all of its non-zero digits or not. If found to be true, then increment the count. Finally, print the count obtained. Time Complexity: O(N * (R – L)), where N is the count of rows Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1327,
"s": 1069,
"text": "Efficient approach: The above approach can be optimized by finding the maximum possible value of arr[i][1] and precompute the count of numbers which is divisible by its non-zero digits using Prefix Sum technique. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1409,
"s": 1327,
"text": "Initialize a variable, say Max, to store the maximum possible value of arr[i][1]."
},
{
"code": null,
"e": 1561,
"s": 1409,
"text": "Initialize an array, say prefCntDiv[], where prefCntDiv[i] stores the count of numbers from the range [1, i] which is divisible by its non-zero digits."
},
{
"code": null,
"e": 1753,
"s": 1561,
"text": "Iterate over the range [1, Max]. For every ith iteration, check if i is divisible by all of its non-zero digits or not. If found to be true, then update prefCntDiv[i] = prefCntDiv[i – 1] + 1."
},
{
"code": null,
"e": 1806,
"s": 1753,
"text": "Otherwise, update prefCntDiv[i] = prefCntDiv[i – 1]."
},
{
"code": null,
"e": 1921,
"s": 1806,
"text": "Traverse the array arr[]. For every ith row of the array, print prefCntDiv[arr[i][1]] – prefCntDiv[arr[i][0] – 1]."
},
{
"code": null,
"e": 1972,
"s": 1921,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1976,
"s": 1972,
"text": "C++"
},
{
"code": null,
"e": 1981,
"s": 1976,
"text": "Java"
},
{
"code": null,
"e": 1989,
"s": 1981,
"text": "Python3"
},
{
"code": null,
"e": 1992,
"s": 1989,
"text": "C#"
},
{
"code": null,
"e": 2003,
"s": 1992,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std;#define Max 1000005 // Function to check if a number is divisible// by all of its non-zero digits or notbool CheckDivByAllDigits(int number){ // Stores the number int n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10) // If number is not divisible // by its current digit if (number % (n % 10)) { return false; } // Update n n /= 10; } return true;} // Function to count of numbers which are// divisible by all of its non-zero// digits in the range [1, i]void cntNumInRang(int arr[][2], int N){ // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] int prefCntDiv[Max] = { 0 }; // Iterate over the range [1, Max] for (int i = 1; i <= Max; i++) { // Update prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i)); } // Traverse the array, arr[] for (int i = 0; i < N; i++) cout << (prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1]) << \" \";} // Driver Codeint main(){ int arr[][2] = { { 1, 5 }, { 12, 14 } }; int N = sizeof(arr) / sizeof(arr[0]); cntNumInRang(arr, N); return 0;}",
"e": 3436,
"s": 2003,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.io.*;class GFG{ public static int Max = 1000005; // Function to check if a number is divisible // by all of its non-zero digits or not static boolean CheckDivByAllDigits(int number) { // Stores the number int n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10 != 0) // If number is not divisible // by its current digit if (number % (n % 10) != 0) { return false; } // Update n n /= 10; } return true; } // Function to count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] static void cntNumInRang(int arr[][], int N) { // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] int prefCntDiv[] = new int[Max + 1]; // Iterate over the range [1, Max] for (int i = 1; i <= Max; i++) { int ans = 0; if (CheckDivByAllDigits(i)) ans = 1; // Update prefCntDiv[i] = prefCntDiv[i - 1] + ans; } // Traverse the array, arr[] for (int i = 0; i < N; i++) System.out.print((prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1]) + \" \"); } // Driver Code public static void main(String[] args) { int arr[][] = { { 1, 5 }, { 12, 14 } }; int N = arr.length; cntNumInRang(arr, N); }} // This code is contributed by Dharanendra L V",
"e": 4999,
"s": 3436,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if a number is divisible# by all of its non-zero digits or notdef CheckDivByAllDigits(number): # Stores the number n = number # Iterate over the digits # of the numbers while (n > 0): # If digit of number # is non-zero if (n % 10): # If number is not divisible # by its current digit if (number % (n % 10)): return False # Update n n //= 10 return True # Function to count of numbers which are# divisible by all of its non-zero# digits in the range [1, i]def cntNumInRang(arr, N): global Max # Stores count of numbers which are # divisible by all of its non-zero # digits in the range [1, i] prefCntDiv = [0]*Max # Iterate over the range [1, Max] for i in range(1, Max): # Update prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i)) # Traverse the array, arr[] for i in range(N): print(prefCntDiv[arr[i][1]]- prefCntDiv[arr[i][0] - 1], end = \" \") # Driver Codeif __name__ == '__main__': arr =[ [ 1, 5 ], [12, 14]] Max = 1000005 N = len(arr) cntNumInRang(arr, N) # This code is contributed by mohit kumar 29.",
"e": 6265,
"s": 4999,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ public static int Max = 1000005; // Function to check if a number is divisible // by all of its non-zero digits or not static bool CheckDivByAllDigits(int number) { // Stores the number int n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10 != 0) // If number is not divisible // by its current digit if (number % (n % 10) != 0) { return false; } // Update n n /= 10; } return true; } // Function to count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] static void cntNumInRang(int[, ] arr, int N) { // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] int[] prefCntDiv = new int[Max + 1]; // Iterate over the range [1, Max] for (int i = 1; i <= Max; i++) { int ans = 0; if (CheckDivByAllDigits(i)) ans = 1; // Update prefCntDiv[i] = prefCntDiv[i - 1] + ans; } // Traverse the array, arr[] for (int i = 0; i < N; i++) Console.Write((prefCntDiv[arr[i, 1]] - prefCntDiv[arr[i, 0] - 1]) + \" \"); } // Driver Code public static void Main(string[] args) { int[, ] arr = { { 1, 5 }, { 12, 14 } }; int N = arr.GetLength(0); cntNumInRang(arr, N); }} // This code is contributed by chitranayal.",
"e": 7807,
"s": 6265,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach const Max = 1000005; // Function to check if a number is divisible// by all of its non-zero digits or notfunction CheckDivByAllDigits(number){ // Stores the number let n = number; // Iterate over the digits // of the numbers while (n > 0) { // If digit of number // is non-zero if (n % 10) // If number is not divisible // by its current digit if (number % (n % 10)) { return false; } // Update n n = parseInt(n / 10); } return true;} // Function to count of numbers which are// divisible by all of its non-zero// digits in the range [1, i]function cntNumInRang(arr, N){ // Stores count of numbers which are // divisible by all of its non-zero // digits in the range [1, i] let prefCntDiv = new Array(Max).fill(0); // Iterate over the range [1, Max] for (let i = 1; i <= Max; i++) { // Update prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i)); } // Traverse the array, arr[] for (let i = 0; i < N; i++) document.write((prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1]) + \" \");} // Driver Code let arr = [ [ 1, 5 ], [ 12, 14 ] ]; let N = arr.length; cntNumInRang(arr, N); </script>",
"e": 9197,
"s": 7807,
"text": null
},
{
"code": null,
"e": 9201,
"s": 9197,
"text": "5 1"
},
{
"code": null,
"e": 9297,
"s": 9203,
"text": "Time Complexity: O(N + Max), where Max is the maximum value of arr[i][1]Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9312,
"s": 9297,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9328,
"s": 9312,
"text": "dharanendralv23"
},
{
"code": null,
"e": 9334,
"s": 9328,
"text": "ukasp"
},
{
"code": null,
"e": 9350,
"s": 9334,
"text": "rishavmahato348"
},
{
"code": null,
"e": 9370,
"s": 9350,
"text": "array-range-queries"
},
{
"code": null,
"e": 9383,
"s": 9370,
"text": "divisibility"
},
{
"code": null,
"e": 9397,
"s": 9383,
"text": "number-digits"
},
{
"code": null,
"e": 9408,
"s": 9397,
"text": "prefix-sum"
},
{
"code": null,
"e": 9415,
"s": 9408,
"text": "Greedy"
},
{
"code": null,
"e": 9428,
"s": 9415,
"text": "Mathematical"
},
{
"code": null,
"e": 9438,
"s": 9428,
"text": "Searching"
},
{
"code": null,
"e": 9457,
"s": 9438,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9468,
"s": 9457,
"text": "prefix-sum"
},
{
"code": null,
"e": 9478,
"s": 9468,
"text": "Searching"
},
{
"code": null,
"e": 9485,
"s": 9478,
"text": "Greedy"
},
{
"code": null,
"e": 9498,
"s": 9485,
"text": "Mathematical"
},
{
"code": null,
"e": 9596,
"s": 9498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9627,
"s": 9596,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 9646,
"s": 9627,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 9689,
"s": 9646,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 9717,
"s": 9689,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 9740,
"s": 9717,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 9770,
"s": 9740,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9813,
"s": 9770,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9828,
"s": 9813,
"text": "C++ Data Types"
},
{
"code": null,
"e": 9852,
"s": 9828,
"text": "Merge two sorted arrays"
}
]
|
Pascal - File Handling | Pascal treats a file as a sequence of components, which must be of uniform type. A file's type is determined by the type of the components. File data type is defined as −
type
file-name = file of base-type;
Where, the base-type indicates the type of the components of the file. The base type could be anything like, integer, real, Boolean, enumerated, subrange, record, arrays and sets except another file type. Variables of a file type are created using the var declaration −
var
f1, f2,...: file-name;
Following are some examples of defining some file types and file variables −
type
rfile = file of real;
ifile = file of integer;
bfile = file of boolean;
datafile = file of record
arrfile = file of array[1..4] of integer;
var
marks: arrfile;
studentdata: datafile;
rainfalldata: rfile;
tempdata: ifile;
choices: bfile;
Let us write a program that would create a data file for students' records. It would create a file named students.dat and write a student's data into it −
program DataFiles;
type
StudentRecord = Record
s_name: String;
s_addr: String;
s_batchcode: String;
end;
var
Student: StudentRecord;
f: file of StudentRecord;
begin
Assign(f,'students.dat');
Rewrite(f);
Student.s_name := 'John Smith';
Student.s_addr := 'United States of America';
Student.s_batchcode := 'Computer Science';
Write(f,Student);
Close(f);
end.
When compiled and run, the program would create a file named students.dat into the working directory. You can open the file using a text editor, like notepad, to look at John Smith's data.
We have just created and written into a file named students.dat. Now, let us write a program that would read the student's data from the file −
program DataFiles;
type
StudentRecord = Record
s_name: String;
s_addr: String;
s_batchcode: String;
end;
var
Student: StudentRecord;
f: file of StudentRecord;
begin
assign(f, 'students.dat');
reset(f);
while not eof(f) do
begin
read(f,Student);
writeln('Name: ',Student.s_name);
writeln('Address: ',Student.s_addr);
writeln('Batch Code: ', Student.s_batchcode);
end;
close(f);
end.
When the above code is compiled and executed, it produces the following result −
Name: John Smith
Address: United States of America
Batch Code: Computer Science
Pascal allows file variables to be used as parameters in standard and user-defined subprograms. The following example illustrates this concept. The program creates a file named rainfall.txt and stores some rainfall data. Next, it opens the file, reads the data and computes the average rainfall.
Please note that, if you use a file parameter with subprograms, it must be declared as a var parameter.
program addFiledata;
const
MAX = 4;
type
raindata = file of real;
var
rainfile: raindata;
filename: string;
procedure writedata(var f: raindata);
var
data: real;
i: integer;
begin
rewrite(f, sizeof(data));
for i:=1 to MAX do
begin
writeln('Enter rainfall data: ');
readln(data);
write(f, data);
end;
close(f);
end;
procedure computeAverage(var x: raindata);
var
d, sum: real;
average: real;
begin
reset(x);
sum:= 0.0;
while not eof(x) do
begin
read(x, d);
sum := sum + d;
end;
average := sum/MAX;
close(x);
writeln('Average Rainfall: ', average:7:2);
end;
begin
writeln('Enter the File Name: ');
readln(filename);
assign(rainfile, filename);
writedata(rainfile);
computeAverage(rainfile);
end.
When the above code is compiled and executed, it produces the following result −
Enter the File Name:
rainfall.txt
Enter rainfall data:
34
Enter rainfall data:
45
Enter rainfall data:
56
Enter rainfall data:
78
Average Rainfall: 53.25
A text file, in Pascal, consists of lines of characters where each line is terminated with an end-of-line marker. You can declare and define such files as −
type
file-name = text;
Difference between a normal file of characters and a text file is that a text file is divided into lines, each terminated by a special end-of-line marker, automatically inserted by the system. The following example creates and writes into a text file named contact.txt −
program exText;
var
filename, data: string;
myfile: text;
begin
writeln('Enter the file name: ');
readln(filename);
assign(myfile, filename);
rewrite(myfile);
writeln(myfile, 'Note to Students: ');
writeln(myfile, 'For details information on Pascal Programming');
writeln(myfile, 'Contact: Tutorials Point');
writeln('Completed writing');
close(myfile);
end.
When the above code is compiled and executed, it produces the following result −
Enter the file name:
contact.txt
Completed writing
Appending to a file means writing to an existing file that already has some data without overwriting the file. The following program illustrates this −
program exAppendfile;
var
myfile: text;
info: string;
begin
assign(myfile, 'contact.txt');
append(myfile);
writeln('Contact Details');
writeln('[email protected]');
close(myfile);
(* let us read from this file *)
assign(myfile, 'contact.txt');
reset(myfile);
while not eof(myfile) do
begin
readln(myfile, info);
writeln(info);
end;
close(myfile);
end.
When the above code is compiled and executed, it produces the following result −
Contact Details
[email protected]
Note to Students:
For details information on Pascal Programming
Contact: Tutorials Point
Free Pascal provides the following functions/procedures for file handling −
procedure Append(var t: Text);
Opens a file in append mode
procedure Assign(out f: file; const Name:);
Assigns a name to a file
procedure Assign(out f: file; p: PChar);
Assigns a name to a file
procedure Assign(out f: file; c: Char);
Assigns a name to a file
procedure Assign(out f: TypedFile; const Name:);
Assigns a name to a file
procedure Assign(out f: TypedFile; p: PChar);
Assigns a name to a file
procedure Assign(out f: TypedFile; c: Char);
Assigns a name to a file
procedure Assign(out t: Text; const s:);
Assigns a name to a file
procedure Assign(out t: Text; p: PChar);
Assigns a name to a file
procedure Assign(out t: Text; c: Char);
Assigns a name to a file
procedure BlockRead(var f: file; var Buf; count: Int64; var Result: Int64);
Reads data from a file into memory
procedure BlockRead(var f: file; var Buf; count: LongInt; var Result: LongInt);
Reads data from a file into memory
procedure BlockRead(var f: file; var Buf; count: Cardinal; var Result: Cardinal);
Reads data from a file into memory
procedure BlockRead(var f: file; var Buf; count: Word; var Result: Word);
Reads data from a file into memory
procedure BlockRead(var f: file; var Buf; count: Word; var Result: Integer);
Reads data from a file into memory
procedure BlockRead(var f: file; var Buf; count: Int64);
Reads data from a file into memory
procedure BlockWrite(var f: file; const Buf; Count: Int64; var Result: Int64);
Writes data from memory to a file
procedure BlockWrite(var f: file; const Buf; Count: LongInt; var Result: LongInt);
Writes data from memory to a file
procedure BlockWrite(var f: file; const Buf; Count: Cardinal; var Result: Cardinal);
Writes data from memory to a file
procedure BlockWrite(var f: file; const Buf; Count: Word; var Result: Word);
Writes data from memory to a file
procedure BlockWrite(var f: file; const Buf; Count: Word; var Result: Integer);
Writes data from memory to a file
procedure BlockWrite(var f: file; const Buf; Count: LongInt);
Writes data from memory to a file
procedure Close(var f: file);
Closes a file
procedure Close(var t: Text);
Closes a file
function EOF(var f: file):Boolean;
Checks for end of file
function EOF(var t: Text):Boolean;
Checks for end of file
function EOF: Boolean;
Checks for end of file
function EOLn(var t: Text):Boolean;
Checks for end of line
function EOLn: Boolean;
Checks for end of line
procedure Erase(var f: file);
Deletes file from disk
procedure Erase(var t: Text);
Deletes file from disk
function FilePos( var f: file):Int64;
Position in file
function FileSize(var f: file):Int64;
Size of file
procedure Flush(var t: Text);
Writes file buffers to disk
function IOResult: Word;
Returns result of last file IO operation
procedure Read(var F: Text; Args: Arguments);
Reads from file into variable
procedure Read(Args: Arguments);
Reads from file into variable
procedure ReadLn(var F: Text; Args: Arguments);
Reads from file into variable and goto next line
procedure ReadLn(Args: Arguments);
Reads from file into variable and goto next line
procedure Rename(var f: file; const s:);
Renames file on disk
procedure Rename(var f: file; p: PChar);
Renames file on disk
procedure Rename(var f: file; c: Char);
Renames file on disk
procedure Rename(var t: Text; const s);
Rename file on disk
procedure Rename(var t: Text; p: PChar);
Renames file on disk
procedure Rename( var t: Text; c: Char);
Renames file on disk
procedure Reset(var f: file; l: LongInt);
Opens file for reading
procedure Reset(var f: file);
Opens file for reading
procedure Reset(var f: TypedFile);
Opens file for reading
procedure Reset(var t: Text);
Opens file for reading
procedure Rewrite(var f: file; l: LongInt);
Opens file for writing
procedure Rewrite(var f: file);
Opens file for writing
procedure Rewrite(var f: TypedFile);
Opens file for writing
procedure Rewrite(var t: Text);
Opens file for writing
procedure Seek(var f: file; Pos: Int64);
Sets file position
function SeekEOF(var t: Text):Boolean;
Sets file position to end of file
function SeekEOF: Boolean;
Sets file position to end of file
function SeekEOLn(var t: Text):Boolean;
Sets file position to end of line
function SeekEOLn: Boolean;
Sets file position to end of line
procedure SetTextBuf(var f: Text; var Buf);
Sets size of file buffer
procedure SetTextBuf(var f: Text; var Buf; Size: SizeInt);
Sets size of file buffer
procedure Truncate(var F: file);
Truncate the file at position
procedure Write(Args: Arguments);
Writes variable to file
procedure Write(var F: Text; Args: Arguments);
Write variable to file
procedure Writeln(Args: Arguments);
Writes variable to file and append newline
procedure WriteLn(var F: Text; Args: Arguments);
Writes variable to file and append newline | [
{
"code": null,
"e": 2388,
"s": 2217,
"text": "Pascal treats a file as a sequence of components, which must be of uniform type. A file's type is determined by the type of the components. File data type is defined as −"
},
{
"code": null,
"e": 2424,
"s": 2388,
"text": "type\nfile-name = file of base-type;"
},
{
"code": null,
"e": 2694,
"s": 2424,
"text": "Where, the base-type indicates the type of the components of the file. The base type could be anything like, integer, real, Boolean, enumerated, subrange, record, arrays and sets except another file type. Variables of a file type are created using the var declaration −"
},
{
"code": null,
"e": 2721,
"s": 2694,
"text": "var\nf1, f2,...: file-name;"
},
{
"code": null,
"e": 2798,
"s": 2721,
"text": "Following are some examples of defining some file types and file variables −"
},
{
"code": null,
"e": 3071,
"s": 2798,
"text": "type\n rfile = file of real;\n ifile = file of integer;\n bfile = file of boolean;\n datafile = file of record\n arrfile = file of array[1..4] of integer;\n\nvar\n marks: arrfile;\n studentdata: datafile;\n rainfalldata: rfile;\n tempdata: ifile;\n choices: bfile;"
},
{
"code": null,
"e": 3226,
"s": 3071,
"text": "Let us write a program that would create a data file for students' records. It would create a file named students.dat and write a student's data into it −"
},
{
"code": null,
"e": 3636,
"s": 3226,
"text": "program DataFiles;\ntype\n StudentRecord = Record\n s_name: String;\n s_addr: String;\n s_batchcode: String;\n end;\n\nvar\n Student: StudentRecord;\n f: file of StudentRecord;\n\nbegin\n Assign(f,'students.dat');\n Rewrite(f);\n Student.s_name := 'John Smith';\n Student.s_addr := 'United States of America';\n Student.s_batchcode := 'Computer Science';\n Write(f,Student);\n Close(f);\nend."
},
{
"code": null,
"e": 3825,
"s": 3636,
"text": "When compiled and run, the program would create a file named students.dat into the working directory. You can open the file using a text editor, like notepad, to look at John Smith's data."
},
{
"code": null,
"e": 3969,
"s": 3825,
"text": "We have just created and written into a file named students.dat. Now, let us write a program that would read the student's data from the file −"
},
{
"code": null,
"e": 4434,
"s": 3969,
"text": "program DataFiles;\ntype\n StudentRecord = Record\n s_name: String;\n s_addr: String;\n s_batchcode: String;\n end;\n\nvar\n Student: StudentRecord;\n f: file of StudentRecord;\n\nbegin\n assign(f, 'students.dat');\n reset(f); \n while not eof(f) do\n \n begin\n read(f,Student);\n writeln('Name: ',Student.s_name);\n writeln('Address: ',Student.s_addr);\n writeln('Batch Code: ', Student.s_batchcode);\n end;\n \n close(f);\nend."
},
{
"code": null,
"e": 4515,
"s": 4434,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4596,
"s": 4515,
"text": "Name: John Smith\nAddress: United States of America\nBatch Code: Computer Science\n"
},
{
"code": null,
"e": 4892,
"s": 4596,
"text": "Pascal allows file variables to be used as parameters in standard and user-defined subprograms. The following example illustrates this concept. The program creates a file named rainfall.txt and stores some rainfall data. Next, it opens the file, reads the data and computes the average rainfall."
},
{
"code": null,
"e": 4996,
"s": 4892,
"text": "Please note that, if you use a file parameter with subprograms, it must be declared as a var parameter."
},
{
"code": null,
"e": 5820,
"s": 4996,
"text": "program addFiledata;\nconst\n MAX = 4;\ntype\n raindata = file of real;\n\nvar\n rainfile: raindata;\n filename: string;\nprocedure writedata(var f: raindata);\n\nvar\n data: real;\n i: integer;\n\nbegin\n rewrite(f, sizeof(data));\n for i:=1 to MAX do\n \n begin\n writeln('Enter rainfall data: ');\n readln(data);\n write(f, data);\n end;\n \n close(f);\nend;\n\nprocedure computeAverage(var x: raindata);\nvar\n d, sum: real;\n average: real;\n\nbegin\n reset(x);\n sum:= 0.0;\n while not eof(x) do\n \n begin\n read(x, d);\n sum := sum + d;\n end;\n \n average := sum/MAX;\n close(x);\n writeln('Average Rainfall: ', average:7:2);\nend;\n\nbegin\n writeln('Enter the File Name: ');\n readln(filename);\n assign(rainfile, filename);\n writedata(rainfile);\n computeAverage(rainfile);\nend."
},
{
"code": null,
"e": 5901,
"s": 5820,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6056,
"s": 5901,
"text": "Enter the File Name:\nrainfall.txt\nEnter rainfall data:\n34\nEnter rainfall data:\n45\nEnter rainfall data:\n56\nEnter rainfall data:\n78\nAverage Rainfall: 53.25\n"
},
{
"code": null,
"e": 6213,
"s": 6056,
"text": "A text file, in Pascal, consists of lines of characters where each line is terminated with an end-of-line marker. You can declare and define such files as −"
},
{
"code": null,
"e": 6236,
"s": 6213,
"text": "type\nfile-name = text;"
},
{
"code": null,
"e": 6507,
"s": 6236,
"text": "Difference between a normal file of characters and a text file is that a text file is divided into lines, each terminated by a special end-of-line marker, automatically inserted by the system. The following example creates and writes into a text file named contact.txt −"
},
{
"code": null,
"e": 6913,
"s": 6507,
"text": "program exText;\nvar\n filename, data: string;\n myfile: text;\n\nbegin\n writeln('Enter the file name: ');\n readln(filename);\n \n assign(myfile, filename);\n rewrite(myfile);\n \n writeln(myfile, 'Note to Students: ');\n writeln(myfile, 'For details information on Pascal Programming');\n writeln(myfile, 'Contact: Tutorials Point');\n writeln('Completed writing'); \n \n close(myfile);\nend."
},
{
"code": null,
"e": 6994,
"s": 6913,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7047,
"s": 6994,
"text": "Enter the file name:\ncontact.txt \nCompleted writing\n"
},
{
"code": null,
"e": 7199,
"s": 7047,
"text": "Appending to a file means writing to an existing file that already has some data without overwriting the file. The following program illustrates this −"
},
{
"code": null,
"e": 7629,
"s": 7199,
"text": "program exAppendfile;\nvar\n myfile: text;\n info: string;\n\nbegin\n assign(myfile, 'contact.txt');\n append(myfile);\n \n writeln('Contact Details');\n writeln('[email protected]');\n close(myfile);\n \n (* let us read from this file *)\n assign(myfile, 'contact.txt');\n reset(myfile);\n while not eof(myfile) do\n \n begin\n readln(myfile, info);\n writeln(info);\n end;\n close(myfile);\nend."
},
{
"code": null,
"e": 7710,
"s": 7629,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7845,
"s": 7710,
"text": "Contact Details\[email protected]\nNote to Students:\nFor details information on Pascal Programming\nContact: Tutorials Point\n"
},
{
"code": null,
"e": 7921,
"s": 7845,
"text": "Free Pascal provides the following functions/procedures for file handling −"
},
{
"code": null,
"e": 7952,
"s": 7921,
"text": "procedure Append(var t: Text);"
},
{
"code": null,
"e": 7980,
"s": 7952,
"text": "Opens a file in append mode"
},
{
"code": null,
"e": 8024,
"s": 7980,
"text": "procedure Assign(out f: file; const Name:);"
},
{
"code": null,
"e": 8049,
"s": 8024,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8090,
"s": 8049,
"text": "procedure Assign(out f: file; p: PChar);"
},
{
"code": null,
"e": 8115,
"s": 8090,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8155,
"s": 8115,
"text": "procedure Assign(out f: file; c: Char);"
},
{
"code": null,
"e": 8180,
"s": 8155,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8229,
"s": 8180,
"text": "procedure Assign(out f: TypedFile; const Name:);"
},
{
"code": null,
"e": 8254,
"s": 8229,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8300,
"s": 8254,
"text": "procedure Assign(out f: TypedFile; p: PChar);"
},
{
"code": null,
"e": 8325,
"s": 8300,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8370,
"s": 8325,
"text": "procedure Assign(out f: TypedFile; c: Char);"
},
{
"code": null,
"e": 8395,
"s": 8370,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8436,
"s": 8395,
"text": "procedure Assign(out t: Text; const s:);"
},
{
"code": null,
"e": 8461,
"s": 8436,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8502,
"s": 8461,
"text": "procedure Assign(out t: Text; p: PChar);"
},
{
"code": null,
"e": 8527,
"s": 8502,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8567,
"s": 8527,
"text": "procedure Assign(out t: Text; c: Char);"
},
{
"code": null,
"e": 8592,
"s": 8567,
"text": "Assigns a name to a file"
},
{
"code": null,
"e": 8668,
"s": 8592,
"text": "procedure BlockRead(var f: file; var Buf; count: Int64; var Result: Int64);"
},
{
"code": null,
"e": 8703,
"s": 8668,
"text": "Reads data from a file into memory"
},
{
"code": null,
"e": 8783,
"s": 8703,
"text": "procedure BlockRead(var f: file; var Buf; count: LongInt; var Result: LongInt);"
},
{
"code": null,
"e": 8818,
"s": 8783,
"text": "Reads data from a file into memory"
},
{
"code": null,
"e": 8900,
"s": 8818,
"text": "procedure BlockRead(var f: file; var Buf; count: Cardinal; var Result: Cardinal);"
},
{
"code": null,
"e": 8935,
"s": 8900,
"text": "Reads data from a file into memory"
},
{
"code": null,
"e": 9009,
"s": 8935,
"text": "procedure BlockRead(var f: file; var Buf; count: Word; var Result: Word);"
},
{
"code": null,
"e": 9044,
"s": 9009,
"text": "Reads data from a file into memory"
},
{
"code": null,
"e": 9121,
"s": 9044,
"text": "procedure BlockRead(var f: file; var Buf; count: Word; var Result: Integer);"
},
{
"code": null,
"e": 9156,
"s": 9121,
"text": "Reads data from a file into memory"
},
{
"code": null,
"e": 9213,
"s": 9156,
"text": "procedure BlockRead(var f: file; var Buf; count: Int64);"
},
{
"code": null,
"e": 9248,
"s": 9213,
"text": "Reads data from a file into memory"
},
{
"code": null,
"e": 9327,
"s": 9248,
"text": "procedure BlockWrite(var f: file; const Buf; Count: Int64; var Result: Int64);"
},
{
"code": null,
"e": 9361,
"s": 9327,
"text": "Writes data from memory to a file"
},
{
"code": null,
"e": 9444,
"s": 9361,
"text": "procedure BlockWrite(var f: file; const Buf; Count: LongInt; var Result: LongInt);"
},
{
"code": null,
"e": 9478,
"s": 9444,
"text": "Writes data from memory to a file"
},
{
"code": null,
"e": 9563,
"s": 9478,
"text": "procedure BlockWrite(var f: file; const Buf; Count: Cardinal; var Result: Cardinal);"
},
{
"code": null,
"e": 9597,
"s": 9563,
"text": "Writes data from memory to a file"
},
{
"code": null,
"e": 9674,
"s": 9597,
"text": "procedure BlockWrite(var f: file; const Buf; Count: Word; var Result: Word);"
},
{
"code": null,
"e": 9708,
"s": 9674,
"text": "Writes data from memory to a file"
},
{
"code": null,
"e": 9788,
"s": 9708,
"text": "procedure BlockWrite(var f: file; const Buf; Count: Word; var Result: Integer);"
},
{
"code": null,
"e": 9822,
"s": 9788,
"text": "Writes data from memory to a file"
},
{
"code": null,
"e": 9884,
"s": 9822,
"text": "procedure BlockWrite(var f: file; const Buf; Count: LongInt);"
},
{
"code": null,
"e": 9918,
"s": 9884,
"text": "Writes data from memory to a file"
},
{
"code": null,
"e": 9948,
"s": 9918,
"text": "procedure Close(var f: file);"
},
{
"code": null,
"e": 9962,
"s": 9948,
"text": "Closes a file"
},
{
"code": null,
"e": 9992,
"s": 9962,
"text": "procedure Close(var t: Text);"
},
{
"code": null,
"e": 10006,
"s": 9992,
"text": "Closes a file"
},
{
"code": null,
"e": 10042,
"s": 10006,
"text": "function EOF(var f: file):Boolean; "
},
{
"code": null,
"e": 10065,
"s": 10042,
"text": "Checks for end of file"
},
{
"code": null,
"e": 10100,
"s": 10065,
"text": "function EOF(var t: Text):Boolean;"
},
{
"code": null,
"e": 10123,
"s": 10100,
"text": "Checks for end of file"
},
{
"code": null,
"e": 10146,
"s": 10123,
"text": "function EOF: Boolean;"
},
{
"code": null,
"e": 10169,
"s": 10146,
"text": "Checks for end of file"
},
{
"code": null,
"e": 10206,
"s": 10169,
"text": "function EOLn(var t: Text):Boolean; "
},
{
"code": null,
"e": 10229,
"s": 10206,
"text": "Checks for end of line"
},
{
"code": null,
"e": 10253,
"s": 10229,
"text": "function EOLn: Boolean;"
},
{
"code": null,
"e": 10276,
"s": 10253,
"text": "Checks for end of line"
},
{
"code": null,
"e": 10306,
"s": 10276,
"text": "procedure Erase(var f: file);"
},
{
"code": null,
"e": 10329,
"s": 10306,
"text": "Deletes file from disk"
},
{
"code": null,
"e": 10359,
"s": 10329,
"text": "procedure Erase(var t: Text);"
},
{
"code": null,
"e": 10382,
"s": 10359,
"text": "Deletes file from disk"
},
{
"code": null,
"e": 10421,
"s": 10382,
"text": "function FilePos( var f: file):Int64; "
},
{
"code": null,
"e": 10438,
"s": 10421,
"text": "Position in file"
},
{
"code": null,
"e": 10476,
"s": 10438,
"text": "function FileSize(var f: file):Int64;"
},
{
"code": null,
"e": 10489,
"s": 10476,
"text": "Size of file"
},
{
"code": null,
"e": 10519,
"s": 10489,
"text": "procedure Flush(var t: Text);"
},
{
"code": null,
"e": 10547,
"s": 10519,
"text": "Writes file buffers to disk"
},
{
"code": null,
"e": 10572,
"s": 10547,
"text": "function IOResult: Word;"
},
{
"code": null,
"e": 10613,
"s": 10572,
"text": "Returns result of last file IO operation"
},
{
"code": null,
"e": 10659,
"s": 10613,
"text": "procedure Read(var F: Text; Args: Arguments);"
},
{
"code": null,
"e": 10689,
"s": 10659,
"text": "Reads from file into variable"
},
{
"code": null,
"e": 10722,
"s": 10689,
"text": "procedure Read(Args: Arguments);"
},
{
"code": null,
"e": 10752,
"s": 10722,
"text": "Reads from file into variable"
},
{
"code": null,
"e": 10800,
"s": 10752,
"text": "procedure ReadLn(var F: Text; Args: Arguments);"
},
{
"code": null,
"e": 10849,
"s": 10800,
"text": "Reads from file into variable and goto next line"
},
{
"code": null,
"e": 10884,
"s": 10849,
"text": "procedure ReadLn(Args: Arguments);"
},
{
"code": null,
"e": 10933,
"s": 10884,
"text": "Reads from file into variable and goto next line"
},
{
"code": null,
"e": 10974,
"s": 10933,
"text": "procedure Rename(var f: file; const s:);"
},
{
"code": null,
"e": 10995,
"s": 10974,
"text": "Renames file on disk"
},
{
"code": null,
"e": 11036,
"s": 10995,
"text": "procedure Rename(var f: file; p: PChar);"
},
{
"code": null,
"e": 11057,
"s": 11036,
"text": "Renames file on disk"
},
{
"code": null,
"e": 11097,
"s": 11057,
"text": "procedure Rename(var f: file; c: Char);"
},
{
"code": null,
"e": 11118,
"s": 11097,
"text": "Renames file on disk"
},
{
"code": null,
"e": 11159,
"s": 11118,
"text": "procedure Rename(var t: Text; const s); "
},
{
"code": null,
"e": 11179,
"s": 11159,
"text": "Rename file on disk"
},
{
"code": null,
"e": 11220,
"s": 11179,
"text": "procedure Rename(var t: Text; p: PChar);"
},
{
"code": null,
"e": 11241,
"s": 11220,
"text": "Renames file on disk"
},
{
"code": null,
"e": 11282,
"s": 11241,
"text": "procedure Rename( var t: Text; c: Char);"
},
{
"code": null,
"e": 11303,
"s": 11282,
"text": "Renames file on disk"
},
{
"code": null,
"e": 11345,
"s": 11303,
"text": "procedure Reset(var f: file; l: LongInt);"
},
{
"code": null,
"e": 11368,
"s": 11345,
"text": "Opens file for reading"
},
{
"code": null,
"e": 11398,
"s": 11368,
"text": "procedure Reset(var f: file);"
},
{
"code": null,
"e": 11421,
"s": 11398,
"text": "Opens file for reading"
},
{
"code": null,
"e": 11456,
"s": 11421,
"text": "procedure Reset(var f: TypedFile);"
},
{
"code": null,
"e": 11479,
"s": 11456,
"text": "Opens file for reading"
},
{
"code": null,
"e": 11509,
"s": 11479,
"text": "procedure Reset(var t: Text);"
},
{
"code": null,
"e": 11532,
"s": 11509,
"text": "Opens file for reading"
},
{
"code": null,
"e": 11576,
"s": 11532,
"text": "procedure Rewrite(var f: file; l: LongInt);"
},
{
"code": null,
"e": 11599,
"s": 11576,
"text": "Opens file for writing"
},
{
"code": null,
"e": 11631,
"s": 11599,
"text": "procedure Rewrite(var f: file);"
},
{
"code": null,
"e": 11654,
"s": 11631,
"text": "Opens file for writing"
},
{
"code": null,
"e": 11691,
"s": 11654,
"text": "procedure Rewrite(var f: TypedFile);"
},
{
"code": null,
"e": 11714,
"s": 11691,
"text": "Opens file for writing"
},
{
"code": null,
"e": 11746,
"s": 11714,
"text": "procedure Rewrite(var t: Text);"
},
{
"code": null,
"e": 11769,
"s": 11746,
"text": "Opens file for writing"
},
{
"code": null,
"e": 11810,
"s": 11769,
"text": "procedure Seek(var f: file; Pos: Int64);"
},
{
"code": null,
"e": 11829,
"s": 11810,
"text": "Sets file position"
},
{
"code": null,
"e": 11868,
"s": 11829,
"text": "function SeekEOF(var t: Text):Boolean;"
},
{
"code": null,
"e": 11902,
"s": 11868,
"text": "Sets file position to end of file"
},
{
"code": null,
"e": 11929,
"s": 11902,
"text": "function SeekEOF: Boolean;"
},
{
"code": null,
"e": 11963,
"s": 11929,
"text": "Sets file position to end of file"
},
{
"code": null,
"e": 12003,
"s": 11963,
"text": "function SeekEOLn(var t: Text):Boolean;"
},
{
"code": null,
"e": 12037,
"s": 12003,
"text": "Sets file position to end of line"
},
{
"code": null,
"e": 12065,
"s": 12037,
"text": "function SeekEOLn: Boolean;"
},
{
"code": null,
"e": 12099,
"s": 12065,
"text": "Sets file position to end of line"
},
{
"code": null,
"e": 12143,
"s": 12099,
"text": "procedure SetTextBuf(var f: Text; var Buf);"
},
{
"code": null,
"e": 12168,
"s": 12143,
"text": "Sets size of file buffer"
},
{
"code": null,
"e": 12227,
"s": 12168,
"text": "procedure SetTextBuf(var f: Text; var Buf; Size: SizeInt);"
},
{
"code": null,
"e": 12252,
"s": 12227,
"text": "Sets size of file buffer"
},
{
"code": null,
"e": 12285,
"s": 12252,
"text": "procedure Truncate(var F: file);"
},
{
"code": null,
"e": 12315,
"s": 12285,
"text": "Truncate the file at position"
},
{
"code": null,
"e": 12349,
"s": 12315,
"text": "procedure Write(Args: Arguments);"
},
{
"code": null,
"e": 12373,
"s": 12349,
"text": "Writes variable to file"
},
{
"code": null,
"e": 12420,
"s": 12373,
"text": "procedure Write(var F: Text; Args: Arguments);"
},
{
"code": null,
"e": 12443,
"s": 12420,
"text": "Write variable to file"
},
{
"code": null,
"e": 12479,
"s": 12443,
"text": "procedure Writeln(Args: Arguments);"
},
{
"code": null,
"e": 12522,
"s": 12479,
"text": "Writes variable to file and append newline"
},
{
"code": null,
"e": 12571,
"s": 12522,
"text": "procedure WriteLn(var F: Text; Args: Arguments);"
}
]
|
Self Descriptive Number | 17 Jun, 2022
Given an integer N, the task is to find all the self-descriptive numbers from 1 to N
A self-descriptive number is an integer n in given base b is b digits long in which each digit at position p (the most significant digit being at position 0 and the least significant at position b – 1) counts how many times a digit p is in n.
For example in base 10, 6210001000 is a self descriptive number as there are six 0s, two 1s, one 2 and one 6.Explanation : It is 10 digit number in base 10. It has 6 at the position 0 and there are six 0s in 6210001000. It has 2 at the position 1 and there are two 1s in 6210001000. It has 1 at the position 2 and there is one 2s in 6210001000. It has 0 at the position 3 and there are zero 3s in 6210001000. It has 0 at the position 4 and there are zero 4s in 6210001000. It has 0 at the position 5 and there are zero 5s in 6210001000. It has 1 at the position 6 and there is one 6 in 6210001000. It has 0 at the position 7 and there are zero 7s in 6210001000. It has 0 at the position 8 and there are zero 8s in 6210001000. It has 0 at the position 9 and there are zero 9s in 6210001000.[Source : Wikipedia]
Examples:
Input: N = 10000Output: 1210 2020Explanation: From 1 to N only these two numbers are the self-descriptive numbers
Input: N = 10Output: Explanation: There is no self descriptive number in range [1, 10]
Here is a program to print all self-descriptive numbers below 100000000. In the below program we have just ignored one fact about the self-descriptive number that it should have as many number of digits as much the base is given.
Description of Program : 1 . Firstly all the digits get extracted from the outer loop and are stored in a variable b in each iteration. 2 . Then in the inner loop there is a count on how many times number i (this i is ith index of outer loop) is present in the string. 3 . Finally that count is compared with the digit present at the ith index stored in variable b.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print// all self descriptive// number below 100000000#include <iostream>using namespace std; bool isSelfDescriptiveNumber(int num){ // converting the integer // num to string string s = to_string(num); for (int i = 0; i < s.size(); i++) { // Extracting each digit // one by one from the // string char temp_char = s.at(i); // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' int b = temp_char - '0'; // counting how many // times the particular // digit occur in the // whole number "num" int count = 0; for (int j = 0; j < s.size(); j++) { // converting string // char to integer int temp = s.at(j) - '0'; // checking whether it is // equal to the index 'i' // if it is then increment // the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true;} // Driver Codeint main(){ int N = 1000000; for (int i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) cout << i << endl; return 0;} // This code is contributed by// Manish Shaw(manishshaw1)
// Java program to print all self descriptive// number below 100000000public class SelfDescriptive { public static boolean isSelfDescriptiveNumber(int num) { // converting the integer num to string String s = Integer.toString(num); for (int i = 0; i < s.length(); i++) { // Extracting each digit one by one from the string String temp_char = s.charAt(i) + ""; // converting the string (digit) into integer // b variable stores the digit present at index 'i' int b = Integer.parseInt(temp_char); // counting how many times the particular digit // occur in the whole number "num" int count = 0; for (int j = 0; j < s.length(); j++) { // converting string char to integer int temp = Integer.parseInt(s.charAt(j) + ""); // checking whether it is equal to the index 'i' // if it is then increment the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true; } public static void main(String[] args) { int N = 1000000; for (int i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) System.out.println(i); }}
# Python3 program to print# all self descriptive# number below 100000000def isSelfDescriptiveNumber(num): # Converting the integer # num to string s = str(num) for i in range(len(s)): # Extracting each digit # one by one from the # string temp_char = s[i] # Converting the string # (digit) into integer b # variable stores the digit # present at index 'i' b = ord(temp_char) - ord('0') # Counting how many # times the particular # digit occur in the # whole number "num" count = 0 for j in range(len(s)): # Converting string # char to integer temp = ord(s[j]) - ord('0') # Checking whether it is # equal to the index 'i' # if it is then increment # the count . if (temp == i): count += 1 # If it is not equal # it return false . if (count != b): return False return True # Driver codeif __name__=="__main__": N = 1000000 for i in range(1, N+1): if (isSelfDescriptiveNumber(i)): print(i) # This code is contributed by rutvik_56
// C# program to print// all self descriptive// number below 100000000using System; class GFG { static bool isSelfDescriptiveNumber(int num) { // converting the integer // num to string string s = num.ToString(); for (int i = 0; i < s.Length; i++) { // Extracting each digit // one by one from the // string string temp_char = s[i] + ""; // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' int b = int.Parse(temp_char); // counting how many // times the particular // digit occur in the // whole number "num" int count = 0; for (int j = 0; j < s.Length; j++) { // converting string // char to integer int temp = int.Parse(s[j] + ""); // checking whether it is // equal to the index 'i' // if it is then increment // the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true; } // Driver Code static void Main() { int N = 1000000; for (int i = 0; i < N; i++) if (isSelfDescriptiveNumber(i)) Console.WriteLine(i); }} // This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program to print// all self descriptive// number below 100000000 // Note:// 100000000 is a huge no so// it give sometime TLE error// because its takes compile// time above 5 secfunction isSelfDescriptiveNumber($num){ // converting the integer // num to string $s = strval($num); for ($i = 0; $i < strlen($s); $i++) { // Extracting each digit // one by one from the // string $temp_char = $s[$i]; // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' $b = $temp_char - '0'; // counting how many // times the particular // digit occur in the // whole number "num" $count = 0; for ($j = 0; $j < strlen($s); $j++) { // converting string // char to integer $temp = $s[$j] - '0'; // checking whether it is // equal to the index 'i' // if it is then increment // the count . if ($temp == $i) { $count++; } } // If it is not equal // it return false . if ($count != $b) return false; } return true;} // Driver Code$N = 1000000;for ($i = 0; $i <= $N; $i++) if (isSelfDescriptiveNumber($i)) echo $i."\n"; // This code is contributed// by mits?>
// JavaScript program to print// all self descriptive// number below 100000000 function isSelfDescriptiveNumber(num){ // converting the integer // num to string let s = num.toString(); for (let i = 0; i < s.length; i++) { // Extracting each digit // one by one from the // string let temp_char = s[i]; // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' let b = temp_char - '0'; // counting how many // times the particular // digit occur in the // whole number "num" let count = 0; for (let j = 0; j < s.length; j++) { // converting string // char to integer let temp = s[j] - '0'; // checking whether it is // equal to the index 'i' // if it is then increment // the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true;} // Driver Codelet N = 1000000;for (let i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) console.log(i); // This code is contributed by Nidhi goel
1210
2020
21200
Time Complexity: O( N*len(N)*len(N) )Auxiliary Space: O(1)
Efficient Approach: The time in above approach can be reduced by storing frequency of each digit in a 10 length array and then checking it consecutively with the corresponding digit.
C++14
#include <bits/stdc++.h>using namespace std; bool isSelfDescriptiveNumber(int num){ string str=to_string(num); int i; int freq[10]={0}; while(num>0) { freq[num%10]++; num/=10; } for(i=0;i<str.length();i++) if(freq[i]!=str[i]-'0') return 0; return 1;} int main(){ int N = 1000000; for (int i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) cout << i << endl; return 0;}
1210
2020
21200
Time Complexity: O( N*len(N) )Auxiliary Space: O(1)
manishshaw1
Mithun Kumar
sanskar27jain
rutvik_56
prophet1999
animeshdey
classroompxico
number-digits
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 137,
"s": 52,
"text": "Given an integer N, the task is to find all the self-descriptive numbers from 1 to N"
},
{
"code": null,
"e": 381,
"s": 137,
"text": "A self-descriptive number is an integer n in given base b is b digits long in which each digit at position p (the most significant digit being at position 0 and the least significant at position b – 1) counts how many times a digit p is in n. "
},
{
"code": null,
"e": 1191,
"s": 381,
"text": "For example in base 10, 6210001000 is a self descriptive number as there are six 0s, two 1s, one 2 and one 6.Explanation : It is 10 digit number in base 10. It has 6 at the position 0 and there are six 0s in 6210001000. It has 2 at the position 1 and there are two 1s in 6210001000. It has 1 at the position 2 and there is one 2s in 6210001000. It has 0 at the position 3 and there are zero 3s in 6210001000. It has 0 at the position 4 and there are zero 4s in 6210001000. It has 0 at the position 5 and there are zero 5s in 6210001000. It has 1 at the position 6 and there is one 6 in 6210001000. It has 0 at the position 7 and there are zero 7s in 6210001000. It has 0 at the position 8 and there are zero 8s in 6210001000. It has 0 at the position 9 and there are zero 9s in 6210001000.[Source : Wikipedia]"
},
{
"code": null,
"e": 1201,
"s": 1191,
"text": "Examples:"
},
{
"code": null,
"e": 1315,
"s": 1201,
"text": "Input: N = 10000Output: 1210 2020Explanation: From 1 to N only these two numbers are the self-descriptive numbers"
},
{
"code": null,
"e": 1402,
"s": 1315,
"text": "Input: N = 10Output: Explanation: There is no self descriptive number in range [1, 10]"
},
{
"code": null,
"e": 1632,
"s": 1402,
"text": "Here is a program to print all self-descriptive numbers below 100000000. In the below program we have just ignored one fact about the self-descriptive number that it should have as many number of digits as much the base is given."
},
{
"code": null,
"e": 1999,
"s": 1632,
"text": "Description of Program : 1 . Firstly all the digits get extracted from the outer loop and are stored in a variable b in each iteration. 2 . Then in the inner loop there is a count on how many times number i (this i is ith index of outer loop) is present in the string. 3 . Finally that count is compared with the digit present at the ith index stored in variable b. "
},
{
"code": null,
"e": 2003,
"s": 1999,
"text": "C++"
},
{
"code": null,
"e": 2008,
"s": 2003,
"text": "Java"
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Python3"
},
{
"code": null,
"e": 2019,
"s": 2016,
"text": "C#"
},
{
"code": null,
"e": 2023,
"s": 2019,
"text": "PHP"
},
{
"code": null,
"e": 2034,
"s": 2023,
"text": "Javascript"
},
{
"code": "// C++ program to print// all self descriptive// number below 100000000#include <iostream>using namespace std; bool isSelfDescriptiveNumber(int num){ // converting the integer // num to string string s = to_string(num); for (int i = 0; i < s.size(); i++) { // Extracting each digit // one by one from the // string char temp_char = s.at(i); // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' int b = temp_char - '0'; // counting how many // times the particular // digit occur in the // whole number \"num\" int count = 0; for (int j = 0; j < s.size(); j++) { // converting string // char to integer int temp = s.at(j) - '0'; // checking whether it is // equal to the index 'i' // if it is then increment // the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true;} // Driver Codeint main(){ int N = 1000000; for (int i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) cout << i << endl; return 0;} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 3481,
"s": 2034,
"text": null
},
{
"code": "// Java program to print all self descriptive// number below 100000000public class SelfDescriptive { public static boolean isSelfDescriptiveNumber(int num) { // converting the integer num to string String s = Integer.toString(num); for (int i = 0; i < s.length(); i++) { // Extracting each digit one by one from the string String temp_char = s.charAt(i) + \"\"; // converting the string (digit) into integer // b variable stores the digit present at index 'i' int b = Integer.parseInt(temp_char); // counting how many times the particular digit // occur in the whole number \"num\" int count = 0; for (int j = 0; j < s.length(); j++) { // converting string char to integer int temp = Integer.parseInt(s.charAt(j) + \"\"); // checking whether it is equal to the index 'i' // if it is then increment the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true; } public static void main(String[] args) { int N = 1000000; for (int i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) System.out.println(i); }}",
"e": 4924,
"s": 3481,
"text": null
},
{
"code": "# Python3 program to print# all self descriptive# number below 100000000def isSelfDescriptiveNumber(num): # Converting the integer # num to string s = str(num) for i in range(len(s)): # Extracting each digit # one by one from the # string temp_char = s[i] # Converting the string # (digit) into integer b # variable stores the digit # present at index 'i' b = ord(temp_char) - ord('0') # Counting how many # times the particular # digit occur in the # whole number \"num\" count = 0 for j in range(len(s)): # Converting string # char to integer temp = ord(s[j]) - ord('0') # Checking whether it is # equal to the index 'i' # if it is then increment # the count . if (temp == i): count += 1 # If it is not equal # it return false . if (count != b): return False return True # Driver codeif __name__==\"__main__\": N = 1000000 for i in range(1, N+1): if (isSelfDescriptiveNumber(i)): print(i) # This code is contributed by rutvik_56",
"e": 6188,
"s": 4924,
"text": null
},
{
"code": "// C# program to print// all self descriptive// number below 100000000using System; class GFG { static bool isSelfDescriptiveNumber(int num) { // converting the integer // num to string string s = num.ToString(); for (int i = 0; i < s.Length; i++) { // Extracting each digit // one by one from the // string string temp_char = s[i] + \"\"; // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' int b = int.Parse(temp_char); // counting how many // times the particular // digit occur in the // whole number \"num\" int count = 0; for (int j = 0; j < s.Length; j++) { // converting string // char to integer int temp = int.Parse(s[j] + \"\"); // checking whether it is // equal to the index 'i' // if it is then increment // the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true; } // Driver Code static void Main() { int N = 1000000; for (int i = 0; i < N; i++) if (isSelfDescriptiveNumber(i)) Console.WriteLine(i); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 7771,
"s": 6188,
"text": null
},
{
"code": "<?php// PHP program to print// all self descriptive// number below 100000000 // Note:// 100000000 is a huge no so// it give sometime TLE error// because its takes compile// time above 5 secfunction isSelfDescriptiveNumber($num){ // converting the integer // num to string $s = strval($num); for ($i = 0; $i < strlen($s); $i++) { // Extracting each digit // one by one from the // string $temp_char = $s[$i]; // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' $b = $temp_char - '0'; // counting how many // times the particular // digit occur in the // whole number \"num\" $count = 0; for ($j = 0; $j < strlen($s); $j++) { // converting string // char to integer $temp = $s[$j] - '0'; // checking whether it is // equal to the index 'i' // if it is then increment // the count . if ($temp == $i) { $count++; } } // If it is not equal // it return false . if ($count != $b) return false; } return true;} // Driver Code$N = 1000000;for ($i = 0; $i <= $N; $i++) if (isSelfDescriptiveNumber($i)) echo $i.\"\\n\"; // This code is contributed// by mits?>",
"e": 9196,
"s": 7771,
"text": null
},
{
"code": "// JavaScript program to print// all self descriptive// number below 100000000 function isSelfDescriptiveNumber(num){ // converting the integer // num to string let s = num.toString(); for (let i = 0; i < s.length; i++) { // Extracting each digit // one by one from the // string let temp_char = s[i]; // converting the string // (digit) into integer b // variable stores the digit // present at index 'i' let b = temp_char - '0'; // counting how many // times the particular // digit occur in the // whole number \"num\" let count = 0; for (let j = 0; j < s.length; j++) { // converting string // char to integer let temp = s[j] - '0'; // checking whether it is // equal to the index 'i' // if it is then increment // the count . if (temp == i) { count++; } } // If it is not equal // it return false . if (count != b) return false; } return true;} // Driver Codelet N = 1000000;for (let i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) console.log(i); // This code is contributed by Nidhi goel",
"e": 10525,
"s": 9196,
"text": null
},
{
"code": null,
"e": 10541,
"s": 10525,
"text": "1210\n2020\n21200"
},
{
"code": null,
"e": 10600,
"s": 10541,
"text": "Time Complexity: O( N*len(N)*len(N) )Auxiliary Space: O(1)"
},
{
"code": null,
"e": 10783,
"s": 10600,
"text": "Efficient Approach: The time in above approach can be reduced by storing frequency of each digit in a 10 length array and then checking it consecutively with the corresponding digit."
},
{
"code": null,
"e": 10789,
"s": 10783,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h>using namespace std; bool isSelfDescriptiveNumber(int num){ string str=to_string(num); int i; int freq[10]={0}; while(num>0) { freq[num%10]++; num/=10; } for(i=0;i<str.length();i++) if(freq[i]!=str[i]-'0') return 0; return 1;} int main(){ int N = 1000000; for (int i = 1; i <= N; i++) if (isSelfDescriptiveNumber(i)) cout << i << endl; return 0;}",
"e": 11268,
"s": 10789,
"text": null
},
{
"code": null,
"e": 11284,
"s": 11268,
"text": "1210\n2020\n21200"
},
{
"code": null,
"e": 11337,
"s": 11284,
"text": "Time Complexity: O( N*len(N) )Auxiliary Space: O(1) "
},
{
"code": null,
"e": 11349,
"s": 11337,
"text": "manishshaw1"
},
{
"code": null,
"e": 11362,
"s": 11349,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 11376,
"s": 11362,
"text": "sanskar27jain"
},
{
"code": null,
"e": 11386,
"s": 11376,
"text": "rutvik_56"
},
{
"code": null,
"e": 11398,
"s": 11386,
"text": "prophet1999"
},
{
"code": null,
"e": 11409,
"s": 11398,
"text": "animeshdey"
},
{
"code": null,
"e": 11424,
"s": 11409,
"text": "classroompxico"
},
{
"code": null,
"e": 11438,
"s": 11424,
"text": "number-digits"
},
{
"code": null,
"e": 11445,
"s": 11438,
"text": "series"
},
{
"code": null,
"e": 11458,
"s": 11445,
"text": "Mathematical"
},
{
"code": null,
"e": 11471,
"s": 11458,
"text": "Mathematical"
},
{
"code": null,
"e": 11478,
"s": 11471,
"text": "series"
}
]
|
Perfect Cube factors of a Number | 05 Apr, 2021
Given an integer N, the task is to find the number of factors of N that are a perfect cube.
Examples:
Input: N = 27Output: 2Explanation : There are 2 factors of 27 (1, 27) that are perfect cube
Input: N = 216Output: 4 Explanation: There are 4 factors of 216 (1, 8, 27, 216) that are perfect cube
Naive Approach: The naive idea is to find all possible factors of the given number N and count if each factor is a perfect cube or not. If yes then count this factor and check for the next factor.
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: The idea is to use mathematical observation to find a formula to calculate the number of factors that are a perfect cube. The number of factors for a number is given by:
Factors of N = (1 + a1)*(1 + a2)*(1 + a3)*..*(1 + an)where a1, a2, a3, .., an are the count of distinct prime factors of N.
In a perfect cube, the count of distinct prime factors must be divisible by 3. Therefore, the count of factors that are a perfect cube is given by:
Factors of N that are perfect cube = (1 + a1/3)*(1 + a2/3)*...*(1 + an/3)where a1, a2, a3, .., an are the count of distinct prime factors of N.
Illustration:
The factors of N = 216 are 2, 2, 2, 3, 3, 3.Therefore, number of factors that are perfect cube are (1 + 3/3) * (1 + 3/3) = 4. The factors are 1, 8, 27, and 216.
Therefore, find the count of prime factors and apply the above formula to find the count of factors that are a perfect cube.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the count// of factors that are perfect cubeint noOfFactors(int N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. int count = 0; // To store the number of factors // that are perfect cube int ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 3 + 1); // Check for all the possible // numbers that can divide it for (int i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 3 + 1); } // Return final count return ans;} // Driver Codeint main(){ // Given number int N = 216; // Function Call cout << noOfFactors(N); return 0;}
// Java program for the above approachclass GFG{ // Function that returns the count// of factors that are perfect cubestatic int noOfFactors(int N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. int count = 0; // To store the number of factors // that are perfect cube int ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 3 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 3 + 1); } // Return final count return ans;} // Driver Codepublic static void main(String[] args){ // Given number int N = 216; // Function call System.out.print(noOfFactors(N));}} // This code is contributed by Rajput-Ji
# Python3 program for the above approach # Function that returns the count# of factors that are perfect cubedef noofFactors(N): if N == 1: return 1 # To store the count of number # of times a prime number # divides N count = 0 # To store the count of factors that # are perfect cube ans = 1 # Count number of 2's that divides N while(N % 2 == 0): count += 1 N //= 2 # Calculate ans according # to above formula ans *= ((count // 3) + 1) # Check for all possible # numbers that can divide it i = 3 while((i * i) <= N): count = 0 # Loop to check the number # of times prime number # i divides it while(N % i == 0): count += 1 N //= i # Calculate ans according # to above formula ans *= ((count // 3) + 1) i += 2 return ans # Driver Code # Given numberN = 216 # Function callprint(noofFactors(N)) # This code is contributed by VirusBuddah_
// C# program for the above approachusing System; class GFG{ // Function that returns the count// of factors that are perfect cubestatic int noOfFactors(int N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. int count = 0; // To store the number of factors // that are perfect cube int ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 3 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 3 + 1); } // Return final count return ans;} // Driver Codepublic static void Main(String[] args){ // Given number int N = 216; // Function call Console.Write(noOfFactors(N));}} // This code is contributed by Rajput-Ji
<script> // Javascript program for the above approach // Function that returns the count// of factors that are perfect cubefunction noOfFactors(N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. let count = 0; // To store the number of factors // that are perfect cube let ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = parseInt(N / 2); } // Calculate ans according // to above formula ans *= (parseInt(count / 3) + 1); // Check for all the possible // numbers that can divide it for (let i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = parseInt(N / i); } // Calculate ans according // to above formula ans *= (parseInt(count / 3) + 1); } // Return final count return ans;} // Driver Code// Given numberlet N = 216; // Function Calldocument.write(noOfFactors(N)); </script>
4
Time Complexity: O(log(N))Auxiliary Space: O(1)
Rajput-Ji
virusbuddha
subhammahato348
factor
maths-perfect-cube
Numbers
prime-factor
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "Given an integer N, the task is to find the number of factors of N that are a perfect cube."
},
{
"code": null,
"e": 130,
"s": 120,
"text": "Examples:"
},
{
"code": null,
"e": 222,
"s": 130,
"text": "Input: N = 27Output: 2Explanation : There are 2 factors of 27 (1, 27) that are perfect cube"
},
{
"code": null,
"e": 324,
"s": 222,
"text": "Input: N = 216Output: 4 Explanation: There are 4 factors of 216 (1, 8, 27, 216) that are perfect cube"
},
{
"code": null,
"e": 521,
"s": 324,
"text": "Naive Approach: The naive idea is to find all possible factors of the given number N and count if each factor is a perfect cube or not. If yes then count this factor and check for the next factor."
},
{
"code": null,
"e": 564,
"s": 521,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 754,
"s": 564,
"text": "Efficient Approach: The idea is to use mathematical observation to find a formula to calculate the number of factors that are a perfect cube. The number of factors for a number is given by:"
},
{
"code": null,
"e": 880,
"s": 754,
"text": "Factors of N = (1 + a1)*(1 + a2)*(1 + a3)*..*(1 + an)where a1, a2, a3, .., an are the count of distinct prime factors of N. "
},
{
"code": null,
"e": 1028,
"s": 880,
"text": "In a perfect cube, the count of distinct prime factors must be divisible by 3. Therefore, the count of factors that are a perfect cube is given by:"
},
{
"code": null,
"e": 1174,
"s": 1028,
"text": "Factors of N that are perfect cube = (1 + a1/3)*(1 + a2/3)*...*(1 + an/3)where a1, a2, a3, .., an are the count of distinct prime factors of N. "
},
{
"code": null,
"e": 1188,
"s": 1174,
"text": "Illustration:"
},
{
"code": null,
"e": 1349,
"s": 1188,
"text": "The factors of N = 216 are 2, 2, 2, 3, 3, 3.Therefore, number of factors that are perfect cube are (1 + 3/3) * (1 + 3/3) = 4. The factors are 1, 8, 27, and 216."
},
{
"code": null,
"e": 1474,
"s": 1349,
"text": "Therefore, find the count of prime factors and apply the above formula to find the count of factors that are a perfect cube."
},
{
"code": null,
"e": 1525,
"s": 1474,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1529,
"s": 1525,
"text": "C++"
},
{
"code": null,
"e": 1534,
"s": 1529,
"text": "Java"
},
{
"code": null,
"e": 1542,
"s": 1534,
"text": "Python3"
},
{
"code": null,
"e": 1545,
"s": 1542,
"text": "C#"
},
{
"code": null,
"e": 1556,
"s": 1545,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the count// of factors that are perfect cubeint noOfFactors(int N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. int count = 0; // To store the number of factors // that are perfect cube int ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 3 + 1); // Check for all the possible // numbers that can divide it for (int i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 3 + 1); } // Return final count return ans;} // Driver Codeint main(){ // Given number int N = 216; // Function Call cout << noOfFactors(N); return 0;}",
"e": 2694,
"s": 1556,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function that returns the count// of factors that are perfect cubestatic int noOfFactors(int N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. int count = 0; // To store the number of factors // that are perfect cube int ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 3 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 3 + 1); } // Return final count return ans;} // Driver Codepublic static void main(String[] args){ // Given number int N = 216; // Function call System.out.print(noOfFactors(N));}} // This code is contributed by Rajput-Ji",
"e": 3890,
"s": 2694,
"text": null
},
{
"code": "# Python3 program for the above approach # Function that returns the count# of factors that are perfect cubedef noofFactors(N): if N == 1: return 1 # To store the count of number # of times a prime number # divides N count = 0 # To store the count of factors that # are perfect cube ans = 1 # Count number of 2's that divides N while(N % 2 == 0): count += 1 N //= 2 # Calculate ans according # to above formula ans *= ((count // 3) + 1) # Check for all possible # numbers that can divide it i = 3 while((i * i) <= N): count = 0 # Loop to check the number # of times prime number # i divides it while(N % i == 0): count += 1 N //= i # Calculate ans according # to above formula ans *= ((count // 3) + 1) i += 2 return ans # Driver Code # Given numberN = 216 # Function callprint(noofFactors(N)) # This code is contributed by VirusBuddah_",
"e": 4928,
"s": 3890,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function that returns the count// of factors that are perfect cubestatic int noOfFactors(int N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. int count = 0; // To store the number of factors // that are perfect cube int ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = N / 2; } // Calculate ans according // to above formula ans *= (count / 3 + 1); // Check for all the possible // numbers that can divide it for(int i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = N / i; } // Calculate ans according // to above formula ans *= (count / 3 + 1); } // Return final count return ans;} // Driver Codepublic static void Main(String[] args){ // Given number int N = 216; // Function call Console.Write(noOfFactors(N));}} // This code is contributed by Rajput-Ji",
"e": 6133,
"s": 4928,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function that returns the count// of factors that are perfect cubefunction noOfFactors(N){ if (N == 1) return 1; // To store the count of number // of times a prime number // divides N. let count = 0; // To store the number of factors // that are perfect cube let ans = 1; // Count number of 2's that divides N while (N % 2 == 0) { count++; N = parseInt(N / 2); } // Calculate ans according // to above formula ans *= (parseInt(count / 3) + 1); // Check for all the possible // numbers that can divide it for (let i = 3; i * i <= N; i = i + 2) { count = 0; // Loop to check the number // of times prime number // i divides it while (N % i == 0) { count++; N = parseInt(N / i); } // Calculate ans according // to above formula ans *= (parseInt(count / 3) + 1); } // Return final count return ans;} // Driver Code// Given numberlet N = 216; // Function Calldocument.write(noOfFactors(N)); </script>",
"e": 7265,
"s": 6133,
"text": null
},
{
"code": null,
"e": 7267,
"s": 7265,
"text": "4"
},
{
"code": null,
"e": 7317,
"s": 7269,
"text": "Time Complexity: O(log(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7327,
"s": 7317,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7339,
"s": 7327,
"text": "virusbuddha"
},
{
"code": null,
"e": 7355,
"s": 7339,
"text": "subhammahato348"
},
{
"code": null,
"e": 7362,
"s": 7355,
"text": "factor"
},
{
"code": null,
"e": 7381,
"s": 7362,
"text": "maths-perfect-cube"
},
{
"code": null,
"e": 7389,
"s": 7381,
"text": "Numbers"
},
{
"code": null,
"e": 7402,
"s": 7389,
"text": "prime-factor"
},
{
"code": null,
"e": 7415,
"s": 7402,
"text": "Mathematical"
},
{
"code": null,
"e": 7428,
"s": 7415,
"text": "Mathematical"
},
{
"code": null,
"e": 7436,
"s": 7428,
"text": "Numbers"
}
]
|
Java Program for Search an element in a sorted and rotated array | 06 Apr, 2022
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.
Example:
Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
key = 3
Output : Found at index 8
Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
key = 30
Output : Not found
Input : arr[] = {30, 40, 50, 10, 20}
key = 10
Output : Found at index 3
All solutions provided here assume that all elements in the array are distinct.Basic Solution: Approach:
The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.Using the above statement and binary search pivot can be found.After the pivot is found out divide the array in two sub-arrays.Now the individual sub – arrays are sorted so the element can be searched using Binary Search.
The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.
The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.
Using the above statement and binary search pivot can be found.
After the pivot is found out divide the array in two sub-arrays.
Now the individual sub – arrays are sorted so the element can be searched using Binary Search.
Implementation:
Input arr[] = {3, 4, 5, 1, 2}
Element to Search = 1
1) Find out pivot point and divide the array in two
sub-arrays. (pivot = 2) /*Index of 5*/
2) Now call binary search for one of the two sub-arrays.
(a) If element is greater than 0th element then
search in left array
(b) Else Search in right array
(1 will go in else as 1 < 0th element(3))
3) If element is found in selected sub-array then return index
Else return -1.
Below is the implementation of the above approach:
Java
/* Java program to search an element in a sorted and pivoted array*/ class Main { /* Searches an element key in a pivoted sorted array arrp[] of size n */ static int pivotedBinarySearch(int arr[], int n, int key) { int pivot = findPivot(arr, 0, n - 1); // If we didn't find a pivot, then // array is not rotated at all if (pivot == -1) return binarySearch(arr, 0, n - 1, key); // If we found a pivot, then first // compare with pivot and then // search in two subarrays around pivot if (arr[pivot] == key) return pivot; if (arr[0] <= key) return binarySearch(arr, 0, pivot - 1, key); return binarySearch(arr, pivot + 1, n - 1, key); } /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */ static int findPivot(int arr[], int low, int high) { // base cases if (high < low) return -1; if (high == low) return low; /* low + (high - low)/2; */ int mid = (low + high) / 2; if (mid < high && arr[mid] > arr[mid + 1]) return mid; if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); if (arr[low] >= arr[mid]) return findPivot(arr, low, mid - 1); return findPivot(arr, mid + 1, high); } /* Standard Binary Search function */ static int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; /* low + (high - low)/2; */ int mid = (low + high) / 2; if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } // main function public static void main(String args[]) { // Let us search 3 in below array int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; int n = arr1.length; int key = 3; System.out.println("Index of the element is : " + pivotedBinarySearch(arr1, n, key)); }}
Output:
Index of the element is : 8
Complexity Analysis:
Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n).
Space Complexity:O(1), No extra space is required.
Thanks to Ajay Mishra for initial solution.Improved Solution: Approach: Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key.
1) Find middle point mid = (l + h)/2
2) If key is present at middle point, return mid.
3) Else If arr[l..mid] is sorted
a) If key to be searched lies in range from arr[l]
to arr[mid], recur for arr[l..mid].
b) Else recur for arr[mid+1..h]
4) Else (arr[mid+1..h] must be sorted)
a) If key to be searched lies in range from arr[mid+1]
to arr[h], recur for arr[mid+1..h].
b) Else recur for arr[l..mid]
Below is the implementation of above idea:
Java
/* Java program to search an element in sorted and rotated array using single pass of Binary Search*/ class Main { // Returns index of key in arr[l..h] // if key is present, otherwise returns -1 static int search(int arr[], int l, int h, int key) { if (l > h) return -1; int mid = (l + h) / 2; if (arr[mid] == key) return mid; /* If arr[l...mid] first subarray is sorted */ if (arr[l] <= arr[mid]) { /* As this subarray is sorted, we can quickly check if key lies in half or other half */ if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); /*If key not lies in first half subarray, Divide other half into two subarrays, such that we can quickly check if key lies in other half */ return search(arr, mid + 1, h, key); } /* If arr[l..mid] first subarray is not sorted, then arr[mid... h] must be sorted subarray*/ if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // main function public static void main(String args[]) { int arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 }; int n = arr.length; int key = 6; int i = search(arr, 0, n - 1, key); if (i != -1) System.out.println("Index: " + i); else System.out.println("Key not found"); }}
Output:
Index: 2
Complexity Analysis:
Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n).
Space Complexity: O(1). As no extra space is required.
Thanks to Gaurav Ahirwar for suggesting above solution. How to handle duplicates? It doesn’t look possible to search in O(Logn) time in all cases when duplicates are allowed. For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}. It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle.
Search an element in a sorted and rotated array | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSearch an element in a sorted and rotated array | 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 / 15:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uN5QUBHUQaM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Similar Articles:
Find the minimum element in a sorted and rotated array
Given a sorted and rotated array, find if there is a pair with a given sum.
Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem.
Please refer complete article on Search an element in a sorted and rotated array for more details!
simmytarika5
Adobe
Amazon
BankBazaar
Binary Search
D-E-Shaw
FactSet
Flipkart
Hike
MakeMyTrip
Microsoft
Paytm
rotation
Samsung
SAP Labs
Snapdeal
Times Internet
Arrays
Java
Java Programs
Searching
Paytm
Flipkart
Amazon
Microsoft
Samsung
Snapdeal
D-E-Shaw
FactSet
Hike
MakeMyTrip
Adobe
BankBazaar
Times Internet
SAP Labs
Arrays
Searching
Java
Binary Search
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
Chocolate Distribution Problem
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 324,
"s": 28,
"text": "An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. "
},
{
"code": null,
"e": 335,
"s": 324,
"text": "Example: "
},
{
"code": null,
"e": 594,
"s": 335,
"text": "Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};\n key = 3\nOutput : Found at index 8\n\nInput : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};\n key = 30\nOutput : Not found\n\nInput : arr[] = {30, 40, 50, 10, 20}\n key = 10 \nOutput : Found at index 3"
},
{
"code": null,
"e": 705,
"s": 598,
"text": "All solutions provided here assume that all elements in the array are distinct.Basic Solution: Approach: "
},
{
"code": null,
"e": 1198,
"s": 705,
"text": "The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.Using the above statement and binary search pivot can be found.After the pivot is found out divide the array in two sub-arrays.Now the individual sub – arrays are sorted so the element can be searched using Binary Search."
},
{
"code": null,
"e": 1297,
"s": 1198,
"text": "The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search."
},
{
"code": null,
"e": 1471,
"s": 1297,
"text": "The main idea for finding pivot is – for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it."
},
{
"code": null,
"e": 1535,
"s": 1471,
"text": "Using the above statement and binary search pivot can be found."
},
{
"code": null,
"e": 1600,
"s": 1535,
"text": "After the pivot is found out divide the array in two sub-arrays."
},
{
"code": null,
"e": 1695,
"s": 1600,
"text": "Now the individual sub – arrays are sorted so the element can be searched using Binary Search."
},
{
"code": null,
"e": 1713,
"s": 1695,
"text": "Implementation: "
},
{
"code": null,
"e": 2186,
"s": 1713,
"text": "Input arr[] = {3, 4, 5, 1, 2}\nElement to Search = 1\n 1) Find out pivot point and divide the array in two\n sub-arrays. (pivot = 2) /*Index of 5*/\n 2) Now call binary search for one of the two sub-arrays.\n (a) If element is greater than 0th element then\n search in left array\n (b) Else Search in right array\n (1 will go in else as 1 < 0th element(3))\n 3) If element is found in selected sub-array then return index\n Else return -1."
},
{
"code": null,
"e": 2239,
"s": 2186,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2244,
"s": 2239,
"text": "Java"
},
{
"code": "/* Java program to search an element in a sorted and pivoted array*/ class Main { /* Searches an element key in a pivoted sorted array arrp[] of size n */ static int pivotedBinarySearch(int arr[], int n, int key) { int pivot = findPivot(arr, 0, n - 1); // If we didn't find a pivot, then // array is not rotated at all if (pivot == -1) return binarySearch(arr, 0, n - 1, key); // If we found a pivot, then first // compare with pivot and then // search in two subarrays around pivot if (arr[pivot] == key) return pivot; if (arr[0] <= key) return binarySearch(arr, 0, pivot - 1, key); return binarySearch(arr, pivot + 1, n - 1, key); } /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */ static int findPivot(int arr[], int low, int high) { // base cases if (high < low) return -1; if (high == low) return low; /* low + (high - low)/2; */ int mid = (low + high) / 2; if (mid < high && arr[mid] > arr[mid + 1]) return mid; if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); if (arr[low] >= arr[mid]) return findPivot(arr, low, mid - 1); return findPivot(arr, mid + 1, high); } /* Standard Binary Search function */ static int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; /* low + (high - low)/2; */ int mid = (low + high) / 2; if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } // main function public static void main(String args[]) { // Let us search 3 in below array int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; int n = arr1.length; int key = 3; System.out.println(\"Index of the element is : \" + pivotedBinarySearch(arr1, n, key)); }}",
"e": 4393,
"s": 2244,
"text": null
},
{
"code": null,
"e": 4403,
"s": 4393,
"text": "Output: "
},
{
"code": null,
"e": 4431,
"s": 4403,
"text": "Index of the element is : 8"
},
{
"code": null,
"e": 4454,
"s": 4431,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 4575,
"s": 4454,
"text": "Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n)."
},
{
"code": null,
"e": 4626,
"s": 4575,
"text": "Space Complexity:O(1), No extra space is required."
},
{
"code": null,
"e": 4953,
"s": 4626,
"text": "Thanks to Ajay Mishra for initial solution.Improved Solution: Approach: Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key. "
},
{
"code": null,
"e": 5383,
"s": 4953,
"text": "1) Find middle point mid = (l + h)/2\n2) If key is present at middle point, return mid.\n3) Else If arr[l..mid] is sorted\n a) If key to be searched lies in range from arr[l]\n to arr[mid], recur for arr[l..mid].\n b) Else recur for arr[mid+1..h]\n4) Else (arr[mid+1..h] must be sorted)\n a) If key to be searched lies in range from arr[mid+1]\n to arr[h], recur for arr[mid+1..h].\n b) Else recur for arr[l..mid] "
},
{
"code": null,
"e": 5428,
"s": 5383,
"text": "Below is the implementation of above idea: "
},
{
"code": null,
"e": 5433,
"s": 5428,
"text": "Java"
},
{
"code": "/* Java program to search an element in sorted and rotated array using single pass of Binary Search*/ class Main { // Returns index of key in arr[l..h] // if key is present, otherwise returns -1 static int search(int arr[], int l, int h, int key) { if (l > h) return -1; int mid = (l + h) / 2; if (arr[mid] == key) return mid; /* If arr[l...mid] first subarray is sorted */ if (arr[l] <= arr[mid]) { /* As this subarray is sorted, we can quickly check if key lies in half or other half */ if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); /*If key not lies in first half subarray, Divide other half into two subarrays, such that we can quickly check if key lies in other half */ return search(arr, mid + 1, h, key); } /* If arr[l..mid] first subarray is not sorted, then arr[mid... h] must be sorted subarray*/ if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // main function public static void main(String args[]) { int arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 }; int n = arr.length; int key = 6; int i = search(arr, 0, n - 1, key); if (i != -1) System.out.println(\"Index: \" + i); else System.out.println(\"Key not found\"); }}",
"e": 6970,
"s": 5433,
"text": null
},
{
"code": null,
"e": 6979,
"s": 6970,
"text": "Output: "
},
{
"code": null,
"e": 6988,
"s": 6979,
"text": "Index: 2"
},
{
"code": null,
"e": 7011,
"s": 6988,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 7132,
"s": 7011,
"text": "Time Complexity: O(log n). Binary Search requires log n comparisons to find the element. So time complexity is O(log n)."
},
{
"code": null,
"e": 7187,
"s": 7132,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 7613,
"s": 7187,
"text": "Thanks to Gaurav Ahirwar for suggesting above solution. How to handle duplicates? It doesn’t look possible to search in O(Logn) time in all cases when duplicates are allowed. For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}. It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle. "
},
{
"code": null,
"e": 8526,
"s": 7613,
"text": "Search an element in a sorted and rotated array | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSearch an element in a sorted and rotated array | 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 / 15:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uN5QUBHUQaM\" 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": 8546,
"s": 8526,
"text": "Similar Articles: "
},
{
"code": null,
"e": 8601,
"s": 8546,
"text": "Find the minimum element in a sorted and rotated array"
},
{
"code": null,
"e": 8677,
"s": 8601,
"text": "Given a sorted and rotated array, find if there is a pair with a given sum."
},
{
"code": null,
"e": 8797,
"s": 8677,
"text": "Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 8896,
"s": 8797,
"text": "Please refer complete article on Search an element in a sorted and rotated array for more details!"
},
{
"code": null,
"e": 8909,
"s": 8896,
"text": "simmytarika5"
},
{
"code": null,
"e": 8915,
"s": 8909,
"text": "Adobe"
},
{
"code": null,
"e": 8922,
"s": 8915,
"text": "Amazon"
},
{
"code": null,
"e": 8933,
"s": 8922,
"text": "BankBazaar"
},
{
"code": null,
"e": 8947,
"s": 8933,
"text": "Binary Search"
},
{
"code": null,
"e": 8956,
"s": 8947,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 8964,
"s": 8956,
"text": "FactSet"
},
{
"code": null,
"e": 8973,
"s": 8964,
"text": "Flipkart"
},
{
"code": null,
"e": 8978,
"s": 8973,
"text": "Hike"
},
{
"code": null,
"e": 8989,
"s": 8978,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 8999,
"s": 8989,
"text": "Microsoft"
},
{
"code": null,
"e": 9005,
"s": 8999,
"text": "Paytm"
},
{
"code": null,
"e": 9014,
"s": 9005,
"text": "rotation"
},
{
"code": null,
"e": 9022,
"s": 9014,
"text": "Samsung"
},
{
"code": null,
"e": 9031,
"s": 9022,
"text": "SAP Labs"
},
{
"code": null,
"e": 9040,
"s": 9031,
"text": "Snapdeal"
},
{
"code": null,
"e": 9055,
"s": 9040,
"text": "Times Internet"
},
{
"code": null,
"e": 9062,
"s": 9055,
"text": "Arrays"
},
{
"code": null,
"e": 9067,
"s": 9062,
"text": "Java"
},
{
"code": null,
"e": 9081,
"s": 9067,
"text": "Java Programs"
},
{
"code": null,
"e": 9091,
"s": 9081,
"text": "Searching"
},
{
"code": null,
"e": 9097,
"s": 9091,
"text": "Paytm"
},
{
"code": null,
"e": 9106,
"s": 9097,
"text": "Flipkart"
},
{
"code": null,
"e": 9113,
"s": 9106,
"text": "Amazon"
},
{
"code": null,
"e": 9123,
"s": 9113,
"text": "Microsoft"
},
{
"code": null,
"e": 9131,
"s": 9123,
"text": "Samsung"
},
{
"code": null,
"e": 9140,
"s": 9131,
"text": "Snapdeal"
},
{
"code": null,
"e": 9149,
"s": 9140,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 9157,
"s": 9149,
"text": "FactSet"
},
{
"code": null,
"e": 9162,
"s": 9157,
"text": "Hike"
},
{
"code": null,
"e": 9173,
"s": 9162,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 9179,
"s": 9173,
"text": "Adobe"
},
{
"code": null,
"e": 9190,
"s": 9179,
"text": "BankBazaar"
},
{
"code": null,
"e": 9205,
"s": 9190,
"text": "Times Internet"
},
{
"code": null,
"e": 9214,
"s": 9205,
"text": "SAP Labs"
},
{
"code": null,
"e": 9221,
"s": 9214,
"text": "Arrays"
},
{
"code": null,
"e": 9231,
"s": 9221,
"text": "Searching"
},
{
"code": null,
"e": 9236,
"s": 9231,
"text": "Java"
},
{
"code": null,
"e": 9250,
"s": 9236,
"text": "Binary Search"
},
{
"code": null,
"e": 9348,
"s": 9250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9380,
"s": 9348,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9405,
"s": 9380,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9452,
"s": 9405,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9516,
"s": 9452,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9547,
"s": 9516,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 9583,
"s": 9547,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 9627,
"s": 9583,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9652,
"s": 9627,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9703,
"s": 9652,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
]
|
Convert PySpark RDD to DataFrame | 16 May, 2021
In this article, we will discuss how to convert the RDD to dataframe in PySpark. There are two approaches to convert RDD to dataframe.
Using createDataframe(rdd, schema)Using toDF(schema)
Using createDataframe(rdd, schema)
Using toDF(schema)
But before moving forward for converting RDD to Dataframe first let’s create an RDD
Example:
Python
# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .appName("Corona_cases_statewise.com") \ .getOrCreate() return spk # function to create RDDdef create_RDD(sc_obj, data): df = sc.parallelize(data) return df if __name__ == "__main__": input_data = [("Uttar Pradesh", 122000, 89600, 12238), ("Maharashtra", 454000, 380000, 67985), ("Tamil Nadu", 115000, 102000, 13933), ("Karnataka", 147000, 111000, 15306), ("Kerala", 153000, 124000, 5259)] # calling function to create SparkSession spark = create_session() # creating spark context object sc = spark.sparkContext # calling function to create RDD rd_df = create_RDD(sc, input_data) # printing the type print(type(rd_df))
Output:
<class 'pyspark.rdd.RDD'>
After creating the RDD we have converted it to Dataframe using createDataframe() function in which we have passed the RDD and defined schema for Dataframe.
Syntax:
spark.CreateDataFrame(rdd, schema)
Python
# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .appName("Corona_cases_statewise.com") \ .getOrCreate() return spk # function to create RDDdef create_RDD(sc_obj,data): df = sc.parallelize(data) return df # function to convert RDD to dataframedef RDD_to_df(spark,df,schema): # converting RDD to df using createDataframe() # in which we are passing RDD and schema of df df1 = spark.createDataFrame(df,schema) return df1 if __name__ == "__main__": input_data = [("Uttar Pradesh",122000,89600,12238), ("Maharashtra",454000,380000,67985), ("Tamil Nadu",115000,102000,13933), ("Karnataka",147000,111000,15306), ("Kerala",153000,124000,5259)] # calling function to create SparkSession spark = create_session() # creating spark context object sc = spark.sparkContext # calling function to create RDD rd_df = create_RDD(sc,input_data) schema_lst = ["State","Cases","Recovered","Deaths"] # calling function to covert RDD to dataframe converted_df = RDD_to_df(spark,rd_df,schema_lst) # visualizing the schema and dataframe converted_df.printSchema() converted_df.show()
Output:
After creating the RDD we have converted it to Dataframe using the toDF() function in which we have passed the defined schema for Dataframe.
Syntax:
df.toDF(schema)
Python
# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .appName("Corona_cases_statewise.com") \ .getOrCreate() return spk # function to create RDDdef create_RDD(sc,data): df = sc.parallelize(data) return df # function to convert RDD to dataframedef RDD_to_df(df,schema): # converting RDD to dataframe using toDF() # in which we are passing schema of df df = rd_df.toDF(schema) return df if __name__ == "__main__": input_data = [("Uttar Pradesh",122000,89600,12238), ("Maharashtra",454000,380000,67985), ("Tamil Nadu",115000,102000,13933), ("Karnataka",147000,111000,15306), ("Kerala",153000,124000,5259)] # calling function to create SparkSession spark = create_session() # creating spark context object sc = spark.sparkContext # calling function to create RDD rd_df = create_RDD(sc,input_data) schema_lst = ["State","Cases","Recovered","Deaths"] # calling function to covert RDD to dataframe converted_df = RDD_to_df(rd_df,schema_lst) # visualizing the schema and dataframe converted_df.printSchema() converted_df.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 163,
"s": 28,
"text": "In this article, we will discuss how to convert the RDD to dataframe in PySpark. There are two approaches to convert RDD to dataframe."
},
{
"code": null,
"e": 216,
"s": 163,
"text": "Using createDataframe(rdd, schema)Using toDF(schema)"
},
{
"code": null,
"e": 251,
"s": 216,
"text": "Using createDataframe(rdd, schema)"
},
{
"code": null,
"e": 270,
"s": 251,
"text": "Using toDF(schema)"
},
{
"code": null,
"e": 354,
"s": 270,
"text": "But before moving forward for converting RDD to Dataframe first let’s create an RDD"
},
{
"code": null,
"e": 363,
"s": 354,
"text": "Example:"
},
{
"code": null,
"e": 370,
"s": 363,
"text": "Python"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .appName(\"Corona_cases_statewise.com\") \\ .getOrCreate() return spk # function to create RDDdef create_RDD(sc_obj, data): df = sc.parallelize(data) return df if __name__ == \"__main__\": input_data = [(\"Uttar Pradesh\", 122000, 89600, 12238), (\"Maharashtra\", 454000, 380000, 67985), (\"Tamil Nadu\", 115000, 102000, 13933), (\"Karnataka\", 147000, 111000, 15306), (\"Kerala\", 153000, 124000, 5259)] # calling function to create SparkSession spark = create_session() # creating spark context object sc = spark.sparkContext # calling function to create RDD rd_df = create_RDD(sc, input_data) # printing the type print(type(rd_df))",
"e": 1282,
"s": 370,
"text": null
},
{
"code": null,
"e": 1290,
"s": 1282,
"text": "Output:"
},
{
"code": null,
"e": 1316,
"s": 1290,
"text": "<class 'pyspark.rdd.RDD'>"
},
{
"code": null,
"e": 1472,
"s": 1316,
"text": "After creating the RDD we have converted it to Dataframe using createDataframe() function in which we have passed the RDD and defined schema for Dataframe."
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "Syntax:"
},
{
"code": null,
"e": 1515,
"s": 1480,
"text": "spark.CreateDataFrame(rdd, schema)"
},
{
"code": null,
"e": 1522,
"s": 1515,
"text": "Python"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .appName(\"Corona_cases_statewise.com\") \\ .getOrCreate() return spk # function to create RDDdef create_RDD(sc_obj,data): df = sc.parallelize(data) return df # function to convert RDD to dataframedef RDD_to_df(spark,df,schema): # converting RDD to df using createDataframe() # in which we are passing RDD and schema of df df1 = spark.createDataFrame(df,schema) return df1 if __name__ == \"__main__\": input_data = [(\"Uttar Pradesh\",122000,89600,12238), (\"Maharashtra\",454000,380000,67985), (\"Tamil Nadu\",115000,102000,13933), (\"Karnataka\",147000,111000,15306), (\"Kerala\",153000,124000,5259)] # calling function to create SparkSession spark = create_session() # creating spark context object sc = spark.sparkContext # calling function to create RDD rd_df = create_RDD(sc,input_data) schema_lst = [\"State\",\"Cases\",\"Recovered\",\"Deaths\"] # calling function to covert RDD to dataframe converted_df = RDD_to_df(spark,rd_df,schema_lst) # visualizing the schema and dataframe converted_df.printSchema() converted_df.show()",
"e": 2784,
"s": 1522,
"text": null
},
{
"code": null,
"e": 2792,
"s": 2784,
"text": "Output:"
},
{
"code": null,
"e": 2933,
"s": 2792,
"text": "After creating the RDD we have converted it to Dataframe using the toDF() function in which we have passed the defined schema for Dataframe."
},
{
"code": null,
"e": 2941,
"s": 2933,
"text": "Syntax:"
},
{
"code": null,
"e": 2957,
"s": 2941,
"text": "df.toDF(schema)"
},
{
"code": null,
"e": 2964,
"s": 2957,
"text": "Python"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .appName(\"Corona_cases_statewise.com\") \\ .getOrCreate() return spk # function to create RDDdef create_RDD(sc,data): df = sc.parallelize(data) return df # function to convert RDD to dataframedef RDD_to_df(df,schema): # converting RDD to dataframe using toDF() # in which we are passing schema of df df = rd_df.toDF(schema) return df if __name__ == \"__main__\": input_data = [(\"Uttar Pradesh\",122000,89600,12238), (\"Maharashtra\",454000,380000,67985), (\"Tamil Nadu\",115000,102000,13933), (\"Karnataka\",147000,111000,15306), (\"Kerala\",153000,124000,5259)] # calling function to create SparkSession spark = create_session() # creating spark context object sc = spark.sparkContext # calling function to create RDD rd_df = create_RDD(sc,input_data) schema_lst = [\"State\",\"Cases\",\"Recovered\",\"Deaths\"] # calling function to covert RDD to dataframe converted_df = RDD_to_df(rd_df,schema_lst) # visualizing the schema and dataframe converted_df.printSchema() converted_df.show()",
"e": 4182,
"s": 2964,
"text": null
},
{
"code": null,
"e": 4190,
"s": 4182,
"text": "Output:"
},
{
"code": null,
"e": 4197,
"s": 4190,
"text": "Picked"
},
{
"code": null,
"e": 4212,
"s": 4197,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 4219,
"s": 4212,
"text": "Python"
}
]
|
Make your own Rick Sanchez (bot) with Transformers and DialoGPT fine-tuning | by Rostyslav Neskorozhenyi | Towards Data Science | I am a big fan of ‘Rick and Morty’ and NLP (Natural Language Processing). After watching the last episode of a mad scientist’s and his grandson’s adventures I realized that I have to apply my knowledge in NLP and Machine Learning to create my own Rick (in a form of chat-bot, at least for now).
The path to creating virtual Rick was not easy. I tried many models and approaches but virtual Rick did not want to find a common language with me for a long time. Rick’s first response to my greeting was “I am not your buddy” (to tell you the truth, in the beginning, he knew only this phrase). But I did not give up and with the help of excellent Transformers library and Microsoft’s Large-scale Pretrained Response Generation Model (DialoGPT) I managed to talk heart-to-heart with Rick. Here is one of our conversations:
User:Hey, Rick, make me a time machine RickBot: You’re a monster! User:No, I just want to travel in time RickBot: To the past. User:yes RickBot: No time machine, please. User:But I need it RickBot: You don’t need it, Morty. Just do it. User:I want to see ancient Greece RickBot: Oh, geez.
In this article, I will tell you how to create a virtual character whose statements will be based on a transcript of my favorite animated science fiction sitcom. You can use characters and sitcoms of your choice. I added code to convert a regular text file with dialogs into a format that the model understands.
As I already mentioned, the Transformers library, which contains the latest NLP models (such as BERT, XLNet, GPT-2) will help us in our task. You can read more about transformers in a beautifully illustrated article by Jay Alammar.
Not so long ago, Microsoft’s DialoGPT was added to the Transformers model collection. DialoGPT is a GPT-2 model, trained on 147M multi-turn dialogue from Reddit discussion thread (you can learn more about GPT-2 here). This model is ideally suited for creating a virtual character for a fascinating conversation and even in the small implementation option, it can maintain a coherent dialogue, which we will see now.
We will conduct all our experiments in Google Colab, its resources are enough to train the small DialoGPT model. Firstly, we will connect to Google Drive and install the necessary modules.
from google.colab import drivedrive.mount('/content/drive/')! pip -q install transformers
Let’s move to the desired folder in which we will store all our data.
import osos.chdir("/content/drive/My Drive/Colab Notebooks")
Try to chat with DialoGPT without fine-tuning.
from transformers import AutoModelWithLMHead, AutoTokenizerimport torchtokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")model = AutoModelWithLMHead.from_pretrained("microsoft/DialoGPT-small")
Let’s chat for 5 lines
for step in range(5): # encode the new user input, add the eos_token and return a tensor in Pytorch new_user_input_ids = tokenizer.encode(input(">> User:") + tokenizer.eos_token, return_tensors='pt')# append the new user input tokens to the chat history bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if step > 0 else new_user_input_ids# generated a response while limiting the total chat history to 1000 tokens chat_history_ids = model.generate( bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id )# pretty print last ouput tokens from bot print("DialoGPT: {}".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))
User:Hi Rick DialoGPT: Hi Rick User:How are you? DialoGPT: I’m good, how are you? User:I am fine. Where is Morty? DialoGPT: He’s in the basement. User:Who is Morty? DialoGPT: He’s a Morty. User:Who are you? DialoGPT: I am a Morty.
Not bad but not too impressive. We will fix it with fine-tuning.
Let’s train our own Rick chatbot. For a start, we will need basic configuration and a dataset. Configuration and training scripts are mostly based on this script from Huggingface and great tutorial from Nathan Cooper.
Class Args for conversion of Python script arguments to Colab notebook.
Our dialogues dataset will be based on a dataset used in Andrada Olteanu’s article about Rick and Morty sentiment analysis. Big thanks to her work and also to Gabriel Hernandes, author of original text dataset!
First of all, we will use a Kaggle module to download the needed dataset. You can read in more detail about the module and how to get a Kaggle API Token by this link. Or you can just download RickAndMortyScripts.csv file from this article and place this file in your working directory.
!pip install kaggle!mkdir ~/.kaggle!cp kaggle.json ~/.kaggle/kaggle.json!kaggle datasets download andradaolteanu/rickmorty-scripts -f RickAndMortyScripts.csv !mv datasets%2F506221%2F935855%2FRickAndMortyScripts.csv RickAndMortyScripts.csv
Let’s look at the original dataset.
all_rick = pd.read_csv('RickAndMortyScripts.csv')all_rick.head(10)
We will convert this dataset in a way that every response row will contain n previous responses as a context. For our purposes, seven previous responses will be enough.
contexted = []n = 7for i in range(n, len(all_rick['line'])): row = [] prev = i - 1 - n # we additionally subtract 1, so row will contain current response and 7 previous responses for j in range(i, prev, -1): row.append(all_rick['line'][j]) contexted.append(row)columns = ['response', 'context'] columns = columns + ['context/'+str(i) for i in range(n-1)]df = pd.DataFrame.from_records(contexted, columns=columns)df.head(5)
Split our dataset into training and test parts.
trn_df, val_df = train_test_split(df, test_size = 0.1)
Now we will convert our dataset in a format suitable for our model. Basically we will concatenate responses in one string for each row (additionally we will add special ‘end of string’ token between responses, so the model will understand the end of each response in a string).
There will be quite a lot of code needed for training our model but don’t worry, everything should work as is, the main thing is to give the model the dataset in the right format.
And here is the main runner code.
It is time to train our model!
main(trn_df, val_df)
Our dataset is quite small so training will not take a lot of time (usually — about a half an hour).
The model is ready, so it’s time to chat with Rick. But don’t forget that Rick can be rude, I warned you.
A variety of methods can be used in responses generation. You can find more details about these methods by this link.
tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-small')model = AutoModelWithLMHead.from_pretrained('output-small')# Let's chat for 5 linesfor step in range(5): # encode the new user input, add the eos_token and return a tensor in Pytorch new_user_input_ids = tokenizer.encode(input(">> User:") + tokenizer.eos_token, return_tensors='pt') # print(new_user_input_ids)# append the new user input tokens to the chat history bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if step > 0 else new_user_input_ids# generated a response while limiting the total chat history to 1000 tokens, chat_history_ids = model.generate( bot_input_ids, max_length=200, pad_token_id=tokenizer.eos_token_id, no_repeat_ngram_size=3, do_sample=True, top_k=100, top_p=0.7, temperature = 0.8 ) # pretty print last ouput tokens from bot print("RickBot: {}".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))
User:How are you, Rick? RickBot: I’m fine. User:Where is Morty? RickBot: He’s in a hospital. User:Why? RickBot: Well, that depends on who breaks first — me or the hospital. I mean, you know, the one that keeps giving me pills. User:I don’t understand RickBot: Whoa! Whoa! User:I see, you took your pills RickBot: Hey, I-I’m not proud of this.
Not bad. I will give examples of a few more dialogues to show how Ricky is our Rick now.
User:Who are you? RickBot: A musician, I’m not a musician, but I’m pretty close to you. User:What kind of musician are you? RickBot: Who cares? I’m a musician. User:Ok, play a song for me RickBot: Shut up and listen to me, Morty. Listen to me. Listen! I’m the leader of a bunch of different death worlds, and I’m just trying to assemble a band. I’m gonna make this one-piece, and you’re gonna be part of it. User:ok RickBot: Whoa, whoa, hey, who’s this? User:This is Morty RickBot: Geez!!!
User:What do you think about Elon Musk? RickBot: I think about him a lot. User:But what exactly do you think? RickBot: He’s not a bad guy. He’s just... not a very charismatic one. User:I think he is charismatic RickBot: He is. User:What else you can say about him? RickBot: You don’t have to say anything. He is the leader of your class. User:ok, thank you RickBot: !!!
Congratulations! Our virtual Rick is alive (almost)! With the help of fine-tuning of DialoGPT model on a small dataset, we were able to create a virtual character with whom we can make a lot of mad dialogs.
Using the proposed approach we can create many interesting virtual characters based on an arbitrary dialogs dataset (just a csv file with characters speeches, one speech per line).
All mentioned code is accessible as a Google Colab notebook. | [
{
"code": null,
"e": 466,
"s": 171,
"text": "I am a big fan of ‘Rick and Morty’ and NLP (Natural Language Processing). After watching the last episode of a mad scientist’s and his grandson’s adventures I realized that I have to apply my knowledge in NLP and Machine Learning to create my own Rick (in a form of chat-bot, at least for now)."
},
{
"code": null,
"e": 990,
"s": 466,
"text": "The path to creating virtual Rick was not easy. I tried many models and approaches but virtual Rick did not want to find a common language with me for a long time. Rick’s first response to my greeting was “I am not your buddy” (to tell you the truth, in the beginning, he knew only this phrase). But I did not give up and with the help of excellent Transformers library and Microsoft’s Large-scale Pretrained Response Generation Model (DialoGPT) I managed to talk heart-to-heart with Rick. Here is one of our conversations:"
},
{
"code": null,
"e": 1279,
"s": 990,
"text": "User:Hey, Rick, make me a time machine RickBot: You’re a monster! User:No, I just want to travel in time RickBot: To the past. User:yes RickBot: No time machine, please. User:But I need it RickBot: You don’t need it, Morty. Just do it. User:I want to see ancient Greece RickBot: Oh, geez."
},
{
"code": null,
"e": 1591,
"s": 1279,
"text": "In this article, I will tell you how to create a virtual character whose statements will be based on a transcript of my favorite animated science fiction sitcom. You can use characters and sitcoms of your choice. I added code to convert a regular text file with dialogs into a format that the model understands."
},
{
"code": null,
"e": 1823,
"s": 1591,
"text": "As I already mentioned, the Transformers library, which contains the latest NLP models (such as BERT, XLNet, GPT-2) will help us in our task. You can read more about transformers in a beautifully illustrated article by Jay Alammar."
},
{
"code": null,
"e": 2239,
"s": 1823,
"text": "Not so long ago, Microsoft’s DialoGPT was added to the Transformers model collection. DialoGPT is a GPT-2 model, trained on 147M multi-turn dialogue from Reddit discussion thread (you can learn more about GPT-2 here). This model is ideally suited for creating a virtual character for a fascinating conversation and even in the small implementation option, it can maintain a coherent dialogue, which we will see now."
},
{
"code": null,
"e": 2428,
"s": 2239,
"text": "We will conduct all our experiments in Google Colab, its resources are enough to train the small DialoGPT model. Firstly, we will connect to Google Drive and install the necessary modules."
},
{
"code": null,
"e": 2518,
"s": 2428,
"text": "from google.colab import drivedrive.mount('/content/drive/')! pip -q install transformers"
},
{
"code": null,
"e": 2588,
"s": 2518,
"text": "Let’s move to the desired folder in which we will store all our data."
},
{
"code": null,
"e": 2649,
"s": 2588,
"text": "import osos.chdir(\"/content/drive/My Drive/Colab Notebooks\")"
},
{
"code": null,
"e": 2696,
"s": 2649,
"text": "Try to chat with DialoGPT without fine-tuning."
},
{
"code": null,
"e": 2908,
"s": 2696,
"text": "from transformers import AutoModelWithLMHead, AutoTokenizerimport torchtokenizer = AutoTokenizer.from_pretrained(\"microsoft/DialoGPT-small\")model = AutoModelWithLMHead.from_pretrained(\"microsoft/DialoGPT-small\")"
},
{
"code": null,
"e": 2931,
"s": 2908,
"text": "Let’s chat for 5 lines"
},
{
"code": null,
"e": 3667,
"s": 2931,
"text": "for step in range(5): # encode the new user input, add the eos_token and return a tensor in Pytorch new_user_input_ids = tokenizer.encode(input(\">> User:\") + tokenizer.eos_token, return_tensors='pt')# append the new user input tokens to the chat history bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if step > 0 else new_user_input_ids# generated a response while limiting the total chat history to 1000 tokens chat_history_ids = model.generate( bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id )# pretty print last ouput tokens from bot print(\"DialoGPT: {}\".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))"
},
{
"code": null,
"e": 3898,
"s": 3667,
"text": "User:Hi Rick DialoGPT: Hi Rick User:How are you? DialoGPT: I’m good, how are you? User:I am fine. Where is Morty? DialoGPT: He’s in the basement. User:Who is Morty? DialoGPT: He’s a Morty. User:Who are you? DialoGPT: I am a Morty."
},
{
"code": null,
"e": 3963,
"s": 3898,
"text": "Not bad but not too impressive. We will fix it with fine-tuning."
},
{
"code": null,
"e": 4181,
"s": 3963,
"text": "Let’s train our own Rick chatbot. For a start, we will need basic configuration and a dataset. Configuration and training scripts are mostly based on this script from Huggingface and great tutorial from Nathan Cooper."
},
{
"code": null,
"e": 4253,
"s": 4181,
"text": "Class Args for conversion of Python script arguments to Colab notebook."
},
{
"code": null,
"e": 4464,
"s": 4253,
"text": "Our dialogues dataset will be based on a dataset used in Andrada Olteanu’s article about Rick and Morty sentiment analysis. Big thanks to her work and also to Gabriel Hernandes, author of original text dataset!"
},
{
"code": null,
"e": 4750,
"s": 4464,
"text": "First of all, we will use a Kaggle module to download the needed dataset. You can read in more detail about the module and how to get a Kaggle API Token by this link. Or you can just download RickAndMortyScripts.csv file from this article and place this file in your working directory."
},
{
"code": null,
"e": 4989,
"s": 4750,
"text": "!pip install kaggle!mkdir ~/.kaggle!cp kaggle.json ~/.kaggle/kaggle.json!kaggle datasets download andradaolteanu/rickmorty-scripts -f RickAndMortyScripts.csv !mv datasets%2F506221%2F935855%2FRickAndMortyScripts.csv RickAndMortyScripts.csv"
},
{
"code": null,
"e": 5025,
"s": 4989,
"text": "Let’s look at the original dataset."
},
{
"code": null,
"e": 5092,
"s": 5025,
"text": "all_rick = pd.read_csv('RickAndMortyScripts.csv')all_rick.head(10)"
},
{
"code": null,
"e": 5261,
"s": 5092,
"text": "We will convert this dataset in a way that every response row will contain n previous responses as a context. For our purposes, seven previous responses will be enough."
},
{
"code": null,
"e": 5693,
"s": 5261,
"text": "contexted = []n = 7for i in range(n, len(all_rick['line'])): row = [] prev = i - 1 - n # we additionally subtract 1, so row will contain current response and 7 previous responses for j in range(i, prev, -1): row.append(all_rick['line'][j]) contexted.append(row)columns = ['response', 'context'] columns = columns + ['context/'+str(i) for i in range(n-1)]df = pd.DataFrame.from_records(contexted, columns=columns)df.head(5)"
},
{
"code": null,
"e": 5741,
"s": 5693,
"text": "Split our dataset into training and test parts."
},
{
"code": null,
"e": 5796,
"s": 5741,
"text": "trn_df, val_df = train_test_split(df, test_size = 0.1)"
},
{
"code": null,
"e": 6074,
"s": 5796,
"text": "Now we will convert our dataset in a format suitable for our model. Basically we will concatenate responses in one string for each row (additionally we will add special ‘end of string’ token between responses, so the model will understand the end of each response in a string)."
},
{
"code": null,
"e": 6254,
"s": 6074,
"text": "There will be quite a lot of code needed for training our model but don’t worry, everything should work as is, the main thing is to give the model the dataset in the right format."
},
{
"code": null,
"e": 6288,
"s": 6254,
"text": "And here is the main runner code."
},
{
"code": null,
"e": 6319,
"s": 6288,
"text": "It is time to train our model!"
},
{
"code": null,
"e": 6340,
"s": 6319,
"text": "main(trn_df, val_df)"
},
{
"code": null,
"e": 6441,
"s": 6340,
"text": "Our dataset is quite small so training will not take a lot of time (usually — about a half an hour)."
},
{
"code": null,
"e": 6547,
"s": 6441,
"text": "The model is ready, so it’s time to chat with Rick. But don’t forget that Rick can be rude, I warned you."
},
{
"code": null,
"e": 6665,
"s": 6547,
"text": "A variety of methods can be used in responses generation. You can find more details about these methods by this link."
},
{
"code": null,
"e": 7723,
"s": 6665,
"text": "tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-small')model = AutoModelWithLMHead.from_pretrained('output-small')# Let's chat for 5 linesfor step in range(5): # encode the new user input, add the eos_token and return a tensor in Pytorch new_user_input_ids = tokenizer.encode(input(\">> User:\") + tokenizer.eos_token, return_tensors='pt') # print(new_user_input_ids)# append the new user input tokens to the chat history bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if step > 0 else new_user_input_ids# generated a response while limiting the total chat history to 1000 tokens, chat_history_ids = model.generate( bot_input_ids, max_length=200, pad_token_id=tokenizer.eos_token_id, no_repeat_ngram_size=3, do_sample=True, top_k=100, top_p=0.7, temperature = 0.8 ) # pretty print last ouput tokens from bot print(\"RickBot: {}\".format(tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)))"
},
{
"code": null,
"e": 8066,
"s": 7723,
"text": "User:How are you, Rick? RickBot: I’m fine. User:Where is Morty? RickBot: He’s in a hospital. User:Why? RickBot: Well, that depends on who breaks first — me or the hospital. I mean, you know, the one that keeps giving me pills. User:I don’t understand RickBot: Whoa! Whoa! User:I see, you took your pills RickBot: Hey, I-I’m not proud of this."
},
{
"code": null,
"e": 8155,
"s": 8066,
"text": "Not bad. I will give examples of a few more dialogues to show how Ricky is our Rick now."
},
{
"code": null,
"e": 8645,
"s": 8155,
"text": "User:Who are you? RickBot: A musician, I’m not a musician, but I’m pretty close to you. User:What kind of musician are you? RickBot: Who cares? I’m a musician. User:Ok, play a song for me RickBot: Shut up and listen to me, Morty. Listen to me. Listen! I’m the leader of a bunch of different death worlds, and I’m just trying to assemble a band. I’m gonna make this one-piece, and you’re gonna be part of it. User:ok RickBot: Whoa, whoa, hey, who’s this? User:This is Morty RickBot: Geez!!!"
},
{
"code": null,
"e": 9015,
"s": 8645,
"text": "User:What do you think about Elon Musk? RickBot: I think about him a lot. User:But what exactly do you think? RickBot: He’s not a bad guy. He’s just... not a very charismatic one. User:I think he is charismatic RickBot: He is. User:What else you can say about him? RickBot: You don’t have to say anything. He is the leader of your class. User:ok, thank you RickBot: !!!"
},
{
"code": null,
"e": 9222,
"s": 9015,
"text": "Congratulations! Our virtual Rick is alive (almost)! With the help of fine-tuning of DialoGPT model on a small dataset, we were able to create a virtual character with whom we can make a lot of mad dialogs."
},
{
"code": null,
"e": 9403,
"s": 9222,
"text": "Using the proposed approach we can create many interesting virtual characters based on an arbitrary dialogs dataset (just a csv file with characters speeches, one speech per line)."
}
]
|
Plot the phase spectrum in Python using Matplotlib - GeeksforGeeks | 27 Apr, 2020
A Signal is an electromagnetic field or an electric current to transmit data. There are various components of a signal such as frequency, amplitude, wavelength, phase, angular frequency and period from which it is described.A periodic signal can be represented using the below sine function:
y = A sin(w*t + Q)
In which A represents the amplitude(in meter), w represents frequency(in hertz), t represents time period(in seconds) and Q represents phase(in radian) of the periodic signal.
The two major components frequency and phase of a periodic signal define the Phase Spectrum of that signal. The frequency components of the periodic signal are plotted in the horizontal axis and phase component of the periodic signal is plotted in the vertical axis.
In Python, the phase_spectrum() method in the pyplot module of Python matplotlib library plots the phase spectrum of a periodic signal. Below are some programs which demonstrate the use of phase_spectrum() method to visualize the phase spectrum of different periodic signals.Example 1:
# importing modulesimport numpyfrom matplotlib import pyplot # assigning time values of the signal# initial time period, final time period and phase anglesignalTime = numpy.arange(5, 10, 0.25); # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # plotting the signal pyplot.plot(signalTime, signalAmplitude, color ='green')pyplot.show() pyplot.xlabel('Time')pyplot.ylabel('Amplitude')pyplot.title("Signal") # plotting the phase spectrum of the signal pyplot.phase_spectrum(signalAmplitude, color ='green') pyplot.title("Phase Spectrum of the Signal")pyplot.show()
Output:The first graph represent the signal in Amplitude vs Time components, the second graph represents the phase spectrum of the signal in Phase vs Frequency graph by using phase_spectrum() on the signal having time period from 5 to 10 seconds, 0.25 radian phase angle, frequency of the signal is calculated from the given time period and amplitude of the signal is calculated using the sin() function in numpy module.Example 2:
# importing modulesimport numpyfrom matplotlib import pyplot # assigning time values of the signal# initial time period, final time period and phase anglesignalTime = numpy.arange(0, 1, 0.1) # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # plotting the signal pyplot.plot(signalTime, signalAmplitude, color ='green')pyplot.show() pyplot.xlabel('Time')pyplot.ylabel('Amplitude')pyplot.title("Signal") # plotting the phase spectrum of the signal pyplot.phase_spectrum(signalAmplitude, color ='green') pyplot.title("Phase Spectrum of the Signal")pyplot.show()
Output:In the above program, as the amplitude of the signal is increasing with time so a sinusoidal wave is not formed in the first graph. The signal exists in the time period of 0 to 1 second and the phase angle is 0.1 radian, the phase spectrum of the signal is depicted using phase_spectrum() method.
Example 3:
# importing modulesimport numpyfrom matplotlib import pyplot # assigning time values of the signal# initial time period, final time period and phase angle signalTime = numpy.arange(1, 100, 0.5); # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # plotting the signal pyplot.plot(signalTime, signalAmplitude, color ='green')pyplot.show() pyplot.xlabel('Time')pyplot.ylabel('Amplitude')pyplot.title("Signal") # plotting the phase spectrum of the signal pyplot.phase_spectrum(signalAmplitude, color ='green') pyplot.title("Phase Spectrum of the Signal")pyplot.show()
Output:Here, the signal is represented in Amplitude vs Time graph which forms sinusoidal waves and the phase spectrum of the signal is represented using phase_spectrum() method in Phase vs Frequency graph. The time period of the signal starts from 1 second to 100th second and the phase angle is 0.5 radian.
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 25817,
"s": 25789,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 26109,
"s": 25817,
"text": "A Signal is an electromagnetic field or an electric current to transmit data. There are various components of a signal such as frequency, amplitude, wavelength, phase, angular frequency and period from which it is described.A periodic signal can be represented using the below sine function:"
},
{
"code": null,
"e": 26129,
"s": 26109,
"text": "y = A sin(w*t + Q)\n"
},
{
"code": null,
"e": 26305,
"s": 26129,
"text": "In which A represents the amplitude(in meter), w represents frequency(in hertz), t represents time period(in seconds) and Q represents phase(in radian) of the periodic signal."
},
{
"code": null,
"e": 26572,
"s": 26305,
"text": "The two major components frequency and phase of a periodic signal define the Phase Spectrum of that signal. The frequency components of the periodic signal are plotted in the horizontal axis and phase component of the periodic signal is plotted in the vertical axis."
},
{
"code": null,
"e": 26858,
"s": 26572,
"text": "In Python, the phase_spectrum() method in the pyplot module of Python matplotlib library plots the phase spectrum of a periodic signal. Below are some programs which demonstrate the use of phase_spectrum() method to visualize the phase spectrum of different periodic signals.Example 1:"
},
{
"code": "# importing modulesimport numpyfrom matplotlib import pyplot # assigning time values of the signal# initial time period, final time period and phase anglesignalTime = numpy.arange(5, 10, 0.25); # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # plotting the signal pyplot.plot(signalTime, signalAmplitude, color ='green')pyplot.show() pyplot.xlabel('Time')pyplot.ylabel('Amplitude')pyplot.title(\"Signal\") # plotting the phase spectrum of the signal pyplot.phase_spectrum(signalAmplitude, color ='green') pyplot.title(\"Phase Spectrum of the Signal\")pyplot.show()",
"e": 27458,
"s": 26858,
"text": null
},
{
"code": null,
"e": 27889,
"s": 27458,
"text": "Output:The first graph represent the signal in Amplitude vs Time components, the second graph represents the phase spectrum of the signal in Phase vs Frequency graph by using phase_spectrum() on the signal having time period from 5 to 10 seconds, 0.25 radian phase angle, frequency of the signal is calculated from the given time period and amplitude of the signal is calculated using the sin() function in numpy module.Example 2:"
},
{
"code": "# importing modulesimport numpyfrom matplotlib import pyplot # assigning time values of the signal# initial time period, final time period and phase anglesignalTime = numpy.arange(0, 1, 0.1) # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # plotting the signal pyplot.plot(signalTime, signalAmplitude, color ='green')pyplot.show() pyplot.xlabel('Time')pyplot.ylabel('Amplitude')pyplot.title(\"Signal\") # plotting the phase spectrum of the signal pyplot.phase_spectrum(signalAmplitude, color ='green') pyplot.title(\"Phase Spectrum of the Signal\")pyplot.show()",
"e": 28486,
"s": 27889,
"text": null
},
{
"code": null,
"e": 28790,
"s": 28486,
"text": "Output:In the above program, as the amplitude of the signal is increasing with time so a sinusoidal wave is not formed in the first graph. The signal exists in the time period of 0 to 1 second and the phase angle is 0.1 radian, the phase spectrum of the signal is depicted using phase_spectrum() method."
},
{
"code": null,
"e": 28801,
"s": 28790,
"text": "Example 3:"
},
{
"code": "# importing modulesimport numpyfrom matplotlib import pyplot # assigning time values of the signal# initial time period, final time period and phase angle signalTime = numpy.arange(1, 100, 0.5); # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # plotting the signal pyplot.plot(signalTime, signalAmplitude, color ='green')pyplot.show() pyplot.xlabel('Time')pyplot.ylabel('Amplitude')pyplot.title(\"Signal\") # plotting the phase spectrum of the signal pyplot.phase_spectrum(signalAmplitude, color ='green') pyplot.title(\"Phase Spectrum of the Signal\")pyplot.show()",
"e": 29402,
"s": 28801,
"text": null
},
{
"code": null,
"e": 29710,
"s": 29402,
"text": "Output:Here, the signal is represented in Amplitude vs Time graph which forms sinusoidal waves and the phase spectrum of the signal is represented using phase_spectrum() method in Phase vs Frequency graph. The time period of the signal starts from 1 second to 100th second and the phase angle is 0.5 radian."
},
{
"code": null,
"e": 29728,
"s": 29710,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29735,
"s": 29728,
"text": "Python"
},
{
"code": null,
"e": 29751,
"s": 29735,
"text": "Write From Home"
},
{
"code": null,
"e": 29849,
"s": 29751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29867,
"s": 29849,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29902,
"s": 29867,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29934,
"s": 29902,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29956,
"s": 29934,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29998,
"s": 29956,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30034,
"s": 29998,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 30070,
"s": 30034,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 30131,
"s": 30070,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30147,
"s": 30131,
"text": "Python infinity"
}
]
|
3 Must-Know SQL Functions For Efficient Data Analysis | by Soner Yıldırım | Towards Data Science | Explained with practical examples
SQL is a programming language used by relational database management systems. It provides numerous functions and methods that operate on the data stored in relational databases.
SQL is not just a query language. We can use it to filter, manipulate, and analyze data as well. In this article, we will go over 3 SQL functions that are quite useful for efficient data analysis.
The functions we will cover are:
Coalesce
Case when
Row_number
I have created two sample tables and filled them with mock data. Let’s first take a look at these tables.
The tables contain sales and product data from two different stores.
Consider a case where we need to left join the sales table to the products table. They are related by the product codes so we join the tables based on this column.
SELECT P.*, S.storecode, s.date, s.salesqty, s.salesrevenue FROM products P LEFT JOIN sales S ON P.productcode = S.productcode;
Not every product has sales on the given date. For these products, the columns from the sales table contain null values (empty in the screenshot above).
We can use the coalesce function to handle null values as a result of joining tables. In our case, we can fill the sales quantity and sales revenue columns with zeroes. The date column can be filled with the date in the other rows.
SELECT P.*, S.storecode, coalesce(s.date, '2021-05-10') as date, coalesce(s.salesqty,0) as salesqty, coalesce(s.salesrevenue, 0)as salesrevenue FROM Products P LEFT JOIN Sales S ON P.productcode = S.productcode;
The empty cells are filled with the specified values in the coalesce function. I have left the store code as empty.
The case when function allows for updating values based on given conditions. It is similar to the if-else statement in Python.
Let’s say we want to select all the columns from the sales table and create an additional column based on the sales revenue. If the revenue is higher than 5, this column takes the value “high”. Otherwise, it is filled with “regular”.
We can accomplish this operation with the case when function as follows:
SELECT *, CASE WHEN salesrevenue > 5 THEN 'high' ELSE 'regular' END AS salesgroupFROM Sales;
The case when statement in the above query performs the following steps:
Create a column named “salesgroup”
When the value in the sales revenue column is more than 5, assign “high” to this column
Otherwise (i.e. else) assign “regular”
The row_number function allows for assigning a rank to the rows based on the values in a particular column. We can make it more flexible or useful by combining with a partition.
Recall the sales table:
Let’s assume we need to assign a rank based on the sales revenue. We want to have separate ranks for different product groups. Thus, fruits and vegetables will be ranked within themselves.
The first step is to take the product group column from the products table. Then, we will use the row_number function.
SELECT S.*, P.productgroup, ROW_NUMBER() OVER(PARTITION BY P.productgroup ORDER BY salesrevenue DESC) AS salesrankFROM sales S LEFT JOIN products P ON S.productcode = P.productcode;
In each group, first rank is assigned to the row with the highest sales revenue. Then, it increases accordingly.
SQL is a powerful tool in the data science ecosystem. It is definitely a must-have skill for data scientists. We should use SQL not only for retrieving data from a database but also for data analysis and manipulation.
SQL is able to perform almost all the operations that can be done with popular data analysis libraries such as Python pandas and R data table.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 205,
"s": 171,
"text": "Explained with practical examples"
},
{
"code": null,
"e": 383,
"s": 205,
"text": "SQL is a programming language used by relational database management systems. It provides numerous functions and methods that operate on the data stored in relational databases."
},
{
"code": null,
"e": 580,
"s": 383,
"text": "SQL is not just a query language. We can use it to filter, manipulate, and analyze data as well. In this article, we will go over 3 SQL functions that are quite useful for efficient data analysis."
},
{
"code": null,
"e": 613,
"s": 580,
"text": "The functions we will cover are:"
},
{
"code": null,
"e": 622,
"s": 613,
"text": "Coalesce"
},
{
"code": null,
"e": 632,
"s": 622,
"text": "Case when"
},
{
"code": null,
"e": 643,
"s": 632,
"text": "Row_number"
},
{
"code": null,
"e": 749,
"s": 643,
"text": "I have created two sample tables and filled them with mock data. Let’s first take a look at these tables."
},
{
"code": null,
"e": 818,
"s": 749,
"text": "The tables contain sales and product data from two different stores."
},
{
"code": null,
"e": 982,
"s": 818,
"text": "Consider a case where we need to left join the sales table to the products table. They are related by the product codes so we join the tables based on this column."
},
{
"code": null,
"e": 1425,
"s": 982,
"text": "SELECT P.*, S.storecode, s.date, s.salesqty, s.salesrevenue FROM products P LEFT JOIN sales S ON P.productcode = S.productcode;"
},
{
"code": null,
"e": 1578,
"s": 1425,
"text": "Not every product has sales on the given date. For these products, the columns from the sales table contain null values (empty in the screenshot above)."
},
{
"code": null,
"e": 1810,
"s": 1578,
"text": "We can use the coalesce function to handle null values as a result of joining tables. In our case, we can fill the sales quantity and sales revenue columns with zeroes. The date column can be filled with the date in the other rows."
},
{
"code": null,
"e": 2408,
"s": 1810,
"text": "SELECT P.*, S.storecode, coalesce(s.date, '2021-05-10') as date, coalesce(s.salesqty,0) as salesqty, coalesce(s.salesrevenue, 0)as salesrevenue FROM Products P LEFT JOIN Sales S ON P.productcode = S.productcode;"
},
{
"code": null,
"e": 2524,
"s": 2408,
"text": "The empty cells are filled with the specified values in the coalesce function. I have left the store code as empty."
},
{
"code": null,
"e": 2651,
"s": 2524,
"text": "The case when function allows for updating values based on given conditions. It is similar to the if-else statement in Python."
},
{
"code": null,
"e": 2885,
"s": 2651,
"text": "Let’s say we want to select all the columns from the sales table and create an additional column based on the sales revenue. If the revenue is higher than 5, this column takes the value “high”. Otherwise, it is filled with “regular”."
},
{
"code": null,
"e": 2958,
"s": 2885,
"text": "We can accomplish this operation with the case when function as follows:"
},
{
"code": null,
"e": 3058,
"s": 2958,
"text": "SELECT *, CASE WHEN salesrevenue > 5 THEN 'high' ELSE 'regular' END AS salesgroupFROM Sales;"
},
{
"code": null,
"e": 3131,
"s": 3058,
"text": "The case when statement in the above query performs the following steps:"
},
{
"code": null,
"e": 3166,
"s": 3131,
"text": "Create a column named “salesgroup”"
},
{
"code": null,
"e": 3254,
"s": 3166,
"text": "When the value in the sales revenue column is more than 5, assign “high” to this column"
},
{
"code": null,
"e": 3293,
"s": 3254,
"text": "Otherwise (i.e. else) assign “regular”"
},
{
"code": null,
"e": 3471,
"s": 3293,
"text": "The row_number function allows for assigning a rank to the rows based on the values in a particular column. We can make it more flexible or useful by combining with a partition."
},
{
"code": null,
"e": 3495,
"s": 3471,
"text": "Recall the sales table:"
},
{
"code": null,
"e": 3684,
"s": 3495,
"text": "Let’s assume we need to assign a rank based on the sales revenue. We want to have separate ranks for different product groups. Thus, fruits and vegetables will be ranked within themselves."
},
{
"code": null,
"e": 3803,
"s": 3684,
"text": "The first step is to take the product group column from the products table. Then, we will use the row_number function."
},
{
"code": null,
"e": 3997,
"s": 3803,
"text": "SELECT S.*, P.productgroup, ROW_NUMBER() OVER(PARTITION BY P.productgroup ORDER BY salesrevenue DESC) AS salesrankFROM sales S LEFT JOIN products P ON S.productcode = P.productcode;"
},
{
"code": null,
"e": 4110,
"s": 3997,
"text": "In each group, first rank is assigned to the row with the highest sales revenue. Then, it increases accordingly."
},
{
"code": null,
"e": 4328,
"s": 4110,
"text": "SQL is a powerful tool in the data science ecosystem. It is definitely a must-have skill for data scientists. We should use SQL not only for retrieving data from a database but also for data analysis and manipulation."
},
{
"code": null,
"e": 4471,
"s": 4328,
"text": "SQL is able to perform almost all the operations that can be done with popular data analysis libraries such as Python pandas and R data table."
}
]
|
Try/catch/finally/throw keywords in C# | Exception handling is based on the following keywords and its usage −
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
To handle exceptions, you need to set them like the following syntax in C# −
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
} | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "Exception handling is based on the following keywords and its usage −"
},
{
"code": null,
"e": 1267,
"s": 1132,
"text": "try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks."
},
{
"code": null,
"e": 1402,
"s": 1267,
"text": "try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks."
},
{
"code": null,
"e": 1589,
"s": 1402,
"text": "catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception."
},
{
"code": null,
"e": 1776,
"s": 1589,
"text": "catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception."
},
{
"code": null,
"e": 1986,
"s": 1776,
"text": "finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not."
},
{
"code": null,
"e": 2196,
"s": 1986,
"text": "finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not."
},
{
"code": null,
"e": 2295,
"s": 2196,
"text": "throw − A program throws an exception when a problem shows up. This is done using a throw keyword."
},
{
"code": null,
"e": 2394,
"s": 2295,
"text": "throw − A program throws an exception when a problem shows up. This is done using a throw keyword."
},
{
"code": null,
"e": 2471,
"s": 2394,
"text": "To handle exceptions, you need to set them like the following syntax in C# −"
},
{
"code": null,
"e": 2726,
"s": 2471,
"text": "try {\n // statements causing exception\n} catch( ExceptionName e1 ) {\n // error handling code\n} catch( ExceptionName e2 ) {\n // error handling code\n} catch( ExceptionName eN ) {\n // error handling code\n} finally {\n // statements to be executed\n}"
}
]
|
Tryit Editor v3.7 | Background Image Repeat
Tryit: Using no-repeat | [
{
"code": null,
"e": 49,
"s": 25,
"text": "Background Image Repeat"
}
]
|
Natural Language Processing — Beginner to Advanced (Part-3) | by Ishan Singh | Towards Data Science | In the previous part of the series ‘The NLP Project’, we learned all the basic lexical processing techniques such as removing stop words, tokenization, stemming, and lemmatization.
Even after going through all those preprocessing steps, a lot of noise is still present in the textual data. For example, spelling mistakes that happen by mistake as well as by choice (informal words such as ‘lol’, ‘u’, ‘gud’ etc.). Also, the problem of spelling variations of a word that occurs due to different pronunciations (e.g. Mumbai, Bombay).
The two methods that we talked about in the last part — stemming and lemmatization — are both parts of a technique called canonicalization. Basically, canonicalization means reducing a word to its base form.
There are scenarios where we can not canonicalize a word just by using stemming and lemmatization. Thus, we will need another technique to canonicalize the words correctly. For example, if the word ‘allowing’ is misspelled as ‘alowing’, then we will have a redundant token as ‘alow’ after stemming the misspelled word, and lemmatization wouldn’t even work as it only works on correct dictionary spelling.
The same problem is with the pronunciation of same words in different patois. For example, the word ‘humour’ used in British English, is spelled as ‘humor’ in American English. Both are correct spellings, but they will give two different base forms, after stemming, when used in the form ‘humouring’ and ‘humoring’.
There are some words that have different pronunciation in different languages. As a result, they are ultimately written differently. For example a common Indian surname like ‘Srivastava’ is also spelled as ‘Shrivastava’, ‘Shrivastav’, or ‘Srivastav’. Therefore, we must reduce all forms of a particular word to one single and common word.
To attain this, we will get to know about a technique is called phonetic hashing. The phonetic hashing method combines the same phonemes (smallest unit of sound) into one bucket and gives them the same hash code for all the variations. So, the words ‘color’ and ‘colour’ have the same code.
Phonetic hashing is a technique used to canocalize words that have different variants but same phonetic characteristics, that is, the same pronunciation.
Now, Soundexes are algorithms that can be used to calculate the hash code of a given word. Phonetic Hashing uses these Soundex algorithms. The algorithms differ from language to language. American Soundex is the most popular Soundex algorithm and we will be using that. Also, it doesn’t matter which language the input word comes from — as long as the words sound similar, they will get the same hash code.
Phonetic hashing is a four-character code. So, let us calculate the hash code(also known as Soundex) of the word ‘Chennai’ by applying the following steps:-
Retain the first letter of the word as is — Soundex is based on the rationale that the English pronunciation depends on the first letter and pattern of the consonants. So, C becomes the first letter.Remove all the vowels. So we have ‘CHNN’ now.Replace consonants with digits as follows (after the first letter)
Retain the first letter of the word as is — Soundex is based on the rationale that the English pronunciation depends on the first letter and pattern of the consonants. So, C becomes the first letter.
Remove all the vowels. So we have ‘CHNN’ now.
Replace consonants with digits as follows (after the first letter)
b, f, p, v → 1
c, g, j, k, q, s, x, z → 2
d, t → 3
l → 4
m, n → 5
r → 6
h, w, y→ unencoded/removed
After encoding the code becomes C55.
4. If two or more letters with the same number are adjacent in the original name (before step 1), only retain the first letter; also two letters with the same number separated by ‘h’ or ‘w’ are coded as a single number, whereas such letters separated by a vowel are coded twice. This rule also applies to the first letter. Now, we have two 5’s, so we will merge them into one and get C5.
5. If there are too few letters in our word that we can’t assign three numbers, append with zeros until there are three numbers. If we have four or more numbers, retain only the first three. Since we have one letter and only one number, we will append two zeroes at the end of the encoding to make it a four-character code. Hence, we get C500 as the final code for ‘Chennai’.
Thus, we see that the Soundex code for city names like ‘Bengaluru’ and ‘Bangalore’ is the same, B524, which is what we were aiming for.
So, we saw how to deal with different pronunciations of a particular word. Next, let us see how to deal with misspellings.
Simply put, an edit distance is the minimum number of edits required to convert one string to another, that is, given string to the target string.
Now, you must be wondering what is an edit. So, the possible edits are as follows:-
Insertion of a character into a given string. To convert the misspelled word ‘Aquire’ to its correct spelling ‘Acquire’, we need to insert the character ‘c’ in the given misspelled string.
Deletion of a character from a given string. To convert ‘neccessary’ to ‘necessary’, we need to delete the extra ‘c’ from the given string.
Substitution of a character in a given string. To convert ‘Absense’ to its correct form ‘Absence’, we need to substitute the character ‘s’ with the character ‘c’.
The most common edit distance algorithm is the Levenshtein edit distance which you can learn about, in detail, here. There is another edit option that you can do called the ‘transpose operation’, where you can swap the two adjacent characters of a given string. But, this operation is only available in the Damerau-Levenshtein edit distance.
A spelling corrector is a widely used application. If you have the autocorrect feature enabled on your phone, the incorrect spellings get replaced by the correct ones. Another example is when you use a search engine such as Google to search for anything and mistype a word, it suggests the correct word. Spell correction is an important part of lexical processing. In many applications, spell correction forms an initial preprocessing layer.
We saw how to calculate the edit distance between two words. Now, we will use the concept of edit distance to make a spelling corrector. We will now see how to make the famous Norvig spell corrector.
We need a large corpus of text with proper spelling. This corpus of text will also serve as a dictionary search for our spell corrector. Here, the large corpus of text ‘big.txt’ is nothing but a book. It’s the book ‘The Adventures of Sherlock Holmes’ present in text format at Project Gutenberg’s website.
# function to tokenise wordsdef words(document): “Convert text to lower case and tokenise the document” return re.findall(r’\w+’, document.lower())# create a frequency table of all the words of the documentall_words = Counter(words(open('big.txt').read()))
There are five main functions that we will use to find the correct spelling of a word and they are as follows:
edits_one(): function creates all the possible words that are one edit distance away from the input word. Most of the words that this function creates are garbage, i.e. they are not valid English words. For example, if we pass the word ‘laern’ (misspelling of the word ‘learn’) to edits_one(), it will create a list where the word ‘lgern’ will be present since it is an edit away from the word ‘laern’. But it’s not an English word. Only a subset of the words will be actual English words.
edits_one(): function creates all the possible words that are one edit distance away from the input word. Most of the words that this function creates are garbage, i.e. they are not valid English words. For example, if we pass the word ‘laern’ (misspelling of the word ‘learn’) to edits_one(), it will create a list where the word ‘lgern’ will be present since it is an edit away from the word ‘laern’. But it’s not an English word. Only a subset of the words will be actual English words.
def edits_one(word): “Create all edits that are one edit away from `word`.” alphabets = ‘abcdefghijklmnopqrstuvwxyz’ splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [left + right[1:] for left, right in splits if right] inserts = [left + c + right for left, right in splits for c in alphabets] replaces = [left + c + right[1:] for left, right in splits if right for c in alphabets] transposes = [left + right[1] + right[0] + right[2:] for left, right in splits if len(right)>1] return set(deletes + inserts + replaces + transposes)
2. edits_two(): function creates a list of all the possible words that are two edits away from the input word. Most of these words will also be garbage.
def edits_two(word): “Create all edits that are two edits away from `word`.” return (e2 for e1 in edits_one(word) for e2 in edits_one(e1))
3. known(): function filters out the valid English word from a list of given words. It uses the frequency distribution as a dictionary that was created using the seed document. If the words created using edits_one() and edits_two() are not in the dictionary, they’re discarded.
def known(words): “The subset of `words` that appear in the `all_words`.” return set(word for word in words if word in all_words)
4. possible_corrections(): This function takes the input word and uses the above three functions to return the correct spelling for a given input word. First, it checks for the spelling of the input word and if the spelling is correct, that is, if the word is present in the dictionary, it returns no spelling suggestions since it is already a correct dictionary word.
If the spelling is incorrect, it searches for every dictionary words that are one edit away from the input word and returns a list of them. If there are no dictionary words that are an edit away from the given word, then it searches for all dictionary words which are two edits away and returns a list of them. If there are no words that are two edits away, the input word is returned back, this means that there are no alternatives that the spell corrector could find.
def possible_corrections(word): “Generate possible spelling corrections for word.” return (known([word]) or known(edits_one(word)) or known(edits_two(word)) or [word])
5. prob(): The prob() function will create a probability associated with each of the suggested correct spellings and return the one with the highest probability, or we can say, it takes the suggested correct spellings and returns the one that is most frequent among the input words in our text corpus.
This is exactly why we need a large text corpus instead of a dictionary. A dictionary only contains a list of all correct English words. But, a text corpus not only contains all the correct words but it could also be used to create a frequency distribution of all these words.
def prob(word, N=sum(all_words.values())): “Probability of `word`: Number of appearances of ‘word’ / total number of tokens” return all_words[word] / N
Now, we’re almost done building the spell corrector. We just need to put all the pieces of the code together and wrap them up in a new function that uses all the functions created till now.
def spell_check(word): “Print the most probable spelling correction for `word` out of all the `possible_corrections`” correct_word = max(possible_corrections(word), key=prob) if correct_word != word: return “Did you mean “ + correct_word + “?” else: return “Correct spelling.”
Voila! We have successfully created a simple yet very effective spelling corrector. We can now use it to correct spellings on any given text corpus.
That’s it form part 3 folks. We have covered the whole of lexical processing in part 2 and part 3. Now, we will move onto the next major part of NLP — Syntactic Processing. Cheers! | [
{
"code": null,
"e": 352,
"s": 171,
"text": "In the previous part of the series ‘The NLP Project’, we learned all the basic lexical processing techniques such as removing stop words, tokenization, stemming, and lemmatization."
},
{
"code": null,
"e": 703,
"s": 352,
"text": "Even after going through all those preprocessing steps, a lot of noise is still present in the textual data. For example, spelling mistakes that happen by mistake as well as by choice (informal words such as ‘lol’, ‘u’, ‘gud’ etc.). Also, the problem of spelling variations of a word that occurs due to different pronunciations (e.g. Mumbai, Bombay)."
},
{
"code": null,
"e": 911,
"s": 703,
"text": "The two methods that we talked about in the last part — stemming and lemmatization — are both parts of a technique called canonicalization. Basically, canonicalization means reducing a word to its base form."
},
{
"code": null,
"e": 1316,
"s": 911,
"text": "There are scenarios where we can not canonicalize a word just by using stemming and lemmatization. Thus, we will need another technique to canonicalize the words correctly. For example, if the word ‘allowing’ is misspelled as ‘alowing’, then we will have a redundant token as ‘alow’ after stemming the misspelled word, and lemmatization wouldn’t even work as it only works on correct dictionary spelling."
},
{
"code": null,
"e": 1632,
"s": 1316,
"text": "The same problem is with the pronunciation of same words in different patois. For example, the word ‘humour’ used in British English, is spelled as ‘humor’ in American English. Both are correct spellings, but they will give two different base forms, after stemming, when used in the form ‘humouring’ and ‘humoring’."
},
{
"code": null,
"e": 1971,
"s": 1632,
"text": "There are some words that have different pronunciation in different languages. As a result, they are ultimately written differently. For example a common Indian surname like ‘Srivastava’ is also spelled as ‘Shrivastava’, ‘Shrivastav’, or ‘Srivastav’. Therefore, we must reduce all forms of a particular word to one single and common word."
},
{
"code": null,
"e": 2262,
"s": 1971,
"text": "To attain this, we will get to know about a technique is called phonetic hashing. The phonetic hashing method combines the same phonemes (smallest unit of sound) into one bucket and gives them the same hash code for all the variations. So, the words ‘color’ and ‘colour’ have the same code."
},
{
"code": null,
"e": 2416,
"s": 2262,
"text": "Phonetic hashing is a technique used to canocalize words that have different variants but same phonetic characteristics, that is, the same pronunciation."
},
{
"code": null,
"e": 2823,
"s": 2416,
"text": "Now, Soundexes are algorithms that can be used to calculate the hash code of a given word. Phonetic Hashing uses these Soundex algorithms. The algorithms differ from language to language. American Soundex is the most popular Soundex algorithm and we will be using that. Also, it doesn’t matter which language the input word comes from — as long as the words sound similar, they will get the same hash code."
},
{
"code": null,
"e": 2980,
"s": 2823,
"text": "Phonetic hashing is a four-character code. So, let us calculate the hash code(also known as Soundex) of the word ‘Chennai’ by applying the following steps:-"
},
{
"code": null,
"e": 3291,
"s": 2980,
"text": "Retain the first letter of the word as is — Soundex is based on the rationale that the English pronunciation depends on the first letter and pattern of the consonants. So, C becomes the first letter.Remove all the vowels. So we have ‘CHNN’ now.Replace consonants with digits as follows (after the first letter)"
},
{
"code": null,
"e": 3491,
"s": 3291,
"text": "Retain the first letter of the word as is — Soundex is based on the rationale that the English pronunciation depends on the first letter and pattern of the consonants. So, C becomes the first letter."
},
{
"code": null,
"e": 3537,
"s": 3491,
"text": "Remove all the vowels. So we have ‘CHNN’ now."
},
{
"code": null,
"e": 3604,
"s": 3537,
"text": "Replace consonants with digits as follows (after the first letter)"
},
{
"code": null,
"e": 3619,
"s": 3604,
"text": "b, f, p, v → 1"
},
{
"code": null,
"e": 3646,
"s": 3619,
"text": "c, g, j, k, q, s, x, z → 2"
},
{
"code": null,
"e": 3655,
"s": 3646,
"text": "d, t → 3"
},
{
"code": null,
"e": 3661,
"s": 3655,
"text": "l → 4"
},
{
"code": null,
"e": 3670,
"s": 3661,
"text": "m, n → 5"
},
{
"code": null,
"e": 3676,
"s": 3670,
"text": "r → 6"
},
{
"code": null,
"e": 3703,
"s": 3676,
"text": "h, w, y→ unencoded/removed"
},
{
"code": null,
"e": 3740,
"s": 3703,
"text": "After encoding the code becomes C55."
},
{
"code": null,
"e": 4128,
"s": 3740,
"text": "4. If two or more letters with the same number are adjacent in the original name (before step 1), only retain the first letter; also two letters with the same number separated by ‘h’ or ‘w’ are coded as a single number, whereas such letters separated by a vowel are coded twice. This rule also applies to the first letter. Now, we have two 5’s, so we will merge them into one and get C5."
},
{
"code": null,
"e": 4504,
"s": 4128,
"text": "5. If there are too few letters in our word that we can’t assign three numbers, append with zeros until there are three numbers. If we have four or more numbers, retain only the first three. Since we have one letter and only one number, we will append two zeroes at the end of the encoding to make it a four-character code. Hence, we get C500 as the final code for ‘Chennai’."
},
{
"code": null,
"e": 4640,
"s": 4504,
"text": "Thus, we see that the Soundex code for city names like ‘Bengaluru’ and ‘Bangalore’ is the same, B524, which is what we were aiming for."
},
{
"code": null,
"e": 4763,
"s": 4640,
"text": "So, we saw how to deal with different pronunciations of a particular word. Next, let us see how to deal with misspellings."
},
{
"code": null,
"e": 4910,
"s": 4763,
"text": "Simply put, an edit distance is the minimum number of edits required to convert one string to another, that is, given string to the target string."
},
{
"code": null,
"e": 4994,
"s": 4910,
"text": "Now, you must be wondering what is an edit. So, the possible edits are as follows:-"
},
{
"code": null,
"e": 5183,
"s": 4994,
"text": "Insertion of a character into a given string. To convert the misspelled word ‘Aquire’ to its correct spelling ‘Acquire’, we need to insert the character ‘c’ in the given misspelled string."
},
{
"code": null,
"e": 5323,
"s": 5183,
"text": "Deletion of a character from a given string. To convert ‘neccessary’ to ‘necessary’, we need to delete the extra ‘c’ from the given string."
},
{
"code": null,
"e": 5486,
"s": 5323,
"text": "Substitution of a character in a given string. To convert ‘Absense’ to its correct form ‘Absence’, we need to substitute the character ‘s’ with the character ‘c’."
},
{
"code": null,
"e": 5828,
"s": 5486,
"text": "The most common edit distance algorithm is the Levenshtein edit distance which you can learn about, in detail, here. There is another edit option that you can do called the ‘transpose operation’, where you can swap the two adjacent characters of a given string. But, this operation is only available in the Damerau-Levenshtein edit distance."
},
{
"code": null,
"e": 6270,
"s": 5828,
"text": "A spelling corrector is a widely used application. If you have the autocorrect feature enabled on your phone, the incorrect spellings get replaced by the correct ones. Another example is when you use a search engine such as Google to search for anything and mistype a word, it suggests the correct word. Spell correction is an important part of lexical processing. In many applications, spell correction forms an initial preprocessing layer."
},
{
"code": null,
"e": 6470,
"s": 6270,
"text": "We saw how to calculate the edit distance between two words. Now, we will use the concept of edit distance to make a spelling corrector. We will now see how to make the famous Norvig spell corrector."
},
{
"code": null,
"e": 6776,
"s": 6470,
"text": "We need a large corpus of text with proper spelling. This corpus of text will also serve as a dictionary search for our spell corrector. Here, the large corpus of text ‘big.txt’ is nothing but a book. It’s the book ‘The Adventures of Sherlock Holmes’ present in text format at Project Gutenberg’s website."
},
{
"code": null,
"e": 7033,
"s": 6776,
"text": "# function to tokenise wordsdef words(document): “Convert text to lower case and tokenise the document” return re.findall(r’\\w+’, document.lower())# create a frequency table of all the words of the documentall_words = Counter(words(open('big.txt').read()))"
},
{
"code": null,
"e": 7144,
"s": 7033,
"text": "There are five main functions that we will use to find the correct spelling of a word and they are as follows:"
},
{
"code": null,
"e": 7634,
"s": 7144,
"text": "edits_one(): function creates all the possible words that are one edit distance away from the input word. Most of the words that this function creates are garbage, i.e. they are not valid English words. For example, if we pass the word ‘laern’ (misspelling of the word ‘learn’) to edits_one(), it will create a list where the word ‘lgern’ will be present since it is an edit away from the word ‘laern’. But it’s not an English word. Only a subset of the words will be actual English words."
},
{
"code": null,
"e": 8124,
"s": 7634,
"text": "edits_one(): function creates all the possible words that are one edit distance away from the input word. Most of the words that this function creates are garbage, i.e. they are not valid English words. For example, if we pass the word ‘laern’ (misspelling of the word ‘learn’) to edits_one(), it will create a list where the word ‘lgern’ will be present since it is an edit away from the word ‘laern’. But it’s not an English word. Only a subset of the words will be actual English words."
},
{
"code": null,
"e": 8679,
"s": 8124,
"text": "def edits_one(word): “Create all edits that are one edit away from `word`.” alphabets = ‘abcdefghijklmnopqrstuvwxyz’ splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [left + right[1:] for left, right in splits if right] inserts = [left + c + right for left, right in splits for c in alphabets] replaces = [left + c + right[1:] for left, right in splits if right for c in alphabets] transposes = [left + right[1] + right[0] + right[2:] for left, right in splits if len(right)>1] return set(deletes + inserts + replaces + transposes)"
},
{
"code": null,
"e": 8832,
"s": 8679,
"text": "2. edits_two(): function creates a list of all the possible words that are two edits away from the input word. Most of these words will also be garbage."
},
{
"code": null,
"e": 8971,
"s": 8832,
"text": "def edits_two(word): “Create all edits that are two edits away from `word`.” return (e2 for e1 in edits_one(word) for e2 in edits_one(e1))"
},
{
"code": null,
"e": 9249,
"s": 8971,
"text": "3. known(): function filters out the valid English word from a list of given words. It uses the frequency distribution as a dictionary that was created using the seed document. If the words created using edits_one() and edits_two() are not in the dictionary, they’re discarded."
},
{
"code": null,
"e": 9379,
"s": 9249,
"text": "def known(words): “The subset of `words` that appear in the `all_words`.” return set(word for word in words if word in all_words)"
},
{
"code": null,
"e": 9748,
"s": 9379,
"text": "4. possible_corrections(): This function takes the input word and uses the above three functions to return the correct spelling for a given input word. First, it checks for the spelling of the input word and if the spelling is correct, that is, if the word is present in the dictionary, it returns no spelling suggestions since it is already a correct dictionary word."
},
{
"code": null,
"e": 10218,
"s": 9748,
"text": "If the spelling is incorrect, it searches for every dictionary words that are one edit away from the input word and returns a list of them. If there are no dictionary words that are an edit away from the given word, then it searches for all dictionary words which are two edits away and returns a list of them. If there are no words that are two edits away, the input word is returned back, this means that there are no alternatives that the spell corrector could find."
},
{
"code": null,
"e": 10386,
"s": 10218,
"text": "def possible_corrections(word): “Generate possible spelling corrections for word.” return (known([word]) or known(edits_one(word)) or known(edits_two(word)) or [word])"
},
{
"code": null,
"e": 10688,
"s": 10386,
"text": "5. prob(): The prob() function will create a probability associated with each of the suggested correct spellings and return the one with the highest probability, or we can say, it takes the suggested correct spellings and returns the one that is most frequent among the input words in our text corpus."
},
{
"code": null,
"e": 10965,
"s": 10688,
"text": "This is exactly why we need a large text corpus instead of a dictionary. A dictionary only contains a list of all correct English words. But, a text corpus not only contains all the correct words but it could also be used to create a frequency distribution of all these words."
},
{
"code": null,
"e": 11118,
"s": 10965,
"text": "def prob(word, N=sum(all_words.values())): “Probability of `word`: Number of appearances of ‘word’ / total number of tokens” return all_words[word] / N"
},
{
"code": null,
"e": 11308,
"s": 11118,
"text": "Now, we’re almost done building the spell corrector. We just need to put all the pieces of the code together and wrap them up in a new function that uses all the functions created till now."
},
{
"code": null,
"e": 11585,
"s": 11308,
"text": "def spell_check(word): “Print the most probable spelling correction for `word` out of all the `possible_corrections`” correct_word = max(possible_corrections(word), key=prob) if correct_word != word: return “Did you mean “ + correct_word + “?” else: return “Correct spelling.”"
},
{
"code": null,
"e": 11734,
"s": 11585,
"text": "Voila! We have successfully created a simple yet very effective spelling corrector. We can now use it to correct spellings on any given text corpus."
}
]
|
Python - Tkinter Frame | The Frame widget is very important for the process of grouping and organizing other widgets in a somehow friendly way. It works like a container, which is responsible for arranging the position of other widgets.
It uses rectangular areas in the screen to organize the layout and to provide padding of these widgets. A frame can also be used as a foundation class to implement complex widgets.
Here is the simple syntax to create this widget −
w = Frame ( master, option, ... )
master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
bg
The normal background color displayed behind the label and indicator.
bd
The size of the border around the indicator. Default is 2 pixels.
cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton.
height
The vertical dimension of the new frame.
highlightbackground
Color of the focus highlight when the frame does not have focus.
highlightcolor
Color shown in the focus highlight when the frame has the focus.
highlightthickness
Thickness of the focus highlight.
relief
With the default value, relief=FLAT, the checkbutton does not stand out from its background. You may set this option to any of the other styles
width
The default width of a checkbutton is determined by the size of the displayed image or text. You can set this option to a number of characters and the checkbutton will always have room for that many characters.
Try the following example yourself −
from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text="Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)
root.mainloop()
When the above code is executed, it produces the following result −
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2456,
"s": 2244,
"text": "The Frame widget is very important for the process of grouping and organizing other widgets in a somehow friendly way. It works like a container, which is responsible for arranging the position of other widgets."
},
{
"code": null,
"e": 2637,
"s": 2456,
"text": "It uses rectangular areas in the screen to organize the layout and to provide padding of these widgets. A frame can also be used as a foundation class to implement complex widgets."
},
{
"code": null,
"e": 2687,
"s": 2637,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2722,
"s": 2687,
"text": "w = Frame ( master, option, ... )\n"
},
{
"code": null,
"e": 2766,
"s": 2722,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2810,
"s": 2766,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2950,
"s": 2810,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3090,
"s": 2950,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 3093,
"s": 3090,
"text": "bg"
},
{
"code": null,
"e": 3163,
"s": 3093,
"text": "The normal background color displayed behind the label and indicator."
},
{
"code": null,
"e": 3166,
"s": 3163,
"text": "bd"
},
{
"code": null,
"e": 3232,
"s": 3166,
"text": "The size of the border around the indicator. Default is 2 pixels."
},
{
"code": null,
"e": 3239,
"s": 3232,
"text": "cursor"
},
{
"code": null,
"e": 3376,
"s": 3239,
"text": "If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton."
},
{
"code": null,
"e": 3383,
"s": 3376,
"text": "height"
},
{
"code": null,
"e": 3425,
"s": 3383,
"text": "The vertical dimension of the new frame. "
},
{
"code": null,
"e": 3445,
"s": 3425,
"text": "highlightbackground"
},
{
"code": null,
"e": 3510,
"s": 3445,
"text": "Color of the focus highlight when the frame does not have focus."
},
{
"code": null,
"e": 3525,
"s": 3510,
"text": "highlightcolor"
},
{
"code": null,
"e": 3590,
"s": 3525,
"text": "Color shown in the focus highlight when the frame has the focus."
},
{
"code": null,
"e": 3609,
"s": 3590,
"text": "highlightthickness"
},
{
"code": null,
"e": 3643,
"s": 3609,
"text": "Thickness of the focus highlight."
},
{
"code": null,
"e": 3650,
"s": 3643,
"text": "relief"
},
{
"code": null,
"e": 3794,
"s": 3650,
"text": "With the default value, relief=FLAT, the checkbutton does not stand out from its background. You may set this option to any of the other styles"
},
{
"code": null,
"e": 3800,
"s": 3794,
"text": "width"
},
{
"code": null,
"e": 4011,
"s": 3800,
"text": "The default width of a checkbutton is determined by the size of the displayed image or text. You can set this option to a number of characters and the checkbutton will always have room for that many characters."
},
{
"code": null,
"e": 4048,
"s": 4011,
"text": "Try the following example yourself −"
},
{
"code": null,
"e": 4536,
"s": 4048,
"text": "from Tkinter import *\n\nroot = Tk()\nframe = Frame(root)\nframe.pack()\n\nbottomframe = Frame(root)\nbottomframe.pack( side = BOTTOM )\n\nredbutton = Button(frame, text=\"Red\", fg=\"red\")\nredbutton.pack( side = LEFT)\n\ngreenbutton = Button(frame, text=\"Brown\", fg=\"brown\")\ngreenbutton.pack( side = LEFT )\n\nbluebutton = Button(frame, text=\"Blue\", fg=\"blue\")\nbluebutton.pack( side = LEFT )\n\nblackbutton = Button(bottomframe, text=\"Black\", fg=\"black\")\nblackbutton.pack( side = BOTTOM)\n\nroot.mainloop()"
},
{
"code": null,
"e": 4605,
"s": 4536,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4642,
"s": 4605,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4658,
"s": 4642,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4691,
"s": 4658,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4710,
"s": 4691,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4745,
"s": 4710,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4767,
"s": 4745,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4801,
"s": 4767,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4829,
"s": 4801,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4864,
"s": 4829,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4878,
"s": 4864,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4911,
"s": 4878,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4928,
"s": 4911,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4935,
"s": 4928,
"text": " Print"
},
{
"code": null,
"e": 4946,
"s": 4935,
"text": " Add Notes"
}
]
|
File opening modes(r versus r+) in C++ | File handling in programming languages is very important for the interaction of programming with the memory for accessing files and fetching data in it.
Using a program, you can read data from a file as well as write data to the file and do a lot more functions.
Here, we will see reading of data from a file.
In programming, before performing any operation you need to open the file. And there are multiple modes to open a file in the programming language. The access to the file is based on the mode it is opened with.
Here we will learn about the difference between two modes of opening file for reading files, these are r and r+.
Both are used for reading files in the program.
Syntax for opening a file :
FILE *fp;
fp = fopen( “filename.fileextension” , “mode” )
r mode for opening a file:
The r mode for opening file, opens files for reading only. If the file does not exist NULL character is returned.
Program to illustrate the opening of file:
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
FILE* readFile;
char ch;
readFile = fopen("file.txt", "r");
while (1) {
ch = fgetc(readFile);
if (ch == EOF)
break;
cout<<ch;
}
fclose(readFile);
}
Tutorials Point
r+ mode for opening a file:
The r+ mode for opening a file is similar to r mode but has some added features. It opens the file in both read and write mode. If the file does not exist with w+, the program creates new files to work on it.
Program to illustrate the opening of file in r+ mode:
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
FILE* readFile;
char ch;
readFile = fopen("file.txt", "r+");
while (1) {
ch = fgetc(readFile);
if (ch == EOF)
break;
cout<<ch;
}
fclose(readFile);
}
Tutorials Point | [
{
"code": null,
"e": 1215,
"s": 1062,
"text": "File handling in programming languages is very important for the interaction of programming with the memory for accessing files and fetching data in it."
},
{
"code": null,
"e": 1325,
"s": 1215,
"text": "Using a program, you can read data from a file as well as write data to the file and do a lot more functions."
},
{
"code": null,
"e": 1372,
"s": 1325,
"text": "Here, we will see reading of data from a file."
},
{
"code": null,
"e": 1583,
"s": 1372,
"text": "In programming, before performing any operation you need to open the file. And there are multiple modes to open a file in the programming language. The access to the file is based on the mode it is opened with."
},
{
"code": null,
"e": 1696,
"s": 1583,
"text": "Here we will learn about the difference between two modes of opening file for reading files, these are r and r+."
},
{
"code": null,
"e": 1744,
"s": 1696,
"text": "Both are used for reading files in the program."
},
{
"code": null,
"e": 1773,
"s": 1744,
"text": "Syntax for opening a file : "
},
{
"code": null,
"e": 1793,
"s": 1773,
"text": " FILE *fp;"
},
{
"code": null,
"e": 1851,
"s": 1793,
"text": " fp = fopen( “filename.fileextension” , “mode” )"
},
{
"code": null,
"e": 1879,
"s": 1851,
"text": "r mode for opening a file: "
},
{
"code": null,
"e": 1993,
"s": 1879,
"text": "The r mode for opening file, opens files for reading only. If the file does not exist NULL character is returned."
},
{
"code": null,
"e": 2036,
"s": 1993,
"text": "Program to illustrate the opening of file:"
},
{
"code": null,
"e": 2308,
"s": 2036,
"text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nint main() {\n \n FILE* readFile;\n char ch;\n readFile = fopen(\"file.txt\", \"r\");\n while (1) {\n ch = fgetc(readFile);\n if (ch == EOF)\n break;\n cout<<ch;\n }\n fclose(readFile);\n}\n"
},
{
"code": null,
"e": 2324,
"s": 2308,
"text": "Tutorials Point"
},
{
"code": null,
"e": 2352,
"s": 2324,
"text": "r+ mode for opening a file:"
},
{
"code": null,
"e": 2561,
"s": 2352,
"text": "The r+ mode for opening a file is similar to r mode but has some added features. It opens the file in both read and write mode. If the file does not exist with w+, the program creates new files to work on it."
},
{
"code": null,
"e": 2615,
"s": 2561,
"text": "Program to illustrate the opening of file in r+ mode:"
},
{
"code": null,
"e": 2887,
"s": 2615,
"text": "#include <stdio.h>\n#include <iostream>\nusing namespace std;\n\nint main() {\n \n FILE* readFile;\n char ch;\n readFile = fopen(\"file.txt\", \"r+\");\n while (1) {\n ch = fgetc(readFile);\n if (ch == EOF)\n break;\n cout<<ch;\n }\n fclose(readFile);\n}"
},
{
"code": null,
"e": 2903,
"s": 2887,
"text": "Tutorials Point"
}
]
|
Tryit Editor v3.7 | Tryit: HTML table - border bottom | []
|
How to check if a document is ready in JavaScript? | Following is the code to check if a document is ready in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Check if a document is ready</h1>
<div class="result"></div>
<button class="Btn">Check</button>
<h3>Click on the above button to see document state</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
resEle.innerHTML = document.readyState + "<br><br>";
BtnEle.addEventListener("click", () => {
if (document.readyState === "complete") {
resEle.innerHTML = "The page has finished loading completely";
} else {
resEle.innerHTML = "The page is still loading";
}
});
</script>
</body>
</html>
On clicking the ‘Check’ button − | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "Following is the code to check if a document is ready in JavaScript −"
},
{
"code": null,
"e": 1143,
"s": 1132,
"text": " Live Demo"
},
{
"code": null,
"e": 2108,
"s": 1143,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Check if a document is ready</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">Check</button>\n<h3>Click on the above button to see document state</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n resEle.innerHTML = document.readyState + \"<br><br>\";\n BtnEle.addEventListener(\"click\", () => {\n if (document.readyState === \"complete\") {\n resEle.innerHTML = \"The page has finished loading completely\";\n } else {\n resEle.innerHTML = \"The page is still loading\";\n }\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2141,
"s": 2108,
"text": "On clicking the ‘Check’ button −"
}
]
|
Arduino - Passing Arrays to Functions | To pass an array argument to a function, specify the name of the array without any brackets. For example, if an array hourlyTemperatures has been declared as the function, the call passes array hourlyTemperatures and its size to function modifyArray.
Here is a list of some important points that you need to know while passing arrays to functions −
When passing an array to a function, normally the array size is passed as well, so the function can process the specific number of elements in the array. Otherwise, we would need to build this knowledge into the called function itself or, worse yet, place the array size in a global variable.
When passing an array to a function, normally the array size is passed as well, so the function can process the specific number of elements in the array. Otherwise, we would need to build this knowledge into the called function itself or, worse yet, place the array size in a global variable.
C++ passes arrays to functions by reference i.e. the called functions can modify the element values in the callers’ original arrays.
C++ passes arrays to functions by reference i.e. the called functions can modify the element values in the callers’ original arrays.
The value of the name of the array is the address in the computer’s memory of the first element of the array. Since the starting address of the array is passed, the called function knows precisely where the array is stored in the memory. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory locations.
The value of the name of the array is the address in the computer’s memory of the first element of the array. Since the starting address of the array is passed, the called function knows precisely where the array is stored in the memory. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory locations.
Although the entire arrays are passed by reference, individual array elements are passed by value exactly as simple variables are.
Although the entire arrays are passed by reference, individual array elements are passed by value exactly as simple variables are.
To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call.
To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call.
For a function to receive an array through a function call, the function’s parameter list must specify that the function expects to receive an array.
For a function to receive an array through a function call, the function’s parameter list must specify that the function expects to receive an array.
For example, the function header for function modifyArray might be written as −
For example, the function header for function modifyArray might be written as −
void modifyArray( int b[], int arraySize )
The statement indicates that modifyArray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraySize. The array’s size is not required in the array brackets. If it is included, the compiler ignores it; thus, arrays of any size can be passed to the function.
The statement indicates that modifyArray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraySize. The array’s size is not required in the array brackets. If it is included, the compiler ignores it; thus, arrays of any size can be passed to the function.
C++ passes arrays to the functions by reference. When the called function uses the array name b, it refers to the actual array in the caller (i.e., arrayhourlyTemperatures discussed at the beginning of this section).
C++ passes arrays to the functions by reference. When the called function uses the array name b, it refers to the actual array in the caller (i.e., arrayhourlyTemperatures discussed at the beginning of this section).
Note the strange appearance of the function prototype for modifyArray.
void modifyArray( int [] , int ) ;
This prototype could have been written in the following way for documentation purposes.
void modifyArray( int anyArrayName[], int anyVariableName ) ;
However, C++ compilers ignore variable names in prototypes. Remember, the prototype tells the compiler the number of arguments and the type of each argument in the order in which the arguments are expected to appear.
The program in the next example demonstrates the difference between passing an entire array and passing an array element.
void modifyArray( int [], int ); // appears strange; array and size
void modifyElement( int ); // receive array element value
void setup () {
Serial.begin (9600);
const int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize array a
Serial.print ( "Effects of passing entire array by reference:" ) ;
// output original array elements
for ( int i = 0; i < arraySize ; ++i )
Serial.print ( a[ i ] ) ;
Serial.print ("\r" ) ;
Serial.print ("The values of the modified array are:\n" );
// output modified array elements
for ( int j = 0; j < arraySize; ++j )
Serial.print ( a[j ] ) ;
Serial.print ("\r" ) ;
Serial.print ("\r\rEffects of passing array element by value:" );
Serial.print ( "\ra[3] before modifyElement: " );
Serial.print ( a[ 3 ] );
Serial.print ( "\ra[3] after modifyElement: " );
Serial.print ( a[ 3 ] );
}
void loop () {
}
// in function modifyArray, "b" points to the original array "a" in memory
void modifyArray( int b[], int sizeOfArray ) {
// multiply each array element by 2
for ( int k = 0 ; k < sizeOfArray ; ++k )
b[ k ] *= 2;
}
// end function modifyArray
// in function modifyElement, "e" is a local copy of
// array element a[ 3 ] passed from main
void modifyElement( int e ) {
// multiply parameter by 2
Serial.print ( "Value of element in modifyElement: " );
Serial.print ( ( e *= 2 ) );
}
// end function modifyElement
Effects of passing entire array by reference:01234
The values of the modified array are:01234
Effects of passing array element by value:
a[3] before modifyElement: 3
a[3] after modifyElement: 3
$ is not a hexadecimal digit
f is a hexadecimal digit
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3121,
"s": 2870,
"text": "To pass an array argument to a function, specify the name of the array without any brackets. For example, if an array hourlyTemperatures has been declared as the function, the call passes array hourlyTemperatures and its size to function modifyArray."
},
{
"code": null,
"e": 3219,
"s": 3121,
"text": "Here is a list of some important points that you need to know while passing arrays to functions −"
},
{
"code": null,
"e": 3512,
"s": 3219,
"text": "When passing an array to a function, normally the array size is passed as well, so the function can process the specific number of elements in the array. Otherwise, we would need to build this knowledge into the called function itself or, worse yet, place the array size in a global variable."
},
{
"code": null,
"e": 3805,
"s": 3512,
"text": "When passing an array to a function, normally the array size is passed as well, so the function can process the specific number of elements in the array. Otherwise, we would need to build this knowledge into the called function itself or, worse yet, place the array size in a global variable."
},
{
"code": null,
"e": 3938,
"s": 3805,
"text": "C++ passes arrays to functions by reference i.e. the called functions can modify the element values in the callers’ original arrays."
},
{
"code": null,
"e": 4071,
"s": 3938,
"text": "C++ passes arrays to functions by reference i.e. the called functions can modify the element values in the callers’ original arrays."
},
{
"code": null,
"e": 4476,
"s": 4071,
"text": "The value of the name of the array is the address in the computer’s memory of the first element of the array. Since the starting address of the array is passed, the called function knows precisely where the array is stored in the memory. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory locations."
},
{
"code": null,
"e": 4881,
"s": 4476,
"text": "The value of the name of the array is the address in the computer’s memory of the first element of the array. Since the starting address of the array is passed, the called function knows precisely where the array is stored in the memory. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory locations."
},
{
"code": null,
"e": 5012,
"s": 4881,
"text": "Although the entire arrays are passed by reference, individual array elements are passed by value exactly as simple variables are."
},
{
"code": null,
"e": 5143,
"s": 5012,
"text": "Although the entire arrays are passed by reference, individual array elements are passed by value exactly as simple variables are."
},
{
"code": null,
"e": 5272,
"s": 5143,
"text": "To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call."
},
{
"code": null,
"e": 5401,
"s": 5272,
"text": "To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call."
},
{
"code": null,
"e": 5551,
"s": 5401,
"text": "For a function to receive an array through a function call, the function’s parameter list must specify that the function expects to receive an array."
},
{
"code": null,
"e": 5701,
"s": 5551,
"text": "For a function to receive an array through a function call, the function’s parameter list must specify that the function expects to receive an array."
},
{
"code": null,
"e": 5781,
"s": 5701,
"text": "For example, the function header for function modifyArray might be written as −"
},
{
"code": null,
"e": 5861,
"s": 5781,
"text": "For example, the function header for function modifyArray might be written as −"
},
{
"code": null,
"e": 5905,
"s": 5861,
"text": "void modifyArray( int b[], int arraySize )\n"
},
{
"code": null,
"e": 6229,
"s": 5905,
"text": "The statement indicates that modifyArray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraySize. The array’s size is not required in the array brackets. If it is included, the compiler ignores it; thus, arrays of any size can be passed to the function."
},
{
"code": null,
"e": 6553,
"s": 6229,
"text": "The statement indicates that modifyArray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraySize. The array’s size is not required in the array brackets. If it is included, the compiler ignores it; thus, arrays of any size can be passed to the function."
},
{
"code": null,
"e": 6770,
"s": 6553,
"text": "C++ passes arrays to the functions by reference. When the called function uses the array name b, it refers to the actual array in the caller (i.e., arrayhourlyTemperatures discussed at the beginning of this section)."
},
{
"code": null,
"e": 6987,
"s": 6770,
"text": "C++ passes arrays to the functions by reference. When the called function uses the array name b, it refers to the actual array in the caller (i.e., arrayhourlyTemperatures discussed at the beginning of this section)."
},
{
"code": null,
"e": 7058,
"s": 6987,
"text": "Note the strange appearance of the function prototype for modifyArray."
},
{
"code": null,
"e": 7094,
"s": 7058,
"text": "void modifyArray( int [] , int ) ;\n"
},
{
"code": null,
"e": 7182,
"s": 7094,
"text": "This prototype could have been written in the following way for documentation purposes."
},
{
"code": null,
"e": 7245,
"s": 7182,
"text": "void modifyArray( int anyArrayName[], int anyVariableName ) ;\n"
},
{
"code": null,
"e": 7462,
"s": 7245,
"text": "However, C++ compilers ignore variable names in prototypes. Remember, the prototype tells the compiler the number of arguments and the type of each argument in the order in which the arguments are expected to appear."
},
{
"code": null,
"e": 7584,
"s": 7462,
"text": "The program in the next example demonstrates the difference between passing an entire array and passing an array element."
},
{
"code": null,
"e": 9048,
"s": 7584,
"text": "void modifyArray( int [], int ); // appears strange; array and size\nvoid modifyElement( int ); // receive array element value\n\nvoid setup () {\n Serial.begin (9600);\n const int arraySize = 5; // size of array a\n int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize array a\n Serial.print ( \"Effects of passing entire array by reference:\" ) ;\n // output original array elements\n for ( int i = 0; i < arraySize ; ++i )\n Serial.print ( a[ i ] ) ;\n Serial.print (\"\\r\" ) ;\n Serial.print (\"The values of the modified array are:\\n\" );\n // output modified array elements\n for ( int j = 0; j < arraySize; ++j )\n Serial.print ( a[j ] ) ;\n Serial.print (\"\\r\" ) ;\n Serial.print (\"\\r\\rEffects of passing array element by value:\" );\n Serial.print ( \"\\ra[3] before modifyElement: \" );\n Serial.print ( a[ 3 ] );\n Serial.print ( \"\\ra[3] after modifyElement: \" );\n Serial.print ( a[ 3 ] );\n}\n\nvoid loop () {\n\n}\n\n// in function modifyArray, \"b\" points to the original array \"a\" in memory\n\nvoid modifyArray( int b[], int sizeOfArray ) {\n // multiply each array element by 2\n for ( int k = 0 ; k < sizeOfArray ; ++k )\n b[ k ] *= 2;\n} \n\n// end function modifyArray\n// in function modifyElement, \"e\" is a local copy of\n// array element a[ 3 ] passed from main\n\nvoid modifyElement( int e ) {\n // multiply parameter by 2\n Serial.print ( \"Value of element in modifyElement: \" );\n Serial.print ( ( e *= 2 ) );\n} \n\n// end function modifyElement"
},
{
"code": null,
"e": 9298,
"s": 9048,
"text": "Effects of passing entire array by reference:01234\nThe values of the modified array are:01234\n\nEffects of passing array element by value:\na[3] before modifyElement: 3\na[3] after modifyElement: 3\n$ is not a hexadecimal digit\nf is a hexadecimal digit\n"
},
{
"code": null,
"e": 9333,
"s": 9298,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 9344,
"s": 9333,
"text": " Amit Rana"
},
{
"code": null,
"e": 9377,
"s": 9344,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9388,
"s": 9377,
"text": " Amit Rana"
},
{
"code": null,
"e": 9421,
"s": 9388,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9434,
"s": 9421,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9469,
"s": 9434,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9482,
"s": 9469,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9514,
"s": 9482,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 9527,
"s": 9514,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9558,
"s": 9527,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 9571,
"s": 9558,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9578,
"s": 9571,
"text": " Print"
},
{
"code": null,
"e": 9589,
"s": 9578,
"text": " Add Notes"
}
]
|
File Handling in Java - GeeksforGeeks | 03 Jan, 2022
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.
Why File Handling is Required?
File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.
Java
// Importing File Classimport java.io.File; class GFG { public static void main(String[] args) { // File name specified File obj = new File("myfile.txt"); System.out.println("File Created!"); }}
Output
File Created!
In Java, the concept Stream is used in order to perform I/O operations on a file. So at first, let us get acquainted with a concept known as Stream in Java.
In Java, a sequence of data is known as a stream.
This concept is used to perform I/O operations on a file.
There are two types of streams :
The Java InputStream class is the superclass of all input streams. The input stream is used to read data from numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful by itself. However, its subclasses are used to read data.
There are several subclasses of the InputStream class, which are as follows:
AudioInputStreamByteArrayInputStreamFileInputStreamFilterInputStreamStringBufferInputStreamObjectInputStream
AudioInputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
StringBufferInputStream
ObjectInputStream
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using FileInputStream.
Note: We can create an input stream from other subclasses as well as InputStream.
The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not useful by itself. However, its subclasses are used to write data.
There are several subclasses of the OutputStream class which are as follows:
ByteArrayOutputStreamFileOutputStreamStringBufferOutputStreamObjectOutputStreamDataOutputStreamPrintStream
ByteArrayOutputStream
FileOutputStream
StringBufferOutputStream
ObjectOutputStream
DataOutputStream
PrintStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using FileOutputStream.
Note: We can create an output stream from other subclasses as well as OutputStream.
Based on the data type, there are two types of streams :
This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:
Byte Input Stream: Used to read byte data from different devices.
Byte Output Stream: Used to write byte data to different devices.
This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:
Character Input Stream: Used to read character data from different devices.
Character Output Stream: Used to write character data to different devices.
Owing to the fact that you know what a stream is, let’s polish up File Handling in Java by further understanding the various methods that are useful for performing operations on the files like creating, reading, and writing files.
The following table depicts several File Class methods:
Let us now get acquainted with the various file operations in Java.
The following are the several operations that can be performed on a file in Java :
Create a File
Read from a File
Write to a File
Delete a File
Now let us study each of the above operations in detail.
1. Create a File
In order to create a file in Java, you can use the createNewFile() method.
If the file is successfully created, it will return a Boolean value true and false if the file already exists.
Following is a demonstration of how to create a file in Java :
Java
// Import the File classimport java.io.File; // Import the IOException class to handle errorsimport java.io.IOException; public class GFG { public static void main(String[] args) { try { File Obj = new File("myfile.txt"); if (Obj.createNewFile()) { System.out.println("File created: " + Obj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error has occurred."); e.printStackTrace(); } }}
Output
An error has occurred.
2. Read from a File: We will use the Scanner class in order to read contents from a file. Following is a demonstration of how to read contents from a file in Java :
Java
// Import the File classimport java.io.File; // Import this class for handling errorsimport java.io.FileNotFoundException; // Import the Scanner class to read content from text filesimport java.util.Scanner; public class GFG { public static void main(String[] args) { try { File Obj = new File("myfile.txt"); Scanner Reader = new Scanner(Obj); while (Reader.hasNextLine()) { String data = Reader.nextLine(); System.out.println(data); } Reader.close(); } catch (FileNotFoundException e) { System.out.println("An error has occurred."); e.printStackTrace(); } }}
Output
An error has occurred.
3. Write to a File: We use the FileWriter class along with its write() method in order to write some text to the file. Following is a demonstration of how to write text to a file in Java :
Java
// Import the FileWriter classimport java.io.FileWriter; // Import the IOException class for handling errorsimport java.io.IOException; public class GFG { public static void main(String[] args) { try { FileWriter Writer = new FileWriter("myfile.txt"); Writer.write( "Files in Java are seriously good!!"); Writer.close(); System.out.println("Successfully written."); } catch (IOException e) { System.out.println("An error has occurred."); e.printStackTrace(); } }}
Output
An error has occurred.
4. Delete a File: We use the delete() method in order to delete a file. Following is a demonstration of how to delete a file in Java :
Java
// Import the File classimport java.io.File; public class GFG { public static void main(String[] args) { File Obj = new File("myfile.txt"); if (Obj.delete()) { System.out.println("The deleted file is : " + myObj.getName()); } else { System.out.println( "Failed in deleting the file."); } }}
Output
Failed in deleting the file.
java-file-handling
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java | [
{
"code": null,
"e": 23972,
"s": 23944,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 24185,
"s": 23972,
"text": "In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file."
},
{
"code": null,
"e": 24216,
"s": 24185,
"text": "Why File Handling is Required?"
},
{
"code": null,
"e": 24413,
"s": 24216,
"text": "File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it."
},
{
"code": null,
"e": 24486,
"s": 24413,
"text": "In simple words, file handling means reading and writing data to a file."
},
{
"code": null,
"e": 24491,
"s": 24486,
"text": "Java"
},
{
"code": "// Importing File Classimport java.io.File; class GFG { public static void main(String[] args) { // File name specified File obj = new File(\"myfile.txt\"); System.out.println(\"File Created!\"); }}",
"e": 24721,
"s": 24491,
"text": null
},
{
"code": null,
"e": 24728,
"s": 24721,
"text": "Output"
},
{
"code": null,
"e": 24742,
"s": 24728,
"text": "File Created!"
},
{
"code": null,
"e": 24899,
"s": 24742,
"text": "In Java, the concept Stream is used in order to perform I/O operations on a file. So at first, let us get acquainted with a concept known as Stream in Java."
},
{
"code": null,
"e": 24949,
"s": 24899,
"text": "In Java, a sequence of data is known as a stream."
},
{
"code": null,
"e": 25007,
"s": 24949,
"text": "This concept is used to perform I/O operations on a file."
},
{
"code": null,
"e": 25040,
"s": 25007,
"text": "There are two types of streams :"
},
{
"code": null,
"e": 25336,
"s": 25040,
"text": "The Java InputStream class is the superclass of all input streams. The input stream is used to read data from numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful by itself. However, its subclasses are used to read data."
},
{
"code": null,
"e": 25413,
"s": 25336,
"text": "There are several subclasses of the InputStream class, which are as follows:"
},
{
"code": null,
"e": 25522,
"s": 25413,
"text": "AudioInputStreamByteArrayInputStreamFileInputStreamFilterInputStreamStringBufferInputStreamObjectInputStream"
},
{
"code": null,
"e": 25539,
"s": 25522,
"text": "AudioInputStream"
},
{
"code": null,
"e": 25560,
"s": 25539,
"text": "ByteArrayInputStream"
},
{
"code": null,
"e": 25576,
"s": 25560,
"text": "FileInputStream"
},
{
"code": null,
"e": 25594,
"s": 25576,
"text": "FilterInputStream"
},
{
"code": null,
"e": 25618,
"s": 25594,
"text": "StringBufferInputStream"
},
{
"code": null,
"e": 25636,
"s": 25618,
"text": "ObjectInputStream"
},
{
"code": null,
"e": 25704,
"s": 25636,
"text": "// Creating an InputStream\nInputStream obj = new FileInputStream();"
},
{
"code": null,
"e": 25761,
"s": 25704,
"text": "Here, an input stream is created using FileInputStream. "
},
{
"code": null,
"e": 25843,
"s": 25761,
"text": "Note: We can create an input stream from other subclasses as well as InputStream."
},
{
"code": null,
"e": 26143,
"s": 25843,
"text": "The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not useful by itself. However, its subclasses are used to write data."
},
{
"code": null,
"e": 26220,
"s": 26143,
"text": "There are several subclasses of the OutputStream class which are as follows:"
},
{
"code": null,
"e": 26327,
"s": 26220,
"text": "ByteArrayOutputStreamFileOutputStreamStringBufferOutputStreamObjectOutputStreamDataOutputStreamPrintStream"
},
{
"code": null,
"e": 26349,
"s": 26327,
"text": "ByteArrayOutputStream"
},
{
"code": null,
"e": 26366,
"s": 26349,
"text": "FileOutputStream"
},
{
"code": null,
"e": 26391,
"s": 26366,
"text": "StringBufferOutputStream"
},
{
"code": null,
"e": 26410,
"s": 26391,
"text": "ObjectOutputStream"
},
{
"code": null,
"e": 26427,
"s": 26410,
"text": "DataOutputStream"
},
{
"code": null,
"e": 26439,
"s": 26427,
"text": "PrintStream"
},
{
"code": null,
"e": 26510,
"s": 26439,
"text": "// Creating an OutputStream\nOutputStream obj = new FileOutputStream();"
},
{
"code": null,
"e": 26568,
"s": 26510,
"text": "Here, an output stream is created using FileOutputStream."
},
{
"code": null,
"e": 26652,
"s": 26568,
"text": "Note: We can create an output stream from other subclasses as well as OutputStream."
},
{
"code": null,
"e": 26709,
"s": 26652,
"text": "Based on the data type, there are two types of streams :"
},
{
"code": null,
"e": 26830,
"s": 26709,
"text": "This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:"
},
{
"code": null,
"e": 26896,
"s": 26830,
"text": "Byte Input Stream: Used to read byte data from different devices."
},
{
"code": null,
"e": 26962,
"s": 26896,
"text": "Byte Output Stream: Used to write byte data to different devices."
},
{
"code": null,
"e": 27087,
"s": 26962,
"text": "This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:"
},
{
"code": null,
"e": 27163,
"s": 27087,
"text": "Character Input Stream: Used to read character data from different devices."
},
{
"code": null,
"e": 27239,
"s": 27163,
"text": "Character Output Stream: Used to write character data to different devices."
},
{
"code": null,
"e": 27470,
"s": 27239,
"text": "Owing to the fact that you know what a stream is, let’s polish up File Handling in Java by further understanding the various methods that are useful for performing operations on the files like creating, reading, and writing files."
},
{
"code": null,
"e": 27526,
"s": 27470,
"text": "The following table depicts several File Class methods:"
},
{
"code": null,
"e": 27594,
"s": 27526,
"text": "Let us now get acquainted with the various file operations in Java."
},
{
"code": null,
"e": 27677,
"s": 27594,
"text": "The following are the several operations that can be performed on a file in Java :"
},
{
"code": null,
"e": 27691,
"s": 27677,
"text": "Create a File"
},
{
"code": null,
"e": 27708,
"s": 27691,
"text": "Read from a File"
},
{
"code": null,
"e": 27724,
"s": 27708,
"text": "Write to a File"
},
{
"code": null,
"e": 27738,
"s": 27724,
"text": "Delete a File"
},
{
"code": null,
"e": 27795,
"s": 27738,
"text": "Now let us study each of the above operations in detail."
},
{
"code": null,
"e": 27812,
"s": 27795,
"text": "1. Create a File"
},
{
"code": null,
"e": 27887,
"s": 27812,
"text": "In order to create a file in Java, you can use the createNewFile() method."
},
{
"code": null,
"e": 27998,
"s": 27887,
"text": "If the file is successfully created, it will return a Boolean value true and false if the file already exists."
},
{
"code": null,
"e": 28061,
"s": 27998,
"text": "Following is a demonstration of how to create a file in Java :"
},
{
"code": null,
"e": 28066,
"s": 28061,
"text": "Java"
},
{
"code": "// Import the File classimport java.io.File; // Import the IOException class to handle errorsimport java.io.IOException; public class GFG { public static void main(String[] args) { try { File Obj = new File(\"myfile.txt\"); if (Obj.createNewFile()) { System.out.println(\"File created: \" + Obj.getName()); } else { System.out.println(\"File already exists.\"); } } catch (IOException e) { System.out.println(\"An error has occurred.\"); e.printStackTrace(); } }}",
"e": 28704,
"s": 28066,
"text": null
},
{
"code": null,
"e": 28711,
"s": 28704,
"text": "Output"
},
{
"code": null,
"e": 28734,
"s": 28711,
"text": "An error has occurred."
},
{
"code": null,
"e": 28899,
"s": 28734,
"text": "2. Read from a File: We will use the Scanner class in order to read contents from a file. Following is a demonstration of how to read contents from a file in Java :"
},
{
"code": null,
"e": 28904,
"s": 28899,
"text": "Java"
},
{
"code": "// Import the File classimport java.io.File; // Import this class for handling errorsimport java.io.FileNotFoundException; // Import the Scanner class to read content from text filesimport java.util.Scanner; public class GFG { public static void main(String[] args) { try { File Obj = new File(\"myfile.txt\"); Scanner Reader = new Scanner(Obj); while (Reader.hasNextLine()) { String data = Reader.nextLine(); System.out.println(data); } Reader.close(); } catch (FileNotFoundException e) { System.out.println(\"An error has occurred.\"); e.printStackTrace(); } }}",
"e": 29613,
"s": 28904,
"text": null
},
{
"code": null,
"e": 29620,
"s": 29613,
"text": "Output"
},
{
"code": null,
"e": 29643,
"s": 29620,
"text": "An error has occurred."
},
{
"code": null,
"e": 29832,
"s": 29643,
"text": "3. Write to a File: We use the FileWriter class along with its write() method in order to write some text to the file. Following is a demonstration of how to write text to a file in Java :"
},
{
"code": null,
"e": 29837,
"s": 29832,
"text": "Java"
},
{
"code": "// Import the FileWriter classimport java.io.FileWriter; // Import the IOException class for handling errorsimport java.io.IOException; public class GFG { public static void main(String[] args) { try { FileWriter Writer = new FileWriter(\"myfile.txt\"); Writer.write( \"Files in Java are seriously good!!\"); Writer.close(); System.out.println(\"Successfully written.\"); } catch (IOException e) { System.out.println(\"An error has occurred.\"); e.printStackTrace(); } }}",
"e": 30438,
"s": 29837,
"text": null
},
{
"code": null,
"e": 30445,
"s": 30438,
"text": "Output"
},
{
"code": null,
"e": 30468,
"s": 30445,
"text": "An error has occurred."
},
{
"code": null,
"e": 30603,
"s": 30468,
"text": "4. Delete a File: We use the delete() method in order to delete a file. Following is a demonstration of how to delete a file in Java :"
},
{
"code": null,
"e": 30608,
"s": 30603,
"text": "Java"
},
{
"code": "// Import the File classimport java.io.File; public class GFG { public static void main(String[] args) { File Obj = new File(\"myfile.txt\"); if (Obj.delete()) { System.out.println(\"The deleted file is : \" + myObj.getName()); } else { System.out.println( \"Failed in deleting the file.\"); } }}",
"e": 31012,
"s": 30608,
"text": null
},
{
"code": null,
"e": 31019,
"s": 31012,
"text": "Output"
},
{
"code": null,
"e": 31048,
"s": 31019,
"text": "Failed in deleting the file."
},
{
"code": null,
"e": 31067,
"s": 31048,
"text": "java-file-handling"
},
{
"code": null,
"e": 31074,
"s": 31067,
"text": "Picked"
},
{
"code": null,
"e": 31079,
"s": 31074,
"text": "Java"
},
{
"code": null,
"e": 31084,
"s": 31079,
"text": "Java"
},
{
"code": null,
"e": 31182,
"s": 31084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31197,
"s": 31182,
"text": "Stream In Java"
},
{
"code": null,
"e": 31243,
"s": 31197,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31264,
"s": 31243,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31283,
"s": 31264,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31313,
"s": 31283,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31330,
"s": 31313,
"text": "Generics in Java"
},
{
"code": null,
"e": 31373,
"s": 31330,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31402,
"s": 31373,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 31423,
"s": 31402,
"text": "Introduction to Java"
}
]
|
submit() element method - Selenium Python - GeeksforGeeks | 27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use submit method in Selenium. submit method is used to submit a form after you have sent data to a form.
element.submit()
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
To enter text into a field, for example,
element.send_keys("some text")
Now one can submit this search with
element.submit()
Let’s try to enter text in search field on geeksforgeeks and then submit its contents.Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # send keys element.send_keys("Arrays") # submit contentselement.submit()
Output-
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 26112,
"s": 25555,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies"
},
{
"code": null,
"e": 26254,
"s": 26112,
"text": "This article revolves around how to use submit method in Selenium. submit method is used to submit a form after you have sent data to a form."
},
{
"code": null,
"e": 26271,
"s": 26254,
"text": "element.submit()"
},
{
"code": null,
"e": 26281,
"s": 26271,
"text": "Example –"
},
{
"code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />",
"e": 26332,
"s": 26281,
"text": null
},
{
"code": null,
"e": 26413,
"s": 26332,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": null,
"e": 26577,
"s": 26413,
"text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")"
},
{
"code": null,
"e": 26623,
"s": 26577,
"text": "Also, to find multiple elements, we can use –"
},
{
"code": null,
"e": 26673,
"s": 26623,
"text": "elements = driver.find_elements_by_name(\"passwd\")"
},
{
"code": null,
"e": 26714,
"s": 26673,
"text": "To enter text into a field, for example,"
},
{
"code": null,
"e": 26745,
"s": 26714,
"text": "element.send_keys(\"some text\")"
},
{
"code": null,
"e": 26781,
"s": 26745,
"text": "Now one can submit this search with"
},
{
"code": null,
"e": 26798,
"s": 26781,
"text": "element.submit()"
},
{
"code": null,
"e": 26894,
"s": 26798,
"text": "Let’s try to enter text in search field on geeksforgeeks and then submit its contents.Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # send keys element.send_keys(\"Arrays\") # submit contentselement.submit()",
"e": 27207,
"s": 26894,
"text": null
},
{
"code": null,
"e": 27215,
"s": 27207,
"text": "Output-"
},
{
"code": null,
"e": 27231,
"s": 27215,
"text": "Python-selenium"
},
{
"code": null,
"e": 27240,
"s": 27231,
"text": "selenium"
},
{
"code": null,
"e": 27247,
"s": 27240,
"text": "Python"
},
{
"code": null,
"e": 27345,
"s": 27247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27377,
"s": 27345,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27419,
"s": 27377,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27461,
"s": 27419,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27517,
"s": 27461,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27544,
"s": 27517,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27575,
"s": 27544,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27614,
"s": 27575,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27643,
"s": 27614,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27665,
"s": 27643,
"text": "Defaultdict in Python"
}
]
|
Practice Questions for Recursion | Set 2 - GeeksforGeeks | 12 May, 2022
Explain the functionality of following functions.
Question 1
C++
Java
Python3
C#
Javascript
/* Assume that n is greater than or equal to 1 */int fun1(int n){ if (n == 1) return 0; else return 1 + fun1(n / 2);} // This code is contributed by shubhamsingh10// Improved by Adwitiya Mourya
/* Assume that n is greater than or equal to 1 */static int fun1(int n){ if (n == 1) return 0; else return 1 + fun1(n / 2);} // This code is contributed by shubhamsingh10
# Assume that n is greater than or equal to 1 */def fun1(n): if(n == 1): return 0 else: return 1 + fun1(n//2) # This code is contributed by shubhamsingh10
/* Assume that n is greater than or equal to 1 */static int fun1(int n){ if (n == 1) return 0; else return 1 + fun1(n / 2);} // This code is contributed by shubhamsingh10
<script> /* Assume that n is greater than or equal to 1 */function fun1(n){ if (n == 1) return 0 else return 1 + fun1(Math.floor(n / 2))} // This code is contributed by gottumukkalabobby </script>
Answer: The function calculates and returns
. For example, if n is between 8 and 15 then fun1() returns 3. If n is between 16 to 31 then fun1() returns 4.Question 2
C++
C
Java
Python3
C#
Javascript
/* Assume that n is greater than or equal to 0 */void fun2(int n){if(n == 0) return; fun2(n/2);cout << n%2 << endl;} //This code is contributed by shubhamsingh10
/* Assume that n is greater than or equal to 0 */void fun2(int n){ if(n == 0) return; fun2(n/2); printf("%d", n%2);}
/* Assume that n is greater than or equal to 1 */static void fun2(int n){if(n == 0) return; fun2(n/2);System.out.println(n%2);} // This code is contributed by Shubhamsingh10
# Assume that n is greater than or equal to 0 */def fun2(n): if(n == 0): return fun2(n / 2) print(n % 2, end="") # This code is contributed by shubhamsingh10
void fun2(int n){if(n == 0) return; fun2(n/2);Console.Write(n%2);}// This code is contributed by shubhamsingh10
<script> // Assume that n is greater than or equal to 1function fun2(n){ if (n == 0) return; fun2(Math.floor(n / 2)); document.write(n % 2 + " ")} // This code is contributed by gottumukkalabobby </script>
Answer: The function fun2() prints binary equivalent of n. For example, if n is 21 then fun2() prints 10101. Note that above functions are just for practicing recursion, they are not the ideal implementation of the functionality they provide. Please write comments if you find any of the answers/codes incorrect.
SHUBHAMSINGH10
gottumukkalabobby
smlakhera
adwitiya5727
beingharsh
borysenkomaksym
Misc
Recursion
Misc
Recursion
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Association Rule
Recursive Functions
Activation Functions
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)
Program for Tower of Hanoi
Backtracking | Introduction
Print all possible combinations of r elements in a given array of size n | [
{
"code": null,
"e": 26301,
"s": 26273,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26352,
"s": 26301,
"text": "Explain the functionality of following functions. "
},
{
"code": null,
"e": 26364,
"s": 26352,
"text": "Question 1 "
},
{
"code": null,
"e": 26368,
"s": 26364,
"text": "C++"
},
{
"code": null,
"e": 26373,
"s": 26368,
"text": "Java"
},
{
"code": null,
"e": 26381,
"s": 26373,
"text": "Python3"
},
{
"code": null,
"e": 26384,
"s": 26381,
"text": "C#"
},
{
"code": null,
"e": 26395,
"s": 26384,
"text": "Javascript"
},
{
"code": "/* Assume that n is greater than or equal to 1 */int fun1(int n){ if (n == 1) return 0; else return 1 + fun1(n / 2);} // This code is contributed by shubhamsingh10// Improved by Adwitiya Mourya",
"e": 26609,
"s": 26395,
"text": null
},
{
"code": "/* Assume that n is greater than or equal to 1 */static int fun1(int n){ if (n == 1) return 0; else return 1 + fun1(n / 2);} // This code is contributed by shubhamsingh10",
"e": 26800,
"s": 26609,
"text": null
},
{
"code": "# Assume that n is greater than or equal to 1 */def fun1(n): if(n == 1): return 0 else: return 1 + fun1(n//2) # This code is contributed by shubhamsingh10",
"e": 26975,
"s": 26800,
"text": null
},
{
"code": "/* Assume that n is greater than or equal to 1 */static int fun1(int n){ if (n == 1) return 0; else return 1 + fun1(n / 2);} // This code is contributed by shubhamsingh10",
"e": 27166,
"s": 26975,
"text": null
},
{
"code": "<script> /* Assume that n is greater than or equal to 1 */function fun1(n){ if (n == 1) return 0 else return 1 + fun1(Math.floor(n / 2))} // This code is contributed by gottumukkalabobby </script>",
"e": 27383,
"s": 27166,
"text": null
},
{
"code": null,
"e": 27428,
"s": 27383,
"text": "Answer: The function calculates and returns "
},
{
"code": null,
"e": 27550,
"s": 27428,
"text": ". For example, if n is between 8 and 15 then fun1() returns 3. If n is between 16 to 31 then fun1() returns 4.Question 2 "
},
{
"code": null,
"e": 27554,
"s": 27550,
"text": "C++"
},
{
"code": null,
"e": 27556,
"s": 27554,
"text": "C"
},
{
"code": null,
"e": 27561,
"s": 27556,
"text": "Java"
},
{
"code": null,
"e": 27569,
"s": 27561,
"text": "Python3"
},
{
"code": null,
"e": 27572,
"s": 27569,
"text": "C#"
},
{
"code": null,
"e": 27583,
"s": 27572,
"text": "Javascript"
},
{
"code": "/* Assume that n is greater than or equal to 0 */void fun2(int n){if(n == 0) return; fun2(n/2);cout << n%2 << endl;} //This code is contributed by shubhamsingh10",
"e": 27748,
"s": 27583,
"text": null
},
{
"code": "/* Assume that n is greater than or equal to 0 */void fun2(int n){ if(n == 0) return; fun2(n/2); printf(\"%d\", n%2);} ",
"e": 27873,
"s": 27748,
"text": null
},
{
"code": "/* Assume that n is greater than or equal to 1 */static void fun2(int n){if(n == 0) return; fun2(n/2);System.out.println(n%2);} // This code is contributed by Shubhamsingh10",
"e": 28051,
"s": 27873,
"text": null
},
{
"code": "# Assume that n is greater than or equal to 0 */def fun2(n): if(n == 0): return fun2(n / 2) print(n % 2, end=\"\") # This code is contributed by shubhamsingh10",
"e": 28230,
"s": 28051,
"text": null
},
{
"code": "void fun2(int n){if(n == 0) return; fun2(n/2);Console.Write(n%2);}// This code is contributed by shubhamsingh10",
"e": 28347,
"s": 28230,
"text": null
},
{
"code": "<script> // Assume that n is greater than or equal to 1function fun2(n){ if (n == 0) return; fun2(Math.floor(n / 2)); document.write(n % 2 + \" \")} // This code is contributed by gottumukkalabobby </script>",
"e": 28574,
"s": 28347,
"text": null
},
{
"code": null,
"e": 28888,
"s": 28574,
"text": "Answer: The function fun2() prints binary equivalent of n. For example, if n is 21 then fun2() prints 10101. Note that above functions are just for practicing recursion, they are not the ideal implementation of the functionality they provide. Please write comments if you find any of the answers/codes incorrect. "
},
{
"code": null,
"e": 28903,
"s": 28888,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 28921,
"s": 28903,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 28931,
"s": 28921,
"text": "smlakhera"
},
{
"code": null,
"e": 28944,
"s": 28931,
"text": "adwitiya5727"
},
{
"code": null,
"e": 28955,
"s": 28944,
"text": "beingharsh"
},
{
"code": null,
"e": 28971,
"s": 28955,
"text": "borysenkomaksym"
},
{
"code": null,
"e": 28976,
"s": 28971,
"text": "Misc"
},
{
"code": null,
"e": 28986,
"s": 28976,
"text": "Recursion"
},
{
"code": null,
"e": 28991,
"s": 28986,
"text": "Misc"
},
{
"code": null,
"e": 29001,
"s": 28991,
"text": "Recursion"
},
{
"code": null,
"e": 29006,
"s": 29001,
"text": "Misc"
},
{
"code": null,
"e": 29104,
"s": 29006,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29138,
"s": 29104,
"text": "How to write Regular Expressions?"
},
{
"code": null,
"e": 29219,
"s": 29138,
"text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)"
},
{
"code": null,
"e": 29236,
"s": 29219,
"text": "Association Rule"
},
{
"code": null,
"e": 29256,
"s": 29236,
"text": "Recursive Functions"
},
{
"code": null,
"e": 29277,
"s": 29256,
"text": "Activation Functions"
},
{
"code": null,
"e": 29337,
"s": 29277,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29422,
"s": 29337,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 29449,
"s": 29422,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 29477,
"s": 29449,
"text": "Backtracking | Introduction"
}
]
|
Check a given sentence for a given set of simple grammar rules - GeeksforGeeks | 25 Feb, 2022
A simple sentence if syntactically correct if it fulfills given rules. The following are given rules.1. Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.) 2. Then lowercase character follows. 3. There must be spaces between words. 4. Then the sentence must end with a full stop(.) after a word. 5. Two continuous spaces are not allowed. 6. Two continuous upper case characters are not allowed. 7. However, the sentence can end after an upper case character.Examples:
Correct sentences -
"My name is Ram."
"The vertex is S."
"I am single."
"I love Geeksquiz and Geeksforgeeks."
Incorrect sentence -
"My name is KG."
"I lovE cinema."
"GeeksQuiz. is a quiz site."
" You are my friend."
"I love cinema"
Question: Given a sentence, validate the given sentence for above given rules.We strongly recommend to minimize the browser and try this yourself first. The idea is to use an automata for the given set of rules.Algorithm : 1. Check for the corner cases .....1.a) Check if the first character is uppercase or not in the sentence. .....1.b) Check if the last character is a full stop or not.2. For rest of the string, this problem could be solved by following a state diagram. Please refer to the below state diagram for that.
3. We need to maintain previous and current state of different characters in the string. Based on that we can always validate the sentence of every character traversed.A C based implementation is below. (By the way this sentence is also correct according to the rule and code)
C++
Java
Python3
C#
Javascript
// C program to validate a given sentence for a set of rules#include<stdio.h>#include<string.h>#include<stdbool.h> // Method to check a given sentence for given rulesbool checkSentence(char str[]){ // Calculate the length of the string. int len = strlen(str); // Check that the first character lies in [A-Z]. // Otherwise return false. if (str[0] < 'A' || str[0] > 'Z') return false; //If the last character is not a full stop(.) no //need to check further. if (str[len - 1] != '.') return false; // Maintain 2 states. Previous and current state based // on which vertex state you are. Initialise both with // 0 = start state. int prev_state = 0, curr_state = 0; //Keep the index to the next character in the string. int index = 1; //Loop to go over the string. while (str[index]) { // Set states according to the input characters in the // string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if (str[index] >= 'A' && str[index] <= 'Z') curr_state = 0; // If current character is a space. Set current state as 1. else if (str[index] == ' ') curr_state = 1; // If current character is [a-z]. Set current state as 2. else if (str[index] >= 'a' && str[index] <= 'z') curr_state = 2; // If current state is a dot(.). Set current state as 3. else if (str[index] == '.') curr_state = 3; // Validates all current state with previous state for the // rules in the description of the problem. if (prev_state == curr_state && curr_state != 2) return false; if (prev_state == 2 && curr_state == 0) return false; // If we have reached last state and previous state is not 1, // then check next character. If next character is '\0', then // return true, else false if (curr_state == 3 && prev_state != 1) return (str[index + 1] == '\0'); index++; // Set previous state as current state before going over // to the next character. prev_state = curr_state; } return false;} // Driver programint main(){ char *str[] = { "I love cinema.", "The vertex is S.", "I am single.", "My name is KG.", "I lovE cinema.", "GeeksQuiz. is a quiz site.", "I love Geeksquiz and Geeksforgeeks.", " You are my friend.", "I love cinema" }; int str_size = sizeof(str) / sizeof(str[0]); int i = 0; for (i = 0; i < str_size; i++) checkSentence(str[i])? printf("\"%s\" is correct \n", str[i]): printf("\"%s\" is incorrect \n", str[i]); return 0;}
// Java program to validate a given sentence// for a set of rulesclass GFG{ // Method to check a given sentence for given rules static boolean checkSentence(char[] str) { // Calculate the length of the string. int len = str.length; // Check that the first character lies in [A-Z]. // Otherwise return false. if (str[0] < 'A' || str[0] > 'Z') return false; // If the last character is not a full stop(.) // no need to check further. if (str[len - 1] != '.') return false; // Maintain 2 states. Previous and current state // based on which vertex state you are. // Initialise both with 0 = start state. int prev_state = 0, curr_state = 0; // Keep the index to the next character in the string. int index = 1; // Loop to go over the string. while (index <= str.length) { // Set states according to the input characters // in the string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if (str[index] >= 'A' && str[index] <= 'Z') curr_state = 0; // If current character is a space. // Set current state as 1. else if (str[index] == ' ') curr_state = 1; // If current character is [a-z]. // Set current state as 2. else if (str[index] >= 'a' && str[index] <= 'z') curr_state = 2; // If current state is a dot(.). // Set current state as 3. else if (str[index] == '.') curr_state = 3; // Validates all current state with previous state // for the rules in the description of the problem. if (prev_state == curr_state && curr_state != 2) return false; if (prev_state == 2 && curr_state == 0) return false; // If we have reached last state and previous state // is not 1, then check next character. If next character // is '\0', then return true, else false if (curr_state == 3 && prev_state != 1) return (index + 1 == str.length); index++; // Set previous state as current state // before going over to the next character. prev_state = curr_state; } return false; } // Driver Code public static void main(String[] args) { String[] str = { "I love cinema.", "The vertex is S.", "I am single.", "My name is KG.", "I lovE cinema.", "GeeksQuiz. is a quiz site.", "I love Geeksquiz and Geeksforgeeks.", " You are my friend.", "I love cinema" }; int str_size = str.length; int i = 0; for (i = 0; i < str_size; i++) { if (checkSentence(str[i].toCharArray())) System.out.println("\"" + str[i] + "\"" + " is correct"); else System.out.println("\"" + str[i] + "\"" + " is incorrect"); } }} // This code is contributed by// sanjeev2552
# Python program to validate a given sentence for a set of rules # Method to check a given sentence for given rulesdef checkSentence(string): # Calculate the length of the string. length = len(string) # Check that the first character lies in [A-Z]. # Otherwise return false. if string[0] < 'A' or string[0] > 'Z': return False # If the last character is not a full stop(.) no # need to check further. if string[length-1] != '.': return False # Maintain 2 states. Previous and current state based # on which vertex state you are. Initialise both with # 0 = start state. prev_state = 0 curr_state = 0 # Keep the index to the next character in the string. index = 1 # Loop to go over the string. while (string[index]): # Set states according to the input characters in the # string and the rule defined in the description. # If current character is [A-Z]. Set current state as 0. if string[index] >= 'A' and string[index] <= 'Z': curr_state = 0 # If current character is a space. Set current state as 1. else if string[index] == ' ': curr_state = 1 # If current character is a space. Set current state as 2. else if string[index] >= 'a' and string[index] <= 'z': curr_state = 2 # If current character is a space. Set current state as 3. else if string[index] == '.': curr_state = 3 # Validates all current state with previous state for the # rules in the description of the problem. if prev_state == curr_state and curr_state != 2: return False # If we have reached last state and previous state is not 1, # then check next character. If next character is '\0', then # return true, else false if prev_state == 2 and curr_state == 0: return False # Set previous state as current state before going over # to the next character. if curr_state == 3 and prev_state != 1: return True index += 1 prev_state = curr_state return False # Driver programstring = ["I love cinema.", "The vertex is S.", "I am single.", "My name is KG.", "I lovE cinema.", "GeeksQuiz. is a quiz site.", "I love Geeksquiz and Geeksforgeeks.", " You are my friend.", "I love cinema"]string_size = len(string)for i in range(string_size): if checkSentence(string[i]): print ("\"" + string[i] + "\" is correct") else: print ("\"" + string[i] + "\" is incorrect") # This code is contributed by BHAVYA JAIN
// C# program to validate a given sentence// for a set of rulesusing System; class GFG{ // Method to check a given sentence for given rules static bool checkSentence(char[] str) { // Calculate the length of the string. int len = str.Length; // Check that the first character lies in [A-Z]. // Otherwise return false. if (str[0] < 'A' || str[0] > 'Z') return false; // If the last character is not a full stop(.) // no need to check further. if (str[len - 1] != '.') return false; // Maintain 2 states. Previous and current state // based on which vertex state you are. // Initialise both with 0 = start state. int prev_state = 0, curr_state = 0; // Keep the index to the next character in the string. int index = 1; // Loop to go over the string. while (index <= str.Length) { // Set states according to the input characters // in the string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if (str[index] >= 'A' && str[index] <= 'Z') curr_state = 0; // If current character is a space. // Set current state as 1. else if (str[index] == ' ') curr_state = 1; // If current character is [a-z]. // Set current state as 2. else if (str[index] >= 'a' && str[index] <= 'z') curr_state = 2; // If current state is a dot(.). // Set current state as 3. else if (str[index] == '.') curr_state = 3; // Validates all current state with previous state // for the rules in the description of the problem. if (prev_state == curr_state && curr_state != 2) return false; if (prev_state == 2 && curr_state == 0) return false; // If we have reached last state and previous state // is not 1, then check next character. If next character // is '\0', then return true, else false if (curr_state == 3 && prev_state != 1) return (index + 1 == str.Length); index++; // Set previous state as current state // before going over to the next character. prev_state = curr_state; } return false; } // Driver Code public static void Main(String[] args) { String[] str = { "I love cinema.", "The vertex is S.", "I am single.", "My name is KG.", "I lovE cinema.", "GeeksQuiz. is a quiz site.", "I love Geeksquiz and Geeksforgeeks.", " You are my friend.", "I love cinema" }; int str_size = str.Length; int i = 0; for (i = 0; i < str_size; i++) { if (checkSentence(str[i].ToCharArray())) Console.WriteLine("\"" + str[i] + "\"" + " is correct"); else Console.WriteLine("\"" + str[i] + "\"" + " is incorrect"); } }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to validate a given sentence // for a set of rules // Method to check a given sentence for given rules function checkSentence(str) { // Calculate the length of the string. var len = str.length; // Check that the first character lies in [A-Z]. // Otherwise return false. if ( str[0].charCodeAt(0) < "A".charCodeAt(0) || str[0].charCodeAt(0) > "Z".charCodeAt(0) ) return false; // If the last character is not a full stop(.) // no need to check further. if (str[len - 1] !== ".") return false; // Maintain 2 states. Previous and current state // based on which vertex state you are. // Initialise both with 0 = start state. var prev_state = 0, curr_state = 0; // Keep the index to the next character in the string. var index = 1; // Loop to go over the string. while (index <= str.length) { // Set states according to the input characters // in the string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if ( str[index].charCodeAt(0) >= "A".charCodeAt(0) && str[index].charCodeAt(0) <= "Z".charCodeAt(0) ) curr_state = 0; // If current character is a space. // Set current state as 1. else if (str[index] === " ") curr_state = 1; // If current character is [a-z]. // Set current state as 2. else if ( str[index].charCodeAt(0) >= "a".charCodeAt(0) && str[index].charCodeAt(0) <= "z".charCodeAt(0) ) curr_state = 2; // If current state is a dot(.). // Set current state as 3. else if (str[index] === ".") curr_state = 3; // Validates all current state with previous state // for the rules in the description of the problem. if (prev_state === curr_state && curr_state !== 2) return false; if (prev_state === 2 && curr_state === 0) return false; // If we have reached last state and previous state // is not 1, then check next character. If next character // is '\0', then return true, else false if (curr_state === 3 && prev_state !== 1) return index + 1 == str.length; index++; // Set previous state as current state // before going over to the next character. prev_state = curr_state; } return false; } // Driver Code var str = [ "I love cinema.", "The vertex is S.", "I am single.", "My name is KG.", "I lovE cinema.", "GeeksQuiz. is a quiz site.", "I love Geeksquiz and Geeksforgeeks.", " You are my friend.", "I love cinema", ]; var str_size = str.length; var i = 0; for (i = 0; i < str_size; i++) { var temp = str[i].split(""); if (checkSentence(temp)) document.write('"' + str[i] + '"' + " is correct" + "<br>"); else document.write('"' + str[i] + '"' + " is incorrect" + "<br>"); } </script>
Output:
"I love cinema." is correct
"The vertex is S." is correct
"I am single." is correct
"My name is KG." is incorrect
"I lovE cinema." is incorrect
"GeeksQuiz. is a quiz site." is incorrect
"I love Geeksquiz and Geeksforgeeks." is correct
" You are my friend." is incorrect
"I love cinema" is incorrect
Time complexity – O(n), worst case as we have to traverse the full sentence where n is the length of the sentence. Auxiliary space – O(1)This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sanjeev2552
29AjayKumar
rdtank
abhishek0719kadiyan
amartyaghoshgfg
simmytarika5
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
String class in Java | Set 1
sprintf() in C
Print all subsequences of a string
Convert character array to string in C++
How to Append a Character to a String in C
Program to count occurrence of a given character in a string
Naive algorithm for Pattern Searching | [
{
"code": null,
"e": 26099,
"s": 26071,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 26592,
"s": 26099,
"text": "A simple sentence if syntactically correct if it fulfills given rules. The following are given rules.1. Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.) 2. Then lowercase character follows. 3. There must be spaces between words. 4. Then the sentence must end with a full stop(.) after a word. 5. Two continuous spaces are not allowed. 6. Two continuous upper case characters are not allowed. 7. However, the sentence can end after an upper case character.Examples: "
},
{
"code": null,
"e": 26855,
"s": 26592,
"text": "Correct sentences -\n \"My name is Ram.\"\n \"The vertex is S.\"\n \"I am single.\"\n \"I love Geeksquiz and Geeksforgeeks.\"\n\nIncorrect sentence - \n \"My name is KG.\"\n \"I lovE cinema.\"\n \"GeeksQuiz. is a quiz site.\"\n \" You are my friend.\"\n \"I love cinema\" "
},
{
"code": null,
"e": 27382,
"s": 26855,
"text": "Question: Given a sentence, validate the given sentence for above given rules.We strongly recommend to minimize the browser and try this yourself first. The idea is to use an automata for the given set of rules.Algorithm : 1. Check for the corner cases .....1.a) Check if the first character is uppercase or not in the sentence. .....1.b) Check if the last character is a full stop or not.2. For rest of the string, this problem could be solved by following a state diagram. Please refer to the below state diagram for that. "
},
{
"code": null,
"e": 27661,
"s": 27382,
"text": "3. We need to maintain previous and current state of different characters in the string. Based on that we can always validate the sentence of every character traversed.A C based implementation is below. (By the way this sentence is also correct according to the rule and code) "
},
{
"code": null,
"e": 27665,
"s": 27661,
"text": "C++"
},
{
"code": null,
"e": 27670,
"s": 27665,
"text": "Java"
},
{
"code": null,
"e": 27678,
"s": 27670,
"text": "Python3"
},
{
"code": null,
"e": 27681,
"s": 27678,
"text": "C#"
},
{
"code": null,
"e": 27692,
"s": 27681,
"text": "Javascript"
},
{
"code": "// C program to validate a given sentence for a set of rules#include<stdio.h>#include<string.h>#include<stdbool.h> // Method to check a given sentence for given rulesbool checkSentence(char str[]){ // Calculate the length of the string. int len = strlen(str); // Check that the first character lies in [A-Z]. // Otherwise return false. if (str[0] < 'A' || str[0] > 'Z') return false; //If the last character is not a full stop(.) no //need to check further. if (str[len - 1] != '.') return false; // Maintain 2 states. Previous and current state based // on which vertex state you are. Initialise both with // 0 = start state. int prev_state = 0, curr_state = 0; //Keep the index to the next character in the string. int index = 1; //Loop to go over the string. while (str[index]) { // Set states according to the input characters in the // string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if (str[index] >= 'A' && str[index] <= 'Z') curr_state = 0; // If current character is a space. Set current state as 1. else if (str[index] == ' ') curr_state = 1; // If current character is [a-z]. Set current state as 2. else if (str[index] >= 'a' && str[index] <= 'z') curr_state = 2; // If current state is a dot(.). Set current state as 3. else if (str[index] == '.') curr_state = 3; // Validates all current state with previous state for the // rules in the description of the problem. if (prev_state == curr_state && curr_state != 2) return false; if (prev_state == 2 && curr_state == 0) return false; // If we have reached last state and previous state is not 1, // then check next character. If next character is '\\0', then // return true, else false if (curr_state == 3 && prev_state != 1) return (str[index + 1] == '\\0'); index++; // Set previous state as current state before going over // to the next character. prev_state = curr_state; } return false;} // Driver programint main(){ char *str[] = { \"I love cinema.\", \"The vertex is S.\", \"I am single.\", \"My name is KG.\", \"I lovE cinema.\", \"GeeksQuiz. is a quiz site.\", \"I love Geeksquiz and Geeksforgeeks.\", \" You are my friend.\", \"I love cinema\" }; int str_size = sizeof(str) / sizeof(str[0]); int i = 0; for (i = 0; i < str_size; i++) checkSentence(str[i])? printf(\"\\\"%s\\\" is correct \\n\", str[i]): printf(\"\\\"%s\\\" is incorrect \\n\", str[i]); return 0;}",
"e": 30493,
"s": 27692,
"text": null
},
{
"code": "// Java program to validate a given sentence// for a set of rulesclass GFG{ // Method to check a given sentence for given rules static boolean checkSentence(char[] str) { // Calculate the length of the string. int len = str.length; // Check that the first character lies in [A-Z]. // Otherwise return false. if (str[0] < 'A' || str[0] > 'Z') return false; // If the last character is not a full stop(.) // no need to check further. if (str[len - 1] != '.') return false; // Maintain 2 states. Previous and current state // based on which vertex state you are. // Initialise both with 0 = start state. int prev_state = 0, curr_state = 0; // Keep the index to the next character in the string. int index = 1; // Loop to go over the string. while (index <= str.length) { // Set states according to the input characters // in the string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if (str[index] >= 'A' && str[index] <= 'Z') curr_state = 0; // If current character is a space. // Set current state as 1. else if (str[index] == ' ') curr_state = 1; // If current character is [a-z]. // Set current state as 2. else if (str[index] >= 'a' && str[index] <= 'z') curr_state = 2; // If current state is a dot(.). // Set current state as 3. else if (str[index] == '.') curr_state = 3; // Validates all current state with previous state // for the rules in the description of the problem. if (prev_state == curr_state && curr_state != 2) return false; if (prev_state == 2 && curr_state == 0) return false; // If we have reached last state and previous state // is not 1, then check next character. If next character // is '\\0', then return true, else false if (curr_state == 3 && prev_state != 1) return (index + 1 == str.length); index++; // Set previous state as current state // before going over to the next character. prev_state = curr_state; } return false; } // Driver Code public static void main(String[] args) { String[] str = { \"I love cinema.\", \"The vertex is S.\", \"I am single.\", \"My name is KG.\", \"I lovE cinema.\", \"GeeksQuiz. is a quiz site.\", \"I love Geeksquiz and Geeksforgeeks.\", \" You are my friend.\", \"I love cinema\" }; int str_size = str.length; int i = 0; for (i = 0; i < str_size; i++) { if (checkSentence(str[i].toCharArray())) System.out.println(\"\\\"\" + str[i] + \"\\\"\" + \" is correct\"); else System.out.println(\"\\\"\" + str[i] + \"\\\"\" + \" is incorrect\"); } }} // This code is contributed by// sanjeev2552",
"e": 33812,
"s": 30493,
"text": null
},
{
"code": "# Python program to validate a given sentence for a set of rules # Method to check a given sentence for given rulesdef checkSentence(string): # Calculate the length of the string. length = len(string) # Check that the first character lies in [A-Z]. # Otherwise return false. if string[0] < 'A' or string[0] > 'Z': return False # If the last character is not a full stop(.) no # need to check further. if string[length-1] != '.': return False # Maintain 2 states. Previous and current state based # on which vertex state you are. Initialise both with # 0 = start state. prev_state = 0 curr_state = 0 # Keep the index to the next character in the string. index = 1 # Loop to go over the string. while (string[index]): # Set states according to the input characters in the # string and the rule defined in the description. # If current character is [A-Z]. Set current state as 0. if string[index] >= 'A' and string[index] <= 'Z': curr_state = 0 # If current character is a space. Set current state as 1. else if string[index] == ' ': curr_state = 1 # If current character is a space. Set current state as 2. else if string[index] >= 'a' and string[index] <= 'z': curr_state = 2 # If current character is a space. Set current state as 3. else if string[index] == '.': curr_state = 3 # Validates all current state with previous state for the # rules in the description of the problem. if prev_state == curr_state and curr_state != 2: return False # If we have reached last state and previous state is not 1, # then check next character. If next character is '\\0', then # return true, else false if prev_state == 2 and curr_state == 0: return False # Set previous state as current state before going over # to the next character. if curr_state == 3 and prev_state != 1: return True index += 1 prev_state = curr_state return False # Driver programstring = [\"I love cinema.\", \"The vertex is S.\", \"I am single.\", \"My name is KG.\", \"I lovE cinema.\", \"GeeksQuiz. is a quiz site.\", \"I love Geeksquiz and Geeksforgeeks.\", \" You are my friend.\", \"I love cinema\"]string_size = len(string)for i in range(string_size): if checkSentence(string[i]): print (\"\\\"\" + string[i] + \"\\\" is correct\") else: print (\"\\\"\" + string[i] + \"\\\" is incorrect\") # This code is contributed by BHAVYA JAIN",
"e": 36459,
"s": 33812,
"text": null
},
{
"code": "// C# program to validate a given sentence// for a set of rulesusing System; class GFG{ // Method to check a given sentence for given rules static bool checkSentence(char[] str) { // Calculate the length of the string. int len = str.Length; // Check that the first character lies in [A-Z]. // Otherwise return false. if (str[0] < 'A' || str[0] > 'Z') return false; // If the last character is not a full stop(.) // no need to check further. if (str[len - 1] != '.') return false; // Maintain 2 states. Previous and current state // based on which vertex state you are. // Initialise both with 0 = start state. int prev_state = 0, curr_state = 0; // Keep the index to the next character in the string. int index = 1; // Loop to go over the string. while (index <= str.Length) { // Set states according to the input characters // in the string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if (str[index] >= 'A' && str[index] <= 'Z') curr_state = 0; // If current character is a space. // Set current state as 1. else if (str[index] == ' ') curr_state = 1; // If current character is [a-z]. // Set current state as 2. else if (str[index] >= 'a' && str[index] <= 'z') curr_state = 2; // If current state is a dot(.). // Set current state as 3. else if (str[index] == '.') curr_state = 3; // Validates all current state with previous state // for the rules in the description of the problem. if (prev_state == curr_state && curr_state != 2) return false; if (prev_state == 2 && curr_state == 0) return false; // If we have reached last state and previous state // is not 1, then check next character. If next character // is '\\0', then return true, else false if (curr_state == 3 && prev_state != 1) return (index + 1 == str.Length); index++; // Set previous state as current state // before going over to the next character. prev_state = curr_state; } return false; } // Driver Code public static void Main(String[] args) { String[] str = { \"I love cinema.\", \"The vertex is S.\", \"I am single.\", \"My name is KG.\", \"I lovE cinema.\", \"GeeksQuiz. is a quiz site.\", \"I love Geeksquiz and Geeksforgeeks.\", \" You are my friend.\", \"I love cinema\" }; int str_size = str.Length; int i = 0; for (i = 0; i < str_size; i++) { if (checkSentence(str[i].ToCharArray())) Console.WriteLine(\"\\\"\" + str[i] + \"\\\"\" + \" is correct\"); else Console.WriteLine(\"\\\"\" + str[i] + \"\\\"\" + \" is incorrect\"); } }} // This code is contributed by 29AjayKumar",
"e": 39773,
"s": 36459,
"text": null
},
{
"code": "<script> // JavaScript program to validate a given sentence // for a set of rules // Method to check a given sentence for given rules function checkSentence(str) { // Calculate the length of the string. var len = str.length; // Check that the first character lies in [A-Z]. // Otherwise return false. if ( str[0].charCodeAt(0) < \"A\".charCodeAt(0) || str[0].charCodeAt(0) > \"Z\".charCodeAt(0) ) return false; // If the last character is not a full stop(.) // no need to check further. if (str[len - 1] !== \".\") return false; // Maintain 2 states. Previous and current state // based on which vertex state you are. // Initialise both with 0 = start state. var prev_state = 0, curr_state = 0; // Keep the index to the next character in the string. var index = 1; // Loop to go over the string. while (index <= str.length) { // Set states according to the input characters // in the string and the rule defined in the description. // If current character is [A-Z]. Set current state as 0. if ( str[index].charCodeAt(0) >= \"A\".charCodeAt(0) && str[index].charCodeAt(0) <= \"Z\".charCodeAt(0) ) curr_state = 0; // If current character is a space. // Set current state as 1. else if (str[index] === \" \") curr_state = 1; // If current character is [a-z]. // Set current state as 2. else if ( str[index].charCodeAt(0) >= \"a\".charCodeAt(0) && str[index].charCodeAt(0) <= \"z\".charCodeAt(0) ) curr_state = 2; // If current state is a dot(.). // Set current state as 3. else if (str[index] === \".\") curr_state = 3; // Validates all current state with previous state // for the rules in the description of the problem. if (prev_state === curr_state && curr_state !== 2) return false; if (prev_state === 2 && curr_state === 0) return false; // If we have reached last state and previous state // is not 1, then check next character. If next character // is '\\0', then return true, else false if (curr_state === 3 && prev_state !== 1) return index + 1 == str.length; index++; // Set previous state as current state // before going over to the next character. prev_state = curr_state; } return false; } // Driver Code var str = [ \"I love cinema.\", \"The vertex is S.\", \"I am single.\", \"My name is KG.\", \"I lovE cinema.\", \"GeeksQuiz. is a quiz site.\", \"I love Geeksquiz and Geeksforgeeks.\", \" You are my friend.\", \"I love cinema\", ]; var str_size = str.length; var i = 0; for (i = 0; i < str_size; i++) { var temp = str[i].split(\"\"); if (checkSentence(temp)) document.write('\"' + str[i] + '\"' + \" is correct\" + \"<br>\"); else document.write('\"' + str[i] + '\"' + \" is incorrect\" + \"<br>\"); } </script>",
"e": 43008,
"s": 39773,
"text": null
},
{
"code": null,
"e": 43017,
"s": 43008,
"text": "Output: "
},
{
"code": null,
"e": 43317,
"s": 43017,
"text": "\"I love cinema.\" is correct\n\"The vertex is S.\" is correct\n\"I am single.\" is correct\n\"My name is KG.\" is incorrect\n\"I lovE cinema.\" is incorrect\n\"GeeksQuiz. is a quiz site.\" is incorrect\n\"I love Geeksquiz and Geeksforgeeks.\" is correct\n\" You are my friend.\" is incorrect\n\"I love cinema\" is incorrect"
},
{
"code": null,
"e": 43626,
"s": 43317,
"text": "Time complexity – O(n), worst case as we have to traverse the full sentence where n is the length of the sentence. Auxiliary space – O(1)This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 43638,
"s": 43626,
"text": "sanjeev2552"
},
{
"code": null,
"e": 43650,
"s": 43638,
"text": "29AjayKumar"
},
{
"code": null,
"e": 43657,
"s": 43650,
"text": "rdtank"
},
{
"code": null,
"e": 43677,
"s": 43657,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 43693,
"s": 43677,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 43706,
"s": 43693,
"text": "simmytarika5"
},
{
"code": null,
"e": 43714,
"s": 43706,
"text": "Strings"
},
{
"code": null,
"e": 43722,
"s": 43714,
"text": "Strings"
},
{
"code": null,
"e": 43820,
"s": 43722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43865,
"s": 43820,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 43910,
"s": 43865,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 43927,
"s": 43910,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 43956,
"s": 43927,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 43971,
"s": 43956,
"text": "sprintf() in C"
},
{
"code": null,
"e": 44006,
"s": 43971,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 44047,
"s": 44006,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 44090,
"s": 44047,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 44151,
"s": 44090,
"text": "Program to count occurrence of a given character in a string"
}
]
|
k-th prime factor of a given number - GeeksforGeeks | 24 Jan, 2022
Given two numbers n and k, print k-th prime factor among all prime factors of n. For example, if the input number is 15 and k is 2, then output should be “5”. And if the k is 3, then output should be “-1” (there are less than k prime factors). Examples:
Input : n = 225, k = 2
Output : 3
Prime factors are 3 3 5 5. Second
prime factor is 3.
Input : n = 81, k = 5
Output : -1
Prime factors are 3 3 3 3
A Simple Solution is to first find prime factors of n. While finding prime factors, keep track of count. If count becomes k, we return current prime factor.
C++
Java
Python3
C#
PHP
Javascript
// Program to print kth prime factor# include<bits/stdc++.h>using namespace std; // A function to generate prime factors of a// given number n and return k-th prime factorint kPrimeFactor(int n, int k){ // Find the number of 2's that divide k while (n%2 == 0) { k--; n = n/2; if (k == 0) return 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, store i and divide n while (n%i == 0) { if (k == 1) return i; k--; n = n/i; } } // This condition is to handle the case where // n is a prime number greater than 2 if (n > 2 && k == 1) return n; return -1;} // Driver Programint main(){ int n = 12, k = 3; cout << kPrimeFactor(n, k) << endl; n = 14, k = 3; cout << kPrimeFactor(n, k) << endl; return 0;}
// JAVA Program to print kth prime factorimport java.io.*;import java.math.*; class GFG{ // A function to generate prime factors // of a given number n and return k-th // prime factor static int kPrimeFactor(int n, int k) { // Find the number of 2's that // divide k while (n % 2 == 0) { k--; n = n / 2; if (k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, store i // and divide n while (n % i == 0) { if (k == 1) return i; k--; n = n / i; } } // This condition is to handle the // case where n is a prime number // greater than 2 if (n > 2 && k == 1) return n; return -1; } // Driver Program public static void main(String args[]) { int n = 12, k = 3; System.out.println(kPrimeFactor(n, k)); n = 14; k = 3; System.out.println(kPrimeFactor(n, k)); }} /*This code is contributed by Nikita Tiwari.*/
# Python Program to print kth prime factorimport math # A function to generate prime factors of a# given number n and return k-th prime factordef kPrimeFactor(n,k) : # Find the number of 2's that divide k while (n % 2 == 0) : k = k - 1 n = n // 2 if (k == 0) : return 2 # n must be odd at this point. So we can # skip one element (Note i = i +2) i = 3 while i <= math.sqrt(n) : # While i divides n, store i and divide n while (n % i == 0) : if (k == 1) : return i k = k - 1 n = n // i i = i + 2 # This condition is to handle the case # where n is a prime number greater than 2 if (n > 2 and k == 1) : return n return -1 # Driver Programn = 12k = 3print(kPrimeFactor(n, k)) n = 14k = 3print(kPrimeFactor(n, k)) # This code is contributed by Nikita Tiwari.
// C# Program to print kth prime factor.using System; class GFG { // A function to generate prime factors // of a given number n and return k-th // prime factor static int kPrimeFactor(int n, int k) { // Find the number of 2's that // divide k while (n % 2 == 0) { k--; n = n / 2; if (k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, store i // and divide n while (n % i == 0) { if (k == 1) return i; k--; n = n / i; } } // This condition is to handle the // case where n is a prime number // greater than 2 if (n > 2 && k == 1) return n; return -1; } // Driver Program public static void Main() { int n = 12, k = 3; Console.WriteLine(kPrimeFactor(n, k)); n = 14; k = 3; Console.WriteLine(kPrimeFactor(n, k)); }} // This code is contributed by nitin mittal.
<?php// PHP Program to print kth prime factor // A function to generate prime// factors of a given number n// and return k-th prime factorfunction kPrimeFactor($n, $k){ // Find the number of 2's // that divide k while ($n%2 == 0) { $k--; $n = $n/2; if ($k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for($i = 3; $i <= sqrt($n); $i = $i+2) { // While i divides n, // store i and divide n while ($n % $i == 0) { if ($k == 1) return $i; $k--; $n = $n / $i; } } // This condition is to // handle the case where // n is a prime number // greater than 2 if ($n > 2 && $k == 1) return $n; return -1;} // Driver Code{ $n = 12; $k = 3; echo kPrimeFactor($n, $k),"\n" ; $n = 14; $k = 3; echo kPrimeFactor($n, $k) ; return 0;} // This code contributed by nitin mittal.?>
<script> // Javascript Program to print kth prime factor // A function to generate prime factors // of a given number n and return k-th // prime factor function kPrimeFactor(n, k) { // Find the number of 2's that // divide k while (n % 2 == 0) { k--; n = n / 2; if (k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, store i // and divide n while (n % i == 0) { if (k == 1) return i; k--; n = n / i; } } // This condition is to handle the // case where n is a prime number // greater than 2 if (n > 2 && k == 1) return n; return -1; } // Driver code let n = 12, k = 3; document.write(kPrimeFactor(n, k) + "<br/>"); n = 14; k = 3; document.write(kPrimeFactor(n, k)); // This code is contributed by susmitakundugoaldanga. </script>
Output:
3
-1
An Efficient Solution is to use Sieve of Eratosthenes. Note that this solution is efficient when we need k-th prime factor for multiple test cases. For a single case, previous approach is better. The idea is to do preprocessing and store least prime factor of all numbers in given range. Once we have least prime factors stored in an array, we can find k-th prime factor by repeatedly dividing n with least prime factor while it is divisible, then repeating the process for reduced n.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find k-th prime factor using Sieve Of// Eratosthenes. This program is efficient when we have// a range of numbers.#include<bits/stdc++.h> using namespace std;const int MAX = 10001; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7void sieveOfEratosthenes(int s[]){ // Create a boolean array "prime[0..MAX]" and // initialize all entries in it as false. vector <bool> prime(MAX+1, false); // Initializing smallest factor equal to 2 // for all the even numbers for (int i=2; i<=MAX; i+=2) s[i] = 2; // For odd numbers less then equal to n for (int i=3; i<=MAX; i+=2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j=i; j*i<=MAX; j+=2) { if (prime[i*j] == false) { prime[i*j] = true; // i is the smallest prime factor for // number "i*j". s[i*j] = i; } } } }} // Function to generate prime factors and return its// k-th prime factor. s[i] stores least prime factor// of i.int kPrimeFactor(int n, int k, int s[]){ // Keep dividing n by least prime factor while // either n is not 1 or count of prime factors // is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver Programint main(){ // s[i] is going to store prime factor // of i. int s[MAX+1]; memset(s, -1, sizeof(s)); sieveOfEratosthenes(s); int n = 12, k = 3; cout << kPrimeFactor(n, k, s) << endl; n = 14, k = 3; cout << kPrimeFactor(n, k, s) << endl; return 0;}
// Java program to find k-th prime factor// using Sieve Of Eratosthenes. This// program is efficient when we have// a range of numbers.class GFG{static int MAX = 10001; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7static void sieveOfEratosthenes(int []s){ // Create a boolean array "prime[0..MAX]" and // initialize all entries in it as false. boolean[] prime=new boolean[MAX+1]; // Initializing smallest factor equal to 2 // for all the even numbers for (int i = 2; i <= MAX; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= MAX; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j = i; j * i <= MAX; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number "i*j". s[i * j] = i; } } } }} // Function to generate prime factors// and return its k-th prime factor.// s[i] stores least prime factor of i.static int kPrimeFactor(int n, int k, int []s){ // Keep dividing n by least // prime factor while either // n is not 1 or count of // prime factors is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver codepublic static void main (String[] args){ // s[i] is going to store prime factor // of i. int[] s = new int[MAX + 1]; sieveOfEratosthenes(s); int n = 12, k = 3; System.out.println(kPrimeFactor(n, k, s)); n = 14; k = 3; System.out.println(kPrimeFactor(n, k, s));}} // This code is contributed by mits
# python3 program to find k-th prime factor using Sieve Of# Eratosthenes. This program is efficient when we have# a range of numbers. MAX = 10001 # Using SieveOfEratosthenes to find smallest prime# factor of all the numbers.# For example, if MAX is 10,# s[2] = s[4] = s[6] = s[10] = 2# s[3] = s[9] = 3# s[5] = 5# s[7] = 7def sieveOfEratosthenes(s): # Create a boolean array "prime[0..MAX]" and# initialize all entries in it as false. prime=[False for i in range(MAX+1)] # Initializing smallest factor equal to 2 # for all the even numbers for i in range(2,MAX+1,2): s[i] = 2; # For odd numbers less then equal to n for i in range(3,MAX,2): if (prime[i] == False): # s(i) for a prime is the number itself s[i] = i # For all multiples of current prime number for j in range(i,MAX+1,2): if j*j> MAX: break if (prime[i*j] == False): prime[i*j] = True # i is the smallest prime factor for # number "i*j". s[i*j] = i # Function to generate prime factors and return its# k-th prime factor. s[i] stores least prime factor# of i.def kPrimeFactor(n, k, s): # Keep dividing n by least prime factor while # either n is not 1 or count of prime factors # is not k. while (n > 1): if (k == 1): return s[n] # To keep track of count of prime factors k-=1 # Divide n to find next prime factor n //= s[n] return -1 # Driver Program # s[i] is going to store prime factor# of i.s=[-1 for i in range(MAX+1)] sieveOfEratosthenes(s) n = 12k = 3print(kPrimeFactor(n, k, s)) n = 14k = 3print(kPrimeFactor(n, k, s)) # This code is contributed by mohit kumar 29
// C# program to find k-th prime factor// using Sieve Of Eratosthenes. This// program is efficient when we have// a range of numbers and weusing System;class GFG{static int MAX = 10001; // Using SieveOfEratosthenes to find// smallest prime factor of all the// numbers. For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7static void sieveOfEratosthenes(int []s){ // Create a boolean array "prime[0..MAX]" // and initialize all entries in it as false. bool[] prime = new bool[MAX + 1]; // Initializing smallest factor equal // to 2 for all the even numbers for (int i = 2; i <= MAX; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= MAX; i += 2) { if (prime[i] == false) { // s(i) for a prime is the // number itself s[i] = i; // For all multiples of current // prime number for (int j = i; j * i <= MAX; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor // for number "i*j". s[i * j] = i; } } } }} // Function to generate prime factors// and return its k-th prime factor.// s[i] stores least prime factor of i.static int kPrimeFactor(int n, int k, int []s){ // Keep dividing n by least prime // factor while either n is not 1 // or count of prime factors is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of // prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver Codestatic void Main(){ // s[i] is going to store prime // factor of i. int[] s = new int[MAX + 1]; sieveOfEratosthenes(s); int n = 12, k = 3; Console.WriteLine(kPrimeFactor(n, k, s)); n = 14; k = 3; Console.WriteLine(kPrimeFactor(n, k, s));}} // This code is contributed by mits
<?php// PHP program to find k-th prime factor// using Sieve Of Eratosthenes. This program// is efficient when we have a range of numbers. $MAX = 10001; // Using SieveOfEratosthenes to find// smallest prime factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7function sieveOfEratosthenes(&$s){ global $MAX; // Create a boolean array "prime[0..MAX]" // and initialize all entries in it as false. $prime = array_fill(0, $MAX + 1, false); // Initializing smallest factor equal // to 2 for all the even numbers for ($i = 2; $i <= $MAX; $i += 2) $s[$i] = 2; // For odd numbers less then equal to n for ($i = 3; $i <= $MAX; $i += 2) { if ($prime[$i] == false) { // s(i) for a prime is the // number itself $s[$i] = $i; // For all multiples of current // prime number for ($j = $i; $j * $i <= $MAX; $j += 2) { if ($prime[$i * $j] == false) { $prime[$i * $j] = true; // i is the smallest prime // factor for number "i*j". $s[$i * $j] = $i; } } } }} // Function to generate prime factors and// return its k-th prime factor. s[i] stores// least prime factor of i.function kPrimeFactor($n, $k, $s){ // Keep dividing n by least prime // factor while either n is not 1 // or count of prime factors is not k. while ($n > 1) { if ($k == 1) return $s[$n]; // To keep track of count of // prime factors $k--; // Divide n to find next prime factor $n = (int)($n / $s[$n]); } return -1;} // Driver Code // s[i] is going to store prime// factor of i.$s = array_fill(0, $MAX + 1, -1);sieveOfEratosthenes($s); $n = 12;$k = 3;print(kPrimeFactor($n, $k, $s) . "\n"); $n = 14;$k = 3;print(kPrimeFactor($n, $k, $s)); // This code is contributed by chandan_jnu?>
<script> // Javascript program to find k-th prime factor// using Sieve Of Eratosthenes. This// program is efficient when we have// a range of numbers. var MAX = 10001; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7function sieveOfEratosthenes(s){ // Create a boolean array "prime[0..MAX]" and // initialize all entries in it as false. prime=Array.from({length: MAX+1}, (_, i) => false); // Initializing smallest factor equal to 2 // for all the even numbers for (i = 2; i <= MAX; i += 2) s[i] = 2; // For odd numbers less then equal to n for (i = 3; i <= MAX; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (j = i; j * i <= MAX; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number "i*j". s[i * j] = i; } } } }} // Function to generate prime factors// and return its k-th prime factor.// s[i] stores least prime factor of i.function kPrimeFactor(n , k , s){ // Keep dividing n by least // prime factor while either // n is not 1 or count of // prime factors is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver code // s[i] is going to store prime factor// of i.var s = Array.from({length: MAX + 1}, (_, i) => 0);sieveOfEratosthenes(s); var n = 12, k = 3;document.write(kPrimeFactor(n, k, s)+"<br>");n = 14;k = 3;document.write(kPrimeFactor(n, k, s)); // This code contributed by shikhasingrajput </script>
Output:
3
-1
This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Mithun Kumar
Chandan_Kumar
mohit kumar 29
susmitakundugoaldanga
shikhasingrajput
gabaa406
amartyaghoshgfg
factorial
Prime Number
prime-factor
sieve
Mathematical
Mathematical
Prime Number
sieve
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion
Find minimum number of coins that make a given value
Program to find sum of elements in a given array | [
{
"code": null,
"e": 25765,
"s": 25737,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 26021,
"s": 25765,
"text": "Given two numbers n and k, print k-th prime factor among all prime factors of n. For example, if the input number is 15 and k is 2, then output should be “5”. And if the k is 3, then output should be “-1” (there are less than k prime factors). Examples: "
},
{
"code": null,
"e": 26177,
"s": 26021,
"text": "Input : n = 225, k = 2 \nOutput : 3\nPrime factors are 3 3 5 5. Second\nprime factor is 3.\n\nInput : n = 81, k = 5\nOutput : -1\nPrime factors are 3 3 3 3"
},
{
"code": null,
"e": 26338,
"s": 26179,
"text": "A Simple Solution is to first find prime factors of n. While finding prime factors, keep track of count. If count becomes k, we return current prime factor. "
},
{
"code": null,
"e": 26342,
"s": 26338,
"text": "C++"
},
{
"code": null,
"e": 26347,
"s": 26342,
"text": "Java"
},
{
"code": null,
"e": 26355,
"s": 26347,
"text": "Python3"
},
{
"code": null,
"e": 26358,
"s": 26355,
"text": "C#"
},
{
"code": null,
"e": 26362,
"s": 26358,
"text": "PHP"
},
{
"code": null,
"e": 26373,
"s": 26362,
"text": "Javascript"
},
{
"code": "// Program to print kth prime factor# include<bits/stdc++.h>using namespace std; // A function to generate prime factors of a// given number n and return k-th prime factorint kPrimeFactor(int n, int k){ // Find the number of 2's that divide k while (n%2 == 0) { k--; n = n/2; if (k == 0) return 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, store i and divide n while (n%i == 0) { if (k == 1) return i; k--; n = n/i; } } // This condition is to handle the case where // n is a prime number greater than 2 if (n > 2 && k == 1) return n; return -1;} // Driver Programint main(){ int n = 12, k = 3; cout << kPrimeFactor(n, k) << endl; n = 14, k = 3; cout << kPrimeFactor(n, k) << endl; return 0;}",
"e": 27336,
"s": 26373,
"text": null
},
{
"code": "// JAVA Program to print kth prime factorimport java.io.*;import java.math.*; class GFG{ // A function to generate prime factors // of a given number n and return k-th // prime factor static int kPrimeFactor(int n, int k) { // Find the number of 2's that // divide k while (n % 2 == 0) { k--; n = n / 2; if (k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, store i // and divide n while (n % i == 0) { if (k == 1) return i; k--; n = n / i; } } // This condition is to handle the // case where n is a prime number // greater than 2 if (n > 2 && k == 1) return n; return -1; } // Driver Program public static void main(String args[]) { int n = 12, k = 3; System.out.println(kPrimeFactor(n, k)); n = 14; k = 3; System.out.println(kPrimeFactor(n, k)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 28634,
"s": 27336,
"text": null
},
{
"code": "# Python Program to print kth prime factorimport math # A function to generate prime factors of a# given number n and return k-th prime factordef kPrimeFactor(n,k) : # Find the number of 2's that divide k while (n % 2 == 0) : k = k - 1 n = n // 2 if (k == 0) : return 2 # n must be odd at this point. So we can # skip one element (Note i = i +2) i = 3 while i <= math.sqrt(n) : # While i divides n, store i and divide n while (n % i == 0) : if (k == 1) : return i k = k - 1 n = n // i i = i + 2 # This condition is to handle the case # where n is a prime number greater than 2 if (n > 2 and k == 1) : return n return -1 # Driver Programn = 12k = 3print(kPrimeFactor(n, k)) n = 14k = 3print(kPrimeFactor(n, k)) # This code is contributed by Nikita Tiwari.",
"e": 29550,
"s": 28634,
"text": null
},
{
"code": "// C# Program to print kth prime factor.using System; class GFG { // A function to generate prime factors // of a given number n and return k-th // prime factor static int kPrimeFactor(int n, int k) { // Find the number of 2's that // divide k while (n % 2 == 0) { k--; n = n / 2; if (k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, store i // and divide n while (n % i == 0) { if (k == 1) return i; k--; n = n / i; } } // This condition is to handle the // case where n is a prime number // greater than 2 if (n > 2 && k == 1) return n; return -1; } // Driver Program public static void Main() { int n = 12, k = 3; Console.WriteLine(kPrimeFactor(n, k)); n = 14; k = 3; Console.WriteLine(kPrimeFactor(n, k)); }} // This code is contributed by nitin mittal.",
"e": 30892,
"s": 29550,
"text": null
},
{
"code": "<?php// PHP Program to print kth prime factor // A function to generate prime// factors of a given number n// and return k-th prime factorfunction kPrimeFactor($n, $k){ // Find the number of 2's // that divide k while ($n%2 == 0) { $k--; $n = $n/2; if ($k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for($i = 3; $i <= sqrt($n); $i = $i+2) { // While i divides n, // store i and divide n while ($n % $i == 0) { if ($k == 1) return $i; $k--; $n = $n / $i; } } // This condition is to // handle the case where // n is a prime number // greater than 2 if ($n > 2 && $k == 1) return $n; return -1;} // Driver Code{ $n = 12; $k = 3; echo kPrimeFactor($n, $k),\"\\n\" ; $n = 14; $k = 3; echo kPrimeFactor($n, $k) ; return 0;} // This code contributed by nitin mittal.?>",
"e": 31912,
"s": 30892,
"text": null
},
{
"code": "<script> // Javascript Program to print kth prime factor // A function to generate prime factors // of a given number n and return k-th // prime factor function kPrimeFactor(n, k) { // Find the number of 2's that // divide k while (n % 2 == 0) { k--; n = n / 2; if (k == 0) return 2; } // n must be odd at this point. // So we can skip one element // (Note i = i +2) for (let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, store i // and divide n while (n % i == 0) { if (k == 1) return i; k--; n = n / i; } } // This condition is to handle the // case where n is a prime number // greater than 2 if (n > 2 && k == 1) return n; return -1; } // Driver code let n = 12, k = 3; document.write(kPrimeFactor(n, k) + \"<br/>\"); n = 14; k = 3; document.write(kPrimeFactor(n, k)); // This code is contributed by susmitakundugoaldanga. </script>",
"e": 33145,
"s": 31912,
"text": null
},
{
"code": null,
"e": 33155,
"s": 33145,
"text": "Output: "
},
{
"code": null,
"e": 33160,
"s": 33155,
"text": "3\n-1"
},
{
"code": null,
"e": 33647,
"s": 33160,
"text": "An Efficient Solution is to use Sieve of Eratosthenes. Note that this solution is efficient when we need k-th prime factor for multiple test cases. For a single case, previous approach is better. The idea is to do preprocessing and store least prime factor of all numbers in given range. Once we have least prime factors stored in an array, we can find k-th prime factor by repeatedly dividing n with least prime factor while it is divisible, then repeating the process for reduced n. "
},
{
"code": null,
"e": 33651,
"s": 33647,
"text": "C++"
},
{
"code": null,
"e": 33656,
"s": 33651,
"text": "Java"
},
{
"code": null,
"e": 33664,
"s": 33656,
"text": "Python3"
},
{
"code": null,
"e": 33667,
"s": 33664,
"text": "C#"
},
{
"code": null,
"e": 33671,
"s": 33667,
"text": "PHP"
},
{
"code": null,
"e": 33682,
"s": 33671,
"text": "Javascript"
},
{
"code": "// C++ program to find k-th prime factor using Sieve Of// Eratosthenes. This program is efficient when we have// a range of numbers.#include<bits/stdc++.h> using namespace std;const int MAX = 10001; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7void sieveOfEratosthenes(int s[]){ // Create a boolean array \"prime[0..MAX]\" and // initialize all entries in it as false. vector <bool> prime(MAX+1, false); // Initializing smallest factor equal to 2 // for all the even numbers for (int i=2; i<=MAX; i+=2) s[i] = 2; // For odd numbers less then equal to n for (int i=3; i<=MAX; i+=2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j=i; j*i<=MAX; j+=2) { if (prime[i*j] == false) { prime[i*j] = true; // i is the smallest prime factor for // number \"i*j\". s[i*j] = i; } } } }} // Function to generate prime factors and return its// k-th prime factor. s[i] stores least prime factor// of i.int kPrimeFactor(int n, int k, int s[]){ // Keep dividing n by least prime factor while // either n is not 1 or count of prime factors // is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver Programint main(){ // s[i] is going to store prime factor // of i. int s[MAX+1]; memset(s, -1, sizeof(s)); sieveOfEratosthenes(s); int n = 12, k = 3; cout << kPrimeFactor(n, k, s) << endl; n = 14, k = 3; cout << kPrimeFactor(n, k, s) << endl; return 0;}",
"e": 35699,
"s": 33682,
"text": null
},
{
"code": "// Java program to find k-th prime factor// using Sieve Of Eratosthenes. This// program is efficient when we have// a range of numbers.class GFG{static int MAX = 10001; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7static void sieveOfEratosthenes(int []s){ // Create a boolean array \"prime[0..MAX]\" and // initialize all entries in it as false. boolean[] prime=new boolean[MAX+1]; // Initializing smallest factor equal to 2 // for all the even numbers for (int i = 2; i <= MAX; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= MAX; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (int j = i; j * i <= MAX; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number \"i*j\". s[i * j] = i; } } } }} // Function to generate prime factors// and return its k-th prime factor.// s[i] stores least prime factor of i.static int kPrimeFactor(int n, int k, int []s){ // Keep dividing n by least // prime factor while either // n is not 1 or count of // prime factors is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver codepublic static void main (String[] args){ // s[i] is going to store prime factor // of i. int[] s = new int[MAX + 1]; sieveOfEratosthenes(s); int n = 12, k = 3; System.out.println(kPrimeFactor(n, k, s)); n = 14; k = 3; System.out.println(kPrimeFactor(n, k, s));}} // This code is contributed by mits",
"e": 37786,
"s": 35699,
"text": null
},
{
"code": "# python3 program to find k-th prime factor using Sieve Of# Eratosthenes. This program is efficient when we have# a range of numbers. MAX = 10001 # Using SieveOfEratosthenes to find smallest prime# factor of all the numbers.# For example, if MAX is 10,# s[2] = s[4] = s[6] = s[10] = 2# s[3] = s[9] = 3# s[5] = 5# s[7] = 7def sieveOfEratosthenes(s): # Create a boolean array \"prime[0..MAX]\" and# initialize all entries in it as false. prime=[False for i in range(MAX+1)] # Initializing smallest factor equal to 2 # for all the even numbers for i in range(2,MAX+1,2): s[i] = 2; # For odd numbers less then equal to n for i in range(3,MAX,2): if (prime[i] == False): # s(i) for a prime is the number itself s[i] = i # For all multiples of current prime number for j in range(i,MAX+1,2): if j*j> MAX: break if (prime[i*j] == False): prime[i*j] = True # i is the smallest prime factor for # number \"i*j\". s[i*j] = i # Function to generate prime factors and return its# k-th prime factor. s[i] stores least prime factor# of i.def kPrimeFactor(n, k, s): # Keep dividing n by least prime factor while # either n is not 1 or count of prime factors # is not k. while (n > 1): if (k == 1): return s[n] # To keep track of count of prime factors k-=1 # Divide n to find next prime factor n //= s[n] return -1 # Driver Program # s[i] is going to store prime factor# of i.s=[-1 for i in range(MAX+1)] sieveOfEratosthenes(s) n = 12k = 3print(kPrimeFactor(n, k, s)) n = 14k = 3print(kPrimeFactor(n, k, s)) # This code is contributed by mohit kumar 29",
"e": 39583,
"s": 37786,
"text": null
},
{
"code": "// C# program to find k-th prime factor// using Sieve Of Eratosthenes. This// program is efficient when we have// a range of numbers and weusing System;class GFG{static int MAX = 10001; // Using SieveOfEratosthenes to find// smallest prime factor of all the// numbers. For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7static void sieveOfEratosthenes(int []s){ // Create a boolean array \"prime[0..MAX]\" // and initialize all entries in it as false. bool[] prime = new bool[MAX + 1]; // Initializing smallest factor equal // to 2 for all the even numbers for (int i = 2; i <= MAX; i += 2) s[i] = 2; // For odd numbers less then equal to n for (int i = 3; i <= MAX; i += 2) { if (prime[i] == false) { // s(i) for a prime is the // number itself s[i] = i; // For all multiples of current // prime number for (int j = i; j * i <= MAX; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor // for number \"i*j\". s[i * j] = i; } } } }} // Function to generate prime factors// and return its k-th prime factor.// s[i] stores least prime factor of i.static int kPrimeFactor(int n, int k, int []s){ // Keep dividing n by least prime // factor while either n is not 1 // or count of prime factors is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of // prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver Codestatic void Main(){ // s[i] is going to store prime // factor of i. int[] s = new int[MAX + 1]; sieveOfEratosthenes(s); int n = 12, k = 3; Console.WriteLine(kPrimeFactor(n, k, s)); n = 14; k = 3; Console.WriteLine(kPrimeFactor(n, k, s));}} // This code is contributed by mits",
"e": 41686,
"s": 39583,
"text": null
},
{
"code": "<?php// PHP program to find k-th prime factor// using Sieve Of Eratosthenes. This program// is efficient when we have a range of numbers. $MAX = 10001; // Using SieveOfEratosthenes to find// smallest prime factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7function sieveOfEratosthenes(&$s){ global $MAX; // Create a boolean array \"prime[0..MAX]\" // and initialize all entries in it as false. $prime = array_fill(0, $MAX + 1, false); // Initializing smallest factor equal // to 2 for all the even numbers for ($i = 2; $i <= $MAX; $i += 2) $s[$i] = 2; // For odd numbers less then equal to n for ($i = 3; $i <= $MAX; $i += 2) { if ($prime[$i] == false) { // s(i) for a prime is the // number itself $s[$i] = $i; // For all multiples of current // prime number for ($j = $i; $j * $i <= $MAX; $j += 2) { if ($prime[$i * $j] == false) { $prime[$i * $j] = true; // i is the smallest prime // factor for number \"i*j\". $s[$i * $j] = $i; } } } }} // Function to generate prime factors and// return its k-th prime factor. s[i] stores// least prime factor of i.function kPrimeFactor($n, $k, $s){ // Keep dividing n by least prime // factor while either n is not 1 // or count of prime factors is not k. while ($n > 1) { if ($k == 1) return $s[$n]; // To keep track of count of // prime factors $k--; // Divide n to find next prime factor $n = (int)($n / $s[$n]); } return -1;} // Driver Code // s[i] is going to store prime// factor of i.$s = array_fill(0, $MAX + 1, -1);sieveOfEratosthenes($s); $n = 12;$k = 3;print(kPrimeFactor($n, $k, $s) . \"\\n\"); $n = 14;$k = 3;print(kPrimeFactor($n, $k, $s)); // This code is contributed by chandan_jnu?>",
"e": 43749,
"s": 41686,
"text": null
},
{
"code": "<script> // Javascript program to find k-th prime factor// using Sieve Of Eratosthenes. This// program is efficient when we have// a range of numbers. var MAX = 10001; // Using SieveOfEratosthenes to find smallest prime// factor of all the numbers.// For example, if MAX is 10,// s[2] = s[4] = s[6] = s[10] = 2// s[3] = s[9] = 3// s[5] = 5// s[7] = 7function sieveOfEratosthenes(s){ // Create a boolean array \"prime[0..MAX]\" and // initialize all entries in it as false. prime=Array.from({length: MAX+1}, (_, i) => false); // Initializing smallest factor equal to 2 // for all the even numbers for (i = 2; i <= MAX; i += 2) s[i] = 2; // For odd numbers less then equal to n for (i = 3; i <= MAX; i += 2) { if (prime[i] == false) { // s(i) for a prime is the number itself s[i] = i; // For all multiples of current prime number for (j = i; j * i <= MAX; j += 2) { if (prime[i * j] == false) { prime[i * j] = true; // i is the smallest prime factor for // number \"i*j\". s[i * j] = i; } } } }} // Function to generate prime factors// and return its k-th prime factor.// s[i] stores least prime factor of i.function kPrimeFactor(n , k , s){ // Keep dividing n by least // prime factor while either // n is not 1 or count of // prime factors is not k. while (n > 1) { if (k == 1) return s[n]; // To keep track of count of prime factors k--; // Divide n to find next prime factor n /= s[n]; } return -1;} // Driver code // s[i] is going to store prime factor// of i.var s = Array.from({length: MAX + 1}, (_, i) => 0);sieveOfEratosthenes(s); var n = 12, k = 3;document.write(kPrimeFactor(n, k, s)+\"<br>\");n = 14;k = 3;document.write(kPrimeFactor(n, k, s)); // This code contributed by shikhasingrajput </script>",
"e": 45778,
"s": 43749,
"text": null
},
{
"code": null,
"e": 45788,
"s": 45778,
"text": "Output: "
},
{
"code": null,
"e": 45793,
"s": 45788,
"text": "3\n-1"
},
{
"code": null,
"e": 46214,
"s": 45793,
"text": "This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 46227,
"s": 46214,
"text": "nitin mittal"
},
{
"code": null,
"e": 46240,
"s": 46227,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 46254,
"s": 46240,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 46269,
"s": 46254,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 46291,
"s": 46269,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 46308,
"s": 46291,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 46317,
"s": 46308,
"text": "gabaa406"
},
{
"code": null,
"e": 46333,
"s": 46317,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 46343,
"s": 46333,
"text": "factorial"
},
{
"code": null,
"e": 46356,
"s": 46343,
"text": "Prime Number"
},
{
"code": null,
"e": 46369,
"s": 46356,
"text": "prime-factor"
},
{
"code": null,
"e": 46375,
"s": 46369,
"text": "sieve"
},
{
"code": null,
"e": 46388,
"s": 46375,
"text": "Mathematical"
},
{
"code": null,
"e": 46401,
"s": 46388,
"text": "Mathematical"
},
{
"code": null,
"e": 46414,
"s": 46401,
"text": "Prime Number"
},
{
"code": null,
"e": 46420,
"s": 46414,
"text": "sieve"
},
{
"code": null,
"e": 46430,
"s": 46420,
"text": "factorial"
},
{
"code": null,
"e": 46528,
"s": 46430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46552,
"s": 46528,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 46595,
"s": 46552,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 46609,
"s": 46595,
"text": "Prime Numbers"
},
{
"code": null,
"e": 46682,
"s": 46609,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 46703,
"s": 46682,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 46746,
"s": 46703,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 46780,
"s": 46746,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 46821,
"s": 46780,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 46874,
"s": 46821,
"text": "Find minimum number of coins that make a given value"
}
]
|
Using Threads in Rust Programming | We know that a process is a program in a running state. The Operating System maintains and manages multiple processes at once. These processes are run on independent parts and these independent parts are known as threads.
Rust provides an implementation of 1:1 threading. It provides different APIs that
handles the case of thread creation, joining, and many such methods.
To create a new thread in Rust, we call the thread::spawn function and then pass it a closure, which in turn contains the code that we want to run in the new thread.
Consider the example shown below:
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 1..10 {
println!("hey number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..3 {
println!("hey number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}
hey number 1 from the main thread!
hey number 1 from the spawned thread!
hey number 2 from the main thread!
hey number 2 from the spawned thread!
There are chances that a spawned thread might not run, and to handle that case, we store the value returned from thread::spawn in a variable. The return type of thread::spawn is JoinHandle.
A JoinHandle is an owned value that, when we call the join method on it, will wait for its thread to finish
Let’s modify the example shown above just slightly, like this:
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hey number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
handle.join().unwrap();
for i in 1..5 {
println!("hey number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}
hey number 1 from the spawned thread!
hey number 2 from the spawned thread!
hey number 3 from the spawned thread!
hey number 4 from the spawned thread!
hey number 5 from the spawned thread!
hey number 6 from the spawned thread!
hey number 7 from the spawned thread!
hey number 8 from the spawned thread!
hey number 9 from the spawned thread!
hey number 1 from the main thread!
hey number 2 from the main thread! | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "We know that a process is a program in a running state. The Operating System maintains and manages multiple processes at once. These processes are run on independent parts and these independent parts are known as threads."
},
{
"code": null,
"e": 1435,
"s": 1284,
"text": "Rust provides an implementation of 1:1 threading. It provides different APIs that\nhandles the case of thread creation, joining, and many such methods."
},
{
"code": null,
"e": 1601,
"s": 1435,
"text": "To create a new thread in Rust, we call the thread::spawn function and then pass it a closure, which in turn contains the code that we want to run in the new thread."
},
{
"code": null,
"e": 1635,
"s": 1601,
"text": "Consider the example shown below:"
},
{
"code": null,
"e": 1996,
"s": 1635,
"text": "use std::thread;\nuse std::time::Duration;\n\nfn main() {\n thread::spawn(|| {\n for i in 1..10 {\n println!(\"hey number {} from the spawned thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n });\n\n for i in 1..3 {\n println!(\"hey number {} from the main thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n}"
},
{
"code": null,
"e": 2142,
"s": 1996,
"text": "hey number 1 from the main thread!\nhey number 1 from the spawned thread!\nhey number 2 from the main thread!\nhey number 2 from the spawned thread!"
},
{
"code": null,
"e": 2332,
"s": 2142,
"text": "There are chances that a spawned thread might not run, and to handle that case, we store the value returned from thread::spawn in a variable. The return type of thread::spawn is JoinHandle."
},
{
"code": null,
"e": 2440,
"s": 2332,
"text": "A JoinHandle is an owned value that, when we call the join method on it, will wait for its thread to finish"
},
{
"code": null,
"e": 2503,
"s": 2440,
"text": "Let’s modify the example shown above just slightly, like this:"
},
{
"code": null,
"e": 2903,
"s": 2503,
"text": "use std::thread;\nuse std::time::Duration;\n\nfn main() {\n let handle = thread::spawn(|| {\n for i in 1..10 {\n println!(\"hey number {} from the spawned thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n });\n handle.join().unwrap();\n for i in 1..5 {\n println!(\"hey number {} from the main thread!\", i);\n thread::sleep(Duration::from_millis(1));\n }\n}"
},
{
"code": null,
"e": 3315,
"s": 2903,
"text": "hey number 1 from the spawned thread!\nhey number 2 from the spawned thread!\nhey number 3 from the spawned thread!\nhey number 4 from the spawned thread!\nhey number 5 from the spawned thread!\nhey number 6 from the spawned thread!\nhey number 7 from the spawned thread!\nhey number 8 from the spawned thread!\nhey number 9 from the spawned thread!\nhey number 1 from the main thread!\nhey number 2 from the main thread!"
}
]
|
PHP - Sessions | An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.
When a session is started following things happen −
PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.
A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result −
<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
It will produce the following result −
You have visited this page 1in this session.
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is the example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.
There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to another page using SID.
<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
echo ( $msg );
?>
<p>
To continue click following link <br />
<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>
It will produce the following result −
You have visited this page 1in this session.
To continue click following link
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2871,
"s": 2757,
"text": "An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session."
},
{
"code": null,
"e": 3071,
"s": 2871,
"text": "A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit."
},
{
"code": null,
"e": 3249,
"s": 3071,
"text": "The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path."
},
{
"code": null,
"e": 3301,
"s": 3249,
"text": "When a session is started following things happen −"
},
{
"code": null,
"e": 3459,
"s": 3301,
"text": "PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443."
},
{
"code": null,
"e": 3617,
"s": 3459,
"text": "PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443."
},
{
"code": null,
"e": 3735,
"s": 3617,
"text": "A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string."
},
{
"code": null,
"e": 3853,
"s": 3735,
"text": "A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string."
},
{
"code": null,
"e": 4040,
"s": 3853,
"text": "A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443."
},
{
"code": null,
"e": 4227,
"s": 4040,
"text": "A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443."
},
{
"code": null,
"e": 4512,
"s": 4227,
"text": "When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values."
},
{
"code": null,
"e": 4692,
"s": 4512,
"text": "A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration."
},
{
"code": null,
"e": 4958,
"s": 4692,
"text": "A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page."
},
{
"code": null,
"e": 5090,
"s": 4958,
"text": "Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session."
},
{
"code": null,
"e": 5239,
"s": 5090,
"text": "The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session."
},
{
"code": null,
"e": 5320,
"s": 5239,
"text": "Make use of isset() function to check if session variable is already set or not."
},
{
"code": null,
"e": 5403,
"s": 5320,
"text": "Put this code in a test.php file and load this file many times to see the result −"
},
{
"code": null,
"e": 5802,
"s": 5403,
"text": "<?php\n session_start();\n \n if( isset( $_SESSION['counter'] ) ) {\n $_SESSION['counter'] += 1;\n }else {\n $_SESSION['counter'] = 1;\n }\n\t\n $msg = \"You have visited this page \". $_SESSION['counter'];\n $msg .= \"in this session.\";\n?>\n\n<html>\n \n <head>\n <title>Setting up a PHP session</title>\n </head>\n \n <body>\n <?php echo ( $msg ); ?>\n </body>\n \n</html>"
},
{
"code": null,
"e": 5841,
"s": 5802,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5887,
"s": 5841,
"text": "You have visited this page 1in this session.\n"
},
{
"code": null,
"e": 6160,
"s": 5887,
"text": "A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable."
},
{
"code": null,
"e": 6209,
"s": 6160,
"text": "Here is the example to unset a single variable −"
},
{
"code": null,
"e": 6250,
"s": 6209,
"text": "<?php\n unset($_SESSION['counter']);\n?>"
},
{
"code": null,
"e": 6314,
"s": 6250,
"text": "Here is the call which will destroy all the session variables −"
},
{
"code": null,
"e": 6345,
"s": 6314,
"text": "<?php\n session_destroy();\n?>"
},
{
"code": null,
"e": 6506,
"s": 6345,
"text": "You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file."
},
{
"code": null,
"e": 6650,
"s": 6506,
"text": "There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser."
},
{
"code": null,
"e": 6926,
"s": 6650,
"text": "Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs."
},
{
"code": null,
"e": 7042,
"s": 6926,
"text": "The following example demonstrates how to register a variable, and how to link correctly to another page using SID."
},
{
"code": null,
"e": 7437,
"s": 7042,
"text": "<?php\n session_start();\n \n if (isset($_SESSION['counter'])) {\n $_SESSION['counter'] = 1;\n }else {\n $_SESSION['counter']++;\n }\n \n $msg = \"You have visited this page \". $_SESSION['counter'];\n $msg .= \"in this session.\";\n \n echo ( $msg );\n?>\n\n<p>\n To continue click following link <br />\n \n <a href = \"nextpage.php?<?php echo htmlspecialchars(SID); ?>\">\n</p>"
},
{
"code": null,
"e": 7476,
"s": 7437,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 7556,
"s": 7476,
"text": "You have visited this page 1in this session.\nTo continue click following link \n"
},
{
"code": null,
"e": 7654,
"s": 7556,
"text": "The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks."
},
{
"code": null,
"e": 7687,
"s": 7654,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7703,
"s": 7687,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7736,
"s": 7703,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7747,
"s": 7736,
"text": " Syed Raza"
},
{
"code": null,
"e": 7782,
"s": 7747,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7799,
"s": 7782,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7832,
"s": 7799,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7847,
"s": 7832,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 7882,
"s": 7847,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 7894,
"s": 7882,
"text": " Azaz Patel"
},
{
"code": null,
"e": 7929,
"s": 7894,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7957,
"s": 7929,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 7964,
"s": 7957,
"text": " Print"
},
{
"code": null,
"e": 7975,
"s": 7964,
"text": " Add Notes"
}
]
|
Tryit Editor v3.7 | Tryit: Different HSLA colors | []
|
Converting ArrayList to HashMap in Java 8 using a Lambda Expression - GeeksforGeeks | 17 Aug, 2021
A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap.
Syntax:
(parms1, parms2) -> expression
Examples:
Input : List : [1="1", 2="2", 3="3"]
Output: Map : {1=1, 2=2, 3=3, 4=4, 5=5}
Input : List : [1="I", 2="love", 3="Geeks" , 4="for" , 5="Geeks"]
Output: Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Approach:
Get the List to be converted into MapCreate an empty MapPut the list values to the map using Lambda ExpressionReturn the formed Map
Get the List to be converted into Map
Create an empty Map
Put the list values to the map using Lambda Expression
Return the formed Map
Below is the implementation of the above approach.
Java
// Converting ArrayList to HashMap// in Java 8 using a Lambda Expressionimport java.util.*;import java.util.ArrayList;import java.util.Scanner; // here we are making a class , and we will makeclass ListItems { // key will act as an id of the value private Integer key; // value will be the value of the above key private String value; // create constructor for reference public ListItems(Integer id, String name) { // assigning the value of key and value this.key = id; this.value = name; } // return private variable key public Integer getkey() { return key; } // return private variable name public String getvalue() { return value; }}class Main { public static void main(String[] args) { // Write your code here // Creating a List of type ListItems using ArrayList List<ListItems> list = new ArrayList<ListItems>(); // add the member of list list.add(new ListItems(1, "I")); list.add(new ListItems(2, "Love")); list.add(new ListItems(3, "Geeks")); list.add(new ListItems(4, "For")); list.add(new ListItems(5, "Geeks")); // Map which will store the list items Map<Integer, String> map = new HashMap<>(); // for (ListItems n : list) { map.put(n.getkey(), // n.getvalue()); } // the below lambda performs the same task as the // above given for loop will do // put the list items in the Map list.forEach( (n) -> { map.put(n.getkey(), n.getvalue()); }); // Printing the given map System.out.println("Map : " + map); }}
Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}
Time Complexity: O(N), where N is the length of Arraylist.
sagartomar9927
Java 8
Java-ArrayList
Java-HashMap
java-lambda
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 23749,
"s": 23557,
"text": "A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap."
},
{
"code": null,
"e": 23757,
"s": 23749,
"text": "Syntax:"
},
{
"code": null,
"e": 23788,
"s": 23757,
"text": "(parms1, parms2) -> expression"
},
{
"code": null,
"e": 23798,
"s": 23788,
"text": "Examples:"
},
{
"code": null,
"e": 23997,
"s": 23798,
"text": "Input : List : [1=\"1\", 2=\"2\", 3=\"3\"]\nOutput: Map : {1=1, 2=2, 3=3, 4=4, 5=5}\n\nInput : List : [1=\"I\", 2=\"love\", 3=\"Geeks\" , 4=\"for\" , 5=\"Geeks\"]\nOutput: Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}"
},
{
"code": null,
"e": 24007,
"s": 23997,
"text": "Approach:"
},
{
"code": null,
"e": 24139,
"s": 24007,
"text": "Get the List to be converted into MapCreate an empty MapPut the list values to the map using Lambda ExpressionReturn the formed Map"
},
{
"code": null,
"e": 24177,
"s": 24139,
"text": "Get the List to be converted into Map"
},
{
"code": null,
"e": 24197,
"s": 24177,
"text": "Create an empty Map"
},
{
"code": null,
"e": 24252,
"s": 24197,
"text": "Put the list values to the map using Lambda Expression"
},
{
"code": null,
"e": 24274,
"s": 24252,
"text": "Return the formed Map"
},
{
"code": null,
"e": 24325,
"s": 24274,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 24330,
"s": 24325,
"text": "Java"
},
{
"code": "// Converting ArrayList to HashMap// in Java 8 using a Lambda Expressionimport java.util.*;import java.util.ArrayList;import java.util.Scanner; // here we are making a class , and we will makeclass ListItems { // key will act as an id of the value private Integer key; // value will be the value of the above key private String value; // create constructor for reference public ListItems(Integer id, String name) { // assigning the value of key and value this.key = id; this.value = name; } // return private variable key public Integer getkey() { return key; } // return private variable name public String getvalue() { return value; }}class Main { public static void main(String[] args) { // Write your code here // Creating a List of type ListItems using ArrayList List<ListItems> list = new ArrayList<ListItems>(); // add the member of list list.add(new ListItems(1, \"I\")); list.add(new ListItems(2, \"Love\")); list.add(new ListItems(3, \"Geeks\")); list.add(new ListItems(4, \"For\")); list.add(new ListItems(5, \"Geeks\")); // Map which will store the list items Map<Integer, String> map = new HashMap<>(); // for (ListItems n : list) { map.put(n.getkey(), // n.getvalue()); } // the below lambda performs the same task as the // above given for loop will do // put the list items in the Map list.forEach( (n) -> { map.put(n.getkey(), n.getvalue()); }); // Printing the given map System.out.println(\"Map : \" + map); }}",
"e": 25970,
"s": 24330,
"text": null
},
{
"code": null,
"e": 26015,
"s": 25970,
"text": "Map : {1=I, 2=Love, 3=Geeks, 4=For, 5=Geeks}"
},
{
"code": null,
"e": 26074,
"s": 26015,
"text": "Time Complexity: O(N), where N is the length of Arraylist."
},
{
"code": null,
"e": 26091,
"s": 26076,
"text": "sagartomar9927"
},
{
"code": null,
"e": 26098,
"s": 26091,
"text": "Java 8"
},
{
"code": null,
"e": 26113,
"s": 26098,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 26126,
"s": 26113,
"text": "Java-HashMap"
},
{
"code": null,
"e": 26138,
"s": 26126,
"text": "java-lambda"
},
{
"code": null,
"e": 26145,
"s": 26138,
"text": "Picked"
},
{
"code": null,
"e": 26169,
"s": 26145,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26174,
"s": 26169,
"text": "Java"
},
{
"code": null,
"e": 26188,
"s": 26174,
"text": "Java Programs"
},
{
"code": null,
"e": 26207,
"s": 26188,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26212,
"s": 26207,
"text": "Java"
},
{
"code": null,
"e": 26310,
"s": 26212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26319,
"s": 26310,
"text": "Comments"
},
{
"code": null,
"e": 26332,
"s": 26319,
"text": "Old Comments"
},
{
"code": null,
"e": 26362,
"s": 26332,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26377,
"s": 26362,
"text": "Stream In Java"
},
{
"code": null,
"e": 26398,
"s": 26377,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26444,
"s": 26398,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26463,
"s": 26444,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26507,
"s": 26463,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26533,
"s": 26507,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26567,
"s": 26533,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 26614,
"s": 26567,
"text": "Implementing a Linked List in Java using Class"
}
]
|
Abstraction in C++ - GeeksforGeeks | 30 May, 2018
Data abstraction is one of the most essential and important feature of object oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.
Consider a real life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.Abstraction using Classes: We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating power of numbers.
Abstraction using access specifiers
Access specifiers are the main pillar of implementing abstraction in C++. We can use access specifiers to enforce restrictions on class members. For example:
Members declared as public in a class, can be accessed from anywhere in the program.
Members declared as private in a class, can be accessed only from within the class. They are not allowed to be accessed from any part of code outside the class.
We can easily implement abstraction using the above two features provided by access specifiers. Say, the members that defines the internal implementation can be marked as private in a class. And the important information needed to be given to the outside world can be marked as public. And these public members can access the private members as they are inside the class.
Example:
#include <iostream>using namespace std; class implementAbstraction{ private: int a, b; public: // method to set values of // private members void set(int x, int y) { a = x; b = y; } void display() { cout<<"a = " <<a << endl; cout<<"b = " << b << endl; }}; int main() { implementAbstraction obj; obj.set(10, 20); obj.display(); return 0;}
Output:
a = 10
b = 20
You can see in the above program we are not allowed to access the variables a and b directly, however one can call the function set() to set the values in a and b and the function display() to display the values of a and b.
Advantages of Data Abstraction:
Helps the user to avoid writing the low level code
Avoids code duplication and increases reusability.
Can change internal implementation of class independently without affecting the user.
Helps to increase security of an application or program as only important details are provided to the user.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-class
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
Virtual Function in C++
vector erase() and clear() in C++
rand() and srand() in C/C++
Templates in C++ with Examples
unordered_map in C++ STL | [
{
"code": null,
"e": 26569,
"s": 26541,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 26906,
"s": 26569,
"text": "Data abstraction is one of the most essential and important feature of object oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation."
},
{
"code": null,
"e": 27568,
"s": 26906,
"text": "Consider a real life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.Abstraction using Classes: We can implement Abstraction in C++ using classes. Class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to outside world and which is not."
},
{
"code": null,
"e": 27990,
"s": 27568,
"text": "Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating power of numbers."
},
{
"code": null,
"e": 28026,
"s": 27990,
"text": "Abstraction using access specifiers"
},
{
"code": null,
"e": 28184,
"s": 28026,
"text": "Access specifiers are the main pillar of implementing abstraction in C++. We can use access specifiers to enforce restrictions on class members. For example:"
},
{
"code": null,
"e": 28269,
"s": 28184,
"text": "Members declared as public in a class, can be accessed from anywhere in the program."
},
{
"code": null,
"e": 28430,
"s": 28269,
"text": "Members declared as private in a class, can be accessed only from within the class. They are not allowed to be accessed from any part of code outside the class."
},
{
"code": null,
"e": 28802,
"s": 28430,
"text": "We can easily implement abstraction using the above two features provided by access specifiers. Say, the members that defines the internal implementation can be marked as private in a class. And the important information needed to be given to the outside world can be marked as public. And these public members can access the private members as they are inside the class."
},
{
"code": null,
"e": 28811,
"s": 28802,
"text": "Example:"
},
{
"code": "#include <iostream>using namespace std; class implementAbstraction{ private: int a, b; public: // method to set values of // private members void set(int x, int y) { a = x; b = y; } void display() { cout<<\"a = \" <<a << endl; cout<<\"b = \" << b << endl; }}; int main() { implementAbstraction obj; obj.set(10, 20); obj.display(); return 0;}",
"e": 29295,
"s": 28811,
"text": null
},
{
"code": null,
"e": 29303,
"s": 29295,
"text": "Output:"
},
{
"code": null,
"e": 29318,
"s": 29303,
"text": "a = 10\nb = 20\n"
},
{
"code": null,
"e": 29542,
"s": 29318,
"text": "You can see in the above program we are not allowed to access the variables a and b directly, however one can call the function set() to set the values in a and b and the function display() to display the values of a and b."
},
{
"code": null,
"e": 29574,
"s": 29542,
"text": "Advantages of Data Abstraction:"
},
{
"code": null,
"e": 29625,
"s": 29574,
"text": "Helps the user to avoid writing the low level code"
},
{
"code": null,
"e": 29676,
"s": 29625,
"text": "Avoids code duplication and increases reusability."
},
{
"code": null,
"e": 29762,
"s": 29676,
"text": "Can change internal implementation of class independently without affecting the user."
},
{
"code": null,
"e": 29870,
"s": 29762,
"text": "Helps to increase security of an application or program as only important details are provided to the user."
},
{
"code": null,
"e": 30171,
"s": 29870,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30296,
"s": 30171,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30306,
"s": 30296,
"text": "cpp-class"
},
{
"code": null,
"e": 30310,
"s": 30306,
"text": "C++"
},
{
"code": null,
"e": 30314,
"s": 30310,
"text": "CPP"
},
{
"code": null,
"e": 30412,
"s": 30314,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30421,
"s": 30412,
"text": "Comments"
},
{
"code": null,
"e": 30434,
"s": 30421,
"text": "Old Comments"
},
{
"code": null,
"e": 30452,
"s": 30434,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30498,
"s": 30452,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30521,
"s": 30498,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 30548,
"s": 30521,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30576,
"s": 30548,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30600,
"s": 30576,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 30634,
"s": 30600,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 30662,
"s": 30634,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 30693,
"s": 30662,
"text": "Templates in C++ with Examples"
}
]
|
Difference Between Streams and Collections in Java | 27 May, 2022
Collection is an in-memory data structure, which holds all the values that the data structure currently has. Every element in the Collection has to be computed before we add it to the Collection. Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a Collection. It provides many interfaces like (Set, List, Queue, Deque) and Classes like (ArrayList, Vector, LinkedList, PriorityQueue, HashSet).
On the other hand, IStream is an API that is introduced in Java 8 which is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The Stream API is used to process collections of objects.
Main features of the Java stream are as follows:
A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels.
Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
Each intermediate operation is lazily executed and returns another stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Example 1: Collections
Java
// Java Program to Illustrate Collection // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of list List<String> CompanyList = new ArrayList<>(); // Adding elements using add() method CompanyList.add("Google"); CompanyList.add("Apple"); CompanyList.add("Microsoft"); // Now creating a comparator Comparator<String> com = (String o1, String o2) -> o1.compareTo(o2); // Sorting the list Collections.sort(CompanyList, com); // Iterating using for each loop for (String name : CompanyList) { // Printing the elements System.out.println(name); } }}
Apple
Google
Microsoft
Example: Streams
Java
// Java Program to Demonstrate streams // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty Arraylist List<String> CompanyList = new ArrayList<>(); // Adding elements to above ArrayList CompanyList.add("Google"); CompanyList.add("Apple"); CompanyList.add("Microsoft"); // Sorting the list // using sorted() method and // printing using for-each loop CompanyList.stream().sorted().forEach( System.out::println); }}
Apple
Google
Microsoft
Let us tabulate the difference between them which is as follows:
STREAMS
COLLECTIONS
solankimayank
niteeshasd
Java-Collections
java-stream
Difference Between
Java
Java
Java-Collections
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
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Stack vs Heap Memory Allocation
Difference between Clustered and Non-clustered index
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 468,
"s": 28,
"text": "Collection is an in-memory data structure, which holds all the values that the data structure currently has. Every element in the Collection has to be computed before we add it to the Collection. Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a Collection. It provides many interfaces like (Set, List, Queue, Deque) and Classes like (ArrayList, Vector, LinkedList, PriorityQueue, HashSet)."
},
{
"code": null,
"e": 759,
"s": 468,
"text": "On the other hand, IStream is an API that is introduced in Java 8 which is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The Stream API is used to process collections of objects."
},
{
"code": null,
"e": 808,
"s": 759,
"text": "Main features of the Java stream are as follows:"
},
{
"code": null,
"e": 911,
"s": 808,
"text": "A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels."
},
{
"code": null,
"e": 1020,
"s": 911,
"text": "Streams don’t change the original data structure, they only provide the result as per the pipelined methods."
},
{
"code": null,
"e": 1233,
"s": 1020,
"text": "Each intermediate operation is lazily executed and returns another stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result."
},
{
"code": null,
"e": 1256,
"s": 1233,
"text": "Example 1: Collections"
},
{
"code": null,
"e": 1261,
"s": 1256,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Collection // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of list List<String> CompanyList = new ArrayList<>(); // Adding elements using add() method CompanyList.add(\"Google\"); CompanyList.add(\"Apple\"); CompanyList.add(\"Microsoft\"); // Now creating a comparator Comparator<String> com = (String o1, String o2) -> o1.compareTo(o2); // Sorting the list Collections.sort(CompanyList, com); // Iterating using for each loop for (String name : CompanyList) { // Printing the elements System.out.println(name); } }}",
"e": 2074,
"s": 1261,
"text": null
},
{
"code": null,
"e": 2097,
"s": 2074,
"text": "Apple\nGoogle\nMicrosoft"
},
{
"code": null,
"e": 2115,
"s": 2097,
"text": " Example: Streams"
},
{
"code": null,
"e": 2120,
"s": 2115,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate streams // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty Arraylist List<String> CompanyList = new ArrayList<>(); // Adding elements to above ArrayList CompanyList.add(\"Google\"); CompanyList.add(\"Apple\"); CompanyList.add(\"Microsoft\"); // Sorting the list // using sorted() method and // printing using for-each loop CompanyList.stream().sorted().forEach( System.out::println); }}",
"e": 2752,
"s": 2120,
"text": null
},
{
"code": null,
"e": 2775,
"s": 2752,
"text": "Apple\nGoogle\nMicrosoft"
},
{
"code": null,
"e": 2840,
"s": 2775,
"text": "Let us tabulate the difference between them which is as follows:"
},
{
"code": null,
"e": 2860,
"s": 2840,
"text": " STREAMS "
},
{
"code": null,
"e": 2884,
"s": 2860,
"text": " COLLECTIONS "
},
{
"code": null,
"e": 2898,
"s": 2884,
"text": "solankimayank"
},
{
"code": null,
"e": 2909,
"s": 2898,
"text": "niteeshasd"
},
{
"code": null,
"e": 2926,
"s": 2909,
"text": "Java-Collections"
},
{
"code": null,
"e": 2938,
"s": 2926,
"text": "java-stream"
},
{
"code": null,
"e": 2957,
"s": 2938,
"text": "Difference Between"
},
{
"code": null,
"e": 2962,
"s": 2957,
"text": "Java"
},
{
"code": null,
"e": 2967,
"s": 2962,
"text": "Java"
},
{
"code": null,
"e": 2984,
"s": 2967,
"text": "Java-Collections"
},
{
"code": null,
"e": 3082,
"s": 2984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3143,
"s": 3082,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3211,
"s": 3143,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 3248,
"s": 3211,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 3280,
"s": 3248,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 3333,
"s": 3280,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 3348,
"s": 3333,
"text": "Arrays in Java"
},
{
"code": null,
"e": 3384,
"s": 3348,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 3428,
"s": 3384,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 3453,
"s": 3428,
"text": "Reverse a string in Java"
}
]
|
Introduction of 4th and 5th Normal form in DBMS | 02 Feb, 2022
Prerequisite – Functional Dependency, Database Normalization, Normal Forms If two or more independent relation are kept in a single relation or we can say multivalue dependency occurs when the presence of one or more rows in a table implies the presence of one or more other rows in that same table. Put another way, two attributes (or columns) in a table are independent of one another, but both depend on a third attribute. A multivalued dependency always requires at least three attributes because it consists of at least two attributes that are dependent on a third.
For a dependency A -> B, if for a single value of A, multiple value of B exists, then the table may have multi-valued dependency. The table should have at least 3 attributes and B and C should be independent for A ->> B multivalued dependency. For example,
Person->-> mobile,
Person ->-> food_likes
This is read as “person multidetermines mobile” and “person multidetermines food_likes.”
Note that a functional dependency is a special case of multivalued dependency. In a functional dependency X -> Y, every x determines exactly one y, never more than one.
Fourth normal form (4NF) is a level of database normalization where there are no non-trivial multivalued dependencies other than a candidate key. It builds on the first three normal forms (1NF, 2NF and 3NF) and the Boyce-Codd Normal Form (BCNF). It states that, in addition to a database meeting the requirements of BCNF, it must not contain more than one multivalued dependency.
Properties – A relation R is in 4NF if and only if the following conditions are satisfied:
It should be in the Boyce-Codd Normal Form (BCNF).the table should not have any Multi-valued Dependency.
It should be in the Boyce-Codd Normal Form (BCNF).
the table should not have any Multi-valued Dependency.
A table with a multivalued dependency violates the normalization standard of Fourth Normal Form (4NK) because it creates unnecessary redundancies and can contribute to inconsistent data. To bring this up to 4NF, it is necessary to break this information into two tables.
Example – Consider the database table of a class which has two relations R1 contains student ID(SID) and student name (SNAME) and R2 contains course id(CID) and course name (CNAME).
Table – R1(SID, SNAME)
Table – R2(CID, CNAME)
When there cross product is done it resulted in multivalued dependencies:
Table – R1 X R2
Multivalued dependencies (MVD) are:
SID->->CID; SID->->CNAME; SNAME->->CNAME
Joint dependency – Join decomposition is a further generalization of Multivalued dependencies. If the join of R1 and R2 over C is equal to relation R then we can say that a join dependency (JD) exists, where R1 and R2 are the decomposition R1(A, B, C) and R2(C, D) of a given relations R (A, B, C, D). Alternatively, R1 and R2 are a lossless decomposition of R. A JD ⋈ {R1, R2, ..., Rn} is said to hold over a relation R if R1, R2, ....., Rn is a lossless-join decomposition. The *(A, B, C, D), (C, D) will be a JD of R if the join of join’s attribute is equal to the relation R. Here, *(R1, R2, R3) is used to indicate that relation R1, R2, R3 and so on are a JD of R.
Let R is a relation schema R1, R2, R3........Rn be the decomposition of R. r( R ) is said to satisfy join dependency if and only if
Example –
Table – R1
Company->->Product
Table – R2
Agent->->Company
Table – R3
Agent->->Product
Table – R1⋈R2⋈R3
Agent->->Product
A relation R is in 5NF if and only if every join dependency in R is implied by the candidate keys of R. A relation decomposed into two relations must have loss-less join Property, which ensures that no spurious or extra tuples are generated, when relations are reunited through a natural join.
Properties – A relation R is in 5NF if and only if it satisfies following conditions:
R should be already in 4NF. It cannot be further non loss decomposed (join dependency)
R should be already in 4NF.
It cannot be further non loss decomposed (join dependency)
Example – Consider the above schema, with a case as “if a company makes a product and an agent is an agent for that company, then he always sells that product for the company”. Under these circumstances, the ACP table is shown as:
Table – ACP
The relation ACP is again decompose into 3 relations. Now, the natural Join of all the three relations will be shown as:
Table – R1
Table – R2
Table – R3
Result of Natural Join of R1 and R3 over ‘Company’ and then Natural Join of R13 and R2 over ‘Agent’and ‘Product’ will be table ACP.
Hence, in this example, all the redundancies are eliminated, and the decomposition of ACP is a lossless join decomposition. Therefore, the relation is in 5NF as it does not violate the property of lossless join.
krsudhir002
DBMS-Normalization
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 624,
"s": 52,
"text": "Prerequisite – Functional Dependency, Database Normalization, Normal Forms If two or more independent relation are kept in a single relation or we can say multivalue dependency occurs when the presence of one or more rows in a table implies the presence of one or more other rows in that same table. Put another way, two attributes (or columns) in a table are independent of one another, but both depend on a third attribute. A multivalued dependency always requires at least three attributes because it consists of at least two attributes that are dependent on a third. "
},
{
"code": null,
"e": 882,
"s": 624,
"text": "For a dependency A -> B, if for a single value of A, multiple value of B exists, then the table may have multi-valued dependency. The table should have at least 3 attributes and B and C should be independent for A ->> B multivalued dependency. For example, "
},
{
"code": null,
"e": 929,
"s": 886,
"text": "Person->-> mobile,\nPerson ->-> food_likes "
},
{
"code": null,
"e": 1019,
"s": 929,
"text": "This is read as “person multidetermines mobile” and “person multidetermines food_likes.” "
},
{
"code": null,
"e": 1189,
"s": 1019,
"text": "Note that a functional dependency is a special case of multivalued dependency. In a functional dependency X -> Y, every x determines exactly one y, never more than one. "
},
{
"code": null,
"e": 1572,
"s": 1191,
"text": "Fourth normal form (4NF) is a level of database normalization where there are no non-trivial multivalued dependencies other than a candidate key. It builds on the first three normal forms (1NF, 2NF and 3NF) and the Boyce-Codd Normal Form (BCNF). It states that, in addition to a database meeting the requirements of BCNF, it must not contain more than one multivalued dependency. "
},
{
"code": null,
"e": 1665,
"s": 1572,
"text": "Properties – A relation R is in 4NF if and only if the following conditions are satisfied: "
},
{
"code": null,
"e": 1770,
"s": 1665,
"text": "It should be in the Boyce-Codd Normal Form (BCNF).the table should not have any Multi-valued Dependency."
},
{
"code": null,
"e": 1821,
"s": 1770,
"text": "It should be in the Boyce-Codd Normal Form (BCNF)."
},
{
"code": null,
"e": 1876,
"s": 1821,
"text": "the table should not have any Multi-valued Dependency."
},
{
"code": null,
"e": 2148,
"s": 1876,
"text": "A table with a multivalued dependency violates the normalization standard of Fourth Normal Form (4NK) because it creates unnecessary redundancies and can contribute to inconsistent data. To bring this up to 4NF, it is necessary to break this information into two tables. "
},
{
"code": null,
"e": 2331,
"s": 2148,
"text": "Example – Consider the database table of a class which has two relations R1 contains student ID(SID) and student name (SNAME) and R2 contains course id(CID) and course name (CNAME). "
},
{
"code": null,
"e": 2355,
"s": 2331,
"text": "Table – R1(SID, SNAME) "
},
{
"code": null,
"e": 2380,
"s": 2355,
"text": "Table – R2(CID, CNAME) "
},
{
"code": null,
"e": 2455,
"s": 2380,
"text": "When there cross product is done it resulted in multivalued dependencies: "
},
{
"code": null,
"e": 2472,
"s": 2455,
"text": "Table – R1 X R2 "
},
{
"code": null,
"e": 2510,
"s": 2472,
"text": "Multivalued dependencies (MVD) are: "
},
{
"code": null,
"e": 2552,
"s": 2510,
"text": " SID->->CID; SID->->CNAME; SNAME->->CNAME"
},
{
"code": null,
"e": 3223,
"s": 2552,
"text": "Joint dependency – Join decomposition is a further generalization of Multivalued dependencies. If the join of R1 and R2 over C is equal to relation R then we can say that a join dependency (JD) exists, where R1 and R2 are the decomposition R1(A, B, C) and R2(C, D) of a given relations R (A, B, C, D). Alternatively, R1 and R2 are a lossless decomposition of R. A JD ⋈ {R1, R2, ..., Rn} is said to hold over a relation R if R1, R2, ....., Rn is a lossless-join decomposition. The *(A, B, C, D), (C, D) will be a JD of R if the join of join’s attribute is equal to the relation R. Here, *(R1, R2, R3) is used to indicate that relation R1, R2, R3 and so on are a JD of R. "
},
{
"code": null,
"e": 3356,
"s": 3223,
"text": "Let R is a relation schema R1, R2, R3........Rn be the decomposition of R. r( R ) is said to satisfy join dependency if and only if "
},
{
"code": null,
"e": 3367,
"s": 3356,
"text": "Example – "
},
{
"code": null,
"e": 3379,
"s": 3367,
"text": "Table – R1 "
},
{
"code": null,
"e": 3399,
"s": 3379,
"text": "Company->->Product "
},
{
"code": null,
"e": 3411,
"s": 3399,
"text": "Table – R2 "
},
{
"code": null,
"e": 3429,
"s": 3411,
"text": "Agent->->Company "
},
{
"code": null,
"e": 3441,
"s": 3429,
"text": "Table – R3 "
},
{
"code": null,
"e": 3459,
"s": 3441,
"text": "Agent->->Product "
},
{
"code": null,
"e": 3477,
"s": 3459,
"text": "Table – R1⋈R2⋈R3 "
},
{
"code": null,
"e": 3495,
"s": 3477,
"text": "Agent->->Product "
},
{
"code": null,
"e": 3790,
"s": 3495,
"text": "A relation R is in 5NF if and only if every join dependency in R is implied by the candidate keys of R. A relation decomposed into two relations must have loss-less join Property, which ensures that no spurious or extra tuples are generated, when relations are reunited through a natural join. "
},
{
"code": null,
"e": 3878,
"s": 3790,
"text": "Properties – A relation R is in 5NF if and only if it satisfies following conditions: "
},
{
"code": null,
"e": 3966,
"s": 3878,
"text": "R should be already in 4NF. It cannot be further non loss decomposed (join dependency)"
},
{
"code": null,
"e": 3996,
"s": 3966,
"text": "R should be already in 4NF. "
},
{
"code": null,
"e": 4055,
"s": 3996,
"text": "It cannot be further non loss decomposed (join dependency)"
},
{
"code": null,
"e": 4287,
"s": 4055,
"text": "Example – Consider the above schema, with a case as “if a company makes a product and an agent is an agent for that company, then he always sells that product for the company”. Under these circumstances, the ACP table is shown as: "
},
{
"code": null,
"e": 4300,
"s": 4287,
"text": "Table – ACP "
},
{
"code": null,
"e": 4422,
"s": 4300,
"text": "The relation ACP is again decompose into 3 relations. Now, the natural Join of all the three relations will be shown as: "
},
{
"code": null,
"e": 4434,
"s": 4422,
"text": "Table – R1 "
},
{
"code": null,
"e": 4447,
"s": 4434,
"text": "Table – R2 "
},
{
"code": null,
"e": 4460,
"s": 4447,
"text": "Table – R3 "
},
{
"code": null,
"e": 4593,
"s": 4460,
"text": "Result of Natural Join of R1 and R3 over ‘Company’ and then Natural Join of R13 and R2 over ‘Agent’and ‘Product’ will be table ACP. "
},
{
"code": null,
"e": 4806,
"s": 4593,
"text": "Hence, in this example, all the redundancies are eliminated, and the decomposition of ACP is a lossless join decomposition. Therefore, the relation is in 5NF as it does not violate the property of lossless join. "
},
{
"code": null,
"e": 4818,
"s": 4806,
"text": "krsudhir002"
},
{
"code": null,
"e": 4837,
"s": 4818,
"text": "DBMS-Normalization"
},
{
"code": null,
"e": 4842,
"s": 4837,
"text": "DBMS"
},
{
"code": null,
"e": 4850,
"s": 4842,
"text": "GATE CS"
},
{
"code": null,
"e": 4855,
"s": 4850,
"text": "DBMS"
},
{
"code": null,
"e": 4953,
"s": 4855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5000,
"s": 4953,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 5018,
"s": 5000,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 5059,
"s": 5018,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 5070,
"s": 5059,
"text": "CTE in SQL"
},
{
"code": null,
"e": 5123,
"s": 5070,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 5143,
"s": 5123,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5170,
"s": 5143,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 5183,
"s": 5170,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 5232,
"s": 5183,
"text": "Page Replacement Algorithms in Operating Systems"
}
]
|
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes | 24 Jun, 2022
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to use O(1) extra space.
Input:
List1 = 1->3->30->90->120->240->511
List2 = 0->3->12->32->90->125->240->249
Output: Following is maximum sum linked list out of two input lists
list = 1->3->12->32->90->125->240->511
we switch at 3 and 240 to get above maximum sum linked list
We strongly recommend to minimize the browser and try this yourself first.
The idea here in the below solution is to adjust next pointers after common nodes.
Start with head of both linked lists and find first common node. Use merging technique of sorted linked list for that. Keep track of sum of the elements too while doing this and set head of result list based on greater sum till first common node. After this till the current pointers of both lists don’t become NULL we need to adjust the next of prev pointers based on greater sum.
Start with head of both linked lists and find first common node. Use merging technique of sorted linked list for that.
Keep track of sum of the elements too while doing this and set head of result list based on greater sum till first common node.
After this till the current pointers of both lists don’t become NULL we need to adjust the next of prev pointers based on greater sum.
This way it can be done in-place with constant extra space. Time complexity of the below solution is O(n).
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to construct the maximum sum linked// list out of two given sorted lists#include<bits/stdc++.h>using namespace std; //A linked list nodestruct Node{ int data; //data belong to that node Node *next; //next pointer}; // Push the data to the head of the linked listvoid push(Node **head, int data){ //Allocation memory to the new node Node *newnode = new Node; //Assigning data to the new node newnode->data = data; //Adjusting next pointer of the new node newnode->next = *head; //New node becomes the head of the list *head = newnode;} // Method that adjusts the pointers and prints the final listvoid finalMaxSumList(Node *a, Node *b){ Node *result = NULL; // Assigning pre and cur to the head of the // linked list. Node *pre1 = a, *curr1 = a; Node *pre2 = b, *curr2 = b; // Till either of the current pointers is not // NULL execute the loop while (curr1 != NULL || curr2 != NULL) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur pointer elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1!=NULL && curr2!=NULL && curr1->data!=curr2->data) { if (curr1->data < curr2->data) { sum1 += curr1->data; curr1 = curr1->next; } else // (curr2->data < curr1->data) { sum2 += curr2->data; curr2 = curr2->next; } } // If either of current pointers becomes NULL // carry on the sum calculation for other one. if (curr1 == NULL) { while (curr2 != NULL) { sum2 += curr2->data; curr2 = curr2->next; } } if (curr2 == NULL) { while (curr1 != NULL) { sum1 += curr1->data; curr1 = curr1->next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2)? pre1 : pre2; // If pre1 and pre2 don't contain the head pointers of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2->next = pre1->next; else pre1->next = pre2->next; } // Adjusting previous pointers pre1 = curr1, pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1) curr1 = curr1->next; // If curr2 is not NULL move to the next. if (curr2) curr2 = curr2->next; } // Print the resultant list. while (result != NULL) { cout << result->data << " "; result = result->next; }} //Main driver programint main(){ //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL Node *head1 = NULL, *head2 = NULL; push(&head1, 120); push(&head1, 110); push(&head1, 90); push(&head1, 30); push(&head1, 3); push(&head1, 1); push(&head2, 130); push(&head2, 120); push(&head2, 100); push(&head2, 90); push(&head2, 32); push(&head2, 12); push(&head2, 3); push(&head2, 0); finalMaxSumList(head1, head2); return 0;}
// Java program to construct a Maximum Sum Linked List out of// two Sorted Linked Lists having some Common nodesclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } // Method to adjust pointers and print final list void finalMaxSumList(Node a, Node b) { Node result = null; /* assigning pre and cur to head of the linked list */ Node pre1 = a, curr1 = a; Node pre2 = b, curr2 = b; /* Till either of current pointers is not null execute the loop */ while (curr1 != null || curr2 != null) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur reference elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1 != null && curr2 != null && curr1.data != curr2.data) { if (curr1.data<curr2.data) { sum1 += curr1.data; curr1 = curr1.next; } else { sum2 += curr2.data; curr2 = curr2.next; } } // If either of current pointers becomes null // carry on the sum calculation for other one. if (curr1 == null) { while (curr2 != null) { sum2 += curr2.data; curr2 = curr2.next; } } if (curr2 == null) { while(curr1 != null) { sum1 += curr1.data; curr1 = curr1.next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2) ? pre1 : pre2; // If pre1 and pre2 don't contain the head references of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2.next = pre1.next; else pre1.next = pre2.next; } // Adjusting previous pointers pre1 = curr1; pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1 != null) curr1 = curr1.next; // If curr2 is not NULL move to the next. if (curr2 != null) curr2 = curr2.next; } while (result != null) { System.out.print(result.data + " "); result = result.next; } System.out.println(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120); llist1.push(110); llist1.push(90); llist1.push(30); llist1.push(3); llist1.push(1); llist2.push(130); llist2.push(120); llist2.push(100); llist2.push(90); llist2.push(32); llist2.push(12); llist2.push(3); llist2.push(0); llist1.finalMaxSumList(llist1.head, llist2.head); }} /* This code is contributed by Rajat Mishra */
# Python program to construct a Maximum Sum Linked List out of# two Sorted Linked Lists having some Common nodesclass LinkedList(object): def __init__(self): # head of list self.head = None # Linked list Node class Node(object): def __init__(self, d): self.data = d self.next = None # Method to adjust pointers and print final list def finalMaxSumList(self, a, b): result = None # assigning pre and cur to head # of the linked list pre1 = a curr1 = a pre2 = b curr2 = b # Till either of current pointers is not null # execute the loop while curr1 != None or curr2 != None: # Keeping 2 local variables at the start of every # loop run to keep track of the sum between pre # and cur reference elements. sum1 = 0 sum2 = 0 # Calculating sum by traversing the nodes of linked # list as the merging of two linked list. The loop # stops at a common node while curr1 != None and curr2 != None and curr1.data != curr2.data: if curr1.data < curr2.data: sum1 += curr1.data curr1 = curr1.next else: sum2 += curr2.data curr2 = curr2.next # If either of current pointers becomes null # carry on the sum calculation for other one. if curr1 == None: while curr2 != None: sum2 += curr2.data curr2 = curr2.next if curr2 == None: while curr1 != None: sum1 += curr1.data curr1 = curr1.next # First time adjustment of resultant head based on # the maximum sum. if pre1 == a and pre2 == b: result = pre1 if (sum1 > sum2) else pre2 else: # If pre1 and pre2 don't contain the head references of # lists adjust the next pointers of previous pointers. if sum1 > sum2: pre2.next = pre1.next else: pre1.next = pre2.next # Adjusting previous pointers pre1 = curr1 pre2 = curr2 # If curr1 is not NULL move to the next. if curr1 != None: curr1 = curr1.next # If curr2 is not NULL move to the next. if curr2 != None: curr2 = curr2.next while result != None: print (str(result.data),end=" ") result = result.next print () # Utility functions # Inserts a new Node at front of the list. def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Driver programllist1 = LinkedList()llist2 = LinkedList() # Linked List 1 : 1->3->30->90->110->120->NULL# Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120)llist1.push(110)llist1.push(90)llist1.push(30)llist1.push(3)llist1.push(1) llist2.push(130)llist2.push(120)llist2.push(100)llist2.push(90)llist2.push(32)llist2.push(12)llist2.push(3)llist2.push(0) llist1.finalMaxSumList(llist1.head, llist2.head) # This code is contributed by BHAVYA JAIN
// C# program to construct a Maximum// Sum Linked List out of two Sorted// Linked Lists having some Common nodesusing System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Method to adjust pointers // and print final list void finalMaxSumList(Node a, Node b) { Node result = null; /* assigning pre and cur to head of the linked list */ Node pre1 = a, curr1 = a; Node pre2 = b, curr2 = b; /* Till either of current pointers is not null execute the loop */ while (curr1 != null || curr2 != null) { // Keeping 2 local variables at the start // of every loop run to keep track of the // sum between pre and cur reference elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1 != null && curr2 != null && curr1.data != curr2.data) { if (curr1.data<curr2.data) { sum1 += curr1.data; curr1 = curr1.next; } else { sum2 += curr2.data; curr2 = curr2.next; } } // If either of current pointers becomes null // carry on the sum calculation for other one. if (curr1 == null) { while (curr2 != null) { sum2 += curr2.data; curr2 = curr2.next; } } if (curr2 == null) { while(curr1 != null) { sum1 += curr1.data; curr1 = curr1.next; } } // First time adjustment of resultant // head based on the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2) ? pre1 : pre2; // If pre1 and pre2 don't contain // the head references of lists adjust // the next pointers of previous pointers. else { if (sum1 > sum2) pre2.next = pre1.next; else pre1.next = pre2.next; } // Adjusting previous pointers pre1 = curr1; pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1 != null) curr1 = curr1.next; // If curr2 is not NULL move to the next. if (curr2 != null) curr2 = curr2.next; } while (result != null) { Console.Write(result.data + " "); result = result.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Driver code */ public static void Main() { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120); llist1.push(110); llist1.push(90); llist1.push(30); llist1.push(3); llist1.push(1); llist2.push(130); llist2.push(120); llist2.push(100); llist2.push(90); llist2.push(32); llist2.push(12); llist2.push(3); llist2.push(0); llist1.finalMaxSumList(llist1.head, llist2.head); }} /* This code contributed by PrinciRaj1992 */
<script>// javascript program to construct a Maximum Sum Linked List out of// two Sorted Linked Lists having some Common nodesvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } // Method to adjust pointers and print final list function finalMaxSumList(a, b) { var result = null; /* * assigning pre and cur to head of the linked list */ var pre1 = a, curr1 = a; var pre2 = b, curr2 = b; /* * Till either of current pointers is not null execute the loop */ while (curr1 != null || curr2 != null) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur reference elements. var sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1 != null && curr2 != null && curr1.data != curr2.data) { if (curr1.data < curr2.data) { sum1 += curr1.data; curr1 = curr1.next; } else { sum2 += curr2.data; curr2 = curr2.next; } } // If either of current pointers becomes null // carry on the sum calculation for other one. if (curr1 == null) { while (curr2 != null) { sum2 += curr2.data; curr2 = curr2.next; } } if (curr2 == null) { while (curr1 != null) { sum1 += curr1.data; curr1 = curr1.next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2) ? pre1 : pre2; // If pre1 and pre2 don't contain the head references of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2.next = pre1.next; else pre1.next = pre2.next; } // Adjusting previous pointers pre1 = curr1; pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1 != null) curr1 = curr1.next; // If curr2 is not NULL move to the next. if (curr2 != null) curr2 = curr2.next; } while (result != null) { document.write(result.data + " "); result = result.next; } document.write(); } /* Inserts a node at start of linked list */ function push(headl, new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = headl; /* 4. Move the head to point to new Node */ headl = new_node; return headl; } /* Driver program to test above functions */ // Linked List 1 : 1->3->30->90->110->120->NULL // Linked List 2 : 0->3->12->32->90->100->120->130->NULL var llist1 = null; var llist2 = null; llist1 = push(llist1,120); llist1=push(llist1,110); llist1=push(llist1,90); llist1=push(llist1,30); llist1=push(llist1,3); llist1=push(llist1,1); llist2=push(llist2,130); llist2=push(llist2,120); llist2=push(llist2,100); llist2=push(llist2,90); llist2=push(llist2,32); llist2=push(llist2,12); llist2=push(llist2,3); llist2=push(llist2,0); finalMaxSumList(llist1, llist2); // This code is contributed by umadevi9616</script>
1 3 12 32 90 110 120 130
Time complexity: O(n) where n is the length of bigger linked list Auxiliary space: O(1)
However a problem in this solution is that the original lists are changed.
Exercise:1. Try this problem when auxiliary space is not a constraint. 2. Try this problem when we don’t modify the actual list and create the resultant list.
princiraj1992
shubham_singh
nidhi_biet
umadevi9616
arorakashish0911
amartyaghoshgfg
hardikkoriintern
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Linked List vs Array
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Write a function to get the intersection point of two Linked Lists
Remove duplicates from an unsorted linked list
Circular Linked List | Set 1 (Introduction and Applications) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 422,
"s": 52,
"text": "Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to use O(1) extra space."
},
{
"code": null,
"e": 676,
"s": 422,
"text": "Input:\nList1 = 1->3->30->90->120->240->511\nList2 = 0->3->12->32->90->125->240->249\n\nOutput: Following is maximum sum linked list out of two input lists\nlist = 1->3->12->32->90->125->240->511\nwe switch at 3 and 240 to get above maximum sum linked list"
},
{
"code": null,
"e": 751,
"s": 676,
"text": "We strongly recommend to minimize the browser and try this yourself first."
},
{
"code": null,
"e": 835,
"s": 751,
"text": "The idea here in the below solution is to adjust next pointers after common nodes. "
},
{
"code": null,
"e": 1219,
"s": 835,
"text": " Start with head of both linked lists and find first common node. Use merging technique of sorted linked list for that. Keep track of sum of the elements too while doing this and set head of result list based on greater sum till first common node. After this till the current pointers of both lists don’t become NULL we need to adjust the next of prev pointers based on greater sum."
},
{
"code": null,
"e": 1340,
"s": 1219,
"text": " Start with head of both linked lists and find first common node. Use merging technique of sorted linked list for that. "
},
{
"code": null,
"e": 1470,
"s": 1340,
"text": " Keep track of sum of the elements too while doing this and set head of result list based on greater sum till first common node. "
},
{
"code": null,
"e": 1605,
"s": 1470,
"text": "After this till the current pointers of both lists don’t become NULL we need to adjust the next of prev pointers based on greater sum."
},
{
"code": null,
"e": 1712,
"s": 1605,
"text": "This way it can be done in-place with constant extra space. Time complexity of the below solution is O(n)."
},
{
"code": null,
"e": 1728,
"s": 1712,
"text": "Implementation:"
},
{
"code": null,
"e": 1732,
"s": 1728,
"text": "C++"
},
{
"code": null,
"e": 1737,
"s": 1732,
"text": "Java"
},
{
"code": null,
"e": 1745,
"s": 1737,
"text": "Python3"
},
{
"code": null,
"e": 1748,
"s": 1745,
"text": "C#"
},
{
"code": null,
"e": 1759,
"s": 1748,
"text": "Javascript"
},
{
"code": "// C++ program to construct the maximum sum linked// list out of two given sorted lists#include<bits/stdc++.h>using namespace std; //A linked list nodestruct Node{ int data; //data belong to that node Node *next; //next pointer}; // Push the data to the head of the linked listvoid push(Node **head, int data){ //Allocation memory to the new node Node *newnode = new Node; //Assigning data to the new node newnode->data = data; //Adjusting next pointer of the new node newnode->next = *head; //New node becomes the head of the list *head = newnode;} // Method that adjusts the pointers and prints the final listvoid finalMaxSumList(Node *a, Node *b){ Node *result = NULL; // Assigning pre and cur to the head of the // linked list. Node *pre1 = a, *curr1 = a; Node *pre2 = b, *curr2 = b; // Till either of the current pointers is not // NULL execute the loop while (curr1 != NULL || curr2 != NULL) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur pointer elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1!=NULL && curr2!=NULL && curr1->data!=curr2->data) { if (curr1->data < curr2->data) { sum1 += curr1->data; curr1 = curr1->next; } else // (curr2->data < curr1->data) { sum2 += curr2->data; curr2 = curr2->next; } } // If either of current pointers becomes NULL // carry on the sum calculation for other one. if (curr1 == NULL) { while (curr2 != NULL) { sum2 += curr2->data; curr2 = curr2->next; } } if (curr2 == NULL) { while (curr1 != NULL) { sum1 += curr1->data; curr1 = curr1->next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2)? pre1 : pre2; // If pre1 and pre2 don't contain the head pointers of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2->next = pre1->next; else pre1->next = pre2->next; } // Adjusting previous pointers pre1 = curr1, pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1) curr1 = curr1->next; // If curr2 is not NULL move to the next. if (curr2) curr2 = curr2->next; } // Print the resultant list. while (result != NULL) { cout << result->data << \" \"; result = result->next; }} //Main driver programint main(){ //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL Node *head1 = NULL, *head2 = NULL; push(&head1, 120); push(&head1, 110); push(&head1, 90); push(&head1, 30); push(&head1, 3); push(&head1, 1); push(&head2, 130); push(&head2, 120); push(&head2, 100); push(&head2, 90); push(&head2, 32); push(&head2, 12); push(&head2, 3); push(&head2, 0); finalMaxSumList(head1, head2); return 0;}",
"e": 5276,
"s": 1759,
"text": null
},
{
"code": "// Java program to construct a Maximum Sum Linked List out of// two Sorted Linked Lists having some Common nodesclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } // Method to adjust pointers and print final list void finalMaxSumList(Node a, Node b) { Node result = null; /* assigning pre and cur to head of the linked list */ Node pre1 = a, curr1 = a; Node pre2 = b, curr2 = b; /* Till either of current pointers is not null execute the loop */ while (curr1 != null || curr2 != null) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur reference elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1 != null && curr2 != null && curr1.data != curr2.data) { if (curr1.data<curr2.data) { sum1 += curr1.data; curr1 = curr1.next; } else { sum2 += curr2.data; curr2 = curr2.next; } } // If either of current pointers becomes null // carry on the sum calculation for other one. if (curr1 == null) { while (curr2 != null) { sum2 += curr2.data; curr2 = curr2.next; } } if (curr2 == null) { while(curr1 != null) { sum1 += curr1.data; curr1 = curr1.next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2) ? pre1 : pre2; // If pre1 and pre2 don't contain the head references of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2.next = pre1.next; else pre1.next = pre2.next; } // Adjusting previous pointers pre1 = curr1; pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1 != null) curr1 = curr1.next; // If curr2 is not NULL move to the next. if (curr2 != null) curr2 = curr2.next; } while (result != null) { System.out.print(result.data + \" \"); result = result.next; } System.out.println(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120); llist1.push(110); llist1.push(90); llist1.push(30); llist1.push(3); llist1.push(1); llist2.push(130); llist2.push(120); llist2.push(100); llist2.push(90); llist2.push(32); llist2.push(12); llist2.push(3); llist2.push(0); llist1.finalMaxSumList(llist1.head, llist2.head); }} /* This code is contributed by Rajat Mishra */",
"e": 9422,
"s": 5276,
"text": null
},
{
"code": "# Python program to construct a Maximum Sum Linked List out of# two Sorted Linked Lists having some Common nodesclass LinkedList(object): def __init__(self): # head of list self.head = None # Linked list Node class Node(object): def __init__(self, d): self.data = d self.next = None # Method to adjust pointers and print final list def finalMaxSumList(self, a, b): result = None # assigning pre and cur to head # of the linked list pre1 = a curr1 = a pre2 = b curr2 = b # Till either of current pointers is not null # execute the loop while curr1 != None or curr2 != None: # Keeping 2 local variables at the start of every # loop run to keep track of the sum between pre # and cur reference elements. sum1 = 0 sum2 = 0 # Calculating sum by traversing the nodes of linked # list as the merging of two linked list. The loop # stops at a common node while curr1 != None and curr2 != None and curr1.data != curr2.data: if curr1.data < curr2.data: sum1 += curr1.data curr1 = curr1.next else: sum2 += curr2.data curr2 = curr2.next # If either of current pointers becomes null # carry on the sum calculation for other one. if curr1 == None: while curr2 != None: sum2 += curr2.data curr2 = curr2.next if curr2 == None: while curr1 != None: sum1 += curr1.data curr1 = curr1.next # First time adjustment of resultant head based on # the maximum sum. if pre1 == a and pre2 == b: result = pre1 if (sum1 > sum2) else pre2 else: # If pre1 and pre2 don't contain the head references of # lists adjust the next pointers of previous pointers. if sum1 > sum2: pre2.next = pre1.next else: pre1.next = pre2.next # Adjusting previous pointers pre1 = curr1 pre2 = curr2 # If curr1 is not NULL move to the next. if curr1 != None: curr1 = curr1.next # If curr2 is not NULL move to the next. if curr2 != None: curr2 = curr2.next while result != None: print (str(result.data),end=\" \") result = result.next print () # Utility functions # Inserts a new Node at front of the list. def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Driver programllist1 = LinkedList()llist2 = LinkedList() # Linked List 1 : 1->3->30->90->110->120->NULL# Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120)llist1.push(110)llist1.push(90)llist1.push(30)llist1.push(3)llist1.push(1) llist2.push(130)llist2.push(120)llist2.push(100)llist2.push(90)llist2.push(32)llist2.push(12)llist2.push(3)llist2.push(0) llist1.finalMaxSumList(llist1.head, llist2.head) # This code is contributed by BHAVYA JAIN",
"e": 12909,
"s": 9422,
"text": null
},
{
"code": "// C# program to construct a Maximum// Sum Linked List out of two Sorted// Linked Lists having some Common nodesusing System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Method to adjust pointers // and print final list void finalMaxSumList(Node a, Node b) { Node result = null; /* assigning pre and cur to head of the linked list */ Node pre1 = a, curr1 = a; Node pre2 = b, curr2 = b; /* Till either of current pointers is not null execute the loop */ while (curr1 != null || curr2 != null) { // Keeping 2 local variables at the start // of every loop run to keep track of the // sum between pre and cur reference elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1 != null && curr2 != null && curr1.data != curr2.data) { if (curr1.data<curr2.data) { sum1 += curr1.data; curr1 = curr1.next; } else { sum2 += curr2.data; curr2 = curr2.next; } } // If either of current pointers becomes null // carry on the sum calculation for other one. if (curr1 == null) { while (curr2 != null) { sum2 += curr2.data; curr2 = curr2.next; } } if (curr2 == null) { while(curr1 != null) { sum1 += curr1.data; curr1 = curr1.next; } } // First time adjustment of resultant // head based on the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2) ? pre1 : pre2; // If pre1 and pre2 don't contain // the head references of lists adjust // the next pointers of previous pointers. else { if (sum1 > sum2) pre2.next = pre1.next; else pre1.next = pre2.next; } // Adjusting previous pointers pre1 = curr1; pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1 != null) curr1 = curr1.next; // If curr2 is not NULL move to the next. if (curr2 != null) curr2 = curr2.next; } while (result != null) { Console.Write(result.data + \" \"); result = result.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Driver code */ public static void Main() { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120); llist1.push(110); llist1.push(90); llist1.push(30); llist1.push(3); llist1.push(1); llist2.push(130); llist2.push(120); llist2.push(100); llist2.push(90); llist2.push(32); llist2.push(12); llist2.push(3); llist2.push(0); llist1.finalMaxSumList(llist1.head, llist2.head); }} /* This code contributed by PrinciRaj1992 */",
"e": 17066,
"s": 12909,
"text": null
},
{
"code": "<script>// javascript program to construct a Maximum Sum Linked List out of// two Sorted Linked Lists having some Common nodesvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } // Method to adjust pointers and print final list function finalMaxSumList(a, b) { var result = null; /* * assigning pre and cur to head of the linked list */ var pre1 = a, curr1 = a; var pre2 = b, curr2 = b; /* * Till either of current pointers is not null execute the loop */ while (curr1 != null || curr2 != null) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur reference elements. var sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1 != null && curr2 != null && curr1.data != curr2.data) { if (curr1.data < curr2.data) { sum1 += curr1.data; curr1 = curr1.next; } else { sum2 += curr2.data; curr2 = curr2.next; } } // If either of current pointers becomes null // carry on the sum calculation for other one. if (curr1 == null) { while (curr2 != null) { sum2 += curr2.data; curr2 = curr2.next; } } if (curr2 == null) { while (curr1 != null) { sum1 += curr1.data; curr1 = curr1.next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2) ? pre1 : pre2; // If pre1 and pre2 don't contain the head references of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2.next = pre1.next; else pre1.next = pre2.next; } // Adjusting previous pointers pre1 = curr1; pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1 != null) curr1 = curr1.next; // If curr2 is not NULL move to the next. if (curr2 != null) curr2 = curr2.next; } while (result != null) { document.write(result.data + \" \"); result = result.next; } document.write(); } /* Inserts a node at start of linked list */ function push(headl, new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = headl; /* 4. Move the head to point to new Node */ headl = new_node; return headl; } /* Driver program to test above functions */ // Linked List 1 : 1->3->30->90->110->120->NULL // Linked List 2 : 0->3->12->32->90->100->120->130->NULL var llist1 = null; var llist2 = null; llist1 = push(llist1,120); llist1=push(llist1,110); llist1=push(llist1,90); llist1=push(llist1,30); llist1=push(llist1,3); llist1=push(llist1,1); llist2=push(llist2,130); llist2=push(llist2,120); llist2=push(llist2,100); llist2=push(llist2,90); llist2=push(llist2,32); llist2=push(llist2,12); llist2=push(llist2,3); llist2=push(llist2,0); finalMaxSumList(llist1, llist2); // This code is contributed by umadevi9616</script>",
"e": 21081,
"s": 17066,
"text": null
},
{
"code": null,
"e": 21107,
"s": 21081,
"text": "1 3 12 32 90 110 120 130 "
},
{
"code": null,
"e": 21196,
"s": 21107,
"text": "Time complexity: O(n) where n is the length of bigger linked list Auxiliary space: O(1) "
},
{
"code": null,
"e": 21271,
"s": 21196,
"text": "However a problem in this solution is that the original lists are changed."
},
{
"code": null,
"e": 21430,
"s": 21271,
"text": "Exercise:1. Try this problem when auxiliary space is not a constraint. 2. Try this problem when we don’t modify the actual list and create the resultant list."
},
{
"code": null,
"e": 21444,
"s": 21430,
"text": "princiraj1992"
},
{
"code": null,
"e": 21458,
"s": 21444,
"text": "shubham_singh"
},
{
"code": null,
"e": 21469,
"s": 21458,
"text": "nidhi_biet"
},
{
"code": null,
"e": 21481,
"s": 21469,
"text": "umadevi9616"
},
{
"code": null,
"e": 21498,
"s": 21481,
"text": "arorakashish0911"
},
{
"code": null,
"e": 21514,
"s": 21498,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 21531,
"s": 21514,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 21543,
"s": 21531,
"text": "Linked List"
},
{
"code": null,
"e": 21555,
"s": 21543,
"text": "Linked List"
},
{
"code": null,
"e": 21653,
"s": 21555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21685,
"s": 21653,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 21749,
"s": 21685,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 21770,
"s": 21749,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 21817,
"s": 21770,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 21872,
"s": 21817,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 21907,
"s": 21872,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 21963,
"s": 21907,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 22030,
"s": 21963,
"text": "Write a function to get the intersection point of two Linked Lists"
},
{
"code": null,
"e": 22077,
"s": 22030,
"text": "Remove duplicates from an unsorted linked list"
}
]
|
MATCH Function in Excel With Examples | 24 May, 2021
Excel contains many useful functions and such a function is the ‘MATCH()’ function. It is basically used to get the relative position of a specific item from a range of cells(i.e. from a row or a column or from a table). This function also supports exact and approximate match like VLOOKUP() function. Generally, MATCH() function is used with the INDEX() function.
With the help of the MATCH() function, the user can get a relative position of a specific element from a table or range of cells. Relative position means the position of the element in the row or column where the MATCH() function is searching for the element. Precisely, this function helps us to get the position of an element in an array.
Syntax:
=MATCH(lookup_value, lookup_array, [match_type])
Here, the [match_type] value denotes if the user wants an exact match or approximate match.
Arguments:
lookup_value (Required): It is the value(text or number or logical value or a cell reference that contains number, text or logical value) that the user wants to search. This argument must be provided by the user.
lookup_array (Required): This argument contains the range of cells or a reference to an array where the MATCH() function will try to find out the lookup_value. Again this argument must be provided by the user.
[match_type] (Optional): This is an optional argument. This value maybe 1, 0 or -1. If the value is 0 the user wants an exact match. If the value is 1 MATCH() function will return the largest value that is less than or equal to lookup_value and if it is -1 the function will return the smallest value that is greater than or equal to lookup_value.
Note: If [match_type] argument is 1 or -1 then the lookup_array must be in a sorted order(ascending for 1 and descending for -1) and if the argument is not provided by the user the value becomes 1 by default.
Return Value: This function returns a value that represents the relative position of the lookup value in a range of cells.
Examples:
The example of the MATCH() function is given below. The names used in the list are only for example purposes and these are not related to any real persons.
The above list is used for example.
Here [match_type] argument is omitted so the value is 1 and the function
searches for an approximate match and returns the position
of the next greater element in the list.
Here [match_type] argument is -1 and the function searches for an approximate match
and returns the position of the next smallest element in the list.
Below is the output screenshot of the Excel sheet.
Output Screenshot
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 393,
"s": 28,
"text": "Excel contains many useful functions and such a function is the ‘MATCH()’ function. It is basically used to get the relative position of a specific item from a range of cells(i.e. from a row or a column or from a table). This function also supports exact and approximate match like VLOOKUP() function. Generally, MATCH() function is used with the INDEX() function."
},
{
"code": null,
"e": 734,
"s": 393,
"text": "With the help of the MATCH() function, the user can get a relative position of a specific element from a table or range of cells. Relative position means the position of the element in the row or column where the MATCH() function is searching for the element. Precisely, this function helps us to get the position of an element in an array."
},
{
"code": null,
"e": 742,
"s": 734,
"text": "Syntax:"
},
{
"code": null,
"e": 791,
"s": 742,
"text": "=MATCH(lookup_value, lookup_array, [match_type])"
},
{
"code": null,
"e": 883,
"s": 791,
"text": "Here, the [match_type] value denotes if the user wants an exact match or approximate match."
},
{
"code": null,
"e": 894,
"s": 883,
"text": "Arguments:"
},
{
"code": null,
"e": 1107,
"s": 894,
"text": "lookup_value (Required): It is the value(text or number or logical value or a cell reference that contains number, text or logical value) that the user wants to search. This argument must be provided by the user."
},
{
"code": null,
"e": 1317,
"s": 1107,
"text": "lookup_array (Required): This argument contains the range of cells or a reference to an array where the MATCH() function will try to find out the lookup_value. Again this argument must be provided by the user."
},
{
"code": null,
"e": 1666,
"s": 1317,
"text": "[match_type] (Optional): This is an optional argument. This value maybe 1, 0 or -1. If the value is 0 the user wants an exact match. If the value is 1 MATCH() function will return the largest value that is less than or equal to lookup_value and if it is -1 the function will return the smallest value that is greater than or equal to lookup_value."
},
{
"code": null,
"e": 1875,
"s": 1666,
"text": "Note: If [match_type] argument is 1 or -1 then the lookup_array must be in a sorted order(ascending for 1 and descending for -1) and if the argument is not provided by the user the value becomes 1 by default."
},
{
"code": null,
"e": 1998,
"s": 1875,
"text": "Return Value: This function returns a value that represents the relative position of the lookup value in a range of cells."
},
{
"code": null,
"e": 2008,
"s": 1998,
"text": "Examples:"
},
{
"code": null,
"e": 2164,
"s": 2008,
"text": "The example of the MATCH() function is given below. The names used in the list are only for example purposes and these are not related to any real persons."
},
{
"code": null,
"e": 2200,
"s": 2164,
"text": "The above list is used for example."
},
{
"code": null,
"e": 2274,
"s": 2200,
"text": "Here [match_type] argument is omitted so the value is 1 and the function "
},
{
"code": null,
"e": 2333,
"s": 2274,
"text": "searches for an approximate match and returns the position"
},
{
"code": null,
"e": 2375,
"s": 2333,
"text": " of the next greater element in the list."
},
{
"code": null,
"e": 2459,
"s": 2375,
"text": "Here [match_type] argument is -1 and the function searches for an approximate match"
},
{
"code": null,
"e": 2527,
"s": 2459,
"text": " and returns the position of the next smallest element in the list."
},
{
"code": null,
"e": 2578,
"s": 2527,
"text": "Below is the output screenshot of the Excel sheet."
},
{
"code": null,
"e": 2596,
"s": 2578,
"text": "Output Screenshot"
},
{
"code": null,
"e": 2603,
"s": 2596,
"text": "Picked"
},
{
"code": null,
"e": 2609,
"s": 2603,
"text": "Excel"
},
{
"code": null,
"e": 2707,
"s": 2609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2745,
"s": 2707,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 2777,
"s": 2745,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 2818,
"s": 2777,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 2873,
"s": 2818,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 2901,
"s": 2873,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 2941,
"s": 2901,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 2975,
"s": 2941,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 2991,
"s": 2975,
"text": "Macros in Excel"
},
{
"code": null,
"e": 3049,
"s": 2991,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
}
]
|
SQL- Lock Table | 06 Jun, 2021
SQL Server is a versatile database and it is the most used Relational Database that is used across many software industries. In this article, let us see about the SQL Lock table in SQL Server by taking some practical examples. As it is meeting Atomicity(A), Consistency(C), Isolation(I), and Durability(D) requirements it is called a relational database. In order to maintain ACID mechanisms, in SQL Server, a lock is maintained.
By using Azure Data Studio, let us see the concepts of the Lock mechanism by starting with creating the database, table creation, locks, etc. Azure Data Studio works well for Windows 10, Mac, and Linux environments. It can be installed from here.
Command to create the database. Here GEEKSFORGEEKS is the db name.
--CREATE DATABASE <dbname>;
Make the database active
USE GEEKSFORGEEKS;
Once the database is made active, at the top, the database name will be shown
Creating a table with Primary Key. Here ID is a PRIMARY KEY meaning each author will have their own ID
CREATE TABLE Authors (
ID INT NOT NULL PRIMARY KEY,
<other column name1> <datatype> <null/not null>,
..........
);
If explicitly “NOT NULL” is specified, that column should have values. If not specified, it is by default “NULL”.
“Authors” named table is created under “GEEKSFORGEEKS” database
There will be scenarios like either we can add all columns or few column values to the table. The reason is some columns might require null values by default.
Example 1 :
INSERT INTO <table_name> (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
Here we are taking into consideration the mentioned columns and hence only their required values are inserted by the above query.
Example 2 :
INSERT INTO <table_name> VALUES (value1, value2, value3, ...);
Here we are not specifying any columns means, all the values to all the columns need to be inserted.
Violation of PRIMARY KEY constraint 'PK__Authors__3214EC277EBB8ED1'.
Cannot insert duplicate key in object 'dbo.Authors'. The duplicate key value is (1).
The above errors occurred in the above screenshot shows that “ID” column is unique and it should not have duplicate values
Now, let us correct that and query the table by using:
SELECT * FROM <tablename>
Clear output for the applied Example 1 and Example 2 methods
It is observed that Row 1 is having ‘Null’ values in the place of ‘Skillsets’ and ‘NumberOfPosts’ column. The reason is as we have not specified values for those columns, it has taken default Null values.
SQL Locks :
SQL Server is a relational database, data consistency is an important mechanism, and it can be done by means of SQL Locks. A lock is established in SQL Server when a transaction starts, and it is released when it is ended.. There are different types of locks are there.
Shared (S) Locks: When the object needs to be read, this type of lock will occur, but this is not harmful.
Exclusive (X) Locks: It prevents other transactions like inserting/updating/deleting etc., Hence no modifications can be done on a locked object.
Update (U) Locks: More or less similar to Exclusive lock but here the operation can be viewed as “read phase” and “write phase”. Especially during the read phase, other transactions are prevented.
Intent Locks: When SQL Server has the shared (S) lock or exclusive (X) lock on a row, then the intent lock is on the table.
Regular intent locks: Intent exclusive (IX) , Intent shared (IS), and Intent update (IU).
Conversion locks: Shared with intent exclusive (SIX), Shared with intent update (SIU), and Update with intent exclusive (UIX).
Lock hierarchy starts from Database, then table, then row.
The shared lock on a database level is very much important as it prevents dropping of the database or restoring a database backup over the database in use.
Lock occurrences when there is a “SELECT” statement is issued.
During DML statement execution i.e. either during insert/update/delete.
With our example, let us see the locking mechanisms.
--Let us create an open transaction and analyze the locked resource.
BEGIN TRAN
Let us update the Skillsets column for ID = 1
UPDATE Authors SET Skillsets='Java,Android,PHP' where ID=1
select @@SPID
select * from sys.dm_tran_locks WHERE request_session_id=<our session id. here it is 52>
Let us insert some more records(nearly around 100 records) into the table and then using a transaction, let us update few columns as well as parallel apply the select query also
--Let us create an open transaction and analyze the locked resources.
BEGIN TRAN
--Let us update the Skillsets when ID < 20
UPDATE Authors SET Skillsets='Java,Android,R Programming' where ID < 20
--Let us update the Skillsets when ID >= 25
UPDATE Authors SET Skillsets='Android,IOS,R Programming' where ID >= 25
--Other DML statements like Update/Delete. This statement must be taking a long time
--(if there are huge updates are happening) as previous statement itself
--is either not committed or rolled back yet
SELECT * FROM Authors;
select @@SPID
Actually when the earlier command transaction are not yet complete(if there are huge records at least 100 records) and update is happening on each and every row and before completion of it, if we are proceeding for another set of commands like “select”
Then there are possibilities of the status will be “Awaiting” (Queries which are executing) and “Suspended” (Queries which are halt)
How to overcome the so far running process?
KILL <spid> -> Kill the session
(Or) Inside a transaction, after each query, apply
COMMIT -> TO COMMIT THE CHANGES
ROLLBACK -> TO ROLLBACK THE CHANGES
By doing this process, we are enforcing the operation either to get committed or rolled back(depends upon the requirements, it has to be carried out)
But unless we know that the entire process is required or not, we cannot either commit or rollback the transaction.
Alternative way :
By using NOLOCK with SELECT QUERY, we can overcome
SELECT * FROM Authors WITH (NOLOCK);
For SELECT statement status using the sp_who2 command. The query runs without waiting for the UPDATE transaction to be completed successfully and release the locking on the table,
SELECT * FROM Authors WITH (READUNCOMMITTED);
--This way also we can do
Conclusion :
SQL Locks are much important for any RDBMS. SQL Server handles them in the mentioned ways.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "SQL Server is a versatile database and it is the most used Relational Database that is used across many software industries. In this article, let us see about the SQL Lock table in SQL Server by taking some practical examples. As it is meeting Atomicity(A), Consistency(C), Isolation(I), and Durability(D) requirements it is called a relational database. In order to maintain ACID mechanisms, in SQL Server, a lock is maintained. "
},
{
"code": null,
"e": 707,
"s": 460,
"text": "By using Azure Data Studio, let us see the concepts of the Lock mechanism by starting with creating the database, table creation, locks, etc. Azure Data Studio works well for Windows 10, Mac, and Linux environments. It can be installed from here."
},
{
"code": null,
"e": 775,
"s": 707,
"text": "Command to create the database. Here GEEKSFORGEEKS is the db name."
},
{
"code": null,
"e": 803,
"s": 775,
"text": "--CREATE DATABASE <dbname>;"
},
{
"code": null,
"e": 828,
"s": 803,
"text": "Make the database active"
},
{
"code": null,
"e": 847,
"s": 828,
"text": "USE GEEKSFORGEEKS;"
},
{
"code": null,
"e": 925,
"s": 847,
"text": "Once the database is made active, at the top, the database name will be shown"
},
{
"code": null,
"e": 1028,
"s": 925,
"text": "Creating a table with Primary Key. Here ID is a PRIMARY KEY meaning each author will have their own ID"
},
{
"code": null,
"e": 1152,
"s": 1028,
"text": "CREATE TABLE Authors (\n ID INT NOT NULL PRIMARY KEY,\n <other column name1> <datatype> <null/not null>,\n ..........\n);"
},
{
"code": null,
"e": 1266,
"s": 1152,
"text": "If explicitly “NOT NULL” is specified, that column should have values. If not specified, it is by default “NULL”."
},
{
"code": null,
"e": 1330,
"s": 1266,
"text": "“Authors” named table is created under “GEEKSFORGEEKS” database"
},
{
"code": null,
"e": 1490,
"s": 1330,
"text": "There will be scenarios like either we can add all columns or few column values to the table. The reason is some columns might require null values by default. "
},
{
"code": null,
"e": 1502,
"s": 1490,
"text": "Example 1 :"
},
{
"code": null,
"e": 1599,
"s": 1502,
"text": "INSERT INTO <table_name> (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);"
},
{
"code": null,
"e": 1729,
"s": 1599,
"text": "Here we are taking into consideration the mentioned columns and hence only their required values are inserted by the above query."
},
{
"code": null,
"e": 1741,
"s": 1729,
"text": "Example 2 :"
},
{
"code": null,
"e": 1804,
"s": 1741,
"text": "INSERT INTO <table_name> VALUES (value1, value2, value3, ...);"
},
{
"code": null,
"e": 1905,
"s": 1804,
"text": "Here we are not specifying any columns means, all the values to all the columns need to be inserted."
},
{
"code": null,
"e": 2060,
"s": 1905,
"text": "Violation of PRIMARY KEY constraint 'PK__Authors__3214EC277EBB8ED1'. \nCannot insert duplicate key in object 'dbo.Authors'. The duplicate key value is (1)."
},
{
"code": null,
"e": 2183,
"s": 2060,
"text": "The above errors occurred in the above screenshot shows that “ID” column is unique and it should not have duplicate values"
},
{
"code": null,
"e": 2238,
"s": 2183,
"text": "Now, let us correct that and query the table by using:"
},
{
"code": null,
"e": 2264,
"s": 2238,
"text": "SELECT * FROM <tablename>"
},
{
"code": null,
"e": 2325,
"s": 2264,
"text": "Clear output for the applied Example 1 and Example 2 methods"
},
{
"code": null,
"e": 2531,
"s": 2325,
"text": "It is observed that Row 1 is having ‘Null’ values in the place of ‘Skillsets’ and ‘NumberOfPosts’ column. The reason is as we have not specified values for those columns, it has taken default Null values. "
},
{
"code": null,
"e": 2543,
"s": 2531,
"text": "SQL Locks :"
},
{
"code": null,
"e": 2813,
"s": 2543,
"text": "SQL Server is a relational database, data consistency is an important mechanism, and it can be done by means of SQL Locks. A lock is established in SQL Server when a transaction starts, and it is released when it is ended.. There are different types of locks are there."
},
{
"code": null,
"e": 2920,
"s": 2813,
"text": "Shared (S) Locks: When the object needs to be read, this type of lock will occur, but this is not harmful."
},
{
"code": null,
"e": 3066,
"s": 2920,
"text": "Exclusive (X) Locks: It prevents other transactions like inserting/updating/deleting etc., Hence no modifications can be done on a locked object."
},
{
"code": null,
"e": 3264,
"s": 3066,
"text": "Update (U) Locks: More or less similar to Exclusive lock but here the operation can be viewed as “read phase” and “write phase”. Especially during the read phase, other transactions are prevented. "
},
{
"code": null,
"e": 3388,
"s": 3264,
"text": "Intent Locks: When SQL Server has the shared (S) lock or exclusive (X) lock on a row, then the intent lock is on the table."
},
{
"code": null,
"e": 3478,
"s": 3388,
"text": "Regular intent locks: Intent exclusive (IX) , Intent shared (IS), and Intent update (IU)."
},
{
"code": null,
"e": 3605,
"s": 3478,
"text": "Conversion locks: Shared with intent exclusive (SIX), Shared with intent update (SIU), and Update with intent exclusive (UIX)."
},
{
"code": null,
"e": 3664,
"s": 3605,
"text": "Lock hierarchy starts from Database, then table, then row."
},
{
"code": null,
"e": 3820,
"s": 3664,
"text": "The shared lock on a database level is very much important as it prevents dropping of the database or restoring a database backup over the database in use."
},
{
"code": null,
"e": 3883,
"s": 3820,
"text": "Lock occurrences when there is a “SELECT” statement is issued."
},
{
"code": null,
"e": 3955,
"s": 3883,
"text": "During DML statement execution i.e. either during insert/update/delete."
},
{
"code": null,
"e": 4009,
"s": 3955,
"text": "With our example, let us see the locking mechanisms. "
},
{
"code": null,
"e": 4208,
"s": 4009,
"text": "--Let us create an open transaction and analyze the locked resource.\nBEGIN TRAN\nLet us update the Skillsets column for ID = 1\nUPDATE Authors SET Skillsets='Java,Android,PHP' where ID=1\nselect @@SPID"
},
{
"code": null,
"e": 4298,
"s": 4208,
"text": "select * from sys.dm_tran_locks WHERE request_session_id=<our session id. here it is 52>"
},
{
"code": null,
"e": 4477,
"s": 4298,
"text": " Let us insert some more records(nearly around 100 records) into the table and then using a transaction, let us update few columns as well as parallel apply the select query also"
},
{
"code": null,
"e": 5033,
"s": 4477,
"text": "--Let us create an open transaction and analyze the locked resources.\nBEGIN TRAN\n--Let us update the Skillsets when ID < 20\nUPDATE Authors SET Skillsets='Java,Android,R Programming' where ID < 20 \n--Let us update the Skillsets when ID >= 25\nUPDATE Authors SET Skillsets='Android,IOS,R Programming' where ID >= 25 \n--Other DML statements like Update/Delete. This statement must be taking a long time\n--(if there are huge updates are happening) as previous statement itself\n--is either not committed or rolled back yet\nSELECT * FROM Authors;\nselect @@SPID"
},
{
"code": null,
"e": 5286,
"s": 5033,
"text": "Actually when the earlier command transaction are not yet complete(if there are huge records at least 100 records) and update is happening on each and every row and before completion of it, if we are proceeding for another set of commands like “select”"
},
{
"code": null,
"e": 5419,
"s": 5286,
"text": "Then there are possibilities of the status will be “Awaiting” (Queries which are executing) and “Suspended” (Queries which are halt)"
},
{
"code": null,
"e": 5463,
"s": 5419,
"text": "How to overcome the so far running process?"
},
{
"code": null,
"e": 5495,
"s": 5463,
"text": "KILL <spid> -> Kill the session"
},
{
"code": null,
"e": 5546,
"s": 5495,
"text": "(Or) Inside a transaction, after each query, apply"
},
{
"code": null,
"e": 5614,
"s": 5546,
"text": "COMMIT -> TO COMMIT THE CHANGES\nROLLBACK -> TO ROLLBACK THE CHANGES"
},
{
"code": null,
"e": 5764,
"s": 5614,
"text": "By doing this process, we are enforcing the operation either to get committed or rolled back(depends upon the requirements, it has to be carried out)"
},
{
"code": null,
"e": 5880,
"s": 5764,
"text": "But unless we know that the entire process is required or not, we cannot either commit or rollback the transaction."
},
{
"code": null,
"e": 5898,
"s": 5880,
"text": "Alternative way :"
},
{
"code": null,
"e": 5949,
"s": 5898,
"text": "By using NOLOCK with SELECT QUERY, we can overcome"
},
{
"code": null,
"e": 5986,
"s": 5949,
"text": "SELECT * FROM Authors WITH (NOLOCK);"
},
{
"code": null,
"e": 6166,
"s": 5986,
"text": "For SELECT statement status using the sp_who2 command. The query runs without waiting for the UPDATE transaction to be completed successfully and release the locking on the table,"
},
{
"code": null,
"e": 6238,
"s": 6166,
"text": "SELECT * FROM Authors WITH (READUNCOMMITTED);\n--This way also we can do"
},
{
"code": null,
"e": 6251,
"s": 6238,
"text": "Conclusion :"
},
{
"code": null,
"e": 6342,
"s": 6251,
"text": "SQL Locks are much important for any RDBMS. SQL Server handles them in the mentioned ways."
},
{
"code": null,
"e": 6349,
"s": 6342,
"text": "Picked"
},
{
"code": null,
"e": 6359,
"s": 6349,
"text": "SQL-Query"
},
{
"code": null,
"e": 6370,
"s": 6359,
"text": "SQL-Server"
},
{
"code": null,
"e": 6374,
"s": 6370,
"text": "SQL"
},
{
"code": null,
"e": 6378,
"s": 6374,
"text": "SQL"
},
{
"code": null,
"e": 6476,
"s": 6378,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6542,
"s": 6476,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 6566,
"s": 6542,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 6598,
"s": 6566,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 6631,
"s": 6598,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 6648,
"s": 6631,
"text": "SQL using Python"
},
{
"code": null,
"e": 6678,
"s": 6648,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 6756,
"s": 6678,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 6792,
"s": 6756,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 6823,
"s": 6792,
"text": "SQL Query to Compare Two Dates"
}
]
|
SPACE() function in SQL Server | 28 Dec, 2020
SPACE() :This function in SQL Server helps to return a string that has a specified number of spaces. This function is also available in MYSQL with the same name.
Syntax :
SPACE(number)
Parameters :This function accepts only one parameter.
number –It demotes the number of spaces.
Returns :
If the number is positive, the function will return a string that has a specified number of spaces.
If the number is negative, the function will return NULL.
Applicable in the following versions :
SQL Server 2017
SQL Server 2016
SQL Server 2014
SQL Server 2012
SQL Server 2008 R2
SQL Server 2008
SQL Server 2005
Example-1 :Basic working of SPACE() function, the function will return 5 blank spaces.
SELECT SPACE(5)
AS Result;
Output :The function will return 5 blank spaces.
Example-2 :Concatenating 2 or more strings using SPACE() function.
Concatenating 2 strings using the SPACE() function, we take 2 strings and assign specific spaces in between.SELECT 'HI!' + SPACE(6) + 'NiceToSeeYou'
AS Result;Output :ResultHI! NiceToSeeYou
SELECT 'HI!' + SPACE(6) + 'NiceToSeeYou'
AS Result;
Output :
Concatenating 3 strings using SPACE() function, we take 2 strings and assign specific spaces among them.SELECT 'GEEKS' + SPACE(5) + 'FOR'+ SPACE(5) +'GEEKS' AS Result;Output :ResultGEEKS FOR GEEKS
SELECT 'GEEKS' + SPACE(5) + 'FOR'+ SPACE(5) +'GEEKS' AS Result;
Output :
Example-3 :If the user enters a negative number as an argument, then the function will return NULL.
SELECT SPACE(-20)
AS Result;
Output :
Example-4 :Working of SPACE() function with variable, we use variable along with SPACE() function.
DECLARE @space_Size int
SET @space_Size = 7
SELECT 'KeepChasing' + SPACE(@space_size) + 'YourDreams'
AS Result;
Output :
DBMS-SQL
SQL-Server
Technical Scripter 2020
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "SPACE() :This function in SQL Server helps to return a string that has a specified number of spaces. This function is also available in MYSQL with the same name."
},
{
"code": null,
"e": 199,
"s": 190,
"text": "Syntax :"
},
{
"code": null,
"e": 213,
"s": 199,
"text": "SPACE(number)"
},
{
"code": null,
"e": 267,
"s": 213,
"text": "Parameters :This function accepts only one parameter."
},
{
"code": null,
"e": 308,
"s": 267,
"text": "number –It demotes the number of spaces."
},
{
"code": null,
"e": 318,
"s": 308,
"text": "Returns :"
},
{
"code": null,
"e": 418,
"s": 318,
"text": "If the number is positive, the function will return a string that has a specified number of spaces."
},
{
"code": null,
"e": 476,
"s": 418,
"text": "If the number is negative, the function will return NULL."
},
{
"code": null,
"e": 515,
"s": 476,
"text": "Applicable in the following versions :"
},
{
"code": null,
"e": 531,
"s": 515,
"text": "SQL Server 2017"
},
{
"code": null,
"e": 547,
"s": 531,
"text": "SQL Server 2016"
},
{
"code": null,
"e": 563,
"s": 547,
"text": "SQL Server 2014"
},
{
"code": null,
"e": 579,
"s": 563,
"text": "SQL Server 2012"
},
{
"code": null,
"e": 598,
"s": 579,
"text": "SQL Server 2008 R2"
},
{
"code": null,
"e": 614,
"s": 598,
"text": "SQL Server 2008"
},
{
"code": null,
"e": 630,
"s": 614,
"text": "SQL Server 2005"
},
{
"code": null,
"e": 717,
"s": 630,
"text": "Example-1 :Basic working of SPACE() function, the function will return 5 blank spaces."
},
{
"code": null,
"e": 745,
"s": 717,
"text": "SELECT SPACE(5) \nAS Result;"
},
{
"code": null,
"e": 794,
"s": 745,
"text": "Output :The function will return 5 blank spaces."
},
{
"code": null,
"e": 861,
"s": 794,
"text": "Example-2 :Concatenating 2 or more strings using SPACE() function."
},
{
"code": null,
"e": 1052,
"s": 861,
"text": "Concatenating 2 strings using the SPACE() function, we take 2 strings and assign specific spaces in between.SELECT 'HI!' + SPACE(6) + 'NiceToSeeYou' \nAS Result;Output :ResultHI! NiceToSeeYou"
},
{
"code": null,
"e": 1105,
"s": 1052,
"text": "SELECT 'HI!' + SPACE(6) + 'NiceToSeeYou' \nAS Result;"
},
{
"code": null,
"e": 1114,
"s": 1105,
"text": "Output :"
},
{
"code": null,
"e": 1315,
"s": 1114,
"text": "Concatenating 3 strings using SPACE() function, we take 2 strings and assign specific spaces among them.SELECT 'GEEKS' + SPACE(5) + 'FOR'+ SPACE(5) +'GEEKS' AS Result;Output :ResultGEEKS FOR GEEKS"
},
{
"code": null,
"e": 1379,
"s": 1315,
"text": "SELECT 'GEEKS' + SPACE(5) + 'FOR'+ SPACE(5) +'GEEKS' AS Result;"
},
{
"code": null,
"e": 1388,
"s": 1379,
"text": "Output :"
},
{
"code": null,
"e": 1488,
"s": 1388,
"text": "Example-3 :If the user enters a negative number as an argument, then the function will return NULL."
},
{
"code": null,
"e": 1518,
"s": 1488,
"text": "SELECT SPACE(-20) \nAS Result;"
},
{
"code": null,
"e": 1527,
"s": 1518,
"text": "Output :"
},
{
"code": null,
"e": 1626,
"s": 1527,
"text": "Example-4 :Working of SPACE() function with variable, we use variable along with SPACE() function."
},
{
"code": null,
"e": 1739,
"s": 1626,
"text": "DECLARE @space_Size int\nSET @space_Size = 7\nSELECT 'KeepChasing' + SPACE(@space_size) + 'YourDreams' \nAS Result;"
},
{
"code": null,
"e": 1748,
"s": 1739,
"text": "Output :"
},
{
"code": null,
"e": 1757,
"s": 1748,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1768,
"s": 1757,
"text": "SQL-Server"
},
{
"code": null,
"e": 1792,
"s": 1768,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1796,
"s": 1792,
"text": "SQL"
},
{
"code": null,
"e": 1800,
"s": 1796,
"text": "SQL"
},
{
"code": null,
"e": 1898,
"s": 1800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1964,
"s": 1898,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1988,
"s": 1964,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2020,
"s": 1988,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2053,
"s": 2020,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2070,
"s": 2053,
"text": "SQL using Python"
},
{
"code": null,
"e": 2100,
"s": 2070,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2178,
"s": 2100,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2214,
"s": 2178,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2245,
"s": 2214,
"text": "SQL Query to Compare Two Dates"
}
]
|
Mathematical understanding of RNN and its variants | 22 Jan, 2021
Introduction:
Experts expect Artificial Intelligence (AI) to work towards creating a better life to live. They say as more computation power will be available in the coming time i.e more graphical processing units, AI will make more advancement and productive to humans. Today, one can see a lot of such AI-powered applications like the fight against human trafficking, healthcare adviser, self-driving cars, Intrusion detection and prevention, object tracking and counting, face detection and recognition, disease prediction and virtual assistance for human help. This particular post talks about RNN, its variants (LSTM, GRU) and mathematics behind it. RNN is a type of neural network which accepts variable-length input and produces variable-length output. It is used to develop various applications such as text to speech, chatbots, language modeling, sentimental analysis, time series stocks forecasting, machine translation and nam entity recognition.
Table of content:
What is RNN and how it is different from Feed Forward Neural Networks
Mathematics behind RNN
RNN variants (LSTM and GRU)
Practical Applications of RNN
Final Note
What is RNN and how it is different from Feed Forward Neural Networks:
RNN is a recurrent neural network whose current output not only depends on its present value but also past inputs, whereas for feed-forward network current output only depends on the current input. Have a look at the below example to understand RNN in a better way.
Rahul belongs to congress.
Rahul is part of indian cricket team.
If anyone is asked who is Rahul, he/she will say that both Rahul is different i.e one is from Indian national congress and another is from the Indian cricket team. Now if the same task is given to the machine to give the output it cannot say until it knows the full context i.e predicting the identity of a single word depends on knowing the whole context. Such tasks can be implemented by Bi-LSTM which is a variant of RNN. RNN is suitable for such work thanks to their capability of learning the context. Other applications include speech to text conversion, building virtual assistance, time-series stocks forecasting, sentimental analysis, language modelling and machine translation. On the other hand, a feed-forward neural network produces an output which only depends on the current input. Examples for such are image classification task, image segmentation or object detection task. One such type of such network is a convolutional neural network (CNN). Remember both RNN and CNN are supervised deep learning models i.e, they need labels during the training phase.
1.) Mathematical Equation of RNN
To understand the mathematics behind RNN, have a look at the below image
Mathematics behind RNN
As discussed inside the first heading, output depends on both current and past inputs. Let I1 be the first input whose dimension is n*1 where n is the length of vocabulary. S0 be the hidden state to the first RNN cell having d neurons. For each cell, input hidden state should be one previous. For the first cell initialize S0 with zeros or some random number because no previous state is seen. U be another matrix of dimension d*n where d is the number of neurons in the first RNN cell and n is the input vocabulary size. W is another matrix whose dimension is d*d. b is bias whose dimension is d*1. For finding the output from the first cell, another matrix V is taken whose dimension is k*d where c is bias with dimension k*1.
Mathematically, outputs from the first RNN cell are as below
S1= UI1+ WS0 + b
O1= VS1+c
In General,
Sn= UIn+ WSn-1 + b
On= VSn+c
Key takeaway from the above equation
In general, output On depends on Sn and Sn depends on Sn-1. Sn-1 depend on Sn-2. Process goes till S0 is achieved. This clearly demonstrates that output at the nth time step depends on all previous inputs.
Parameters in the RNN are U, V, b, c, W are shared among all the RNN cells. The reason for sharing is to create a common function which could be applied at all the time steps. Parameters are learnable and are responsible for training the model. At each time step, the loss is computing and is backpropagated through the gradient descent algorithm.
Gradient represents the slope of tangent and points in the direction of the greatest rate of increase of function. We are interested to find that V where loss is minimum. From the loss, it means cost function or error. In a simple sense, the cost function is the difference between a true value and predicted value. Move is made opposite to the direction of the gradient of the loss with respect to V. Mathematically new value of V is obtained using below mathematically formula
Where d(L)/d(V)is the sum of all losses obtained from time steps. There are two ways of updating the weights. One is to calculate the gradient of the defined batch and then update it (Mini Batch) or calculate per sample and update (Stochastic). During the calculation of d(L)/d(V), the chain rule is applied. Have a look at the below figure to understand calculation and chain rule.
Chain rule implementation for calculating gradient of loss w.r.t V
W is multiplied by S. In order to calculate derivative of loss with respect to weight at any time step, the chain rule is applied to take into consideration all the path to reach W from Sn to S0. This means that due to any of the wrong Sn, W is affected. In other words, some wrong information came from some hidden state which leads to loss. Mathematically, weight is updated as below
The key point to remember is that either gradients and weights are updated at every sample or after a batch. This depends on algorithm one is choosing either stochastic or mini-batch. Have a look at the below screenshot to visualize the concept in a more refined way.
Gradient descent with respect to W
From the above discussion, I hope the mathematics behind RNN is clear now. The main drawback of RNN is whatever is the length of the sequence, the dimension of the state vector remains the same. Taking a case into consideration, if the length of the input sequence is very long, new information is being added to the same state vector. When one reaches the nth time step which is far away from the first time step, information is much confusing. At such a position, it is not clear what was the information provided at time step 1 or 2. It is analogous to a whiteboard whose dimension is fixed and one keeps on writing on it. At some position, it becomes very messy. One cannot even read what is written on board. To solve such issues, its variants were developed so-called LSTM and GRU. They work on the principle of selective read, write and forget. Now whiteboard (analogy to state vector) is same but only desired information is written at time step and unnecessary information is filtered out making sequential neural network suitable for training with long sequences. One can read the difference between LSTM and GRU from here.
The strategy followed is selective write, read and forget.
Selective write
Selective Write:
In RNN, St-1 is fed along with xt to a cell whereas in LSTM St-1 is transformed to ht-1 using another vector Ot-1. This process is called selective write. Mathematical equations for selective write are as below
Selective Read:
Have a look at the below image to understand the concept
Selective Read
ht-1 is added with xt to produce st. Then Hadamard product of (written stc in the diagram) and it is made to obtain st. This is called an input gate. In st only selective information goes and this process is called selective read. Mathematically, equations for selective read are as below
Selective Forget:
Have a look at the below image to understand the concept
Selective Forget
st-1 is hadamard product with ft and is called selective forget. Overall st is obtained from the addition of selective read and selective forget. See the below diagram to understand the above statement
addition of selective read and forget
Mathematically, equations for selective forget are as below
Note: There is no forget gate in case of GRU (Gated Recurrent Unit). It has only input and output gates.
Practical Applications of RNN:
RNN finds its use case in a speech to text conversion, building virtual assistance, sentimental analysis, time series stocks forecasting, machine translation, language modelling. More research is going on creating generative chatbots using RNN and its variants. Other applications include image captioning, generating large text from a small paragraph and text summarizer (an app like Inshorts is using this). Music composition and call centre analysis are other domains using RNN.
Final Note:
In a nutshell, one can understand the difference between RNN and feed-forward neural network from the opening paragraph and then going deep into the mathematics behind RNN. In the end, the article is completed by explaining different variants of RNN and some practical applications of RNN. In order to work on applications of RNN, one must gain strong knowledge in calculus, derivatives especially how chain rule works. Once the theory is studied, some codes on these topics should be made in your favorite coding language. This will provide you with the upper hand.
data-science
Deep-Learning
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
Support Vector Machine Algorithm
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 66,
"s": 52,
"text": "Introduction:"
},
{
"code": null,
"e": 1010,
"s": 66,
"text": "Experts expect Artificial Intelligence (AI) to work towards creating a better life to live. They say as more computation power will be available in the coming time i.e more graphical processing units, AI will make more advancement and productive to humans. Today, one can see a lot of such AI-powered applications like the fight against human trafficking, healthcare adviser, self-driving cars, Intrusion detection and prevention, object tracking and counting, face detection and recognition, disease prediction and virtual assistance for human help. This particular post talks about RNN, its variants (LSTM, GRU) and mathematics behind it. RNN is a type of neural network which accepts variable-length input and produces variable-length output. It is used to develop various applications such as text to speech, chatbots, language modeling, sentimental analysis, time series stocks forecasting, machine translation and nam entity recognition."
},
{
"code": null,
"e": 1028,
"s": 1010,
"text": "Table of content:"
},
{
"code": null,
"e": 1098,
"s": 1028,
"text": "What is RNN and how it is different from Feed Forward Neural Networks"
},
{
"code": null,
"e": 1121,
"s": 1098,
"text": "Mathematics behind RNN"
},
{
"code": null,
"e": 1149,
"s": 1121,
"text": "RNN variants (LSTM and GRU)"
},
{
"code": null,
"e": 1179,
"s": 1149,
"text": "Practical Applications of RNN"
},
{
"code": null,
"e": 1190,
"s": 1179,
"text": "Final Note"
},
{
"code": null,
"e": 1261,
"s": 1190,
"text": "What is RNN and how it is different from Feed Forward Neural Networks:"
},
{
"code": null,
"e": 1528,
"s": 1261,
"text": "RNN is a recurrent neural network whose current output not only depends on its present value but also past inputs, whereas for feed-forward network current output only depends on the current input. Have a look at the below example to understand RNN in a better way."
},
{
"code": null,
"e": 1555,
"s": 1528,
"text": "Rahul belongs to congress."
},
{
"code": null,
"e": 1593,
"s": 1555,
"text": "Rahul is part of indian cricket team."
},
{
"code": null,
"e": 2667,
"s": 1593,
"text": "If anyone is asked who is Rahul, he/she will say that both Rahul is different i.e one is from Indian national congress and another is from the Indian cricket team. Now if the same task is given to the machine to give the output it cannot say until it knows the full context i.e predicting the identity of a single word depends on knowing the whole context. Such tasks can be implemented by Bi-LSTM which is a variant of RNN. RNN is suitable for such work thanks to their capability of learning the context. Other applications include speech to text conversion, building virtual assistance, time-series stocks forecasting, sentimental analysis, language modelling and machine translation. On the other hand, a feed-forward neural network produces an output which only depends on the current input. Examples for such are image classification task, image segmentation or object detection task. One such type of such network is a convolutional neural network (CNN). Remember both RNN and CNN are supervised deep learning models i.e, they need labels during the training phase."
},
{
"code": null,
"e": 2700,
"s": 2667,
"text": "1.) Mathematical Equation of RNN"
},
{
"code": null,
"e": 2773,
"s": 2700,
"text": "To understand the mathematics behind RNN, have a look at the below image"
},
{
"code": null,
"e": 2796,
"s": 2773,
"text": "Mathematics behind RNN"
},
{
"code": null,
"e": 3526,
"s": 2796,
"text": "As discussed inside the first heading, output depends on both current and past inputs. Let I1 be the first input whose dimension is n*1 where n is the length of vocabulary. S0 be the hidden state to the first RNN cell having d neurons. For each cell, input hidden state should be one previous. For the first cell initialize S0 with zeros or some random number because no previous state is seen. U be another matrix of dimension d*n where d is the number of neurons in the first RNN cell and n is the input vocabulary size. W is another matrix whose dimension is d*d. b is bias whose dimension is d*1. For finding the output from the first cell, another matrix V is taken whose dimension is k*d where c is bias with dimension k*1."
},
{
"code": null,
"e": 3587,
"s": 3526,
"text": "Mathematically, outputs from the first RNN cell are as below"
},
{
"code": null,
"e": 3614,
"s": 3587,
"text": "S1= UI1+ WS0 + b\nO1= VS1+c"
},
{
"code": null,
"e": 3626,
"s": 3614,
"text": "In General,"
},
{
"code": null,
"e": 3655,
"s": 3626,
"text": "Sn= UIn+ WSn-1 + b\nOn= VSn+c"
},
{
"code": null,
"e": 3692,
"s": 3655,
"text": "Key takeaway from the above equation"
},
{
"code": null,
"e": 3901,
"s": 3692,
"text": "In general, output On depends on Sn and Sn depends on Sn-1. Sn-1 depend on Sn-2. Process goes till S0 is achieved. This clearly demonstrates that output at the nth time step depends on all previous inputs."
},
{
"code": null,
"e": 4250,
"s": 3901,
"text": "Parameters in the RNN are U, V, b, c, W are shared among all the RNN cells. The reason for sharing is to create a common function which could be applied at all the time steps. Parameters are learnable and are responsible for training the model. At each time step, the loss is computing and is backpropagated through the gradient descent algorithm."
},
{
"code": null,
"e": 4729,
"s": 4250,
"text": "Gradient represents the slope of tangent and points in the direction of the greatest rate of increase of function. We are interested to find that V where loss is minimum. From the loss, it means cost function or error. In a simple sense, the cost function is the difference between a true value and predicted value. Move is made opposite to the direction of the gradient of the loss with respect to V. Mathematically new value of V is obtained using below mathematically formula"
},
{
"code": null,
"e": 5112,
"s": 4729,
"text": "Where d(L)/d(V)is the sum of all losses obtained from time steps. There are two ways of updating the weights. One is to calculate the gradient of the defined batch and then update it (Mini Batch) or calculate per sample and update (Stochastic). During the calculation of d(L)/d(V), the chain rule is applied. Have a look at the below figure to understand calculation and chain rule."
},
{
"code": null,
"e": 5179,
"s": 5112,
"text": "Chain rule implementation for calculating gradient of loss w.r.t V"
},
{
"code": null,
"e": 5565,
"s": 5179,
"text": "W is multiplied by S. In order to calculate derivative of loss with respect to weight at any time step, the chain rule is applied to take into consideration all the path to reach W from Sn to S0. This means that due to any of the wrong Sn, W is affected. In other words, some wrong information came from some hidden state which leads to loss. Mathematically, weight is updated as below"
},
{
"code": null,
"e": 5833,
"s": 5565,
"text": "The key point to remember is that either gradients and weights are updated at every sample or after a batch. This depends on algorithm one is choosing either stochastic or mini-batch. Have a look at the below screenshot to visualize the concept in a more refined way."
},
{
"code": null,
"e": 5868,
"s": 5833,
"text": "Gradient descent with respect to W"
},
{
"code": null,
"e": 7002,
"s": 5868,
"text": "From the above discussion, I hope the mathematics behind RNN is clear now. The main drawback of RNN is whatever is the length of the sequence, the dimension of the state vector remains the same. Taking a case into consideration, if the length of the input sequence is very long, new information is being added to the same state vector. When one reaches the nth time step which is far away from the first time step, information is much confusing. At such a position, it is not clear what was the information provided at time step 1 or 2. It is analogous to a whiteboard whose dimension is fixed and one keeps on writing on it. At some position, it becomes very messy. One cannot even read what is written on board. To solve such issues, its variants were developed so-called LSTM and GRU. They work on the principle of selective read, write and forget. Now whiteboard (analogy to state vector) is same but only desired information is written at time step and unnecessary information is filtered out making sequential neural network suitable for training with long sequences. One can read the difference between LSTM and GRU from here."
},
{
"code": null,
"e": 7061,
"s": 7002,
"text": "The strategy followed is selective write, read and forget."
},
{
"code": null,
"e": 7078,
"s": 7061,
"text": " Selective write"
},
{
"code": null,
"e": 7095,
"s": 7078,
"text": "Selective Write:"
},
{
"code": null,
"e": 7307,
"s": 7095,
"text": "In RNN, St-1 is fed along with xt to a cell whereas in LSTM St-1 is transformed to ht-1 using another vector Ot-1. This process is called selective write. Mathematical equations for selective write are as below"
},
{
"code": null,
"e": 7323,
"s": 7307,
"text": "Selective Read:"
},
{
"code": null,
"e": 7380,
"s": 7323,
"text": "Have a look at the below image to understand the concept"
},
{
"code": null,
"e": 7395,
"s": 7380,
"text": "Selective Read"
},
{
"code": null,
"e": 7686,
"s": 7395,
"text": "ht-1 is added with xt to produce st. Then Hadamard product of (written stc in the diagram) and it is made to obtain st. This is called an input gate. In st only selective information goes and this process is called selective read. Mathematically, equations for selective read are as below"
},
{
"code": null,
"e": 7704,
"s": 7686,
"text": "Selective Forget:"
},
{
"code": null,
"e": 7761,
"s": 7704,
"text": "Have a look at the below image to understand the concept"
},
{
"code": null,
"e": 7778,
"s": 7761,
"text": "Selective Forget"
},
{
"code": null,
"e": 7980,
"s": 7778,
"text": "st-1 is hadamard product with ft and is called selective forget. Overall st is obtained from the addition of selective read and selective forget. See the below diagram to understand the above statement"
},
{
"code": null,
"e": 8019,
"s": 7980,
"text": "addition of selective read and forget "
},
{
"code": null,
"e": 8079,
"s": 8019,
"text": "Mathematically, equations for selective forget are as below"
},
{
"code": null,
"e": 8184,
"s": 8079,
"text": "Note: There is no forget gate in case of GRU (Gated Recurrent Unit). It has only input and output gates."
},
{
"code": null,
"e": 8215,
"s": 8184,
"text": "Practical Applications of RNN:"
},
{
"code": null,
"e": 8697,
"s": 8215,
"text": "RNN finds its use case in a speech to text conversion, building virtual assistance, sentimental analysis, time series stocks forecasting, machine translation, language modelling. More research is going on creating generative chatbots using RNN and its variants. Other applications include image captioning, generating large text from a small paragraph and text summarizer (an app like Inshorts is using this). Music composition and call centre analysis are other domains using RNN."
},
{
"code": null,
"e": 8709,
"s": 8697,
"text": "Final Note:"
},
{
"code": null,
"e": 9277,
"s": 8709,
"text": "In a nutshell, one can understand the difference between RNN and feed-forward neural network from the opening paragraph and then going deep into the mathematics behind RNN. In the end, the article is completed by explaining different variants of RNN and some practical applications of RNN. In order to work on applications of RNN, one must gain strong knowledge in calculus, derivatives especially how chain rule works. Once the theory is studied, some codes on these topics should be made in your favorite coding language. This will provide you with the upper hand. "
},
{
"code": null,
"e": 9290,
"s": 9277,
"text": "data-science"
},
{
"code": null,
"e": 9304,
"s": 9290,
"text": "Deep-Learning"
},
{
"code": null,
"e": 9321,
"s": 9304,
"text": "Machine Learning"
},
{
"code": null,
"e": 9328,
"s": 9321,
"text": "Python"
},
{
"code": null,
"e": 9345,
"s": 9328,
"text": "Machine Learning"
},
{
"code": null,
"e": 9443,
"s": 9345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9479,
"s": 9443,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 9520,
"s": 9479,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 9544,
"s": 9520,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 9577,
"s": 9544,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 9628,
"s": 9577,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 9656,
"s": 9628,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 9706,
"s": 9656,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 9728,
"s": 9706,
"text": "Python map() function"
}
]
|
PHP | ctype_alnum() (Check for Alphanumeric) | 07 Jun, 2018
A ctype_alnum() function in PHP used to check all characters of given string/text are alphanumeric or not. If all characters are alphanumeric then return TRUE, otherwise return FALSE.
Syntax:
bool ctype_alnum ($text)
Parameters Used:
$text : It is a mandatory parameter which specifies the string.
Examples:
Input : Geeks
Output : Yes
Explanation : String "Geeks" is alphanumeric.
Note: Read Standard c local letter.
Input : '%%%Contribute_article on GFG!!!'
Output : No
Explanation : String contains Special characters.
Note: Except string or digit, if we input anything then it will return FALSE.
Below programs illustrate the ctype_alnum() function.
Program :1Drive a code ctype_alnum()() function for better understand.
<?php // PHP program to check given string is // all characters are alphanumeric $string = 'GeeksforGeeks'; if ( ctype_alnum($string)) echo "Yes\n"; else echo "No\n"; ?>
Yes
Program: 2 Drive a code of ctype_alnum() function where input will be a array of string integers, string with special symbols.
<?php// PHP program to check given string is // all characters are alphanumeric $strings = array( 'Geeks', '[email protected]', '2018', 'GFG2018', 'a b c ', '@!$%^&*()|2018'); // Checking above given four strings // by used of ctype_alnum() function .foreach ($strings as $test) { if (ctype_alnum($test)) echo "Yes\n"; else echo "No\n"; } ?>
Yes
No
Yes
Yes
No
No
References :http://php.net/manual/en/function.ctype-alnum.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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": 28,
"s": 0,
"text": "\n07 Jun, 2018"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "A ctype_alnum() function in PHP used to check all characters of given string/text are alphanumeric or not. If all characters are alphanumeric then return TRUE, otherwise return FALSE."
},
{
"code": null,
"e": 220,
"s": 212,
"text": "Syntax:"
},
{
"code": null,
"e": 246,
"s": 220,
"text": " bool ctype_alnum ($text)"
},
{
"code": null,
"e": 263,
"s": 246,
"text": "Parameters Used:"
},
{
"code": null,
"e": 327,
"s": 263,
"text": "$text : It is a mandatory parameter which specifies the string."
},
{
"code": null,
"e": 337,
"s": 327,
"text": "Examples:"
},
{
"code": null,
"e": 602,
"s": 337,
"text": "Input : Geeks\nOutput : Yes\nExplanation : String \"Geeks\" is alphanumeric.\n Note: Read Standard c local letter.\n \nInput : '%%%Contribute_article on GFG!!!'\nOutput : No\n \nExplanation : String contains Special characters.\n \n"
},
{
"code": null,
"e": 680,
"s": 602,
"text": "Note: Except string or digit, if we input anything then it will return FALSE."
},
{
"code": null,
"e": 734,
"s": 680,
"text": "Below programs illustrate the ctype_alnum() function."
},
{
"code": null,
"e": 805,
"s": 734,
"text": "Program :1Drive a code ctype_alnum()() function for better understand."
},
{
"code": "<?php // PHP program to check given string is // all characters are alphanumeric $string = 'GeeksforGeeks'; if ( ctype_alnum($string)) echo \"Yes\\n\"; else echo \"No\\n\"; ?>",
"e": 1001,
"s": 805,
"text": null
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "Yes\n"
},
{
"code": null,
"e": 1133,
"s": 1006,
"text": "Program: 2 Drive a code of ctype_alnum() function where input will be a array of string integers, string with special symbols."
},
{
"code": "<?php// PHP program to check given string is // all characters are alphanumeric $strings = array( 'Geeks', '[email protected]', '2018', 'GFG2018', 'a b c ', '@!$%^&*()|2018'); // Checking above given four strings // by used of ctype_alnum() function .foreach ($strings as $test) { if (ctype_alnum($test)) echo \"Yes\\n\"; else echo \"No\\n\"; } ?>",
"e": 1525,
"s": 1133,
"text": null
},
{
"code": null,
"e": 1547,
"s": 1525,
"text": "Yes\nNo\nYes\nYes\nNo\nNo\n"
},
{
"code": null,
"e": 1609,
"s": 1547,
"text": "References :http://php.net/manual/en/function.ctype-alnum.php"
},
{
"code": null,
"e": 1622,
"s": 1609,
"text": "PHP-function"
},
{
"code": null,
"e": 1626,
"s": 1622,
"text": "PHP"
},
{
"code": null,
"e": 1643,
"s": 1626,
"text": "Web Technologies"
},
{
"code": null,
"e": 1647,
"s": 1643,
"text": "PHP"
},
{
"code": null,
"e": 1745,
"s": 1647,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1795,
"s": 1745,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1835,
"s": 1795,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1896,
"s": 1835,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 1946,
"s": 1896,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 1991,
"s": 1946,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2024,
"s": 1991,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2086,
"s": 2024,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2147,
"s": 2086,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2197,
"s": 2147,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Program to convert KiloBytes to Bytes and Bits | 21 Apr, 2021
Given Number of Kilobytes. The task is to Convert them into Bytes and Bits.Bit: A Bit is the basic unit in computer information and has only two different values, normally defined as a 0 or 1. These values can be interpreted as on or off, yes or no, true or false, etc. It just depends on the binary code.Add 1 bit, double the number of patterns.
1 bit – 2 patterns i.e 0 and 12 bits – 4 patterns i.e 00, 01, 10, 113 bits – 8 patterns i.e 000, 001, 010, 011, 100, 101, 110, 111
Mathematically: n bits yields 2n patterns.Bytes: A Byte is just 8 Bits and is the smallest unit of memory that can be addressed in many computer systems.
Important points about Bytes:
One byte can store one character, e.g. ‘A’ or ‘x’ or ‘$’ etc.
1 byte i.e 8 bits can make 256 different patterns.
One byte can hold a number between 0 and 255.
Different Form:-Kilobyte, KB, about 1 thousand bytes.Megabyte, MB, about 1 million bytes.Gigabyte, GB, about 1 billion bytes.Terabyte, TB, about 1 trillion bytes
Kilobyte, KB, about 1 thousand bytes.Megabyte, MB, about 1 million bytes.Gigabyte, GB, about 1 billion bytes.Terabyte, TB, about 1 trillion bytes
Kilobyte, KB, about 1 thousand bytes.
Megabyte, MB, about 1 million bytes.
Gigabyte, GB, about 1 billion bytes.
Terabyte, TB, about 1 trillion bytes
Examples:
Input: kilobytes = 1
Output: 1 Kilobytes = 1024 Bytes and 8192 Bits.
Input: kilobytes = 8
Output: 8 Kilobytes = 8192 Bytes and 65536 Bits.
Below is the program to convert KilloBytes to Bytes and Bits:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above program#include <bits/stdc++.h>using namespace std; // Function to calculates the bitslong Bits(int kilobytes){ long Bits = 0; // calculates Bits // 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192; return Bits;} // Function to calculates the byteslong Bytes(int kilobytes){ long Bytes = 0; // calculates Bytes // 1 KB = 1024 bytes Bytes = kilobytes * 1024; return Bytes;} // Driver codeint main(){ int kilobytes = 1; cout << kilobytes << " Kilobytes = " << Bytes(kilobytes) << " Bytes and " << Bits(kilobytes) << " Bits."; return 0;}
// Java implementation of above program import java.util.*;import java.lang.*;import java.io.*;import java.math.BigInteger; class GFG{ // Function to calculates the bitsstatic BigInteger Bits(int kilobytes){ BigInteger Bits = new BigInteger("0"); // calculates Bits // 1 kilobytes(s) = 8192 bits BigInteger kilo = BigInteger.valueOf(kilobytes); Bits = kilo.multiply(BigInteger.valueOf(8192)); return Bits;} // Function to calculates the bytesstatic BigInteger Bytes(int kilobytes){ BigInteger Bytes = new BigInteger("0"); // calculates Bytes // 1 KB = 1024 bytes BigInteger kilo = BigInteger.valueOf(kilobytes); Bytes = kilo.multiply(BigInteger.valueOf(1024)); return Bytes;} // Driver codepublic static void main(String args[]){ int kilobytes = 1; System.out.print(kilobytes + " Kilobytes = " + Bytes(kilobytes) + " Bytes and " + Bits(kilobytes) + " Bits.");}}
# Python implementation of above program # Function to calculates the bitsdef Bits(kilobytes) : # calculates Bits # 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192 return Bits # Function to calculates the bytesdef Bytes(kilobytes) : # calculates Bytes # 1 KB = 1024 bytes Bytes = kilobytes * 1024 return Bytes # Driver codeif __name__ == "__main__" : kilobytes = 1 print(kilobytes, "Kilobytes =", Bytes(kilobytes) , "Bytes and", Bits(kilobytes), "Bits") # This code is contributed by ANKITRAI1
// C# implementation of above programusing System; class GFG{ // Function to calculates the bitsstatic long Bits(int kilobytes){ long Bits = 0; // calculates Bits // 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192; return Bits;} // Function to calculates the bytesstatic long Bytes(int kilobytes){ long Bytes = 0; // calculates Bytes // 1 KB = 1024 bytes Bytes = kilobytes * 1024; return Bytes;} // Driver codestatic public void Main (){ int kilobytes = 1; Console.WriteLine (kilobytes +" Kilobytes = "+ Bytes(kilobytes) + " Bytes and "+ Bits(kilobytes) + " Bits.");}} // This code is contributed by Sach_Code
<?php// PHP implementation of above program // Function to calculates the bitsfunction Bits($kilobytes){ $Bits = 0; // calculates Bits // 1 kilobytes(s) = 8192 bits $Bits = $kilobytes * 8192; return $Bits;} // Function to calculates the bytesfunction Bytes($kilobytes){ $Bytes = 0; // calculates Bytes // 1 KB = 1024 bytes $Bytes = $kilobytes * 1024; return $Bytes;} // Driver code$kilobytes = 1; echo $kilobytes;echo (" Kilobytes = ");echo Bytes($kilobytes);echo (" Bytes and ");echo Bits($kilobytes);echo (" Bits."); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript implementation of above program function Bits(kilobytes){ var Bits = 0; // Calculates Bits // 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192; return Bits;} // Function to calculates the bytesfunction Bytes(kilobytes){ var Bytes = 0; // Calculates Bytes // 1 KB = 1024 bytes Bytes = kilobytes * 1024; return Bytes;} // Driver codevar kilobytes = 1; document.write(kilobytes + " Kilobytes = " + Bytes(kilobytes) + " Bytes and " + Bits(kilobytes) + " Bits."); // This code is contributed by akshitsaxenaa09 </script>
1 Kilobytes = 1024 Bytes and 8192 Bits.
Shivi_Aggarwal
tufan_gupta2000
ankthon
Sach_Code
akshitsaxenaa09
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 375,
"s": 28,
"text": "Given Number of Kilobytes. The task is to Convert them into Bytes and Bits.Bit: A Bit is the basic unit in computer information and has only two different values, normally defined as a 0 or 1. These values can be interpreted as on or off, yes or no, true or false, etc. It just depends on the binary code.Add 1 bit, double the number of patterns."
},
{
"code": null,
"e": 508,
"s": 375,
"text": "1 bit – 2 patterns i.e 0 and 12 bits – 4 patterns i.e 00, 01, 10, 113 bits – 8 patterns i.e 000, 001, 010, 011, 100, 101, 110, 111 "
},
{
"code": null,
"e": 662,
"s": 508,
"text": "Mathematically: n bits yields 2n patterns.Bytes: A Byte is just 8 Bits and is the smallest unit of memory that can be addressed in many computer systems."
},
{
"code": null,
"e": 692,
"s": 662,
"text": "Important points about Bytes:"
},
{
"code": null,
"e": 754,
"s": 692,
"text": "One byte can store one character, e.g. ‘A’ or ‘x’ or ‘$’ etc."
},
{
"code": null,
"e": 805,
"s": 754,
"text": "1 byte i.e 8 bits can make 256 different patterns."
},
{
"code": null,
"e": 851,
"s": 805,
"text": "One byte can hold a number between 0 and 255."
},
{
"code": null,
"e": 1013,
"s": 851,
"text": "Different Form:-Kilobyte, KB, about 1 thousand bytes.Megabyte, MB, about 1 million bytes.Gigabyte, GB, about 1 billion bytes.Terabyte, TB, about 1 trillion bytes"
},
{
"code": null,
"e": 1159,
"s": 1013,
"text": "Kilobyte, KB, about 1 thousand bytes.Megabyte, MB, about 1 million bytes.Gigabyte, GB, about 1 billion bytes.Terabyte, TB, about 1 trillion bytes"
},
{
"code": null,
"e": 1197,
"s": 1159,
"text": "Kilobyte, KB, about 1 thousand bytes."
},
{
"code": null,
"e": 1234,
"s": 1197,
"text": "Megabyte, MB, about 1 million bytes."
},
{
"code": null,
"e": 1271,
"s": 1234,
"text": "Gigabyte, GB, about 1 billion bytes."
},
{
"code": null,
"e": 1308,
"s": 1271,
"text": "Terabyte, TB, about 1 trillion bytes"
},
{
"code": null,
"e": 1318,
"s": 1308,
"text": "Examples:"
},
{
"code": null,
"e": 1458,
"s": 1318,
"text": "Input: kilobytes = 1\nOutput: 1 Kilobytes = 1024 Bytes and 8192 Bits.\n\nInput: kilobytes = 8\nOutput: 8 Kilobytes = 8192 Bytes and 65536 Bits."
},
{
"code": null,
"e": 1520,
"s": 1458,
"text": "Below is the program to convert KilloBytes to Bytes and Bits:"
},
{
"code": null,
"e": 1524,
"s": 1520,
"text": "C++"
},
{
"code": null,
"e": 1529,
"s": 1524,
"text": "Java"
},
{
"code": null,
"e": 1537,
"s": 1529,
"text": "Python3"
},
{
"code": null,
"e": 1540,
"s": 1537,
"text": "C#"
},
{
"code": null,
"e": 1544,
"s": 1540,
"text": "PHP"
},
{
"code": null,
"e": 1555,
"s": 1544,
"text": "Javascript"
},
{
"code": "// C++ implementation of above program#include <bits/stdc++.h>using namespace std; // Function to calculates the bitslong Bits(int kilobytes){ long Bits = 0; // calculates Bits // 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192; return Bits;} // Function to calculates the byteslong Bytes(int kilobytes){ long Bytes = 0; // calculates Bytes // 1 KB = 1024 bytes Bytes = kilobytes * 1024; return Bytes;} // Driver codeint main(){ int kilobytes = 1; cout << kilobytes << \" Kilobytes = \" << Bytes(kilobytes) << \" Bytes and \" << Bits(kilobytes) << \" Bits.\"; return 0;}",
"e": 2183,
"s": 1555,
"text": null
},
{
"code": "// Java implementation of above program import java.util.*;import java.lang.*;import java.io.*;import java.math.BigInteger; class GFG{ // Function to calculates the bitsstatic BigInteger Bits(int kilobytes){ BigInteger Bits = new BigInteger(\"0\"); // calculates Bits // 1 kilobytes(s) = 8192 bits BigInteger kilo = BigInteger.valueOf(kilobytes); Bits = kilo.multiply(BigInteger.valueOf(8192)); return Bits;} // Function to calculates the bytesstatic BigInteger Bytes(int kilobytes){ BigInteger Bytes = new BigInteger(\"0\"); // calculates Bytes // 1 KB = 1024 bytes BigInteger kilo = BigInteger.valueOf(kilobytes); Bytes = kilo.multiply(BigInteger.valueOf(1024)); return Bytes;} // Driver codepublic static void main(String args[]){ int kilobytes = 1; System.out.print(kilobytes + \" Kilobytes = \" + Bytes(kilobytes) + \" Bytes and \" + Bits(kilobytes) + \" Bits.\");}}",
"e": 3126,
"s": 2183,
"text": null
},
{
"code": "# Python implementation of above program # Function to calculates the bitsdef Bits(kilobytes) : # calculates Bits # 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192 return Bits # Function to calculates the bytesdef Bytes(kilobytes) : # calculates Bytes # 1 KB = 1024 bytes Bytes = kilobytes * 1024 return Bytes # Driver codeif __name__ == \"__main__\" : kilobytes = 1 print(kilobytes, \"Kilobytes =\", Bytes(kilobytes) , \"Bytes and\", Bits(kilobytes), \"Bits\") # This code is contributed by ANKITRAI1",
"e": 3665,
"s": 3126,
"text": null
},
{
"code": "// C# implementation of above programusing System; class GFG{ // Function to calculates the bitsstatic long Bits(int kilobytes){ long Bits = 0; // calculates Bits // 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192; return Bits;} // Function to calculates the bytesstatic long Bytes(int kilobytes){ long Bytes = 0; // calculates Bytes // 1 KB = 1024 bytes Bytes = kilobytes * 1024; return Bytes;} // Driver codestatic public void Main (){ int kilobytes = 1; Console.WriteLine (kilobytes +\" Kilobytes = \"+ Bytes(kilobytes) + \" Bytes and \"+ Bits(kilobytes) + \" Bits.\");}} // This code is contributed by Sach_Code",
"e": 4356,
"s": 3665,
"text": null
},
{
"code": "<?php// PHP implementation of above program // Function to calculates the bitsfunction Bits($kilobytes){ $Bits = 0; // calculates Bits // 1 kilobytes(s) = 8192 bits $Bits = $kilobytes * 8192; return $Bits;} // Function to calculates the bytesfunction Bytes($kilobytes){ $Bytes = 0; // calculates Bytes // 1 KB = 1024 bytes $Bytes = $kilobytes * 1024; return $Bytes;} // Driver code$kilobytes = 1; echo $kilobytes;echo (\" Kilobytes = \");echo Bytes($kilobytes);echo (\" Bytes and \");echo Bits($kilobytes);echo (\" Bits.\"); // This code is contributed// by Shivi_Aggarwal?>",
"e": 4959,
"s": 4356,
"text": null
},
{
"code": "<script> // Javascript implementation of above program function Bits(kilobytes){ var Bits = 0; // Calculates Bits // 1 kilobytes(s) = 8192 bits Bits = kilobytes * 8192; return Bits;} // Function to calculates the bytesfunction Bytes(kilobytes){ var Bytes = 0; // Calculates Bytes // 1 KB = 1024 bytes Bytes = kilobytes * 1024; return Bytes;} // Driver codevar kilobytes = 1; document.write(kilobytes + \" Kilobytes = \" + Bytes(kilobytes) + \" Bytes and \" + Bits(kilobytes) + \" Bits.\"); // This code is contributed by akshitsaxenaa09 </script>",
"e": 5592,
"s": 4959,
"text": null
},
{
"code": null,
"e": 5632,
"s": 5592,
"text": "1 Kilobytes = 1024 Bytes and 8192 Bits."
},
{
"code": null,
"e": 5649,
"s": 5634,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 5665,
"s": 5649,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 5673,
"s": 5665,
"text": "ankthon"
},
{
"code": null,
"e": 5683,
"s": 5673,
"text": "Sach_Code"
},
{
"code": null,
"e": 5699,
"s": 5683,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 5712,
"s": 5699,
"text": "Mathematical"
},
{
"code": null,
"e": 5731,
"s": 5712,
"text": "School Programming"
},
{
"code": null,
"e": 5744,
"s": 5731,
"text": "Mathematical"
},
{
"code": null,
"e": 5842,
"s": 5744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5866,
"s": 5842,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5887,
"s": 5866,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5909,
"s": 5887,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 5923,
"s": 5909,
"text": "Prime Numbers"
},
{
"code": null,
"e": 5965,
"s": 5923,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 5983,
"s": 5965,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6008,
"s": 5983,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6024,
"s": 6008,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 6047,
"s": 6024,
"text": "Introduction To PYTHON"
}
]
|
ASP.NET - Data Sources | A data source control interacts with the data-bound controls and hides the complex data binding processes. These are the tools that provide data to the data bound controls and support execution of operations like insertions, deletions, sorting, and updates.
Each data source control wraps a particular data provider-relational databases, XML documents, or custom classes and helps in:
Managing connection
Selecting data
Managing presentation aspects like paging, caching, etc.
Manipulating data
There are many data source controls available in ASP.NET for accessing data from SQL Server, from ODBC or OLE DB servers, from XML files, and from business objects.
Based on type of data, these controls could be divided into two categories:
Hierarchical data source controls
Table-based data source controls
The data source controls used for hierarchical data are:
XMLDataSource - It allows binding to XML files and strings with or without schema information.
XMLDataSource - It allows binding to XML files and strings with or without schema information.
SiteMapDataSource - It allows binding to a provider that supplies site map information.
SiteMapDataSource - It allows binding to a provider that supplies site map information.
The data source controls used for tabular data are:
Data source views are objects of the DataSourceView class. Which represent a customized view of data for different data operations such as sorting, filtering, etc.
The DataSourceView class serves as the base class for all data source view classes, which define the capabilities of data source controls.
The following table provides the properties of the DataSourceView class:
The following table provides the methods of the DataSourceView class:
The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through two important properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax of the control:
<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource" />
Configuring various data operations on the underlying data depends upon the various properties (property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource control, which provides the programming interface of the control:
DeleteCommand,
DeleteParameters,
DeleteCommandType
FilterExpression,
FilterParameters
InsertCommand,
InsertParameters,
InsertCommandType
SelectCommand,
SelectParameters,
SelectCommandType
UpdateCommand,
UpdateParameters,
UpdateCommandType
The following code snippet shows a data source control enabled for data manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"
UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
FilterExpression= "EMPLOYEEID > 10">
.....
.....
</asp:SqlDataSource>
The ObjectDataSource Control enables user-defined classes to associate the output of their methods to data bound controls. The programming interface of this class is almost same as the SqlDataSource control.
Following are two important aspects of binding business objects:
The bindable class should have a default constructor, it should be stateless, and have methods that can be mapped to select, update, insert, and delete semantics.
The bindable class should have a default constructor, it should be stateless, and have methods that can be mapped to select, update, insert, and delete semantics.
The object must update one item at a time, batch operations are not supported.
The object must update one item at a time, batch operations are not supported.
Let us go directly to an example to work with this control. The student class is the class to be used with an object data source. This class has three properties: a student id, name, and city. It has a default constructor and a GetStudents method for retrieving data.
The student class:
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public string City { get; set; }
public Student()
{ }
public DataSet GetStudents()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Students");
dt.Columns.Add("StudentID", typeof(System.Int32));
dt.Columns.Add("StudentName", typeof(System.String));
dt.Columns.Add("StudentCity", typeof(System.String));
dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });
dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
ds.Tables.Add(dt);
return ds;
}
}
Take the following steps to bind the object with an object data source and retrieve data:
Create a new web site.
Create a new web site.
Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a class template, and placing the above code in it.
Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a class template, and placing the above code in it.
Build the solution so that the application can use the reference to the class.
Build the solution so that the application can use the reference to the class.
Place an object data source control in the web form.
Place an object data source control in the web form.
Configure the data source by selecting the object.
Configure the data source by selecting the object.
Select a data method(s) for different operations on data. In this example, there is only one method.
Select a data method(s) for different operations on data. In this example, there is only one method.
Place a data bound control such as grid view on the page and select the object data source as its underlying data source.
Place a data bound control such as grid view on the page and select the object data source as its underlying data source.
At this stage, the design view should look like the following:
At this stage, the design view should look like the following:
Run the project, it retrieves the hard coded tuples from the students class.
Run the project, it retrieves the hard coded tuples from the students class.
The AccessDataSource control represents a connection to an Access database. It is based on the SqlDataSource control and provides simpler programming interface. The following code snippet provides the basic syntax for the data source:
<asp:AccessDataSource ID="AccessDataSource1 runat="server"
DataFile="~/App_Data/ASPDotNetStepByStep.mdb" SelectCommand="SELECT * FROM [DotNetReferences]">
</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it can also be used for performing insert, update, or delete operations. This is done using the ADO.NET commands and parameter collection.
Updates are problematic for Access databases from within an ASP.NET application because an Access database is a plain file and the default account of the ASP.NET application might not have the permission to write to the database file. | [
{
"code": null,
"e": 2739,
"s": 2481,
"text": "A data source control interacts with the data-bound controls and hides the complex data binding processes. These are the tools that provide data to the data bound controls and support execution of operations like insertions, deletions, sorting, and updates."
},
{
"code": null,
"e": 2866,
"s": 2739,
"text": "Each data source control wraps a particular data provider-relational databases, XML documents, or custom classes and helps in:"
},
{
"code": null,
"e": 2886,
"s": 2866,
"text": "Managing connection"
},
{
"code": null,
"e": 2901,
"s": 2886,
"text": "Selecting data"
},
{
"code": null,
"e": 2958,
"s": 2901,
"text": "Managing presentation aspects like paging, caching, etc."
},
{
"code": null,
"e": 2976,
"s": 2958,
"text": "Manipulating data"
},
{
"code": null,
"e": 3141,
"s": 2976,
"text": "There are many data source controls available in ASP.NET for accessing data from SQL Server, from ODBC or OLE DB servers, from XML files, and from business objects."
},
{
"code": null,
"e": 3217,
"s": 3141,
"text": "Based on type of data, these controls could be divided into two categories:"
},
{
"code": null,
"e": 3251,
"s": 3217,
"text": "Hierarchical data source controls"
},
{
"code": null,
"e": 3284,
"s": 3251,
"text": "Table-based data source controls"
},
{
"code": null,
"e": 3341,
"s": 3284,
"text": "The data source controls used for hierarchical data are:"
},
{
"code": null,
"e": 3436,
"s": 3341,
"text": "XMLDataSource - It allows binding to XML files and strings with or without schema information."
},
{
"code": null,
"e": 3531,
"s": 3436,
"text": "XMLDataSource - It allows binding to XML files and strings with or without schema information."
},
{
"code": null,
"e": 3619,
"s": 3531,
"text": "SiteMapDataSource - It allows binding to a provider that supplies site map information."
},
{
"code": null,
"e": 3707,
"s": 3619,
"text": "SiteMapDataSource - It allows binding to a provider that supplies site map information."
},
{
"code": null,
"e": 3759,
"s": 3707,
"text": "The data source controls used for tabular data are:"
},
{
"code": null,
"e": 3923,
"s": 3759,
"text": "Data source views are objects of the DataSourceView class. Which represent a customized view of data for different data operations such as sorting, filtering, etc."
},
{
"code": null,
"e": 4062,
"s": 3923,
"text": "The DataSourceView class serves as the base class for all data source view classes, which define the capabilities of data source controls."
},
{
"code": null,
"e": 4135,
"s": 4062,
"text": "The following table provides the properties of the DataSourceView class:"
},
{
"code": null,
"e": 4205,
"s": 4135,
"text": "The following table provides the methods of the DataSourceView class:"
},
{
"code": null,
"e": 4485,
"s": 4205,
"text": "The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through two important properties ConnectionString and ProviderName."
},
{
"code": null,
"e": 4554,
"s": 4485,
"text": "The following code snippet provides the basic syntax of the control:"
},
{
"code": null,
"e": 4856,
"s": 4554,
"text": "<asp:SqlDataSource runat=\"server\" ID=\"MySqlSource\"\n ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'\n ConnectionString='<%$ ConnectionStrings:LocalNWind %>'\n SelectionCommand= \"SELECT * FROM EMPLOYEES\" />\n\n<asp:GridView ID=\"GridView1\" runat=\"server\" DataSourceID=\"MySqlSource\" />"
},
{
"code": null,
"e": 4997,
"s": 4856,
"text": "Configuring various data operations on the underlying data depends upon the various properties (property groups) of the data source control."
},
{
"code": null,
"e": 5144,
"s": 4997,
"text": "The following table provides the related sets of properties of the SqlDataSource control, which provides the programming interface of the control:"
},
{
"code": null,
"e": 5159,
"s": 5144,
"text": "DeleteCommand,"
},
{
"code": null,
"e": 5177,
"s": 5159,
"text": "DeleteParameters,"
},
{
"code": null,
"e": 5195,
"s": 5177,
"text": "DeleteCommandType"
},
{
"code": null,
"e": 5213,
"s": 5195,
"text": "FilterExpression,"
},
{
"code": null,
"e": 5230,
"s": 5213,
"text": "FilterParameters"
},
{
"code": null,
"e": 5245,
"s": 5230,
"text": "InsertCommand,"
},
{
"code": null,
"e": 5263,
"s": 5245,
"text": "InsertParameters,"
},
{
"code": null,
"e": 5281,
"s": 5263,
"text": "InsertCommandType"
},
{
"code": null,
"e": 5296,
"s": 5281,
"text": "SelectCommand,"
},
{
"code": null,
"e": 5314,
"s": 5296,
"text": "SelectParameters,"
},
{
"code": null,
"e": 5332,
"s": 5314,
"text": "SelectCommandType"
},
{
"code": null,
"e": 5347,
"s": 5332,
"text": "UpdateCommand,"
},
{
"code": null,
"e": 5365,
"s": 5347,
"text": "UpdateParameters,"
},
{
"code": null,
"e": 5383,
"s": 5365,
"text": "UpdateCommandType"
},
{
"code": null,
"e": 5469,
"s": 5383,
"text": "The following code snippet shows a data source control enabled for data manipulation:"
},
{
"code": null,
"e": 5891,
"s": 5469,
"text": "<asp:SqlDataSource runat=\"server\" ID= \"MySqlSource\"\n ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'\n ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'\n SelectCommand= \"SELECT * FROM EMPLOYEES\"\n UpdateCommand= \"UPDATE EMPLOYEES SET LASTNAME=@lame\"\n DeleteCommand= \"DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid\"\n FilterExpression= \"EMPLOYEEID > 10\">\n .....\n .....\n</asp:SqlDataSource>"
},
{
"code": null,
"e": 6099,
"s": 5891,
"text": "The ObjectDataSource Control enables user-defined classes to associate the output of their methods to data bound controls. The programming interface of this class is almost same as the SqlDataSource control."
},
{
"code": null,
"e": 6164,
"s": 6099,
"text": "Following are two important aspects of binding business objects:"
},
{
"code": null,
"e": 6327,
"s": 6164,
"text": "The bindable class should have a default constructor, it should be stateless, and have methods that can be mapped to select, update, insert, and delete semantics."
},
{
"code": null,
"e": 6490,
"s": 6327,
"text": "The bindable class should have a default constructor, it should be stateless, and have methods that can be mapped to select, update, insert, and delete semantics."
},
{
"code": null,
"e": 6569,
"s": 6490,
"text": "The object must update one item at a time, batch operations are not supported."
},
{
"code": null,
"e": 6648,
"s": 6569,
"text": "The object must update one item at a time, batch operations are not supported."
},
{
"code": null,
"e": 6916,
"s": 6648,
"text": "Let us go directly to an example to work with this control. The student class is the class to be used with an object data source. This class has three properties: a student id, name, and city. It has a default constructor and a GetStudents method for retrieving data."
},
{
"code": null,
"e": 6935,
"s": 6916,
"text": "The student class:"
},
{
"code": null,
"e": 7597,
"s": 6935,
"text": "public class Student\n{\n public int StudentID { get; set; }\n public string Name { get; set; }\n public string City { get; set; }\n \n public Student()\n { }\n \n public DataSet GetStudents()\n {\n DataSet ds = new DataSet();\n DataTable dt = new DataTable(\"Students\");\n \n dt.Columns.Add(\"StudentID\", typeof(System.Int32));\n dt.Columns.Add(\"StudentName\", typeof(System.String));\n dt.Columns.Add(\"StudentCity\", typeof(System.String));\n dt.Rows.Add(new object[] { 1, \"M. H. Kabir\", \"Calcutta\" });\n dt.Rows.Add(new object[] { 2, \"Ayan J. Sarkar\", \"Calcutta\" });\n ds.Tables.Add(dt);\n \n return ds;\n }\n}"
},
{
"code": null,
"e": 7687,
"s": 7597,
"text": "Take the following steps to bind the object with an object data source and retrieve data:"
},
{
"code": null,
"e": 7710,
"s": 7687,
"text": "Create a new web site."
},
{
"code": null,
"e": 7733,
"s": 7710,
"text": "Create a new web site."
},
{
"code": null,
"e": 7882,
"s": 7733,
"text": "Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a class template, and placing the above code in it."
},
{
"code": null,
"e": 8031,
"s": 7882,
"text": "Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a class template, and placing the above code in it."
},
{
"code": null,
"e": 8110,
"s": 8031,
"text": "Build the solution so that the application can use the reference to the class."
},
{
"code": null,
"e": 8189,
"s": 8110,
"text": "Build the solution so that the application can use the reference to the class."
},
{
"code": null,
"e": 8242,
"s": 8189,
"text": "Place an object data source control in the web form."
},
{
"code": null,
"e": 8295,
"s": 8242,
"text": "Place an object data source control in the web form."
},
{
"code": null,
"e": 8346,
"s": 8295,
"text": "Configure the data source by selecting the object."
},
{
"code": null,
"e": 8397,
"s": 8346,
"text": "Configure the data source by selecting the object."
},
{
"code": null,
"e": 8498,
"s": 8397,
"text": "Select a data method(s) for different operations on data. In this example, there is only one method."
},
{
"code": null,
"e": 8599,
"s": 8498,
"text": "Select a data method(s) for different operations on data. In this example, there is only one method."
},
{
"code": null,
"e": 8721,
"s": 8599,
"text": "Place a data bound control such as grid view on the page and select the object data source as its underlying data source."
},
{
"code": null,
"e": 8843,
"s": 8721,
"text": "Place a data bound control such as grid view on the page and select the object data source as its underlying data source."
},
{
"code": null,
"e": 8906,
"s": 8843,
"text": "At this stage, the design view should look like the following:"
},
{
"code": null,
"e": 8969,
"s": 8906,
"text": "At this stage, the design view should look like the following:"
},
{
"code": null,
"e": 9046,
"s": 8969,
"text": "Run the project, it retrieves the hard coded tuples from the students class."
},
{
"code": null,
"e": 9123,
"s": 9046,
"text": "Run the project, it retrieves the hard coded tuples from the students class."
},
{
"code": null,
"e": 9358,
"s": 9123,
"text": "The AccessDataSource control represents a connection to an Access database. It is based on the SqlDataSource control and provides simpler programming interface. The following code snippet provides the basic syntax for the data source:"
},
{
"code": null,
"e": 9542,
"s": 9358,
"text": "<asp:AccessDataSource ID=\"AccessDataSource1 runat=\"server\" \n DataFile=\"~/App_Data/ASPDotNetStepByStep.mdb\" SelectCommand=\"SELECT * FROM [DotNetReferences]\">\n</asp:AccessDataSource>"
},
{
"code": null,
"e": 9758,
"s": 9542,
"text": "The AccessDataSource control opens the database in read-only mode. However, it can also be used for performing insert, update, or delete operations. This is done using the ADO.NET commands and parameter collection."
}
]
|
How to create a new project in Django using Firebase Database? | 13 Oct, 2021
Django is a Python-based web framework that allows you to quickly create efficient web applications. If you are new to Django then you can refer to Django Introduction and Installation. Here we are going to learn How to create a Django project using Firebase as Database .
Step 1: Firstly, We are going to Create a project on Firebase to connect our static web page. Visit Firebase Page For Configuring Your Project – https://console.firebase.google.com/u/0/?pli=1
Click On Add Project Button.
Step 2: Give a Name To your Project and Click On Continue Button.
Step 3: Now Click On Continue Button.
Step 4: Now Choose Default Account For Firebase and Click On Create Project.
Step 5: Now Your Project is created. You are Good to Go. Click on Continue .
Step 6: Now Click On 3rd icon that’s Web Button(</>).
Step 7: Give a nickname to your Web Project and Click On Register App
Step 8: Now you will see the configuration of your App like this. Copy this Code somewhere .You will need it later.
Step 9 : Click On The Realtime Database button As Shown In Figure.
Step 10: Now Click On Create Database.
Step 11: Now Click On Test Mode and then Click On Enable.
Now, We will Add Some Data and will try to Retrieve that using our Website
Now, I hope that you have already create a project in Django. If not then Refer to How to Create a Basic Project using MVT in Django ? Since we are using firebase as Database , We need to install pyrebase . For this Type the following Command in terminal
$pip install pyrebase4
Create a views.py file in your project directly. The Structure should be like this .
Urls.py file
Python3
from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home),]
Views.py
Python3
from django.shortcuts import renderimport pyrebase config={ apiKey: "Use Your Api Key Here", authDomain: "Use Your authDomain Here", databaseURL: "Use Your databaseURL Here", projectId: "Use Your projectId Here", storageBucket: "Use Your storageBucket Here", messagingSenderId: "Use Your messagingSenderId Here", appId: "Use Your appId Here"}firebase=pyrebase.initialize_app(config)authe = firebase.auth()database=firebase.database() def home(request): day = database.child('Data').child('Day').get().val() id = database.child('Data').child('Id').get().val() projectname = database.child('Data').child('Projectname').get().val() return render(request,"Home.html",{"day":day,"id":id,"projectname":projectname })
Home.html
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Sample Project</title></head><body><H1>Project Name is {{ projectname }} </H1><br/><h2>Project Id is {{ id }} </h2><br><h3>Day {{ day }} </h3><br></body></html>
Now move to your project directory and run our project using the given command :
python manage.py runserver
Project Output will be as Follow –
abhishek0719kadiyan
sooda367
Firebase
Technical Scripter 2020
Python
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 328,
"s": 54,
"text": "Django is a Python-based web framework that allows you to quickly create efficient web applications. If you are new to Django then you can refer to Django Introduction and Installation. Here we are going to learn How to create a Django project using Firebase as Database . "
},
{
"code": null,
"e": 520,
"s": 328,
"text": "Step 1: Firstly, We are going to Create a project on Firebase to connect our static web page. Visit Firebase Page For Configuring Your Project – https://console.firebase.google.com/u/0/?pli=1"
},
{
"code": null,
"e": 549,
"s": 520,
"text": "Click On Add Project Button."
},
{
"code": null,
"e": 615,
"s": 549,
"text": "Step 2: Give a Name To your Project and Click On Continue Button."
},
{
"code": null,
"e": 654,
"s": 615,
"text": " Step 3: Now Click On Continue Button."
},
{
"code": null,
"e": 731,
"s": 654,
"text": "Step 4: Now Choose Default Account For Firebase and Click On Create Project."
},
{
"code": null,
"e": 808,
"s": 731,
"text": "Step 5: Now Your Project is created. You are Good to Go. Click on Continue ."
},
{
"code": null,
"e": 863,
"s": 808,
"text": "Step 6: Now Click On 3rd icon that’s Web Button(</>)."
},
{
"code": null,
"e": 934,
"s": 863,
"text": "Step 7: Give a nickname to your Web Project and Click On Register App"
},
{
"code": null,
"e": 1050,
"s": 934,
"text": "Step 8: Now you will see the configuration of your App like this. Copy this Code somewhere .You will need it later."
},
{
"code": null,
"e": 1118,
"s": 1050,
"text": "Step 9 : Click On The Realtime Database button As Shown In Figure. "
},
{
"code": null,
"e": 1157,
"s": 1118,
"text": "Step 10: Now Click On Create Database."
},
{
"code": null,
"e": 1215,
"s": 1157,
"text": "Step 11: Now Click On Test Mode and then Click On Enable."
},
{
"code": null,
"e": 1290,
"s": 1215,
"text": "Now, We will Add Some Data and will try to Retrieve that using our Website"
},
{
"code": null,
"e": 1545,
"s": 1290,
"text": "Now, I hope that you have already create a project in Django. If not then Refer to How to Create a Basic Project using MVT in Django ? Since we are using firebase as Database , We need to install pyrebase . For this Type the following Command in terminal"
},
{
"code": null,
"e": 1568,
"s": 1545,
"text": "$pip install pyrebase4"
},
{
"code": null,
"e": 1653,
"s": 1568,
"text": "Create a views.py file in your project directly. The Structure should be like this ."
},
{
"code": null,
"e": 1666,
"s": 1653,
"text": "Urls.py file"
},
{
"code": null,
"e": 1674,
"s": 1666,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home),]",
"e": 1832,
"s": 1674,
"text": null
},
{
"code": null,
"e": 1841,
"s": 1832,
"text": "Views.py"
},
{
"code": null,
"e": 1849,
"s": 1841,
"text": "Python3"
},
{
"code": "from django.shortcuts import renderimport pyrebase config={ apiKey: \"Use Your Api Key Here\", authDomain: \"Use Your authDomain Here\", databaseURL: \"Use Your databaseURL Here\", projectId: \"Use Your projectId Here\", storageBucket: \"Use Your storageBucket Here\", messagingSenderId: \"Use Your messagingSenderId Here\", appId: \"Use Your appId Here\"}firebase=pyrebase.initialize_app(config)authe = firebase.auth()database=firebase.database() def home(request): day = database.child('Data').child('Day').get().val() id = database.child('Data').child('Id').get().val() projectname = database.child('Data').child('Projectname').get().val() return render(request,\"Home.html\",{\"day\":day,\"id\":id,\"projectname\":projectname })",
"e": 2593,
"s": 1849,
"text": null
},
{
"code": null,
"e": 2606,
"s": 2596,
"text": "Home.html"
},
{
"code": null,
"e": 2611,
"s": 2606,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Sample Project</title></head><body><H1>Project Name is {{ projectname }} </H1><br/><h2>Project Id is {{ id }} </h2><br><h3>Day {{ day }} </h3><br></body></html>",
"e": 2855,
"s": 2611,
"text": null
},
{
"code": null,
"e": 2936,
"s": 2855,
"text": "Now move to your project directory and run our project using the given command :"
},
{
"code": null,
"e": 2963,
"s": 2936,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 2999,
"s": 2963,
"text": "Project Output will be as Follow – "
},
{
"code": null,
"e": 3019,
"s": 2999,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 3028,
"s": 3019,
"text": "sooda367"
},
{
"code": null,
"e": 3037,
"s": 3028,
"text": "Firebase"
},
{
"code": null,
"e": 3061,
"s": 3037,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3068,
"s": 3061,
"text": "Python"
},
{
"code": null,
"e": 3087,
"s": 3068,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3104,
"s": 3087,
"text": "Web Technologies"
},
{
"code": null,
"e": 3202,
"s": 3104,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3220,
"s": 3202,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3262,
"s": 3220,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3284,
"s": 3262,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3319,
"s": 3284,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3351,
"s": 3319,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3413,
"s": 3351,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3446,
"s": 3413,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3507,
"s": 3446,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3557,
"s": 3507,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Maximum non-attacking Rooks that can be placed on an N*N Chessboard | 07 Mar, 2022
Given an integers N such that there is a chessboard of size N*N and an array pos[][] of K pairs of integers which represent the positions of placed rooked in the given chessboard. The task is to find the maximum number of rooks with their positions that can be placed on the given chessboard such that no rook attacks some other rook. Print the positions in lexicographical order.
Examples:
Input: N = 4, K = 2, pos[][] = {{1, 4}, {2, 2}} Output: 2 3 1 4 3 Explanation: Only 2 more rooks can be placed on the given chessboard and their positions are (3, 1) and (4, 3).Input: N = 5, K = 0, pos[][] = {} Output: 5 1 1 2 2 3 3 4 4 5 5 Explanation: Since the chessboard is empty we can place 5 rooks the given chessboard and their positions are (1, 1), (2, 2), (3, 3), (4, 4) and (5, 5).
Naive Approach: The simplest approach is to try to place a rook at every empty position of the chessboard and check if it attacks the already placed rooks or not. Below are the steps:
Initialize a 2D matrix M[][] of size N*N to represent the chessboard and place the already given rooks in it.Transverse the complete matrix M[][] and check if the ith row and jth column contains any rookIf the ith row and jth column both don’t contain any rook, then a rook is placed there and this cell is added to the result.Otherwise, move to the next empty cell on the chessboard.
Initialize a 2D matrix M[][] of size N*N to represent the chessboard and place the already given rooks in it.
Transverse the complete matrix M[][] and check if the ith row and jth column contains any rook
If the ith row and jth column both don’t contain any rook, then a rook is placed there and this cell is added to the result.
Otherwise, move to the next empty cell on the chessboard.
Time Complexity: O(N3) Auxiliary Space: O(N2)
Efficient Approach: The approach is based on the idea that a maximum of (N – K) rooks can be placed on the chessboard according to the Pigeonhole Principle. Below are the steps:
Since no two of the given rooks attack each other, all the rows given in the input must be unique. Similarly, all the columns given in the input must be unique.So, place the rooks only in N – K unused rows and N – K unused columns.Therefore, lexicographically minimum configuration can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column, and so on.
Since no two of the given rooks attack each other, all the rows given in the input must be unique. Similarly, all the columns given in the input must be unique.
So, place the rooks only in N – K unused rows and N – K unused columns.
Therefore, lexicographically minimum configuration can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column, and so on.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the maximum rooks// and their positionsvoid countRooks(int n, int k, int pos[2][2]) { int row[n] = {0}; int col[n] = {0}; // Initialize row and col array for (int i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (int i = 0; i < k; i++) { row[pos[i][0] - 1] = 1; col[pos[i][1] - 1] = 1; } int res = n - k; // Print number of non-attacking // rooks that can be placed cout << res << " " << endl; // To store the placed rook // location int ri = 0, ci = 0; while (res-- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } cout << (ri + 1) << " " << (ci + 1) << " " <<endl; ri++; ci++; } } // Driver Codeint main(){ // Size of board int N = 4; // Number of rooks already placed int K = 2; // Position of rooks int pos[2][2] = {{1, 4}, {2, 2}}; // Function call countRooks(N, K, pos);}// This code is contributed by shikhasingrajput
// Java program for the above approachpublic class GFG { // Function to print the maximum rooks // and their positions private static void countRooks(int n, int k, int pos[][]) { int row[] = new int[n]; int col[] = new int[n]; // Initialize row and col array for (int i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (int i = 0; i < k; i++) { row[pos[i][0] - 1] = 1; col[pos[i][1] - 1] = 1; } int res = n - k; // Print number of non-attacking // rooks that can be placed System.out.println(res + " "); // To store the placed rook // location int ri = 0, ci = 0; while (res-- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } System.out.println( (ri + 1) + " " + (ci + 1) + " "); ri++; ci++; } } // Driver Code public static void main(String[] args) { // Size of board int N = 4; // Number of rooks already placed int K = 2; // Position of rooks int pos[][] = { { 1, 4 }, { 2, 2 } }; // Function call countRooks(N, K, pos); }}
# Python3 program for the above approach# Function to print maximum rooks# and their positionsdef countRooks(n, k, pos): row = [0 for i in range(n)] col = [0 for i in range(n)] # Marking the location of # already placed rooks for i in range(k): row[pos[i][0] - 1] = 1 col[pos[i][1] - 1] = 1 res = n - k # Print number of non-attacking # rooks that can be placed print(res) # To store the placed rook # location ri = 0 ci = 0 while (res > 0): # Print lexicographically # smallest order while (row[ri] == 1): ri += 1 while (col[ci] == 1): ci += 1 print((ri + 1), (ci + 1)) ri += 1 ci += 1 res -= 1 # Driver Codeif __name__ == '__main__': # Size of board N = 4 # Number of rooks already placed K = 2 # Position of rooks pos= [ [ 1, 4 ], [ 2, 2 ] ] # Function call countRooks(N, K, pos) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{ // Function to print the maximum rooks // and their positions private static void countRooks(int n, int k, int [, ]pos) { int []row = new int[n]; int []col = new int[n]; // Initialize row and col array for (int i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (int i = 0; i < k; i++) { row[pos[i, 0] - 1] = 1; col[pos[i, 1] - 1] = 1; } int res = n - k; // Print number of non-attacking // rooks that can be placed Console.WriteLine(res + " "); // To store the placed rook // location int ri = 0, ci = 0; while (res -- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } Console.WriteLine((ri + 1) + " " + (ci + 1) + " "); ri++; ci++; } } // Driver Code public static void Main(String[] args) { // Size of board int N = 4; // Number of rooks already placed int K = 2; // Position of rooks int [, ]pos = {{1, 4}, {2, 2}}; // Function call countRooks(N, K, pos); }} // This code is contributed by Rajput-Ji
<script> // Javascript program to implement// the above approach // Function to print the maximum rooks // and their positions function countRooks(n, k, pos) { let row = new Array(n).fill(0); let col = new Array(n).fill(0); // Initialize row and col array for (let i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (let i = 0; i < k; i++) { row[pos[i][0] - 1] = 1; col[pos[i][1] - 1] = 1; } let res = n - k; // Print number of non-attacking // rooks that can be placed document.write(res + " " + "<br/>"); // To store the placed rook // location let ri = 0, ci = 0; while (res-- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } document.write( (ri + 1) + " " + (ci + 1) + " " + "<br/>"); ri++; ci++; } } // Driver Code // Size of board let N = 4; // Number of rooks already placed let K = 2; // Position of rooks let pos = [[ 1, 4 ], [ 2, 2 ]]; // Function call countRooks(N, K, pos); </script>
2
3 1
4 3
Time Complexity: O(N2) Auxiliary Space: O(N2)
mohit kumar 29
Rajput-Ji
shikhasingrajput
avijitmondal1998
khushboogoyal499
ankita_saini
simranarora5sos
chessboard-problems
Mathematical
Matrix
Searching
Searching
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
Matrix Chain Multiplication | DP-8
Print a given matrix in spiral form
Program to find largest element in an array
Sudoku | Backtracking-7
The Celebrity Problem | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 435,
"s": 54,
"text": "Given an integers N such that there is a chessboard of size N*N and an array pos[][] of K pairs of integers which represent the positions of placed rooked in the given chessboard. The task is to find the maximum number of rooks with their positions that can be placed on the given chessboard such that no rook attacks some other rook. Print the positions in lexicographical order."
},
{
"code": null,
"e": 445,
"s": 435,
"text": "Examples:"
},
{
"code": null,
"e": 838,
"s": 445,
"text": "Input: N = 4, K = 2, pos[][] = {{1, 4}, {2, 2}} Output: 2 3 1 4 3 Explanation: Only 2 more rooks can be placed on the given chessboard and their positions are (3, 1) and (4, 3).Input: N = 5, K = 0, pos[][] = {} Output: 5 1 1 2 2 3 3 4 4 5 5 Explanation: Since the chessboard is empty we can place 5 rooks the given chessboard and their positions are (1, 1), (2, 2), (3, 3), (4, 4) and (5, 5)."
},
{
"code": null,
"e": 1022,
"s": 838,
"text": "Naive Approach: The simplest approach is to try to place a rook at every empty position of the chessboard and check if it attacks the already placed rooks or not. Below are the steps:"
},
{
"code": null,
"e": 1407,
"s": 1022,
"text": "Initialize a 2D matrix M[][] of size N*N to represent the chessboard and place the already given rooks in it.Transverse the complete matrix M[][] and check if the ith row and jth column contains any rookIf the ith row and jth column both don’t contain any rook, then a rook is placed there and this cell is added to the result.Otherwise, move to the next empty cell on the chessboard."
},
{
"code": null,
"e": 1517,
"s": 1407,
"text": "Initialize a 2D matrix M[][] of size N*N to represent the chessboard and place the already given rooks in it."
},
{
"code": null,
"e": 1612,
"s": 1517,
"text": "Transverse the complete matrix M[][] and check if the ith row and jth column contains any rook"
},
{
"code": null,
"e": 1737,
"s": 1612,
"text": "If the ith row and jth column both don’t contain any rook, then a rook is placed there and this cell is added to the result."
},
{
"code": null,
"e": 1795,
"s": 1737,
"text": "Otherwise, move to the next empty cell on the chessboard."
},
{
"code": null,
"e": 1841,
"s": 1795,
"text": "Time Complexity: O(N3) Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 2019,
"s": 1841,
"text": "Efficient Approach: The approach is based on the idea that a maximum of (N – K) rooks can be placed on the chessboard according to the Pigeonhole Principle. Below are the steps:"
},
{
"code": null,
"e": 2467,
"s": 2019,
"text": "Since no two of the given rooks attack each other, all the rows given in the input must be unique. Similarly, all the columns given in the input must be unique.So, place the rooks only in N – K unused rows and N – K unused columns.Therefore, lexicographically minimum configuration can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column, and so on."
},
{
"code": null,
"e": 2628,
"s": 2467,
"text": "Since no two of the given rooks attack each other, all the rows given in the input must be unique. Similarly, all the columns given in the input must be unique."
},
{
"code": null,
"e": 2700,
"s": 2628,
"text": "So, place the rooks only in N – K unused rows and N – K unused columns."
},
{
"code": null,
"e": 2917,
"s": 2700,
"text": "Therefore, lexicographically minimum configuration can be achieved by pairing the smallest unused row with the smallest unused column, the second smallest unused row with the second smallest unused column, and so on."
},
{
"code": null,
"e": 2968,
"s": 2917,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2972,
"s": 2968,
"text": "C++"
},
{
"code": null,
"e": 2977,
"s": 2972,
"text": "Java"
},
{
"code": null,
"e": 2985,
"s": 2977,
"text": "Python3"
},
{
"code": null,
"e": 2988,
"s": 2985,
"text": "C#"
},
{
"code": null,
"e": 2999,
"s": 2988,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the maximum rooks// and their positionsvoid countRooks(int n, int k, int pos[2][2]) { int row[n] = {0}; int col[n] = {0}; // Initialize row and col array for (int i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (int i = 0; i < k; i++) { row[pos[i][0] - 1] = 1; col[pos[i][1] - 1] = 1; } int res = n - k; // Print number of non-attacking // rooks that can be placed cout << res << \" \" << endl; // To store the placed rook // location int ri = 0, ci = 0; while (res-- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } cout << (ri + 1) << \" \" << (ci + 1) << \" \" <<endl; ri++; ci++; } } // Driver Codeint main(){ // Size of board int N = 4; // Number of rooks already placed int K = 2; // Position of rooks int pos[2][2] = {{1, 4}, {2, 2}}; // Function call countRooks(N, K, pos);}// This code is contributed by shikhasingrajput",
"e": 4344,
"s": 2999,
"text": null
},
{
"code": "// Java program for the above approachpublic class GFG { // Function to print the maximum rooks // and their positions private static void countRooks(int n, int k, int pos[][]) { int row[] = new int[n]; int col[] = new int[n]; // Initialize row and col array for (int i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (int i = 0; i < k; i++) { row[pos[i][0] - 1] = 1; col[pos[i][1] - 1] = 1; } int res = n - k; // Print number of non-attacking // rooks that can be placed System.out.println(res + \" \"); // To store the placed rook // location int ri = 0, ci = 0; while (res-- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } System.out.println( (ri + 1) + \" \" + (ci + 1) + \" \"); ri++; ci++; } } // Driver Code public static void main(String[] args) { // Size of board int N = 4; // Number of rooks already placed int K = 2; // Position of rooks int pos[][] = { { 1, 4 }, { 2, 2 } }; // Function call countRooks(N, K, pos); }}",
"e": 5860,
"s": 4344,
"text": null
},
{
"code": "# Python3 program for the above approach# Function to print maximum rooks# and their positionsdef countRooks(n, k, pos): row = [0 for i in range(n)] col = [0 for i in range(n)] # Marking the location of # already placed rooks for i in range(k): row[pos[i][0] - 1] = 1 col[pos[i][1] - 1] = 1 res = n - k # Print number of non-attacking # rooks that can be placed print(res) # To store the placed rook # location ri = 0 ci = 0 while (res > 0): # Print lexicographically # smallest order while (row[ri] == 1): ri += 1 while (col[ci] == 1): ci += 1 print((ri + 1), (ci + 1)) ri += 1 ci += 1 res -= 1 # Driver Codeif __name__ == '__main__': # Size of board N = 4 # Number of rooks already placed K = 2 # Position of rooks pos= [ [ 1, 4 ], [ 2, 2 ] ] # Function call countRooks(N, K, pos) # This code is contributed by mohit kumar 29",
"e": 6900,
"s": 5860,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to print the maximum rooks // and their positions private static void countRooks(int n, int k, int [, ]pos) { int []row = new int[n]; int []col = new int[n]; // Initialize row and col array for (int i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (int i = 0; i < k; i++) { row[pos[i, 0] - 1] = 1; col[pos[i, 1] - 1] = 1; } int res = n - k; // Print number of non-attacking // rooks that can be placed Console.WriteLine(res + \" \"); // To store the placed rook // location int ri = 0, ci = 0; while (res -- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } Console.WriteLine((ri + 1) + \" \" + (ci + 1) + \" \"); ri++; ci++; } } // Driver Code public static void Main(String[] args) { // Size of board int N = 4; // Number of rooks already placed int K = 2; // Position of rooks int [, ]pos = {{1, 4}, {2, 2}}; // Function call countRooks(N, K, pos); }} // This code is contributed by Rajput-Ji",
"e": 8477,
"s": 6900,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to print the maximum rooks // and their positions function countRooks(n, k, pos) { let row = new Array(n).fill(0); let col = new Array(n).fill(0); // Initialize row and col array for (let i = 0; i < n; i++) { row[i] = 0; col[i] = 0; } // Marking the location of // already placed rooks for (let i = 0; i < k; i++) { row[pos[i][0] - 1] = 1; col[pos[i][1] - 1] = 1; } let res = n - k; // Print number of non-attacking // rooks that can be placed document.write(res + \" \" + \"<br/>\"); // To store the placed rook // location let ri = 0, ci = 0; while (res-- > 0) { // Print lexicographically // smallest order while (row[ri] == 1) { ri++; } while (col[ci] == 1) { ci++; } document.write( (ri + 1) + \" \" + (ci + 1) + \" \" + \"<br/>\"); ri++; ci++; } } // Driver Code // Size of board let N = 4; // Number of rooks already placed let K = 2; // Position of rooks let pos = [[ 1, 4 ], [ 2, 2 ]]; // Function call countRooks(N, K, pos); </script>",
"e": 9945,
"s": 8477,
"text": null
},
{
"code": null,
"e": 9957,
"s": 9945,
"text": "2 \n3 1 \n4 3"
},
{
"code": null,
"e": 10004,
"s": 9957,
"text": "Time Complexity: O(N2) Auxiliary Space: O(N2) "
},
{
"code": null,
"e": 10019,
"s": 10004,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 10029,
"s": 10019,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10046,
"s": 10029,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 10063,
"s": 10046,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 10080,
"s": 10063,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 10093,
"s": 10080,
"text": "ankita_saini"
},
{
"code": null,
"e": 10109,
"s": 10093,
"text": "simranarora5sos"
},
{
"code": null,
"e": 10129,
"s": 10109,
"text": "chessboard-problems"
},
{
"code": null,
"e": 10142,
"s": 10129,
"text": "Mathematical"
},
{
"code": null,
"e": 10149,
"s": 10142,
"text": "Matrix"
},
{
"code": null,
"e": 10159,
"s": 10149,
"text": "Searching"
},
{
"code": null,
"e": 10169,
"s": 10159,
"text": "Searching"
},
{
"code": null,
"e": 10182,
"s": 10169,
"text": "Mathematical"
},
{
"code": null,
"e": 10189,
"s": 10182,
"text": "Matrix"
},
{
"code": null,
"e": 10287,
"s": 10189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10311,
"s": 10287,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 10332,
"s": 10311,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 10346,
"s": 10332,
"text": "Prime Numbers"
},
{
"code": null,
"e": 10388,
"s": 10346,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 10441,
"s": 10388,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 10476,
"s": 10441,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 10512,
"s": 10476,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 10556,
"s": 10512,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 10580,
"s": 10556,
"text": "Sudoku | Backtracking-7"
}
]
|
Python | How to get Subtraction of tuples | 21 Nov, 2019
Sometimes, while working with records, we might have a common problem of subtracting contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using map() + lambdaCombination of above functionalities can solve the problem for us. In this, we compute the subtraction using lambda functions and extend the logic to keys using map().
# Python3 code to demonstrate working of# Subtraction of tuples# using map() + lambda # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Subtraction of tuples# using map() + lambdares = tuple(map(lambda i, j: i - j, test_tup1, test_tup2)) # printing resultprint("Resultant tuple after subtraction : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after subtraction : (8, -1, -13)
Method #2 : Using map() + sub()The combination of above functions can help us achieve this task. In this, we first extend the logic to all using map() and then perform subtraction of each index using sub().
# Python3 code to demonstrate working of# Addition of tuples# using map() + sub()import operator # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Addition of tuples# using map() + sub()res = tuple(map(operator.sub, test_tup1, test_tup2)) # printing resultprint("Resultant tuple after subtraction : " + str(res))
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after subtraction : (8, -1, -13)
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 349,
"s": 53,
"text": "Sometimes, while working with records, we might have a common problem of subtracting contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 549,
"s": 349,
"text": "Method #1 : Using map() + lambdaCombination of above functionalities can solve the problem for us. In this, we compute the subtraction using lambda functions and extend the logic to keys using map()."
},
{
"code": "# Python3 code to demonstrate working of# Subtraction of tuples# using map() + lambda # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (2, 5, 18) # printing original tuples print(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Subtraction of tuples# using map() + lambdares = tuple(map(lambda i, j: i - j, test_tup1, test_tup2)) # printing resultprint(\"Resultant tuple after subtraction : \" + str(res))",
"e": 1008,
"s": 549,
"text": null
},
{
"code": null,
"e": 1126,
"s": 1008,
"text": "The original tuple 1 : (10, 4, 5)\nThe original tuple 2 : (2, 5, 18)\nResultant tuple after subtraction : (8, -1, -13)\n"
},
{
"code": null,
"e": 1335,
"s": 1128,
"text": "Method #2 : Using map() + sub()The combination of above functions can help us achieve this task. In this, we first extend the logic to all using map() and then perform subtraction of each index using sub()."
},
{
"code": "# Python3 code to demonstrate working of# Addition of tuples# using map() + sub()import operator # initialize tuples test_tup1 = (10, 4, 5)test_tup2 = (2, 5, 18) # printing original tuples print(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Addition of tuples# using map() + sub()res = tuple(map(operator.sub, test_tup1, test_tup2)) # printing resultprint(\"Resultant tuple after subtraction : \" + str(res))",
"e": 1795,
"s": 1335,
"text": null
},
{
"code": null,
"e": 1913,
"s": 1795,
"text": "The original tuple 1 : (10, 4, 5)\nThe original tuple 2 : (2, 5, 18)\nResultant tuple after subtraction : (8, -1, -13)\n"
},
{
"code": null,
"e": 1935,
"s": 1913,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1942,
"s": 1935,
"text": "Python"
},
{
"code": null,
"e": 1958,
"s": 1942,
"text": "Python Programs"
},
{
"code": null,
"e": 2056,
"s": 1958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2098,
"s": 2056,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2120,
"s": 2098,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2146,
"s": 2120,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2178,
"s": 2146,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2207,
"s": 2178,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2229,
"s": 2207,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2268,
"s": 2229,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2306,
"s": 2268,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2343,
"s": 2306,
"text": "Python Program for Fibonacci numbers"
}
]
|
References in C++ | 02 Jun, 2022
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration.
CPP
#include <iostream>using namespace std; int main(){ int x = 10; // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << "x = " << x << '\n'; // Value of x is now changed to 30 x = 30; cout << "ref = " << ref << '\n'; return 0;}
Output:
x = 20
ref = 30
Applications :
1. Modify the passed parameters in a function: If a function receives a reference to a variable, it can modify the value of the variable. For example, the following program variables are swapped using references.
CPP
#include <iostream>using namespace std; void swap(int& first, int& second){ int temp = first; first = second; second = temp;} int main(){ int a = 2, b = 3; swap(a, b); cout << a << " " << b; return 0;}
Output:
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.
3 2
2. Avoiding a copy of large structures: Imagine a function that has to receive a large object. If we pass it without reference, a new copy of it is created which causes wastage of CPU time and memory. We can use references to avoid this.
CPP
struct Student { string name; string address; int rollNo;} // If we remove & in below function, a new// copy of the student object is created.// We use const to avoid accidental updates// in the function as the purpose of the function// is to print s only.void print(const Student &s){ cout << s.name << " " << s.address << " " << s.rollNo << '\n';}
3. In For Each Loop to modify all objects: We can use references in for each loop to modify all elements.
CPP
#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect{ 10, 20, 30, 40 }; // We can modify elements if we // use reference for (int& x : vect) { x = x + 5; } // Printing elements for (int x : vect) { cout << x << " "; } cout << '\n'; return 0;}
4. For Each Loop to avoid the copy of objects: We can use references in each loop to avoid a copy of individual objects when objects are large.
CPP
#include <bits/stdc++.h>using namespace std; int main(){ vector<string> vect{ "geeksforgeeks practice", "geeksforgeeks write", "geeksforgeeks ide" }; // We avoid copy of the whole string // object by using reference. for (const auto& x : vect) { cout << x << '\n'; } return 0;}
References vs Pointers:
Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.
1. A pointer can be declared as void but a reference can never be void For example
int a = 10;
void* aa = &a; // it is valid
void& ar = a; // it is not valid
2. The pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-pointer, triple-pointer. Whereas, the reference variable has only one/single level of indirection. The following code reveals the mentioned points:
3. Reference variable cannot be updated.
4. Reference variable is an internal pointer.
5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but do not read it as “address of”).
C++
#include <iostream>using namespace std; int main(){ int i = 10; // simple or ordinary variable. int* p = &i; // single pointer int** pt = &p; // double pointer int*** ptr = &pt; // triple pointer // All the above pointers differ in the value they store // or point to. cout << "i = " << i << "\t" << "p = " << p << "\t" << "pt = " << pt << "\t" << "ptr = " << ptr << '\n'; int a = 5; // simple or ordinary variable int& S = a; int& S0 = S; int& S1 = S0; cout << "a = " << a << "\t" << "S = " << S << "\t" << "S0 = " << S0 << "\t" << "S1 = " << S1 << '\n'; // All the above references do not differ in their // values as they all refer to the same variable.}
References are less powerful than pointers1) Once a reference is created, it cannot be later made to reference another object; it cannot be reset. This is often done with pointers. 2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing. 3) A reference must be initialized when declared. There is no such restriction with pointers.Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java is the main reason Java doesn’t need pointers.
References are safer and easier to use: 1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise) 2) Easier to use: References don’t need a dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.
Together with the above reasons, there are few places like the copy constructor argument where pointer cannot be used. Reference must be used to pass the argument in the copy constructor. Similarly, references must be used for overloading some operators like ++.
Exercise: Predict the output of the following programs. If there are compilation errors, then fix them.Question 1
CPP
#include <iostream>using namespace std; int& fun(){ static int x = 10; return x;} int main(){ fun() = 30; cout << fun(); return 0;}
Question 2
CPP
#include <iostream>using namespace std; int fun(int& x) { return x; } int main(){ cout << fun(10); return 0;}
Question 3
CPP
#include <iostream>using namespace std; void swap(char*& str1, char*& str2){ char* temp = str1; str1 = str2; str2 = temp;} int main(){ char* str1 = "GEEKS"; char* str2 = "FOR GEEKS"; swap(str1, str2); cout << "str1 is " << str1 << '\n'; cout << "str2 is " << str2 << '\n'; return 0;}
Question 4
CPP
#include <iostream>using namespace std; int main(){ int x = 10; int* ptr = &x; int&* ptr1 = ptr;}
Question 5
CPP
#include <iostream>using namespace std; int main(){ int* ptr = NULL; int& ref = *ptr; cout << ref << '\n';}
Question 6
CPP
#include <iostream>using namespace std; int& fun(){ int x = 10; return x;} int main(){ fun() = 30; cout << fun(); return 0;}
Related Articles :
Pointers vs References in C++
When do we pass arguments by reference or pointer?
Can references refer to invalid location in C++?
Passing by pointer Vs Passing by Reference in C++
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
pkthapa
BabisSarantoglou
jugranswaranjali99
singhbishalkumarsingh
jparas277
rs1686740
chhabradhanvi
kziemianfvt
jake1924
CPP-Basics
cpp-references
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Function Pointer in C
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
vector erase() and clear() in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 233,
"s": 54,
"text": "When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. "
},
{
"code": null,
"e": 237,
"s": 233,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; int main(){ int x = 10; // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << \"x = \" << x << '\\n'; // Value of x is now changed to 30 x = 30; cout << \"ref = \" << ref << '\\n'; return 0;}",
"e": 538,
"s": 237,
"text": null
},
{
"code": null,
"e": 547,
"s": 538,
"text": "Output: "
},
{
"code": null,
"e": 563,
"s": 547,
"text": "x = 20\nref = 30"
},
{
"code": null,
"e": 580,
"s": 563,
"text": "Applications : "
},
{
"code": null,
"e": 798,
"s": 580,
"text": " 1. Modify the passed parameters in a function: If a function receives a reference to a variable, it can modify the value of the variable. For example, the following program variables are swapped using references. "
},
{
"code": null,
"e": 802,
"s": 798,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; void swap(int& first, int& second){ int temp = first; first = second; second = temp;} int main(){ int a = 2, b = 3; swap(a, b); cout << a << \" \" << b; return 0;}",
"e": 1025,
"s": 802,
"text": null
},
{
"code": null,
"e": 1033,
"s": 1025,
"text": "Output:"
},
{
"code": null,
"e": 1042,
"s": 1033,
"text": "Chapters"
},
{
"code": null,
"e": 1069,
"s": 1042,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1119,
"s": 1069,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1142,
"s": 1119,
"text": "captions off, selected"
},
{
"code": null,
"e": 1150,
"s": 1142,
"text": "English"
},
{
"code": null,
"e": 1174,
"s": 1150,
"text": "This is a modal window."
},
{
"code": null,
"e": 1243,
"s": 1174,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1265,
"s": 1243,
"text": "End of dialog window."
},
{
"code": null,
"e": 1271,
"s": 1265,
"text": " 3 2 "
},
{
"code": null,
"e": 1513,
"s": 1271,
"text": " 2. Avoiding a copy of large structures: Imagine a function that has to receive a large object. If we pass it without reference, a new copy of it is created which causes wastage of CPU time and memory. We can use references to avoid this. "
},
{
"code": null,
"e": 1517,
"s": 1513,
"text": "CPP"
},
{
"code": "struct Student { string name; string address; int rollNo;} // If we remove & in below function, a new// copy of the student object is created.// We use const to avoid accidental updates// in the function as the purpose of the function// is to print s only.void print(const Student &s){ cout << s.name << \" \" << s.address << \" \" << s.rollNo << '\\n';}",
"e": 1889,
"s": 1517,
"text": null
},
{
"code": null,
"e": 1999,
"s": 1889,
"text": " 3. In For Each Loop to modify all objects: We can use references in for each loop to modify all elements. "
},
{
"code": null,
"e": 2003,
"s": 1999,
"text": "CPP"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect{ 10, 20, 30, 40 }; // We can modify elements if we // use reference for (int& x : vect) { x = x + 5; } // Printing elements for (int x : vect) { cout << x << \" \"; } cout << '\\n'; return 0;}",
"e": 2314,
"s": 2003,
"text": null
},
{
"code": null,
"e": 2463,
"s": 2314,
"text": " 4. For Each Loop to avoid the copy of objects: We can use references in each loop to avoid a copy of individual objects when objects are large. "
},
{
"code": null,
"e": 2467,
"s": 2463,
"text": "CPP"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ vector<string> vect{ \"geeksforgeeks practice\", \"geeksforgeeks write\", \"geeksforgeeks ide\" }; // We avoid copy of the whole string // object by using reference. for (const auto& x : vect) { cout << x << '\\n'; } return 0;}",
"e": 2820,
"s": 2467,
"text": null
},
{
"code": null,
"e": 2844,
"s": 2820,
"text": "References vs Pointers:"
},
{
"code": null,
"e": 3208,
"s": 2844,
"text": "Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers."
},
{
"code": null,
"e": 3291,
"s": 3208,
"text": "1. A pointer can be declared as void but a reference can never be void For example"
},
{
"code": null,
"e": 3367,
"s": 3291,
"text": "int a = 10;\nvoid* aa = &a; // it is valid\nvoid& ar = a; // it is not valid"
},
{
"code": null,
"e": 3613,
"s": 3367,
"text": "2. The pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-pointer, triple-pointer. Whereas, the reference variable has only one/single level of indirection. The following code reveals the mentioned points: "
},
{
"code": null,
"e": 3654,
"s": 3613,
"text": "3. Reference variable cannot be updated."
},
{
"code": null,
"e": 3700,
"s": 3654,
"text": "4. Reference variable is an internal pointer."
},
{
"code": null,
"e": 3810,
"s": 3700,
"text": "5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but do not read it as “address of”)."
},
{
"code": null,
"e": 3814,
"s": 3810,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ int i = 10; // simple or ordinary variable. int* p = &i; // single pointer int** pt = &p; // double pointer int*** ptr = &pt; // triple pointer // All the above pointers differ in the value they store // or point to. cout << \"i = \" << i << \"\\t\" << \"p = \" << p << \"\\t\" << \"pt = \" << pt << \"\\t\" << \"ptr = \" << ptr << '\\n'; int a = 5; // simple or ordinary variable int& S = a; int& S0 = S; int& S1 = S0; cout << \"a = \" << a << \"\\t\" << \"S = \" << S << \"\\t\" << \"S0 = \" << S0 << \"\\t\" << \"S1 = \" << S1 << '\\n'; // All the above references do not differ in their // values as they all refer to the same variable.}",
"e": 4562,
"s": 3814,
"text": null
},
{
"code": null,
"e": 5270,
"s": 4562,
"text": "References are less powerful than pointers1) Once a reference is created, it cannot be later made to reference another object; it cannot be reset. This is often done with pointers. 2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing. 3) A reference must be initialized when declared. There is no such restriction with pointers.Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java is the main reason Java doesn’t need pointers. "
},
{
"code": null,
"e": 5871,
"s": 5270,
"text": "References are safer and easier to use: 1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise) 2) Easier to use: References don’t need a dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members. "
},
{
"code": null,
"e": 6134,
"s": 5871,
"text": "Together with the above reasons, there are few places like the copy constructor argument where pointer cannot be used. Reference must be used to pass the argument in the copy constructor. Similarly, references must be used for overloading some operators like ++."
},
{
"code": null,
"e": 6249,
"s": 6134,
"text": "Exercise: Predict the output of the following programs. If there are compilation errors, then fix them.Question 1 "
},
{
"code": null,
"e": 6253,
"s": 6249,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; int& fun(){ static int x = 10; return x;} int main(){ fun() = 30; cout << fun(); return 0;}",
"e": 6400,
"s": 6253,
"text": null
},
{
"code": null,
"e": 6412,
"s": 6400,
"text": "Question 2 "
},
{
"code": null,
"e": 6416,
"s": 6412,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; int fun(int& x) { return x; } int main(){ cout << fun(10); return 0;}",
"e": 6532,
"s": 6416,
"text": null
},
{
"code": null,
"e": 6544,
"s": 6532,
"text": "Question 3 "
},
{
"code": null,
"e": 6548,
"s": 6544,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; void swap(char*& str1, char*& str2){ char* temp = str1; str1 = str2; str2 = temp;} int main(){ char* str1 = \"GEEKS\"; char* str2 = \"FOR GEEKS\"; swap(str1, str2); cout << \"str1 is \" << str1 << '\\n'; cout << \"str2 is \" << str2 << '\\n'; return 0;}",
"e": 6859,
"s": 6548,
"text": null
},
{
"code": null,
"e": 6871,
"s": 6859,
"text": "Question 4 "
},
{
"code": null,
"e": 6875,
"s": 6871,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; int main(){ int x = 10; int* ptr = &x; int&* ptr1 = ptr;}",
"e": 6982,
"s": 6875,
"text": null
},
{
"code": null,
"e": 6994,
"s": 6982,
"text": "Question 5 "
},
{
"code": null,
"e": 6998,
"s": 6994,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; int main(){ int* ptr = NULL; int& ref = *ptr; cout << ref << '\\n';}",
"e": 7115,
"s": 6998,
"text": null
},
{
"code": null,
"e": 7127,
"s": 7115,
"text": "Question 6 "
},
{
"code": null,
"e": 7131,
"s": 7127,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; int& fun(){ int x = 10; return x;} int main(){ fun() = 30; cout << fun(); return 0;}",
"e": 7271,
"s": 7131,
"text": null
},
{
"code": null,
"e": 7291,
"s": 7271,
"text": "Related Articles : "
},
{
"code": null,
"e": 7321,
"s": 7291,
"text": "Pointers vs References in C++"
},
{
"code": null,
"e": 7372,
"s": 7321,
"text": "When do we pass arguments by reference or pointer?"
},
{
"code": null,
"e": 7421,
"s": 7372,
"text": "Can references refer to invalid location in C++?"
},
{
"code": null,
"e": 7471,
"s": 7421,
"text": "Passing by pointer Vs Passing by Reference in C++"
},
{
"code": null,
"e": 7596,
"s": 7471,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 7604,
"s": 7596,
"text": "pkthapa"
},
{
"code": null,
"e": 7621,
"s": 7604,
"text": "BabisSarantoglou"
},
{
"code": null,
"e": 7640,
"s": 7621,
"text": "jugranswaranjali99"
},
{
"code": null,
"e": 7662,
"s": 7640,
"text": "singhbishalkumarsingh"
},
{
"code": null,
"e": 7672,
"s": 7662,
"text": "jparas277"
},
{
"code": null,
"e": 7682,
"s": 7672,
"text": "rs1686740"
},
{
"code": null,
"e": 7696,
"s": 7682,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 7708,
"s": 7696,
"text": "kziemianfvt"
},
{
"code": null,
"e": 7717,
"s": 7708,
"text": "jake1924"
},
{
"code": null,
"e": 7728,
"s": 7717,
"text": "CPP-Basics"
},
{
"code": null,
"e": 7743,
"s": 7728,
"text": "cpp-references"
},
{
"code": null,
"e": 7754,
"s": 7743,
"text": "C Language"
},
{
"code": null,
"e": 7758,
"s": 7754,
"text": "C++"
},
{
"code": null,
"e": 7777,
"s": 7758,
"text": "School Programming"
},
{
"code": null,
"e": 7781,
"s": 7777,
"text": "CPP"
},
{
"code": null,
"e": 7879,
"s": 7781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7902,
"s": 7879,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 7929,
"s": 7902,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 7946,
"s": 7929,
"text": "Substring in C++"
},
{
"code": null,
"e": 8024,
"s": 7946,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 8046,
"s": 8024,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 8064,
"s": 8046,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 8110,
"s": 8064,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 8133,
"s": 8110,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 8160,
"s": 8133,
"text": "Bitwise Operators in C/C++"
}
]
|
Scala - Anonymous Functions | Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values.
Scala supports first-class functions, which means functions can be expressed in function literal syntax, i.e., (x: Int) => x + 1, and that functions can be represented by objects, which are called function values.
Try the following expression, it creates a successor function for integers −
var inc = (x:Int) => x+1
Variable inc is now a function that can be used the usual way −
var x = inc(7)-1
It is also possible to define functions with multiple parameters as follows −
var mul = (x: Int, y: Int) => x*y
Variable mul is now a function that can be used the usual way −
println(mul(3, 4))
It is also possible to define functions with no parameter as follows −
var userDir = () => { System.getProperty("user.dir") }
Variable userDir is now a function that can be used the usual way −
println( userDir )
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2232,
"s": 1998,
"text": "Scala provides a relatively lightweight syntax for defining anonymous functions. Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values."
},
{
"code": null,
"e": 2446,
"s": 2232,
"text": "Scala supports first-class functions, which means functions can be expressed in function literal syntax, i.e., (x: Int) => x + 1, and that functions can be represented by objects, which are called function values."
},
{
"code": null,
"e": 2523,
"s": 2446,
"text": "Try the following expression, it creates a successor function for integers −"
},
{
"code": null,
"e": 2549,
"s": 2523,
"text": "var inc = (x:Int) => x+1\n"
},
{
"code": null,
"e": 2613,
"s": 2549,
"text": "Variable inc is now a function that can be used the usual way −"
},
{
"code": null,
"e": 2631,
"s": 2613,
"text": "var x = inc(7)-1\n"
},
{
"code": null,
"e": 2709,
"s": 2631,
"text": "It is also possible to define functions with multiple parameters as follows −"
},
{
"code": null,
"e": 2744,
"s": 2709,
"text": "var mul = (x: Int, y: Int) => x*y\n"
},
{
"code": null,
"e": 2808,
"s": 2744,
"text": "Variable mul is now a function that can be used the usual way −"
},
{
"code": null,
"e": 2828,
"s": 2808,
"text": "println(mul(3, 4))\n"
},
{
"code": null,
"e": 2899,
"s": 2828,
"text": "It is also possible to define functions with no parameter as follows −"
},
{
"code": null,
"e": 2955,
"s": 2899,
"text": "var userDir = () => { System.getProperty(\"user.dir\") }\n"
},
{
"code": null,
"e": 3023,
"s": 2955,
"text": "Variable userDir is now a function that can be used the usual way −"
},
{
"code": null,
"e": 3043,
"s": 3023,
"text": "println( userDir )\n"
},
{
"code": null,
"e": 3076,
"s": 3043,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3095,
"s": 3076,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3130,
"s": 3095,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3151,
"s": 3130,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 3186,
"s": 3151,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3204,
"s": 3186,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3239,
"s": 3204,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3257,
"s": 3239,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3292,
"s": 3257,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3310,
"s": 3292,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3345,
"s": 3310,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3368,
"s": 3345,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3375,
"s": 3368,
"text": " Print"
},
{
"code": null,
"e": 3386,
"s": 3375,
"text": " Add Notes"
}
]
|
How to add DatePicker in NuxtJS ? - GeeksforGeeks | 13 Dec, 2021
In this article, we are going to learn how we can add a Datepicker in NuxtJs. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of similar purpose, based on React.js.
Approach: To add our DatePicker we are going to use the vuejs-datepicker package. The vuejs-datepicker package helps us to add a DatePicker anywhere in our app. So first, we will install the vuejs-datepicker package and then we will create a vue-datepicker.js file in our plugins folder then we will add the datepicker in our app.
Create NuxtJS Application: You can create a new NuxtJs project using the below command:
npx create-nuxt-app gfg
Install the required package: Now we will install the vuejs-datepicker package using the below command:
npm i vuejs-datepicker
Project Structure: It will look like this
Adding the DatePicker: To add our datepicker, we have to follow the below steps:
Step 1: Create a new file with the name ‘vue-datepicker.js‘ inside the plugins folder. After creating the file add the below content in the file.
Javascript
import Vue from 'vue'import Datepicker from 'vuejs-datepicker'Vue.component('date-picker', Datepicker)
Step 2: Inside the nuxt.config.js file add the below line inside the plugins section:
nuxt.config.js
plugins: [ '@/plugins/view-ui', { src: '~/plugins/vue-datepicker', ssr: false }, ],
Step 3: Now to add the DatePicker inside our app add the below lines inside the index.vue file in pages folder.
index.vue
<template> <div> <h4>GeeksforGeeks - NuxtJs DatePicker</h4> <client-only> <date-picker placeholder="MM/DD/YYYY" format="MM/dd/yyyy" v-model="date_today" /> </client-only> </div></template> <script> export default { data() { return { date_today:new Date() } } }</script>
Explanation: In the above example first, we created the vue-datepicker file in the plugin folder and added the path in nuxt.config.js file. Now we can use the datepicker package anywhere in our app. To add the datepicker we used the <date-picker> component in our index.vue file.
Steps to run the application: Run the below command in the terminal to run the app.
npm run dev
Nuxt.js
Vue.JS
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to update Node.js and NPM to next version ?
Node.js fs.readFile() Method
Node.js fs.writeFile() Method | [
{
"code": null,
"e": 25560,
"s": 25532,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 25836,
"s": 25560,
"text": "In this article, we are going to learn how we can add a Datepicker in NuxtJs. Nuxt.js is a free and open-source web application framework based on Vue.js, Node.js, Webpack, and Babel.js. Nuxt is inspired by Next.js, which is a framework of similar purpose, based on React.js."
},
{
"code": null,
"e": 26167,
"s": 25836,
"text": "Approach: To add our DatePicker we are going to use the vuejs-datepicker package. The vuejs-datepicker package helps us to add a DatePicker anywhere in our app. So first, we will install the vuejs-datepicker package and then we will create a vue-datepicker.js file in our plugins folder then we will add the datepicker in our app."
},
{
"code": null,
"e": 26255,
"s": 26167,
"text": "Create NuxtJS Application: You can create a new NuxtJs project using the below command:"
},
{
"code": null,
"e": 26279,
"s": 26255,
"text": "npx create-nuxt-app gfg"
},
{
"code": null,
"e": 26385,
"s": 26281,
"text": "Install the required package: Now we will install the vuejs-datepicker package using the below command:"
},
{
"code": null,
"e": 26408,
"s": 26385,
"text": "npm i vuejs-datepicker"
},
{
"code": null,
"e": 26450,
"s": 26408,
"text": "Project Structure: It will look like this"
},
{
"code": null,
"e": 26531,
"s": 26450,
"text": "Adding the DatePicker: To add our datepicker, we have to follow the below steps:"
},
{
"code": null,
"e": 26677,
"s": 26531,
"text": "Step 1: Create a new file with the name ‘vue-datepicker.js‘ inside the plugins folder. After creating the file add the below content in the file."
},
{
"code": null,
"e": 26688,
"s": 26677,
"text": "Javascript"
},
{
"code": "import Vue from 'vue'import Datepicker from 'vuejs-datepicker'Vue.component('date-picker', Datepicker)",
"e": 26791,
"s": 26688,
"text": null
},
{
"code": null,
"e": 26877,
"s": 26791,
"text": "Step 2: Inside the nuxt.config.js file add the below line inside the plugins section:"
},
{
"code": null,
"e": 26892,
"s": 26877,
"text": "nuxt.config.js"
},
{
"code": "plugins: [ '@/plugins/view-ui', { src: '~/plugins/vue-datepicker', ssr: false }, ],",
"e": 26983,
"s": 26892,
"text": null
},
{
"code": null,
"e": 27095,
"s": 26983,
"text": "Step 3: Now to add the DatePicker inside our app add the below lines inside the index.vue file in pages folder."
},
{
"code": null,
"e": 27105,
"s": 27095,
"text": "index.vue"
},
{
"code": "<template> <div> <h4>GeeksforGeeks - NuxtJs DatePicker</h4> <client-only> <date-picker placeholder=\"MM/DD/YYYY\" format=\"MM/dd/yyyy\" v-model=\"date_today\" /> </client-only> </div></template> <script> export default { data() { return { date_today:new Date() } } }</script>",
"e": 27432,
"s": 27105,
"text": null
},
{
"code": null,
"e": 27714,
"s": 27432,
"text": "Explanation: In the above example first, we created the vue-datepicker file in the plugin folder and added the path in nuxt.config.js file. Now we can use the datepicker package anywhere in our app. To add the datepicker we used the <date-picker> component in our index.vue file. "
},
{
"code": null,
"e": 27798,
"s": 27714,
"text": "Steps to run the application: Run the below command in the terminal to run the app."
},
{
"code": null,
"e": 27810,
"s": 27798,
"text": "npm run dev"
},
{
"code": null,
"e": 27818,
"s": 27810,
"text": "Nuxt.js"
},
{
"code": null,
"e": 27825,
"s": 27818,
"text": "Vue.JS"
},
{
"code": null,
"e": 27836,
"s": 27825,
"text": "JavaScript"
},
{
"code": null,
"e": 27844,
"s": 27836,
"text": "Node.js"
},
{
"code": null,
"e": 27861,
"s": 27844,
"text": "Web Technologies"
},
{
"code": null,
"e": 27959,
"s": 27861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28020,
"s": 27959,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28061,
"s": 28020,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28101,
"s": 28061,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28155,
"s": 28101,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28203,
"s": 28155,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28236,
"s": 28203,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28269,
"s": 28236,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 28317,
"s": 28269,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28346,
"s": 28317,
"text": "Node.js fs.readFile() Method"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.