Reputation: 41
How to convert the following python code into R programming?
def weirdFaculty(v):
n = len(v)
Convert all the zeros to -1
as the zero gives us the negative score of -1
:
for i in range(n):
if not v[i]:
v[i] = -1
# Find the total sum
totalSum = sum(v)
currSum = 0
Find the point where current sum is greater than the total sum
for i in range(n):
if currSum > totalSum:
return i
currSum += v[i]
totalSum -= v[i]
return n
Upvotes: 0
Views: 209
Reputation: 1327
For the first one, the following R function zeros_to_minus_one
does the job:
zeros_to_minus_one <- function (vector) {
for (i in 1:length(vector)){
if (vector[i] == 0){
vector[i] <- -1
}
}
return(vector)
}
vector <- c(0,1,0,1,0)
zeros_to_minus_one(vector) # Returns: -1 1 -1 1 -1
For the second, the following R function find_point
does what you want:
find_point <- function (vector) {
currSum <- 0
totalSum <- 0
for (i in 1:length(vector)){
if (currSum > totalSum){
return(i)
}
currSum <- currSum + vector[i]
totalSum <- currSum - vector[i]
}
}
vector <- c(0,1,0,1,0)
find_point(vector) # Returns: 3
Upvotes: 1
Reputation: 887691
The first function would be
weirdFaculty <- function(v) {
v[v == 0] <- -1
sum(v)
}
Upvotes: 2