943,671 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 128880
  • Python RSS
You are currently viewing page 20 of this multi-page discussion thread; Jump to the first page
Sep 6th, 2009
0

Re: Starting Python

This class can be used to toggle between True and False, but can easily be changed to count calls ...
python Syntax (Toggle Plain Text)
  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.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Sep 8th, 2009
3

Re: Starting Python

Still another way
python Syntax (Toggle Plain Text)
  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. """
Reputation Points: 930
Solved Threads: 667
Posting Maven
Gribouillis is offline Offline
2,655 posts
since Jul 2008
Sep 17th, 2009
0

Re: Starting Python

Just a little cosmetic code:
python Syntax (Toggle Plain Text)
  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. """
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Sep 21st, 2009
2

Re: Starting Python

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:
python Syntax (Toggle Plain Text)
  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.
Reputation Points: 961
Solved Threads: 211
Nearly a Posting Maven
sneekula is offline Offline
2,413 posts
since Oct 2006
Sep 22nd, 2009
2

Re: Starting Python

Here is an example how to present the elements of a list or tuple in a nice tabular format ...
python Syntax (Toggle Plain Text)
  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. """
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 26th, 2009
0
Re: Starting Python
Here is an example of how you can create a C type switch/case construct using a Python dictionary ...
python Syntax (Toggle Plain Text)
  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
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Dec 8th, 2009
0
Re: Starting Python
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
Reputation Points: 10
Solved Threads: 0
Newbie Poster
wolf_london is offline Offline
6 posts
since Nov 2009
Dec 22nd, 2009
0
Re: Starting Python
Combinations and Permutations are closely linked. The function shown here is a recursive generator function that returns permutations with selectable sample size ...
python Syntax (Toggle Plain Text)
  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(seq, n):
  9. """
  10. permutations(seq, n) is a recursive generator function where
  11. seq 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(seq) is the max sample size
  15. """
  16. if n == 0:
  17. yield []
  18. else:
  19. for k in range(len(seq)):
  20. # a recursive function
  21. for p in permutations(seq[:k] + seq[k+1:], n - 1):
  22. yield [seq[k]] + p
  23.  
  24. def unique_combinations(seq, n):
  25. """
  26. unique_combinations(seq, n) is a recursive generator function
  27. where
  28. seq is an iterable object like a list or string
  29. n is the sample size
  30. returns a list of nonrepeating sample size items
  31. n = len(seq) is the max sample size
  32. """
  33. if n == 0:
  34. yield []
  35. else:
  36. for i in range(len(seq) - n + 1):
  37. # recursion
  38. for uc in unique_combinations(seq[i+1:], n - 1):
  39. yield [seq[i]] + uc
  40.  
  41.  
  42. iterable = 'abc'
  43. sample_size = 2
  44. perm_list = list(permutations(iterable, sample_size))
  45.  
  46. # show as a list of lists
  47. print( perm_list )
  48.  
  49. print( '-'*40 )
  50.  
  51. # show as a list of strings
  52. print( ["".join(item) for item in perm_list] )
  53.  
  54. print( '-'*40 )
  55.  
  56. comb_list = list(unique_combinations(iterable, sample_size))
  57.  
  58. # show as a list of lists
  59. print( comb_list )
  60.  
  61. print( '-'*40 )
  62.  
  63. # show as a list of strings
  64. print( ["".join(item) for item in comb_list] )
  65.  
  66. """ my result (sample size max - 1) -->
  67. [['a', 'b'], ['a', 'c'], ['b', 'a'],
  68. ['b', 'c'], ['c', 'a'], ['c', 'b']]
  69. ----------------------------------------
  70. ['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
  71. ----------------------------------------
  72. [['a', 'b'], ['a', 'c'], ['b', 'c']]
  73. ----------------------------------------
  74. ['ab', 'ac', 'bc']
  75. """
Note: corrected post, see sneekula's post at ...
http://www.daniweb.com/forums/post10...ml#post1086335
Last edited by vegaseat; Dec 25th, 2009 at 12:09 pm. Reason: snee post
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Dec 26th, 2009
1
Re: Starting Python
The Python module time has many interesting functions to process date and time related problems. Here is an example that shows how you can switch one date format to another format ...
Python Syntax (Toggle Plain Text)
  1. # convert one time format to another
  2.  
  3. import time
  4.  
  5. date_old = "08-Jan-2009"
  6.  
  7. # use strptime(string, format_str) to form a time tuple
  8. # (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)
  9. time_tuple = time.strptime(date_old, "%d-%b-%Y")
  10.  
  11. # use time.strftime(format_str, time_tuple) to create new format
  12. date_new = time.strftime("%m/%d/%y", time_tuple)
  13.  
  14. print( "New format = %s" % date_new )
  15. print( "Old format = %s" % date_old )
  16. print( "Time_tuple = %s" % time_tuple )
  17.  
  18. """my output -->
  19. New format = 01/08/09
  20. Old format = 08-Jan-2009
  21. Time tuple = (2009, 1, 8, 0, 0, 0, 3, 8, -1)
  22. """
Last edited by vegaseat; Dec 26th, 2009 at 10:41 am. Reason: Python3 modify
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Jan 31st, 2010
1
Re: Starting Python
One thing that I'm very glad I learned to do as a beginner and still use today - even though I'm probably still a beginner - is to have a basic file with code that is used more often than not in the script. I can copy this file each time I want to create a script and have several things I'd normally want to do in a polished script all ready done.

I call my file "base.py".

Python Syntax (Toggle Plain Text)
  1. #!/usr/bin/env python
  2.  
  3. version = '3.1.1'
  4.  
  5. def main():
  6. pass
  7.  
  8. if __name__ is "__main__":
  9. main()

The first line is called a "shebang" I think. I'm a Windows user, but as I understand it having this line in a script allows Linux users to execute the script more easily than if it wasn't included. Having the line doesn't alter program execution so it isn't necessary, but I do it out of consideration for Linux users when I publish code.

The variable "version" does not represent the script's version, but it is the version of Python I wrote the script in. I do this out of consideration for users who might be using different versions of Python.

The 'if __name__ is "__main__":' idiom allows a script to function as an executable script or a module. If the program is executed as a script, the __name__ attribute is "__main__" and the "main" function is called. However, if the script is imported then this code is not executed. The pass statement in the "main" function is necessary for it to be a valid function, and when I add code I usually leave it at the beginning so if I need to erase code it will still function without having to remove the "main" function.

Do you have any ideas or contributions?
Reputation Points: 106
Solved Threads: 35
Posting Whiz in Training
lrh9 is offline Offline
238 posts
since Oct 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: help with Quadratic Formula Code
Next Thread in Python Forum Timeline: First time using cx_Freeze





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC