What are some cool Python tricks?
I think the data structures in the collections module are underused power tools. I use Counters to represent probability mass functions, defaultdict for accumulating lists, and namedtuple instead of writing small class definitions.I have a note book that demonstrates counters here: Page on ipython.org
What does a map function do in Python 3?
map function takes an arbitrary function and applies it over the elements of an iterable. An iterable, loosely speaking, is anything which allows you to loop through its elements.Consider this example,>>> round(2.3)2>>> round(4.9)5>>> rounded = map(round, [2.3, 4.9])>>> list(rounded)[2, 5]There are two main components to this example:the round functionthe iterable i.e., list [2.3, 4.9]Let’s say you have this list of hundred numbers that you want to round off. Of course, you are not going to write hundred round statements. One of the many ways to achieve this [in Python] is to use map.You can provide map with the function as argument, and the list of elements on which it has to be applied. The result is a generator expression. The last step retrieves the results from the generator.Now, let’s look at the code below:a, b = map(int, input().split())Here’s a breakdown:In : input().split()12 13Out : ['12', '13']That is, take an input, split it and create a list, then convert them into an integer by mapping the function int, finally save the results in variables a, b.That’s one way you can take multiple inputs on the same line.
Is OOP important in Python in general?
It depends - there are usages of Python where it’s essential, and those where you’d most likely go for procedural programming rather than lose your time trying to figure out how to make your app or tool object-oriented.Just look up this article I just found: Embracing the Four Python Programming StylesException handling is something for which OOP is just must-have. As your application grows, generic Exception class turns out to be insufficient and you start extending it to your own ReadingDataException, GraphException etc. At some point you realize that you want to treat StrayNodeException differently than InvalidNodeLinkageException, and in some others not. So basically even if your application is not very object-oriented in general, you might still need to have object-oriented exception handling to react to errors properly.If you are developing f.e. Python scripts for some sort of automation, OOP might turn out to be somewhat useless as the only thing you need is to accept a limited set of parameters and make your script act accordingly, usually by having ArgParse object to handle command line arguments and handling each argument with call to different handler. Except if your script does some really advanced stuff, f.e. if I were to rewrite Nmap: the Network Mapper using Python I’d likely opt for OOP and patterns like Strategy to incorporate numerous scanning techniques that can be combined in Nmap.If you’re developing Python plugin for existing software, it will depend on its API, supported Python version and what exactly do you need to do. I have written Abaqus FEA plugin that almost completely automates process of CAE model generation for pretty wide set of armor impact simulations (multiple layers, terminal velocity, mesh element size, angle of incidence, spaced armor, different projectiles and materials etc) using exactly 2 classes just for convenience, without OOP approach - however I probably need to refactor it to be able to extend it further. You can take a look: superdurszlak/ImpactTestIn web development, you can get along with both object-oriented approach (I haven’t used Django so far yet it should involve some OOP as it incorporates MVC), and procedural one, with the only classes being your database model (this is perfectly possible in Flask and you don’t even have to make your code messy).I’d say that decorators and versatility are much more important in Python than OOP, or any other approach.
Why doesn't Java have map and filter as functions like Python? What are the pros and cons of that approach? For what it's worth, Python is considered a purely object-oriented language despite having such functions.
As others have pointed out, Java does have the map and filter function using the streams API. What’s important here is the way Java has realized its functional self: rather than having functional constructs baked into the language syntax (like Python), Java uses libraries. This means that you’re actually calling methods on the Streams API to synthesize functional programming.The pro of that approach is that functional programming is almost an “opt-in” feature of the language. This means that if you want functional programming, you import the library just like you would any other non-essential library. You can just as easily opt-out of it. Besides lambdas and method references, there are no functional constructs in the language syntax.The con is that functional programming is a second-class citizen of the language. If you’re a hard core functional programmer (like Haskell), you won’t feel at home. Contrast that with object orientation in Java which is inextricably linked to the language. You’re always developing in terms of classes.For what it’s worth, Python is not considered a “purely object-oriented” language. It actually marries five different paradigms: object-oriented, imperative, functional, procedural, and reflective.Footnotes Python (programming language) - Wikipedia
Why can't I wrap my head around object oriented programming?
Why is there the "TypeError: 'int' object is not callable" error here?
While it's unclear for now what you're trying to do (I will edit this answer later), a couple of general tips:make function names descriptive. 'fn' is not a descriptive function name;if it's not obvious what the function does from its name alone, use a docstring to describe what it does;you can only return one value. A return statement exits the function, so any code that comes after it, will not be executed.
Can you explain the benefits of object-oriented programming vs. functional programming? I come from an academic setting using MATLAB. I primarily have learned only functional programming. I am now trying to learn Python.
Both object-oriented programming and functional programming attempt to help you manage program complexity, but they do so in different ways. In functional programming, you decompose a problem into functions, and functions are composed from other functions. The data that these functions operate on may be scattered helter-skelter.In object-oriented programming, you decompose a problem into objects, which encapsulate data and the functions that operate on them. An object is a nice, tidy, conceptual unit. It bears a strong resemblance to the module concept in regular procedural programming, except that the data is “hidden” from the outside world and access to the data is carefully regulated by “accessors.” Objects are usually much more fine-grained than modules.OOP programs are composed in one of two ways:composition or aggregationinheritanceInheritance can be a powerful mechanism for reusability, but it mustn’t be overused or abused. Inheritance isn’t always necessary, and composition should be applied when it is more suitable.In class-based OOP, special objects known as classes serve as templates or factories for creating real instances of objects. You create or instantiate an object by using “new” or some such syntactical element. This is typically built into the language. (That’s where “new” came from in your case.)In a pure object-oriented language like Smalltalk, everything is an object, including primitive types such as integers and strings. Through the inheritance hierarchy, these objects will acquire a great many methods and properties. (That’s what you’re observing.)Object-oriented programming and functional programming each have their best use cases. Neither paradigm is universal; neither paradigm is a programming panacea.At the end of the day, it’s all about managing complexity. You just need to understand when and where to apply either of these paradigms.
How do you get Python to print values rather than the memory addresses of functions?