why my result is overriding in python - python-3.x

def geteta(self,b=0,etatype="schedule"):
eta_3_cuurtime = self.currtime + timedelta(hours = b)
[self.a["legdata"].get(str(i)).append({'depdetails':self.func(self.a["legdata"].get(str(i))[2],eta_3_cuurtime,etatype,self.thceta)}) if i==1 else self.a["legdata"].get(str(i)).append({'depdetails':self.func(self.a["legdata"].get(str(i))[2],self.a['legdata'].get(str(i-1))[3]['depdetails'][2])}) for i in range(1,len(self.a['legdata'])+1)]
eta1 = self.a["legdata"].get(str(len(self.a["legdata"])))[3]['depdetails'][2] #13. eta is last items depdetails [2] (available)
return eta1
def main(self):
eta3 = self.geteta()
eta4 = self.geteta(b=3)
when i am calling geteta method with different inputs my result (eta3,eta4) are same values.when i run method indiviual (comment first geteta) it is giving correct values.i know some where values are overriding but i am not able to figure out where it is.i hv struggling from couple of days for finding this but not.please help me in this

Related

How Can I Get A Dictionary Value From Python?

I was trying to convert a look up today to a data dictionary...for performance reasons...
It's almost working...Except that it's duplicating the entries on my output...
Here is my code in question...
class Calendar(HTMLCalendar):
def __init__(self, year=None, month=None, user=None):
self.user = user
self.year = year
self.month = month
super(Calendar, self).__init__()
# formats a day as a td
# filter events by day
def formatday(self, day, requests):
requests_per_day = DailyPlannerRequest.objects.filter(Q(created_by=self.user)).distinct().order_by('start_time')
daily_planner_events1 = []
for requests in requests_per_day:
requests_per_day_dict = model_to_dict(requests)
daily_planner_events1.append(requests_per_day_dict)
daily_planner_events1 = dict()
events = add_event_dates(requests_per_day)
all_event_dates = []
for event in events:
for date in event.dates:
if date not in all_event_dates and date.month == self.month and date.year == self.year:
all_event_dates.append(date)
for event in events:
for date in event.dates:
if date in all_event_dates and date not in daily_planner_events1 and date.month == self.month and date.year == self.year:
daily_planner_events1[date] = [event]
else:
if date.month == self.month and date.year == self.year:
daily_planner_events1[date].append(event)
# daily_planner_events[date].append(events)
d = ''
for requests in requests_per_day:
for event in daily_planner_events1:
if event.day == day:
d += f'<li> {requests.get_html_url} </li>'
if day != 0:
return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
return '<td></td>'
The code above works...Except it's giving me incorrect output...The problem piece in particular is this...
for requests in requests_per_day:
for event in daily_planner_events1:
if event.day == day:
d += f'<li> {requests.get_html_url} </li>'
It's not narrowing down the output specific enough.
I've played with this all afternoon..and the other version that actually kinda works is...
for event in daily_planner_events1:
if event.day == day:
d += f'<li> {event.get_html_url} </li>'
If I remove the request piece and change request to event it works exactly how I want except the get_html_url piece now doesn't work. It won't access the ID from the dictionary and as far as I can tell the way that I'm comparing the events...it doesn't have the ID information to provide. What am I doing wrong?
Thanks in advance for any thoughts.
Your code is very convoluted and could probably be made a whole lot simpler. For example, daily_planner_events1 is used as a list and then replaced with a dict() before you do anything with it? It's very hard to review your question because your code isn't straightforward and some of the functions aren't included, like add_event_dates and get_html_url.
To try and answer your question, the most likely reason why you are struggling to get your intended results is because your final nested for-loop aren't connected to each other properly, i.e. they aren't looping on related objects. Hence removing the outer for-loop has helped, presumably the reason why you aren't getting the output you want is because event.get_html_url isn't returning the right thing.
I went through all your code to try and figure out what's happening and think it could be far more succinct. As I mentioned already, I don't know what some of the functions do and I suspect there is a different model somewhere, so some things might need to change:
def formatday(self, day, requests):
# if the day is zero then return an empty table cell, don't run through any more code
if day == 0:
return '<td></td>'
# Q expression isn't needed here
requests_per_day = DailyPlannerRequest.objects.filter(created_by=self.user)...
# repeated checks of self.month and self.year can be done in an ORM filter
all_event_dates = SomeEventModel.filter(
dates__month=self.month,
dates__year=self.year
)
# no idea what this does?
events = add_event_dates(requests_per_day)
d = ''
# remove the if-statement and use another filter
for event in all_event_dates.filter(day=day):
d += f'<li> {event.get_html_url} </li>'
# return your table cell with the list appended
return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
After a week of trial and error...it turns out I needed to add a .date() to the loop to make it work.
for event in requests_per_day:
for request in daily_planner_events1:
if request.day == day and request == event.start_time.date():
d += f'<li> {event.get_html_url} </li>'

