Posted in Python

Python Post #7 Important pointers (´・ω・)っ由

(✿ ♥‿♥)

As many of you by now may know, Python is a commonly used high-level programming language. The core benefit of python is to boost code readability, whereby the program’s language arrangement allows coders to write concepts in fewer lines of codes as compared to other programming languages such as Java. Python language has constructs that deliver clear and concise programs for both small and big developer projects. Python supports various programming forms, including object orientation, imperative styles, and functional programming styles.
Now moving on from the basic concepts, here are some simply useful and, well you might say essential, tips for the awakened programmers like you…
1) Writing functions with its variable lists
One of the awesome things about Python is with its variable parameter lists. Programmers can simply write functions without even knowing what sort of parameters will be passed.
Let’s focus on the codes listed below the asterisk at the first marks parameter may be any positional parameters.
def lessThan(cutoffMark, *marks) :
”’ Return a list of values less than the cutoff. ”’
    arr = []
    for val in marks :
        if val < cutoffMark:
    return arr
After using the function, we get:
>>> print(lessThan(10, 2, 17, -3, 42))
[2, -3]
Looking at the first positional value we state in the function call (10) that is given to the first parameter in the function (cutoffMark), it will cause all the remaining positional values to be assigned to marks. Scanning through these values, we can then search for those that are smaller than the cutoff value.
2) Apply the same technique used in tip 1 with named parameters
Likewise with named parameters, as shown below, a double asterisk place at the dict parameter below means any named parameters. Python will then be able to provide us with value pairs in dictionary form.
def printVals(prefix=”, **dict):
#Print out the extra named parameters and their values
    for key, val in dict.items():
        print(‘%s [%s] => [%s]’ % (prefix, str(key),str(val)))
After using the function, we get:
>>> printVals(prefix=’..’, foo=42, bar=’!!!’)
[foo] => [42]
[bar] => [!!!]
>>> printVals(prefix=’..’, one=1, two=2)
[two] => [2]
[one] => [1]
As extra named parameters are passed through in a dictionary, which is an unordered data structure, the values are not printed out in the same order as they were not defined in the function call.
3) Using True and False as Indexes
A technique you can use to select values is to use True and False as list indexes. The technique is useful due to the fact that False == 0 and True == 1:
test = True
# test = False
result = [‘Test is False’,’Test is True’][test]
# result is now ‘Test is True’
This method is simple and you wouldn’t encounter any hiccups when the value_if_true must actually be true.
However, do bear in mind that this method only works when you know the test is False or True (0 or 1), but not other integer values or arbitrary objects.
4) Improving Python performance with multiple approaches
If you intend on placing similar coding approaches whenever you create an application, it could cause your application to run slower than before. For instance, when handling codes in a dictionary, you may adopt a secured approach of dictating whether an item exists and update it or you can choose an alternative option by adding the item directly and then handling the given circumstances where the item does not exist as an exception.
Focusing on the safe and secured approach first,
p = 16
myDiction = {}
for i in range(0, p):
    char = ‘abcd'[i%4]
    if char not in myDict:
        myDiction[char] = 0
myDiction[char] += 1
As predicted, the code will normally perform quicker when myDict is empty at the beginning. However, when myDict is filled or almost filled with data, the alternative option is proven to be better as based on the set of codes listed below.
p = 16
myDiction = {}
for I in range(0, p):
    char = ‘abcd'[i%4]
        myDiction[char] += 1
    except KeyError:
        myDiction[char] = 1

