Maximum Recursion depth exceeded: Code Academy; Taking a Vacation 5/7 - recursion

I'm making a model for vacation costs in a code academy exercise, and I have three functions defined so far, rental_car_costs with the argument days, hotel_cost with the argument nights, and plane_ride_cost with the argument of city. The code looks like this:
def hotel_cost(nights):
return hotel_cost(nights)
return 140 * nights
def plane_ride_cost(city):
return plane_ride_cost(city)
if "Charlotte":
return 183
elif "Tampa":
return 220
elif "Pittsburgh":
return 222
elif "Los Angeles":
return 475
def rental_car_cost(days):
rental_car_cost = 40 * days
if days >= 7:
rental_car_cost -= 50
elif days >= 3:
rental_car_cost -= 20
return rental_car_cost
All that works and I have no problem with it, but I want to make a function called trip_cost, and I keep getting a maximum recursion depth exceeded. The code looks like this
def trip_cost(city, days):
return plane_ride_cost(city) + hotel_costs(days) + rental_car_cost(days)
I pass the value of nights to days, and just in case I've tried substituting nights in anyway, but I still get the exact same error message. What am I doing wrong, and what does maximum depth recursion exceeded mean?

This should work:
def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
rental_car_cost = 40 * days
if days >= 7:
rental_car_cost -= 50
elif days >= 3:
rental_car_cost -= 20
return rental_car_cost

def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == ("Charlotte"):
return 183
elif city == ("Tampa"):
return 220
elif city == ("Pittsburgh"):
return 222
else:
return 475
def rental_car_cost(days):
if days >= 7:
return (40 * days) - 50
elif days >= 3:
return (40 * days) - 20
elif days < 3:
return (40 * days)
else:
return 0
def trip_cost(city, days):
return (hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days))
return trip_cost
this answer worked.

Related

Using data.table in r to eliminate inner for loop

