Capt.Krusty
Capt.Krusty

Reputation: 627

If-else function from Python to R

I have watched this video and wrote the code down. The code shall put brackets around the repeating decimals occcuring in divisions. Today I tried to translate it from Python to R, but my knowledge of ifelse, while and functionin general are not that good as I hoped for. Down below you can see the steps I already tried and how far I have come, but I need help now for the following `while command part.

rep_dec = function(num,den){
  neg = FALSE
  if (den == 0){
    return("Undefined")
  } else if (num == 0){
    return("0")
  } else if (num*den < 0){
    neg = TRUE
  } else if (num%%den == 0){
    return(as.character(num/den))
  } 
numerator = abs(num)
denominator = abs(den)
paste("",(numerator%/%denominator),".")

results = list(0)
while (TRUE){
 remainder = numerator %% denominator
 numerator = remainder * 10
 quotient  = numerator %/% denominator
 if ([numerator,quotient]%!in% results){

 }

[Python Code from the video:]

def repeating_decimals(num,den):

    if den == 0:
        "Undefined"
    if num == 0:
        "0"
    neg = False    
    if num*den < 0:
        neg = True
    if num % den == 0:
        return str(num / den)

    numerator = abs(num)
    denominator = abs(den)

    output = ""
    output += str(numerator // denominator)
    output += "."
    print(output)

    num_q = []
    while True:
        rem = numerator % denominator
        if rem == 0:
            for element in num_q:
                output+= str(element[-1])
            break
        numerator = rem * 10
        q = numerator // denominator
        if [numerator, q] not in num_q:
            num_q.append([numerator, q])
        elif [numerator, q] in num_q:
            ind = num_q.index([numerator, q])
            for element in num_q[:ind]:
                output+=str(element[-1])
            output+= "("
            for element in num_q[ind:]:
                output+= str(element[-1])
            output+=")"
            break
    print(output)

repeating_decimals(1,7)

If someone could help me "translate this Python Code" into "R Code" I would get more insight on more complex functions and in a next step I would like to find the solution to get a "-" infront of the numbers to see if I get addings to the ifelse statement correctly.

Upvotes: 1

Views: 295

Answers (1)

Chelmy88
Chelmy88

Reputation: 1116

In R, the modulo takes the form %%, by doing so your code works.

rep_dec = function(num,den){
  neg = FALSE
  if (den == 0){
    return("Undefined")
  } else if (num == 0){
    return("0")
  } else if (num*den < 0){
    neg = TRUE
  } else if (num%%den == 0){
    return(as.character(num/den))
  } 
  numerator = abs(num)
  denominator = abs(den)
  output=paste0("",(numerator%/%denominator),".")

  num_vect=c()
  quo_vect=c()

  while (TRUE){
    remainder = numerator %% denominator
    numerator = remainder * 10
    quotient  = numerator %/% denominator

    if(remainder==0)
    {
      for(q in quo_vect)
      {
        output=paste0(output,q)
      }
      break
    }
    position <- which(num_vect==numerator & quo_vect==quotient)
    if ( length(position)==0 ){
      num_vect=c(num_vect,numerator)
      quo_vect=c(quo_vect,quotient)
    }
    else
    { 
      position=position[1]
      for (element in quo_vect[1:position])
      {
        output=paste0(output,element)
        output=paste0(output,"(")
        for (element in quo_vect[position:length(quo_vect)]){
          output=paste0(output,element)
        }
        output=paste0(output,")")
      }
      break
    }
  }
  return(output)
}

rep_dec(33,4) #"8.25"

rep_dec(20,4) #"5"

rep_dec(10,3) #"3.3(3)"

This should more or less do what you need, since I cant test there are probably some typos. To learn R I really encourage you to look at the documentation of the functions I use. The main difference with python is that I use thwo vectors num_vect and quo_vectinstead of an array of array as in python. Indeed, array of array does not exists in R (I could have used a data.frame instead or a matrix).

Upvotes: 1

Related Questions