0
Can anyone tell where my code is wrong? The 'sum in range' problem in R programming course.
input <- readLines('stdin') x <- as.integer(input[1]) y <- as.integer(input[2]) rangeSum <- function(x,y) { i <- 0 for (i in x:y) { i <- i+1 } return(i) } result <- rangeSum(x, y) print(result)
14 Answers
+ 3
Pradnya Meshram
declare variable with another name like sum instead of i because there is already a same variable in for loop so do this:
sum <- 0
for (i in x:y) {
sum <- sum + i
}
return (sum)
You have to add number between x to y so there should not be +1
For example : 5 - 9 so it should be 5 + 6 + 7 + 8 + 9
+ 1
Thank you, this helped a lot.
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟
+ 1
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟
Just want to add that "sum" is not an ideal variable name because there's also a built-in "sum()" function.
(Actually you could use sum() directly instead of loop, though I think the task asks for a loop)
+ 1
Lisa
Actually we can use function or method name as a variable, program will not give any error. When we do () with name then it is considered as a function and without () it's a variable.
+ 1
Yes, at least it doesn't overwrite in R :)
+ 1
Rolf Straub Could you please link the complete code?
+ 1
I copied the code to playground and did get any errors. Sometimes there's an error that sololearn doesn't execute it correctly (for me it helps to shut and restart the app)
If that doesn't help either, you can try to reset the code (click on the 3 dots in the top right) and re-write the solution
+ 1
I did that already. Danke.
0
Lisa
Neither in R nor in other programming languages.
Even python also accept inbuilt function as a variable.
As we know that function definition start with def in python so if we just write sum it doesn't mean that it is a function, it's a simple variable.
You can try this in python
sum = sum([1, 2, 3, 4])
print (sum)
Edited : But remember we cannot use sum function again after defining variable sum.
0
Does anbody else have this error?
" }" unexpected input
There must be some invisible token(s) somewhere in this part of the code. Best is to delete the line(s) and rewrite the code.
0
The Code is the ordinary code without any visible mistakes:
#define the function
rangeSum <- function(a,b) {
summe <- 0
for(z in a:b) {
summe <- summe+z
}
return(summe)
}
result <- rangeSum(x, y)
print(result)
0
Somewhere in this sequence was an unexpected token:
}
return(summe)
}
0
Mihai Apostol
I am saying in this case:
code 1:
li = [1, 2, 3, 4]
sum = 0
for i in li:
sum = sum + i
print (sum)
------------
code 2:
li1 = [1, 2, 3, 4]
print (sum(li1))
----------
Not in that case which you are talking.
- 1
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟
You are wrong. Try to use again sum as function after those two lines. You can't...