2

An example how to find a file (Windows7):

# search for a filename in a given directory
# and all its subdirectories
# tested with Python27 and Python33

import os

def find_file(folder, filename):
    """
    search for a filename starting in directory/folder
    and then its subdirectories, return full path name or None
    """
    for root, dirs, files in os.walk(folder):
        #print(dirs)
        for fname in files:
            # make search case insensitive
            if fname.lower() == filename.lower():
                return os.path.join(root, fname)
    return None

# file to search for
filename = "i_view32.exe"
# directory/folder to start search
folder  = r"C:\Program Files (x86)"

result = find_file(folder, filename)
if result:
    print("File found --> %s" % result)
else:
    print("File %s not found" % filename)
2

Some basic class code example:

'''class_box101.py
create a basic class Box with at least one method
'''

class Box:
    '''
    self is the particular instance
    '''
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height

    def volume(self):
        '''
        a method starts with argument self
        this method calculates the volume of a box instance
        '''
        return self.length * self.width * self.height


# supply length, width, height of instance mybox 
mybox = Box(2, 3, 4)

print("Box({},{},{})".format(mybox.length, mybox.width, mybox.height))
print("has volume = {}".format(mybox.volume()))

# create another box instance with different dimensions
mybox2 = Box(2.5, 3.3, 4.8)

print("Box({},{},{})".format(mybox2.length, mybox2.width, mybox2.height))
print("has volume = {}".format(mybox2.volume()))

'''my result -->
Box(2,3,4)
has volume = 24
Box(2.5,3.3,4.8)
has volume = 39.6
'''

Now add a method surface_area to this example.

Edited by Lardmeister

1

Importing modules inside anonymous functions:

t = lambda: __import__('time').localtime()
print('Date: %s/%s/%s'%(t().tm_mday, t().tm_mon, t().tm_year))
1

You can create a hashed password this way:

'''password_create_py2.py
MD5 is not encryption, but a one-way hashing (check sum)

This program creates the hashed value of a given password.

Use this value in another program that compares it to
a similarly hashed user password.  This way the actual
password is not shown in the other program

Note:
Python3 dropped md5.md5(str) and uses hashlib.md5(bstr) instead

tested with Python27
'''

import md5

# to protect your actual password used here
# you can change that later to
# password = ""
password = "peanuts"

print(md5.md5(password).hexdigest())

'''
possible result, use that for MYPASSWORDHASH string in your program:
6e932d615f16a74d3cfe0c42f30a541d
'''

The hashed password can be used in another program this way, without revealing the actual password:

'''password_use_py2.py
MD5 is not encryption, but a one-way hashing (check sum)

The value for MYPASSWORDHASH was created with a separate program
to keep the actual password secret in this program.

tested with Python27
'''

import md5

# hash value created with a separate program
MYPASSWORDHASH = "6e932d615f16a74d3cfe0c42f30a541d"

def check_password():
    # give it three tries
    for i in range(3):
        # get the password string and hash it
        pw = raw_input("Enter your password: ")
        pw_hash = md5.md5(pw).hexdigest()
        print(pw_hash)  # for testing only
        # compare the two hashed values
        if pw_hash == MYPASSWORDHASH:
            return True
    return False

def test():
    if check_password():
        print("Success")
        # do something here
    else:
        print("Failure")
        # do something else here


test()

Edited by HiHe

3

A closer look at recursive functions:

''' func_recursion_GDC1.py
exploring recursive functions, in a nutshell:
return exit value if condition is met else
call function again with adjusted paramters
'''

def GCD(x, y):
    '''
    a recursive function to return the
    Greatest Common Divisor/Denominator of x and y
    '''
    return x if y == 0 else GCD(y, x%y) 


# testing ...
print(GCD(240, 150))  # 30
print(GCD(14, 63))    # 7
print(GCD(14, 0))     # 14
print(GCD(14, 3))     # 1

Edited by vegaseat: spelling

2

Another look at format() and print() using local variable names ...

''' vars_format_printing1.py
using vars() in named formatted print
tested with Python273, Python33 and IronPython273
'''

name = 'Abigale'
age = 72

