Starting Python

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply   View First Unread View First Unread

Join Date: Oct 2004
Posts: 4,157
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 952
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #191
Sep 6th, 2009
This class can be used to toggle between True and False, but can easily be changed to count calls ...
  1. # a class to allow you to toggle between True and False
  2.  
  3. class Static:
  4. """toggle between True and False"""
  5. flag = False
  6. # decorator allows you to simply call Static.toggle()
  7. @classmethod
  8. def toggle(self):
  9. self.flag = not self.flag
  10. return self.flag
  11.  
  12. for k in range(6):
  13. print( '%d) flag = %s' % (k+1, Static.toggle()) )
  14.  
  15. """my output -->
  16. 1) flag = True
  17. 2) flag = False
  18. 3) flag = True
  19. 4) flag = False
  20. 5) flag = True
  21. 6) flag = False
  22. """
Last edited by vegaseat; Sep 6th, 2009 at 10:24 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 984
Reputation: Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough 
Solved Threads: 223
Gribouillis's Avatar
Gribouillis Gribouillis is offline Offline
Posting Shark

Re: Starting Python

 
2
  #192
Sep 8th, 2009
Still another way
  1. class Static(object):
  2. def __init__(self, **kwd):
  3. self.__dict__.update(kwd)
  4.  
  5. def toggle(static=Static(flag=True)):
  6. static.flag = not static.flag
  7. return static.flag
  8.  
  9. for i in range(5):
  10. print(toggle())
  11.  
  12. """ my output --->
  13. False
  14. True
  15. False
  16. True
  17. False
  18. """
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,305
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 179
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #193
Sep 17th, 2009
Just a little cosmetic code:
  1. # a simple way to display plural strings
  2.  
  3. def visits(n):
  4. # adds an s to 'time' if n > 1
  5. return "I visited you %d time%s" % (n, ['','s'][n>1])
  6.  
  7. for n in range(1, 4):
  8. print( visits(n) )
  9.  
  10. """my result -->
  11. I visited you 1 time
  12. I visited you 2 times
  13. I visited you 3 times
  14. """
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,305
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 179
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
1
  #194
Sep 21st, 2009
The ultimate user friendly Temperature Converter program. If you put an 'F' or 'f' on the end of the temperature you enter it will give you Celsius. Otherwise it simply assumes you entered a Celsius value and want Fahrenheit:
  1. # a Fahrenheit/Celsius program easy on the user
  2. # tested with Python25
  3. # snee
  4.  
  5. def f2c(t):
  6. """given t Fahrenheit return Celsius"""
  7. return 5/9.0 * (t - 32)
  8.  
  9. def c2f(t):
  10. """given t Celsius return Fahrenheit"""
  11. return 9/5.0 * t + 32
  12.  
  13. def extract_number(s):
  14. """
  15. extract the numeric value from string s
  16. (the string can contain only one numeric value)
  17. return the number or None
  18. """
  19. ts = ""
  20. for c in s:
  21. if c in '1234567890.-':
  22. ts += c
  23. if ts:
  24. # convert number to int or float
  25. return eval(ts)
  26. else:
  27. return None
  28.  
  29. def pick_cf(s):
  30. """given a numeric string s select f or c calculation"""
  31. t = extract_number(s)
  32. print('')
  33. if not t:
  34. print("***need a number***")
  35. return False
  36. if 'f' in s.lower():
  37. print( "%0.2f Fahrenheit is %0.2f Celsius" % (t, f2c(t)) )
  38. else:
  39. print( "%0.2f Celsius is %0.2f Fahrenheit" % (t, c2f(t)) )
  40. return True
  41.  
  42. prompt = """
  43. Enter a temperature ending with an F to calculate Celsius
  44. otherwise the temperature is assumed to be Celsius and will
  45. give the result in Fahrenheit (press just enter to quit): """
  46.  
  47. while True:
  48. s = raw_input(prompt)
  49. if not s:
  50. break
  51. s = pick_cf(s)
Yes Gloria, if you entered $12.99 it will give you the Fahrenheit temperature of 12.99 Celsius.
Last edited by sneekula; Sep 21st, 2009 at 6:56 pm.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,157
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 952
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite

Re: Starting Python

 
1
  #195
Sep 22nd, 2009
Here is an example how to present the elements of a list or tuple in a nice tabular format ...
  1. # create a table string from a list
  2.  
  3. def create_table(mylist, itemsperline=5):
  4. """
  5. given a list mylist return a string containing
  6. itemsperline of the list items in each line
  7. """
  8. table = ""
  9. for ix, element in enumerate(mylist):
  10. # add new line character after every itemsperline elements
  11. if ix % itemsperline == 0 and ix != 0:
  12. table += '\n'
  13. # use string formatting (adjust to your needs)
  14. # if length of element varies from 1 to 10 use for instance
  15. # table += "%-12s" % element
  16. table += "%-4s" % element
  17. return table
  18.  
  19.  
  20. # create the test list
  21. mylist = [x+y for x in 'abcdef' for y in '1234']
  22.  
  23. #print mylist # test ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', ... ]
  24.  
  25. itemsperline = 4
  26. table = create_table(mylist, itemsperline)
  27.  
  28. print(table)
  29.  
  30. """my result -->
  31. a1 a2 a3 a4
  32. b1 b2 b3 b4
  33. c1 c2 c3 c4
  34. d1 d2 d3 d4
  35. e1 e2 e3 e4
  36. f1 f2 f3 f4
  37. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,157
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 952
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite
 
0
  #196
28 Days Ago
Here is an example of how you can create a C type switch/case construct using a Python dictionary ...
  1. # a simple reverse polish notation calculator
  2.  
  3. def do_operation(a, b, op):
  4. """
  5. here a dictionary combined with the
  6. lambda inline function acts like C switch/case
  7. a and b are numbers and op is a string
  8. """
  9. return {'+': lambda: a + b,
  10. '-': lambda: a - b,
  11. '*': lambda: a * b,
  12. '/': lambda: a / b
  13. }[op]()
  14.  
  15. # evaluate a reverse Polish notation string
  16. rev_pol = "12 3 *"
  17.  
  18. a, b , op = rev_pol.split()
  19. result = do_operation(float(a), float(b) , op)
  20.  
  21. print( "%s --> %s" % (rev_pol, result) ) # 12 3 * --> 36.0
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Nov 2009
Posts: 6
Reputation: wolf_london is an unknown quantity at this point 
Solved Threads: 0
wolf_london wolf_london is offline Offline
Newbie Poster
 
0
  #197
17 Days Ago
well done!when i went about learning python ,i used the a byte of python . i recommand two websites which are filled with the good ebooks for python .
http://www.onlinecomputerbooks.com/
http://www.bookfm.com
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,157
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 952
Moderator
vegaseat's Avatar
vegaseat vegaseat is online now Online
DaniWeb's Hypocrite
 
0
  #198
2 Days Ago
Combinations and Permutations are closely linked. The function shown here is a recursive generator function that returns permutations with selectable sample size ...
  1. # a permutation or combination does not repeat sample items
  2. # Python3 has a non-recursive combination function
  3. # via itertools.combinations(iterable, sample_size)
  4. # and a non-recursive permutation function
  5. # via itertools.permutations(iterable, sample_size=None)
  6. # vegaseat
  7.  
  8. def permutations(itr, n):
  9. """
  10. permutations(items, n) is a recursive generator function where
  11. itr is an iterable object like a list or string
  12. n is the sample size
  13. returns a list of nonrepeating sample size items
  14. n = len(itr) is the max sample size
  15. """
  16. if n == 0:
  17. yield []
  18. else:
  19. for k in range(len(itr)):
  20. # a recursive function
  21. for c in permutations(itr[:k] + itr[k+1:], n - 1):
  22. yield [itr[k]] + c
  23.  
  24. iterable = 'abc'
  25. sample_size = 2
  26. perm_list = list(permutations(iterable, sample_size))
  27.  
  28. # show as a list of lists
  29. print( perm_list )
  30.  
  31. print( '-'*50 )
  32.  
  33. # show as a list of strings
  34. print( ["".join(item) for item in perm_list] )
  35.  
  36. """ my result (sample size max - 1) -->
  37. [['a', 'b'], ['a', 'c'], ['b', 'a'],
  38. ['b', 'c'], ['c', 'a'], ['c', 'b']]
  39. --------------------------------------------------
  40. ['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
  41. """
Note: corrected post, see sneekula's post at ...
http://www.daniweb.com/forums/post10...ml#post1086335
Last edited by vegaseat; 12 Minutes Ago at 11:45 am. Reason: snee post
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



Similar Threads
Other Threads in the Python Forum


Views: 89814 | Replies: 197
Thread Tools Search this Thread



Tag cloud for code, hints, python, tricks, tutorial
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC