Mathematica Asked by giuseppe scafiti on March 28, 2021
I want to create a FormFunction that takes arbitrary many integer numbers and calculates the average. You want to use only one input field, but for more convenince allow users to write their numbers in different formats:
All inputs should yield 3 as the output of the FormFunction (after the input has been submitted). I want to use Interpreter to process these different types of input.
Thanks a lot for your help!!!
You may use StringReplace
to transform the different inputs into WL. The only problematic case is when two numbers are only separated by a space, but we can treat this by using a regular expression.
mean[in_String] := Module[{st = in},
st = StringReplace[st, {";" -> ",", "/" -> ",",
RegularExpression["(d) (d)"] -> "$1,$2"}];
st = "{" <> st <> "}";
Mean[ToExpression[st]]
]
mean["1; 2; 3; 4; 5 "]
mean["1, 2, 3, 4, 5 "]
mean["1/ 2/ 3/ 4/ 5 "]
mean["1, 2; 3/ 4 5 "]
Correct answer by Daniel Huber on March 28, 2021
The tricky part is the number extraction:
extract[s_String] :=
ToExpression /@ StringSplit[s, (" " | "," | ";" | "/") ..]
extract /@ {"1; 2; 3; 4; 5 ",
"1, 2, 3, 4, 5 ",
"1/ 2/ 3/ 4/ 5 ",
"1, 2; 3/ 4 5 "}
(* {{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5}} *)
Define a FormFunction
using the above extract
and a call to Mean
:
form = FormFunction["input" -> "String",
Mean[extract["input" /. #]] &];
activate it with
form[]
and see if it does what you need.
Answered by Roman on March 28, 2021
that tasks seems like a tough one. As in the previous solutions mentioned, the hard part for me was adding a space a separator but eventually I tried RegularExpression[]. However, I am not sure how to implement my idea in the function Interpreter[] as it is needed by your request.
Answered by Alexsom23814 on March 28, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP