Author Topic: Python 3.x examples ...  (Read 26302 times)

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Python 3.x examples ...
« on: February 06, 2015, 03:57:56 AM »
Here are some Python 3.x examples that beginners in Python ... and even intermediate level coders in Python ... may find useful.

Enjoy :)



The first illustrates an important "GOTCHA" in Python ... take a look:

Code: [Select]
# demo_GOTCHA'S_with_list_and_.py #


# CARE needed ... when using functions ...
# when passing in MUTABLE objects to functions !!!

# (Since with objects .... passing in a reference,
#  i.e. a pointer, i,e, an address)

# So ... if obj gets CHANGED inside the function ...
# AND IF CHANGES NEED to be
# reflected in the OBJECT, outside the function scope,
# i.e. you want to change, (or maybe NOT to change),
# the passed in mutable object,
# and have, (or maybe NOT TO have),
# those changes RETAINED in the calling scope !!! #


outLst = [ 1,2,3 ]
print( "Before ...", outLst )

# Note: this is NOT an efficent use of list ... popping off the front #
# If need to pop from front, better to use a 'deque' container,
# that handles well, adding and popping at both front and back ends #
def popFront( lst ): # changes reflected in calling scope #
    while lst:
        # print( "deleting", lst[0], "from list... " )
        # del(lst[0]) # oe use below to return val)
        print( "lst.pop(0) =", lst.pop(0) )
        print( "lst is now:", lst )

popFront( outLst )
print( "After ...", outLst )


print( "vs..." )


outLst = [ 1,2,3 ]
print( "Before ...", outLst )

def popBack( lst ): # changes NOT reflected in calling scope #
    while lst:
        print( "deleting", lst[-1], "from list... " )
        lst = lst[:-1]  # lst now is NEW,
                        # SO NOT same address as lst passed in "
        print( "lst is now:", lst )

popBack( outLst )
print( "After ...", outLst )


name = '  maTThew daVid jOHn zAVITz   '
print( "\nBefore :  '" + name + "'" )

# recall strings are IMMUTABLE,
# so NEED to make and return NEW string #
def toTitleCase( strIn ):
    newStr = ''
    prev = ' '
    for c in strIn.strip():
        if prev.isspace():
            newStr += c.upper()
        else:
            newStr += c.lower()
        prev = c
       
    return newStr

print( "After  :  '" + toTitleCase(name) + "'" )


name = '  maTThew    daVid  jOHn         zAVITz   '
print( "\nBefore :  '" + name + "'" )

# recall strings are IMMUTABLE,
# so NEED to make and return NEW string #
def toTitleCase2( strIn ):
    lst = strIn.split()
    return ' '.join( [x[0].upper() + x[1:].lower() for x in lst] )


print( "After  :  '" + toTitleCase2(name) + "'" )

       
input( "\nPress 'Enter' to continue/exit ... " )
   
« Last Edit: February 06, 2015, 04:57:40 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #1 on: February 06, 2015, 04:03:12 AM »
These next two program illustrate common Python dictionary use

and sorting things on several fields at the same time ...


Firstly, using a dictionary or a specialized dictionary to count duplicates in a sequence
( a simple python list of integers with several duplicate entries is used  here )

Code: [Select]
# countDups.py #  # 2015-02-06 #


lst = [ 1, 2,2, 3,3,3, 4,4,4,4 ] # test list used to count duplicates #

# method 1 ... a plain use of Python type dict (dictionary) ...
d = {} # an empty Python dictionary (a Python 'dict' has key -> value pairs) #

for item in lst:
    if item in d:
        d[item] += 1 # update count ... #
    else:
        d[item] = 1 # set initial count value #

for key in d:
    print( key, '-', d[key] )


# or method 2 ...
print( '\nmethod 2 ...' )

d2 = {} # an empty dictionary

for item in lst:
    d2[item] = d2.get(item, 0) + 1  # if NOT found,
                                    # '0' IS the initial value to use here #

for item in d2.items(): # get a list of item ( key, value ) pairs (tuples) #
    print( '{} - {} '.format( *item ) ) # unpack item (unpack each tuple) #

   

# or method 3 ...
print( '\nmethod 3 ...' )

from collections import Counter
d3 = Counter() # a specialized Python (counter) dictionary type

for item in lst:
    d3[item] += 1 # make initial, or update count for this item

# show ...
for item in d3.items():
    print( '{} - {} '.format( *item ) ) # unpack item #

# or alternate show ...
print( 'or ...' )
for key in d3:
    print( key, '-', d3[key] )


input( "\nPress 'Enter' to continue/exit ... " )



Above methods running times compared ...

also demonstrating use of Python mean and pstdev functions.

NOTE!!! The program needs/uses the text file, named 'Genesis_1.txt', available here:

http://developers-heaven.net/forum/index.php/topic,2616.msg3152.html#msg3152

Code: [Select]
# countDupsTimed.py #  # 2015-02-06 #

# This program uses/needs/assumes ...
# the presence of the (enlarged) text file 'Genesis_1.txt' #


from time import time
from collections import Counter
from statistics import mean, pstdev

formatStr = 'time to create dictonary was: {:.3f} with ratio: {:.3f}'

# get a good sized list of words to use ...
# load the text file 'Genesis_1.txt' into the lst #
lst = []
with open( "Genesis_1.txt" ) as f:
    for line in f:
        words = line.split()
        for word in words:
            lst.append( word.strip("[].,;:?!").upper() )



NUM = 200     
times = [ [], [], [] ]

for loop in range(10):
   
    print( "Doing method 1" , end = ' ' )

    t1 = time()
    d = {} # an empty Python dictionary (a Python 'dict' has key -> value pairs) #
    for loop in range(NUM):
        # method 1 ... a plain use of Python type dict (dictionary) ...

        for item in lst:
            if item in d:
                d[item] += 1 # update count ... #
            else:
                d[item] = 1 # set initial count value #
               
    t2 = time()
    times[0].append( t2-t1 )

    print( "Done 1", end = ' ' )



    print( "Doing method 2", end = ' ' )

    t1 = time()
    d2 = {} # an empty dictionary
    for loop in range(NUM):
        # or method 2 ...
        # print( '\nmethod 2 ...' )

        for item in lst:
            d2[item] = d2.get(item, 0) + 1  # if NOT found,
                                            # '0' IS the initial value to use here #
       
        #print( 'Method 2: '+formatStr.format(t2-t1, (t2-t1)/save), '(to method 1)' )

    t2 = time()
    times[1].append( t2-t1 )

    print( "Done 2", end = ' ' )



    print( "Doing method 3", end = ' ' )

    t1 = time()
    d3 = Counter() # a specialized Python (counter) dictionary type
    for loop in range(NUM):
        # or method 3 ...
        # print( '\nmethod 3 ...' )

        for item in lst:
            d3[item] += 1 # make initial, or update count for this item
       
        #print( 'Method 3: '+formatStr.format(t2-t1, (t2-t1)/save), '(to method 1)' )

    t2 = time()
    times[2].append( t2-t1 )

    print( "Done 3" )


print( "Calculating means ... " )
meansLst = [ mean(lst) for lst in times ]
ratiosLst = [ round(meansLst[i]/meansLst[0], 3) for i in range(3) ]
print( "meansLst       :", meansLst )
print( "ratio of times :", ratiosLst )

print( "Calculating each pstdev... " )
pstdevLst = [ round( pstdev( tLst,m ), 3) for tLst,m in zip(times,meansLst) ]
print( "pstdevLst      :", pstdevLst )
 
def plusMimusTwoSdAsPercent( sd, m ):
    return sd*200 / m

asPerCnt = [ round(plusMimusTwoSdAsPercent( sd, m ), 1) for
             sd,m in zip(pstdevLst,meansLst) ]

print( "+- 2sd's as %  :", asPerCnt )


### show ...
### sort on ascending word order, then on descending count order
##tmpLstTups = sorted( d.items(), key=lambda e:e[0] )
##for tup in sorted( tmpLstTups, key=lambda e:e[1], reverse = True ) :
##    print( '{:12} {:3}'.format( *tup ) ) # * means to unpack each tuple #



input( "\nPress 'Enter' to continue/exit ... " )


'''
output from two runs ...

RUN 1:
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Calculating means ...
meansLst       : [0.4960808753967285, 0.648961091041565, 0.962521743774414]
ratio of times : [1.0, 1.308, 1.94]
Calculating each pstdev...
pstdevLst      : [0.009, 0.008, 0.007]
+- 2sd's as %  : [3.6, 2.5, 1.5]

Press 'Enter' to continue/exit ...

RUN 2:
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Doing method 1 Done 1 Doing method 2 Done 2 Doing method 3 Done 3
Calculating means ...
meansLst       : [0.5038808107376098, 0.6567611932754517, 0.9859216928482055]
ratio of times : [1.0, 1.303, 1.957]
Calculating each pstdev...
pstdevLst      : [0.007, 0.008, 0.006]
+- 2sd's as %  : [2.8, 2.4, 1.2]

Press 'Enter' to continue/exit ...

'''


The next ... illustrates sorting ... including sorting on multiple 'fields' ...
using tuples  ...
or
using class objects ...
(here ... sorting a list of objects of class Student is demo'd)

Code: [Select]
# keys_values_dict_sort_demo.py #

# get a 'test' Python type dict (i.e. a dictionary of key,value pairs)
d = { "sam":13, "sarah":12, "joe":14, "bill":12 }

print( "joe's age is:", d["joe"] )

print( "the whole dict  : ", d )

print( "just the keys   : ", d.keys() ) # returns a list of keys

print( "just the values : ", d.values() ) # returns a list of values

print()

print( d.items() ) # returns a list of pairs of (key, value) tuples

print( "\nfor item in sorted( d.items(), key = lambda item:item[1] ) :  print( item )" )
for item in sorted( d.items(), key = lambda item:item[1] ) :  print( item )
#Or ...
print( "\nOr ... print( sorted( d.items(), key = lambda e: e[1] ) )" )
print( sorted( d.items(), key = lambda e: e[1] ) )

# without using lambda functions ... can do complex sorts easily, by importing ... #
from operator import itemgetter, attrgetter # attrgetter used re. 'sorted' class below #

# firstly sort on index 1, then on index 0 #
print( "\nOr ... without using lambda functions ... can do complex sorts easily, ")
print( "by importing: \nfrom operator import itemgetter, attrgetter " )
print( sorted( d.items(), key = itemgetter(1,0) ) )


# get a demo class Student so can demo sorting a list of Students
print("\nCreating a demo class Student so can demo sorting a list of Students ... " )

class Student:
    def __init__(self, uid, name, age): # define constructor #
        self.uid = uid
        self.name = name
        self.age = age
    def __repr__(self): # 'def' this so can print out a Student object #
        return repr((self.uid, self.name, self.age))

# get a 'test demo' list of Students ...
myStuds = [Student(1,"Bill",14), Student(2,"Jill",15), \
           Student(3,"Sam",11), Student(4,"Anne",12), Student(5,"Sam",12)]

print( 'unsorted list is ...' )
print( myStuds )

# example of print sorted by reverse age, then by name and uid ... #

# firstly, sort by ...
tmp = sorted(myStuds, key = attrgetter( 'name', 'uid' ))
print( 'firstly sorted by name and then by uid ...' )
print( tmp ) # just to show intermediate step here ... #

print( 'then above, reverse sorted by age ...' )
print( sorted(tmp, key = attrgetter( 'age' ), reverse = True ))

input( "\nPress 'Enter' to continue/exit ... " )
« Last Edit: February 07, 2015, 08:01:52 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #2 on: February 06, 2015, 04:23:49 AM »
This next little demo illustrates getting valid input in a loop ...

here ... getting 3 valid integers that are part of a valid Python date.


The test program below, illustrates a simple Python way to get the days between any two dates.

Code: [Select]
# takeInValidDate.py #

# demo's input validation using a loop with a 'try ... except' structure #
# demo's 'parsing' an input string using the Python 'split' function #

# the 'main' here ... demo's getting the (inclusive) days between two dates #

from datetime import date

# 'default' entry, by just pressing ENTER, (after the prompt), returns today's date #
def takeInValidDate( msg ):
    more = True
    while( more ):
        dStr = input( msg )

        if len(dStr) == 0:
            return date.today()

 
        # Replace any of the following '-:.,' char's ... with a space char,
        # so CAN DO A SIMPLE 'split' using just ' ' char's as delimiters.
        for c in '-:.,' :
            dStr = dStr.replace( c, ' ' ) # REMEMBER to UPDATE dStr with the NEW string each time! #
        print( "Your 'edited' input line is: '" + dStr + "'" )
        dLst = dStr.split() # get a list of 'words' split on default delimiter = ' ' #
       
        if len(dLst) == 3: # Ensure that 3 and only 3 'items' were entered. #
            try:
                # will throw an exception if any ... 'to int conversion' ... fails
                # will also thow an exception if 'to date conversion' ... fails. #
                tmpDate = date( int(dLst[0]), int(dLst[1]), int(dLst[2]) )
                more = False # OK .. a good date ... so can EXIT 'while loop' NOW. #
            except:
                print( "NOT a valid date ... try again. " )
               
        else:
            print( "NEED to enter exactly 3 spaced numbers ... try again. " )
           
    return tmpDate



# main ... for testing purposes ... gets (inclusive) days between 2 dates #

if __name__ == '__main__':
    d1 = date.today()
    d2 = date.today()
    print( "Date", d2, "and date", d1, "have", (d2-d1).days+1,
           "(inclusive) day between them." )

    print( "\nThis program asks the user to enter two dates.\n"
           "The input loop repeats until each date entered is a valid date.\n"
           "Then it outputs the (inclusive) days between the two dates." )

    # main loop ... #

    msg = "To enter 'today\'s date', you can just PRESS the ENTER KEY,\n" \
          "OR ... ENTER THREE spaced numbers for y m d  :  "
   
    while True:
        print( "\nEnter the first date ... " )
        d1 = takeInValidDate( msg )
        print( "You entered:", d1 )
       
        print( "Enter the second date ... " )
        d2 = takeInValidDate( msg )
        print( "You entered:", d2 )
       
        print( "\n(Inclusive) days between",
               d2, "and", d1, "=", abs((d2-d1).days)+1, "day(s)." )
       
        if input( 'More (y/n) ? ' ).lower() == 'n' : break
       

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #3 on: February 06, 2015, 04:27:44 AM »
This next little snippet illustrates a simple method to get/accept only a NON_EMPTY string/line in Python ...

here ... also showing a safe open/read/show of any (text) file.

Code: [Select]
# takeInNonEmptyStr.py #


def takeInStr( msg, emptyOk = False ):
    while( True ):
        s = input( msg )
        if emptyOk:
            return s
        # else ... if reach here ...
        s = s.strip()
        if s:
            return s
        # else ... if reach here ...
        print( "Empty lines are not valid here ... " )


# test it out ... demo here is of 'safe file' open/read/show ... #

if __name__ == '__main__':

    while( True ):
        fname = takeInStr('Enter name of file to show: ')
        try:
            with open( fname ) as f:
                count = 0
                for line in f:
                    count += 1
                    print("{:4}".format(count), line, end='')
        except:
            print( "There was a problem opening/reading the file ..." )

        if input( 'More (y/n) ? ' ).lower() == 'n' : break
       
« Last Edit: February 06, 2015, 05:20:24 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #4 on: February 06, 2015, 04:32:16 AM »
This next ... may help beginners think again about the power and ease gained in coding,
by using versatile well designed functions ...

using a modular design ...

with one function calling another function in a loop ...

Code: [Select]
# boxes.py #

'''
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
'''

def printLine( totNum, otherNum, defaultLet, otherLet ):
    for i in range( totNum ):
        if i % otherNum == 0: print( otherLet, end = ' ' )
        else: print( defaultLet, end = ' ' )
    print()

def printBoxes( n, otherNum ):
    totNum = otherNum*n +1
    for i in range(totNum):
        if i % otherNum == 0: printLine( totNum, otherNum, '-', '+' )
        else: printLine( totNum, otherNum, ' ', '|' )

size = 4
for numBoxes in range(10):
    printBoxes( numBoxes, size )

input( "\nPress 'Enter' to continue/exit ... " )

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #5 on: February 06, 2015, 04:40:27 AM »
OK ... a little problem ... with two solution approaches demo'd below ...

Code: [Select]
# findAll4DigitVampireNumbers.py #  # 2015-02-06 #


lst = []
for i in range(1, 10):
    for j in range(10):
        for k in range(10):
            for m in range(10):
                prod = i*1000 + j*100 + k*10 + m
                if prod == (i*10+j) * (k*10+m):
                    lst.append( [prod, [(i*10+j), (k*10+m)]] )
                elif prod == (i*10+j) * (m*10+k):
                    lst.append( [prod, [(i*10+j), (m*10+k)]] )
                elif prod == (j*10+i) * (k*10+m):
                    lst.append( [prod, [(j*10+i), (k*10+m)]] )
                elif prod == (j*10+i) * (m*10+k):
                    lst.append( [prod, [(j*10+i), (m*10+k)]] )

                elif prod == (i*10+k) * (j*10+m):
                    lst.append( [prod, [(i*10+k), (j*10+m)]] )
                elif prod == (i*10+k) * (m*10+j):
                    lst.append( [prod, [(i*10+k), (m*10+j)]] )
                elif prod == (k*10+i) * (j*10+m):
                    lst.append( [prod, [(k*10+i), (j*10+m)]] )
                elif prod == (k*10+i) * (m*10+j):
                    lst.append( [prod, [(k*10+i), (m*10+j)]] )

                elif prod == (i*10+m) * (k*10+j):
                    lst.append( [prod, [(i*10+m), (k*10+j)]] )
                elif prod == (i*10+m) * (j*10+k):
                    lst.append( [prod, [(i*10+m), (j*10+k)]] )
                elif prod == (j*10+i) * (k*10+m):
                    lst.append( [prod, [(j*10+i), (k*10+m)]] )
                elif prod == (j*10+i) * (m*10+k):
                    lst.append( [prod, [(j*10+i), (m*10+k)]] )
                         


                         

print( "The number of 4 digit 'Vampire Numbers' is :", len(lst) )
for val in lst:
    print( '{} = {} * {}'.format( val[0], *sorted(val[1]) ) ) # unpack each sorted(val[1]) (list) #


print( 'checking ... ' )
for item in lst :
    print( '{} =? {}'.format( item[0], item[1][0] *item[1][1] ) )



input( "\nPress 'Enter' to continue/exit ... " )




And counting/comparing the design efficiency ... compare the number of 'if's called ...
(Note which method is much easier to extend to higher numbers ...)

Code: [Select]
# findVampireNumbers.py #  # 2015-02-06 #


count = 0
lst = []
for i in range(1, 10):
    for j in range(10):
        for k in range(10):
            for m in range(10):
                prod = i*1000 + j*100 + k*10 + m
                # ij km, ij mk, ji km, ji mk
                count += 1
                if prod == (i*10+j) * (k*10+m):
                    lst.append( [prod, (i*10+j), (k*10+m)] )
                    continue
                count += 1
                if prod == (i*10+j) * (m*10+k):
                    lst.append( [prod, (i*10+j), (m*10+k)] )
                    continue
                count += 1
                if prod == (j*10+i) * (k*10+m):
                    lst.append( [prod, (j*10+i), (k*10+m)] )
                    continue
                count += 1
                if prod == (j*10+i) * (m*10+k):
                    lst.append( [prod, (j*10+i), (m*10+k)] )
                    continue

                # ik jm, ik mj, ki jm, ki mj
                count += 1
                if prod == (i*10+k) * (j*10+m):
                    lst.append( [prod, (i*10+k), (j*10+m)] )
                    continue
                count += 1
                if prod == (i*10+k) * (m*10+j):
                    lst.append( [prod, (i*10+k), (m*10+j)] )
                    continue
                count += 1
                if prod == (k*10+i) * (j*10+m):
                    lst.append( [prod, (k*10+i), (j*10+m)] )
                    continue
                count += 1
                if prod == (k*10+i) * (m*10+j):
                    lst.append( [prod, (k*10+i), (m*10+j)] )
                    continue

                # im kj, im jk, mi kj, mi jk
                count += 1
                if prod == (i*10+m) * (k*10+j):
                    lst.append( [prod, (i*10+m), (k*10+j)] )
                    continue
                count += 1
                if prod == (i*10+m) * (j*10+k):
                    lst.append( [prod, (i*10+m), (j*10+k)] )
                    continue
                count += 1
                if prod == (m*10+i) * (k*10+j):
                    lst.append( [prod, (m*10+i), (k*10+j)] )
                    continue
                count += 1
                if prod == (m*10+i) * (j*10+k):
                    lst.append( [prod, (m*10+i), (j*10+k)] )
                    #continue
               
##                # kj im, kj mi, jk im, jk mi
##                elif prod == (k*10+j) * (i*10+m):
##                    lst.append( [prod, (k*10+j), (i*10+m)] )
##                elif prod == (k*10+j) * (m*10+i):
##                    lst.append( [prod, (k*10+j), (m*10+i)] )
##                elif prod == (j*10+k) * (i*10+m):
##                    lst.append( [prod, (j*10+k), (i*10+m)] )
##                elif prod == (j*10+k) * (m*10+i):
##                    lst.append( [prod, (j*10+k), (m*10+i)] )
                         
print( "count =", count )
print( "The number of 4 digit 'Vampire Numbers' is :", len(lst) )
for val in lst:
    print( val[0], '= {}*{} '.format( *sorted([val[1], val[2]]) ))




### METHOD 2 ###

def excise( inStr, letterToExcise ):
    newStr = ''
    i = 0
    inStrLen = len(inStr)
    while i < inStrLen:
        if inStr[i] == letterToExcise:
            i += 1
            break
        newStr += inStr[i]
        i += 1
       
    if i < inStrLen:
        newStr += inStr[i:]
    return newStr


           
count = 0
d = {}
for i in range(10, 100):
    for j in range(10, 100):
        prod = i*j
       
        count += 1
        if prod > 999:
            prodStr = str(prod)
            a = str(i)
           
            count += 1
            if a[0] in prodStr:
                prodStr = excise( prodStr, a[0] )
                count += 1
                if a[1] in prodStr:
                    prodStr = excise( prodStr, a[1] )
                    b = str(j)
                    count += 1
                    if b[0] in prodStr:
                        prodStr = excise( prodStr, b[0] )
                        count += 1
                        if b[1] in prodStr:
                            # if reach here, ok to add to dictionary ... #
                            d[prod] = [i, j]
                           
print( "\ncount =", count )
print( "METHOD 2: the number of 4 digit 'Vampire Numbers' is :", len(d) )
lst3 = []
for key in d:
    lst3.append( [key, d[key]] )
   
lst3.sort()
for item in lst3: print( item[0], '= {}*{}'.format(*sorted(item[1]) ) )

           


count = 0
d = {}
for i in range(100, 1000):
    for j in range(100, 1000):
        prod = i*j
       
        count += 1
        if prod > 99999:
            prodStr = str(prod)
            a = str(i)
           
            count += 1
            if a[0] in prodStr:
                prodStr = excise( prodStr, a[0] )
                count += 1
                if a[1] in prodStr:
                    prodStr = excise( prodStr, a[1] )
                    count += 1
                    if a[2] in prodStr:
                        prodStr = excise( prodStr, a[2] )
                        b = str(j)
                        count += 1
                        if b[0] in prodStr:
                            prodStr = excise( prodStr, b[0] )
                            count += 1
                            if b[1] in prodStr:
                                prodStr = excise( prodStr, b[1] )
                                count += 1
                                if b[2] in prodStr:
                                    # if reach here, ok to add to dictionary ... #
                                    d[prod] = [i, j]
                                   
print( "\ncount =", count )
print( "METHOD 2: the number of 6 digit 'Vampire Numbers' is :", len(d) )
lst3 = []
for key in d:
    lst3.append( [key, d[key]] )
   
lst3.sort()
for i, item in enumerate(lst3):
    print( str(item[0]) + '={}*{}'.format( *sorted(item[1]) ), end = ' ' )
    if (i+1) % 5== 0: print()

lst4 = []
for item in lst3:
    if item[1][0] * item[1][1] == item[0]:
        lst4.append( item )

input( "\nPress 'Enter' to continue ... " )

print( 'len(lst4) =', len(lst4) )
for i, item in enumerate(lst4):
    print( str(item[0]) + '={}*{}'.format( *sorted(item[1]) ), end = ' ' )
    if (i+1) % 5== 0: print()




print( "\n\nMETHOD 2: finding the number of 8 digit 'Vampire Numbers'  ... \nTHIS WILL take a while ..." )
       
count = 0
d = {}
for i in range(1000, 10000):
    for j in range(1000, 10000):
        prod = i*j
       
        count += 1
        if prod > 9999999:
            prodStr = str(prod)
            a = str(i)
           
            count += 1
            if a[0] in prodStr:
                prodStr = excise( prodStr, a[0] )
                count += 1
                if a[1] in prodStr:
                    prodStr = excise( prodStr, a[1] )
                    count += 1
                    if a[2] in prodStr:
                        prodStr = excise( prodStr, a[2] )
                        count += 1
                        if a[3] in prodStr:
                            prodStr = excise( prodStr, a[3] )
                            b = str(j)
                            count += 1
                            if b[0] in prodStr:
                                prodStr = excise( prodStr, b[0] )
                                count += 1
                                if b[1] in prodStr:
                                    prodStr = excise( prodStr, b[1] )
                                    count += 1
                                    if b[2] in prodStr:
                                        prodStr = excise( prodStr, b[2] )
                                        count += 1
                                        if b[3] in prodStr:
                                            # if reach here, ok to add to dictionary ... #
                                            d[prod] = [i, j]
print( "\ncount =", count )
print( "METHOD 2: the number of 8 digit 'Vampire Numbers' is :", len(d) )

input( "\nPress 'Enter' to continue ... " )

lst3 = []
for key in d:
    lst3.append( [key, d[key]] )
lst3.sort()
for i, item in enumerate(lst3):
    print( str(item[0]) + '={}*{}'.format( *sorted(item[1]) ), end = ' ' )
    if (i+1) % 4== 0: print()

     
input( "\nPress 'Enter' to continue/exit ... " )

« Last Edit: February 07, 2015, 06:07:49 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #6 on: February 06, 2015, 04:43:42 AM »
A little timer compared speed test ...

of three methods to reverse a string ... 
(Note, python does not supply a function to REVERSE A STRING,  but there IS an easy, very simple and  fast Pythonic way!)

also demonstrating use of Python mean and stdev functions ...

Code: [Select]
# 3stringReverseTimesCompared.py #  # 2015-02-06 #

from time import time
from statistics import mean, pstdev


s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
print( 'Compare times for these 3 reverse methods for string:' )
print( s )
print()

def reverse_string( s ):
    return s[::-1] # Python 'slice' to reverse string #

# return value of 2 pstdev expressed as % of mean #
def plusMinus( mean, sd ):
    return 200*sd/mean


NUM = 300000 # number of times to get a string reversed (each method) #
times = [ [], [], [] ] # to hold running sum of time taken for each method #

def rev_test():   
    loop = 10 # each rev_test loops 10 times here #
    while loop:

        t1 = time()
        for i in range(NUM):
            r = s[::-1]
        dt = time() - t1
        #print( '{:.5f}'.format(dt), end = ', ' )
        times[0].append(dt)


        t1 = time()
        for i in range(NUM):
            r = reverse_string( s )
        dt = time() - t1
        #print( '{:.5f}'.format(dt) )
        times[1].append(dt)

        t1 = time()
        for i in range(NUM):
            r = ''.join( reversed( s ))
        dt = time() - t1
        #print( '{:.5f}'.format(dt), end = ', ' )
        times[2].append(dt)

        loop -= 1

    m1, m2, m3 = [ mean(x) for x in times ]
    sd1, sd2, sd3 = [ pstdev(vals,m) for vals,m in zip(times,[m1,m2,m3]) ]
    pmsd1, pmsd2, pmsd3 = [ plusMinus(m, sd)
                         for m,sd in zip([m1,m2,m3],[sd1,sd2,sd3]) ]
   
    print( 'means :  ({:.3f}, {:.3f}, {:.3f})'.
           format(m1, m2, m3), end = '   -->   ' )
    print( "+- 2pstdev's as % :  ({:2.0f}%, {:2.1f}%, {:2.1f}%)".
           format( pmsd1, pmsd2, pmsd3 ) )


   
for run in range(10): rev_test()

#print( times ) # dump of all the time data

input( "\nPress 'Enter' to continue/exit ... " )
« Last Edit: February 07, 2015, 05:32:41 AM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #7 on: February 06, 2015, 04:53:34 AM »
And finally ...  an example of one READABLE way to compress a short list of strings ...

Code: [Select]
# compressListOfStrings.py #  # version 2015-02-08 #


def compressListOfStrings( lstIn ):
    """Reurns a readable 'compressed string' rep of the list of strings passed in.

    Note: the lst passed in *IS* a list of strings, all with len > 0
    """

    # work with a COPY of lstIn, of lstIn ...
    # use a COPY, since inside here ... copy is to be altered ...
    lst = sorted(lstIn) # also ... ensure sorted #

    # this next section is in case some strings are of different length #
    tmpLengths = [ len(item) for item in lst ]
    tmpLengths.sort()
    startLen = tmpLengths[0]-1 # set shortest string len to startLen#
   

    # returns a string of size commonsize that shows the first string that has
    # a next string with that commonsize ...
    # or ...
    # returns empty string '', if NOT exit [0:commonsize] slices with duplicate commonsize parts #
    def haveCommonLen( lst, commonsize ):
        i = 1
        while i < len(lst) :
            if lst[i-1][0:commonsize] == lst[i][0:commonsize]:
                return lst[i-1][0:commonsize]
            else:
                i += 1
               
        return ''



    # Note: 'newLst' is 'global' w.r. to the 'update' function below
    # where it gets updated ... each time called ...
    newLst = []  # get an empty newLst to hold the compressed new list #
       
    # pass in OLD lst to be updated ... and the comStr
    # if comStr not '', that means that there are still some common parts ...
    # NOTE! newLst is updated each time called, with the newStr formed here #
    def update( lst, comStr ) :

        comlen = len(comStr)
        newStr = ''

        # get a (slice) COPY so can traverse THE COPY while removing from lst #
        for item in lst[:] :
            if comStr == item[0:comlen] :
                if newStr == '' :  #first time 'comStr' appears #
                    newStr = item
                else : # next time 'comStr' appears #
                    newStr += '-' + item[comlen:] # append THIS end unique part #

                # here, every time, since 'if' ... AND... we also pre-KNOW that
                # inside this function, that comStr 'repeats' #
                lst.remove( item )

        # ok ... done loop for this common size, so now add this newStr to newLst #       
        newLst.append( newStr )



    # loop (down) through all possible common lengths,
    # beginning with commonLen = startLen ...
    # and ending on the final value, commonLen = 1
    # NOTE: step is -1 on each loop #

    for commonLen in range(startLen, 0, -1):
        comStr = haveCommonLen( lst, commonLen )           
        if comStr:
            update( lst, comStr )


    if lst: # update newLst with items remaining,
            # items that had NOthing in common ... #
        newLst += lst


    # OK ... return the 'joined string' after sorting newLst ... #

    return ', '.join( sorted(newLst) )
     
    #####  end of function: compressListOfStrings( lstIn )  #####



# OK ... here is a little test list #

if __name__ == '__main__':

    print( 'Original list (sorted copy):' )
    lst = ["2319827",
           "2320578",
           "2320579",
           "2321529",
           "2321530",
           "7005121"]
    print( sorted(lst) ) # ensure sorted copy is shown, so it will match string rep below #

    print( 'Compressed representative string:' )
    print( compressListOfStrings( lst )  )

    input( "Press 'Enter' to continue/exit ..." )
« Last Edit: February 08, 2015, 12:57:01 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #8 on: February 07, 2015, 07:58:45 AM »
Appendix:

text file used above ...

name this text file: Genesis_1.txt

~~~~~~~~~~~~~~ begins after this ~~~~~~~~~~~~~~~~
In the beginning God created the heaven and the earth.
And the earth was without form, and void; and darkness [was] upon the face of the deep.
And the Spirit of God moved upon the face of the waters.
And God said, Let there be light: and there was light.
And God saw the light, that [it was] good: and God divided the light from the darkness.
And God called the light Day, and the darkness he called Night.
And the evening and the morning were the first day.
And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.
And God made the firmament, and divided the waters which [were] under the firmament from the waters which [were] above the firmament: and it was so.
And God called the firmament Heaven.
And the evening and the morning were the second day.
And God said, Let the waters under the heaven be gathered together unto one place, and let the dry [land] appear: and it was so.
And God called the dry [land] Earth; and the gathering together of the waters called he Seas: and God saw that [it was] good.
And God said, Let the earth bring forth grass, the herb yielding seed, [and] the fruit tree yielding fruit after his kind, whose seed [is] in itself, upon the earth: and it was so.
And the earth brought forth grass, [and] herb yielding seed after his kind, and the tree yielding fruit, whose seed [was] in itself, after his kind: and God saw that [it was] good.
And the evening and the morning were the third day.
And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so.
And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: [he made] the stars also.
And God set them in the firmament of the heaven to give light upon the earth, And to rule over the day and over the night, and to divide the light from the darkness: and God saw that [it was] good.
And the evening and the morning were the fourth day.
And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl [that] may fly above the earth in the open firmament of heaven.
And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that [it was] good.
And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth.
And the evening and the morning were the fifth day.
And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so.
And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that [it was] good.
And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth.
So God created man in his [own] image, in the image of God created he him; male and female created he them.
And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth.
And God said, Behold, I have given you every herb bearing seed, which [is] upon the face of all the earth, and every tree, in the which [is] the fruit of a tree yielding seed; to you it shall be for meat.
And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein [there is] life, [I have given] every green herb for meat: and it was so.
And God saw every thing that he had made, and, behold, [it was] very good.
And the evening and the morning were the sixth day.
In the beginning God created the heaven and the earth.
And the earth was without form, and void; and darkness [was] upon the face of the deep.
And the Spirit of God moved upon the face of the waters.
And God said, Let there be light: and there was light.
And God saw the light, that [it was] good: and God divided the light from the darkness.
And God called the light Day, and the darkness he called Night.
And the evening and the morning were the first day.
And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.
And God made the firmament, and divided the waters which [were] under the firmament from the waters which [were] above the firmament: and it was so.
And God called the firmament Heaven.
And the evening and the morning were the second day.
And God said, Let the waters under the heaven be gathered together unto one place, and let the dry [land] appear: and it was so.
And God called the dry [land] Earth; and the gathering together of the waters called he Seas: and God saw that [it was] good.
And God said, Let the earth bring forth grass, the herb yielding seed, [and] the fruit tree yielding fruit after his kind, whose seed [is] in itself, upon the earth: and it was so.
And the earth brought forth grass, [and] herb yielding seed after his kind, and the tree yielding fruit, whose seed [was] in itself, after his kind: and God saw that [it was] good.
And the evening and the morning were the third day.
And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so.
And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: [he made] the stars also.
And God set them in the firmament of the heaven to give light upon the earth, And to rule over the day and over the night, and to divide the light from the darkness: and God saw that [it was] good.
And the evening and the morning were the fourth day.
And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl [that] may fly above the earth in the open firmament of heaven.
And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that [it was] good.
And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth.
And the evening and the morning were the fifth day.
And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so.
And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that [it was] good.
And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth.
So God created man in his [own] image, in the image of God created he him; male and female created he them.
And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth.
And God said, Behold, I have given you every herb bearing seed, which [is] upon the face of all the earth, and every tree, in the which [is] the fruit of a tree yielding seed; to you it shall be for meat.
And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein [there is] life, [I have given] every green herb for meat: and it was so.
And God saw every thing that he had made, and, behold, [it was] very good.
And the evening and the morning were the sixth day.
In the beginning God created the heaven and the earth.
And the earth was without form, and void; and darkness [was] upon the face of the deep.
And the Spirit of God moved upon the face of the waters.
And God said, Let there be light: and there was light.
And God saw the light, that [it was] good: and God divided the light from the darkness.
And God called the light Day, and the darkness he called Night.
And the evening and the morning were the first day.
And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.
And God made the firmament, and divided the waters which [were] under the firmament from the waters which [were] above the firmament: and it was so.
And God called the firmament Heaven.
And the evening and the morning were the second day.
And God said, Let the waters under the heaven be gathered together unto one place, and let the dry [land] appear: and it was so.
And God called the dry [land] Earth; and the gathering together of the waters called he Seas: and God saw that [it was] good.
And God said, Let the earth bring forth grass, the herb yielding seed, [and] the fruit tree yielding fruit after his kind, whose seed [is] in itself, upon the earth: and it was so.
And the earth brought forth grass, [and] herb yielding seed after his kind, and the tree yielding fruit, whose seed [was] in itself, after his kind: and God saw that [it was] good.
And the evening and the morning were the third day.
And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so.
And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: [he made] the stars also.
And God set them in the firmament of the heaven to give light upon the earth, And to rule over the day and over the night, and to divide the light from the darkness: and God saw that [it was] good.
And the evening and the morning were the fourth day.
And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl [that] may fly above the earth in the open firmament of heaven.
And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that [it was] good.
And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth.
And the evening and the morning were the fifth day.
And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so.
And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that [it was] good.
And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth.
So God created man in his [own] image, in the image of God created he him; male and female created he them.
And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth.
And God said, Behold, I have given you every herb bearing seed, which [is] upon the face of all the earth, and every tree, in the which [is] the fruit of a tree yielding seed; to you it shall be for meat.
And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein [there is] life, [I have given] every green herb for meat: and it was so.
And God saw every thing that he had made, and, behold, [it was] very good.
And the evening and the morning were the sixth day.
In the beginning God created the heaven and the earth.
And the earth was without form, and void; and darkness [was] upon the face of the deep.
And the Spirit of God moved upon the face of the waters.
And God said, Let there be light: and there was light.
And God saw the light, that [it was] good: and God divided the light from the darkness.
And God called the light Day, and the darkness he called Night.
And the evening and the morning were the first day.
And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.
And God made the firmament, and divided the waters which [were] under the firmament from the waters which [were] above the firmament: and it was so.
And God called the firmament Heaven.
And the evening and the morning were the second day.
And God said, Let the waters under the heaven be gathered together unto one place, and let the dry [land] appear: and it was so.
And God called the dry [land] Earth; and the gathering together of the waters called he Seas: and God saw that [it was] good.
And God said, Let the earth bring forth grass, the herb yielding seed, [and] the fruit tree yielding fruit after his kind, whose seed [is] in itself, upon the earth: and it was so.
And the earth brought forth grass, [and] herb yielding seed after his kind, and the tree yielding fruit, whose seed [was] in itself, after his kind: and God saw that [it was] good.
And the evening and the morning were the third day.
And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so.
And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: [he made] the stars also.
And God set them in the firmament of the heaven to give light upon the earth, And to rule over the day and over the night, and to divide the light from the darkness: and God saw that [it was] good.
And the evening and the morning were the fourth day.
And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl [that] may fly above the earth in the open firmament of heaven.
And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that [it was] good.
And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth.
And the evening and the morning were the fifth day.
And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so.
And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that [it was] good.
And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth.
So God created man in his [own] image, in the image of God created he him; male and female created he them.
And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth.
And God said, Behold, I have given you every herb bearing seed, which [is] upon the face of all the earth, and every tree, in the which [is] the fruit of a tree yielding seed; to you it shall be for meat.
And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein [there is] life, [I have given] every green herb for meat: and it was so.
And God saw every thing that he had made, and, behold, [it was] very good.
And the evening and the morning were the sixth day.
~~~~~~~~~~~~~~ end before  this ~~~~~~~~~~~~~~~~

Offline David

  • Hero Member
  • *****
  • Posts: 644
    • View Profile
Re: Python 3.x examples ...
« Reply #9 on: June 19, 2015, 10:15:17 AM »
Ok ... here is a Python 3 Turtle Graphics example ...

It demo's some data processing of the ages of our Patriarchs.

This data is carefully recorded for us in the Book of Genesis.

Here ... the results are displayed using a bar graph.

Take a look ...

Code: [Select]
# agesOfPatriarchs.py #  # ver. 2015-06-20 #

# Global stuff ...  Note: here we are holding the 'age data' in Python lists #

width = 400
height = 300

import turtle # so can use Python Turtle Graphics library for bar-graphs #

ref1 = '''Genesis 5:1 - 9:29'''
n1 =  ['Adam','Seth','Enos','Cainan','Mahalaleel','Jared','Enoch','Methuselah','Lamech','Noah']
y11 = [130, 105,  90,  70,  65, 162,  65, 187, 182, 500] # age at 'son' born #
y12 = [800, 807, 815, 840, 830, 800, 300, 782, 595, 450] # years lived after #
y13 = [930, 912, 905, 910, 895, 962, 365, 969, 777, 950] # years at death #
yson =[130, 235, 325, 395, 460, 622, 687, 874, 1056, 1556] #year 'son' born#
yend =[930, 1042, 1140, 1235, 1290, 1422, 987, 1656, 1651, 2006] #year of death#


ref2 = '''Genesis 11:10 - 12:5'''
n2  =   ['Shem','Arphaxad','Salah','Eber','Peleg','Reu','Serug','Nahor','Terah']
y21 =   [102,  35,  30,  34,  30,  32,  30,  29,  70] # age at 'son' born #
y22 =   [500, 403, 403, 430, 209, 207, 200, 119, 135] # years lived after #
y23 =   [602, 438, 433, 464, 239, 239, 230, 148, 205] # years at death #
yson2 = [1658, 1693, 1723, 1757, 1787, 1819, 1849, 1878, 1948] #year 'son' born#
yend2 = [2158, 2096, 2126, 2187, 1996, 2026, 2049, 1997, 2083] #year of death#

n3 = n1 + n2 # Python list n3, now holds list n1, with list n2 at end also. #
y31 = y11 + y21
y33 = y13 + y23
yend3 = yend + yend2


s1 = sum(y11) # now holding sum of values in list 'y11', at 's1' #
s2 = sum(y21)
print( "Year from creation at Shem's birth: ", s1,
       ", Gap: ", s2,
       ", Year at Abram's birth: ", s1+s2, sep = '' )
#1556 392 1948#
text = " (YEAR of FLOOD was 1656 when Noah was 600 and Shem was 100,"
text += " Abram born in 1948!"


print( "\nNames ({}):\n".format(ref1), ', '.join(n1), sep = '   ' )
print( "   Age at birth of 'son':\n", y11, sep ='' )
yson= []
summ = 0
for item in y11:
    summ += item
    yson.append( summ )
print( "   'yson' (Years from creation at birth of 'this son'): " )
print( yson )
print( "   Age at death:\n", y13, sep ='' )
print( "   Years, from creation, at death:\n", yend, sep = '' )
yend= []
for a, b in zip( yson, y12 ):
    yend.append( a + b )
print( "   yend (x-check of line above):" )
print( yend )



print( "\nNames2 ({}):\n".format(ref2), ', '.join(n2), sep = '   ' )

yson2= []
summ = 1556
for item in y21:
    summ += item
    yson2.append( summ )
print( "   'yson2' (Years from creation at birth of 'this son'): " )
print( yson2 )

yend2= []
for a, b in zip( yson2, y22 ):
    yend2.append( a + b )
print( "   Years, from creation, at death:\n", yend2, sep = '' )

   
input( "\nPress 'Enter' to continue ... " )


def draw_bar( t, w, h ):
    hh = h[0] / top * height
    t.pendown()
    t.begin_fill()
    t.setheading(90)
    t.forward(hh)
    t.write(str(h[0]) + ' ' + h[1][:5])
    t.right(90)
    t.forward(w)
    t.right(90)
    t.forward(hh)
    t.right(90)
    t.forward(w)
    t.end_fill()
   
    t.penup()
    t.setheading(0)
    t.forward(w*1.7)


def pause( wn, t, i ):
    wn.textinput("This is bargraph {} of 6".format(i),
                 "Click ANY button or PRESS 'Enter' KEY to continue ... " )
    t.clear()
   


''' main program stuff begins here ... '''

wn = turtle.Screen()
wn.bgcolor( 'lightgreen' )
wn.screensize( width, height )

t = turtle.Turtle()
t.color( 'blue', 'red' )
t.pensize( 3 )

t.speed(0) # max speed #

t.penup()
t.hideturtle()


topTmp = 2006


titles = ['Adam to Noah', 'Shem to Abram', 'Adam to Abram']
j = 0

for loop in [ 1, 2, 3 ]:
   
    wn.title( titles[loop-1] + text )
   
    data = [ (years, name) for years, name in zip(y13, n1) ]
    numItems = len(data)

    top = topTmp

    t.penup()
    t.goto( -width*3//4, -height/2 )

    for val in data:
        draw_bar( t, width/1.2/numItems, val )

    t.penup()
    t.goto( 0, -height/2 - 25 )
    t.write( "(Years old at death)", align = 'right' )


   

    '''
    wn.textinput("Next", "Click any button or press 'Enter' to continue ... " )
    t.clear()
    '''
    j += 1
    pause( wn, t, j )
   


    data = [ (years, name) for years, name in zip(y13, n1) ]
    numItems = len(data)

    top = topTmp

    t.penup()
    t.goto( -width*3//4, -height/2 )

    for yr, val in zip(y11, data):
        draw_bar( t, width/1.2/numItems, val )

        t.write(str(yr))
       
        y = t.ycor()
        y += height * yr/top
        t.sety( y )

    if loop == 1:
        n1 = n2
        y11 = y21
        y13 = y23
    elif loop == 2:
        n1 = n3
        y11 = y31
        y13 = y33


    t.penup()
    t.goto( -width*3//4, -height/2 )
    t.setheading(90)
    t.pendown()
    dh = height/10 * 2500/top
    for i in range(10):
        t.forward(dh)
        t.setheading(0)
        t.forward(10)
        t.setx( -width*3//4 )
        t.setheading(90)
        t.write( "   " + str(250+i*250) )

    t.forward(dh)
    if( loop != 2 ):
        t.write( "   LIFE SPANS : YEARS FROM CREATION" )
    else: # is 2
        t.write( "   LIFE SPANS : YEARS FROM BIRTH OF NOAH's son SHEM" )
   
       

    if loop < 3:
        j += 1
        pause( wn, t, j )
        '''
        turtle.textinput("Next", "Click ANY button or PRESS 'Enter' KEY to continue ... " )
        t.clear()
        '''

    if loop == 3:
        t.penup()
        x = -width*3//4
        h = -height/2 - 25
        t.goto( x, h  )
        t.setheading(0)
        k = 0
        for y, n in zip(yend, n1):
            t.write( "({},{}) ".format( y, n ) )
            t.forward(100)
            k += 1
            if k == 5:
                k = 0
                h -= 25
                t.goto( x, h )

        h =-height/2 - 25*3
        k = 0
        t.goto( x, h  )
        for y, n in zip(yend2, n2):
            t.write( "({},{}) ".format( y, n ) )
            t.forward(100)
            k += 1
            if k == 5:
                k = 0
                h -= 25
                t.goto( x, h )

        h =-height/2 - 25*5
        t.goto( x, h )
        t.write( "(Years, from creation, for death of Patriarchs)" )
       



wn.mainloop()

« Last Edit: June 20, 2015, 10:42:22 AM by David »