Result of user-defined function not displaying on web app - output

I am trying to define a function that divides Amount of money by Number of days.
So far the user can submit values, but I don't know how to make the result display on my Streamlit web app.
I copied part of my code below.
P.S. I am also a complete beginner in Python.
Thanks for any help
#HOW OFTEN EAT OUT
st.write("2. How often do you eat out?")
form04 = st.form(key='form04')
days = form04.text_input('Please enter average number of days')
submit04 = form04.form_submit_button('Submit')
#HOW MUCH INCOME
if submit04:
st.write('3. What is your monthly income?')
form05 = st.form(key='form05')
income = form05.text_input('Please enter monthly income')
submit05 = form05.form_submit_button('Submit')
if submit05:
def idealbudget(days, income):
budget=float(income)/float(days)
return float(budget)
st.write('Result is', budget)

In this code snippet, you define a function but you never actually call it:
if submit05:
def idealbudget(days, income):
budget=float(income)/float(days)
return float(budget)
st.write('Result is', budget)
Additionally, your st.write call is tabbed incorrectly, it should be at the same level as the def statement. A working solution probably looks like the following (untested):
if submit05:
def idealbudget(days, income):
budget=float(income)/float(days)
return float(budget)
st.write('Result is', idealbudget(days, income))

Related

Use of function / return

I had the task to code the following:
Take a list of integers and returns the value of these numbers added up, but only if they are odd.
Example input: [1,5,3,2]
Output: 9
I did the code below and it worked perfectly.
numbers = [1,5,3,2]
print(numbers)
add_up_the_odds = []
for number in numbers:
if number % 2 == 1:
add_up_the_odds.append(number)
print(add_up_the_odds)
print(sum(add_up_the_odds))
Then I tried to re-code it using function definition / return:
def add_up_the_odds(numbers):
odds = []
for number in range(1,len(numbers)):
if number % 2 == 1:
odds.append(number)
return odds
numbers = [1,5,3,2]
print (sum(odds))
But I couldn’t make it working, anybody can help with that?
Note: I'm going to assume Python 3.x
It looks like you're defining your function, but never calling it.
When the interpreter finishes going through your function definition, the function is now there for you to use - but it never actually executes until you tell it to.
Between the last two lines in your code, you need to call add_up_the_odds() on your numbers array, and assign the result to the odds variable.
i.e. odds = add_up_the_odds(numbers)

Sentence-count function not returning total count

So i've been trying to create a sentence-count function which will cycle through the following 'story':
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
And I realise the problem I'm having but I cannot find a way around this. Basically I want my code to return a the total sCount below but seeing as I've returned my sCount after my loop, it's only adding and returning the one count as a total:
const sentenceTotal = (word) => {
let sCount = 0;
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
return sCount;
};
// console.log(sentenceTotal(story)) returns '1'.
I've tried multiple ways around this, such as returning sentenceTotal(word) instead of sCount but console.log will just log the function name.
I can make it return the correct sCount total if I remove the function element of it, but that's not what I want.
I don't see any loop or iterator which would go through story to count the number of occurrences of ., ?, or !.
Having recently tackled "counting sentences" myself I know it is a non-trivial problem with many edge cases.
For a simple use-case though you can use split and a regular expression;
story.split(/[?!.]/).length
So you could wrap that in your function like so:
const sentenceTotal = (word) => {
return word.split(/[?.!]/).length
};
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
sentenceTotal(story)
=> 13
There a several strange things about you question so I'll do it in 3 steps :
First step : The syntax.
What you wrote is the assignement to a const of an anonymous variable. So what it does is :
Create a const name 'sentenceCount'
To this const, assign the anonymous function (words) => {...}
Now you have this : sentenceCount(words){...}
And that's all. Because what you wrote : ()=>{} is not the calling of a function, but the declaration of an anonym function, you should read this : https://www.w3schools.com/js/js_function_definition.asp
If you want a global total, you must have a global total variable(not constant) so that the total isn't lost. So :
let sCount = 0; //<-- have sCount as a global variable not a const
function isEndOfSentence(word) {
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
};
If you are forbidden from using a global variable (and it's best to not do so), then you have to register the total as a return of your function and store the total in the calling 'CountWords(sentence)' function.
function isEndOfSentence(words) {...}
callingFunction(){
//decalaration
let total;
//...inside your loop
total += isEndOfSentence(currentWord)
}
The algorithm
Can you provide more context as how you use you function ?
If your goal is to count the words until there is a delimiter to mark the end of a sentence, your function will not be of great usage .
As it is written, your function will only ever be able to return 0 or 1. As it does the following :
The function is called.
It create a var called sCount and set it to 0
It increment or not sCount
It return sCount so 1 or 0
It's basically a 'isEndOfSentence' function that would return a boolean. It's usage should be in an algorithm like :
// var totalSentence = 0
// for each word
// if(isEndOfSentence(word))
// totalSentence + totalSentence = 1
// endfor
Also this comes back to just counting the punctuation to count the number of sentence.
The quick and small solution
Also I tried specifically to keep the program in an algorithm explicit form since I guess that's what you're dealing with.
But I feel that you wanted to write something small and with as little characters as possible so for your information, there are faster way of doing this with a tool called regex and the native JS 'split(separator)' function of a string.
A regex is a description of a string that it can match to and when used can return those match. And it can be used in JS to split a string:
story.split(/[?!.]/) //<-- will return an array of the sentences of your story.
story.split(/[?!.]/).length //<-- will return the number of element of the array of the sentences of your story, so the sentence count
That does what you wanted but with one line of code. But If you want to be smart about you problem, remember that I said
Also this comes back to just counting the punctuation to count the number of sentence.
So we'll just do that right ?
story.match(/(\.\.\.)|[.?!]/g).length
Have fun here ;) : https://regexr.com/
I hope that helps you ! Good luck !

