'How to write a program with unspecified number of if-else

I have a little problem which looks like a “combinatorics” problem.

We know that 1+2+3+…+k = (k^2 + k)/2; so, let’s take the set of numbers S = {1,2,3,4,…,(k^2 + k)/2} and divide this collection into k parts:

The 1st part has 1 element 1; the 2nd has 2 elements 2,3; the 3rd has 3 elements 4,5,6; …and so on…; the kth having k elements (k^2 – k + 2)/2,…,(k^2 + k)/2.

Then I have to draw a random integer in S, say i = random.randint(1, (k^2 + k)/2) and I have to do some operations according to the element that was drawn:

if i == 1:
  `something`
   else if 2 <= i <= 3:
     `something else`
     else if 4 <= i <= 6:
       `something else`
         …
         else: # last line when `i` is in the last `kth` part
           `something else`

The number k I have to use is variable, so I can't actually write the above program, because I don't know a priori where it should stop... It seems to me that the best would be to define a function:

def cases(k):
    i = random.randint(1, (k^2 + k)/2)
    if i == 1:
        `something`
        else if 2 <= i <= 3:
            … and so on…

But the problem remains: how could I write such a function without a specific k? There may be a trick in Python to do this, but I don't see how. All ideas will be welcome.



Solution 1:[1]

Sorry for the indenting; I acknowledge it's wrong. Following the comment of Zach Munro, I allow myself an answer to better clarify the idea that I had in mind and which was not very clear. Below is the kind of program I was thinking of; the something and something else are actually similar, for they use the same function, but with a different domain each time:

def cases(start, end, k):
    delta = (end - start) / k
    i = random.randint(1, (k**2 + k)/2)
    if i == 1:
        # random in the 1st part
        x = random.uniform(start, start + 1*delta)
    elif 2 <= i <= 3:
        # random in the 2nd part
        x = random.uniform(start + 1*delta, start + 2*delta)
    elif 4 <= i <= 6:
        # random in the 3rd part
        x = random.uniform(start + 2*delta, start + 3*delta)
    ...
    elif (k**2 – k + 2)/2 <= i <= (k**2 + k)/2:
        # random in the kth part
        x = random.uniform(start + (k-1)*delta, start + k*delta)

The question is always how to stop using ... in the program, but to make something that runs when the parameters are provided (start is the beginning of an interval, end is the end of the interval and k is in fact the number of parts into which we separate this interval).

Basically, we sample more and more as we move away from the origin of the interval.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew