1

I am studying R Shiny package called Reticulate. I was following a Youtube, but I got an error.
R Shiny Codes

library(shiny)
library(reticulate)

source_python("practice2_simulator.py")

ui <- fluidPage(
  
  titlePanel("Using SHiny with Python"),
  
  sidebarLayout(
    
    sidebarPanel(
      numericInput(
        'num_tosses',
        label = "Number of Coin Tosses",
        value = 50
      ),
      numericInput(
        'num_sims',
        label = "Number of Simulations",
        value = 1000
      ),
      sliderInput(
        'bias',
        label = "Probability of Obstaining Heads",
        value = 0.5,
        min = 0,
        max = 1,
        step = 0.1
      )
    ),
    
    mainPanel(
      plotOutput('heads_plot')
    )
    
  )
)

server <- function(input, output) {
  
  output$heads_plot <- renderPlot({
    
    sims <- head_dist(input$num_tosses,
                      input$num_sims,
                      input$bias)
    
    hist(sims, col = "#75AADB", border = 'white', xlab = "Number of Heads")
    
  })
  
}


shinyApp(ui, server)

The Python codes

from random import random

def head_dist(num_tosses, num_sims, bias):
  return [num_heads(num_tosses, bias) for in x range(num_sims)]

def num_heads(num_tosses, bias):
  return sum([random() < bias for x in range(num_tosses)])

I am getting the following error
Error in py_run_file_impl(file, local, convert) : SyntaxError: invalid syntax (, line 4)
Line 4 is

source_python("practice2_simulator.py")

Can you help me why I am getting such error?

Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

0

The error you're getting is in reference to line 4 in your Python file:

1 from random import random
2 
3 def head_dist(num_tosses, num_sims, bias):
4   return [num_heads(num_tosses, bias) for in x range(num_sims)]

Your list comprehension seems to have a typo, I think you need to change it to this:

return [num_heads(num_tosses, bias) for x in range(num_sims)]
seagullnutkin
  • 311
  • 1
  • 10