You are reading the article **Python Program To Sort A Tuple Of Custom Objects By Properties** updated in February 2024 on the website Moimoishop.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 March 2024 Python Program To Sort A Tuple Of Custom Objects By Properties*

Let us now dive into what a custom object in python is. We know that python provides us with a lot of pre-defined datatypes which can be used to store various types of data. But there are times where we have to define custom datatypes that can store data that cannot be represented by built-in datatypes.

For this purpose, python provides us “classes”, these classes help us customize and create that is fit for our needs. A class can have data and function to implement some behavior. An example of implementing a class in python is as follows −

class TempClass: chúng tôi = "" chúng tôi = 0Given above is an example of a class that has a name “TempClass” and stores the name and age with their default values being “” and 0 respectively. We use self to define that we are accessing values of a particular instance of a class and the dot ‘.’ Operator is used to access the elements of a class.

Now that we know what custom objects are in python, we will now see what do we mean by tuple of custom objects. When a tuple is made up of all elements being a custom object, class instances, then we say that we have a tuple of custom objects.

For the examples below, we will be considering a class that has name and age as its data members. And we will make a tuple containing the objects of this class only.

Using the sort() functionThe sort() function is an inbuilt python function which takes the name of list, map, set or tuple as argument and sorts the data structure.

To sort a tuple using the sort function we will have to use the type conversion. The idea will be to store the class objects in an unsorted tuple, then use this tuple and create a list of names and sort it. Use this sorted list of names to sort the entire tuple by names.

AlgorithmStep 1 – Take the number of elements in the tuple as user input

Step 2 – Use the for loop to store the number of objects required, at each iteration input name and age and store a class object with the input values as its data elements.

Step 3 – Create a list called sortedNames, and iterate over the unsortedTuple and store all the name elements of each object in the sortedNames list

Step 4 – Use the sort function on sortedNames list, now we have a list that contains names in sorted order

Step 5 – Create a sortedTuple named tuple, iterate over the sortedNames list using the for loop

Step 6 – Use another nested for loop, to iterate over the unsortedTuple

Step 7 – Check whether the name part of the current object of tuple is the same as the name in the sortedNames list

Step 8 – If yes then store the current object in the sortedTuple list and break out of the inner loop

Step 9 – If no, then continue to the next object of unsorted tuple

Step 10 – Print the elements of sortedTuple

ExampleLet us see an example for this –

class MyTuple: chúng tôi = name chúng tôi = age unsortedTuple =( MyTuple("Vijay",23) , MyTuple("Aman",27), MyTuple("Aastha",21) ) print("Tuple before sorting by names are : ") for person in unsortedTuple: print(f"Name : {person.name} Age : {person.age}") sortedTuple = sorted(unsortedTuple, key= lambda person: person.name) print("Tuple after sorting by names are : ") for person in sortedTuple: print(f"Name : {person.name} Age : {person.age}") Output Tuple before sorting by names are : Name : Raj Age : 23 Name : Aman Age : 21 Name : Suraj Age : 26 Tuple after sorting by names are : Name : Aman Age : 21 Name : Raj Age : 23 Name : Suraj Age : 26 Using the sorted() method with key attributeAlternatively, we can also use the sorted method that is built-in method of python with the key attribute to sort the tuple by properties.

This function returns a sorted list of the specified iterable object. The key attribute takes in a function, usually a lambda function, and sort the iterable based on these keys.

ExampleLet us see an example –

class MyTuple: chúng tôi = name chúng tôi = age unsortedTuple =( MyTuple("Vijay",23) , MyTuple("Aman",27), MyTuple("Aastha",21) ) print("Tuple before sorting by names are : ") for person in unsortedTuple: print(f"Name : {person.name} Age : {person.age}") sortedTuple = sorted(unsortedTuple, key= lambda person: person.name) print("Tuple after sorting by names are : ") for person in sortedTuple: print(f"Name : {person.name} Age : {person.age}") Output Tuple before sorting by names are : Name : Vijay Age : 23 Name : Aman Age : 27 Name : Aastha Age : 21 Tuple after sorting by names are : Name : Aastha Age : 21 Name : Aman Age : 27 Name : Vijay Age : 23 ConclusionIn this article, we saw what a custom object in python is, how we can implement is using classes. We also saw how we can make a tuple of custom objects and how we can make use of sort and sorted methods to sort it by properties.

You're reading __Python Program To Sort A Tuple Of Custom Objects By Properties__

## How To Sort The Objects In A List In Python?

In Python, a list is an ordered sequence that can hold several object types such as integer, character, or float. In other programming languages, a list is equivalent to an array. Square brackets are used to denote it, and a comma (,) is used to divide two items in the list.

In this article, we will show you how to sort the objects and elements in a list using python. Below are the different methods to accomplish this task −

Using sort() method

Using sorted() method

Assume we have taken a list containing some elements. We will return the list elements after sorting either in ascending or descending order.

NOTE − If the object/element of the list is a string the elements are sorted in alphabetical order.

Method 1: Using sort() methodThe sort() method sorts the original list in place. It signifies that the sort() method changes the order of the list’s elements

By default, the sort() method uses the less-than operator (<) to sort the entries of a list i.e, in ascending order. In other words, it prioritizes lesser elements above higher ones.

To sort elements from highest to lowest(descending order), use the reverse=True parameter in the sort() method.

list.sort(reverse=True) Example 1The following program sorts the list elements in ascending and descending order using the sort() method −

lst

=

[

10

,

4

,

12

,

1

,

9

,

5

]

lst

.

sort

(

)

(

“Sorting list items in ascending order: “

,

lst

)

lst

.

sort

(

reverse

=

True

)

(

“Sorting list items in descending order: “

,

lst

)

OutputOn executing, the above program will generate the following output −

Sorting list items in ascending order: [1, 4, 5, 9, 10, 12] Sorting list items in descending order: [12, 10, 9, 5, 4, 1]In this case, we’ve given a list of random values. The sort() method was then applied to the list, which sorted the given list in ascending order and printed the list in ascending order. The same list was then sorted in descending order by passing an additional key to the sort() function, reverse=True, and the list was printed in descending order.

Example:2 For a list containing string valuesThe following program sorts the list elements(string) in ascending and descending order using the sort() method −

lst

=

[

‘hello’

,

‘this’

,

‘is’

,

‘tutorials’

,

‘point’

,

‘website’

,

‘welcome’

,

‘all’

]

lst

.

sort

(

)

(

“Sorting list items in ascending order: “

,

lst

)

lst

.

sort

(

reverse

=

True

)

(

“Sorting list items in descending order: “

,

lst

)

OutputOn executing, the above program will generate the following output −

Sorting list items in ascending order: ['all', 'hello', 'is', 'point', 'this', 'tutorials', 'website', 'welcome'] Sorting list items in descending order: ['welcome', 'website', 'tutorials', 'this', 'point', 'is', 'hello', 'all']We can see that all the elements are sorted in alphabetical order

Method 2: Using sorted() methodThe sorted() function returns a sorted list of the iterable object given.

You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.

Syntax sorted(iterable, key=key, reverse=reverse) Parametersiterable − It is a sequence

key − A function that will be executed to determine the order. The default value is None.

reverse − A Boolean expression. True sorts ascending, False sorts descending. The default value is False.

ExampleThe following program sorts the list elements in ascending and descending order using the sorted() method −

lst

=

[

10

,

4

,

12

,

1

,

9

,

5

]

(

“Sorting list items in ascending order: “

,

sorted

(

lst

)

)

(

“Sorting list items in descending order: “

,

sorted

(

lst

,

reverse

=

True

)

)

OutputOn executing, the above program will generate the following output −

Sorting list items in ascending order: [1, 4, 5, 9, 10, 12] Sorting list items in descending order: [12, 10, 9, 5, 4, 1]In this example, we’ve provided a set of random numbers. We gave the list as an argument to the sorted() method, which sorted and printed the given list in ascending order. The same list was then sorted in descending order by giving an additional key, reverse=True, to the sorted() method, and the list was printed in descending order.

ConclusionIn this article, we learned how to sort list objects/elements using the functions i.e sort() and sorted (). We also learned how to use the same functions to sort a list of items in descending order. We also discussed how the list will be sorted if it contains strings as objects.

## Bucket Sort Algorithm (Java, Python, C/C++ Code Examples)

What is Bucket Sort?

Bucket sort, often called bin sort, is a comparison sort method that accepts an unsorted array as an input and produces a sorted array as a result. This method works by distributing the elements into several buckets and sorting each of those buckets individually by any sorting algorithm such as insertion sort. Then all the buckets are merged together to form a sorted array.

Bucket sort is commonly used when the elements are-

Floating-point values

Uniformly distributed over a range

Bucket sort’s time complexity depends on the number of buckets used and the uniformity of the input distribution. While different sorting algorithms such as shell sort, merge sort, heapsort, and quicksort can achieve the best-case time complexity of O(n*logn), the bucket sorting algorithm can achieve the same in linear time complexity or O(n).

