Missing 1 required positional argument, Recursion - Python [closed] - recursion

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
def times(n,k):
if k >= 1:
return times(k-1) + n
times("140",3)
Traceback (most recent call last):
File "C:\Users\insane 18\Desktop\mat.py", line 21, in <module>
times("140",3)
File "C:\Users\insane 18\Desktop\mat.py", line 19, in times
return times(k-1) + n
TypeError: times() missing 1 required positional argument: 'k'
[Finished in 0.1s with exit code 1]
i keep getting this error even though i am putting the value of k but still getting this. please help me

Your times function takes two arguments as per your definition, namely k and n. However, when yyou recursively call the function times you're just supplying one argument(k) and not the other (n).
If you change your code to the following, it works.
def times(k, n):
if k<=1:
return times(k-1,n) # n has been moved inside the parentheses.
As a general guideline: Python doesn't have Tail Call Optimization and it is advised to avoid recursive calls.

The error is caused because you gave only one argument when you called times in line return times(k-1) + n

Related

Error: Symbol at (1) is not a DUMMY variable [duplicate]

This question already has answers here:
"Unclassifiable statement" when referencing a function
(1 answer)
Fortran array cannot be returned in function: not a DUMMY variable
(1 answer)
Closed 3 years ago.
I tried to write a code which gives GCD of two number:
program main
implicit none
integer::A,B,gcd,ans=0
read*,A,B
gcd(A,B)
write(*,*)'GCD of ',A,' and ',B,': ',ans
end program main
recursive function gcd(A,B) result(ans)
implicit none
integer,intent(in)::A,B
integer::ans
if (A==0) ans=B
if (B==0) ans=A
!base_case
if (A==B) ans=A
!recursive_case
if (A>B)then
ans=gcd(A-B,B)
else
ans=gcd(A,B-A)
end if
end function gcd
My input was:
98 56
I expect 14 but got this error:
source_file.f:5:4:
gcd(A,B)
1
Error: Unclassifiable statement at (1)
I didn't understand why I am getting this error? I heartily thank if anyone explain me why am I getting error.
You cannot specify intent(out) or any other intent or related attribute for the result variable. See Fortran array cannot be returned in function: not a DUMMY variable
Use just
integer::ans
In addition, just
gcd(A,B)
is not a valid way to use a function in Fortran. Use
ans = gcd(A,B)
or
print *, gcd(A,B)
or similar.
Please realize that ans declared in the main program is a variable that is not related to the result variable of the function. Even if the name is the same, they are two different things. It will be better to rename one of them to make it clear.

Is there a limit for the possible number of nested ifelse statements

I wrote a code that uses 75(!!!) nested ifelse statements.
I know its probably the most inefficient code I could write, but when I tried to run it I received the following error:
>Error: unexpected ')' in:
" ifelse(basic$SEMType=="ppc" &
(grepl("Wellpoint Prospecting",basic$CategoryName)), "Wellpoint Prospecting","other"
)))))))))))))))))))))))))))))))))))))"
I checked and doubled checked the number of ")". Its correct and the ifelse closes.
I also tried to run the nested ifelse by chunks, 15 at a time (and sometimes bigger chunks) and it works, so I figured the chance for syntax error is low.
Has anyone ever encountered such limitations?
I now run the code piece wise the inner ifelse first and record the result and move up the channel. This seems to work so far.
At least with this method, I seem to be able to create at most 50 levels of nesting
x<-"NA"
for(i in 1:50) {
x<-paste0("ifelse(x==",i,",",i,",", x, ")")
}
x
eval(parse(text=x), list2env(list(x=21)))
But if i try 51, i get the error
Error in parse(text = x) : contextstack overflow at line 1
so maybe that is specific to parse. It seems odd that you would get a syntax error.
Thanks to the link provided by #shadow, Brian Ripley confirmed this in a 2008 response to an r-help question
In this particular case [contextstack overflow], it is saying that you have more than 50 nested
parse contexts
And #Spacedman found where this limit is defined in the R source code
#define CONTEXTSTACK_SIZE 50

Define a S3 function using UseMethod [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to the programming R. I defined a function called liw.mstreeClass and I defined as below, but when I run the program I am keep getting the following errors:
# define method: lcosts(generic dispatch)
liw.mstreeClass <- function(nb, data, method, p) UseMethod("nbcosts"){
Error: unexpected '{' in "liw.mstreeClass <- function(nb, data, method, p) UseMethod("nbcosts"){"
if(method=="penrose") { liw <- mat2listw(penroseDis.mstreeClass((scale(data))))
return(liw)}
Error: object 'method' not found
}
Error: unexpected '}' in " }"
# liw.mstreeClass <- function(nb, data, method, p) UseMethod("nbcosts"){
# Error: unexpected '{' in "liw.mstreeClass <- function(nb, data, method, p)
Well, to start with, you've got a syntax error here. You can group several expressions with curly brackets but not start curly brackets after an expression.
Compare...
mean(1)
... with ...
mean(1){
# error!!
Secondly, in S3 you define methods for already existing generic functions. So if you have a function "liw" that could be applied to several classes, then liw.mstreeClass would define the way to do the "liw" for a class called "mstreeClass". So you first have to define liw as a generic function:
liw<-function(x,...){
UseMethod("liw")
}
Notice that you must have "liw" as an argument to UseMethod, not some random crap. (Take a look at the manual to understand why.) You would rarely have a lot of code besides the call to UseMethod in a generic function's body.
And having done that, you can define an mstreeClass method for liw. For example,
liw.mstreeClass<-function(x, y, z){
paste("liw equals ", x + y + z)
}
Note that as method dispatch in S3 is based on the first argument, your x must have class "mstreeClass" - only in that case, liw(x) will be directed to liw.mstreeClass(x). And I think if your generic has x as the first argument then the first argument of all methods must be called x too.
UseMethod("nbcosts"){"
if(method=="penrose") { liw <- mat2listw(penroseDis.mstreeClass((scale(data))))
return(liw)}
Error: object 'method' not found
}
Error: unexpected '}' in " }"
Umm.. sorry, these lines don't make a lot of sense. See above or the manuals on how to use UseMethod.

Debugging unexpected errors in R -- how can I find where the error occurred?

Sometimes R throws me errors such as
Error in if (ncol(x) != 2) { : argument is of length zero
with no additional information, when I've written no such code. Is there a general way for finding which function in which package causes an error?
Since most packages come compressed, it isn't trivial to grep /usr/lib/R/library.
You can use traceback() to locate where the last error occurred. Usually it will point you to a call you make in your function. Then I typically put browser() at that point, run the function again and see what is going wrong.
For example, here are two functions:
f2 <- function(x)
{
if (x==1) "foo"
}
f <- function(x)
{
f2(x)
}
Note that f2() assumes an argument of length 1. We can misuse f:
> f(NULL)
Error in if (x == 1) "foo" : argument is of length zero
Now we can use traceback() to locate what went wrong:
> traceback()
2: f2(x) at #3
1: f(NULL)
The number means how deep we are in the nested functions. So we see that f calls f2 and that gives an error at line 3. Pretty clear. We could reassign f with browser placed just before the f2 call now to check it's input. browser() simply allows you to stop executing a function and look around in its environment. Similar to debug and debugonce except that you don't have to execute every line up until the point you know something goes wrong.
Just to add to what #SachaEpskamp has already suggested, setting options(error=recover) and options(show.error.locations=TRUE) can be extremely helpful when debugging unfamiliar code. The first causes R to launch a debugging session on error, giving you the option to invoke the browser at any point in the call stack up to that error. The second option will tell R to include the source line number in the error.

Exception handling in R [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone have examples/tutorials of exception handling in R? The official documentation is very terse.
Basically you want to use the tryCatch() function. Look at help("tryCatch") for more details.
Here's a trivial example (keep in mind that you can do whatever you want with an error):
vari <- 1
tryCatch(print("passes"), error = function(e) print(vari), finally=print("finished"))
tryCatch(stop("fails"), error = function(e) print(vari), finally=print("finished"))
Have a look at these related questions:
Equivalent of "throw" in R
catching an error and then branching logic
https://stackoverflow.com/search?q=[r]+trycatch
Besides Shane's answer pointing you to other StackOverflow discussions, you could try a code search feature. This original answer pointed to Google's Code Search has since been discontinued, but you can try
Github search as e.g. in this query for tryCatch in language=R;
Ohloh/Blackduck Code search eg this query for tryCatch in R files
the Debian code search engine on top of the whole Debian archive
Just for the record, there is also try but tryCatch may be preferable. I tried a quick count at Google Code Search but try gets too many false positives for the verb itself -- yet it seems tryCatch is more widely used.
This result from a related google search helped me: http://biocodenv.com/wordpress/?p=15.
for(i in 1:16){
result <- try(nonlinear_modeling(i));
if(class(result) == "try-error") next;
}
The function trycatch() is fairly straight forward, and there are plenty of good tutorials on that. A excellent explanation of error handling in R can be found in Hadley Wickham's book Advanced-R, and what follows is a very basic intro to withCallingHandlers() and withRestarts() in as few words as possible:
Lets say a low level programmer writes a function to calculate the absolute
value. He isn't sure how to calculate it, but knows how to construct an
error and
diligently conveys his naiveté:
low_level_ABS <- function(x){
if(x<0){
#construct an error
negative_value_error <- structure(
# with class `negative_value`
class = c("negative_value","error", "condition"),
list(message = "Not Sure what to with a negative value",
call = sys.call(),
# and include the offending parameter in the error object
x=x))
# raise the error
stop(negative_value_error)
}
cat("Returning from low_level_ABS()\n")
return(x)
}
A mid-level programmer also writes a function to calculate the absolute value, making use of the woefully incomplete low_level_ABS function. He knows that the low level code throws a negative_value
error when the value of x is negative and suggests an solution to the problem, by
establishing a restart which allows users of mid_level_ABS to control the
way in which mid_level_ABS recovers (or doesn't) from a negative_value error.
mid_level_ABS <- function(y){
abs_y <- withRestarts(low_level_ABS(y),
# establish a restart called 'negative_value'
# which returns the negative of it's argument
negative_value_restart=function(z){-z})
cat("Returning from mid_level_ABS()\n")
return(abs_y)
}
Finally, a high level programmer uses the mid_level_ABS function to calculate
the absolute value, and establishes a condition handler which tells the
mid_level_ABS to recover from a negative_value error by using the restart
handler.
high_level_ABS <- function(z){
abs_z <- withCallingHandlers(
# call this function
mid_level_ABS(z) ,
# and if an `error` occurres
error = function(err){
# and the `error` is a `negative_value` error
if(inherits(err,"negative_value")){
# invoke the restart called 'negative_value_restart'
invokeRestart('negative_value_restart',
# and invoke it with this parameter
err$x)
}else{
# otherwise re-raise the error
stop(err)
}
})
cat("Returning from high_level_ABS()\n")
return(abs_z)
}
The point of all this is that by using withRestarts() and withCallingHandlers(), the function
high_level_ABS was able to tell mid_level_ABS how to recover from errors
raised by low_level_ABS error without stopping the execution of
mid_level_ABS, which is something you can't do with tryCatch():
> high_level_ABS(3)
Returning from low_level_ABS()
Returning from mid_level_ABS()
Returning from high_level_ABS()
[1] 3
> high_level_ABS(-3)
Returning from mid_level_ABS()
Returning from high_level_ABS()
[1] 3
In practice, low_level_ABS represents a function that mid_level_ABS calls a
lot (maybe even millions of times), for which the correct method of error
handling may vary by situation, and choice of how to handle specific errors is
left to higher level functions (high_level_ABS).
The restart function is very important in R inherited from Lisp. It is useful if you want to call some function in the loop body and you just want the program to continue if the function call collapses. Try this code:
for (i in 1:20) withRestarts(tryCatch(
if((a <- runif(1))>0.5) print(a) else stop(a),
finally = print("loop body finished!")),
abort = function(){})

Resources