You are reading the article Javascript Program For Finding Intersection Of Two Sorted Linked Lists updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Javascript Program For Finding Intersection Of Two Sorted Linked Lists
In this program, we are given two linked lists and we have to create a new linked list that will contain all the elements which are common in both of the lists as the lists are given sorted then we can use the concept of two pointers which are going to see in the article below.
Introduction to ProblemIn the given problem we have to find the intersection of the given linked lists. Intersection means to get the common values from the given set of values, so here we have given two sorted linked lists from which we have to find the elements which are common in both. We have to return a new linked list and not change the values of the given linked lists.
For example −
We are given two sorted linked lists −
If none of the values is the same in both of the linked lists then we have to return an empty linked list that is just an empty node or null value.
ApproachWe have seen the example above for the current problem, in this problem we are going to use the concept of the two pointers. Let’s see each step one by one then we will move to the implementation of the code −
First, we will create a class that will make the linked list structure and will help to bind the data and the pointer of the next node.
Then we will create three head nodes for the given linked lists and the new list to store the answer. Also, we will create a tail node to add the values in the answer-linked list.
We will create a function to travel over the linked list to print all the values of the linked list at once.
There will be a push function to add elements to the linked list that will store the answer or the extra linked list.
The intersection function will be used to implement the main concept which is the two-pointer approach.
We will create the given linked lists and then call the intersection function, and later print the final linked list.
Two Pointer Concept ExampleIn the given problems we have given linked lists in a sorted manner, so if the current number of both the linked lists is equal then we can say that is the intersection of the given linked lists and if that number is not equal then the linked list with the smaller value must have to move forward so that matching value could be found and if and list reaches the end of the null value then we will terminate our search.
var heada = null var headb = null var tail = null var extra = null class Node{ constructor(data){ this.value = data; chúng tôi = null; } } function print(head) { var temp = head var values = 0 while (temp != null) { temp = temp.next; } console.log(values + "null"); } function add(val) { var temp_node = new Node(val); if (extra == null) { extra = temp_node; tail = temp_node; } else { chúng tôi = temp_node; tail = temp_node; } } function intersection() { var tempa = heada var tempb = headb while (tempa != null && tempb != null) { if (tempa.value == tempb.value){ add(tempa.value); tempa = tempa.next; tempb = tempb.next; } else if (tempa.value < tempb.value){ tempa = tempa.next; }else tempb = tempb.next; } } heada = new Node(1); heada.next = new Node(2); heada.next.next = new Node(3); heada.next.next.next = new Node(4); heada.next.next.next.next = new Node(6); headb = new Node(2); headb.next = new Node(4); headb.next.next = new Node(6); headb.next.next.next = new Node(8); intersection(); console.log("The linked list containing the common items of the linked list is: "); print(extra); Time and Space ComplexityThe time complexity of the above code is O(N) where N is the size of the linked list because we are iterating over the linked lists using the two pointers.
The space complexity of the above code is O(1). We are using the extra space here but that extra space is to store the final answer, hence that is not the extra which makes the space complexity constant.
ConclusionIn this tutorial, we have implemented a JavaScript program for finding the intersection of two sorted linked lists. We were given two linked lists and we have to create a new linked list that will contain all the elements which are common in both of the lists as the lists are given sorted then we can use the concept of two pointers. The time complexity of our approach is O(N) where N is the size of the linked lists while the space complexity of the given approach is O(1).
You're reading Javascript Program For Finding Intersection Of Two Sorted Linked Lists
Golang Program To Compare Elements In Two Slices
In this tutorial, we will learn how to compare elements in two slices. In slices a simple equality comparison is not possible so the slices are compared with their lengths and the elements present in the loop. The output will be printed in the form of Boolean value on the console with the help of fmt.Println() function. Let’s see how to execute this with the help of an example.
Method 1: Using a user-defined functionIn this method, we will compare elements in two slices using an external function and, in that function, we will set some conditions, if the slices satisfy those conditions, they will be considered equal else they won’t be considered equal. Let’s have a look to get a better understanding.
Syntax func append(slice, element_1, element_2…, element_N) []TThe append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.
Algorithm
Step 1 − Create a package main and import fmt package in the program.
Step 2 − Create a main function, in it create two slices of type string and call a function named slice_equality with two slices as arguments.
Step 3 − Create a function slice_equality and in that function check if the length of the first slice is not equal to the second slice return false.
Step 4 − In the next case run a for loop till the range of str1 and check if the elements of str2 are equal to str1, if they are not equal return false.
Step 5 − After checking all the conditions set in the algorithm, if not even once false is returned, return true to the function.
Step 6 − Print the Boolean value using fmt.Println() function where ln refers to the next line here.
ExampleGolang program to compare elements in two slices using custom function
package main import "fmt" func slice_equality(str1, str2 []string) bool { if len(str1) != len(str2) { return false } for i, str := range str1 { if str != str2[i] { return false } } return true } func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The slices are equal or not before adding any element:") fmt.Println(slice_equality(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The slices are equal or not after adding another element:") fmt.Println(slice_equality(str1, str2)) } Output The slices are equal or not before adding any element: true The slices are equal or not after adding another element: false Method 2: Using built-in functionIn this method, we will use reflect.DeepEqual() function to compare two slices recursively. Built-in functions ease our work and shorten the code. The output here will be printed using fmt.Println() function. Let’s have a look and inculcate how to solve this problem.
Syntax reflect.DeepEqual()This function compares two values recursively. It traverses and check the equality of the corresponding data values at each level. However, the solution is less safe as compared to comparison in loops. Reflect should be used with care and should be used in those cases where it’s of utmost importance.
func append(slice, element_1, element_2…, element_N) []TThe append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.
Algorithm
Step 1 − Create a package main and import fmt and reflect package in the program.
Step 2 − Create a function main and in that function create two slices of type string which are to be compared with each other.
Step 3 − In the first case before adding any new element in the slice, compare the slices using reflect.DeepEqual() function with the slices as parameters.
Step 4 − In the second case add new string in the slice and compare the slices using reflect.DeepEqual() function with the slices as parameters.
Step 5 − The output will be printed using fmt.Prinln() function on the console as a Boolean value.
ExampleGolang program to compare elements in two slices using built-in function
package main import ( "fmt" "reflect" ) func main() { str1 := []string{"Goa", "Gujarat"} str2 := []string{"Goa", "Gujarat"} fmt.Println("The strings are equal or not before adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) str2 = append(str2, "Mumbai") fmt.Println("The strings are equal or not after adding any element:") fmt.Println(reflect.DeepEqual(str1, str2)) } Output The strings are equal or not before adding any element: true The strings are equal or not after adding any element: false ConclusionIn this tutorial, of comparing slices, we used two methods to execute the program. In the first method we used custom function with some conditions and in the second method we used a built-in function named reflect.DeepEqual() function.
Two States Of Angularjs Validation
Introduction to AngularJS Validation
AngularJS offers client-side form validation. We use AngularJS as a frontend framework that is very scalable and easy to code and developed our single-page angular web application. The AngularJS validation also provides us with more exciting features like form validation, which only validates the user input to the client side without sending it to the backend server for validation. Also, it reduces our backend code and complexity for code maintenance. In angular, we have form validation, and we can also create custom validation as well.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
States of AngularJS ValidationSo in angular js, we have divided the states into two parts. They are specific to form and fields.
1. Input Filed StateAs we input different fields into the form, they possess varying states, outlined below. Each of these fields has a Boolean value of either true or false:
$dirty: This state shows whether the file is modified or not.
$untouched: This state shows whether the current form filed is touched.
$valid: This file holds significance as it showcases that the input data we have provided complies with the requested input.
$touched: It is used to show the field is touched.
$invalid: This file shows that the input we have provided is invalid according to the input we have asked to enter.
$pristine: This indicates that we have not done anything on the filed yet means has not been modified by the user.
2. Form StateThe form state is as follows now all the states will apply for whole form fields, not for specific one or two:
$valid: Apply to the entire form that shows fields are valid.
$dirty: Used to show whether more than one field is modified or not.
$submitted: This state shows that the form is submitted.
$pristine: Apply to the whole form to show more than one file has not been modified yet.
$invalid: This indicates that the form fields are invalid corresponding to the input asked to enter.
Similarly, all these form states also have Boolean values, true or false. We can use these states to show some messages to the user, error messages, or success messages.
Following is an example to show validation:
Code:
Output:
Examples of AngularJS ValidationFields can easily ensure validity by applying built-in validation options such as email and required in Angular.
Example #1Email Validation.
If we have user input that contains the user’s email, we need to verify the input data so we can directly make this field a type of email. It is a feature of HTML5. Below is one example to show how to use this.
Code:
When we provide the correct email format, it will show the below output:
Example #2Required Validation.
This is also an HTML5 feature that makes the filed as required. Below is a simple example to show how to use this.
Code:
Output:
We can also have custom validation, which means we can build our own validation according to the requirement. But that is not easy; we must make many things that make the code tricky to understand. We need to add a new directive to our application as follows.
Example #3Custom Validation.
Code:
var app = angular.module(‘myApp’, []); app.directive(‘myDirective1’, function() { return { require: ‘ngModel’, link: function(scope, element, attr, mCtrl) { function myValidation1(value) { mCtrl.$setValidity(‘charE’, true); } else { mCtrl.$setValidity(‘charE’, false); } return value; } mCtrl.$parsers.push(myValidation1); } }; });
Output:
Here we are adding a new directive named mydirective1. The directive should follow the camel case naming convention. When calling the directive, it should be separated by a hyphen (‘-‘). Furthermore, an object is being returned to ngModel. Now we will make one function that takes argument according to requirement, and here mCTRL1 is the ngModelCotroller. Now test the input by providing some value wrong and right it will return true or false based on the value passed.
ConclusionSo AngularJS validation provides client-side validation before submitting it to the back end. So it reduces some backend calls to improve performance. Also, we can create custom validations by creating a directive in AngularJS, linking them with the controller, and providing logic in functions.
Recommended ArticlesThis is a guide to AngularJS Validation. Here we discuss the introduction and states of AngularJS validation, examples, and code implementation. You may also look at the following articles to learn more –
Swap Two Numbers Without Using A Third Variable: C, Python Program
In programming, language swapping means swapping the value of two variables. The variable might contain a number, string, list or array, object, etc. The general way of swapping is to use a temporary variable to hold values. For example,
The general steps of swapping two numbers are:
Declared a temporary variable C
Assign the value of A to C, meaning C = A. Now C = 20
Assign the value of B to A, So A = 30
Assign the value of C to B, So B = 20, as C has the value 20.
It is how swapping is done with the help of a temporary variable. This method will work both for integer numbers and float numbers as well.
Swap using Arithmetic EquationAs we know, swapping means to interchange the content of two objects or fields or variables. Swap using arithmetic operation means to perform the swap operation using the mathematical equation, i.e., addition and subtraction.
If we’re given two numbers and asked to swap without using a temporary variable, then using three arithmetic equations, we can swap the numbers.
Pseudocode for swapping numbers using arithmetic operation:
A = A + B B = A - B A = A - B
Let’s assume we have two numbers, A = 20 and B = 30.
Condition 1: A = A+B
So, current value of A is 20+30 = 50
Condition 2: B = A-B
We can see that we got the value of A in B
Condition 3: A = A-B
A has the initial value of B.
So, we just swapped the numbers.
Here’s the program to swap two numbers in C/C++:
int main() { int a, b; printf(“Enter value of A: “); scanf(“%d”, & a); printf(“Enter value of B: “); scanf(“%d”, & b); printf(“A = %d, B = %d”, a, b); a = a + b; b = a – b; a = a – b; printf(“nNow, A = %d, B = %d”, a, b); }
Output:
Enter value of A: 20 Enter value of B: 30 A = 20 , B = 30 Now, A = 30 , B = 20Program in Python:
a = int(input("Enter value of A: ")) b = int(input("Enter value of B: ")) print("A = {} and B = {}".format(a, b)) a = a + b b = a - b a = a - b print("Now, A = {} and B = {}".format(a, b))Output:
Enter value of A: 20 Enter value of B: 30 A = 20 , B = 30 Now, A = 30 , B = 20Now in Python, we don’t even need to perform arithmetic operations. We can use:
a,b = b,a
Here’s a demonstration where a=20, b=30;
Swap using Bitwise XOR OperatorThis method is also known as XOR swap. XOR mean exclusive OR. We take two bits as inputs to the XOR in this bitwise operation. To get one output from XOR, only one input must be 1. Otherwise, the output will be 0. The following table shows the output for all combinations of input A B.
We need to know how the XOR operation works to swap two numbers using the bitwise operation. Here’s a table for XOR where A and B is input values.
A B A XOR B
0 0 0
0 1 1
1 0 1
1 1 0
If two input has the same value, then the XOR operation gives 0; otherwise, 1. For this example, we will be using a 3 XOR operation. In most programming languages, XOR is denoted as “^”.
Let’s assume A=4 (in Binary = 0100) and B=7(In Binary, 0111)
Condition 1: A = A ^ B
A 0 1 0 0
B 0 1 1 1
A ^ B 0 0 1 1
Now, A = 0011 (in Binary).
Condition 2: B = A^B
A 0 0 1 1
B 0 1 1 1
A ^ B 0 1 0 0
So B = 0100, which was the initial binary value of A.
Condition 3: A = A^B
A 0 0 1 1
B 0 1 0 0
A ^ B 0 1 1 1
Finally, A = 0111, which was the equivalent binary value of B.
Program in C/C++:
int main() { int a, b; printf(“Enter value of A: “); scanf(“%d”, & a); printf(“Enter value of B: “); scanf(“%d”, & b); printf(“A = %d, B = %d”, a, b); a = a ^ b; b = a ^ b; a = a ^ b; printf(“nNow, A = %d, B = %d”, a, b); }
Output:
Enter value of A:4 Enter value of B:7 A=4, B=7 Now, A=7, B=4.Program in Python:
a = int(input("Enter value of A: ")) b = int(input("Enter value of B: ")) print("A = {} and B = {}".format(a, b)) a = a ^ b b = a ^ b a = a ^ b print("Now, A = {} and B = {}".format(a, b))Output:
Enter the value of A:10 Enter the value of B:15 A=10 and B=15 Now, A=15,B=10. Swap Numbers using Bitwise-ArithmeticThis method is the same as the arithmetic method, but we will use Bitwise operations such as AND, OR, and Compliment to perform addition and subtraction. Before going to the steps, let’s look over” Compliment” quickly.
1’s complement means to change all the 0 to 1 and 1 to 0. Let’s have an example.
Let’s assume a number 23, a decimal number.
Converting to Binary gives use 10111. There are only 5 bits, but the computer stores number in 8,16,32,64 .. bits. So let’s add zero in front of the Binary. It will not change the original value of the number. So it will become 00010111.
As we know, 1’s compliment means to change all the 0 to 1 and 1 to 0, so performing 1’s complement over 00010111 gives 11101000
This 1’s complement is represented with “~” this symbol in most programming languages. Putting this symbol before any integer values or floating-point values will give the 1’s complement.
And 2’s complement means adding binary “1” to the 1’s complement. If we do 2’s complement to the above number:
Binary = 00010111
1’s compliment = 11101000
2’s compliment:
11101000
+ 1
11101001
In summary, for performing 2’s complement of a number A, it will look like:
2’s complement of A = (~A) + 1
Now let’s assume A=8 (binary 00001000), B=10(00001010)
It’s equivalent to A = A + B.
A & B = 00001000 & 00001010 = 00001000
Now, 00001000 + 00001010 = 00010010 (decimal 18)
So, A = 18
Condition 2:
B = A + (~B) + 1
Its equivalent to B = A-B
Here, B = A – B
From the above discussion, if we need to perform subtraction, we perform 2’s complement to the negative number and then add it.
So, -B = ~B + 1
Now, B = 00010010 + (11110101) + 1 = 00001000
B’s value is equivalent to decimal 8, which was the initial value.
Condition 3:
A = A + (~B) + 1
Its equivalent to A = A-B
Now, A = 00010010 + 11110111 + 1
A = 00001010 (equivalent to decimal 10)
Finally, A got the value of B. Thus, the swapping was completed.
Program in C/C++:
int main() { int a, b; printf(“Enter value of A: “); scanf(“%d”, & a); printf(“Enter value of B: “); scanf(“%d”, & b); printf(“A = %d, B = %d”, a, b); b = a + ~b + 1; a = a + ~b + 1; printf(“nNow, A = %d, B = %d”, a, b); }
Output:
Enter the value of A: 8 Enter the value of B:10 A=8, B=10 Now, A=10, B=8Program in Python:
a = int(input("Enter value of A: ")) b = int(input("Enter value of B: ")) print("A = {} and B = {}".format(a, b)) b = a + ~b + 1 a = a + ~b + 1 print("Now, A = {} and B = {}".format(a, b))Output:
Enter the value of A: 25 Enter the value of B: 25 A = 25 and B = 25 Now, A = 25 and B = 25 What is Arithmetic Overflow?Integer number representation in a 32-bit system
The consequence of the arithmetic overflow can be:
The addition of two positive numbers becomes negative. Because the sign bit might become 1, meaning a negative number.
The addition of two negative numbers becomes positive. Because the sign bit might become 0, meaning a positive number.
Implementation Of Linkedlist In Javascript
A linked list is a data structure that consists of a sequence of elements, each of which contains a reference (or “link”) to the next element in the sequence. The first element is called the head and the last element is called the tail.
Defining the Node Class and the LinkedList classThis is basically the prerequisite in order to implement a linked list in JavaScript. In this step, 2 classes namely one for the nodes and the other for the linked list need to be created.
The Node class represents a single node in the linked list. It has two properties which are data and next. The data property is used to store the actual data of the node, whereas the next property is a reference to the next node in the list. The Node class consists of a constructor that initializes the data and next property when creating a new Node.
class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } }The LinkedList class is a representation of the linked list itself. It has a head property that refers to the first node in the list. The LinkedList class also has a constructor that initializes the head property when creating a new LinkedList.
class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } }The LinkedList class also consists of a method that allows you to insert, delete, and search for nodes in the list while simultaneously allowing other operations like printing the list, counting the elements, reversing the list and so on.
Printing the linked listYou can print the elements of a linked list by traversing through the list and printing the data of each node.
printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } Adding Node to the Linked ListThere are multiple methods to add data to a linked list depending on where the new node has to be inserted, and are as follows −
Adding node to the beginning of the linked listTo add node/ element at the start of a linked list, once a new node is created with the data, simply set its next property to the current head of the list. Then you can update the head of the list to the new node. This is also known as Insertion at the head of the linked list and is the most basic type of addition of data. It is simply done by calling the add function defined below.
add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } Adding node to the end of the linked listTo add node/ element at the end of a linked list, we need to traverse the list and find the last node. After which a new node with data is created and we set the next property of the last node to the new node. This is also known as Insertion at the tail of the linked list and is the second most basic type of addition of data. It is simply done by calling the addToTail function defined below.
addToTail(data) { let newNode = new Node(data); if (this.head === null) { chúng tôi = newNode; return; } let current = this.head; while (current.next !== null) { current = current.next; } chúng tôi = newNode; } Adding node at a specific positionTo add node/ element at a specific position in a linked list, you can traverse the list to find the node at the position before the insertion point, create a new node with the data, set the next property of the new node to the current node at the position, and set the next property of the previous node to the new node.
addAtPosition(data, position) { let newNode = new Node(data); if (position === 1) { chúng tôi = this.head; chúng tôi = newNode; return; } let current = this.head; let i = 1; while (i < position - 1 && current) { current = current.next; i++; } if (current) { chúng tôi = current.next; chúng tôi = newNode; } } Example (Adding Nodes to the Linked List)In the below example, we implement adding nodes at beginning, at end and at a specific position.
class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } } class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } addToTail(data) { let newNode = new Node(data); if (this.head === null) { chúng tôi = newNode; return; } let current = this.head; while (current.next !== null) { current = current.next; } chúng tôi = newNode; } addAtPosition(data, position) { let newNode = new Node(data); if (position === 1) { chúng tôi = this.head; chúng tôi = newNode; return; } let current = this.head; let i = 1; while (i < position - 1 && current) { current = current.next; i++; } if (current) { chúng tôi = current.next; chúng tôi = newNode; } } it printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } } const list = new LinkedList(); list.add("node1"); list.add("node2"); list.add("node3"); list.add("node4"); console.log("Initial List:"); list.printAll(); list.addAtPosition("nodex",2); list.printAll(); list.addToTail("nodey"); list.printAll(); Output Initial List: node1 node2 node3 node4 List after adding nodex at position 2 node1 nodex node2 node3 node4 List after adding nodey to tail node1 nodex node2 node3 node4 nodey Removing NodeRemoval of data too, can be done via several methods depending upon the requirement.
Removing a specific nodeTo remove a specific node from a linked list, we need to traverse the list and find the node before the one you want to remove, update its next property to skip over the node you want to remove, and update the reference to the next node. This removes the node based upon the value.
remove(data) { if (!this.head) { return null; } if (this.head.data === data) { chúng tôi = this.head.next; this.length--; return this; } let current = this.head; while (current.next) { if (current.next.data === data) { chúng tôi = current.next.next; this.length--; return this; } current = current.next; } return null; } Removing a node at a Specific PositionTo remove a node at a specific position in a linked list, we need to traverse the list and find the node before the one you want to remove, update its next property to skip over the node you want to remove, and update the reference to the next node. This is basically removing the node based upon the index value of it.
removeAt(index) { if (index === 0) return this.remove(); let current = this.head; for (let i = 0; i < index - 1; i++) { current = current.next; } chúng tôi = current.next.next; this.length--; return this; } Example (Removing Nodes from the Lined List)In the below example, we implement removing a specific node and a node at a specific position.
class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } } class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } remove(data) { if (!this.head) { return null; } if (this.head.data === data) { chúng tôi = this.head.next; this.length--; return this; } let current = this.head; while (current.next) { if (current.next.data === data) { chúng tôi = current.next.next; this.length--; return this; } current = current.next; } return null; } removeAt(index) { if (index === 0) return this.remove(); let current = this.head; for (let i = 0; i < index - 1; i++) { current = current.next; } chúng tôi = current.next.next; this.length--; return this; } printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } } const list = new LinkedList(); list.add("node1"); list.add("node2"); list.add("node3"); list.add("node4"); console.log("Initial List:"); list.printAll(); list.remove("node2"); list.printAll(); list.removeAt(2); list.printAll(); Output Initial List: node1 node2 node3 node4 List after removing node2 node1 node3 node4 List after removing node at index 2 node1 node3 ConclusionImplementing a linked list in JavaScript involves creating a Node class to represent each node in the list and a LinkedList class to represent the list itself, and adding methods to the LinkedList class to perform operations such as adding and removing data, and printing the list. It’s important to also consider edge cases and handle them accordingly in your implementation. There are several ways of adding or removing data from a LinkedList based upon the use case.
Lists Of Options In Tkinter Grid With Various Examples
Introduction to Tkinter Grid
Web development, programming languages, Software testing & others
Syntax:
widget.grid(options_of_grid) Lists of Options in Tkinter GridBelow mentioned are the different options provided:
column: This option is used to put the widget in a column that is leftmost column. The default column is 0.
columnspan: This option keeps track of how many columns it will take to occupy widgets, and by default, this is 1.
ipadx and ipady: These two options are used for how many pixels on the interface to pad the widgets in horizontal and vertical, respectively, but it will be used in padding inside the widgets border.
padx and pady: These two options are similar to the above options, but these are used to pad outside widget borders in horizontal and vertical padding the pixels.
row: This option is when the widget is to put in a row; by default, the first row is empty.
rowspan: This option will be used to tell how many rowwidgets are occupied, and the default value is 1.
sticky: This option is used when a cell cannot fit in the widget, which means when the cell is larger than the widget, then this option is used to know which sides and corners of the widgets the cell can stick to. By default, widgets are always centered in the cell. Sticky uses similar to compass directions to stick the cells to the widgets like North, south, east, west and all the combination of these four.
Examples of Tkinter GridIn this article, we will see the Python grid() method in Tkinter. This method is usually used to design and manage the widgets in the graphical interface. This is a geometry manager to manage the widgets in a table-like structure; usually, a 2-dimensional table is used to manage these widgets in the parent widget, which is in turn split into row and column.
As we saw, that grid is one of the modules or class of geometry manager that is available in Tkinter. There are geometry managers like “pack”, which is also very good and powerful, but it’s very difficult to understand, and another geometry manager is “place”, which gives us complete control of positioning or placing each element. The grid manager is best known for its flexibility, easy to understand, easy to use, and mix features, which makes the grid manager powerful than any other geometry manager.
Now let us see a few examples to understand the grid geometry manager with the following code below:
Example #1 import tkinter as tk courses = ['C','C++','Python','Java','Unix','DevOps'] r = ['course'] for c in courses: tk.Label(text=c, width=15).grid(column=0) tk.Label(text=r, relief=tk.RIDGE, width=15).grid(column=1) tk.mainloop()Output:
Explanation: In the above example, firstly, we need to import Tkinter and then we need to declare the parent cell as “tk”, in which we want the grid layout of the widgets in row and column-wise. So in the above code, we have taken a column as the courses and each row is kept for each course; to do this, we have taken a list of programming languages as a column, and these are labeled as courses for each language row-wise. Hence the grid manages to display it in a two-dimensional table. You can even modify the above code to look it more attractive by using ridges which means it looks like boxes are drawn for every row in relief as you can see in the output, and you can also give some background color by using “big”, and you can have the tabs in the sunken mode for relief.
Example #2 from tkinter import * root = Tk() btn_column = Button(root, text="This is column 2") btn_column.grid(column=2) btn_columnspan = Button(root, text="With columnspan of 4") btn_columnspan.grid(columnspan=4) btn_ipadx = Button(root, text="padding horizontally ipadx of 3") btn_ipadx.grid(ipadx=3) btn_ipady = Button(root, text="padding vertically ipady of 3") btn_ipady.grid(ipady=3) btn_padx = Button(root, text="padx 2") btn_padx.grid(padx=4) btn_pady = Button(root, text="pady of 2") btn_pady.grid(pady=2) btn_row = Button(root, text="This is row 2") btn_row.grid(row=2) btn_rowspan = Button(root, text="With Rowspan of 3") btn_rowspan.grid(rowspan=3) btn_sticky = Button(root, text="Sticking to north-east") btn_sticky.grid(sticky=NE) root.mainloop()Output:
Explanation: In the above program, we have imported Tkinket, and we have imported “*”, which means all the methods or functions in the Tkinter can be imported. Then we are declaring the parent cell as “root” as this is a master widget in which other widgets are placed, and we are calling the “Tk()” method from Tkinter, which is used for creating the main window. At the end of the program, we write “root. mainloop”, where mainloop() is a method from Tkinter again which is used to run your GUI application; when it is ready, it waits for the event to occur and then processes this event until the window is closed. In the above code, we have used a button widget to demonstrate all the grid() class options. So each option is displayed using this widget with their working, or we can say how the options layout of grid works.
ConclusionIn this article, we have seen how to develop the GUI in Python using Tkinter. This Tkinter, in turn, has different geometry managers to make the GUI layout look attractive ad we can use them according to our requirements. The geometry managers are grid() which is very powerful and most widely used, pack() is also used, but as it is a little hard to understand than a grid(), place() manager is used to control the layout. The above article explains about the grid() geometry manager along with the options used in it.
Recommended ArticlesThis is a guide to Tkinter Grid. Here we discuss the Introduction and lists of options in Tkinter Grid along with different examples and code implementation. You may also have a look at the following articles to learn more –
Tkinter Menu
Tkinter Widgets
Tkinter Messagebox
Tkinter Menubutton
Update the detailed information about Javascript Program For Finding Intersection Of Two Sorted Linked Lists on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!