Bucket sort follows the scatter-gather approach. Applying this approach, elements are scattered into the corresponding buckets, sorted in the buckets, and gathered to form a sorted array as the final step. This scatter-gather approach is discussed in the following section

Scatter-Gather-Approach

Large-scale, complex problems can occasionally be challenging to solve. The scatter-gather approach attempts to solve such problems by dividing the entire data set into clusters. Then each cluster is addressed separately and brought everything back together to get the final answer.

This is how the bucket sorting algorithm implements the scatter-gather method:

How Bucket Sort WorksThe basic working principle of bucket sort is as follows:

A set of empty buckets is created. Based on different policies, the number of buckets can differ.

From the input array, put each element into its corresponding bucket.

Sort those buckets individually.

Concatenate the sorted buckets to create a single output array.

The in-detailed work steps are provided in the following sections.

Pseudo Code Start Create N empty buckets For each array element: Calculate bucket index Put that element into the corresponding bucket For each bucket: Sort elements within each bucket Merge all the elements from each bucket Output the sorted array End Method 1: Bucket Sort Algorithm for Floating-Point NumbersThe bucket sorting algorithm for floating point numbers within the range from 0.0 to 1.0:

Step 1) Create ten(10) empty buckets such that the first bucket will contain numbers within the range [0.0, 0.1). Then the second bucket will contain within [0.1, 0.2), and so on.

Step 2) For each array element:

bucket index= no_of_buckets *array_element

b. Insert the element into the bucket[bucket_index]

Step 3) Sort each bucket individually using insertion sort.

Step 4) Concatenate all buckets into a single array.

Let’s see a bucket sort example. For this example, we will sort the following array using the bucket sort algorithm-

Step 1) First, we will create 10 empty buckets. The first bucket will contain the numbers between [0.0, 0.1). Then the second bucket will contain the numbers between [0.1, 0.2) and so on.

Step 2) For each array element, we will calculate the bucket index and place the element into that bucket.

bucket_index= no_of_buckets*array_element

Hence, the element 0.78 will be stored on the bucket[floor(7.8)] or bucket[7].

= 1.7

The array element 0.17 will be stored on bucket[floor(1.7)] or bucket[1].

0.39 will be stored on bucket[floor(3.9)] or bucket[3].

After iterating over all array elements, the buckets will be the following:

Step 3) Then, each bucket will be sorted using insertion sort. After the sorting operation, the output would be:

Step 4) In the final step, the buckets will be concatenated into a single array. That array will be the sorted outcome of the input.

Each bucket will be concatenated to the output array. For example-the concatenation of the second bucket elements:

The concatenation of the last bucket elements will be the following:

After concatenation, the resulting array will be the desired sorted array.

Bucket Sort Program in C/C++Input:

#define BUCKET_SIZE 10 using namespace std; void bucketSort(float input[], int array_size) { for (int i = 0; i < array_size; i++) { int index = BUCKET_SIZE*input[i]; bucket[index].push_back(input[i]); } for (int i = 0; i < BUCKET_SIZE; i++) sort(bucket[i].begin(), bucket[i].end()); int out_index = 0; for (int i = 0; i < BUCKET_SIZE; i++) for (int j = 0; j < bucket[i].size(); j++) input[out_index++] = bucket[i][j]; } int main() { float input[]={0.78,0.17,0.39,0.26,0.72,0.94,0.21,0.12,0.23,0.69}; int array_size = sizeof(input)/sizeof(input[0]); bucketSort(input, array_size); cout <<"Sorted Output: n"; for (int i = 0; i< array_size; i++) cout<<input[i]<<" "; return 0; }Output:

Sorted Output: 0.12 0.17 0.21 0.23 0.26 0.39 0.69 0.72 0.78 0.94 Bucket Sort Program in PythonInput:

# Bucket Sort Program in Python # For not having integer parts def bucketSort(input): output = [] bucket_size = 10 for bucket in range(bucket_size): output.append([]) for element in input: index = int(bucket_size * element) output[index].append(element) for bucket in range(bucket_size): output[bucket] = sorted(output[bucket]) out_index = 0 for bucket in range(bucket_size): for element in range(len(output[bucket])): input[out_index] = output[bucket][element] out_index += 1 return input input = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.69] print("Sorted Output:") print(bucketSort(input))Output:

Sorted Output: [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.69, 0.72, 0.78, 0.94] Bucket Sort in JavaInput:

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BucketSort { private static final int BUCKET_SIZE = 10; public static void bucketSort(float[] input, int arraySize) { List < [] bucket = new ArrayList[BUCKET_SIZE]; for (int i = 0; i < arraySize; i++) { int index = (int)(BUCKET_SIZE * input[i]); if (bucket[index] == null) { (); } bucket[index].add(input[i]); } for (int i = 0; i < BUCKET_SIZE; i++) { if (bucket[i] != null) { Collections.sort(bucket[i]); } } int outIndex = 0; for (int i = 0; i < BUCKET_SIZE; i++) { if (bucket[i] != null) { for (float value: bucket[i]) { input[outIndex++] = value; } } } } public static void main(String[] args) { float[] input = {0.78f,0.17f,0.39f,0.26f,0.72f,0.94f,0.21f,0.12f,0.23f,0.69f}; int arraySize = input.length; bucketSort(input, arraySize); System.out.println("Sorted Output:"); for (int i = 0; i < arraySize; i++) { System.out.print(input[i]+" "); } } }Output:

Sorted Output: 0.12 0.17 0.21 0.23 0.26 0.39 0.69 0.72 0.78 0.94 Method 2: Bucket Sort Algorithm for Integer ElementsThe bucket sort algorithm for the input that contains numbers beyond the range [0.0, 1.0] is a little bit different than the previous algorithm. The steps required for this case are as follows-

Step 1) Find the maximum and minimum elements.

Step 2) Select the number of buckets, n, and initialize those buckets as empty.

span = (maximum - minimum)/n

Step 4) For each array element:

bucket_index = (element - minimum)/span

2.Insert the element into bucket[bucket_index]

Step 5) Sort each bucket using insertion sort.

Step 6) Concatenate all the buckets into a single array.

Let’s see an example of this bucket sort algorithm. For this example, we will sort the following array using the bucket sort algorithm-

Step 1) In the first step, the maximum and minimum elements of the given array need to be found. For this example, the maximum is 24 and the minimum is 1.

Step 2) Now, we have to select a number of empty buckets, n. In this example, we will take 5 buckets. Then we will initialize them as empty.

span = (maximum-minimum)/n = (24-1)/5 = 4;

Hence, the first bucket will contain the numbers within the range [0, 5). The second bucket will contain the numbers within [5, 10) and so on.

bucket_index = (element - minimum)/span

Bucket Index Calculation:

=2

Thus, element 11 will be stored in bucket[2].

=2

Note: As 9 is a boundary element for the bucket[1], it needs to be appended in bucket[1] instead of appending in the same bucket of the previous element.

After performing the operations for each element, the buckets will be as follows:

Step 5) Now, each bucket will be sorted using insertion sort. The buckets after sorting-

Step 6) In the final step, the buckets will be concatenated into a single array. That array will be the sorted outcome of the input.

Bucket Sort Program in C/C++Input:

using namespace std; { double max_value = * max_element(input.begin(), input.end()); double min_value = * min_element(input.begin(), input.end()); double span = (max_value – min_value) / No_Of_Buckets; output; for (int i = 0; i < No_Of_Buckets; i++) ()); for (int i = 0; i < input.size(); i++) { double difference = (input[i] – min_value) / span – int((input[i] – min_value) / span); if (difference == 0 && input[i] != min_value) output[int((input[i] – min_value) / span) – 1] .push_back(input[i]); else output[int((input[i] – min_value) / span)].push_back( input[i]); } for (int i = 0; i < output.size(); i++) { if (!output[i].empty()) sort(output[i].begin(), output[i].end()); } int index = 0; { if (!bucket.empty()) { for (double i: bucket) { input[index] = i; index++; } } } } int main() { input ={11,9,21,8,17,19,13,1,24,12 }; int No_Of_Buckets = 5; bucketSort(input, No_Of_Buckets); cout<< “Sorted Output:”; for (int i; i < input.size(); i++) cout <<input[i]<<” “; return 0; }

Output:

Sorted Output:1 8 9 11 12 13 17 19 21 24 Bucket Sort Program in PythonInput:

def bucketSort(input, No_Of_Buckets): max_element = max(input) min_element = min(input) span = (max_element - min_element) / No_Of_Buckets output = [] for bucket in range(No_Of_Buckets): output.append([]) for element in range(len(input)): diff = (input[element] - min_element) / span - int( (input[element] - min_element) / span ) if diff == 0 and input[element] != min_element: output[int((input[element] - min_element) / span) - 1].append( input[element] ) else: output[int((input[element] - min_element) / span)].append(input[element]) for bucket in range(len(output)): if len(output[bucket]) != 0: output[bucket].sort() index = 0 for bucket in output: if bucket: for element in bucket: input[index] = element index = index + 1 input = [11, 9, 21, 8, 17, 19, 13, 1, 24, 12] No_Of_Buckets = 5 bucketSort(input, No_Of_Buckets) print("Sorted Output:n", input)Output:

Sorted Output: [1, 8, 9, 11, 12, 13, 17, 19, 21, 24] Bucket Sort in JavaInput:

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BucketSort { double max_value = Collections.max(input); double min_value = Collections.min(input); double span =(max_value - min_value) / No_Of_Buckets; List < List < (); for (int i = 0; i < No_Of_Buckets; i++) { ()); } for (Double value: input) { double difference = (value - min_value) / span - ((value - min_value) / span); if (difference == 0 && value != min_value) { output.get((int)((value - min_value) / span) - 1).add(value); } else { output.get((int)((value - min_value) / span)).add(value); } } if (!bucket.isEmpty()) { Collections.sort(bucket); } } int index = 0; if (!bucket.isEmpty()) { for (Double value: bucket) { input.set(index,value); index++; } } } } public static void main(String[] args) { (); input.add(11.0); input.add(9.0); input.add(21.0); input.add(8.0); input.add(17.0); input.add(19.0); input.add(13.0); input.add(1.0); input.add(24.0); input.add(12.0); int No_Of_Buckets = 5; bucketSort(input, No_Of_Buckets); System.out.println("Sorted Output:"); for (Double value: input) { System.out.print(value + " "); } } }Output:

Sorted Output: 1.0 8.0 9.0 11.0 12.0 13.0 17.0 19.0 21.0 24.0 Pros & ConsPros Cons

Perform faster computation Consumes more space compared to other algorithms

It can be used as an external sorting method Performs poorly when the data is not uniformly distributed

Buckets can be processed independently

Bucket Sort Complexity Analysis Bucket Sort’s Time Complexity:

Best Case Complexity:If all the array elements are uniformly distributed and sorted beforehand, it would require O(n) time to scatter the elements into the corresponding buckets. Then sorting each bucket using insertion sort would cost O(k). Thus the overall complexity would be O(n+k).

Average Case Complexity:For average cases, we assume the inputs are uniformly distributed. Thus the bucket sorting algorithm achieves linear time complexity of O(n+k). Here O(n) time is required for scattering the elements and O(k) time is required for sorting those elements using insertion sort.

Worst Case Complexity:In the worst case, the elements will not be uniformly distributed and concentrated over one or two specific buckets. In that case, bucket sort will work as a bubble sort algorithm. Hence, in the worst case, the time complexity of a bucket sort would be O(n^2).

Space Complexity of Bucket Sort:Bucket sort’s space complexity is O(n*k). Here n is the number of elements and k is the number of buckets required.

## Python Program To Remove Numbers With Repeating Digits

In this article, we will learn how to remove numbers with repeating digits in python.

Methods UsedThe following are the various methods to accomplish this task −

Using list comprehension and set() function

Using re module

Using the Counter() function

ExampleAssume we have taken an input list containing numbers. We will now remove all the numbers from the list containing repeating digits and return the resultant list using the above-mentioned methods.

Input inputList = [3352, 8135, 661, 7893, 99] Output [8135, 7893]In the above input list, in the 1st element 3352, 3 is repeated twice. Hence it is removed. But the 8135 has no repeating digits hence it is retained. Similarly, 661, and 99 are removed as they contain repeating characters.

Therefore the output list contains only 8135, 7893 elements.

Method 1: Using list comprehension and set() functionlen() − The number of items in an object is returned by the len() method. The len() function returns the number of characters in a string when the object is a string.

set() function(creates a set object. A set list will appear in random order because the items are not ordered. It removes all the duplicates)

Algorithm (Steps)Following are the Algorithms/steps to be followed to perform the desired task –.

Create a variable to store to the input list and print the given list.

Traverse through numbers(elements) of the given list using list comprehension.

Convert each number to a string using the str() function(returns the string format of the object i.e converts it into a string).

Convert this number string to set using the set() function that removes the duplicate digits of the number.

Check if the length of the string(number) is equal to the length of the above set.

Print the resultant list after removing elements with repeating digits from the input list.

ExampleThe following program returns the resultant list after removing the numbers containing repeating digits from the input list using the list comprehension and set() function –

# input list inputList = [3352, 8135, 661, 7893, 99] # printing the input list print("Input list: ", inputList) # Traversing through the numbers of the list using list comprehension # Convering numbers to string and finding a set of strings (removes duplicates) # Checking if the length of the set is equal to the number of digits resultList = [i for i in inputList if len(set(str(i))) == len(str(i))] # printing resultant list after removing elements with repeating digits print("Resultant list after removing elements with repeating digits:") print(resultList) OutputOn executing, the above program will generate the following output –

