Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Insights Simple Python Debugging with Pdb: Part 2 - Comments

  1. Nov 26, 2015 #1

    Mark44

    Staff: Mentor

  2. jcsd
  3. Nov 30, 2015 #2
    Mark, how would you compare Python with other similar languages?
     
  4. Nov 30, 2015 #3

    Mark44

    Staff: Mentor

    Python is in some respects similar to C, but is a language that is significantly higher in level. Without using any external libraries/modules, you can get permutations and combinations very quickly.

    A couple of the features of Python that distinguish it from C and the languages that derive from C are the map() function and list comprehension. map() returns an iterator that will apply some operator to one or more lists (depending on the operator). In the example below, corresponding pairs of numbers are multiplied in two lists to form a new list that contains these products, and then the sum() function is applied to the list to add all of the numbers. In short, the one-line body of the dotprod() function calculates the dot product of the two lists that are in its argument list. Lower-level languages such as C will typically use a for loop to iterate through the lists.


    Code (Python):
    # dotprod.py -- find the dot product of two vectors
    import operator

    def dotprod(u, v):
       return sum(map(operator.mul, u, v))

    u = [1, 2, -1, 4, 2, 1, -2, 6]
    v = [1, 4, -1, 0, 1, 1, -2, 4]

    ans = dotprod(u, v)
    print("Result is: ", ans)
    This code displays 41 as its result.

    List comprehension is "A compact way to process all or part of the elements in a sequence and return a list with the results."
    Here's an example that works with the list [0, 1, ..., 255] and creates a new list with only the list elements that are evenly divisible by 16.
    Code (Python):
    #list_comp.py -- simple example of list comprehension
    my_list = [x for x in range(256) if x % 16 == 0]
    print(my_list)
    The print() statement displays the list as [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240]

    I'm sure there are quite a few more differences, but these are just a few that come to mind.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Simple Python Debugging with Pdb: Part 2 - Comments
  1. Simple python question (Replies: 2)

Loading...