I need to find the 9th positive integer that is a multiple of 4, 13, 14, 26, and 50 using python: - python-3.6

Why doesn't this code work? I am getting a continuous loop...
solution = 0
multiple = 0
max_bound = 100000
i = 1
while i < max_bound:
if (i % 4 == 0) and (i % 13 == 0) and (i % 14) and (i % 26 == 0) and (i % 50 == 0):
multiple += 1
if multiple == 9:
solution = i
break
i += 1
if multiple == 9:
print("#1 : 9th Multiple ::", "Correct." if solution == 81900 else ("Wrong: " + str(solution)))

You just missed the 14 verification you used (1 % 14) instead of (i % 14 == 0) which returns 0(False) when the number is divisible by 14 instead of True and with the and operator it doesn't enter the if statement.
solution = 0
multiple = 0
max_bound = 100000
i = 1
while i < max_bound:
if (i % 4 == 0) and (i % 13 == 0) and (i % 14 == 0) and (i % 26 == 0) and (i % 50 == 0):
multiple += 1
if multiple == 9:
solution = i
break
i += 1
if multiple == 9:
print("#1 : 9th Multiple ::", "Correct." if solution == 81900 else ("Wrong: " + str(solution)))

Related

Why do I need 'd=0'in my r script for searching prime number?

I am a beginner in r language.
I was trying to find prime number with r language, and I found a solution in this site.
But I still can't understand some of the process.
Can any expert in r help me with this??
This is the script I saw.
d=0
primeno<- c(2:100)
for (i in 2:length(primeno)) {
for (j in 1:i) {
if (i %% j == 0) {
d=d+1
}
}
if (d==2) {
print(i)
print ("Prime")
}
d <- 0
}
I just can't understand why I need 'd=0','d=d+1' and the last 'd=0'in this script.
Any help would be appreciated. Thank you in advance.
Round 1 (outer loop)
d=0
i=2
(round 1 - inner loop)
j=1
(2 %% 1 == 0) == True
d=1
(round 2 - inner loop)
j=2
(2 %% 2 == 0) == True
d=2
(d == 2) == True
print('Is Prime')
reset d=0
Round 2 (outer loop)
d=0 (reset after Round 1)
i=3
(round 1 - inner loop)
j=1
(3 %% 1 == 0) == True
d=1
(round 2 - inner loop)
j=2
(3 %% 2 == 0) == False
d=1
(round 3 - inner loop)
j=3
(3 %% 3 == 0) == True
d=2
(d == 2) == True
print('Is Prime')
reset d=0
Round 3 (outer loop)
d=0 (reset after Round 2)
i=4
(round 1 - inner loop)
j=1
(4 %% 1 == 0) == True
d=1
(round 2 - inner loop)
j=2
(4 %% 2 == 0) == True
d=2
(round 3 - inner loop)
j=3
(4 %% 3 == 0) == False
d=2
(round 4 - inner loop)
j=4
(4 %% 4 == 0) == True
d=3
(d == 2) == False
no print
reset d=0

I am trying to use an if else loop to check multiple columns for data ranges, how do I make it so that it ignores NAs in my data

I am trying to check numbers in three columns in a data frame and if they're within a certain range, I want a certain output. I have this part of the code, but one of my tests wants to know if all three are negative, then I get a certain output. My issue is that some of the data in some of the columns are NA. I want to ignore the NAs in my logic. Is there a way to do this? A sample of my code is below.
if((DataWSGR$RouteType == 7 | DataWSGR$RouteType == 9) & (DataWSGR$SGR > 5 ) & (0 < DataWSGR$`30_Year_SGR` < 5) & (0 < DataWSGR$`20_Year_SGR` < 5) & (0 < DataWSGR$`10_Year_SGR` < 5)) {}
The 10, 20, and 30 year SGRs are the columns that will have NAs in them.
After fixing the range condition, I think you can just add | is.na(var) to the last three conditions:
if ((DataWSGR$RouteType == 7 |
DataWSGR$RouteType == 9)) &
(DataWSGR$SGR > 5) &
(DataWSGR$`30_Year_SGR` > 0 & DataWSGR$`30_Year_SGR` < 5 | is.na(DataWSGR$`30_Year_SGR`)) &
(DataWSGR$`20_Year_SGR` > 0 & DataWSGR$`20_Year_SGR` < 5 | is.na(DataWSGR$`20_Year_SGR`)) &
(DataWSGR$`10_Year_SGR` > 0 & DataWSGR$`10_Year_SGR` < 5 | is.na(DataWSGR$`10_Year_SGR`))) {
}
If DataWSGR has more than one row, the above will throw an error.
Here is a reproducible example for doing this in a for loop:
df <- data.frame(
route_type = c(7, 6, 9),
sgr = c(6, 3, 6),
sgr_30 = c(3, 1, NA),
sgr_20 = c(1, 1, NA),
sgr_10 = c(2, 1, NA)
)
for (i in 1:nrow(df)) {
if (
(df$route_type[i] == 7 | df$route_type[i] == 9) &
(df$sgr[i] > 5) &
(df$sgr_30[1] > 0 & df$sgr_30[i] < 5 | is.na(df$sgr_30[i])) &
(df$sgr_20[1] > 0 & df$sgr_20[i] < 5 | is.na(df$sgr_20[i])) &
(df$sgr_10[1] > 0 & df$sgr_10[i] < 5 | is.na(df$sgr_10[i]))
) {
print(paste("In range in row", i))
}
}