I have an inner for-loop in R which I have identified as significant bottleneck in my code. The script simulates the effect of a time-varying policy on individuals prior to adulthood. The outer loop runs over a list of cohorts (yob = 1910,...,1930 etc.) that I would like to study. The inner loop counts from ages from a = 5 to a = 17. CSL.details is a data.table that contains the details of each law that I am studying in form of the variables I grab, which vary by year = birthyear + a. To understand the overall effects of the policy by birth cohort, I need to track ca_years1, ca_years2, ca_years3, and ca_years4 for each a.
ages = seq.int(5,17)
state = "Massachusetts"
yob = seq.int(1910, 1930)
for (birthyear in yob){
ca_years1 = 0; ca_years2 = 0; ca_years3 = 0; ca_years4 = 0;
for (a in ages){
thisyear = birthyear + a
# Grab each law for given state and year and implement exemption permit
thislaw <- CSL.details[statename == state & yob == birthyear & thisyear == year]
if (nrow(thislaw) == 0) next
exempt_workpermit = (ca_years2 >= thislaw$workyrs & a >= thislaw$workage & thislaw$workage > 0)
exempt_yearstodropout = (ca_years3 >= thislaw$earlyyrs & a >= thislaw$earlyyrs_condition & thislaw$earlyyrs > 0)
exempt_cont = ((ca_years2 + ca_years4) >= thislaw$contyrs & thislaw$contyrs > 0)
# Increment each law when school is required
if(thislaw$entryage <= a & a < thislaw$exitage){
ca_years1 = ca_years1 + 1
if(!exempt_workpermit){ca_years2 = ca_years2 + 1}
if(!exempt_yearstodropout){ca_years3 = ca_years3 + 1}
}
if(thislaw$contage > a &
a >= thislaw$workage &
!exempt_cont &
thislaw$workage > 0 &
!(thislaw$entryage <= a & a < thislaw$exitage & !exempt_workpermit)
){ca_years4 = ca_years4 + 1}
}
CSL.exposures[statename == state & yob == birthyear]$ca_years1 = ca_years1
CSL.exposures[statename == state & yob == birthyear]$ca_years2 = ca_years2
CSL.exposures[statename == state & yob == birthyear]$ca_years3 = ca_years3
CSL.exposures[statename == state & yob == birthyear]$ca_years4 = ca_years4
}
Is there a data.table solution for replacing the inner-loop? I am an intermediate R coder and it is a bit difficult to think of how to get started. Although I would prefer data.table exclusively, I am open to dplyr-type solutions if they significantly speed up the code.
Edit: here is an example of what CSL.detail looks like, as a copy-pasted data.table.
statename year yob statefip entryage exitage earlyyrs earlyyrs_condition workage workyrs contage contyrs statecompschoolyr
1: Massachusetts 1913 1800 25 7 16 4 14 14 4 16 0 1852
2: Massachusetts 1913 1801 25 7 16 4 14 14 4 16 0 1852
3: Massachusetts 1913 1802 25 7 16 4 14 14 4 16 0 1852
4: Massachusetts 1913 1803 25 7 16 4 14 14 4 16 0 1852
5: Massachusetts 1913 1804 25 7 16 4 14 14 4 16 0 1852
I managed to refactor the code to solve the problem. The key idea is to exploit state and yob as grouping variables (since all calculations happen within a state and yob pair). This completely eliminates the outer loops and requires only a single loop, iterating by age. I am just saving this answer here for reference, but I am not sure that there is a broader lesson for the stackoverflow.com community so feel free to delete. The time savings are on the order of 95%, primarily because it reduces the overhead time to call data.table.
for(a in ages){
# grab running total of years of education compelled by state and year of birth
CSL.details[CSL.exposures, on = .(statename, yob),
`:=` (ca_years1 = i.ca_years1,
ca_years2 = i.ca_years2,
ca_years3 = i.ca_years3,
ca_years4 = i.ca_years4)] %>%
.[year == a + yob,
`:=`(
# create exemptions by age based on number of years of schooling completed
exempt_workpermit = (ca_years2 >= workyrs & a >= workage & workage > 0),
exempt_yearstodropout = (ca_years3 >= earlyyrs & a >= earlyyrs_condition & earlyyrs > 0),
exempt_cont = ((ca_years2 + ca_years4) >= contyrs & contyrs > 0)
), by = .(statename, yob)]
CSL.exposures[
CSL.details[year == a + yob], on = .(yob, statename),
`:=` (exempt_workpermit = i.exempt_workpermit, exempt_yearstodropout = i.exempt_yearstodropout,
exempt_cont = i.exempt_cont, entryage = i.entryage,
exitage = i.exitage, contage = i.contage, workage = i.workage) ] %>%
.[ ,
`:=` (
ca_years1 =
fifelse(entryage <= a & a < exitage,
ca_years1 + 1, ca_years1, na = as.numeric(ca_years1)),
ca_years2 =
fifelse(entryage <= a & a < exitage & !exempt_workpermit,
ca_years2 + 1, ca_years2, na = as.numeric(ca_years2)),
ca_years3 =
fifelse(entryage <= a & a < exitage & !exempt_yearstodropout,
ca_years3 + 1, ca_years3, na = as.numeric(ca_years3)),
ca_years4 =
fifelse(contage > a & a >= workage & !exempt_cont &
workage > 0 &
!(entryage <= a & a < exitage & !exempt_workpermit),
ca_years4 + 1, ca_years4, na = as.numeric(ca_years4))),
by = .(statename, yob)
]
}

Get Dates of a Certain Weekday from a Year in dart

How might I generate a list of date objects for each Monday of a year?
i want like
7 1 2019
14 1 2019
21 1 2019
...
4 3 2019
11 3 2019
blabla
Is there a function to do this in the DateTime library? i think i missed something,the same question asked for R but I really did not understand anything
As far as I know the function doesn't exist but you can try this code:
void main() {
var givenYear = 1999;
var listOfMondays = [];
var dateIter = DateTime(givenYear);
while (dateIter.year < givenYear + 1) {
dateIter.add(new Duration(days: 1));
if (dateIter.weekday == 1) {
//1 for Monday, 2 for Tuesday, 3 for Wednesday and so on.
listOfMondays.add(dateIter);
}
}
}

problems defining time when pulling data from sqlite3

