PermutationsA.jl: Permutation Types and Methods

PermutationsA

Data types and methods for permutations

Overview

This module implements representations of permutations: list, disjoint cycles, and matrix, and sparse (not SparseMatrix). This module wraps generic routines in the package PermPlain The name is PermutationsA to distinguish it from the Permutations package. PermutationsA differs from Permutations mainly in that it is broader in scope and avoids copying and validating.

The Julia manual says the AbstractArray type includes everything vaguely array-like. Permutations are at least vaguely array-like. This package defines

     AbstractPerm{T} <: AbstractMatrix{T}

and concrete subtypes:

  • PermList an Array{T,1} corresponding to the one-line form
  • PermCyc an Array{Array{T,1},} corresponding to disjoint-cycle form
  • PermMat acts like a matrix. stores data in one-line form Array{T,1}
  • PermSparse is a Dict which can be thought of as one-line form with fixed points omitted

These types differ both in how they store the data representing the permutation, and in their interaction with other types.

This package is not meant to create a type hierarchy faithfully reproducing mathematical structures. It is also meant to be more than an exercise in learning Julia. Some choices follow those made by other languages that have had implementations of permutations for many years. One goal of the package is efficiency. The objects are lightweight; there is little copying and validation, although copy and isperm methods are provided. For instance this

julia M = rand(10,10) v = randperm(10) kron(PermMat(v),M) performs a Kronecker product taking advantage of the structure of a permutation matrix. PermMat(v) only captures a pointer to v. No copying or construction of a matrix, or list, apart from the output (dense) matrix, is done.

The Kronecker product of two permutations is a permutation. With dense matrices, this would crash your computer,

julia> q = randpermmat(1000);
julia> @time size(kron(q,q))
elapsed time: 0.008285471 seconds (8000208 bytes allocated)
(1000000,1000000)

Object types

AbstractPerm

Every finite permutation can be represented (mathematically) as a matrix. The AbstractPerm type implements some of the properties of permutation matrices that are independent of the way the data is stored in the concrete types. The following methods are defined in AbtractPerm and behave as they would on the Matrix type: det, logdet, rank, trace, ishermitian, issym, istriu, istril, isposdef, null, getindex(i,j), transpose, ctranspose, inv, one, size, eltype. The methods full and sparse which return Matrix and SparseMatrix objects are also implemented here. To support all these methods, some stubs are present in place of low-level methods that must be implemented by the concrete types.

PermMat

This type represents the permutation internally as a vector representing one-line form, but is meant to behave as much as possible like a Matrix. One-line form means that the data vector, operating on [1:n], maps i to data[i]. The majority of the methods for PermMatrix are identical to those of PermList.

PermList

PermList represents the permutation internally in exactly the same way as PermMatrix. It also behaves like a matrix when there is no conflict with its role as a permutation. Note this difference between PermList and PermMat

julia> p = randpermlist(3)
( 3 1 2 )

julia> p * 3    # p maps 3 to 2   # Agrees with Gap
2

julia> 2 / p    # preimage of 2 is 3  # Agrees with Gap
3

julia> m = matrix(p)  # capture the pointer to the data in p, nothing else.
3x3 PermMat{Int64}:   # But the display is different.
 0  0  1
 1  0  0
 0  1  0

julia> m * 3          # PermMat behaves like a matrix whenever possible.
3x3 Array{Int64,2}:
 0  0  3
 3  0  0
 0  3  0

julia> M = rand(3,3); kron(m,M) == kron(p,M)  # kron can't be interpreted another way for a permutation
true

PermCyc

PermCyc stores data internally as an array of arrays representing disjoint cycles in the standard canonical form (described below).

julia> c = permcycs( (1,10^5), (2,3) )   # construct with tuples of disjoint cycles
((1 100000)(2 3))

julia> p = list(c); length(p.data)   # convert to PermList. The data is a big array.
100000

julia> @time c^100000;    # Use efficient algorithm copied from Pari
elapsed time: 2.3248e-5 seconds (320 bytes allocated)

julia> @time p^100000;    # Operate on big list. Julia is really fast, anyway
elapsed time: 0.01122444 seconds (1600192 bytes allocated)

PermSparse

PermSparse stores data internally as a Dict of mappings for all non-fixed elements of the permutation.

julia> s  = psparse(c)             # convert to PermSparse. Displays as disjoint cycles
((1 100000)(2 3))

julia> s.data
Dict{Int64,Int64} with 4 entries:  # stored efficiently
  2      => 3
  3      => 2
  100000 => 1
  1      => 100000

julia> sparse(s)                   # convert to sparse matrix; not the same thing
100000x100000 sparse matrix with 100000 Int64 entries:
        [100000,      1]  =  1
        [3     ,      2]  =  1
        [2     ,      3]  =  1
            ...

Usage

Construction

PermList([10,1,3,6,9,8,4,5,7,2])    # construct from one-line form
PermMat([10,1,3,6,9,8,4,5,7,2])
PermSparse([10,1,3,6,9,8,4,5,7,2])
PermCycs(((1, 6, 2, 7, 9),(3, 8, 4,10, 5)))  # construct from tuples representing cycles

The identity permutation,

PermList() == PermMat() == PermCycs() == PermSparse() == 
 one(PermList) == one(PermMat) == one(PermCycs) == one(PermSparse)
true

isid(one(PermList))
true

plength gives the largest number not mapped to itself. Zero means that all numbers are mapped to themselves.

0 == plength(PermMat()) == plength(PermList()) ==
 plength(PermCycs()) == plength(PermSparse())
true 

For PermCycs and PermSparse there is only one representation of the identity. For PermList and PermMat there are many representations of the identity.

julia> one(PermList,10)
( 1  2  3  4  5  6  7  8  9  10 )

one(PermList) == one(PermList,10) == one(PermMat,20) == one(PermCycs)
true

The domain of each permutation is all positive integers.

julia> p = randpermlist(10)
( 10 7  4  2  1  8  3  5  6  9  )

julia> p * 3
4

julia> p * 100
100

julia> psparse(p) * 100  # sparse(p) means SparseMatrix
100

julia> 4 == p * 3 == psparse(p) * 3 == cycles(p) * 3  # These are all the same
true

PermMat is different

julia> size(PermMat(p) * 100)   # Not same, not application of the permutation
(10,10)

julia> pmap(PermMat(p),100)  # Same for all permutation types
100

julia> p[1]     # also application of permutation
10

julia> show(matrix(p)[1:10])  # first column of the matrix
[0,0,0,0,1,0,0,0,0,0]

Sundry

Use list, cycles, psparse, and matrix to convert from one type to another. Use pivtopermlist to convert the 'pivot' vector to PermList, and topiv to convert an AbstractPerm to a pivot vector.

Use full(p) and sparse(p) to get dense and sparse matrices from any permutation type.

aprint,cprint,lprint,mprint,astring,cstring,lstring,mstring: Print or make strings of any type in various forms.

* ^ : composition and power, using various algorithms. ppow(c::PermCyc,n) gives power of c as a PermList using an algorithm from Pari that may be more efficient than list(c^n).

randpermlist, randpermcycs, randpermmat, randpermsparse, randperm(type,n) : generate random permutations

numcycles finds the number of cycles (excluding 1-cycles). iscyclic returns true if the permutation is cyclic. We allow fixed points in a cyclic permutation.

Permutation types support element type parameters,

julia> typeof(PermList(Int32[3,2,1]))
PermList{Int32} (constructor with 1 method)

For other features, see the test and source files.

Download Details:

Author: jlapeyre
Source Code: https://github.com/jlapeyre/PermutationsA.jl 
License: View license

#julia #types #methods 

What is GEEK

Buddha Community

PermutationsA.jl: Permutation Types and Methods

PermutationsA.jl: Permutation Types and Methods

PermutationsA

Data types and methods for permutations

Overview

This module implements representations of permutations: list, disjoint cycles, and matrix, and sparse (not SparseMatrix). This module wraps generic routines in the package PermPlain The name is PermutationsA to distinguish it from the Permutations package. PermutationsA differs from Permutations mainly in that it is broader in scope and avoids copying and validating.