How to list the index of all consecutive and single values in a row in R matrix

I have an xlsx file containing some cells with value -3. Some are single cells and some are consecutive cells with -3 value. I am trying to write a R script, which finds the index of these cells containing -3, such that for single cell -3 values I get the single index and for consecutive cell -3 values I get the starting and the ending index.
Here is matrix from the xlsx file with 20 columns and 2 rows
3.203 3.204 3.205 -3 3.207 3.207 -3 -3 -3 3.206 3.208 3.207 -3 3.264 3.207 3.208 -3 -3 3.209 -3
3.205 3.205 3.205 3.21 3.208 3.208 3.209 -3 -3 3.209 3.211 3.21 3.211 3.211 3.21 -3 3.213 3.211 3.212 3.212
I want the result to look something like this (I have treated -3 as a missing value). So,
1 missing value at: ( 1 , 4 )
3 missing values starting from: ( 1 , 7 ) to ( 1 , 9 )
1 missing value at ( 1 , 13 )
2 missing values starting from: ( 1 , 17) to ( 1 , 18 )
1 missing value at: ( 1, 20 )
2 missing values starting from: ( 2 , 8 ) to ( 2 , 9 )
1 missing value at: ( 2, 16 )
Here is the R script, but it is giving me wrong results. I am very confused with the right use of indexes.
fileData <- read.xlsx(filePath, 1, header = FALSE, sep = ",")
dataMatrix <- data.matrix(fileData)
## Find the number of rows and columns in the matrix
numberOfRows <- nrow(dataMatrix)
numberOfColumns <- ncol(dataMatrix)
## Access each value of the dataMatrix, check if it -3
for (i in 1:numberOfRows) # for each row
{
# Get indexes for -3 value
missingValueList = which(dataMatrix[i,] == -3);
# Find the index after which there is a break (so no consecutive value)
consecutiveBreaks = which(diff(missingValueList) != 1);
print(missingValueList)
print(consecutiveBreaks)
j=0;
for(k in 1:length(consecutiveBreaks))
{
if(k == 1)
{
cat(consecutiveBreaks[k], " missing value at: (",i,",",missingValueList[j+k],")","\n");
}
else
{
cat("Value of k: ", k, "\n");
cat(abs(consecutiveBreaks[k]-consecutiveBreaks[k-1]), " missing values starting from: (",i,",",missingValueList[j],")","\n");
}
j=j+1;
}
}
Can someone please help me to get the desired solution?
Here you go. I think this should work with your data:
val = 1;
counter = 1;
temp = matrix();
for (i in 1:nrow(mdata))
{
for (j in 1:ncol(mdata))
{
if (mdata[i,j] == -3)
{
while (j <= ncol(mdata))
{
if (mdata[i,j + val] == -3)
{
counter = counter + 1;
val = val + 1;
next;
}
else
{
break;
}
}
if (counter == 1)
{
#print(j);
#print(mdata[i, (j - 1):(j + 1)]);
temp <- t(as.matrix(mdata[i, (j - 1):(j + 1)]))
cat("\n This is with counter 1 \n")
print(temp)
cat("\n matrix: temp-1", temp[,1],"temp-2", temp[,3],"\n");
to.avg <- c(temp[,1], temp[,3]);
avg<-mean(to.avg)
mdata[i,j] = avg;
}
else
{
temp <- t(as.matrix(mdata[i,(j - 1):(j + counter)]))
cat("\n This is with multiple count \n")
cat(counter,"consecutive values were found, processing accordingly \n")
print(temp);
for (k in 0:(counter-1))
{
# cat("\n reading temp at the start \n")
# print(temp)
cat("\n K is ",(k+1), "and array is",length(temp),"long \n")
to.avg <- c(temp[,(k+1)], temp[,length(temp)]);
cat("averaging", temp[,(k+1)],"and", temp[,length(temp)]);
avg<-mean(to.avg)
cat("\n average =",avg);
temp[,(k+2)] = avg;
# cat("\n reading temp as this \n")
# print(temp)
mdata[i,j+k]=avg
}
}
}
else
{
mdata[i,j] = mdata[i,j];
}
val = 1;
counter = 1;
}
}

