Sunday, 27 December 2020

Python: not in: Check for non-existence of element in the list

‘not in’ keyword is return True, if given element is not in the list, else False.

 

Syntax

element not in list

 

Example

10 not in first_5_primes

 

Above statement return True, if 10 is not in the list first_5_primes, else False.

 

Example

10 not in first_5_primes

>>> first_5_primes = [2, 3, 5, 7, 11]
>>> 
>>> 10 not in first_5_primes
True
>>> 
>>> 11 not in first_5_primes
False
>>>

 

 

Previous                                                    Next                                                    Home

Python: in: Check for existence of element in the list

‘in’ keyword is used to check for the existence of an element in the list.

 

Syntax

element in list

 

Example

10 in first_5_primes

 

Above statement return True, if 10 is in first primes list, else False.

>>> first_5_primes = [2, 3, 5, 7, 11]
>>> 
>>> 10 in first_5_primes
False
>>> 
>>> 11 in first_5_primes
True

 

 

 

Previous                                                    Next                                                    Home

Sunday, 20 December 2020

JavaFX: TreeView

 

TreeView class is used to define tree view control. You can dynamically add and delete items from a TreeView.

 

TreeItem

TreeItem defines an item for TreeView.

 

TreeItem class provides following constructors to define a TreeItem.

 

public TreeItem()

Creates an empty TreeItem.

 

public TreeItem(final T value)

Creates a TreeItem with the value property set to the provided object.

 

public TreeItem(final T value, final Node graphic)

Creates a TreeItem with the value property set to the provided object, and the graphic set to the provided Node.

 

Example

TreeItem<String> finance = new TreeItem<>("Finance");

TreeItem<String> financeIndia = new TreeItem<>("India");

TreeItem<String> financeUS = new TreeItem<>("US");

 

Can I add TreeItems to a TreeItem?

Yes

 

Example

finance.getChildren().addAll(financeIndia, financeUS);

 

How to add new TreeItem to given TreeItem instance?

selectedItem.getChildren().add(new TreeItem<String>(newItemName));

 

How to remove TreeItem from TreeItem instance?

selectedItem.getChildren().remove(itemToRemove);

 

TreeView

TreeView class provides following constructors to get an instance of TreeView.

 

public TreeView()

Creates an empty TreeView.

 

public TreeView(TreeItem<T> root)

Creates a TreeView with the provided root node.

 

 

Find the below working application.

 

TreeViewDemo.java

package com.sample.app.widgets;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class TreeViewDemo extends Application {

	private TreeView<String> makeTreeView() {
		TreeItem<String> rootItem = new TreeItem<>("Organization Hierarchy");

		TreeItem<String> finance = new TreeItem<>("Finance");
		TreeItem<String> financeIndia = new TreeItem<>("India");
		TreeItem<String> financeUS = new TreeItem<>("US");

		finance.getChildren().addAll(financeIndia, financeUS);

		TreeItem<String> hr = new TreeItem<>("HR");
		TreeItem<String> hrIndia = new TreeItem<>("India");
		TreeItem<String> hrUS = new TreeItem<>("US");
		hr.getChildren().addAll(hrIndia, hrUS);

		TreeItem<String> technical = new TreeItem<>("Technical");
		TreeItem<String> technicalIndia = new TreeItem<>("India");
		TreeItem<String> technicalUS = new TreeItem<>("US");
		TreeItem<String> technicalUK = new TreeItem<>("UK");

		TreeItem<String> technicalIndia_Bangalore = new TreeItem<>("Bangalore");
		TreeItem<String> technicalIndia_Chennai = new TreeItem<>("Chennai");

		technicalIndia.getChildren().addAll(technicalIndia_Bangalore, technicalIndia_Chennai);

		technical.getChildren().addAll(technicalIndia, technicalUS, technicalUK);

		rootItem.getChildren().addAll(finance, hr, technical);
		rootItem.setExpanded(true);

		TreeView<String> treeView = new TreeView<>(rootItem);

		return treeView;
	}

	@Override
	public void start(Stage primaryStage) throws Exception {

		TreeView<String> treeView = makeTreeView();

		VBox vBox1 = new VBox();

		HBox hBox1 = new HBox();
		hBox1.getChildren().add(treeView);
		hBox1.setPadding(new Insets(40));
		hBox1.setSpacing(50);
		hBox1.setAlignment(Pos.TOP_CENTER);
		hBox1.setStyle("-fx-background-color:lightsalmon");

		Font font = Font.font("Verdana", 20);

		TextField textField = new TextField();
		textField.setFont(font);

		Button addButton = new Button("Add");
		addButton.setFont(font);
		addButton.setTooltip(new Tooltip("Add new item to the tree"));

		addButton.setOnAction(event -> {
			TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();
			String newItemName = textField.getText();

			if (selectedItem == null || newItemName == null || newItemName.isEmpty()) {
				return;
			}

			selectedItem.getChildren().add(new TreeItem<String>(newItemName));

		});

		Button removeButton = new Button("Remove");
		removeButton.setFont(font);
		removeButton.setTooltip(new Tooltip("Remove existing item to the tree"));

		removeButton.setOnAction(event -> {
			TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();

			if (selectedItem.getParent() == null) {
				return;
			}

			selectedItem.getParent().getChildren().remove(selectedItem);

		});

		HBox hBox2 = new HBox();
		hBox2.getChildren().addAll(addButton, textField, removeButton);
		hBox2.setPadding(new Insets(20));
		hBox2.setSpacing(20);
		hBox2.setAlignment(Pos.CENTER);
		hBox2.setStyle("-fx-background-color:lightsalmon");

		vBox1.getChildren().addAll(hBox1, hBox2);

		Scene scene = new Scene(vBox1, 700, 500, Color.WHITE);
		primaryStage.setTitle("TreeView Example");
		primaryStage.setScene(scene);
		primaryStage.show();

	}

	public static void main(String args[]) {
		launch(args);
	}

}

 

Output

 

 


You can expand tree items by clicking on > arrow.


 



You can add new child TreeItem by clicking an parent tree item and enter the item name in text filed and click on Add button.

 

For example, I added ‘Hyderabad’ under Technical -> India.

 


 

Similarly, you can select a tree item and click on Remove button to remove it.


Previous                                                    Next                                                    Home

Python: Iterate over elements of a tuple

Using ‘for’ loop, you can iterate over the elements of a tuple.

 

tuple_iteration.py

emp1 = (1, "Krishna", "Gurram")

for elem in emp1:
   print(elem)

 

Output

$python3 tuple_iteration.py 
1
Krishna
Gurram

 

 

 

Previous                                                    Next                                                    Home

Python: Copy entire list

By creating a slice on existing list, you can copy entire list.

 

Syntax

new_list = existing_list[:]

 

Example

my_hobbies_1 = ["Playing cricket", "Blogging"]

my_hobbies_2 = my_hobbies_1[:]

 

list_copy.py

my_hobbies_1 = ["Playing cricket", "Blogging"]

my_hobbies_2 = my_hobbies_1[:]

print(f"my_hobbies_1 :{my_hobbies_1}")
print(f"my_hobbies_2 :{my_hobbies_2}")

 

Output

 

$ python3 list_copy.py 
my_hobbies_1 :['Playing cricket', 'Blogging']
my_hobbies_2 :['Playing cricket', 'Blogging']

 

When you copy using slice notation, it copies the items in exist list to a completely new list. Let’s confirm the same with below example.

 

list_copy2.py

my_hobbies_1 = ["Playing cricket", "Blogging"]

my_hobbies_2 = my_hobbies_1[:]

print(f"my_hobbies_1 :{my_hobbies_1}")
print(f"my_hobbies_2 :{my_hobbies_2}")

print("\nAdd new hobbies to my_hobbies_1 and my_hobbies_2")

my_hobbies_1.append("watching movies")
my_hobbies_1.append("trekking")
my_hobbies_2.append("reading books")

print(f"\nmy_hobbies_1 :{my_hobbies_1}")
print(f"my_hobbies_2 :{my_hobbies_2}")

 

Output

$ python3 list_copy2.py 
my_hobbies_1 :['Playing cricket', 'Blogging']
my_hobbies_2 :['Playing cricket', 'Blogging']

Add new hobbies to my_hobbies_1 and my_hobbies_2

my_hobbies_1 :['Playing cricket', 'Blogging', 'watching movies', 'trekking']
my_hobbies_2 :['Playing cricket', 'Blogging', 'reading books']

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Python: List comprehensions

 List comprehensions are used to create new lists from other iterables.

 

Syntax

new_list = [expression for_loop_with_one_or_more conditions]

 

Example1: Calculate cubes of numbers

cubes = [value**3 for value in range(1, 11)]

print(cubes)

>>> cubes = [value**3 for value in range(1, 11)]
>>> 
>>> cubes
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>

 

Example 2: Find all the vowels in a string

sentence = 'Hello, How are you'

vowels = [i for i in sentence if i in 'aeiouAEIOU']

>>> vowels = [i for i in sentence if i in 'aeiouAEIOU']
>>> 
>>> vowels
['e', 'o', 'o', 'a', 'e', 'o', 'u']

 

Example 3: Get all even numbers from list of numbers

 

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = [number for number in numbers if number % 2 == 0]

 

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 
>>> even_numbers = [number for number in numbers if number % 2 == 0]
>>> 
>>> even_numbers
[2, 4, 6, 8, 10]

 

You can even use a function in the list comprehension.

>>> def is_even(number):
...   return number % 2 == 0
... 
>>> 
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 
>>> even_numbers = [number for number in numbers if is_even(number)]
>>> 
>>> even_numbers
[2, 4, 6, 8, 10]

 

 

 

 

 

Previous                                                    Next                                                    Home

Python: Get sum of list of numbers

‘sum’ function takes a list as argument and return sum of list of numbers.

>>> list1 = [1, 2, 3, 4, 5]
>>> 
>>> sum(list1)
15

 

 

 

Previous                                                    Next                                                    Home