Based on the 2 coding examples listed above, the output of {‘d’: 4, ‘c’: 4, ‘b’: 4, ‘a’: 4} is similar. However, the only difference is the manner in which output is obtained. That being said, it’s certainly helpful for programmers to take the unconventional approach to boost your python’s performance speed.
5) Remember to optimize your loops
One of the beautiful things when working with Python is that you can depend on plenty of different techniques for making loops run faster. However, one crucial reminder while optimizing loops is that you have to prevent yourself from using dots within a loop. For instance, let’s focus on the series of codes listed below:
lowerlist = [‘this’, ‘is’, ‘lowercase’]
upper = str.upper
upperlist = []
append = upperlist.append
for word in lowerlist:
#Output = [‘THIS’, ‘IS’, ‘LOWERCASE’]
Whenever you need to make a call to str.upper, Python assesses the technique. On the other hand, if you place such an evaluation in a variable, the value will be known and Python can perform the tasks quicker than before. The fact of the matter is that you should lessen the amount of work that Python performs within loops as the Python software can probably slow things down based on that example.
Of course, there are other ways to optimize loops such as using list comprehensions, which could be argued to be the next best alternative in achieving faster loops.
6) Useful tip to check whether a file exists in Python
With python, there are several ways you can use to see whether a file does exist (and is accessible) from a directory. One way is by using the os.path.isfile path. This function will be true if the given path is a prevailing, ordinary file. The file adopts symbolic links, which makes foros.path.islink(path) to be true and os.path.isfile(path) to also be true. The os.path.isfile is a very practical one-liner function that helps to check if a file exists.
7) Mixing Python and shell scripts 
It could be useful for you to write a script that can function as a shell script or as a Python script at the exact time, which is probable. To do it, the sequence of four quote characters requires an empty string to the shell, but in Python, it begins as a triple-quoted string that has a quote character. So you can embed shell commands within the python triple-quoted string. Take note that the first string in a module or script can be simply stored as the doc string for that module, but besides that the Python interpreter will just ignore it.
The below example display this particular trick.
if which python >/dev/null; then
    exec python “$0” “$@”
    echo “${0##*/}: Python not found. Please install Python.” >&2
exit 1
__doc__ = “””
Demonstrate how to mix Python + shell script.
import sys
print “Hello World!”
print “This is Python”, sys.version
print “This is my argument vector:”, sys.argv
print “This is my doc string:”, __doc__
sys.exit (0)
8) Know how to translate signal numbers to names
As of now, there is no existing function in the “signal” module that allows programmers to be able to change a signal number to a signal name. However, the listed example below could be a handy function for you to use.
def signal_numtoname (num):
name = []
for key in signal.__dict__.keys():
    if key.startswith(“SIG”) and getattr(signal, key) == num:
        name.append (key)
    if len(name) == 1:
        return name[0]
        return str(num)
9) Using a member of set type
You may not know, but there have been concepts that can boil down to operations on a set. Need to ensure that your list does not have duplicates? Or looking to see whether your two lists have anything common? Python does have a set function that allows you to make these operations quick and easy to read.
Also, you can use the intersection function to compare all the items. After which, you will be able to return them once the items have both sets in common.
# deduplicate a list *fast*
print(set([“chicken”, “eggs”, “bacon”, ” chicken “]))
# {‘bacon’, ‘eggs’, chicken }
# compare lists to find differences/similarities
# {} without “key”:”value” pairs makes a set
menu = {“pancakes”, ” chicken “, “eggs”, “bacon”}
new_menu = {“coffee”, ” chicken “, “eggs”, “bacon”, “bagels”}
new_items = new_menu.difference(menu)
print(“Try our new”, “, “.join(new_items))
# Try our new bagels, coffee
discontinued_items = menu.difference(new_menu)
print(“Sorry, we no longer have”, “, “.join(discontinued_items))
# Sorry, we no longer have pancakes
old_items = new_menu.intersection(menu)
print(“Or get the same old”, “, “.join(old_items))
# Or get the same old eggs, bacon, chicken
full_menu = new_menu.union(menu)
print(“At one time or another, we’ve served:”, “, “.join(full_menu))
# At one time or another, we’ve served: coffee, chicken, pancakes, bagels, bacon, eggs
10) Setting up Virtualenv in python
As virtualenv is a very important function for sandboxing Python environments, as it allows you to form independent Python contexts that are similar to separate sandboxes. Which is definitely a better than modifying the global python environment?
One of the key benefits of sandboxing your Python environment is that you can easily test your code under different Python versions and package dependencies.
To install virtualenv, you need to set up pip first. As such follow these commands:
# easy_install is the default package manager in CPython
% easy_install pip
# Install virtualenv using pip
% pip install virtualenv
% virtualenv python-workspace
# create a virtual environment under the folder ‘python-workspace’
With the new virtualenv set up under ‘python-workspace’, you have to activate the Python environment in order for the current shell to move into the virtualenv:
% cd python-workspace
% source ./bin/activate # activate the virtualenv ‘python-workspace’
% python # enter an interpreter shell by executing the current virtual python program under ‘python-workspace/bin/python’

So that being said, and assuming that I have mentioned everything necessary,let me disclose the winner of today’s lot picking…



And the lucky winner is …


I hope I can deliver this a little less messier than Python *sigh…

φ(゚ ω゚//)♠


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s