I want to embed the following working python code into an html file by using pyscript. The inputs of the scripts are “input_str” as a sequence of integers such as 1,2,3,4,5,6 and “n”, which is an integer that divides the length of input_str. The output of the script is a matrix. Here is the script:
import numpy as np
input_str = input("Enter input_str:")
input_list = input_str.split(",")
w = []
for num in input_list:
w.append(int(num))
n = int(input("Enter n:"))
rows = len(w) // n
A = np.zeros((rows, n))
for i in range(len(w)):
if (w[i] % n == 0):
A[w[i]//n - 1, n-1] = int(i+1)
else:
A[w[i]//n, w[i]%n-1] = int(i+1)
A = A.astype(int)
print(A)
To embed this python script into an html file with pyscript, I have tried this:
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<input type="text" id="input_str"/>
<input type="number" id="n"/>
<button id="submit-button" type="button" py-click="my_function()">OK</button>
<div id="test-output"></div>
<p>Output:</p>
<p id='output'></p>
<py-config>
packages = ["numpy"]
</py-config>
<py-script>
import numpy as np
from pyscript import Element
def my_function():
input_str = Element('input.str').value
n = int(Element('n').value)
input_list = input_str.split(",")
w = []
for num in input_list:
w.append(int(num))
rows = len(w) // n
A = np.zeros((rows, n))
for i in range(len(w)):
if (w[i] % n == 0):
A[w[i]//n - 1, n-1] = int(i+1)
else:
A[w[i]//n, w[i]%n-1] = int(i+1)
result_place = Element('output')
result_place.write(str(A))
</py-script>
</body>
However, this gives the error NameError: name ‘input_list’ is not defined.
Any help or suggestion would be appreciated.