Input list: [3352, 8135, 661, 7893, 99] Resultant list after removing elements with repeating digits: [8135, 7893]Time Complexity − O(n)

Auxiliary Space − O(n)

Method 2: Using re module Syntax re.search() functionSearches the entire target string for occurrences of the regex pattern and returns the appropriate Match Object instance where the match was found. It returns only the first match to the pattern from the target string.

Algorithm (Steps)Following are the Algorithm/steps to be followed to perform the desired task –

Use the import keyword to import the re module (regex).

Use the compile() function of re module by giving the regex pattern to remove elements with repeating digits.

Traverse through the elements of the list and check if the list elements match the above regex pattern using the search() function.

Example # importing re module import re # input list inputList = [3352, 8135, 661, 7893, 99] # printing the input list print("Input list: ", inputList) # regex pattern to remove elements with repeating digits # Checking list elements for the above regex pattern matches resultList = [i for i in inputList if not regexPattern.search(str(i))] # printing resultant list after removing elements with repeating digits print("Resultant list after removing elements with repeating digits:") print(resultList) OutputOn executing, the above program will generate the following output –

Input list: [3352, 8135, 661, 7893, 99] Resultant list after removing elements with repeating digits: [8135, 7893]Time Complexity − O(n)

Auxiliary Space − O(n)

Method 3: Using the Counter() functionCounter() function(a sub-class that counts the hashable objects. It implicitly creates a hash table of an iterable when called/invoked).

ExampleThe following program returns the resultant list after removing the numbers containing repeating digits from the input list using the Counter() function –

# importing a Counter function from the collections module from collections import Counter # input list inputList = [3352, 8135, 661, 7893, 99] # printing the input list print("Input list: ", inputList) # Counter gives the unique keys(digits) of the number resultList = [i for i in inputList if len(Counter(str(i))) == len(str(i))] # printing resultant list after removing elements with repeating digits print("Resultant list after removing elements with repeating digits:") print(resultList) OutputOn executing, the above program will generate the following output –

Input list: [3352, 8135, 661, 7893, 99] Resultant list after removing elements with repeating digits: [8135, 7893]Time Complexity − O(n)

Auxiliary Space − O(n)

The frequency of each digit of the number is given by the Counter() method here. It thus has the unique keys (digits) for the given number. The length of the given number was then compared to the number of unique digits returned by the counter

ConclusionIn this article, we learned 3 different methods for removing integers from a list that have repeated digits. Additionally, we learned how to find pattern matches in iterables using the regex module.

## How To Get The Remaining Elements Of The Tuple In C#?

To get the remaining elements of the Tuple, the Rest property is used. The code is as follows −

ExampleLive Demo

using System; public class Demo { public static void Main(String[] args){ var tuple1 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500, 2000); var tuple2 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500, 2000); Console.WriteLine("Is Tuple1 equal to Tuple2? = "+tuple1.Equals(tuple2)); Console.WriteLine("HashCode of Tuple1 = "+tuple1.GetHashCode()); Console.WriteLine("HashCode of Tuple2 = "+tuple2.GetHashCode()); Console.WriteLine("Tuple1 Item 1st = "+tuple1.Item1); Console.WriteLine("Tuple2 Item 1st = "+tuple2.Item1); Console.WriteLine("Tuple1 Item 2nd = "+tuple1.Item2); Console.WriteLine("Tuple2 Item 2nd = "+tuple2.Item2); Console.WriteLine("Tuple1 Item 4th = "+tuple1.Item4); Console.WriteLine("Tuple2 Item 4th = "+tuple2.Item4); Console.WriteLine("Tuple1 Item 5th = "+tuple1.Item5); Console.WriteLine("Tuple2 Item 5th = "+tuple2.Item5); Console.WriteLine("Tuple1 Item 6th = "+tuple1.Item6); Console.WriteLine("Tuple2 Item 6th = "+tuple2.Item6); Console.WriteLine("Tuple1 Item 7th = "+tuple1.Item7); Console.WriteLine("Tuple2 Item 7th = "+tuple2.Item7); Console.WriteLine("Tuple1 rest value = "+tuple1.Rest); Console.WriteLine("Tuple2 rest value = "+tuple2.Rest); } } OutputThis will produce the following output −

Is Tuple1 equal to Tuple2? = True HashCode of Tuple1 = 3247155 HashCode of Tuple2 = 3247155 Tuple1 Item 1st = 75 Tuple2 Item 1st = 75 Tuple1 Item 2nd = 200 Tuple2 Item 2nd = 200 Tuple1 Item 4th = 700 Tuple2 Item 4th = 700 Tuple1 Item 5th = 100 Tuple2 Item 5th = 100 Tuple1 Item 6th = 1200 Tuple2 Item 6th = 1200 Tuple1 Item 7th = 1500 Tuple2 Item 7th = 1500 Tuple1 rest value = (2000) Tuple2 rest value = (2000) ExampleLet us now see another example −

