I've been wanting to learn some Haskell for a while now, and I know it and similar languages have really good support for various kinds of infinite lists. So, how could I represent the sequence of tetrahedral numbers in Haskell, preferably with an explanation of what's going on?
0 0 0
1 1 1
2 3 4
3 6 10
4 10 20
5 15 35
6 21 56
7 28 84
8 36 120
In case it's not clear what's going on there, the second column is a running total of the first column, and the third column is a running total of the second column. I'd prefer that the Haskell code retain something of the "running total" approach, since that's the concept I was wondering how to express.
You're correct, Haskell is really nice for doing things like this:
first_col = [0..]
second_col = scanl1 (+) first_col
third_col = scanl1 (+) second_col
first_col is an infinite list of integers, starting at 0
scanl (+) calculates a lazy running sum: Prelude docs
We can verify that the above code is doing the right thing:
Prelude> take 10 first_col
[0,1,2,3,4,5,6,7,8,9]
Prelude> take 10 second_col
[0,1,3,6,10,15,21,28,36,45]
Prelude> take 10 third_col
[0,1,4,10,20,35,56,84,120,165]
Adding to perimosocordiae's great answer, languages like Haskell are so slick they allow you to make an infinite list of infinite lists.
First lets define the operator that produces each successive row:
op :: [Integer] -> [Integer]
op = scanl1 (+)
As explained by perimosocordiae, this is just a lazy running sum.
We also need a base case:
tnBase :: [Integer]
tnBase = [0..]
So how do we get an infinite list of infinite lists of tetrahedral numbers? We iterate this operation on the base case, then the output produced by the base case, then that output...
tn = iterate op tnBase
iterate is in the Prelude, such functions can be found using hoogle and searching by name (if you have a good guess) or type signature (you generally know the signature of what you need). Source code is usually linked from the haddock documentation.
Presentation
(in case you're not comfortable with map, take, drop, and head)
This is all well and good, but rather useless if you don't know how to get passed the first infinite list to see the second, third, etc. There are plenty of options, for just getting a particular list you can drop the first few:
getNthTN n = head (drop n tn)
Getting the first few results of each list is probably more what you're looking for though:
printFirstFew n m = print $ take m (map (take n) tn)
Here map (take n) tn will take the first n values from each list of tetrahedral numbers while take m will limit our results to the first m lists.
And lastly, I like the awesome groom package for quick interactive playing with data:
> groom $ take 10 (map (take 10) tn)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45],
[0, 1, 4, 10, 20, 35, 56, 84, 120, 165],
[0, 1, 5, 15, 35, 70, 126, 210, 330, 495],
[0, 1, 6, 21, 56, 126, 252, 462, 792, 1287],
[0, 1, 7, 28, 84, 210, 462, 924, 1716, 3003],
[0, 1, 8, 36, 120, 330, 792, 1716, 3432, 6435],
[0, 1, 9, 45, 165, 495, 1287, 3003, 6435, 12870],
[0, 1, 10, 55, 220, 715, 2002, 5005, 11440, 24310],
[0, 1, 11, 66, 286, 1001, 3003, 8008, 19448, 43758]]
Related
I am working on an optimization problem. I have X number of ambulance locations, where X ranges from 1-39.
There are 43 numbers [Ambulance Locations] to choose from (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39) , we choose 3 of them since I have 3 ambulances.
I can only put my ambulance in three locations among 1-39 locations (Restriction). Assume that I want to put my Ambulance on the 5th, 19th, and 31 positions. -- Chromosome 1= [000010000000000000100000000000100000000]. In the above presentation, I am turning on 5-bit, 19-bit, and 31-bit.
Is it possible to flip a bit close to the original solution? For example, keeping 2 bits on in the original position and randomly changing the 3rd bit close to 2bits. It is important for me to keep 3bits on among 39bits. I want to make a control mutation with the aim to produce a small change.
My goal is to make small changes since each bit represents a location. The purpose of mutation is to make small changes and see evaluate results. Therefore, a code should do something like this. As for CS1: (111000000000000000000000000000000000000), I want something like (011010000000000000000000000000000000000), or (011001000000000000000000000000000000000), or (010110000000000000000000000000000000000) or (101010000000000000000000000000000000000), or (00101100000000000000000000000000000000), etc
To achieve mutation, what can be a good way to randomly change present positions to other positions keeping the range only between 1-39 locations (Restriction)?
you could use numpy and do something like
import numpy
s = "1110000000000000000000000000"
def mutate(s):
arr = numpy.array(list(s))
mask = arr == "1"
indices_of_ones = numpy.argwhere(mask).flatten()
pick_one_1_index = numpy.random.choice(indices_of_ones)
potential_swaps = numpy.argwhere(~mask).flatten()
distances = numpy.abs(pick_one_1_index - potential_swaps)
probabilities = (1/distances) # higher probabilities the less distance from its original position
# probabilities = (1/(distances*2)) # even higher probabilities the less distance from its original position
pick_one_0_index = numpy.random.choice(potential_swaps,p=probabilities/probabilities.sum())
arr[pick_one_1_index] = '0'
arr[pick_one_0_index] = '1'
return "".join(arr)
there is likely a more optimal solution
alternatively you can add a scalar or power to the distances to penalize more for distance...
if you wanted to test different multipliers or powers for the probabilities
you could use something like
def score_solution(s1,s2):
ix1 = set([i for i,v in enumerate(s1) if v == "1"])
ix2 = set([i for i,v in enumerate(s2) if v == "1"])
a,b = ix1 ^ ix2
return numpy.abs(a-b)
def get_solution_score_quantiles(sample_size=100,quantiles = [0.25,0.5,0.75]):
scores = []
for i in range(10):
s1 = mutate(s)
scores.append(score_solution(s,s1))
return numpy.quantile(scores,quantiles)
print(get_solution_score_quantiles(50))
Suppose I have a list of 17 objects, out of these 17 objects some have a certain property say P1. I separate them and say they are n in number where n < 17. Out of these n objects some have another property say P2. I separate them and say they are m in number where m < n. Out of these m objects some have another property say P3. I separate them and say they are k in number where k < m. I want to print these k objects only.
I was thinking of a long way that is I separate n, m and k objects all from 17 objects according to their respective property and then look for common index, the index that appear in all of three calculations.
Either I need to derive this common index or I do what I have written in the first paragraph that is to filter through and through according to the three properties.
Example:
list_1 = [17, 23, 15, 37, 43, 52, 57, 93, 55, 85, 11, 13, 7, 22, 24]
list_odd = [17, 23, 15, 37, 43, 57, 93, 55, 85, 11, 13, 7] #P1 is a number is odd
list_odd_div3 = [15, 57, 93] #P2 is a number divisible by 3
list_odd_div5 = [15, 55, 85] #P3 is a number divisible by 5
required_list = [15] #A number having P1, P2 and P3
I have just started my journey with Wolfram Mathematica and I want to implement a simple genetic algorithm. The construction of the data is given and I have to start with such rows/columns.
Here is what I have:
chromosome := RandomSample[CharacterRange["A", "G"], 7]
chromosomeList = Table[chromosome, 7] // MatrixForm
This gives me a matrix, where every row represents a chromosome:
yPos = Flatten[Position[chromosomeList, #], 1] & /# {"A", "B", "C",
"D", "E", "F", "G"};
yPos = yPos[[All, 3 ;; 21 ;; 3]] // Transpose
Now every column represents a letter (From A to G) and every row it's index in every chromosome:
Here is a given efficiency matrix, where very row represents different letter (From A to G) and every column gives the value that should be applied on the particular position:
efficiencyMatrix = {
{34, 31, 20, 27, 24, 24, 18},
{14, 14, 22, 34, 26, 19, 22},
{22, 16, 21, 27, 35, 25, 30},
{17, 21, 24, 16, 31, 22, 20},
{17, 29, 22, 31, 18, 19, 26},
{26, 29, 37, 34, 37, 20, 21},
{30, 28, 37, 28, 29, 23, 19}}
What I want to do is to create a matrix with values that correspond to the letter and it's position. I have done it like that:
values = Transpose[{ efficiencyMatrix[[1, yPos[[1]]]],
efficiencyMatrix[[2, yPos[[2]]]],
efficiencyMatrix[[3, yPos[[3]]]],
efficiencyMatrix[[4, yPos[[4]]]],
efficiencyMatrix[[5, yPos[[5]]]],
efficiencyMatrix[[6, yPos[[6]]]],
efficiencyMatrix[[7, yPos[[7]]]]}]
How can I write it in more elegant way?
You can apply a list of functions to some variable using the function Through, which is helpful when applying Position multiple times. Because Position[patt][expr] == Position[expr, patt], we can do
Through[ (Position /# CharacterRange["A","C"])[{"B", "C", "A"}] ]
to get {3, 1, 2}.
Position can also operate on lists, so we can simplify finding ypos by doing
Transpose#Map[Last, Through[(Position /# characters)[chromosomeList]], {2}]
where characters is the relevant output of CharacterRange.
We can also simplify dealing with ranges of integers by mapping over the Range function, so in total we end up with
characters = CharacterRange["A","G"]
efficiencies = ...
chromosomes = ...
ypos = Transpose#Map[Last, Through[(Position /# characters)[chromosomes]], {2}];
efficiencies[[#, ypos[[#]]]]& /# Range[Length[characters]] //Transpose ]
I was wondering how i would go about counting combinations in a list. To be more precise i have a list that is comprised of smaller lists that are made up of 6 randomly chosen numbers and i want to count how many times each combinations occurs within the bigger list and then finally display the least occurring combination. So far i tried using Counter() but it seems it can't count lists.
here's an example of what i want to do:
list = [[1,2,3,4,5,6],[1,5,16,35,55,22],[1,2,3,4,5,6],[5,25,35,45,55,10],[1,5,16,35,55,22],[1,2,3,4,5,6],[9,16,21,22,23,6],[9,16,21,22,23,6]]
so after counting the combinations it should print the combination [5,25,35,45,55,10]
since it only occurred once in the list
FYI the list is going to randomly generated with around 1 billion combinations stored but given the range of numbers, there's only 175 million possible combinations
FYI 2 i'm extremely new to python
When you construct the Counter instance you can convert your lists to tuples; the latter are hashable, which is the property an object needs to be able to serve as a key of a dict.
>>> from collections import Counter
>>> l = [[1,2,3,4,5,6],[1,5,16,35,55,22],[1,2,3,4,5,6],[5,25,35,45,55,10],[1,5,16,35,55,22],[1,2,3,4,5,6],[9,16,21,22,23,6],[9,16,21,22,23,6]]
>>> c = Counter(tuple(e) for e in l)
>>> c
Counter({(1, 2, 3, 4, 5, 6): 3, (1, 5, 16, 35, 55, 22): 2, (9, 16, 21, 22, 23, 6): 2, (5, 25, 35, 45, 55, 10): 1})
>>> list(c.most_common()[-1][0])
[5, 25, 35, 45, 55, 10]
I've written a similar question which was closed I would like to ask not the code but an efficiency tip. I haven't coded but if I can't find any good hint in here I'll go and code straightforward. My question:
Suppose you have a function listNums that take a as lower bound and b as upper bound.
For example a=120 and b=400
I want to print numbers between these numbers with one rule. 120's permutations are 102,210,201 etc. Since I've got 120 I would like to skip printing 201 or 210.
Reason: The upper limit can go up to 1020 and reducing the permutations would help the running time.
Again just asking for efficiency tips.
I am not sure how you are handling 0s (eg: after outputting 1 do you skip 10, 100 etc since technically 1=01=001..).
The trick is to select a number such that all its digits are in increasing order (from left to right).
You can do it recursively. AT every recursion add a digit and make sure it is equal to or higher than the one you recently added.
EDIT: If the generated number is less than the lower limit then permute it in such a way that it is greater than or equal to the lower limit. If A1A2A3..Ak is your number and it is lower than limit), then incrementally check if any of A2A1A3...Ak, A3A1A2...Ak, ... , AkA1A2...Ak-1 are within limit. If need arises, repeat this step to with keeping Ak as first digit and finding a combination of A1A2..Ak-1.
Eg: Assume we are selecting 3 digits and lower limit is 99. If the combination is 012, then the lowest permutation that is higher than 99 is 102.
When the lower bound is 0, an answer is given by the set of numbers with non-decreasing digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 24, 25, 26, 27, 28, 29, 33, 34, 35, 36, 37, 38, 39, 44, 45, 46, 47, 48, 49, 55, 56, 57, 58, 59, 66, 67, 68, 69, 77, 78, 79, 88, 89, 99, 111, 112...) that fall in the requested range.
This sequence is easily formed by incrementing an integer, and when there is a carry, replicate the digit instead of carrying. Exemple: 73 is followed by 73+1 = 74 (no carry); 79 is followed by 79+1 = 80 (carry), so 88 instead; 22356999 is followed by 22356999+1 = 22357000, hence 22357777.
# Python code
A= 0 # CAUTION: this version only works for A == 0 !
B= 1000
N= A
while N < B:
# Detect zeroes at the end
S= str(N)
P= S.find('0')
if P > 0:
# Replicate the last nonzero digit
S= S[:P] + ((len(S) - P) * S[P-1])
N= eval(S)
# Next candidate
print N
N+= 1
Dealing with a nonzero lower bound is a lot more tricky.