Showing posts with label itertools-module. Show all posts
Showing posts with label itertools-module. Show all posts

Thursday, October 20, 2016

Permutation facts

By Vasudev Ram



Nicomachus theorem 3D image attribution

Today, I was using the permutations function in Python's itertools module to generate permutations for a few different values of integers, as part of some work I was doing. Looking at the lengths (1, 2, 6, 24, ...) of a few sets of permutations, I noticed a pattern that seemed familiar, so I wrote this program to verify my guess about what it meant:
#--------------------------------------------------------------
# perm_fact.py
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: http://jugad2.blotspot.com
# Product store: https://gumroad.com/vasudevram
#--------------------------------------------------------------

import sys
from itertools import permutations

def num_perms_upto(n):
    num_perms = []
    for i in range(1, n + 1):
        num_perms.append(len(list(permutations(range(i)))))
    return num_perms

def factorial(n):
    if n < 0:
        print "Argument n should be >= 0"
        sys.exit(0)
    if n == 0:
        return 1
    return n * factorial(n - 1)

def factorials_upto(n):
    factorials = []
    for i in range(1, n + 1):
        factorials.append(factorial(i))
    return factorials

print "Number of permutations of 1 .. n, where n in 1 .. 10:"
print num_perms_upto(10)
print "Factorial of n, where n in 1 .. 10:"
print factorials_upto(10)
which, when run, gave this output:
$ python perm_fact.py
Number of permutations of 1 .. n, where n in 1 .. 10:
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
Factorial of n, where n in 1 .. 10:
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
This confirmed (empirically, of course) that the number of permutations of n items (taken n at a time), is just n factorial.

Then I looked up factorial in Wikipedia, and found some interesting facts (pun intended). Here are some excerpts from that page:

[
The factorial operation is encountered in many areas of mathematics, notably in combinatorics, algebra, and mathematical analysis.
...
Its most basic occurrence is the fact that there are n! ways to arrange n distinct objects into a sequence (i.e., permutations of the set of objects). This fact was known at least as early as the 12th century, to Indian scholars. Fabian Stedman, in 1677, described factorials as applied to change ringing.
...
Although the factorial function has its roots in combinatorics, formulas involving factorials occur in many areas of mathematics.
...
Factorials occur in algebra for various reasons, such as via the already mentioned coefficients of the binomial formula.
...
Factorials also turn up in calculus; for example they occur in the denominators of the terms of Taylor's formula.
...
Factorials are also used extensively in probability theory.
...
As n grows, the factorial n! increases faster than all polynomials and exponential functions (but slower than double exponential functions) in n.
...
(Hence) ln n! ~ n ln n ... This result plays a key role in the analysis of the computational complexity of sorting algorithms
...
Factorials have many applications in number theory.
...
The reciprocals of factorials produce a convergent series whose sum is Euler's number e:
...
In mathematics, the gamma function (represented by the capital Greek letter G) is an extension of the factorial function, with its argument shifted down by 1, to real and complex numbers.
...
The gamma function is applicable in the fields of probability and statistics, as well as combinatorics.
...
There are several other integer sequences similar to the factorial that are used in mathematics:
...
Double factorial
...
Quadruple factorial
...
Superfactorial
...
Hyperfactorial
...
Bhargava factorial
]

I did a double take (or should that be factorial take? :) when I saw that one, because I didn't expect a factorial type to be named after a person (but why not, really); the person is Fields Medal-winning mathematician Manjul Bhargava.

All the above factorial-related terms are mentioned in the Wikipedia factorial article, and there are also links to some of them there.

And did you know that triangular numbers are the additive analogues of factorials?

The image at the top of the post is a visual representation of Nicomachus's theorem, which involves what are called squared triangular numbers. His theorem says that:

The sum of the first n cubes is the square of the nth triangular number. That is,

1 cubed + 2 cubed + 3 cubed + ... + n cubed = (1 + 2 + 3 + ... + n) squared,

where the nth triangular number is the sum of the natural numbers from 1 to n.

Speaking of mathematics, you may also like this earlier post by me:

Bhaskaracharya and the man who found zero. In fact, the Wikipedia article on permutations says that the relationship between permutations and factorials (described above) was known to mathematicians in India by around 1150 A.D.

- Enjoy.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

FlyWheel - Managed WordPress Hosting



Tuesday, May 21, 2013

A partial crossword solver in Python

A Cryptic Crossword Clue Solver ←

Saw this via Twitter.

It is a partial crossword solver, because it only helps solve a particular category of crossword clues - those in which the clue (which is usually a sentence or phrase) contains both a "definition" of the answer as well a hint of some kind that leads to the same answer. This solver tries to compute the answer using both the definition and the hint, and checks whether the results match. Ingenious.

I found it interesting because this is a somewhat difficult problem, and yet the author managed to create a solution (involving NLTK and parsing) that works in many, if not all cases.

Also, long ago, in college days, I had written another kind of partial crossword solver (in BASIC); it was much simpler, using a brute force method - what it did was help solve the kind of crossword clues in which the answer is a permutation of a substring of the characters comprising the clue sentence or phrase. The program would generate and display on the screen, all possible permutations of all possible substrings of the sentence, that were of the same length as the answer. Then you had to view those permutations and guess whether any of them was the right answer, based on the clue.

I wrote the permutation-generation code by hand, but saw recently that the Python itertools module has methods to generate permutations (as well as combinations) from sequences:

http://docs.python.org/2/library/itertools.html

http://en.m.wikipedia.org/wiki/Permutation

http://en.wikipedia.org/wiki/Crossword

- Vasudev Ram
dancingbison.com