# 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 ... " )
# 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 ... " )
# 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 ...
'''
# 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 ... " )
# 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
# 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
# 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 ... " )
# 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 ... " )
# 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 ... " )
# 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 ... " )
# 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 ..." )
# 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()