Mean_squared_error output in function includes dtype and '0'

I want to calculate test statistics for a fb prophet forecast in a function because I want to average the test stats over different forecasts and cutoff points after using the fb-prophet cross_validation to get df_cv. I created a function that I apply to the dataframe after grouping by the cutoff points, in order to receive a measure per cutoff point. Then I calculate the mean over all these values.
The problem is that my function returns not only the value I am looking for but also a 0 as well as an information of the dtype. I can still do calculations with the returned value but when I want to plot etc. later it is very inconvenient. How can I strip these unnecessary values from the output?
def compute_avg_stats(df_cv,perf_measure):
measures = {'mse':mean_squared_error,'mae':mean_absolute_error,'mape':mean_absolute_percentage_error,'rmse':mean_squared_error}
performance_stats = {}
if perf_measure == 'rmse':
measure = np.sqrt(measures[perf_measure](y_true=df_cv['y'],y_pred=df_cv['yhat']))
else:
measure = measures[perf_measure](y_true=df_cv['yu'],y_pred=df_cv['yhat'])
return measure
df_cv.groupby('cutoff').apply(compute_avg_stats,perf_measure='rmse').to_frame().mean()
I think .mean() returns a Series. Try with .mean()[0]

Is a "Try / Except ValueError UNLESS" possible?

I'm new to python and have been trying like hell for the past few hours to figure out how to get this to work properly...
It's very simple code I'm sure, but I'm just not getting it.
It should be pretty self-explanatory below in the code, but basically I'm asking a user to input the date of an event as an 'int' and if it's not a number, then ask them to try again... UNLESS it's a "?"
while True:
date = None
street = str(input('Name of street?: ').title())
city = str(input("In what city?: ").title())
while True:
try:
year = int(input("Date of event? (or '?'): "))
if date == "?":
break
except Exception:
print("That's not a date, try again!")
continue
break
It seems that it's not even getting to see IF because it gets caught by the 'except' before it can.
If you're going to display help or something when a '?' is input, then just call the function to display the help where you have the break currently.
if date == "?":
display_help()
continue
Then, split reading the input and processing it into two steps.
in = input("Date of event? (or '?'): ")
if in == "?":
display_help()
continue
year = int(in)
Also, you ask for a date but then assume that a year is entered, I'd be more explicit in your promt.
"Please enter the year of the event, ex: 1998"
or whatever form you actually want it in.
Trying using a valueError exception. Also I think in your post you mentioned you wanted to enter a date as integer, so I replaced year with the date. If you wanted the year to be an integer you can replace the variable date with year. If you wanted to the user to enter a year, day and month then this program needs to be redesigned a bit.
date = None
street = str(input('Name of street?: ').title())
city = str(input("In what city?: ").title())
while True:
date = input("Date of event? (or '?'): ")
if date == "?":
break
else:
try:
date = int(date)
except ValueError:
print("That's not a date, try again!")
continue
break

How do I write a function that takes the average of a list of numbers

I want to avoid importing different modules as that is mostly what I have found while looking online. I am stuck with this bit of code and I don't really know how to fix it or improve on it. Here's what I've got so far.
def avg(lst):
'''lst is a list that contains lists of numbers; the
function prints, one per line, the average of each list'''
for i[0:-1] in lst:
return (sum(i[0:-1]))//len(i)
Again, I'm quite new and this for loops jargon is quite confusing to me, so if someone could help me get it so the output of, say, a list of grades would be different lines containing the averages. So if for lst I inserted grades = [[95,92,86,87], [66,54], [89,72,100], [33,0,0]], it would have 4 lines that all had the averages of those sublists. I also am to assume in the function that the sublists could have any amount of grades, but I can assume that the lists have non-zero values.
Edit1: # jramirez, could you explain what that is doing differently than mine possible? I don't doubt that it is better or that it will work but I still don't really understand how to recreate this myself... regardless, thank you.
I think this is what you want:
def grade_average(grades):
for grade in grades:
avg = 0
for num in grade:
avg += num
avg = avg / len(grade)
print ("Average for " + str(grade) + " is = " + str(avg))
if __name__ == '__main__':
grades = [[95,92,86,87],[66,54],[89,72,100],[33,0,0]]
grade_average(grades)
Result:
Average for [95, 92, 86, 87] is = 90.0
Average for [66, 54] is = 60.0
Average for [89, 72, 100] is = 87.0
Average for [33, 0, 0] is = 11.0
Problems with your code: the extraneous indexing of i; the use of // to truncate he averate (use round if you want to round it); and the use of return in the loop, so it would stop after the first average. Your docstring says 'print' but you return instead. This is actually a good thing. Functions should not print the result they calculate, as that make the answer inaccessible to further calculation. Here is how I would write this, as a generator function.
def averages(gradelists):
'''Yield average for each gradelist.'''
for glist in gradelists:
yield sum(glist) /len(glist)
print(list(averages(
[[95,92,86,87], [66,54], [89,72,100], [33,0,0]])))
[90.0, 60.0, 87.0, 11.0]
To return a list, change the body of the function to (beginner version)
ret = []
for glist in gradelists:
ret.append(sum(glist) /len(glist))
return ret
or (more advanced, using list comprehension)
return [sum(glist) /len(glist) for glist in gradelists]
However, I really recommend learning about iterators, generators, and generator functions (defined with yield).