Non Decreasing Number Combinations (Interval)

So my problem is the following:
Given a number X of size and an A (1st number), B(Last number) interval, I have to find the number of all different kind of non decreasing combinations (increasing or null combinations) that I can build.
Example:
Input: "2 9 11"
X = 2 | A = 9 | B = 11
Output: 8
Possible Combinations ->
[9],[9,9],[9,10],[9,11],[10,10],[10,11],[11,11],[10],[11].
Now, If it was the same input, but with a different X, line X = 4, this would change a lot...
[9],[9,9],[9,9,9],[9,9,9,9],[9,9,9,10],[9,9,9,11],[9,9,10,10]...
Your problem can be reformulated to simplify to just two parameters
X and N = B - A + 1 to give you sequences starting with 0 instead of A.
If you wanted exactly X numbers in each item, it is simple combination with repetition and the equation for that would be
x_of_n = (N + X - 1)! / ((N - 1)! * X!)
so for your first example it would be
X = 2
N = 11 - 9 + 1 = 3
x_of_n = 4! / (2! * 2!) = 4*3*2 / 2*2 = 6
to this you need to add the same with X = 1 to get x_of_n = 3, so you get the required total 9.
I am not aware of simple equation for the required output, but when you expand all the equations to one sum, there is a nice recursive sequence, where you compute next (N,X) from (N,X-1) and sum all the elements:
S[0] = N
S[1] = S[0] * (N + 1) / 2
S[2] = S[1] * (N + 2) / 3
...
S[X-1] = S[X-2] * (N + X - 1) / X
so for the second example you give we have
X = 4, N = 3
S[0] = 3
S[1] = 3 * 4 / 2 = 6
S[2] = 6 * 5 / 3 = 10
S[3] = 10 * 6 / 4 = 15
output = sum(S) = 3 + 6 + 10 + 15 = 34
so you can try the code here:
function count(x, a, b) {
var i,
n = b - a + 1,
s = 1,
total = 0;
for (i = 0; i < x; i += 1) {
s *= (n + i) / (i + 1); // beware rounding!
total += s;
}
return total;
}
console.log(count(2, 9, 11)); // 9
console.log(count(4, 9, 11)); // 34
Update: If you use a language with int types (JS has only double),
you need to use s = s * (n + i) / (i + 1) instead of *= operator to avoid temporary fractional number and subsequent rounding problems.
Update 2: For a more functional version, you can use a recursive definition
function count(x, n) {
return n < 1 || x < 1 ? 0 : 1 + count(n - 1, x) + count(n, x - 1);
}
where n = b - a + 1

Vector as matrix coordinates

See https://stackoverflow.com/questions/41810306/appointment-scheduling....
You example does not work. You are indexing the second element twice (by the way, a nice alternative to your floor (rand (n) * x) is to use randi()):
octave> M = randi(10, 3)
M =
9 2 5
9 3 1
2 8 7
octave> v = [2;2];
octave> M(v)
ans =
9
9
octave> M([2;2])
ans =
9
9
The right way to do what you want is to use sub2ind() which works for any number of dimensions.
octave> M(sub2ind (size (M), 2, 2))
ans = 3
octave> M = randi (10, 3, 3, 3)
M =
ans(:,:,1) =
6 3 10
1 7 9
7 6 8
ans(:,:,2) =
7 9 10
9 4 5
8 5 5
ans(:,:,3) =
3 5 10
8 3 10
4 9 4
octave> M(sub2ind (size (M), 1, 2, 3))
ans = 5
I edited the sub2ind function so it can take a vector.
works like this:
M(sub2ind2(dims, V));
I will probably send the modified sub2ind2 function on the next days.
[EDIT]
function ind = sub2ind2 (dims, varargin)
if (nargin > 1)
if (isvector (dims) && all (round (dims) == dims))
nd = length (dims);
v = varargin{1};
vlen = length (v)
dims(vlen) = prod (dims(vlen:nd));
dims(vlen+1:nd) = [];
scale = cumprod (dims(:));
for i = 1:vlen
arg = v(i);
if (isnumeric (arg) && isequal (round (arg), arg))
if (i == 1)
if (all (arg(:) > 0 & arg(:) <= dims(i)))
ind = first_arg = arg;
else
error ("sub2ind: index out of range");
endif
else
if (size_equal (first_arg, arg))
if ((i > nd && arg == 1) || all (arg(:) > 0 & arg(:) <= dims(i)))
ind += scale(i-1) * (arg - 1);
else
error ("sub2ind: index out of range");
endif
else
error ("sub2ind: all index arguments must be the same size");
endif
endif
else
error ("sub2ind: expecting integer-valued index arguments");
endif
endfor
else
error ("sub2ind: expecting dims to be an integer vector");
endif
else
print_usage ();
endif
endfunction

Resources