python function to pass the boolean operators and predict the survival mean with titanic dataset

I am trying to predict the survival chances of the passengers in the testing set.i was successful to predict the values with out using the function.
Dataset as follows
f = pd.read_csv('https://raw.githubusercontent.com/Explore-AI/Public-Data/master/Data/regression_sprint/titanic_train_raw.csv')
df_clean = pd.read_csv('https://raw.githubusercontent.com/Explore-AI/Public-Data/master/Data/regression_sprint/titanic_train_clean_raw.csv')
the expected results are below if the value is passed via function
survival_likelihood(df_clean,"Pclass","==","3") == 0.24
survival_likelihood(df_clean,"Age","<","15") == 0.58
i was able to get the output with out writing a function as per the below image
i have written the following function and am unable to get the desired results if the values is passed via function
def survival_likelihood(df_clean, column_name, boolean_operator, value):
column_name = df_clean.columns
value = df[column_name]
boolean_operator = [">" or "<" or "=="]
if column_name in df_clean.columns and df_clean[column_name].dtypes != object :
s = round(df_clean[df[column_name][boolean_operator][value]].Survived.mean(),
return s
have tried eval() method which did not help either. Looking forward for a pointer/fix for the same. Thanks in advance.
Regards,
Prakash
The below one works able to achieve what i want
def survival_likelihood(df_clean,column_name, boolean_operator, value):
if boolean_operator == '<':
s = df_clean[df_clean[column_name] < eval(value)] ['Survived'].mean()
#print(boolean_operator)
if boolean_operator == '>':
s = df_clean[df_clean[column_name] < eval(value)] ['Survived'].mean()
#print(boolean_operator)
if boolean_operator == '==':
s = df_clean[df_clean[column_name] == eval(value)] ['Survived'].mean()
return s

getting "none" as result and don't uderstand why

I am learning how to program in python 3 and today i was praticing until i start to struggle with this.
I was trying to make a function to get to know the total square meters of wood that i'll use in one project, but i keep get the none result and i don't know why, even reading almost every post about it that i found here.
Anyway, here's the code:
from math import pi
def acirc(r):
pi*r**2
def madeiratotal(r1,r2,r3,r4,r5):
a = acirc(r1)
b = acirc(r2)
c = acirc(r3)
d = acirc(r4)
e = acirc(r5)
print (a+b+c+d+e)
madeiratotal(0.15,0.09,0.175,0.1,0.115)
I already try defining the "acirc" function inside the "madeiratotal" function, try to print all numbers separated and them suming then... I just don't know what else to do please help
You need to return value from acirc function otherwise return type is None
def acirc(r):
return pi*r**2

Why is my calculation returning a result of 0 when the other identical one is in python

Windows, Spyder, Python 3.6
Hello, I am gradually working on this code and I keep getting null value for a calculation. I am performing the same calculation before it and when I print the variables by themselves they do not have null values. The code I am working on is below. The result I get when running the code is and ever changing value for the trd1() function but a 0.0 for trd2() function. I have looked for answers but cant seem to find any relevant ones?
import random
#define variables
amt1 = (1000)
amt2 = (1000)
prevAmt1 = ()
prevAmt2 = ()
#create random exchange rates
def exRt1():
return round(random.random() * (1.399 - 1.001) + 1.001, 3)
def exRt2():
return round(random.random() * (0.999 - 0.699) + 0.699, 3)
#assign exchange rates to variables
rate1 = exRt1()
rate2 = exRt2()
#create a conversion function
def convert(amount, exchange_rate):
return amount * exchange_rate
#create trade functions
def trd1(amount1,exRt2):
trd1Amt = convert(amount1, exRt2())
print(trd1Amt)
return trd1Amt
trd1(amount1,exRt2)
def trd2(amount2,exRt1):
trd2Amt = convert(amount2, exRt1())
print(trd2Amt)
return trd2Amt
trd1(amount2,exRt1)

Sorting arrays in Groovy

I'm trying to compare two arrays in groovy. My attempts so far have yielded a mixed response and therefore I'm turning to the collective for advice.
In the following code I'm taking 2 REST responses, parsing them and placing everything under the Invoice node into an array. I then further qualify my array so I have a list of InvoiceIDs and then try to compare the results of the two responses to ensure they are the same.
When I compare the array of InvoiceIDs (Guids) they match - this is not what I expect as the invoice order is currently different between my my 2 response sources.
When I sort the arrays of Invoices IDs the results differ.
I'm suspecting my code is faulty, but have spent an hour rattling through it, to no avail.
Any advice on sorting arrays in groovy or on the code below would be most appreciated:
gu = new com.eviware.soapui.support.GroovyUtils( context )
def xmlSlurper = new groovy.util.XmlSlurper()
// Setting up the response parameters
def responseSTAGE = xmlSlurper.parseText(context.expand('${GET Invoices - STAGE#Response}'));
def responseSTAGE2 = xmlSlurper.parseText(context.expand('${GET Invoices - STAGE2#Response}'));
responseInvoicesSTAGE = responseSTAGE.Invoices
responseInvoicesSTAGE2 = responseSTAGE2.Invoices
def arrayOfInvoicesSTAGE = []
def arrayOfInvoicesSTAGE2 = []
def counter = 0
for (invoice in responseInvoicesSTAGE.Invoice) {
arrayOfInvoicesSTAGE[counter] = responseInvoicesSTAGE.Invoice[counter].InvoiceID
//log.info counter+" STAGE"+arrayOfInvoicesSTAGE[counter]
arrayOfInvoicesSTAGE2[counter] = responseInvoicesSTAGE2.Invoice[counter].InvoiceID
//log.info counter+" STAGE2"+arrayOfInvoicesSTAGE2[counter]
counter++
}
log.info arrayOfInvoicesSTAGE
log.info arrayOfInvoicesSTAGE2
def sortedSTAGE = arrayOfInvoicesSTAGE.sort()
def sortedSTAGE2 = arrayOfInvoicesSTAGE2.sort()
log.info sortedSTAGE
As an aside, can't you replace:
def arrayOfInvoicesSTAGE = []
def arrayOfInvoicesSTAGE2 = []
def counter = 0
for (invoice in responseInvoicesSTAGE.Invoice) {
arrayOfInvoicesSTAGE[counter] = responseInvoicesSTAGE.Invoice[counter].InvoiceID
//log.info counter+" STAGE"+arrayOfInvoicesSTAGE[counter]
arrayOfInvoicesSTAGE2[counter] = responseInvoicesSTAGE2.Invoice[counter].InvoiceID
//log.info counter+" STAGE2"+arrayOfInvoicesSTAGE2[counter]
counter++
}
with
def arrayOfInvoicesSTAGE = responseInvoicesSTAGE.Invoice*.InvoiceID
def arrayOfInvoicesSTAGE2 = responseInvoicesSTAGE2.Invoice*.InvoiceID
Two arrays are considered equal in Groovy if they have they have the same number of elements and each element in the same position are equal. You can verify this by running the following code in the Groovy console
Integer[] foo = [1,2,3,4]
Integer[] bar = [4,3,2,1]
assert foo != bar
bar.sort()
assert foo == bar

Resources