python-2.7 interview questions
Top python-2.7 frequently asked interview questions
Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
This seems to be only differentiating between dates that have different days:
t.toordinal()
Any help is much appreciated.
Source: (StackOverflow)
If I do this:
>>> False in [False, True]
True
That returns True
. Simply because False
is in the list.
But if I do:
>>> not(True) in [False, True]
False
That returns False
. Whereas not(True)
is equal to False
:
>>> not(True)
False
Why?
Source: (StackOverflow)
I am new to Python and am working on a Linux machine (Ubuntu 10.10). It is running python 2.6, but I'd like to run 2.7 as it has features I want to use. I have been urged to not install 2.7 and set that as my default python.
My question is, how can I install 2.7 and run it side by side with 2.6?
Source: (StackOverflow)
I'm trying to convert a list to a tuple.
When I google it I find a lot of answers similar to:
l = [4,5,6]
tuple(l)
But if I do that I get this error message:
TypeError: 'tuple' object is not callable
Source: (StackOverflow)
I have the following code
test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test
print(selectiveEscape)
I would like to get the output:
Print percent % in sentence and not have it break.
What actually happens:
selectiveEscape = "Use percent % in sentence and not %s" % test
TypeError: %d format: a number is required, not str
Source: (StackOverflow)
While profiling a piece of python code (python 2.6
up to 3.2
), I discovered that the
str
method to convert an object (in my case an integer) to a string is almost an order of magnitude slower than using string formatting.
Here is the benchmark
>>> from timeit import Timer
>>> Timer('str(100000)').timeit()
0.3145311339386332
>>> Timer('"%s"%100000').timeit()
0.03803517023435887
Does anyone know why this is the case?
Am I missing something?
Source: (StackOverflow)
I'm using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message:
import subprocess
text = 'Hello World.'
print text
subprocess.call(['espeak', text])
eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib..., no socket connect) so i cannot easily read what was printed earlier. Exit code is 0.
Unfortunately there is no documented option to turn off its verbosity, so I'm looking for a way to only visually silence it and keep the open shell clean for further interaction.
How can I do this?
Source: (StackOverflow)
Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod()
. How, then, can one explain this
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
What's the deal?!
I'll explain this a little for those who didn't quite get that.
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
>>> obj.myPublicMethod()
public method
Next, I try and call its private method.
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running dir() on the object reveals a new magical method that python creates magically for all of your 'private' methods.
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
This new method's name is always an underscore, followed by the class name, followed by the method name.
>>> obj._MyClass__myPrivateMethod()
this is private!!
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?
Source: (StackOverflow)
This is a follow-up question to an answer I gave a few days back. Edit: it seems that the OP of that question already used the code I posted to him to ask the same question, but I was unaware of it. Apologies. The answers provided are different though!
Substantially I observed that:
>>> def without_else(param=False):
... if param:
... return 1
... return 0
>>> def with_else(param=False):
... if param:
... return 1
... else:
... return 0
>>> from timeit import Timer as T
>>> T(lambda : without_else()).repeat()
[0.3011460304260254, 0.2866089344024658, 0.2871549129486084]
>>> T(lambda : with_else()).repeat()
[0.27536892890930176, 0.2693932056427002, 0.27011704444885254]
>>> T(lambda : without_else(True)).repeat()
[0.3383951187133789, 0.32756996154785156, 0.3279120922088623]
>>> T(lambda : with_else(True)).repeat()
[0.3305950164794922, 0.32186388969421387, 0.3209099769592285]
...or in other words: having the else
clause is faster regardless of the if
condition being triggered or not.
I assume it has to do with different bytecode generated by the two, but is anybody able to confirm/explain in detail?
EDIT: Seems not everybody is able to reproduce my timings, so I thought it might be useful to give some info on my system. I'm running Ubuntu 11.10 64 bit with the default python installed. python
generates the following version information:
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Here are the results of the disassembly in Python 2.7:
>>> dis.dis(without_else)
2 0 LOAD_FAST 0 (param)
3 POP_JUMP_IF_FALSE 10
3 6 LOAD_CONST 1 (1)
9 RETURN_VALUE
4 >> 10 LOAD_CONST 2 (0)
13 RETURN_VALUE
>>> dis.dis(with_else)
2 0 LOAD_FAST 0 (param)
3 POP_JUMP_IF_FALSE 10
3 6 LOAD_CONST 1 (1)
9 RETURN_VALUE
5 >> 10 LOAD_CONST 2 (0)
13 RETURN_VALUE
14 LOAD_CONST 0 (None)
17 RETURN_VALUE
Source: (StackOverflow)
I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 install package. I've got the install package from http://www.python.org/. What directories/files/configuration file entries do I need to remove? Is there a list somewhere?
Source: (StackOverflow)
When I run a very simple code with pydot
import pydot # import pydot or you're not going to get anywhere my friend :D
graph = pydot.Dot(graph_type='graph')
for i in range(3):
edge = pydot.Edge("king", "lord%d" % i)
graph.add_edge(edge)
vassal_num = 0
for i in range(3):
for j in range(2):
edge = pydot.Edge("lord%d" % i, "vassal%d" % vassal_num)
graph.add_edge(edge)
vassal_num += 1
graph.write_png('example1_graph.png')
It prints me the error message:
Couldn't import dot_parser, loading of dot files will not be possible.
I'm using python 2.7.3
Source: (StackOverflow)
While optimising my code I realised the following:
>>> from timeit import Timer as T
>>> T(lambda : 1234567890 / 4.0).repeat()
[0.22256922721862793, 0.20560789108276367, 0.20530295372009277]
>>> from __future__ import division
>>> T(lambda : 1234567890 / 4).repeat()
[0.14969301223754883, 0.14155197143554688, 0.14141488075256348]
>>> T(lambda : 1234567890 * 0.25).repeat()
[0.13619112968444824, 0.1281130313873291, 0.12830305099487305]
and also:
>>> from math import sqrt
>>> T(lambda : sqrt(1234567890)).repeat()
[0.2597470283508301, 0.2498021125793457, 0.24994492530822754]
>>> T(lambda : 1234567890 ** 0.5).repeat()
[0.15409398078918457, 0.14059877395629883, 0.14049601554870605]
I assume it has to do with the way python is implemented in C, but I wonder if anybody would care to explain why is so?
Source: (StackOverflow)
This question already has an answer here:
Is there any other way to delete an item in a dictionary only if the given key exists, other than:
if key in mydict:
del mydict[key]
The scenario is that I'm given a collection of keys to be removed from a given dictionary, but I am not certain if all of them exist in the dictionary. Just in case I miss a more efficient solution.
Source: (StackOverflow)
I am trying to install PIL (the Python Imaging Library) using the command:
sudo pip install pil
but I get the following message:
Downloading/unpacking PIL
You are installing a potentially insecure and unverifiable file. Future versions of pip will default to disallowing insecure files.
Downloading PIL-1.1.7.tar.gz (506kB): 506kB downloaded
Running setup.py egg_info for package PIL
WARNING: '' not a valid package name; please use only.-separated package names in setup.py
Installing collected packages: PIL
Running setup.py install for PIL
WARNING: '' not a valid package name; please use only.-separated package names in setup.py
--- using frameworks at /System/Library/Frameworks
building '_imaging' extension
clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o
unable to execute clang: No such file or directory
error: command 'clang' failed with exit status 1
Complete output from command /usr/bin/python -c "import setuptools;__file__='/private/tmp/pip_build_root/PIL/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-AYrxVD-record/install-record.txt --single-version-externally-managed:
WARNING: '' not a valid package name; please use only.-separated package names in setup.py
running install
running build
.
.
.
.
copying PIL/XVThumbImagePlugin.py -> build/lib.macosx-10.8-intel-2.7
running build_ext
--- using frameworks at /System/Library/Frameworks
building '_imaging' extension
creating build/temp.macosx-10.8-intel-2.7
creating build/temp.macosx-10.8-intel-2.7/libImaging
clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o
unable to execute clang: No such file or directory
error: command 'clang' failed with exit status 1
----------------------------------------
Cleaning up…
Could you please help me to install PIL??
Source: (StackOverflow)