How can I solve this problem?
def median(lst):
lst_s=lst.sort()
k=len(lst)
if k%2==0:
return ((lst_s[k/2]+lst_s[k/2-1])/2)
elif k%2==1:
return (lst_s[k/2-1/2])
res = median([1,2,3,7,6,5])
print('median:',res)
when I run this, it says
Traceback (most recent call last):
File "E:\lab5_p4_2015123176.py", line 13, in <module>
res = median([1,2,3,7,6,5])
File "E:\lab5_p4_2015123176.py", line 7, in median
return ((lst_s[k/2]+lst_s[k/2-1])/2)
TypeError: 'NoneType' object is not subscriptable
The problem is that list.sort() sorts the items of the list in place thus returns None. In your median function you need to replace lst_s = lst.sort() by lst_s = sorted(lst) if you don't want to modify element order in the original list.
Related
Getting "AttributeError: sender" is thrown as the exchange query iterates. Same with other values (message_id, etc) too. My only option at this point is to put a try/catch around it and need to refactor a lot of content under the loop. However, I would think the query should not be crashing under normal circumstances due to any data issue. Please let me know what could be going wrong. There appears to be a 'bad' email object that causes it?
kwargs = {"is_read": False}
kwargs["datetime_received__gt"] = some_date_time
filtered_items = my_exchange._service_account.inbox.filter(**kwargs)
filtered_items.page_size = 20
print(filtered_items.count())
3 <-- 3 objects
for sender_obj, msg_id, msg_subj, msg_text, msg_size in filtered_items.values_list("sender", "message_id", "subject", "text_body", "size").iterator():
print(sender_obj)
count = count + 1
print(count)
Mailbox(name='Some User1', email_address='someuser1#myemail.acme', routing_type='SMTP', mailbox_type='Mailbox')
1
Mailbox(name='Some User2', email_address='someuser2#myemail.acme', routing_type='SMTP', mailbox_type='OneOff')
2
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 273, in __iter__
yield from self._format_items(items=self._query(), return_format=self.return_format)
File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 352, in _item_yielder
yield item_func(i)
File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 380, in <lambda>
item_func=lambda i: tuple(f.get_value(i) for f in self.only_fields),
File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 380, in <genexpr>
item_func=lambda i: tuple(f.get_value(i) for f in self.only_fields),
File "/usr/local/lib/python3.6/site-packages/exchangelib/fields.py", line 189, in get_value
return getattr(item, self.field.name)
AttributeError: sender
It looks like you are trying to get the sender field of something that is not a Message. Probably your inbox contains a meeting request or some other non-message object.
I'm not sure this is a bug. What did you expect to be the result of getting the sender attribute of something that does not have a sender field?
If you want only Message objects in your list, you can try adding a filter on item_class='IPF.Note'.
This is the part of code I am talking about:
while True:
print 'What is your age(only numeric):'
age = raw_input()
if age.isdigit():
break
print 'Please try again. We take only numeric value.'
When I replace isdigit with isdecimal, I get this error no matter what value i enter.
Traceback (most recent call last):
File "test.py", line 4, in <module>
if age.isdecimal():
AttributeError: 'str' object has no attribute 'isdecimal'
Although it runs fine with isdigit.
Also, when I replace raw_input with input, it give this error.
Traceback (most recent call last):
File "test.py", line 4, in <module>
if age.isdigit():
AttributeError: 'int' object has no attribute 'isdigit'
Am I doing something wrong which I am not able to catch? I am new to python and did my research about isdigit, is decimal, input and raw_input before putting down question here. It may be very minute error but I am not sure what is it.
For the first part:
In Python 2, isdecimal is a method of the unicode class, not of str (i.e. bytes). Hence:
>>> '3.2'.isdecimal()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'isdecimal'
>>> u'3.2'.isdecimal()
For the second part, input tries to guess what kind of input it gets, and will properly cast "1" into an int, while raw_input will always return the raw string. Since isdigit is a method defined in the str class, you get the error.
I often think it would be nice to have the following work even if the original object is a list... Is there a reason why this functionality is not implemented (in python 2.7)?
Example:
>>> a = [1,2,3,4]
>>> a.tolist()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'tolist'
Why is it this code won't work and give AttributeError?
internship = parser.find_all('a', attrs = {'title': lambda job: job.startswith('Internship')})
while this one works:
internship = parser.find_all('a', attrs = {'title': lambda job: job and job.startswith('Internship')})
This is the error that I got from the first code:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\bs4\element.py", line 1299, in find_all
return self._find_all(name, attrs, text, limit, generator, **kwargs)
File "C:\Python27\lib\site-packages\bs4\element.py", line 549, in _find_all
found = strainer.search(i)
File "C:\Python27\lib\site-packages\bs4\element.py", line 1690, in search
found = self.search_tag(markup)
File "C:\Python27\lib\site-packages\bs4\element.py", line 1662, in search_tag
if not self._matches(attr_value, match_against):
File "C:\Python27\lib\site-packages\bs4\element.py", line 1722, in _matches
return match_against(markup)
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'startswith'
In the first line of code, you are getting the attribute error because the code assumes that job contains a string, which has the method startswith(), but it doesn't contain a string, it contains None.
In the second line of code, you are not getting the attribute error because the code is testing to see if job contains None, before calling startswith() on it. Another (not quite equivalent but arguably better) way to express
lambda job: job and job.startswith('Internship')
is
lambda job: job.startswith('Internship') if job else False
I am logging all errors to a file, since there is no other way to see them properly in my case, especially in prod environment. Like this:
sys.stderr = open('py/log/my_logfile.error.log', 'a')
I am getting something similar to this:
Traceback (most recent call last):
File "my_awesome_file.py", line 50, in <module>
revision = session.Query()
AttributeError: 'Awesome' object has no attribute 'SomeSortOfAttribute'
Traceback (most recent call last):
File "my_awesome_file.py", line 50, in <module>
revision = session.Query()
AttributeError: 'Awesome' object has no attribute 'SomeSortOfAttribute'
It's two errors here (well, same error logged twice). I'd like to have if formatted a bit nicer (i.e. additional newline in between errors), and add a datetime if possible. Can I do it using this method of error logging?
After a little bit of reading Python manuals, it seems the solution is rather easy - instead of directly using file open() as a stream for stderr, I just have to use a custom stream. It's so painfully obvious it puzzles me why I didn't come up with it immediately. Well, it was Friday evening after all.
A very basic version would be:
import time
class LogStream(object):
def write(self, text):
f = open('py/log/my.custom.error.log', 'a')
f.write(time.strftime("%H:%M:%S ") + text + "\r\n")
f.close()
And then
sys.stderr = LogStream()
Result:
12:03:05 Traceback (most recent call last):
12:03:05 File "py/stuff.py", line 38, in <module>
12:03:05
12:03:05 raise Exception("just some test")
12:03:05 Exception
12:03:05 :
12:03:05 just some test
12:03:05
I might want to customize it a bit more but it's good enough already.