Also, see the code snippet on checking numeric input at:
http://www.daniweb.com/code/snippet284490.html
lllllIllIlllI commented: This is a code snippet, it is in the wrong place -1
jib -2 Junior Poster
Mind if add some tutorials of mine? i am currently doing python and i am near done with this course. I am moving to Visual Basics.
If those are really your writings, you can add them as tutorials, but not in this particular thread!
Edited by vegaseat because: n/a
sneekula 969 Nearly a Posting Maven
You don't always sort a list of strings alphabetically, sometimes you want to sort by the length of the string:
# sort a list of strings by length of string
text = "I have taken a vow of poverty to annoy me send money"
mylist = text.split()
print( "Original list: \n%s\n" % mylist )
mylist_sorted = sorted(mylist, key=len, reverse=True)
print( "Sorted by length of word: \n%s" % mylist_sorted )
"""my result -->
Original list:
['I', 'have', 'taken', 'a', 'vow', 'of', 'poverty', 'to', 'annoy',
'me', 'send', 'money']
Sorted by length of word:
['poverty', 'taken', 'annoy', 'money', 'have', 'send', 'vow', 'of',
'to', 'me', 'I', 'a']
In a similar fashion you can find the longest word in a list of words:
# find the longest word in a text
text = "I have taken a vow of poverty to annoy me send money"
# Python25 and higher allows key
word_list = text.split()
print( "The longest word is %s" % max(word_list, key=len) )
Edited by sneekula because: n/a
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Just some code I found which makes me scratch my head ...
# interesting use of string replace() function
# to sequencially replace a given marker with items in a tuple
# use for example *** as a marker
text = """\
*** item1
*** item2
*** item3
*** item4
"""
# len of tuple has to match number of *** markers
tup = tuple('ABCD')
new_text = text.replace('***', '%s)') % tup
print(new_text)
"""my result -->
A) item1
B) item2
C) item3
D) item4
"""
Here is a cute application ...
# use for example *** as a marker
text = """\
man who runs *** car gets ***
man who runs *** car gets ***
"""
# len of tuple has to match number of *** markers
tup = ('behind', 'exhausted', 'in front of', 'tired')
new_text = text.replace('***', '%s') % tup
print(new_text)
Edited by vegaseat because: len
TrustyTony 888 pyMod Team Colleague Featured Poster
Sorry, I do not like the style. Here is my counter proposal for same function:
from string import letters
text ="""
%s) item1
%s) item2
%s) item3
%s) item4
"""
# len of tuple has to match number of %s
new_text = text % tuple(letters[:text.count('%s')])
print(new_text)
"""my result -->
A) item1
B) item2
C) item3
D) item4
"""
Edited by TrustyTony because: Better count %s directly
TrustyTony 888 pyMod Team Colleague Featured Poster
Here is a cute application ...
# use for example *** as a marker text = """\ man who runs *** car gets *** man who runs *** car gets *** """ # len of tuple has to match number of *** markers tup = ('behind', 'exhausted', 'in front of', 'tired') new_text = text.replace('***', '%s') % tup print(new_text)
Missed this last time, my version here:
from string import letters
text = """man who runs %s car gets %s
""" *2
tup = ('behind', 'exhausted', 'in front of', 'tired')
new_text = text % tup
print(new_text)
Edited by TrustyTony because: n/a
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Another short look at the simplicity of Python class inheritance ...
# a look at Python's class constructor, method, instance
# inheritance, private variables/methods
# class names are captalized by convention to aid readability
# modified for Python3 formatted printing
class Cat:
# this is public to all instances of class Cat
cost = 100
# this is private to the class
__price = cost + cost * 0.25
# constructor
def __init__(self, num=1):
self.num = num
self.sound = "meow " * self.num
print(self.sound)
def own(self):
#print("I own %s cats" % self.num)
print("I own {:d} cats".format(self.num))
def paid(self):
self.total = self.__price * self.num
#print("I paid $%0.2f for my cats" % self.total)
print("I paid ${:0.2f} for my cats".format(self.total))
def kitten(self):
self.kit = 5
print("One cat just had {:d} kittens".format(self.kit))
return self.kit
class Dog:
# this is public
cost = 400
# this is private to the class
__price = cost + cost * 0.25
# constructor
def __init__(self, num=1):
self.num = num
self.sound = "woof " * self.num
print(self.sound)
def own(self):
#print("I own %s dogs" % self.num)
print("I own {:d} dogs".format(self.num))
def paid(self):
self.total = self.__price * self.num
#print("I paid $%0.2f for my dogs" % self.total
print("I paid ${:0.2f} for my dogs".format(self.total))
class Pets(Cat, Dog):
"""class Pets inherits class Cat and class Dog"""
# constructor
def __init__(self):
self.num = cat.num + dog.num
self.sound = cat.sound + dog.sound
print(self.sound)
def own(self):
#print("I own %s pets" % self.num)
print("I own {:d} pets".format(self.num))
def paid(self):
total = dog.total + cat.total
#print("I paid $%0.2f for my pets" % total)
print("I paid ${:0.2f} for my pets".format(total))
def update(self):
# notice how Pets inherited kitten() from class Cat
self.kit = self.kitten()
number = self.num + self.kit
#print("So now I have %s pets" % number)
print("So now I have {:d} pets".format(number))
cat = Cat(3)
cat.own()
cat.paid()
#cat.__price # this will give AttributeError, __price is private
"""
meow meow meow
I own 3 cats
I paid $375.00 for my cats
"""
print( '-'*30)
dog = Dog(2)
dog.own()
dog.paid()
"""
woof woof
I own 2 dogs
I paid $1000.00 for my dogs
"""
print('-'*30)
pets = Pets()
pets.own()
pets.paid()
"""
meow meow meow woof woof
I own 5 pets
I paid $1375.00 for my pets
"""
print('-'*30)
pets.update()
"""
One cat just had 5 kittens
So now I have 10 pets
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
A way to create a dictionary from a list of lists, and a look at module pprint applied to the display of a dictionary ...
# converting a list of lists to a dictionary
# and testing the result with module pprint
# (pprint will put the keys into alphabetical order)
# data lists
stock1 = ["Google","GOOG", 200, 549.88]
stock2 = ["Microsoft", "MSFT", 300, 26.50]
stock3 = ["Yahoo", "YHOO", 900, 16.82]
stock4 = ["Apple", "AAPL", 400, 188.00]
# create a list od lists
portfolio = [stock1, stock2, stock3, stock4]
# convert to ticker:(name, shares, price) dictionary
# using a generator expression
pf_dict = dict((st[1],(st[0], st[2], st[3])) for st in portfolio)
# or you can use a dictionary comprehension, new in Python3
#pf_dict = {st[1]:(st[0], st[2], st[3]) for st in portfolio}
print(pf_dict)
"""my manually prettified result -->
{'GOOG': ('Google', 200, 549.88),
'YHOO': ('Yahoo', 900, 16.82),
'AAPL': ('Apple', 400, 188.0),
'MSFT': ('Microsoft', 300, 26.5)}
"""
print('-'*50)
import pprint
# adjust width so this prints one key:value pair per line
# note that keys appear in alphabetical order ...
pprint.pprint(pf_dict, indent=0, width=50)
"""my result -->
{'AAPL': ('Apple', 400, 188.0),
'GOOG': ('Google', 200, 549.88),
'MSFT': ('Microsoft', 300, 26.5),
'YHOO': ('Yahoo', 900, 16.82)}
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
This example shows the application of a default dictionary type to create an index of words in a text ...
# index words in a text by initial letter
# using collections.defaultdict(),
# a more memory efficient subset of dict()
# collections.defaultdict() needs Python25+
import collections
import pprint
text = "my younger sister often washes her white shirts once a week"
# create a word list of lower case words first
words = text.lower().split()
# mutliple values go into a list
index = collections.defaultdict(list)
for word in words:
index_letter = word[0]
index[index_letter].append(word)
print("default dictionary:")
print(index)
print('-'*60)
print("regular dictionary:")
print(dict(index))
print('-'*60)
print("pprint the regular dictionary:")
# adjust width to print key:value to suit your taste
# (also shows keys in alphabetical order)
pprint.pprint(dict(index), indent=0, width=75)
# you cam also pprint to a text file ...
fout = open("pprint_test1.txt", "w")
pprint.pprint(dict(index), fout, indent=0, width=75)
fout.close()
"""my output -->
default dictionary:
defaultdict(<type 'list'>, {'a': ['a'], 'h': ['her'], 'm': ['my'],
'o': ['often', 'once'], 's': ['sister', 'shirts'], 'w': ['washes',
'white', 'week'], 'y': ['younger']})
------------------------------------------------------------
regular dictionary:
{'a': ['a'], 's': ['sister', 'shirts'], 'w': ['washes', 'white',
'week'], 'y': ['younger'], 'h': ['her'], 'm': ['my'],
'o': ['often', 'once']}
------------------------------------------------------------
pprint the regular dictionary:
{'a': ['a'],
'h': ['her'],
'm': ['my'],
'o': ['often', 'once'],
's': ['sister', 'shirts'],
'w': ['washes', 'white', 'week'],
'y': ['younger']}
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Dictionaries are useful for designing a menu ...
# use a dictionary of functions for a selectable menu
# that calls these functions
def func_1():
print(" func_1 called, Load")
def func_2():
print(" func_2 called, Save")
def func_3():
print(" func_3 called, Add Phone Number")
def func_4():
print(" func_4 called, View Phone Numbers")
menu_dict = {
1:["func_1()", " 1) Load"],
2:["func_2()", " 2) Save"],
3:["func_3()", " 3) Add Phone Number"],
4:["func_4()", " 4) View Phone Numbers"],
5:["", " 5) Exit"]
}
while True:
print("\nSelect an Option:\n")
for k in range(1, 6):
# print list's element 1 for key=k
print(menu_dict[k][1])
try:
# can be used for Python2 or Python3
choice = int(input("\nEnter choice (1-5): " ))
except:
choice = 0
if choice < 5 and choice in menu_dict:
# evaluate to function call
eval(menu_dict[choice][0])
elif choice == 5:
break
print("\nEnd of program!")
Edited by vegaseat because: call
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
A dictionary with (x,y,z,...):value pairs is a simple way to represent and use a multidimensional array. Here an example of a 3D array ...
# create a 3x4x2 3D-array using a dictionary with (x,y,z):value pairs
import pprint
# initializes values to zero
arr3d = dict(((x,y,z), 0) for x in range(3) for y in range(4)
for z in range(2))
# Python3 has dictionary comprehension to simplify this
#arr3d = {(x,y,z):0 for x in range(3) for y in range(4) for z in range(2)}
pprint.pprint(arr3d)
"""my output -->
{(0, 0, 0): 0,
(0, 0, 1): 0,
(0, 1, 0): 0,
(0, 1, 1): 0,
(0, 2, 0): 0,
(0, 2, 1): 0,
(0, 3, 0): 0,
(0, 3, 1): 0,
(1, 0, 0): 0,
(1, 0, 1): 0,
(1, 1, 0): 0,
(1, 1, 1): 0,
(1, 2, 0): 0,
(1, 2, 1): 0,
(1, 3, 0): 0,
(1, 3, 1): 0,
(2, 0, 0): 0,
(2, 0, 1): 0,
(2, 1, 0): 0,
(2, 1, 1): 0,
(2, 2, 0): 0,
(2, 2, 1): 0,
(2, 3, 0): 0,
(2, 3, 1): 0}
"""
print('-'*20)
# change some values, basically assign to index
arr3d[2, 1, 0] = 550
arr3d[1, 0, 1] = 1700
# or ...
ix = (0, 0, 0)
arr3d[ix] = 99
# or just ...
ix = 1, 1, 1
arr3d[ix] = 303
pprint.pprint(arr3d)
"""my output -->
{(0, 0, 0): 99,
(0, 0, 1): 0,
(0, 1, 0): 0,
(0, 1, 1): 0,
(0, 2, 0): 0,
(0, 2, 1): 0,
(0, 3, 0): 0,
(0, 3, 1): 0,
(1, 0, 0): 0,
(1, 0, 1): 1700,
(1, 1, 0): 0,
(1, 1, 1): 303,
(1, 2, 0): 0,
(1, 2, 1): 0,
(1, 3, 0): 0,
(1, 3, 1): 0,
(2, 0, 0): 0,
(2, 0, 1): 0,
(2, 1, 0): 550,
(2, 1, 1): 0,
(2, 2, 0): 0,
(2, 2, 1): 0,
(2, 3, 0): 0,
(2, 3, 1): 0}
"""
print('-'*20)
# get a specific value from a given index
print(arr3d[1, 1, 1]) # 303
# or ...
ix = 0, 0, 0
print(arr3d[ix]) # 99
print('-'*20)
# get the lowest and highest key
low = min(arr3d.keys()) # --> (0, 0, 0)
heigh = max(arr3d.keys()) # --> (2, 3, 1)
# show values
print( "ix=%s val=%s" % (low, arr3d[low]) )
print( "ix=%s val=%s" % (heigh, arr3d[heigh]) )
# get the heighest value in the array
print(max(arr3d.values())) # 1700
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
This code shows how to present a dictionary sorted by key and by value ...
# print out a key:value pair dictionary sorted by key then by value
# modified to work with Python2 and Python3
from operator import itemgetter
d = { 'a': 4, 'c': 3, 'b': 12, 'd': 2 }
print("Original dictionary (hashed keys):")
print(d)
print('-'*20)
print("Sorted by key:")
# item k at index 0 is default for sort
for k, v in sorted(d.items()):
print( "%r: %s" % (k, v) )
print('-'*20)
print("Sorted by value:")
# itemgetter(1) implies v
for k, v in sorted(d.items(), key=itemgetter(1)):
print( "%r: %s" % (k, v) )
"""my output -->
Original dictionary (hashed keys):
{'a': 4, 'c': 3, 'b': 12, 'd': 2}
--------------------
Sorted by key:
'a': 4
'b': 12
'c': 3
'd': 2
--------------------
Sorted by value:
'd': 2
'c': 3
'a': 4
'b': 12
"""
TrustyTony 888 pyMod Team Colleague Featured Poster
Dictionaries are useful for designing a menu ...
Or you might prefer to use tuple (fixed value lists) of pairs of real function value and menu text, no eval required. Here I chose also to use 0 for exit and make while test meaningful. This code also automatically adapts to count of menu items.
from __future__ import print_function ## make Python2 print Python3-like
# functions for menuactions
def func_1():
print(" func_1 called, Load")
def func_2():
print(" func_2 called, Save")
def func_3():
print(" func_3 called, Add Phone Number")
def func_4():
print(" func_4 called, View Phone Numbers")
functionmenu=(
(func_1, "Load"),
(func_2, "Save"),
(func_3, "Add Phone Number"),
(func_4, "View Phone Numbers"),
('', "Exit"))
menuitemcount=len(functionmenu)
choice=True
while choice:
print("\nSelect an Option:\n")
# enumerate gives choicenumber - 1 (zerobased),
# functionmenu is tuple, we use only second value from that
for choice,(_,text) in enumerate(functionmenu[:-1]):
print(choice+1, end='')
print(')', text)
print('0) '+functionmenu[-1][1]) ## exit item last in functionmenu
try:
# can be used for Python2 or Python3
choice = int(input("\nEnter choice (1-%i or 0): " % (menuitemcount-1)))
except:
print('Invalid menu choice')
continue
print()
if 1 <= choice < menuitemcount:
# call function no eval required
func,_= functionmenu[choice-1] ## first part in tuple, with zerobased index
func()
elif choice: print ('Wrong number for choice') ## not choice == (choice == 0) => exit
print("End of program!")
exit
Edited by TrustyTony because: n/a
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Another example of a dictionary presentation sorted by the index of a value_list ...
# sorting a key:value_list dictionary by value_list index
# create a id:[name, gpa, major] dictionary
data = {
'1234': ['Matt', '3.5', 'CS'],
'1000': ['John', '4.0', 'Music'],
'1023': ['Leon', '3.1', 'PreMed'],
'1001': ['Paul', '3.9', 'Music'],
'9000': ['Kris', '2.5', 'Business']
}
print("Original data (hashed key = id):")
for id in data:
print( "%r: %s" % (id, data[id]) )
"""my output -->
Original data (hashed key = id):
'1234': ['Matt', '3.5', 'CS']
'9000': ['Kris', '2.5', 'Business']
'1001': ['Paul', '3.9', 'Music']
'1023': ['Leon', '3.1', 'PreMed']
'1000': ['John', '4.0', 'Music']
"""
print('-'*40)
print("Sorted by GPA value:")
# sort by index in value list, here GPA at value_list index 1
for id in sorted(data, key=lambda x: data[x][1]):
print( "%r: %s" % (id, data[id]) )
"""my output -->
Sorted by GPA value:
'9000': ['Kris', '2.5', 'Business']
'1023': ['Leon', '3.1', 'PreMed']
'1234': ['Matt', '3.5', 'CS']
'1001': ['Paul', '3.9', 'Music']
'1000': ['John', '4.0', 'Music']
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Looking up a dictionary using the key is simple, but to look it up using the value is just slightly more involved. Here is a class that will do either look up for you ...
# look up a key:value dictionary by key and by value
class DictLookup(dict):
"""
inherits dict
a dictionary class which can look up values by key, and keys by value
"""
def __init__(self, items=[]):
dict.__init__(self, items)
def value(self, value):
"""returns a list of keys matching the value argument"""
return [item[0] for item in self.items() if item[1] == value]
def key(self, key):
return self[key]
# test the module
# this code block will be ignored if imported as a module
if __name__ == '__main__':
# a short dictionary of chemical symbols for the test
symbol_dic = {
'C': 'carbon',
'H': 'hydrogen',
'N': 'nitrogen',
'Li': 'lithium',
'Be': 'beryllium',
'B': 'boron'
}
# create an instance
look = DictLookup(symbol_dic)
value = "nitrogen"
key_symbol = "N"
print(look.value(value)) # ['N']
print(look.key(key_symbol)) # nitrogen
print('-'*20)
# another go ...
value = "boron"
key_symbol = "B"
print(look.value(value)) # ['B']
print(look.key(key_symbol)) # boron
Edited by vegaseat because: look up
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
In Python you can combine functions to form a new functions. Here is an example of combining two functions ...
# combining functions in Python
def combine_two(f1, f2):
"""
combine two functions f1 and f2
having arguments *a
"""
def inner(*a):
return f1(f2(*a))
return inner
def reverse(s):
"""reverse string s"""
return s[::-1]
def uppercase(s):
"""convert string s to all upper case"""
return s.upper()
# combine the functions reverse, uppercase
# creating a new function rev_up()
rev_up = combine_two(reverse, uppercase)
print(rev_up('hello world!')) # !DLROW OLLEH
TrustyTony commented: Nice trick +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Python allows decorators to be attached to functions, so they can be monitored ...
# using an accumulator decorator to count how many times
# a function has been called (can be used for debugging)
# note how the decorator is applied directly above the
# function code using a '@' prefix
def accumulate(func, start=0):
"""
use this decorator function keep track of how
many times function func has been called
"""
cnt = [start]
def inner(*arg):
"""*arg are the arguments of func(*arg)"""
cnt[0] += 1
return cnt[0], func(*arg)
return inner
@accumulate
def funk(s):
return s*2
print("Showing function call count and result tuple:")
print(funk("bah"))
print(funk("hum"))
print(funk("bug"))
"""result >>>
Showing function call count and result tuple:
(1, 'bahbah')
(2, 'humhum')
(3, 'bugbug')
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Here we are using a class to create a decorator. The Memoize decorator is very useful in speeding up recursive functions ...
# applying a memoize decorator to a recursive function
# and timing to show the improvement in speed
# keyword args allowed
# tested with Python 2.6.5 and Python 3.1.2
import timeit
class Memoize(object):
"""
use as a decorator to avoid repeating calculations
previously done by the decorated function
(allows functions with keyword arguments)
"""
def __init__(self,f):
self.f = f
self.memo = {}
def __call__(self, *args, **kwargs):
# allows keyword args with some performance cost
kws = tuple(kwargs.items())
if (args,kws) in self.memo:
return self.memo[(args,kws)]
result = self.f(*args, **kwargs)
self.memo[(args,kws)] = result
return result
def use_timeit(stmt, setup, passes=1000):
"""
use module timeit to time a statement stmt
(this can be a function call too)
setup gives information where too find variables/functions
(for time consuming functions use fewer passes to save time)
for instance ...
stmt = 'myfunction(x)'
setup = 'from __main__ import myfunction, x'
"""
t = timeit.Timer(stmt=stmt, setup=setup)
# doing 10 passes * 100000 gives the time in microseconds/pass
elapsed = (1000000//passes * t.timeit(number=passes))
print( "Function '%s' takes %0.3f micro-seconds/pass" % \
(stmt, elapsed) )
@Memoize
def fibo1(n):
"""
use recursion to get Fibonacci number for n
not very efficient because of the many function calls
"""
if n < 2:
return n
else:
return fibo1(n - 1) + fibo1(n - 2)
stmt1 = 'fibo1(n=30)'
setup1 = 'from __main__ import fibo1'
passes1 = 3
use_timeit(stmt1, setup1, passes1)
# testing output ...
print(fibo1(n=30)) # 832040
"""result >>>
with the @Memoize decorator ...
Function 'fibo1(n=30)' takes 91.496 micro-seconds/pass
832040
without (simply comment out) the @Memoize decorator ...
Function 'fibo1(n=30)' takes 1167785.588 micro-seconds/pass
832040
"""
TrustyTony commented: Usefull as long as multiple arguments don't change too much +1
lrh9 95 Posting Whiz in Training
Very cool.
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
For those of you who want to use the more restrictive, but memory efficient C type array, Python has module array. Here are some experiments with module array ...
# experimenting with Python's array type
# elements are restricted to one data type
# similar to a C array
# modified to work with Python2 or Python3
import array
# create an array of characters
# there is a difference between Python2 and Python3
try:
# Python2 typecode for a 1 byte character is 'c'
char_array = array.array('c', 'hello')
except ValueError:
# Python3 typecode for a 2 byte unicode character is 'u'
char_array = array.array('u', 'hello')
print(char_array[0]) # h
print(char_array)
"""
Python2 --> array('c', 'hello')
Python3 --> array('u', 'hello')
"""
print(char_array * 2)
"""
Python2 --> array('c', 'hellohello')
Python3 --> array('u', 'hellohello')
"""
# turn the array into a list
print(list(char_array)) # ['h', 'e', 'l', 'l', 'o']
# or ...
print(char_array.tolist()) # ['h', 'e', 'l', 'l', 'o']
# you can iterate directly
for c in char_array:
print(c)
# convert to a string
print(''.join(char_array)) # hello
# or ...
print(char_array.tostring())
"""
Python2 --> hello
Python3 --> b'h\x00e\x00l\x00l\x00o\x00'
"""
# add a character in place
char_array.extend('!')
print(char_array)
"""
Python2 --> array('c', 'hello')
Python3 --> array('u', 'hello')
"""
# reverse in place
char_array.reverse()
print(char_array)
"""
Python2 --> array('c', '!olleh')
Python3 --> array('u', '!olleh')
"""
print('-'*30)
# typecode for a 2 byte unsigned integer is 'i'
# (a 4 byte unsigned long integer code is 'l')
int_array = array.array('i',[2, 4, -11])
print(int_array[2]) # -11
print(int_array) # array('i', [2, 4, -11])
print(list(int_array)) # [2, 4, -11]
print(sum(int_array)) # -5
print('-'*30)
# typecode for a 8 byte floating point number (double) is 'd'
# (a 4 byte floating point number is 'f')
float_array = array.array('d', [1.41, 2.79, 3.14])
print(float_array[2]) # 3.14
print(float_array.typecode) # d
print(float_array.itemsize) # 8 (bytes in item)
# using buffer_info() to get (address, length) tuple
id, len = float_array.buffer_info()
sf = "float_array starts at memory address %d and has %d bytes"
print(sf % (id, len * float_array.itemsize))
"""
float_array starts at memory address 11543456 and has 24 bytes
"""
#help('array')
wolfeater017 0 Light Poster
The module pygame makes it easy to load, display and move images around the screen ...
# experiments with module pygame # free from: http://www.pygame.org/ # load, display and move an image import pygame as pg # initialize pygame pg.init() # pick an image you have (.bmp .jpg .png .gif) # if the image file is not in the working folder, # use the full pathname like "C:/Images/gifs/Pooh.gif" image_file = "Pooh.gif" # RGB color tuple used by pygame white = (255, 255, 255) # create a 300x300 white screen screen = pg.display.set_mode((300,300)) screen.fill(white) # load the image from a file # convert() unifies the pixel format for faster blit image = pg.image.load(image_file).convert() # draw image, position the image ulc at x=50, y=20 screen.blit(image, (50, 20)) # get the rectangle the image occupies # rec(x, y, w, h) start_rect = image.get_rect() # set up the timed event loop x = 0 y = 0 clock = pg.time.Clock() keepGoing = True while keepGoing: # set rate of move clock.tick(30) for event in pg.event.get(): # quit when user clicks on window x if event.type == pg.QUIT: keepGoing = False # move the image ... x += 1 y += 1 # stop when x exceeds limit if x > 270: keepGoing = False image_rect = start_rect.move(x, y) # this erases the old sreen with white screen.fill(white) # put the image on the screen at new location screen.blit(image, image_rect) # update screen pg.display.flip()
What is the working file, and how can you put stuff in it?
Editor's note:
Please follow the rules of this thread ...
The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!
Edited by vegaseat because: rules
HiHe 174 Junior Poster
The Python module glob is a real help in listing files you are interested in:
# use module glob to list filenames and pathnames
# glob takes care of upper/lower case variations
# works with Python2 and Python3
import glob
import os
# all files (full path names) in a given directory
directory = r"C:\Temp\*.*"
for path in glob.glob(directory):
print( path )
print( '-'*40 )
# all files (split off file names) in a given directory
directory = r"C:\Temp\*.*"
for path in glob.glob(directory):
dirname, filename = os.path.split(path)
print( filename )
print( '-'*40 )
# all files (full path names) in the next level subdirectories
subdirectories = r"C:\Temp\*\*.*"
for path in glob.glob(subdirectories):
print( path )
print( '-'*40 )
# only .txt files (full path names) in a given directory
directory_txt = r"C:\Temp\*.txt"
for path in glob.glob(directory_txt):
print( path )
print( '-'*40 )
# only .txt and .exe files (full path names) in a given directory
directory_txt = r"C:\Temp\*.txt"
directory_exe = r"C:\Temp\*.exe"
for path in glob.glob(directory_txt) + glob.glob(directory_exe):
print( path )
print( '-'*40 )
# only .py file names (not full path) in the working directory
for fname in glob.glob("*.py"):
print( fname )
print( '-'*40 )
# only .py file names starting with 'f' in the working directory
for fname in glob.glob("f*.py"):
print( fname )
print( '-'*40 )
# only .txt file names in the working directory
# sorted, case insensitive
for fname in sorted(glob.glob("*.txt"), key=str.lower):
print( fname )
-ordi- 6 Junior Poster in Training
import yaml
file = open('file.yaml', 'r')
d_yaml = yaml.load(file.read())
file.close
for _data in d_yaml:
a = [variable['text'] for variable in _data['text']]
i = _data['info'][0]['info']
p = _data['info_o'][0]['info_o']
print str(a) + '\n'
print str(i) + '\n'
print str(p)
- name: name1
text:
- text: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
- text: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
info:
- info: |
<html><body>
<br /> fffffffffffffffffffffffffffffffffffffffffff
<br /> ffffffffffffffffffffffffffffffffffffffffff
<br /> fffffffffffffffffffffffffffffffffffffffffffff</body>
<br /> fffffffffffffffffffffffffffffffffffffffffff<br />
</html>
info_o:
- info_o: eeeeeeeeeeeeeeeeeeeeeeeeeee
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
In the odd and even world of integer numbers the bitwise operators | and & reign supreme ...
# exploring bitwise operators | (or) and & (and)
def next_odd(n):
"""
use n|1 to turn an even integer n into the next odd integer
| is the bitwise or operator
"""
return n|1
print(next_odd(6)) # 7
print(next_odd(5)) # 5
def is_odd(n):
"""
use n&1 to check if an integer n is odd
& is the bitwise and operator
"""
if n&1:
return True
else:
return False
print(is_odd(6)) # False
print(is_odd(5)) # True
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
The Python module string has a class Template that allows an easy way to work on templates ...
# exploring Python module string templating
# needs Python 2.4 or higher
import string
def change_text(template, sub_dictionary):
t = string.Template(template)
return t.substitute(sub_dictionary)
template = 'The $animal says "$sound, my name is $name!"'
# create dictionaries for each animal
d_cow = dict(animal='cow', sound='mooh', name='Hilda')
d_dog = dict(animal='dog', sound='woof', name='Rover')
d_cat = dict(animal='cat', sound='meow', name='George')
for animal_dict in (d_cow, d_dog, d_cat):
print(change_text(template, animal_dict))
""" result >>>
The cow says "mooh, my name is Hilda!"
The dog says "woof, my name is Rover!"
The cat says "meow, my name is George!"
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Splitting a text into its sentences takes a little care ...
# split a text into a list of sentences
def sentence_split(text, seps=".?!"):
"""
split a text string into a list of sentences
assumes sentences end with characters given in seps
also takes care of new line characters and
periods in floating point numbers
"""
sentence_list = []
sentence = ""
# ix allows for look ahead
for ix, c in enumerate(text):
# replace the newline character with a space
if c == '\n':
c = ' '
# build up the sentence string
sentence += c
# look ahaed to next character
if ix < len(text)-1:
next_c = text[ix+1]
# sentences end with .?!, take care of floats
if c in ('.?!') and not next_c.isdigit():
# sentence complete, append to list
sentence_list.append(sentence.strip())
# reset to new sentence
sentence = ""
return sentence_list
# a test text containing sentences ending with .?! characters
# and also containing a floating point number
text = """\
Guido van Rossum is the creator of Python. Why does the Python
community refer to him as BDFL? "Benevolent Dictator For Life"
is from a Monty Python skit! He moved from the Netherlands to
the USA in 1995. Guido lives in Silicon Valley now, working
for Google. He spends about 50.12% of his time on Python!
"""
sentence_list = sentence_split(text)
import pprint
pprint.pprint(sentence_list)
""" result >>>
['Guido van Rossum is the creator of Python.',
'Why does the Python community refer to him as BDFL?',
'"Benevolent Dictator For Life" is from a Monty Python skit!',
'He moved from the Netherlands to the USA in 1995.',
'Guido lives in Silicon Valley now, working for Google.',
'He spends about 50.12% of his time on Python!']
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
The help() feature of Python is very nice, but maybe you want to save the result to a file. Here is one way to accomplish this ...
# pipe the output of Python help() to a string
import subprocess
code_str = """\
help("print")
"""
# save the code
filename = "help_code.py"
fout = open(filename, "w")
fout.write(code_str)
fout.close()
# execute the .py code and pipe the result to a string
# give the full path of python.exe (here Windows path)
test = "D:/Python26/python.exe -u " + filename
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
# important, wait for external program to finish
process.wait()
print process.returncode # 0 = success, optional check
# read the result to a string
help_str = process.stdout.read()
# the result of the code is now in help_str
print('-'*70)
print(help_str) # test
# optionally write to a file
# change the filename as needed
fname = "help_print.txt"
fout = open(fname, "w")
fout.write(help_str)
fout.close()
print('-'*70)
print("file %s written" % fname)
Simpler ...
# simplified version of sending help() output to a file
import sys
# save present stdout
out = sys.stdout
fname = "help_print7.txt"
# set stdout to file handle
sys.stdout = open(fname, "w")
# run your help code
# its console output goes to the file now
help("print")
sys.stdout.close()
# reset stdout
sys.stdout = out
Edited by vegaseat because: sys.stdout
JDuch 0 Newbie Poster
It works great.
Thank you very much
kctan 0 Newbie Poster
For beginner who would like some practice on your python programming, you may try this site:
http://pyschools.appspot.com
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Rumor has it that module py2exe has stopped updating. The good news is that a similar module cx_freeze is still quite active. These modules are used to package Python programs into an executable package. Here is an example of console program setup ...
"""
con_setup.exe
Using cx_freeze from:
http://cx-freeze.sourceforge.net/
with Python31 to package a console program to an executable file
(.exe in Windows OS).
Might want to put a console-wait-line in at the end of your program.
Put this setup program and your console program file into the same
directory. Change the filename in this setup program and also edit
name, version and description in setup() if you so desire.
Run the build process by running the command:
python con_setup.py build
A directory 'build' is created with a subdirectory 'exe.win32-3.1'
containing all the files needed for distribution including the
.exe file named after the console program file.
The total distribution has a size of about 4.2 Mb.
"""
from cx_Freeze import setup, Executable
# change the filename to your program file
filename = "99BottlesOfBeer3.py"
setup(
name = "99Bottles",
version = "1.0",
description = "console cx_Freeze script",
executables = [Executable(filename)])
If you have a Tkinter program, then you need some special considerations ...
"""
tk_setup.exe
Using cx_freeze from:
http://cx-freeze.sourceforge.net/
with Python31 to package a Tkinter GUI toolkit program to an
executable file (.exe in Windows OS).
Put this setup program and your Tkinter program file into the same
directory. Change the filename in this setup program and also edit
name, version and description in setup() if you so desire.
Run the build process by running the command:
python tk_setup.py build
A directory 'build' is created with a subdirectory 'exe.win32-3.1'
containing all the files needed for distribution including the
.exe file named after the Tkinter program file.
Tkinter needs some special considerations (Windows OS):
1) add this line to your Tinter program import tkinter._fix
2) from directory 'tcl' copy subdirectories 'tcl8.5' and 'tk8.5'
to the 'exe.win32-3.1' distribution directory
The total distribution has a size of about 11.1 MB
"""
import sys
from cx_Freeze import setup, Executable
# change the filename to your program file
filename = "tk_calculator2.py"
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "Calculator2",
version = "1.0",
description = "cx_Freeze Tkinter script",
executables = [Executable(filename, base=base)])
This shows you a typical Tkinter program modified for cx_freeze ...
# a tiny Tkinter calculator showing the
# use of the new Python25 partial function
# needs Python25 or higher
from functools import partial
# Python3
import tkinter as tk
import tkinter._fix # needed for cx_freeze
def click(key):
global memory
if key == '=':
# avoid division by integer
if '/' in entry.get() and '.' not in entry.get():
entry.insert(tk.END, ".0")
# guard against the bad guys abusing eval()
str1 = "-+0123456789."
if entry.get()[0] not in str1:
entry.insert(tk.END, "first char not in " + str1)
# here comes the calculation part
try:
result = eval(entry.get())
entry.insert(tk.END, " = " + str(result))
except:
entry.insert(tk.END, "--> Error!")
elif key == 'C':
entry.delete(0, tk.END) # clear entry
elif key == '->M':
memory = entry.get()
# extract the result
if '=' in memory:
ix = memory.find('=')
memory = memory[ix+2:]
root.title('M=' + memory)
elif key == 'M->':
entry.insert(tk.END, memory)
elif key == 'neg':
if '=' in entry.get():
entry.delete(0, tk.END)
try:
if entry.get()[0] == '-':
entry.delete(0)
else:
entry.insert(0, '-')
except IndexError:
pass
else:
# previous calculation has been done, clear entry
if '=' in entry.get():
entry.delete(0, tk.END)
entry.insert(tk.END, key)
root = tk.Tk()
root.title("My Calculator PF")
# this also shows the calculator's button layout
btn_list = [
'7', '8', '9', '*', 'C',
'4', '5', '6', '/', 'M->',
'1', '2', '3', '-', '->M',
'0', '.', '=', '+', 'neg' ]
# create all buttons with a loop
r = 1
c = 0
for b in btn_list:
rel = 'ridge'
# partial takes care of function and argument
cmd = partial(click, b)
tk.Button(root, text=b, width=5, relief=rel,
command=cmd).grid(row=r, column=c)
c += 1
if c > 4:
c = 0
r += 1
# use Entry widget for an editable display
entry = tk.Entry(root, width=33, bg="yellow")
entry.grid(row=0, column=0, columnspan=5)
root.mainloop()
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.