# vars() gives the local dictionary containing variables name and age as keys
# can be used for Python2 and Python3
print("Hello %(name)s, you are %(age)s years old." % vars())

# needs Python273 or Python3 and higher
print("Hello {name}, you are {age} years old.".format(**vars()))


''' result -->
Hello Abigale, you are 72 years old.
Hello Abigale, you are 72 years old.
'''
2

If you want a selected list of Fibonacci numbers, you can use this approach ...

''' fibo_selected_list1.py
get a selected list of Fibonacci numbers given start to end
'''

import itertools

def xfibo():
    '''
    a generator for Fibonacci numbers, goes
    to next number in series on each call
    '''
    current, previous = 0, 1
    while True:
        yield current
        # use a tuple swap
        current, previous = previous, current + previous

start = 1
end = 6
# get a selected list of Fibonacci numbers 1 - 6
print(list(itertools.islice(xfibo(), start, end+1)))

start = 5
end = 10
# get a selected list of Fibonacci numbers 5 - 10
print(list(itertools.islice(xfibo(), start, end+1)))

''' result ...
[1, 1, 2, 3, 5, 8]
[5, 8, 13, 21, 34, 55]
'''
2

A decorator can be used to check a function's requirements:

''' require_decorator1.py
creating a general safe decorator
a safe decorator can be combined with other decorators
py2 and py3 tested on http://ideone.com/SPkbev
'''

def require(expr):
    """a general decorator checking args requirement"""
    def decorator(func):
        def wrapper(*__args,**__kw):
            message = "failed precondition %s" % expr
            assert eval(expr), message
            return func(*__args,**__kw)
        # optional next 3 lines make decorator safe
        wrapper.__name__ = func.__name__
        wrapper.__dict__ = func.__dict__
        wrapper.__doc__ = func.__doc__
        return wrapper
    return decorator

# allows only 1 argument here
@require("len(__args)==1")
def test(*args):
    print(args[0])

# no problem, prints Hello world!
test("Hello world!")

print('-'*50)

# has 2 arguments and will fail showing 
# AssertionError: failed precondition len(__args)==1
test("Hello", "World")
0

Watch out for numpy arrays, they don't always behave as expected:

''' np_array_copy.py
watch out for alias copy of a np array
the normal Python3 list behaves better
'''

import numpy as np

arr1 = np.arange(10)
# even though it's sliced, this will be an alias copy
arr2 = arr1[:5]
# make a true copy
arr3 = np.copy(arr1[:5])

print(arr1)
print(arr2)
print(arr3)

# change an element in arr1 (or arr2)
arr1[3] = 77

print('-'*50)

print(arr1)
print(arr2)
print(arr3)

''' result ...
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4]
[0 1 2 3 4]
--------------------------------------------------
[ 0  1  2 77  4  5  6  7  8  9]
[ 0  1  2 77  4]  <-- oops!
[0 1 2 3 4]
'''
1
If you have a Windows computer, you can use Portable Python.  Here are the latest updates ...
Portable Python installs a portable version of Python right on your USB flash drive (1GB+). 
You can use the flash drive now on any Windows computer that does not have Python installed. 
http://portablepython.com/wiki/PortablePython2.7.5.1
Package file size (compressed): 106MB
Installed size: based on selected packages, between 50MB and 545MB 
also contains these packages ...
NumPy 1.7.1
SciPy 0.12.0
Matplotlib 1.2.1
PyWin32 218
Django 1.5.1
PIL 1.1.7
Py2Exe 0.6.9
wxPython 2.9.4.0
PyScripter v2.5.3    
NetworkX 1.7
Lxml 2.3
PySerial 2.5
PyODBC 3.0.6
PyGame 1.9.1
PyGTK 2.24.2
PyQt 4.10.1
IPython 0.13.1
Pandas 0.11.0 

http://portablepython.com/wiki/PortablePython3.2.5.1
Package file size (compressed): 65MB
Installed size: based on selected packages, between 63MB and 260MB 
also contains these packages ...
PyScripter v2.5.3
NumPy 1.7.1
SciPy 0.12.0
Matplotlib 1.2.1
PyWin32 218
NetworkX 1.7
Lxml 2.3
PySerial 2.5
PyODBC 3.0.2
PyQt 4.9.6-1
IPython 0.13.1
Pandas 0.11.0 

Run the PyScripter IDE via PyScripter-Portable.exe

Edited by vegaseat

Votes + Comments
thanks for the info
0

Working with dictionaries:

''' dict_month1.py
sorting output by value of a dictionary items tuple
'''

months = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
     'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}

# month shows up in dictionary hash order
for key, val in months.items():
    print("{} {}".format(key, val))

print('-'*12)

# sort by value not key, value is at index 1 of tuple
for key, val in sorted(months.items(),key=lambda tup: tup[1]):
    print("{} {}".format(key, val))

''' result -->
Feb 2
Aug 8
Jan 1
Dec 12
Oct 10
Mar 3
Sep 9
May 5
Jun 6
Jul 7
Apr 4
Nov 11
------------
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
'''

Edited by vegaseat: mistakenly done, sorry

0

A little late for Easter this year ...

''' EasterDate1.py
An implementation of Butcher's Algorithm for determining the date of
Easter for the Western church. Works for any date in the Gregorian
calendar (1583 and onward). Returns a date object.
see also: http://code.activestate.com/recipes/576517/
tested with Python27 and Python33
'''

from datetime import date

def calc_easter(year):
    "Returns Easter as a date object."
    a = year % 19
    b = year // 100
    c = year % 100
    d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30
    e = (32 + 2 * (b % 4) + 2 * (c // 4) - d - (c % 4)) % 7
    f = d + e - 7 * ((a + 11 * d + 22 * e) // 451) + 114
    month = f // 31
    day = f % 31 + 1
    return date(year, month, day)

year = 2013
print("Easter for the year {} is on {}".format(year, calc_easter(year)))

''' result ...
Easter for the year 2013 is on 2013-03-31
'''
0

Interesting approximation of pi ...

''' pi_approximate7.py
calculate pi value
tested with Python27 and Python33
'''

import math

print(math.pi)
print(sum((-1.0)**n/(2*n+1) for n in reversed(range(1000000)))*4)

''' result (Python33) ...
3.141592653589793
3.1415916535897934
'''

Edited by vegaseat

0

Use Python's Counter() to find duplicate characters in a text ...

''' Counter_duplicate_items7.py
use Counter() and set() to find duplicate text characters
tip from raymondh
'''

from collections import Counter

text = "supercalifragilisticexpialidocious"
dup_char = sorted(Counter(text) - Counter(set(text)))

print("text = '{}' ".format(text))
print("The duplicate characters are:")
print(dup_char)

''' result ...
text = 'supercalifragilisticexpialidocious'
The duplicate characters are:
['a', 'c', 'e', 'i', 'l', 'o', 'p', 'r', 's', 'u']
'''
0

Function format() can be applied to the datetime specifiers ...

''' format_datetime101.py
use format() on datetime objects
tip from raymondh
'''

import datetime as dt

now = dt.datetime.now()
print(type(now))

print(format(now, '%A %B %d, %Y'))

''' example result ...
<class 'datetime.datetime'>
Wednesday September 25, 2013
'''

Edited by vegaseat

0

The size of an empty dictionary in 32 bit version of Python is half of what it is in a 64 bit Python installation:

''' dictionary_sizeof.py
get the size of a Python object
here an empty dictionary
result will be 2 x higher with 64 bit Python
'''

import sys

# size of empty dictionary object
print(sys.getsizeof({}))

''' result with 32 bit Python -->
140
'''

If you have very large dictionary objects, it might be better to use a 32 bit version of Python.

0

Thanks Lardmeister. The size also changes from Python2 to Python3 ...

''' dictionary_sizeof.py
get the size of a Python object
here an empty dictionary and 2 small dictionaries
result changes with the version of Python
result will be 2 x higher with 64 bit Python
'''

import sys
import pprint

# size of empty dictionary object
print("Empty dictionary = {}".format(sys.getsizeof({})))

d = {key:chr(key) for key in range(65, 65+26)}
pprint.pprint(d)
# size of a small dictionary
print("Above dictionary size = {}".format(sys.getsizeof(d)))

# size of local dictionary
print("Local dictionary vars() = {}".format(sys.getsizeof(vars())))

''' 
result with 32 bit Python33 -->
Empty dictionary = 148
{65: 'A',
 66: 'B',
 67: 'C',
 68: 'D',
 69: 'E',
 70: 'F',
 71: 'G',
 72: 'H',
 73: 'I',
 74: 'J',
 75: 'K',
 76: 'L',
 77: 'M',
 78: 'N',
 79: 'O',
 80: 'P',
 81: 'Q',
 82: 'R',
 83: 'S',
 84: 'T',
 85: 'U',
 86: 'V',
 87: 'W',
 88: 'X',
 89: 'Y',
 90: 'Z'}
Above dictionary size = 820
Local dictionary vars() = 244

result with 32 bit Python27 -->
Empty dictionary = 140
{65: 'A',
 66: 'B',
 67: 'C',
 68: 'D',
 69: 'E',
 70: 'F',
 71: 'G',
 72: 'H',
 73: 'I',
 74: 'J',
 75: 'K',
 76: 'L',
 77: 'M',
 78: 'N',
 79: 'O',
 80: 'P',
 81: 'Q',
 82: 'R',
 83: 'S',
 84: 'T',
 85: 'U',
 86: 'V',
 87: 'W',
 88: 'X',
 89: 'Y',
 90: 'Z'}
Above dictionary size = 1676
Local dictionary vars() = 524
'''
0

Just a little time experiment ...

''' time_current_h_m_s.py
use Python module time to get the current
hour, minute and second values
'''
import time

# take a slice of the current time tuple
# values you want are in index 3, 4, 5
hr, min, sec = time.localtime()[3:6]

# test
sf = "Current time values are {} hours {} minutes and {} seconds"
print(sf.format(hr, min, sec))

''' possible result ...
Current time values are 10 hours 37 minutes and 34 seconds
'''

Another approach ...

''' time_current_h_m_s2.py
use Python module time to get the current
hour, minute and second values
'''
import time

now = time.localtime()
#print(now)  # test to get names (acts like a named tuple)
sf = "Current time values are {} hours {} minutes and {} seconds"
print(sf.format(now.tm_hour, now.tm_min, now.tm_sec))

''' possible result ...
Current time values are 11 hours 15 minutes and 22 seconds
'''

Edited by vegaseat

0

One good use of the ternary if/else ...

''' func_recursion1a.py
recursion calls the function itself from within the function 
with its parameter(s) adjusted, an exit condition has to be given
tested with Python273 and Python33
'''

def del_char_right(s, num, count=0):
    '''
    delete num of characters to the right of string s
    recursive function streamlined with ternary if/else expression
    '''
    return s if count >= num else del_char_right(s[:-1], num, count+1)

# test it
mystr = 'parameter'
num = 5
newstr = del_char_right(mystr, num)
print(mystr)
print(newstr)

''' result ...
parameter
para
'''
1

Sometimes it pays to read the manual ...

''' integer_bitlength.py
how many bits does a given integer have
tested with Python27 and Python33
'''

# denary 12 --> binary 1100
n = 12
print("denary {} has {} bits".format(n, n.bit_length()))

''' result ...
denary 12 has 4 bits
'''
1

Turn an even integer into the next odd integer ...

# x|1 turns an even integer x into the next odd integer
# | is the bitwise or operator
x = 6
print(x, x|1)  # (6, 7)
x = 5
print(x, x|1)  # (5, 5)
0

Always timely ...

''' datetime_days_diff.py
show number of days between two given dates
'''

import datetime as dt

# dt.date(year, month, day)
date1 = dt.date(2013, 1, 1)
date2 = dt.date(2013, 12, 25)

# calculate the days difference
days = abs((date2 - date1).days)

sf = "There are {} days between {} and {}"
print(sf.format(days, date1.strftime("%d%b%Y"), date2.strftime("%d%b%Y")))

''' result ...
There are 358 days between 01Jan2013 and 25Dec2013
'''
1

Notice that in previous post, you could write

sf = "There are {} days between {:%d%b%Y} and {:%d%b%Y}"
print(sf.format(days, date1, date2))
-2

i need a binary addition code with no definition and with a hashtag explanation, please! Thanks

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.