Live Demo

using System; public class Demo { public static void Main(String[] args){ var tuple1 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500, Tuple.Create("AB", 2000, "CD")); var tuple2 = Tuple.Create(75, 200, 500, 700, 100, 1200, 1500, Tuple.Create(2500, 3500, 4000, "XY")); Console.WriteLine("Is Tuple1 equal to Tuple2? = "+tuple1.Equals(tuple2)); Console.WriteLine("HashCode of Tuple1 = "+tuple1.GetHashCode()); Console.WriteLine("HashCode of Tuple2 = "+tuple2.GetHashCode()); Console.WriteLine("Tuple1 Item 1st = "+tuple1.Item1); Console.WriteLine("Tuple2 Item 1st = "+tuple2.Item1); Console.WriteLine("Tuple1 Item 2nd = "+tuple1.Item2); Console.WriteLine("Tuple2 Item 2nd = "+tuple2.Item2); Console.WriteLine("Tuple1 Item 4th = "+tuple1.Item4); Console.WriteLine("Tuple2 Item 4th = "+tuple2.Item4); Console.WriteLine("Tuple1 Item 5th = "+tuple1.Item5); Console.WriteLine("Tuple2 Item 5th = "+tuple2.Item5); Console.WriteLine("Tuple1 Item 6th = "+tuple1.Item6); Console.WriteLine("Tuple2 Item 6th = "+tuple2.Item6); Console.WriteLine("Tuple1 Item 7th = "+tuple1.Item7); Console.WriteLine("Tuple2 Item 7th = "+tuple2.Item7); Console.WriteLine("Tuple1 rest value = "+tuple1.Rest); Console.WriteLine("Tuple2 rest value = "+tuple2.Rest); } } OutputThis will produce the following output −

Is Tuple1 equal to Tuple2? = False HashCode of Tuple1 = -1121878415 HashCode of Tuple2 = -835095725 Tuple1 Item 1st = 75 Tuple2 Item 1st = 75 Tuple1 Item 2nd = 200 Tuple2 Item 2nd = 200 Tuple1 Item 4th = 700 Tuple2 Item 4th = 700 Tuple1 Item 5th = 100 Tuple2 Item 5th = 100 Tuple1 Item 6th = 1200 Tuple2 Item 6th = 1200 Tuple1 Item 7th = 1500 Tuple2 Item 7th = 1500 Tuple1 rest value = ((AB, 2000, CD)) Tuple2 rest value = ((2500, 3500, 4000, XY))## Java Menu Driven Program To Check Type Of A Number

In Java we have primitive numeric data types for numbers that are short, byte, int, long, float and double. These numeric data types allow us to represent different integer and real numbers based on their range as a specific data type has its lower and upper range.

Below are the 6 primitive numeric data types

byte: Range -128 to 127 (Size 1 byte) short: Range -32,768 to 32,767 (Size 2 bytes) int: Range -2,147,483,648 to 2,147,483,647 (Size 4 bytes) long: Range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (8 bytes) float: Range 6 to 7 decimal digits for Fractional Numbers (Size 4 bytes) double: Range 15 decimal digits for Fractional Numbers (Size 8 bytes)In this article we will see how to check the type of number by using Java programming language. We will be implementing the application using a switch case.

To show you some instances Instance-1 Suppose we have taken an integer type of value i.e. 222222 then it must show “number entered is a valid integer”. Instance-2 Suppose we have taken a double type of value i.e 120.0 then it must show “number entered is a valid double”. Instance-3 Suppose we have taken a float type of value i.e 2.1 then it must show “number entered is a valid float”. Instance-4 Suppose we have taken a byte type of value i.e 23 then it must show “number entered is a valid byte”. Instance-5 Suppose we have taken a short type of value i.e 32,765 then it must show “number entered is a valid short”. Instance-6 Suppose we have taken a long type of value i.e 222222222222 then it must show “number entered is a valid long”. SyntaxTo check the type of number we will check its datatype. If the datatype matches then the result will be positive otherwise negative. To check it we have a function called hasNextData_Type.

Following is the syntax to check “integer datatype” −

hasNextInt()Following is the syntax to check “double datatype” −

hasNextDouble()Following is the syntax to check “float datatype” −

hasNextFloat()Following is the syntax to check “byte datatype” −

