def monday_availability(openhours_M): #openhours_M = number hours pool is open
hourone = int(input('Input the first hour in the range of hours the guard can work'))
hourlast = int(input('Input the last hour in the range of hours the guard'))
hour = 1
availability_M = []
while hour <= openhours_M:
if hour >= hourone & hour <= hourlast:
availability_M.append(1)
else:
availability_M.append(0)
return availability_M
Above is a function gathering the availability of a lifeguard and storing the hours a guard can work as a 1 in availability list or a 0 if they cannot. I return this list with the intent of adding it to a dictionary in the function below.
def guard_availability(guards, openhours_M, openhours_T, openhours_W,
openhours_R, openhours_F, openhours_S, openhours_Su):
continueon = 1
while continueon == 1:
name = input('Input guards name of lifeguard to update availability' )
availability = {}
days = {}
if openhours_M != 0:
monday_availability(openhours_M)
if openhours_T != 0:
tuesday_availability(openhours_T)
if openhours_W != 0:
wednesday_availability(openhours_W)
if openhours_R != 0:
thursday_availability(openhours_R)
if openhours_F != 0:
friday_availability(openhours_F)
if openhours_S != 0:
saturday_availability(openhours_S)
if openhours_Su != 0:
sunday_availability(openhours_Su)
days['Monday'] = availability_M
days['Tuesday'] = availability_T
days['Wednesday'] = availability_W
days['Thursday'] = availability_R
days['Friday'] = availability_F
days['Saturday'] = availability_S
days['Sunday'] = availability_Su
availability[name]= days
continueon = input('Enter 1 to add availability for another guard, 0 to stop: ')
return days
When I run this code, I get an error saying my availability lists are undefined even though I returned them in the functions above. Where is the error in my understanding of returning in functions, and how can I remedy this problem.
monday_availability(openhours_M) returns a value.
Returning a variable does not assign it to anything outside the scope of that function.
If you renamed return availability_M to use return foo and update the other uses only within that function accordingly, would the error make more sense?
Now, actually capture the result
availability_M = monday_availability(openhours_M)
Or even just
days['Monday'] = monday_availability(openhours_M)
Also, not seeing how that function has anything to do with Mondays. Try to write DRY code
You return the dic value in your function but don't assign it to any variable. You should do it like this:
if openhours_M != 0:
availability_M=monday_availability(openhours_M)
if openhours_T != 0:
availability_T=tuesday_availability(openhours_T)
if openhours_W != 0:
availability_W=wednesday_availability(openhours_W)
if openhours_R != 0:
availability_R=thursday_availability(openhours_R)
if openhours_F != 0:
availability_F=friday_availability(openhours_F)
if openhours_S != 0:
availability_S=saturday_availability(openhours_S)
if openhours_Su != 0:
availability_Su=sunday_availability(openhours_Su)
Related
Hello this is my first question and sorry I don't know how to phrase it,
I am trying to create a two list. The first list is for one set of codes (code1) and is validated in the VC function. The second function (VC) is to validate the second list. Both functions work well in validating the numbers. However in the third function (add_validations). In that function I want to repeat VC and VQ until the user either types in END or either of the functions return False. When true I want the inputs to be appended into the two separate lists. However, the third function not only does not append any of the list it does not identify/run either of the two functions and comes up with:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
And I'm sorry I didn't know which code to add so I added everything (delete if not allowed sorry):
Code:
def add_validations():
code1 = []
code2 = []
VC()
VQ()
while True:
record = []
i = VC()
q = VQ()
if i != "END":
VQ()
VC()
code1.append(int(i))
code2.append(int(q))
elif VC == True and VQ() == True:
VQ()
VC()
code1.append(int(i))
code2.append(int(q))
elif VC == False and VQ() == True:
print("Invalid code")
else:
print("Invalid quantity")
return code1,code2
def VC():
i = input("What is the item code \n")
minimum = 0
maximum = 39
if i == "END":
i = "END"
return showRecord()
elif int(i) > minimum and int(i) <= maximum:
return int(i)
True
else:
False
def VQ():
q = input("What quanity \n")
minimum = 0
maximum = 49
if q == "END":
isValidCode = "END"
return showRecord()
elif int(q) > minimum and int(q) <= maximum:
True
else:
False
I'm trying to create a while loop and have the index increase by 1 every time the loop runs.
I have n set to zero, which should tell python that this is an integer. However, when it gets to if contact_list[n]['vid'] == '':, it sees n as a string.
Here is the loop. Any help is greatly appreciated:
has_more = True
n = 0
while has_more:
parameters = urllib.parse.urlencode(parameter_dict)
get_url = get_all_contacts_url + parameters + property_params
r = requests.get(url= get_url, headers = headers)
response_dict = json.loads(r.text)
has_more = response_dict['has-more']
contact_list.append(response_dict['contacts'])
parameter_dict['vidOffset']= response_dict['vid-offset']
if len(contact_list) >= max_results:
max_results += 100
if contact_list[n]['vid'] == '':
break
contact_count += 1
print('loop finished')
list_length = len(contact_list)
print("List Length:",list_length)
print("You've succesfully parsed through {} contact records and added them to a list".format(list_length))
Try this:
if 'vid' in contact_list:
if contact_list[n] == '':
break
Hope that helps!
Yes, and realized n is actually not being incremented, if that's the case just call 0 as the list index without having to assign n=0.
The format that I stored them in was:
website/website/objecthash/xcord/ycord/likelyhood/year/month/datenumber/hour/minutes
Right now I have the bucket I want to pull them out of.
Say I want the most recent 10 stored objects. What is an efficient way to do this?
I have the bucket, what do I do with it?
My solution was something like this for get todays however I'm not sure about the logic for get most recent:
def getKeys():
b = bucket.list()
theKeys=[]
for key in b:
theKeys.append(key)
return theKeys
def getDecompiledToday():
time = datetime.datetime.now()
year =time.strftime("%Y")
month = time.strftime("%m")
day = time.strftime("%D")
keys = getKeys()
objects = []
for k in keys:
splitK= k.split("/")
if splitK[6]==year and splitK[7]==month and splitK[8]==day:
objets.append(bucket.get_key(k))
return
The solution that I came up with.
def getPastAmountDecompiledFromFile(number):
if bucketKeys.__len__() > 0:
Found=[]
latest=bucketKeys[0]
while Found.__len__() < number:
laterFound = False
for k in bucketKeys:
if latest in Found:
latest=k
current = k.split("/")
best = k.split("/")
if k not in Found and latest != k:
if int(current[6]) > int(best[6]):
laterFound=True
if int(current[6]) == int(best[6]) and int(current[7]) > int(best[7]):
laterFound=True
if int(current[6]) == int(best[6]) and int(current[7]) == int(best[7]) and int(current[8]) > int(best[8]):
laterFound=True
if int(current[6]) == int(best[6]) and int(current[7]) == int(best[7]) and int(current[8]) == int(best[8]) and int(current[9]) > int(best[9]):
laterFound=True
if laterFound:
latest = k
if laterFound:
Found.append(latest)
return getKeyFromKeyNames(Found)
else:
getKeysInFile()
getPastAmountDecompiledFromFile(number)
return
I'm generating a dictionary in a function and then returning this dictionary. I can't seem to access the returned dict as a dictionary though despite it being the correct format.. It is treating the data as a string only, ie i can print it but can't print d.keys() or d.items() What the heck am I doing wrong?????
data when printed as a str()
{1: '214902885,214902909', 2: '214902910,214902934', 3: '214902935,214902959', 4: '214902960,214902984', 5: '214902985,214903009', 6: '214903010,214903034', 7: '214903035,214903059', 8: '214903060,214903084', 9: '214903085,214903109', 10: '214903110,214903139'}
Error when I try to print d.items() or d.keys()
print bin_mapping.keys()
AttributeError: 'str' object has no attribute 'keys'
Once I have returned the dict from a function do I have to redefine it as a dictionary? I'd really appreciate some help as I'm super frustrated :/
Thanks,
As suggested here is the code.. Function I'm calling to return the dictionary first..
def models2bins_utr(id,type,start,end,strand):
''' chops up utr's into bins for mC analysis'''
# first deal with 5' UTR
feature_len = (int(end) - int(start))+1
bin_len = int(feature_len) /10
if int(feature_len) < 10:
return 'null'
#continue
else:
# now calculate the coordinates for each of the 10 bins
bin_start = start
d_utr_5 = {}
d_utr_3 = {}
for i in range(1,11):
# set 1-9 first, then round up bin# 10 )
if i != 10:
bin_end = (int(bin_start) +int(bin_len)) -1
if str(type) == 'utr_5':
d_utr_5[i] = str(bin_start)+','+str(bin_end)
elif str(type) == 'utr_3':
d_utr_3[i] = str(bin_start)+','+str(bin_end)
else:
pass
#now set new bin_start
bin_start = int(bin_end) + 1
# now round up last bin
else:
bin_end = end
if str(type) == 'utr_5':
d_utr_5[i] = str(bin_start)+','+str(bin_end)
elif str(type) == 'utr_3':
d_utr_3[i] = str(bin_start)+','+str(bin_end)
else:
pass
if str(type) == 'utr_5':
return d_utr_5
elif str(type) == 'utr_3':
return d_utr_3
Calling the function and trying to access the dict
def main():
# get a list of all the mrnas in the db
mrna_list = get_mrna()
for mrna_id in mrna_list:
print '-----'
print mrna_id
mrna_features = features(mrna_id)
# if feature utr, send to models2bins_utr and return dict
for feature in mrna_features:
id = feature[0]
type = feature[1]
start = feature[2]
end = feature[3]
assembly = feature[4]
strand = feature[5]
if str(type) == 'utr_5' or str(type) == 'utr_3':
bin_mapping = models2bins_utr(id,type,start,end,strand)
print bin_mapping
print bin_mapping.keys()
You return a string early on:
bin_len = int(feature_len) /10
if int(feature_len) < 10:
return 'null'
Perhaps you wanted to raise an exception instead here, or at the very least, return an empty dictionary or use None as a flag value.
If you use None do test for it:
bin_mapping = models2bins_utr(id,type,start,end,strand)
if bin_mapping is not None:
# you got a dictionary.
I'm wondering what return 'null' is supposed to achieve. My guess is that once in a while, you call the function with the wrong parameters and get this string back.
I suggest to throw an exception instead (raise Exception('Not enough arguments') or similar) or to return an empty dict.
You should also learn about repr() because it gives you more information about an object which makes debugging much easier.
So i wrote this code and it passes the first test case, and fails all the rest. However, I can't seem to find an input that breaks it. Maybe it's because I've been staring at the code too long, but i would appreciate any help.
The algorithm uses two priority queues for the smallest and largest halves of the current list. Here's the code:
#!/bin/python
import heapq
def fix(minset, maxset):
if len(maxset) > len(minset):
item = heapq.heappop(maxset)
heapq.heappush(minset, -item)
elif len(minset) > (len(maxset) + 1):
item = heapq.heappop(minset)
heapq.heappush(maxset, -item)
N = int(raw_input())
s = []
x = []
for i in range(0, N):
tmp = raw_input()
a, b = [xx for xx in tmp.split(' ')]
s.append(a)
x.append(int(b))
minset = []
maxset = []
for i in range(0, N):
wrong = False
if s[i] == "a":
if len(minset) == 0:
heapq.heappush(minset,-x[i])
else:
if x[i] > minset[0]:
heapq.heappush(maxset, x[i])
else:
heapq.heappush(minset, -x[i])
fix(minset, maxset)
elif s[i] == "r":
if -x[i] in minset:
minset.remove(-x[i])
heapq.heapify(minset)
elif x[i] in maxset:
maxset.remove(x[i])
heapq.heapify(maxset)
else:
wrong = True
fix(minset, maxset)
if len(minset) == 0 and len(maxset) == 0:
wrong = True
if wrong == False:
#Calculate median
if len(minset) > len(maxset):
item = - minset[0]
print int(item)
else:
item = ((-float(minset[0])) + float(maxset[0])) / 2
if item.is_integer():
print int(item)
continue
out = str(item)
out.rstrip('0')
print out
else:
print "Wrong!"
Your original was not so legible, so first I made it object-oriented:
MedianHeapq supports methods rebalance(), add(), remove(), size(), median(). We seriously want to hide the members minset,maxset from the client code, for all sorts of sensible reasons: prevent client from swapping them, modifying them etc. If client needs to see them you just write an accessor.
We also added a __str__() method which we will use to debug visually and make your life easier.
Also added legibility changes to avoid the indexing with [i] everywhere, rename s,x arrays to op,val, add prompts on the raw_input(), reject invalid ops at the input stage.
Your actual computation of the median confuses me (when do you want float and when integer? the rstrip('0') is a bit wack), so I rewrote it, change that if you want something else.
A discussion of the algorithm is here.
Now it is legible and self-contained. Also makes it testable.
You might be making sign errors in your code, I don't know, I'll look at that later.
Next we will want to automate it by writing some PyUnit testcases. doctest is also a possibility. TBC.
Ok I think I see a bug in the sloppiness about locating the median. Remember the minset and maxset can have a size mismatch of +/-1. So take more care about precisely where the median is located.
#!/bin/python
import heapq
class MedianHeapq(object):
def __init__(self):
self.minset = []
self.maxset = []
def rebalance(self):
size_imbalance = len(self.maxset) - len(self.minset)
if len(self.maxset) > len(self.minset):
#if size_imbalance > 0:
item = heapq.heappop(self.maxset)
heapq.heappush(self.minset, -item)
#elif size_imbalance < -1:
elif len(self.minset) > (len(self.maxset) + 1):
item = heapq.heappop(self.minset)
heapq.heappush(self.maxset, -item)
def add(self, value, verbose=False):
if len(self.minset) == 0:
heapq.heappush(self.minset,-value)
else:
if value > self.minset[0]:
heapq.heappush(self.maxset, value)
else:
heapq.heappush(self.minset, -value)
self.rebalance()
if verbose: print self.__str__()
return False
def remove(self,value,verbose=False):
wrong = False
if -value in self.minset:
minset.remove(-value)
heapq.heapify(self.minset)
elif value in maxset:
maxset.remove(value)
heapq.heapify(self.maxset)
else:
wrong = True
self.rebalance()
if verbose: print self.__str__()
return wrong
def size(self):
return len(self.minset)+len(self.maxset)
def median(self):
if len(self.minset) > len(self.maxset):
item = - self.minset[0]
return int(item)
else:
item = (-self.minset[0] + self.maxset[0]) / 2.0
# Can't understand the intent of your code here: int, string or float?
if item.is_integer():
return int(item)
# continue # intent???
else:
return item
# The intent of this vv seems to be round floats and return '%.1f' % item ??
#out = str(item)
#out.rstrip('0') # why can't you just int()? or // operator?
#return out
def __str__(self):
return 'Median: %s Minset:%s Maxset:%s' % (self.median(), self.minset,self.maxset)
# Read size and elements from stdin
N = int(raw_input('Size of heap? '))
op = []
val = []
while(len(val)<N):
tmp = raw_input('a/r value : ')
op_, val_ = tmp.split(' ')
if op_ not in ['a','r']: # reject invalid ops
print 'First argument (operation) must be a:Add or r:Remove! '
continue
op.append(op_)
val.append(int(val_))
mhq = MedianHeapq()
for op_,val_ in zip(op,val): # use zip to avoid indexing with [i] everywhere
wrong = False
if op_ == 'a':
wrong = mhq.add(val_)
elif op_ == 'r':
wrong = mhq.remove(val_)
assert (mhq.size()>0), 'Heap has zero size!'
assert (not wrong), 'Heap structure is wrong!'
if not wrong:
print mhq.__str__()