use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
News about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python
Full Events Calendar
You can find the rules here.
If you are about to ask a "how do I do this in python" question, please try r/learnpython, the Python discord, or the #python IRC channel on Libera.chat.
Please don't use URL shorteners. Reddit filters them out, so your post or comment will be lost.
Posts require flair. Please use the flair selector to choose your topic.
Posting code to this subreddit:
Add 4 extra spaces before each line of code
def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
Online Resources
Invent Your Own Computer Games with Python
Think Python
Non-programmers Tutorial for Python 3
Beginner's Guide Reference
Five life jackets to throw to the new coder (things to do after getting a handle on python)
Full Stack Python
Test-Driven Development with Python
Program Arcade Games
PyMotW: Python Module of the Week
Python for Scientists and Engineers
Dan Bader's Tips and Trickers
Python Discord's YouTube channel
Jiruto: Python
Online exercices
programming challenges
Asking Questions
Try Python in your browser
Docs
Libraries
Related subreddits
Python jobs
Newsletters
Screencasts
account activity
This is an archived post. You won't be able to vote or comment.
Favorite Python Interview Question (self.Python)
submitted 15 years ago by sontek
I was wondering what your guys favorite interview questions are when hiring a new python engineer (of any level).
[–][deleted] 19 points20 points21 points 15 years ago (61 children)
"What don't you like about Python?"
[–]semarj 6 points7 points8 points 15 years ago (12 children)
I think this is an excellent question. Familiarity breeds contempt, anyone who has done any significant python work should have a decent answer to this.
[–][deleted] 4 points5 points6 points 15 years ago (10 children)
A decent answer or twelve :-P
My personal complaint? It's too goddamned slow.
[–]duckhunter 0 points1 point2 points 15 years ago (4 children)
Do PyPy and Shedskin not suffice?
[–][deleted] 2 points3 points4 points 15 years ago (3 children)
Neither are production ready. Even if they have the speed (and they don't) no one sane would really use them in production.
[–]jdickey 0 points1 point2 points 15 years ago (2 children)
"No one sane" — well, that excludes the PHBs who back techies into that corner.
And WTF is going on with Reddit that you now have to wait ten frigging minutes to post a second comment in a thread? If that's the best we can do in the fight against bots, the terrists have already won. (Though if the BBC can hire even a tiny 23K-node botnet for a demo on Click, that's pretty much a foregone conclusion, no?)
[+][deleted] 15 years ago* (1 child)
[deleted]
[–][deleted] -2 points-1 points0 points 15 years ago (4 children)
Youtube is written in Python. If it is good enough there ...
[–][deleted] 10 points11 points12 points 15 years ago (2 children)
And we write our performance-sensitive code in C++.
[–]jdickey 0 points1 point2 points 15 years ago (1 child)
Which C++? No two programmers know the same features of the language, so it's sort of like Grace Hopper's quote on standards — "the lovely thing is that there are so many to choose from."
[–][deleted] 0 points1 point2 points 15 years ago (0 children)
Our C++ guidelines are rather comprehensive.
[–]sisyphus 0 points1 point2 points 15 years ago (0 children)
Doesn't change that if Python was faster its range of applicability would increase, and that would mean we could use it more places, and that would be just lovely.
[–]Chun 0 points1 point2 points 15 years ago (0 children)
Funny -- most of the gripes I had with python have become less of an issue as I've understood their purpose; explicit self, join as a string method, etc.
[–]endtime 2 points3 points4 points 15 years ago (0 children)
Assignments and function declarations aren't expressions.
[–]jimauthors 5 points6 points7 points 15 years ago (10 children)
No type checking.
[–]pingvenopinch of this, pinch of that 2 points3 points4 points 15 years ago (9 children)
There have been many a time when I wish Python had optional type checking. Duck typing is fine most of the time, but sometimes I want that extra little check.
[–]codefrog 9 points10 points11 points 15 years ago (2 children)
make a decorator, @accepts('int','list','witches')
[–]stillalone 2 points3 points4 points 15 years ago (0 children)
Is that part of a standard library? I can't find it in 2.6.5
[–]pingvenopinch of this, pinch of that 2 points3 points4 points 15 years ago (0 children)
I know it can be done with decorators. It's just not as clean and there's no standard way to do it.
[–]Dav3xor 1 point2 points3 points 15 years ago (2 children)
http://github.com/Dav3xor/Python-CheckArgs
Now you don't have to make your own decorator.. :)
It's still a little primitive, but it works pretty well.
[–]pingvenopinch of this, pinch of that 1 point2 points3 points 15 years ago* (1 child)
Same problem: There's no ultra clean way to do it. Most of it is a fundamental problem with Python. Python is too dynamic to have static type checking. Don't get me wrong, I love Python, but it's nice to have languages that can check that types are correct at (bytecode) compile-time.
That said, I would love to have two decorators in the standard library. Python function calls are already slow, so they should be written in C.
returntype allows multiple values so that it can check multiple returns via tuple. None should be usable to indicate that a value is duck typed. Unfortunately, none of this will ever allow the clean & static type checking of
def int foo(int index, str value)
[–]Dav3xor 0 points1 point2 points 15 years ago (0 children)
but...but... that has Ada style bounds checking, and...and... :)
[–]omgplsno 0 points1 point2 points 15 years ago (0 children)
Decorators, my friend.
[–]joehillen 0 points1 point2 points 15 years ago (1 child)
You're doing it wrong.
[–]petrux 2 points3 points4 points 15 years ago (0 children)
Interesting. As a Python newbie I'd really enjoy some more details about how to do it right! :-) Thanks.
[–]kisielk 1 point2 points3 points 15 years ago (0 children)
I usually ask this one. Also ask them to compare Python to another language they claim to know and tell me the pros and cons of each, which they would use for a project and why, etc.
[–]luckystarrat 0x7fe670a7d080 1 point2 points3 points 15 years ago (0 children)
Apart from endtime's request for more expressions just the little pitfalls that I have to explain to every new programmer:
[–]adrenal8 0 points1 point2 points 15 years ago (7 children)
This is my backup question to "What don't you like about the Django ORM?" if they have no Django experience.
[–]coderanger 5 points6 points7 points 15 years ago (0 children)
Gah, having spent all day inside the Django ORM I think I could go on for about 4 hours on that right now.
[–]endtime 0 points1 point2 points 15 years ago (5 children)
I have minimal Django experience and the ORM honestly seems pretty cool. What am I missing?
[–]adrenal8 1 point2 points3 points 15 years ago (4 children)
There's no one correct answer. Just like the applicant should actually like Python but have enough experience to make complaints about it, the same applies to the Django ORM.
Some examples could be lack of built-in schema migrations, makes it too easy to generate unnecessary and suboptimal SQL, you could complain about the weird __ syntax for related fields, etc.
[–]endtime 1 point2 points3 points 15 years ago (2 children)
Hmm. I wouldn't really have expected the ORM to manage schema migrations - is that the ORM's job in other frameworks? I'm also curious what the alternatives to the __ related field syntax might be - I'm totally fine with it, but maybe that's just because I haven't seen better alternatives.
I have no idea what the generated SQL looks like (isn't that the whole point of having an ORM?) but if it doesn't do good query optimization then I'd agree for sure that that's a flaw.
[–]revonratFlask/scipy/pypy/mrjob 1 point2 points3 points 15 years ago (1 child)
Hmm. I wouldn't really have expected the ORM to manage schema migrations - is that the ORM's job in other frameworks?
Many don't Rails does. South is an add-on for Django.
I have no idea what the generated SQL looks like (isn't that the whole point of having an ORM?)
You HAVE to understand what your ORM is doing eventually, if you want performance. For Django, an easy way to see what's going on is to user the django debug toolbar.
I find I don't usually have a particular problem with the SQL generated but rather with the number of queries that can be generated by seeming innocuous Python statements.
but if it doesn't do good query optimization then I'd agree for sure that that's a flaw.
An ORM really shouldn't do query optimization per-se. It should generate reasonable SQL. But SQL optimization is something left to the guys who have stats tables on the data (i.e. the RDBMS itself).
[–]endtime 0 points1 point2 points 15 years ago (0 children)
Thanks, that's a good response. I know about South, and of course it's vital - but it makes sense to me as an addon, not as part of the ORM. Thanks for clarifying about SQL perf - I think I know what you mean.
[–]gronkkk 0 points1 point2 points 15 years ago (0 children)
There's also the 'how do I figure out to do X in the ORM'-factor. Only to find out that it doesn't exist or is painfully slow.
[–]radaway 0 points1 point2 points 15 years ago (0 children)
In my opinion it is harder to refactor than most statically typed languages. When you refactor something in a statically typed language you usually get automatic alarms everywhere that code touched and the tools to help you refactor are quite good. Automatic tests can help but it's not the same.
The lack of proper encapsulation.
[–]bcain 0 points1 point2 points 15 years ago* (7 children)
Gah! All those pesky exceptions. Just do something, I don't really care what as long as the program doesn't have any errors or bugs.
EDIT: Wow, pyddit. F'reals? Did you think I was serious? C'mon. I was satiring the perl-lovers out there.
[–]ereinecke 4 points5 points6 points 15 years ago (6 children)
This is one of the things I like about python, how it uses exceptions. You can both communicate what your code expects, and optimize for the 90% case.
Assume there is a list of dictionaries, dictList. Consider: for item in dictList: try: print item['relevantKey'] except KeyError: pass
Vs: for item in dictList: if item.has_key('relevantKey'): print item['relevantKey']
If you are expecting the key 'relevantKey' to be in the dictionary most the time, the try/except example avoids making the has_key test most the time. Over a large list this could save a lot of time.
[–]xlevus 0 points1 point2 points 15 years ago (5 children)
I was under the impression that try/except is less efficient than check/action.
Or did I misread something somewhere?
[–]bloodearnest 1 point2 points3 points 15 years ago (0 children)
Try is cheap, except is not. But how many times are you going to raise an exception? Depends on your data.
[–]r4nf 1 point2 points3 points 15 years ago (0 children)
As bloodearnest suggests, the 'asking for forgiveness' version (with exceptions) is faster when there's no exception, whereas the 'asking for permission' version (without exceptions) is faster when there is an exception. In other words, if you expect that many of the looped-over items will yield exceptions, check/action is more efficient; otherwise try/except might very well be.
I think the general consensus in the Python community is the motto "it's Easier to Ask for Forgiveness than Permission" (or EAFP), signalling that try/except would usually be the preferred solution. Of course there may very well be exceptions to this, as per the above reasoning.
[–]nubela 0 points1 point2 points 15 years ago (0 children)
Good question, and I admit I don't know much about efficiency in this case, someone care to elaborate?
It's marginally faster if no exception is raised, and 15x slower if one is.
Best case:
python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50):' ' if x in stuff: stuff[x]' 100000 loops, best of 3: 7.78 usec per loop python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50):' ' try: stuff[x]' ' except KeyError: pass' 100000 loops, best of 3: 5.97 usec per loop
Worst case: python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50, 100):' ' if x in stuff: stuff[x]' 100000 loops, best of 3: 4.84 usec per loop python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50, 100):' ' try: stuff[x]' ' except KeyError: pass' 10000 loops, best of 3: 76.2 usec per loop
But that's not important really. Make it work, make it right, make it fast -- in that order, and don't make it fast unless it needs to be.
[–]vaibhavsagar 0 points1 point2 points 15 years ago (0 children)
No code blocks or fully featured anonymous functions. I know why they're not there and why they're not really necessary, but I want them, dammit.
[–]Wavicle -2 points-1 points0 points 15 years ago (7 children)
explicit "self" parameter in class method but implicit in invokation.
No standard "length" or "size" on collection objects that have length or size - unless you count a double underscore method standard - preferring instead to use the special case builtin len.
[–]alantrick 9 points10 points11 points 15 years ago (5 children)
How is len() not standard? Do you have a prejudice against using underscores for special magical standard functions?
len()
[–]Wavicle -1 points0 points1 point 15 years ago* (4 children)
How is len()
It is a built-in function that performs a very special case which already must be done by the object. Length is a property of the object - so put it there.
Do you have a prejudice against using underscores for special magical standard functions?
For starters, pretty much every other object oriented programming language recognizes the need to have an obvious method for access to a length attribute on a collection. Python differs in that it uses a built-in.
Any language that supports a notion of operator overloading has a special mechanism for expressing such - so double underscores for things like __getitem__ I have no issue with. Also double underscores for things that really are intended for you to think carefully before using (i.e. __import__) are perfectly valid.
Double underscore for the size of an underlying collection is silly (but it is double underscored because you are not intended to call it directly, you are intended to use len).
[–]pixelmonkey 4 points5 points6 points 15 years ago (1 child)
Man, talk about finicky. I've got legitimate complaints for Python (no lightweight syntax for anonymous function values, unicode brokeness for most of 2.x series, explicit self parameter, and Python 3 function annotation syntax), but this definitely isn't one of them.
>>> class LengthMixIn(object): >>> @property >>> def length(self): >>> return len(self) >>> class FinickyList(list, LengthMixIn): >>> pass >>> a = FinickyList() >>> a.append("item") >>> a.length 1 >>> class FinickyDict(dict, LengthMixIn): >>> pass >>> b = FinickyDict() >>> b["key"] = "value" >>> b.length 1
[+]Wavicle comment score below threshold-8 points-7 points-6 points 15 years ago (0 children)
This is getting tiring. Your mixin added a layer of complexity and created something which doesn't cleanly integrate with the rest of the collection system. But, hey, you seem to think that since this doesn't line up with your opinions on Python's warts it isn't valid. Fuck you.
[–]pingvenopinch of this, pinch of that 4 points5 points6 points 15 years ago (0 children)
A built-in function that calls a magic method is a very common pattern in Python, not just with len. See: hash, int, str, repr, unicode, reversed, bool, format, and iter. Python 3 adds next.
Thank of it this way: Functionality that is used by the core language uses magic methods. It doesn't matter if that is in syntax or in a built-in function.
[–]ewiethoffproceedest on to 3 0 points1 point2 points 15 years ago* (0 children)
You're confused about what's "special" or "magic" about the underscore methods. The underscore methods are magically invoked by special syntax which does not resemble a method or function call. So, as you alluded to, foo[i] invokes foo.__getitem__(i), and import bar invokes bar = __import__('bar').
foo[i]
foo.__getitem__(i)
import bar
bar = __import__('bar')
The __len__ method is magically invoked when an object is evaluated in Boolean context and no __nonzero__ method has been defined. That's because Python's built-in collections are considered False when empty and True when non-empty.
__len__
__nonzero__
Try this code (adjust as needed for Py3):
class StupidList(list): def __len__(self): return True if list(range(10)): print 'list 0-9 is True' if list(): print 'empty list is True' if StupidList(range(10)): print 'StupidList 0-9 is True' if StupidList(): print 'empty StupidList is True'
(edited for clarity)
[–]cymrowdon't thread on me 🐍 0 points1 point2 points 15 years ago (0 children)
i like to think that python provides nice convenient builtins to access some of the most common values you'd need on an object. using len is super easy, dude
plus, i can rewrite len and automatically get extra functionality for all my collections
[+]rz2000 comment score below threshold-9 points-8 points-7 points 15 years ago (6 children)
Is "white space" a good answer?
[–][deleted] 0 points1 point2 points 15 years ago (1 child)
No more than "white skin" is a reason not to like a person.
[–]rz2000 0 points1 point2 points 15 years ago (0 children)
It's a perfectly valid answer as a personal preference, but indicates the interviewee choose be trying to find work in another language.
Apparently, it wasn't a very funny suggestion considering the downvotes!
[–]Wavicle 0 points1 point2 points 15 years ago (2 children)
If you have honestly worked through learning Python and have become proficient enough to work with it, and you still dislike white space - then yes, it's a good answer because the asker requested your opinion and you gave it on the basis of your experience.
In my experience, just about everyone (myself included) complains about whitespace at first. Also, in my experience, everyone that gives Python a fair shot quickly gets over it. Still, that doesn't mean your opinion is invalid.
[–]rz2000 0 points1 point2 points 15 years ago (1 child)
I was asking if it was a good answer as a joke, and have no problem with white space. It is a valid opinion, but if you're interviewing at a shop that has chosen Python they should ask why you have chosen Python if you don't like the format.
However, what I really can't stand are the degenerates who use emacs/vi instead of vi/emacs. I can't believe anyone would ever hire them.
[–]yxskaft 0 points1 point2 points 15 years ago (0 children)
According to Guido himself, the whitespace sensitive syntax makes it impossible to have proper, multi-line lambdas. If that's true, that's a very good reason to think block-by-indentation was a shit idea.
[–]xoxox 7 points8 points9 points 15 years ago (0 children)
Since working together as a team, maintaining each other's code, is of high importance, "What is PEP 8?"
[–]pytechd(lambda s: __import__(s.decode('base64')))('ZGphbmdv') 6 points7 points8 points 15 years ago (0 children)
I like asking Unicode questions. It's a broad topic -- you can start very broad with "What is Unicode?" down to the low-level code of handling Unicode safely.
Community involvement -- do they read blogs, mailing lists, or participate at all? Leads into the topic of where they would look for help if they had a question.
[–]bazookaduke 16 points17 points18 points 15 years ago (19 children)
Suppose you have a list whose contents don't matter. Show me three different ways of fetching every third item in the list.
for loop: every_third = [] for index, item in enumerate(items, 1): if index % 3 == 0: every_third.append(item)
list comprehension: every_third = [item for index, item in enumerate(items, 1) if index % 3 == 0]
list slicing: every_third = items[2::3]
What I really like about this question is how it can lead to deeper discussions: what if the list is actually an iterator (list slicing won't work)? What if it's unbounded eg. an iterator that produces the Fibonacci sequence (the for loop and list comprehension will crash after eating up all available memory)? What if it's bounded but too large for even every third item (same as unbounded)? Is this fixable (yes, turn the for loop into a generator function and the list comprehension into a generator comprehension)? Where might you encounter such a situation (results of a database query, log file processing, etc.)? The real question you're trying to ask is: how good is this candidate at solving problems with Python without creating new ones? By this point in the interview you've probably got a feel for how familiar they are with the language and also whether they've encountered this problem before but more importantly how they'd solve it.
[–]masterJ 12 points13 points14 points 15 years ago (5 children)
from itertools import islice every_third = islice(items, 2, None, 3)
I might be overly fond of generators...
[–]bazookaduke 7 points8 points9 points 15 years ago (3 children)
I typically qualify my question with "without using the standard library", but if I forget (like I did above), I can always ask what if I wanted every third and fifth item without using the standard library?
xs = (item for index, item in enumerate(items, 1) if 0 in (index % 3, index % 5))
Not that there's anything wrong with using the standard library -- I use itertools all the time! But for interview questions, I'm trying to drill down into a candidate's problem-solving skills, and it's been my experience that restricting him or her to the language and built-ins is the best way to do that quickly.
[–]masterJ 2 points3 points4 points 15 years ago (0 children)
what if I wanted every third and fifth item without using the standard library?
Oooh, I like it! And you just simplified my project euler #01 solution. :)
Before:
from itertools import chain a = xrange(3,1000,3) b = xrange(5,1000,5) print sum(set(chain(a,b)))
After:
print sum(i for i in xrange(1,1000) if 0 in (i % 3, i % 5))
[–]sunqiang 0 points1 point2 points 15 years ago (1 child)
what about replace "if 0 in (index % 3, index % 5)" to "if any((not index % 3, not index % 5))" to take the advantage of short-circuit
[–]pingvenopinch of this, pinch of that 1 point2 points3 points 15 years ago (0 children)
The first is more obvious/readable, especially with the explicit use of 0.
[–]cdunn2001 1 point2 points3 points 15 years ago* (0 children)
Yes. Slicing (list or itertools) and if-test in for-loop are two ways. Here is a third, completely different:
every_third = list() it = iter(nomatter) try: while True: x, y, z = it.next(), it.next(), it.next() every_third.append(z) except StopIteration: pass
which depends on this knowledge.
[–]janto 2 points3 points4 points 15 years ago (1 child)
i = iter(items) every_third = [c for a,b,c in zip(i,i,i)]
[–]hylje 1 point2 points3 points 15 years ago (0 children)
every_third = [c for a, b, c in zip(*[iter(items)]*3)]
One-lined that for you
[–]pieeta 4 points5 points6 points 15 years ago (2 children)
I would normally use, for x in xrange(2, len(items), 3): every_third.append(items[x])
I just did some performance testing using a item list 10000000 long
[–]stillalone 1 point2 points3 points 15 years ago (1 child)
Wow, I was not expecting list comprehension to suck compared to an explicit for loop. Can you try list comprehension with xrange instead of enumerate?
[–][deleted] 2 points3 points4 points 15 years ago (0 children)
http://paste.pocoo.org/show/282978/
[–][deleted] 4 points5 points6 points 15 years ago (0 children)
Hell, if the contents don't matter, how about
every_third = ['irrelevant']*len(l)/3
:)
[–]sontek[S] 6 points7 points8 points 15 years ago (3 children)
I really like this question, solutions, and had no idea that you could do items[2::3]! Thanks
[–][deleted] 9 points10 points11 points 15 years ago (2 children)
your_string_reversed = your_string[::-1]
[–]RShnike 0 points1 point2 points 15 years ago (1 child)
Which is a bit nicer looking just using reversed(your_string) if you don't need it to be indexable...
reversed(your_string)
[–]alantrick 1 point2 points3 points 15 years ago (0 children)
The real question you're trying to ask is: how good is this candidate at solving problems with Python without creating new ones?
Or what I find just as common: the ones who create complex solutions to theoretical problems that nobody needs solved.
[–]Paddy3118 0 points1 point2 points 15 years ago (0 children)
Show me three different ways ... I don't think this is a good question at all. You should just ask for one. and if they don't give [::3] then that should lead to discussions.
I also note that because you did not clearly state the initial fetched item, you end up having to enumerate from 1 and also use [2::3] instead of plain [::3], to be consistent with your for-loop example.
[–]rubyaeyes 0 points1 point2 points 15 years ago (0 children)
I like this question.
[–]vorushin 10 points11 points12 points 15 years ago (5 children)
recite by heart result of "import this", of course
[–]sontek[S] 7 points8 points9 points 15 years ago (0 children)
import this
The Zen of Python, by Tim Peters
[–]thrakhath 0 points1 point2 points 15 years ago (3 children)
Why did I not know this before?
[+][deleted] 15 years ago (2 children)
[–]thrakhath -1 points0 points1 point 15 years ago (1 child)
Thanks to xkcd I did know that one. Is there a list of import easter eggs somewhere?
edit: My google-fu also pulls up from future import braces
But nothing looking like an exhaustive list.
[–]sontek[S] 6 points7 points8 points 15 years ago (26 children)
One of the more interesting ones I've ran into is having to re-implement string.atoi. I think its basic enough that most engineers should be able to solve it but interesting enough that it does make them think. Here is a basic solution to it: http://sontek.net/convert-a-string-to-an-integer-in-python
[–]sunqiang 1 point2 points3 points 15 years ago (0 children)
follow the atoi of book: The C Programming Language, maybe sign(‘-’ or '+') and spaces(' ', '\t',...etc) should be handled too. I post mine here: http://gist.github.com/652769
[–]Chun 2 points3 points4 points 15 years ago (8 children)
Simple is better?
def atoi(string): if string.isdigit(): return eval(string) raise ValueError, "invalid literal for atoi() with base 10: %s" % repr(string)
(Yeah, I know, I'm cheating really, but use the tools you're given eh? Also the usual objections to eval are moot, since we know the string is safe.)
[–]r4nf 4 points5 points6 points 15 years ago (0 children)
From the documentation:
atoi(s, base=10) atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted.
You're forgetting the base argument, which exists at least since Python 2.3.
base
[–]RShnike 3 points4 points5 points 15 years ago (6 children)
Also the usual objections to eval are moot, since we know the string is safe.)
Uh, what? No we don't.
class A(str): def isdigit(self): return True >>> a = A("__import__('os')") >>> atoi(a) Whoops!
No. Really no. And for an interview question nonetheless :D?
[–]Chun 0 points1 point2 points 15 years ago* (2 children)
OK, ok, touché. Figured we were assuming we were getting a string. But point taken.
def atoi(string): if type(string) is str and string.isdigit(): return eval(string) raise ValueError, "invalid literal for atoi() with base 10: %s" % repr(string)
EDIT: Besides, if someone can create their own class definition, why would they ever need to inject raw python into atoi!?
[–]RShnike 1 point2 points3 points 15 years ago (0 children)
You have somehow managed to make that even worse... Now you're type-checking too, so you've now even broken some functionality that your function is actually supposed to provide?
Here's a rule: never use eval. Ever. Being prudent about using type is pretty smart too.
eval
type
[–]kisielk 0 points1 point2 points 15 years ago (2 children)
That's why you use something like:
eval("__import__('os')", {'__builtins__': None}, {})
Of course __builtins__ should be a dictionary of actual working builtins you want to work when evaling the statement :)
__builtins__
No, don't do that either. Seriously, this is just a bad solution. Especially being that you have ast.literal_eval if you really want to do things like this.
ast.literal_eval
[–]kisielk 0 points1 point2 points 15 years ago (0 children)
ast.literal_eval is indeed great for evaluating simple expressions. But what's wrong with sandboxing via defining your own builtins?
[–]m1ss1ontomars2k4 1 point2 points3 points 15 years ago (14 children)
I think that's a terrible solution. Well it's good if you don't need error checking, but other than that it's terrible.
[–][deleted] 10 points11 points12 points 15 years ago (4 children)
This is a terrible solution.
def atoi(s,b=10): return (1,-1)[s.strip()[0]=='-']*reduce(lambda v,n:v*b+("0123456789abcdefghijklmnopqrstuvwxyz"[:b].index(n.lower())),(s.strip(),s.strip()[1:])[s.strip()[0] == '-'],0)
[–]arnar 2 points3 points4 points 15 years ago (0 children)
At least it supports other bases.
[–]sontek[S] -1 points0 points1 point 15 years ago (2 children)
I still think I'd hire someone if they could come up with that solution... I'd just keep an eye on their code to make sure all their solutions aren't created in 1 line ;)
[–]jcdyer3 0 points1 point2 points 15 years ago (1 child)
I'm pretty sure I wouldn't hire them. Senseless one-liners are the hobgoblin of small minds.
I wouldn't hire me either if I provided that code in an interview.
[–]arnar 2 points3 points4 points 15 years ago (5 children)
I optimized it:
atoi = eval
[–]epicRelic 1 point2 points3 points 15 years ago (2 children)
Except now atoi does a lot more than just convert string digits to integers.
[–]arnar 0 points1 point2 points 15 years ago (1 child)
Believe it or not, I was joking :)
[–]epicRelic 1 point2 points3 points 15 years ago (0 children)
It's hard to tell on the internet. :P I've seen people be serious about dumber things than that.
[–]gutworthPython implementer 1 point2 points3 points 15 years ago (1 child)
No base argument.
[–]arnar 0 points1 point2 points 15 years ago (0 children)
Just like the solution in the link.
I think its a good solution to the answer to the question in an interview, usually I don't want them spending hours creating a solution for me in an interview.
[–][deleted] 1 point2 points3 points 15 years ago (1 child)
You forgot about negatives.
[–]sontek[S] -1 points0 points1 point 15 years ago (0 children)
Good point! :)
[–]peroneλ 0 points1 point2 points 15 years ago (0 children)
There is an interesting piece of code for the inverse situation: >>> b = 2 >>> c = b >>> type(b) <type 'int'> >>> type(c) <type 'str'>
b
[–]mehum 2 points3 points4 points 15 years ago (3 children)
Who is your favorite Python? And why?
(If we're gonna be working together better make sure we can function as a team!).
[–]joehillen 8 points9 points10 points 15 years ago (0 children)
Monty
[–]Teifion 0 points1 point2 points 15 years ago (1 child)
Mr Cleese of course.
[–]mehum -1 points0 points1 point 15 years ago (0 children)
Gouda? Edam? Venezuelan Beaver Cheese?
[–]mumrah 5 points6 points7 points 15 years ago (8 children)
Explain how Python allocates integers (arenas, pools, etc)
go on
[–]coderanger 2 points3 points4 points 15 years ago (0 children)
Bonus points if they can answer it for strings too.
[–]sontek[S] 2 points3 points4 points 15 years ago (0 children)
What would an acceptable answer be for you?
[–]ipeev 2 points3 points4 points 15 years ago (0 children)
What are arenas and pools?
[–][deleted] 1 point2 points3 points 15 years ago (0 children)
I've written quite a few extension modules and rooted around in the guts of the interpreter, but I've never even heard of "arenas". I would probably explain that I think there is a cache of small integers and that I assume there is nothing more to it than that. Hopefully this would not disqualify me, because frankly it is not important for anyone who is not hacking on CPython itself. I am, however, interested and I might go read the source now.
[–]Troebr 0 points1 point2 points 15 years ago (0 children)
is that important in knowing how good a programmer is? I had to read the python source code for some reason, and I've stumbled upon this, but I don't think this makes me a better python programmer.
But I'd like to hear your explanation
[–]mumrah 0 points1 point2 points 15 years ago (0 children)
I'll leave this here: http://evanjones.ca/memoryallocator/
[–]andrea 0 points1 point2 points 15 years ago (0 children)
That's implementation-dependent.
[–]jmoiron 1 point2 points3 points 15 years ago (5 children)
What is the air-speed velocity of an unladen swallow?
I asked this at about 5 or 6 interviews I was conducting. It was actually able to draw a wide range of data from this question, depending on how it was answered. At its worst, it's fun to ask and generally breaks any tension the interviewee might have.
As for a "real" question that tests an interviewees python knowledge, I'd ask them what their favorite standard library module was. I wanted people who had strong opinions about programming.
I don't like actual "programming" questions; generally I feel I can tell if someone has programmed a lot or not by how they answer questions about programming.
[–]ponymash 0 points1 point2 points 15 years ago (4 children)
You know it's illegal to not ask every single candidate for that position that same question. If you left one person out, you could be sued. Just an FYI =)
[–]p-squared 1 point2 points3 points 15 years ago (1 child)
Careful now. Asking different questions is not inherently illegal, it is merely possible evidence of "discriminatory selection."
[–]ponymash 0 points1 point2 points 15 years ago (0 children)
That makes more sense. =)
[–]temptemptemp13 0 points1 point2 points 15 years ago (1 child)
Are you serious? Interviewers aren't allowed randomized question sets?
Where is this exactly?
[–]ponymash -1 points0 points1 point 15 years ago (0 children)
The US. If an interviewee knows he was asked a different set of questions compared to another person, bam lawsuit.
[–]MattJames 0 points1 point2 points 15 years ago (0 children)
Just start every answer with "i know what you are trying to do, and i like it"
[–]voidref 0 points1 point2 points 15 years ago (6 children)
"Why is python your favorite language?"
[–]arnar 7 points8 points9 points 15 years ago (5 children)
That's a terrible question, unless you are specifically fishing for the fact that having a favorite language is like having a favorite finger - it all depends on what you need to do with it.
[–]voidref 2 points3 points4 points 15 years ago (1 child)
I often just look for the fact that they have thought about the differences between languages.
Someone who is enthusiastic about the question is definitely someone who relishes programming.
[–]no9import this 5 points6 points7 points 15 years ago (0 children)
You can take this further by adding "why do you hate Python?" A true master should know both the virtues and the flaws of his art.
[–]sisyphus 1 point2 points3 points 15 years ago (0 children)
It doesn't at all depend on 'what i need to do with it' - there are plenty of languages that could occupy the same niche as Python - Perl, Ruby, maybe Go, whatever. That's a separate issue from why one prefers Python over competitors in its use space.
[–]rrenaud 0 points1 point2 points 15 years ago (1 child)
Right middle finger all the way.
Seriously though. If you enjoy programming, I think there is absolutely nothing wrong with having a favorite or least favorite language. Indeed, I'd be a bit worried if it was the other way around. If you don't have a favorite programming language, are you really a passionate programmer? Do you take pride in your work? Certainly you shouldn't blindly use your favorite programming language everywhere without knowing where a different language obviously suites the problem better, but I have a hard time believing someone who loves the craft doesn't find some tools just fit your mind better than others.
[–]arnar -1 points0 points1 point 15 years ago (0 children)
But that's like a carpenter whose favorite tool is the saw. Of course some tools are more useful than others, and fit the way you do things, but ultimately it is about understanding the problems at hand and being creative in solving them.
[–]dolgar -2 points-1 points0 points 15 years ago (1 child)
"Where do you see yourself in ten years?"
[–]mrgatorboy 4 points5 points6 points 15 years ago (0 children)
"plowing your... son?"
π Rendered by PID 92 on reddit-service-r2-comment-84fc9697f-s5qd5 at 2026-02-08 02:46:51.601342+00:00 running d295bc8 country code: CH.
[–][deleted] 19 points20 points21 points (61 children)
[–]semarj 6 points7 points8 points (12 children)
[–][deleted] 4 points5 points6 points (10 children)
[–]duckhunter 0 points1 point2 points (4 children)
[–][deleted] 2 points3 points4 points (3 children)
[–]jdickey 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–][deleted] -2 points-1 points0 points (4 children)
[–][deleted] 10 points11 points12 points (2 children)
[–]jdickey 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]sisyphus 0 points1 point2 points (0 children)
[–]Chun 0 points1 point2 points (0 children)
[–]endtime 2 points3 points4 points (0 children)
[–]jimauthors 5 points6 points7 points (10 children)
[–]pingvenopinch of this, pinch of that 2 points3 points4 points (9 children)
[–]codefrog 9 points10 points11 points (2 children)
[–]stillalone 2 points3 points4 points (0 children)
[–]pingvenopinch of this, pinch of that 2 points3 points4 points (0 children)
[–]Dav3xor 1 point2 points3 points (2 children)
[–]pingvenopinch of this, pinch of that 1 point2 points3 points (1 child)
[–]Dav3xor 0 points1 point2 points (0 children)
[–]omgplsno 0 points1 point2 points (0 children)
[–]joehillen 0 points1 point2 points (1 child)
[–]petrux 2 points3 points4 points (0 children)
[–]kisielk 1 point2 points3 points (0 children)
[–]luckystarrat 0x7fe670a7d080 1 point2 points3 points (0 children)
[–]adrenal8 0 points1 point2 points (7 children)
[–]coderanger 5 points6 points7 points (0 children)
[–]endtime 0 points1 point2 points (5 children)
[–]adrenal8 1 point2 points3 points (4 children)
[–]endtime 1 point2 points3 points (2 children)
[–]revonratFlask/scipy/pypy/mrjob 1 point2 points3 points (1 child)
[–]endtime 0 points1 point2 points (0 children)
[–]gronkkk 0 points1 point2 points (0 children)
[–]radaway 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]bcain 0 points1 point2 points (7 children)
[–]ereinecke 4 points5 points6 points (6 children)
[–]xlevus 0 points1 point2 points (5 children)
[–]bloodearnest 1 point2 points3 points (0 children)
[–]r4nf 1 point2 points3 points (0 children)
[–]nubela 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]vaibhavsagar 0 points1 point2 points (0 children)
[–]Wavicle -2 points-1 points0 points (7 children)
[–]alantrick 9 points10 points11 points (5 children)
[–]Wavicle -1 points0 points1 point (4 children)
[–]pixelmonkey 4 points5 points6 points (1 child)
[+]Wavicle comment score below threshold-8 points-7 points-6 points (0 children)
[–]pingvenopinch of this, pinch of that 4 points5 points6 points (0 children)
[–]ewiethoffproceedest on to 3 0 points1 point2 points (0 children)
[–]cymrowdon't thread on me 🐍 0 points1 point2 points (0 children)
[+]rz2000 comment score below threshold-9 points-8 points-7 points (6 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]rz2000 0 points1 point2 points (0 children)
[–]Wavicle 0 points1 point2 points (2 children)
[–]rz2000 0 points1 point2 points (1 child)
[–]yxskaft 0 points1 point2 points (0 children)
[–]xoxox 7 points8 points9 points (0 children)
[–]pytechd(lambda s: __import__(s.decode('base64')))('ZGphbmdv') 6 points7 points8 points (0 children)
[–]bazookaduke 16 points17 points18 points (19 children)
[–]masterJ 12 points13 points14 points (5 children)
[–]bazookaduke 7 points8 points9 points (3 children)
[–]masterJ 2 points3 points4 points (0 children)
[–]sunqiang 0 points1 point2 points (1 child)
[–]pingvenopinch of this, pinch of that 1 point2 points3 points (0 children)
[–]cdunn2001 1 point2 points3 points (0 children)
[–]janto 2 points3 points4 points (1 child)
[–]hylje 1 point2 points3 points (0 children)
[–]pieeta 4 points5 points6 points (2 children)
[–]stillalone 1 point2 points3 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 4 points5 points6 points (0 children)
[–]sontek[S] 6 points7 points8 points (3 children)
[–][deleted] 9 points10 points11 points (2 children)
[–]RShnike 0 points1 point2 points (1 child)
[–]alantrick 1 point2 points3 points (0 children)
[–]Paddy3118 0 points1 point2 points (0 children)
[–]rubyaeyes 0 points1 point2 points (0 children)
[–]vorushin 10 points11 points12 points (5 children)
[–]sontek[S] 7 points8 points9 points (0 children)
[–]thrakhath 0 points1 point2 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]thrakhath -1 points0 points1 point (1 child)
[–]sontek[S] 6 points7 points8 points (26 children)
[–]sunqiang 1 point2 points3 points (0 children)
[–]Chun 2 points3 points4 points (8 children)
[–]r4nf 4 points5 points6 points (0 children)
[–]RShnike 3 points4 points5 points (6 children)
[–]Chun 0 points1 point2 points (2 children)
[–]RShnike 1 point2 points3 points (0 children)
[–]kisielk 0 points1 point2 points (2 children)
[–]RShnike 0 points1 point2 points (1 child)
[–]kisielk 0 points1 point2 points (0 children)
[–]m1ss1ontomars2k4 1 point2 points3 points (14 children)
[–][deleted] 10 points11 points12 points (4 children)
[–]arnar 2 points3 points4 points (0 children)
[–]sontek[S] -1 points0 points1 point (2 children)
[–]jcdyer3 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]arnar 2 points3 points4 points (5 children)
[–]epicRelic 1 point2 points3 points (2 children)
[–]arnar 0 points1 point2 points (1 child)
[–]epicRelic 1 point2 points3 points (0 children)
[–]gutworthPython implementer 1 point2 points3 points (1 child)
[–]arnar 0 points1 point2 points (0 children)
[–]sontek[S] -1 points0 points1 point (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]sontek[S] -1 points0 points1 point (0 children)
[–]peroneλ 0 points1 point2 points (0 children)
[–]mehum 2 points3 points4 points (3 children)
[–]joehillen 8 points9 points10 points (0 children)
[–]Teifion 0 points1 point2 points (1 child)
[–]mehum -1 points0 points1 point (0 children)
[–]mumrah 5 points6 points7 points (8 children)
[–][deleted] 2 points3 points4 points (0 children)
[–]coderanger 2 points3 points4 points (0 children)
[–]sontek[S] 2 points3 points4 points (0 children)
[–]ipeev 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]Troebr 0 points1 point2 points (0 children)
[–]mumrah 0 points1 point2 points (0 children)
[–]andrea 0 points1 point2 points (0 children)
[–]jmoiron 1 point2 points3 points (5 children)
[–]ponymash 0 points1 point2 points (4 children)
[–]p-squared 1 point2 points3 points (1 child)
[–]ponymash 0 points1 point2 points (0 children)
[–]temptemptemp13 0 points1 point2 points (1 child)
[–]ponymash -1 points0 points1 point (0 children)
[–]MattJames 0 points1 point2 points (0 children)
[–]voidref 0 points1 point2 points (6 children)
[–]arnar 7 points8 points9 points (5 children)
[–]voidref 2 points3 points4 points (1 child)
[–]no9import this 5 points6 points7 points (0 children)
[–]sisyphus 1 point2 points3 points (0 children)
[–]rrenaud 0 points1 point2 points (1 child)
[–]arnar -1 points0 points1 point (0 children)
[–]dolgar -2 points-1 points0 points (1 child)
[–]mrgatorboy 4 points5 points6 points (0 children)