Bruteforce program in python 3.6 - python-3.6

I need to write a bruteforce program in python to iterate from "aaaaaaa" till "xxxxxxx" and determine how many guesses it takes to reach it.
How can I iterate from "aaaaaaa" to "xxxxxxx" with each iteration changing one alphabet from the right i.e. after the first iteration "aaaaaaa" should be "aaaaaab"?
Also, after an alphabets reaches "z" , it changes the adjacent left alphabet by one and goes back to "a".

This is pseudo code for you to giving you an idea how to implement it though this platform is not thought to take your job and program the things for you. Hope that helps.
a={'a',....,'z'}
i1=0, i2=0, i3=0, i4=0, i5=0
while a[i1] <= 'z':
while a[i2] <= 'z':
while a[i3] <= 'z':
while a[i4] <= 'z':
while a[i5] <= 'z':
outString = a[i1] + a[i2] + a[i3] + a[i4] + a[i5]
i5 = i5+1
i4 = i4+1
i5 = 0
i3 = i3+1
i4 = 0
i2 = i2+1
i3 = 0
i1 = i1+1
i2 = 0

Related

Error in for loop - attempt to select less than one element in integerOneIndex

I'm trying to translate a C routine from an old sound synthesis program into R, but have indexing issues which I'm struggling to understand (I'm a beginner when it comes to using loops).
The routine creates an exponential lookup table - the vector exptab:
# Define parameters
sinetabsize <- 8192
prop <- 0.8
BP <- 10
BD <- -5
BA <- -1
# Create output vector
exptab <- vector("double", sinetabsize)
# Loop
while(abs(BD) > 0.00001){
BY = (exp(BP) -1) / (exp(BP*prop)-1)
if (BY > 2){
BS = -1
}
else{
BS = 1
}
if (BA != BS){
BD = BD * -0.5
BA = BS
BP = BP + BD
}
if (BP <= 0){
BP = 0.001
}
BQ = 1 / (exp(BP) - 1)
incr = 1 / sinetabsize
x = 0
stabsize = sinetabsize + 1
for (i in (1:(stabsize-1))){
x = x + incr
exptab [[sinetabsize-i]] = 1 - (BQ * (exp(BP * x) - 1))
}
}
Running the code gives the error:
Error in exptab[[sinetabsize - i]] <- 1 - (BQ * (exp(BP * x) - 1)) :
attempt to select less than one element in integerOneIndex
Which, I understand from looking at other posts, indicates an indexing problem. But, I'm finding it difficult to work out the exact issue.
I suspect the error may lie in my translation. The original C code for the last few lines is:
for (i=1; i < stabsize;i++){
x += incr;
exptab[sinetabsize-i] = 1.0 - (float) (BQ*(exp(BP*x) - 1.0));
}
I had thought the R code for (i in (1:(stabsize-1))) was equivalent to the C code for (i=1; i< stabsize;i++) (i.e. the initial value of i is i = 1, the test is whether i < stabsize, and the increment is +1). But now I'm not so sure.
Any suggestions as to where I'm going wrong would be greatly appreciated!
As you say, array indexing in R starts at 1. In C it starts at zero. I reckon that's your problem. Can sinetabsize-i ever get to zero?

Fortran reshape - N-dimensional transpose

I'm trying to write some code in Fortran which requires the re-ordering of an n-dimensional array. I thought the reshape intrinsic combined with the order argument should allow this, however I'm running into difficulties.
Consider the following minimal example
program test
implicit none
real, dimension(:,:,:,:,:), allocatable :: matA, matB
integer, parameter :: n1=3, n2=5, n3=7, n4=11, n5=13
integer :: i1, i2, i3, i4, i5
allocate(matA(n1,n2,n3,n4,n5)) !Source array
allocate(matB(n3,n2,n4,n1,n5)) !Reshaped array
!Populate matA
do i5=1, n5
do i4=1, n4
do i3=1, n3
do i2=1, n2
do i1=1, n1
matA(i1,i2,i3,i4,i5) = i1+i2*10+i3*100+i4*10000+i5*1000000
enddo
enddo
enddo
enddo
enddo
print*,"Ad1 : ",matA(:,1,1,1,1),shape(matA)
matB = reshape(matA, shape(matB), order = [3,2,4,1,5])
print*,"Bd4 : ",matB(1,1,1,:,1),shape(matB) !Leading dimension of A is the fourth dimension of B
end program test
I would expect this to result in
Ad1 : 1010111.00 1010112.00 1010113.00 3 5 7 11 13
Bd4 : 1010111.00 1010112.00 1010113.00 7 5 11 3 13
But instead I find:
Ad1 : 1010111.00 1010112.00 1010113.00 3 5 7 11 13
Bd4 : 1010111.00 1010442.00 1020123.00 7 5 11 3 13
I've tried this with gfortran (4.8.3 and 4.9) and ifort (11.0) and find the same results, so it's likely that I am simply misunderstanding something about how reshape works.
Can anybody shed any light on where I'm going wrong and how I can achieve my goal?
Because I also feel the behavior of order for multi-dimensional arrays is quite non-intuitive, I made some code comparison below to make the situation even clear (in addition to the already complete #francescalus' answer). First, in a simple case, reshape() with and without order gives the following:
mat = reshape( [1,2,3,4,5,6,7,8], [2,4] )
=> [ 1 3 5 7 ;
2 4 6 8 ]
mat = reshape( [1,2,3,4,5,6,7,8], [2,4], order=[2,1] )
=> [ 1 2 3 4 ;
5 6 7 8 ]
This example shows that without order the elements are filled in the usual column-major way, while with order=[2,1] the 2nd dimension runs faster and so the elements are filled row-wise. The key point here is that the order specifies which dimension of the LHS (rather than the source array) runs faster (as emphasized in the above answer).
Now we apply the same mechanism to higher-dimensional cases. First, reshape() of the 5-dimensional array without order
matB = reshape( matA, [n3,n2,n4,n1,n5] )
corresponds to the explicit loops
k = 0
do i5 = 1, n5 !! (5)-th dimension of LHS
do i1 = 1, n1 !! (4)
do i4 = 1, n4 !! (3)
do i2 = 1, n2 !! (2)
do i3 = 1, n3 !! (1)-st dimension of LHS
k = k + 1
matB( i3, i2, i4, i1, i5 ) = matA_seq( k )
enddo;enddo;enddo;enddo;enddo
where matA_seq is a sequential view of matA
real, pointer :: matA_seq(:)
matA_seq( 1 : n1*n2*n3*n4*n5 ) => matA(:,:,:,:,:)
Now attaching order=[3,2,4,1,5] to reshape(),
matB = reshape( matA, [n3,n2,n4,n1,n5], order = [3,2,4,1,5] )
then the order of DO-loops is changed such that
k = 0
do i5 = 1, n5 !! (5)-th dim of LHS
do i3 = 1, n3 !! (1)
do i1 = 1, n1 !! (4)
do i2 = 1, n2 !! (2)
do i4 = 1, n4 !! (3)-rd dim of LHS
k = k + 1
matB( i3, i2, i4, i1, i5 ) = matA_seq( k )
enddo;enddo;enddo;enddo;enddo
This means that the 3rd dimension of matB (and thus i4) runs fastest (which corresponds to the second line in the above Answer). But what is desired by OP is
k = 0
do i5 = 1, n5 !! (5)-th dim of LHS
do i4 = 1, n4 !! (3)
do i3 = 1, n3 !! (1)
do i2 = 1, n2 !! (2)
do i1 = 1, n1 !! (4)-th dim of LHS
k = k + 1
matB( i3, i2, i4, i1, i5 ) = matA_seq( k )
enddo;enddo;enddo;enddo;enddo
which corresponds to
matB = reshape( matA, [n3,n2,n4,n1,n5], order = [4,2,1,3,5] )
i.e., the final line of the francescalus' answer.
Hope this comparison further clarifies the situation...
When order= is specified in reshape the elements of the result taken with permuted subscript order correspond to the elements of the source array. That probably isn't entirely clear. The Fortran 2008 standard states this as (ignoring the part about pad=)
The elements of the result, taken in permuted subscript order ORDER (1), ..., ORDER (n), are those of SOURCE in normal array element order ..
What this means is that from your example with order=[3,2,4,1,5] there is the mapping to
matA(1,1,1,1,1), matA(2,1,1,1,1), matA(3,1,1,1,1), matA(1,2,1,1,1), ...
of
matB(1,1,1,1,1), matB(1,1,2,1,1), matB(1,1,3,1,1), matB(1,1,4,1,1), ...
with offset changing most rapidly in the third index of matB corresponding to most rapidly varying in the first of matA. The next fastest varying in matB being dimension 2, then 4, and so on.
So, it's the elements matB(1,1,1:3,1,1) that correspond the matA(:,1,1,1,1).
I've been explicit in the extent of that matB slice because you've a problem with the shape of matB: you want the shape of matB to be the inverse of the permutation given by the order= specifier.
You could write your example as
implicit none
integer, parameter :: n1=3, n2=5, n3=7, n4=11, n5=13
integer matA(n1,n2,n3,n4,n5)
integer matB(n4,n2,n1,n3,n5) ! Inverse of permutation (3 2 4 1 5)
integer i1, i2, i3, i4, i5
forall (i1=1:n1, i2=1:n2, i3=1:n3, i4=1:n4, i5=1:n5) &
matA(i1,i2,i3,i4,i5)=i1+i2*10+i3*100+i4*10000+i5*1000000
print*,"Ad1 : ",matA(:,1,1,1,1),shape(matA)
matB = reshape(matA, shape(matB), order = [3,2,4,1,5])
print*,"Bd3 : ",matB(1,1,:,1,1),shape(matB)
end
Alternatively, if it's the shape of matB that you want, then it's the order permutation that wants inverting:
matB = reshape(matA, shape(matB), order = [4,2,1,3,5])
At first glance, it may be natural to view the order relating to the dimensions of the source. However, the following may clarify: the result of the reshaping is the same regardless of the shape of source (what is used are the elements of the array in natural order); the order= value has size equal to that of the shape= value. For the first of these, if the source were, say [1,2,3,4,5,6] (recall how we construct rank-2 arrays), then order= could never have any effect (it would have to be [1]) if it were used on the source.

Easy dynamic programming recursive formula (uva 147 coin change)

the problem is about coin change - "how many ways you can change 3,5,10 dollars
if you have 5c,10c ......
"http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=83
the problem is solved many times on various blogs( solution here )
In dp, the hardest thing is to understand the relation between subproblems and get the formula(optimal substructure)
I only give the actual for loop that stores the ways into 2d table like the solution:
for (int i = 2; i <= NCHANGES; ++i){
for (int m = 1; m <= MAX_AMOUNT; ++m){
if (m >= coins[i])
n[i][m] = n[i-1][m] + n[i][m - coins[i]];
else
n[i][m] = n[i-1][m];
}
}
=================================
The actual important code:
if (m >= coins[i])
n[i][m] = n[i-1][m] + n[i][m - coins[i]];
else
n[i][m] = n[i-1][m];
My thinking.
for example:
(else case)
I have the amount 5 cents and 1 coin to use : 5c. there is only 1 way : 5c = 1 * 5c
(store n[5][coin(5)])
I have the amount 5c and 2 coins to use : 5c and 10c i can't use BOTH 5C and 10c => i go back to 1 WAY of doing it ( store 1 in the table for n[5][coin(5,10)])
for this case
that's why n[i][m] = n[i-1][m]
can you explain the first if case? n[i][m] = n[i-1][m] + n[i][m - coins[i]]?
Ok, i found it on a website - same problem.
The coin change recurrence:
a[i][j] = a[i-1][j] (d[i] > j)
(If the coin can't be used, then don't use it)
a[i][j] = a[i-1][j] + a[i][j-d[i]] (d[i] <= j)
(If the coin can be used: don't use OR use it)

R convert vector of numbers to skipping indexes

I have a vector of widths,
ws = c(1,1,2,1,3,1)
From this vector I'd like to have another vector of this form:
indexes = c(1,2,3,5,6,7,9,11,12)
In order to create such vector I did the following for loop in R:
ws = c(1,1,2,1,3,1)
indexes = rep(0, sum(ws))
counter = 1
counter2 = 1
last = 0
for(i in 1:length(ws))
{
if (ws[i] == 1)
{
indexes[counter] = counter2
counter = counter + 1
} else {
for(j in 1:ws[i])
{
indexes[counter] = counter2
counter = counter + 1
counter2 = counter2+2
}
counter2 = counter2 - 2
}
counter2 = counter2+1
}
The logic is as follows, each element in ws specifies the respective number of elements in index. For example if ws is 1, the respective number of elements in indexes is 1, but if ws is > 1, let us say 3, the respective number of elements in index is 3, and the elements are skipped 1-by-1, corresponding to 3,5,7.
However, I'd like to avoid for loops since they tend to be very slow in R. Do you have any suggestions on how to achieve such results only with vector operations? or some more crantastic solution?
Thanks!
Here's a vectorized one-liner for you:
ws <- c(1,1,2,1,3,1)
cumsum((unlist(sapply(ws, seq_len)) > 1) + 1)
# [1] 1 2 3 5 6 7 9 11 12
You can pick it apart piece by piece, working from the inside out, to see how it works.

Vectorize simple loop-based trading system in R?

After studying the vectorization methods used in the two links below, I've attempted to create a simple trading strategy template (code shown below) that can be vectorized in R for better speed vs a loop-based structure. I'm having difficulty vectorizing because variable state must be maintained and built upon such as:
1) The signals I'm using are not mutually exclusive for long and short (as in a simplistic MA crossover system).
2) Once triggered, the signal can wander until it gets an opposing indication (such as an RSI go short above 80, go long below 20 type system).
3) Positions are held for multiple periods so it isn't a case of enter on every signal or exit after a signal is false (I wish to be able to only enter once as in a Stop and Reverse or SAR system).
I consider this to be a simple example system but it is a bit more complex than the examples listed here:
http://blog.fosstrading.com/2011/03/how-to-backtest-strategy-in-r.html
Cumulative Return in Trading Strategy Test
System logic summary: The system starts flat then goes long (short) at the ask (bid) price when zscore is below (above) -2 (2). The system keeps track of performance statistics such as 'trades', 'wins', closed P&L (others omitted for simplicity). The system also keeps a running 'equity' for plotting after a system run.
# assume vectors bid, ask, and zscore containing those price series respectively
# pos = current position where 1 == long, -1 == short, 0 == flat
# entryP = entry price, pnl = open pnl, cpnl = closed pnl
pos = 0; entryP = 0.0; pnl = 0; cpnl = 0; trades = 0; wins = 0
ub = length(bid)
equity = rep(0, ub)
for (i in 10000:ub) {
pnl = 0
if (pos > 0) pnl = bid[i] - entryP
if (pos < 0) pnl = entryP - ask[i]
if (zscore[i] > 2.0 && pos != -1) { # go short
if (pos > 0) { # exit long and record pnl
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
trades = trades + 1
pnl = 0
}
pos = -1
entryP = bid[i]
} else if (zscore[i] < -2.0 && pos != 1) { # go long
if (pos < 0) { # exit short and record pnl
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
trades = trades + 1
pnl = 0
}
pos = 1
entryP = ask[i]
}
equity[i] = cpnl + pnl
}
# assume close-out of final position
cpnl = cpnl + pnl
if (pnl > 0) wins = wins + 1
if (pos != 0) trades = trades + 1
# plot equity chart and report performance stats
plot(equity, t='l', lwd=3)
cpnl;trades; cpnl / trades; wins/trades
Is it possible to vectorize this simple loop-based mean reversion trading system in R?
" I'm having difficulty vectorizing because variable state must be maintained "
That sums it all. You can't avoid loops if your result in any iteration depends on previous iterations.

Resources