The Julia manual says the AbstractArray type includes everything vaguely array-like. Permutations are at least vaguely array-like. This package defines

     AbstractPerm{T} <: AbstractMatrix{T}

and concrete subtypes:

  • PermList an Array{T,1} corresponding to the one-line form
  • PermCyc an Array{Array{T,1},} corresponding to disjoint-cycle form
  • PermMat acts like a matrix. stores data in one-line form Array{T,1}
  • PermSparse is a Dict which can be thought of as one-line form with fixed points omitted

These types differ both in how they store the data representing the permutation, and in their interaction with other types.

This package is not meant to create a type hierarchy faithfully reproducing mathematical structures. It is also meant to be more than an exercise in learning Julia. Some choices follow those made by other languages that have had implementations of permutations for many years. One goal of the package is efficiency. The objects are lightweight; there is little copying and validation, although copy and isperm methods are provided. For instance this

julia M = rand(10,10) v = randperm(10) kron(PermMat(v),M) performs a Kronecker product taking advantage of the structure of a permutation matrix. PermMat(v) only captures a pointer to v. No copying or construction of a matrix, or list, apart from the output (dense) matrix, is done.

The Kronecker product of two permutations is a permutation. With dense matrices, this would crash your computer,

julia> q = randpermmat(1000);
julia> @time size(kron(q,q))
elapsed time: 0.008285471 seconds (8000208 bytes allocated)
(1000000,1000000)

Object types

AbstractPerm

Every finite permutation can be represented (mathematically) as a matrix. The AbstractPerm type implements some of the properties of permutation matrices that are independent of the way the data is stored in the concrete types. The following methods are defined in AbtractPerm and behave as they would on the Matrix type: det, logdet, rank, trace, ishermitian, issym, istriu, istril, isposdef, null, getindex(i,j), transpose, ctranspose, inv, one, size, eltype. The methods full and sparse which return Matrix and SparseMatrix objects are also implemented here. To support all these methods, some stubs are present in place of low-level methods that must be implemented by the concrete types.

PermMat

This type represents the permutation internally as a vector representing one-line form, but is meant to behave as much as possible like a Matrix. One-line form means that the data vector, operating on [1:n], maps i to data[i]. The majority of the methods for PermMatrix are identical to those of PermList.

PermList

PermList represents the permutation internally in exactly the same way as PermMatrix. It also behaves like a matrix when there is no conflict with its role as a permutation. Note this difference between PermList and PermMat

julia> p = randpermlist(3)
( 3 1 2 )

julia> p * 3    # p maps 3 to 2   # Agrees with Gap
2

julia> 2 / p    # preimage of 2 is 3  # Agrees with Gap
3

julia> m = matrix(p)  # capture the pointer to the data in p, nothing else.
3x3 PermMat{Int64}:   # But the display is different.
 0  0  1
 1  0  0
 0  1  0

julia> m * 3          # PermMat behaves like a matrix whenever possible.
3x3 Array{Int64,2}:
 0  0  3
 3  0  0
 0  3  0

julia> M = rand(3,3); kron(m,M) == kron(p,M)  # kron can't be interpreted another way for a permutation
true

PermCyc

PermCyc stores data internally as an array of arrays representing disjoint cycles in the standard canonical form (described below).

julia> c = permcycs( (1,10^5), (2,3) )   # construct with tuples of disjoint cycles
((1 100000)(2 3))

julia> p = list(c); length(p.data)   # convert to PermList. The data is a big array.
100000

julia> @time c^100000;    # Use efficient algorithm copied from Pari
elapsed time: 2.3248e-5 seconds (320 bytes allocated)

julia> @time p^100000;    # Operate on big list. Julia is really fast, anyway
elapsed time: 0.01122444 seconds (1600192 bytes allocated)

PermSparse

PermSparse stores data internally as a Dict of mappings for all non-fixed elements of the permutation.

julia> s  = psparse(c)             # convert to PermSparse. Displays as disjoint cycles
((1 100000)(2 3))

julia> s.data
Dict{Int64,Int64} with 4 entries:  # stored efficiently
  2      => 3
  3      => 2
  100000 => 1
  1      => 100000