i have a problem getting the right setup for pulling data from a database.
i need to pull the last 10 minutes of data, and put it into a chart. i have 2 problems with that, i cant seem to get the arguments to work to get a specific time period (last 10 minutes), but i did manage to just grab the last 600 entries.
that works, but my chart X-axis is the wrong way, and i cant seem to find a way to invert the data in the table, after i pull it out of the database. (newest reading left and then getting older as you go further right on the chart)
the code i am using at the moment is this (yes it's ugly and borrowed from all over) but i hope you can look past it since this is my first time coding anything like this.
#!/usr/bin/env python
import sqlite3
import sys
import cgi
import cgitb
import time
global variables
speriod=(15)-1
dbname='/var/www/sensors.db'
def printHTTPheader():
print "Content-type: text/html\n\n"
def printHTMLHead(title, table):
print "<head>"
print " <title>"
print title
print " </title>"
print_graph_script(table)
print "</head>"
#current_time=time.time()
def get_data(interval):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
if interval == None:
curs.execute("SELECT * FROM readings")
else:
# curs.execute("SELECT * FROM readings")
curs.execute("SELECT * FROM readings ORDER BY timestamp DESC LIMIT "+str(600))
# curs.execute("SELECT * FROM readings WHERE time>=datetime('now','%s minutes')" % interval)
rows=curs.fetchall()
conn.close()
return rows
def create_table(rows):
chart_table=""
for row in rows[:-4]:
rowstr="['{0}', {1}],\n".format(str(row[2]),str(row[5]))
chart_table+=rowstr
row=rows[-1]
rowstr="['{0}', {1}]\n".format(str(row[2]),str(row[5]))
chart_table+=rowstr
return chart_table
def print_graph_script(table):
chart_code="""
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['windspeed', 'temperature'],
%s
]);
var options = {
title: 'windspeed'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>"""
print chart_code % (table)
def show_graph():
print "<h2>Windspeed Chart</h2>"
print '<div id="chart_div" style="width: 900px; height: 500px;"></div>'
def show_stats(option):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
if option is None:
option = str(24)
curs.execute("SELECT timestamp,max(windspeed) FROM readings WHERE time>date('now','-%s hour') AND time<=date('now')" % option)
# curs.execute("SELECT timestamp,max(windspeed) FROM readings WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowmax=curs.fetchone()
rowstrmax="{0}&nbsp&nbsp&nbsp{1}C".format(str(rowmax[0]),str(rowmax[1]))
curs.execute("SELECT timestamp,min(windspeed) FROM readings WHERE timestamp>time('time','-%s hour') AND timestamp<=time('current_time')" % option)
# curs.execute("SELECT timestamp,min(temp) FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowmin=curs.fetchone()
rowstrmin="{0}&nbsp&nbsp&nbsp{1}C".format(str(rowmin[0]),str(rowmin[1]))
curs.execute("SELECT avg(windspeed) FROM readings WHERE timestamp>time('now','-%s hour') AND timestamp<=time('current_time')" % option)
# curs.execute("SELECT avg(temp) FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowavg=curs.fetchone()
print "<hr>"
print "<h2>Minumum temperature&nbsp</h2>"
print rowstrmin
print "<h2>Maximum temperature</h2>"
print rowstrmax
print "<h2>Average temperature</h2>"
print "%.3f" % rowavg+ "C"
print "<hr>"
print "<h2>In the last hour:</h2>"
print "<table>"
print "<tr><td><strong>Date/Time</strong></td><td>
<strong>Temperature</strong></td></tr>"
rows=curs.execute("SELECT * FROM readings WHERE timestamp>datetime('now','-1 hour') AND timestamp<=datetime('now')")
# rows=curs.execute("SELECT * FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-1 hour') AND timestamp<=datetime('2013-09-19 21:31:02')")
for row in rows:
rowstr="<tr><td>{0}  </td><td>{1}C</td></tr>".format(str(row[0]),str(row[1]))
print rowstr
print "</table>"
print "<hr>"
conn.close()
def print_time_selector(option):
print """<form action="/cgi-bin/webgui.py" method="POST">
Show the temperature logs for
<select name="timeinterval">"""
if option is not None:
if option == "6":
print "<option value=\"6\" selected=\"selected\">the last 6 hours</option>"
else:
print "<option value=\"6\">the last 6 hours</option>"
if option == "12":
print "<option value=\"12\" selected=\"selected\">the last 12 hours</option>"
else:
print "<option value=\"12\">the last 12 hours</option>"
if option == "24":
print "<option value=\"24\" selected=\"selected\">the last 24 hours</option>"
else:
print "<option value=\"24\">the last 24 hours</option>"
else:
print """<option value="6">the last 6 hours</option>
<option value="12">the last 12 hours</option>
<option value="24" selected="selected">the last 24 hours</option>"""
print """ </select>
<input type="submit" value="Display">
</form>"""
def validate_input(option_str):
if option_str.isalnum():
if int(option_str) > 0 and int(option_str) <= 24:
return option_str
else:
return None
else:
return None
def get_option():
form=cgi.FieldStorage()
if "timeinterval" in form:
option = form["timeinterval"].value
return validate_input (option)
else:
return None
def main():
cgitb.enable()
option=get_option()
if option is None:
option = str(24)
records=get_data(option)
printHTTPheader()
if len(records) != 0:
table=create_table(records)
else:
print "No data found"
return
print "<html>"
printHTMLHead("Raspberry Pi Wind Logger", table)
print "<body>"
print "<h1>Raspberry Pi Wind Logger</h1>"
print "<hr>"
print_time_selector(option)
show_graph()
show_stats(option)
print "</body>"
print "</html>"
sys.stdout.flush()
if __name__=="__main__":
main()
the database contains 7 rows (unix time, date, time, windspeed, direction, temperature, checksum) it's data comming from an ultrasonic wind sensor, i would like to get the "options" in this working aswell like the max wind speed or the average wind speed, but i think that should become clear once i figure out how to actualy get the time sorted.
edit:
here is a reading pulled from the database
1540300313.94403|23/10/2018|21:11:53|0.1|273|24.1|5E*4B
and part of the code to store data in the database
cursor.execute('''insert into readings values (?, ?, ?, ?, ?, ?, ?)''',
(timestamp, current_date, current_time, windspeed, direction, temperature, checksum));
dbconnect.commit()

if else multiple conditions comparing rows

I am strugling with this loop. I want to get "6" in the second row of column "Newcolumn".I get the following error.
Error in if (mydata$type_name[i] == "a" && mydata$type_name[i - :
missing value where TRUE/FALSE needed.
The code that I created:
id type_name name score newcolumn
1 a Car 2 2
1 a van 2 6
1 b Car 2 2
1 b Car 2 2
mydata$newcolumn <-c(0)
for (i in 1:length(mydata$id)){
if ((mydata$type_name [i] == "a") && (mydata$type_name[i-1] == "a") && ((mydata$name[i]) != (mydata$name[i-1]))){
mydata$newcolumn[i]=mydata$score[i]*3 }
else {
mydata$newcolumn[i]=mydata$score[i]*1
}
}
Thank you very much in advance
List starts at index 1 in R but like you are doing a i-1 in your loop starting at 1, your list is out of range (i-1=0) so your code can not return a True or False.

Number pattern for checkboxes in asp.net?

I have a database table which contanis a field name Province bits and it adds up the count of the pattern like:
AB-1
BC-2
CD-4
DE-8
EF-16.... and so on.
Now in the table entry I have a value-13(Province bit), which implies checkboxes against entry AB,CD,DE(adds up to 13)should be checked.
I am not able to get the logic behind the same, how can check only those checkboxes whose sum adds up to the entry in the table?
You need to check to see if the value is in the bitwise total.
if( interestedInValue & totalValue == interestedInValue)
{
// this value is in the total, check the box
}
Documentation on & http://msdn.microsoft.com/en-us/library/sbf85k1c(v=vs.71).aspx
e.g. 13 = 1 + 4 + 8
13 & 1 == 1 // true
13 & 2 == 2 // false
13 & 4 == 4 // true
13 & 8 == 8 // true
13 & 16 == 16 // false
EDIT: for more clarification
ab.Checked = 1 && ProvinceBit == 1 // checkbox AB
bc.Checked = 2 && ProvinceBit == 2 // checkbox BC
...
The field is using bit flags.
13 is 1101 binary.
So convert the value to bits and assign one bit to each checkbox.
By converting your number to a string, you can convert to an array or just iterate through the string. A bit brute force, but will give you what you need.
var value = 13
string binary = Convert.ToString(value, 2);
//binary = "1101"

Resources