Subtracting two lists in Python

Python 2.7 and 3.2 added the collections.Counter class, which is a dictionary subclass that maps elements to the number of occurrences of the element. This can be used as a multiset. You can do something like this: As well, if you want to check that every element in b is in a: But since you … Read more

module has no attribute

The problem is submodules are not automatically imported. You have to explicitly import the api module: If you really insist on api being available when importing myproject.mymodule you can put this in myproject/mymodule/__init__.py: Then this will work as expected:

TypeError: ‘bool’ object is not callable

You do cls.isFilled = True. That overwrites the method called isFilled and replaces it with the value True. That method is now gone and you can’t call it anymore. So when you try to call it again you get an error, since it’s not there anymore. The solution is use a different name for the … Read more

How to truncate float values?

First, the function, for those who just want some copy-and-paste code: This is valid in Python 2.7 and 3.1+. For older versions, it’s not possible to get the same “intelligent rounding” effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time: … Read more

Add Variables to Tuple

Tuples are immutable; you can’t change which variables they contain after construction. However, you can concatenate or slice them to form new tuples: And, of course, build them from existing values:

ImportError: no module named win32api

I am using Python 2.7 and I want to use pywin32-214 on Windows 7. I installed pywin32-214 by using the msi installer. But when I import win32api in my Python script, it throws the error: What should I do? Can I use pywin32 api for Windows 7?

isPrime Function for Python Language

Of many prime number tests floating around the Internet, consider the following Python function: Since all primes > 3 are of the form 6n ± 1, once we eliminate that n is: not 2 or 3 (which are prime) and not even (with n%2) and not divisible by 3 (with n%3) then we can test … Read more