julia> sparse(s)                   # convert to sparse matrix; not the same thing
100000x100000 sparse matrix with 100000 Int64 entries:
        [100000,      1]  =  1
        [3     ,      2]  =  1
        [2     ,      3]  =  1
            ...

Usage

Construction

PermList([10,1,3,6,9,8,4,5,7,2])    # construct from one-line form
PermMat([10,1,3,6,9,8,4,5,7,2])
PermSparse([10,1,3,6,9,8,4,5,7,2])
PermCycs(((1, 6, 2, 7, 9),(3, 8, 4,10, 5)))  # construct from tuples representing cycles

The identity permutation,

PermList() == PermMat() == PermCycs() == PermSparse() == 
 one(PermList) == one(PermMat) == one(PermCycs) == one(PermSparse)
true

isid(one(PermList))
true

plength gives the largest number not mapped to itself. Zero means that all numbers are mapped to themselves.

0 == plength(PermMat()) == plength(PermList()) ==
 plength(PermCycs()) == plength(PermSparse())
true 

For PermCycs and PermSparse there is only one representation of the identity. For PermList and PermMat there are many representations of the identity.

julia> one(PermList,10)
( 1  2  3  4  5  6  7  8  9  10 )

one(PermList) == one(PermList,10) == one(PermMat,20) == one(PermCycs)
true

The domain of each permutation is all positive integers.

julia> p = randpermlist(10)
( 10 7  4  2  1  8  3  5  6  9  )

julia> p * 3
4

julia> p * 100
100

julia> psparse(p) * 100  # sparse(p) means SparseMatrix
100

julia> 4 == p * 3 == psparse(p) * 3 == cycles(p) * 3  # These are all the same
true

PermMat is different

julia> size(PermMat(p) * 100)   # Not same, not application of the permutation
(10,10)

julia> pmap(PermMat(p),100)  # Same for all permutation types
100

julia> p[1]     # also application of permutation
10

julia> show(matrix(p)[1:10])  # first column of the matrix
[0,0,0,0,1,0,0,0,0,0]

Sundry

Use list, cycles, psparse, and matrix to convert from one type to another. Use pivtopermlist to convert the 'pivot' vector to PermList, and topiv to convert an AbstractPerm to a pivot vector.

Use full(p) and sparse(p) to get dense and sparse matrices from any permutation type.

aprint,cprint,lprint,mprint,astring,cstring,lstring,mstring: Print or make strings of any type in various forms.

* ^ : composition and power, using various algorithms. ppow(c::PermCyc,n) gives power of c as a PermList using an algorithm from Pari that may be more efficient than list(c^n).

randpermlist, randpermcycs, randpermmat, randpermsparse, randperm(type,n) : generate random permutations

numcycles finds the number of cycles (excluding 1-cycles). iscyclic returns true if the permutation is cyclic. We allow fixed points in a cyclic permutation.

Permutation types support element type parameters,

julia> typeof(PermList(Int32[3,2,1]))
PermList{Int32} (constructor with 1 method)

For other features, see the test and source files.

Download Details:

Author: jlapeyre
Source Code: https://github.com/jlapeyre/PermutationsA.jl 
License: View license

#julia #types #methods 

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Joseph  Murray

Joseph Murray

1624005060

Scanner Class in Java: Types of Constructors & Methods, How to Use [With Examples]

Anyone who works with the Java programming language is well aware of Scanner class in Java. And for aspiring Java Developers who don’t know what Scanner class is and how to use Scanner class in Java, this article is the perfect introduction to it.

In this post, we’ll engage in a detailed discussion of Scanner class in Java, its different methods, and how they function. So, if you are looking forward to knowing more about Scanner class in Java, keep reading till the end!

Table of Contents

#full stack development #java #scanner class #scanner class in java #types of constructors & methods #types

Mikel  Okuneva

Mikel Okuneva

1604091600

Some Helpful Extensions When Dealing With Types in .NET

If you are writing reusable code, chances are high that you will write quite some code that deals with types, generics, and interfaces. Over the years, the collection of my helper extensions for that have grown. As some of my upcoming posts use them, I share them (also) for future reference.

1. Check if a Type Is Deriving From Another Type

Deriving types is a common practice. To some extent, you can use pattern matching. Sometimes, that isn’t enough, though (especially if you have a multi-level derivation path). This is when I use one of these two extensions:

Java

1

        public static bool IsDerivingFrom(this Type type, Type searchType)

2

        {

3

            if (type == null) throw new NullReferenceException();

4

5

            return

6

                type.BaseType != null &&

7

                (type.BaseType == searchType ||

8

                type.BaseType.IsDerivingFrom(searchType));

9

        }

10

11

        public static bool IsDerivingFromGenericType(this Type type, Type searchGenericType)

12

        {

13

            if (type == null) throw new ArgumentNullException(nameof(type));

14

            if (searchGenericType == null) throw new ArgumentNullException(nameof(searchGenericType));

15

16

            return

17

                type != typeof(object) &&

18

                (type.IsGenericType &&

19

                searchGenericType.GetGenericTypeDefinition() == searchGenericType ||

20

                IsDerivingFromGenericType(type.BaseType, searchGenericType));

21

        }

Update 1: Type.IsSubclassOf will give you the same result as IsDerivingFrom. The main purpose was (is) to use my implementation when having multiple levels of derivation and being able to debug the whole detection process.

2. Get Type of T From IEnumerable

Sometimes, one needs to know the item type of an IEnumerable. These two extensions will help you in this case:

Java

1

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Extension method")]

2

        public static Type GetItemType<T>(this IEnumerable<T> enumerable) => typeof(T);

3

4

        public static Type? GetItemType(this object enumerable)

5

            => enumerable == null ? null :

6

            (enumerable.GetType().GetInterface(typeof(IEnumerable<>).Name)?.GetGenericArguments()[0]);

3. Check if a Type Implements a Certain Interface

Interfaces are supposed to make the life of a developer easier. Like with the type derivation, sometimes we need to know if a type implements a certain interface. This extension answers the question for you:

Java

1

        public static bool ImplementsInterface(this Type? type, Type? @interface)

2

        {

3

            bool result = false;

4

5

            if (type == null || @interface == null)

6

                return result;

7

8

            var interfaces = type.GetInterfaces();

9

            if (@interface.IsGenericTypeDefinition)

10

            {

11

                foreach (var item in interfaces)

12

                {

13

                    if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)

14

                        result = true;

15

                }

16

            }

17

            else

18

            {

19

                foreach (var item in interfaces)

20

                {

21

                    if (item == @interface)

22

                        result = true;

23

                }

24

            }

25

26

            return result;

27

        }

Update 2: Type.IsAssignableFrom will also tell you if a type implements an interface. As for the IsDerivingFrom method, I wanted to be able to debug the detection, which is - besides from having an explicit implementation - the main reason for this method.

#web dev #mvvm #interface #types #type #assembly #extension methods #dev stories #helper #msicc

HI Python

HI Python

1621628640

Comprehensive Guide To Python Dunder Methods

Python has a set of magic methods that can be used to enrich data classes; they are special in the way they are invoked. These methods are also called “dunder methods” because they start and end with double underscores. Dunder methods allow developers to emulate built-in methods, and it’s also how operator overloading is implemented in Python. For example, when we add two integers together, 4 + 2, and when we add two strings together, “machine” + “learning”, the behaviour is different. The strings get concatenated while the integers are actually added together.

The “Essential” Dunder Methods

If you have ever created a class of your own, you already know one of the dunder methods, __init__(). Although it’s often referred to as the constructor, it’s not the real constructor; the __new__() method is the constructor. The superclass’s  __new__() , super().__new__(cls[, ...]), method is invoked, which creates an instance of the class, which is then passed to the __init__() along with other arguments. Why go through the ordeal of creating the __new__() method? You don’t need to; the __new__() method was created mainly to facilitate the creation of subclasses of immutable types (such as int, str, list) and metaclasses.

#developers corner #uncategorized #dunder methods #magic methods #operator overriding #python dunder methods #python magic methods