hasNextByte()Following is the syntax to check “short datatype” −

hasNextShort()Following is the syntax to check “long datatype” −

hasNextLong() AlgorithmStep-1 − Ask the user to enter their choice.

Step-2 − Display the menu.

Step-3 − Ask the user to input the data.

Step-4 − Use a switch case to go to the choice and perform the operation.

Step-5 − Print the result.

Let’s see the program to understand it clearly.

Exampleimport

java

.

util.

*

;

public

class

Main

{

public

static

void

main

(

String

args[

]

)

{

mainLoop:

while

(

true

)

{

Scanner

sc=

new

Scanner

(

System

.

in)

;

System

.

out.

println

(

"n***Menu***"

)

;

System

.

out.

println

(

"1. Check for Integer"

)

;

System

.

out.

println

(

"2. Check for Double"

)

;

System

.

out.

println

(

"3. Check for Float"

)

;

System

.

out.

println

(

"4. Check for Byte"

)

;

System

.

out.

println

(

"5. Check for Short"

)

;

System

.

out.

println

(

"6. Check for Long"

)

;

System

.

out.

println

(

"7. Terminate the program"

)

;

System

.

out.

println

(

"Enter action number (1-7): "

)

;

int

command=

sc.

nextInt

(

)

;

switch

(

command)

{

case

1

:

int

input=

0

;

System

.

out.

println

(

"Enter an integer for its validation"

)

;

if

(

sc.

hasNextInt

(

)

)

{

input=

sc.

nextInt

(

)

;

System

.

out.

println

(

input+

" is a valid Integer"

)

;

}

else

{

System

.

out.

println

(

"It is not a valid Integer"

)

;

}

break

;

case

2

:

double

input1=

0

;

System

.

out.

println

(

"Enter a Double for its validation"

)

;

if

(

sc.

hasNextDouble

(

)

)

{

input1=

sc.

nextDouble

(

)

;

System

.

out.

println

(

input1+

" is a valid Double"

)

;

}

else

{

System

.

out.

println

(

"It is not a valid Double"

)

;

}

break

;

case

3

:

float

input2;

System

.

out.

println

(

"Enter a Float for its validation"

)

;

if

(

sc.

hasNextFloat

(

)

)

{

input2=

sc.

nextFloat

(

)

;

System

.

out.

println

(

input2+

" is a valid Float"

)

;

}

else

{

System

.

out.

println

(

"It is not a valid Float"

)

;

}

break

;

case

4

:

byte

input3=

0

;

System

.

out.

println

(

"Enter a Byte for its validation"

)

;

if

(

sc.

hasNextByte

(

)

)

{

input3=

sc.

nextByte

(

)

;

System

.

out.

println

(

input3+

" is a valid Byte"

)

;

}

else

{

System

.

out.

println

(

"It is not a valid Byte"

)

;

}

break

;

case

5

:

short

input4=

0

;

System

.

out.

println

(

"Enter a Short for its validation"

)

;

if

(

sc.

hasNextShort

(

)

)

{

input4=

sc.

nextShort

(

)

;

System

.

out.

println

(

input4+

" is a valid Short"

)

;

}

else

{

System

.

out.

println

(

"It is not a valid Short"

)

;

}

break

;

case

6

:

long

input5=

0

;

System

.

out.

println

(

"Enter a Short for its validation"

)

;

if

(

sc.

hasNextLong

(

)

)

{

input5=

sc.

nextLong

(

)

;

System

.

out.

println

(

input5+

" is a valid Long"

)

;

}

else

{

System

.

out.

println

(

"It is not a valid Long"

)

;

}

break

;

case

7

:

System

.

out.

println

(

"Program terminated"

)

;

break

mainLoop;

default

:

System

.

out.

println

(

"Wrong choice!!"

)

;

}

}

}

}

Output ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 1 Enter an integer for its validation 22222 22222 is a valid Integer ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 2 Enter a Double for its validation 2.4 2.4 is a valid Double ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 3 Enter a Float for its validation 2.5 2.5 is a valid Float ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 4 Enter a Byte for its validation 123 123 is a valid Byte ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 5 Enter a Short for its validation 1234 1234 is a valid Short ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 6 Enter a Short for its validation 345 345 is a valid Long ***Menu*** 1. Check for Integer 2. Check for Double 3. Check for Float 4. Check for Byte 5. Check for Short 6. Check for Long 7. Terminate the program Enter action number (1-7): 7 Program terminatedIn this article, we explored how to check type of a number in Java by using menu driven approache.

Update the detailed information about **Python Program To Sort A Tuple Of Custom Objects By Properties** on the Moimoishop.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!