Starting Python

Reply

Join Date: Aug 2005
Posts: 1,536
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 170
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: Starting Python

 
0
  #111
Jan 19th, 2008
An example for how to search a dictionary with key: value pairs for both the value and the key:
  1. # search a dictionary for key or value
  2.  
  3. def find_key(dic, val):
  4. """return the key of dictionary dic given the value"""
  5. return [k for k, v in symbol_dic.iteritems() if v == val][0]
  6.  
  7. def find_value(dic, key):
  8. """return the value of dictionary dic given the key"""
  9. return dic[key]
  10.  
  11. # test it out
  12. if __name__ == '__main__':
  13. # dictionary of chemical symbols
  14. symbol_dic = {
  15. 'C': 'carbon',
  16. 'H': 'hydrogen',
  17. 'N': 'nitrogen',
  18. 'Li': 'lithium',
  19. 'Be': 'beryllium',
  20. 'B': 'boron'
  21. }
  22.  
  23. print find_key(symbol_dic, 'boron') # B
  24. print find_value(symbol_dic, 'B') # boron
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
0
  #112
Jan 29th, 2008
Sometimes you just have to clear the display screen when you work with the Python command shell. This little function does that in both Windows or Linux:
  1. def clear_screen():
  2. """
  3. clear the screen in the command shell
  4. works on windows (nt, xp, Vista) or linux
  5. """
  6. import os
  7. os.system(['clear','cls'][os.name == 'nt'])
  8.  
  9. # test module out
  10. if __name__ == '__main__':
  11. import time
  12. print "some text on the screen for a few seconds"
  13. # wait 2.5 seconds
  14. time.sleep(2.5)
  15. # now clear the screen
  16. clear_screen()
  17. # wait
  18. time.sleep(1.5)
  19. print "test completed"
  20. raw_input("press enter to go on ")
You can save the whole module as clear_screen.py and import it into your program.
Last edited by ZZucker; Jan 29th, 2008 at 12:09 pm.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,009
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: 928
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #113
Jan 30th, 2008
Just an updated way to count the frequency of letters in a text ...
  1. # count the character frequency in a text:
  2. # create a list of unique (frequency, character) tuples
  3. # then sort and display highest frequency characters first
  4.  
  5. text = 'mississippi mudslide'
  6.  
  7. # create a list of characters from the text
  8. c_list = list(text)
  9.  
  10. # make a list of (frequency, char) tuples, use set() to avoid duplicates
  11. fc_list = [(c_list.count(c), c) for c in set(c_list) if c.isalpha()]
  12.  
  13. for item in sorted(fc_list, reverse=True):
  14. print "%s --> %s" % (item[1], item[0])
  15.  
  16. """
  17. my output -->
  18. s --> 5
  19. i --> 5
  20. p --> 2
  21. m --> 2
  22. d --> 2
  23. u --> 1
  24. l --> 1
  25. e --> 1
  26. """
You can rewrite the code to count words in a text.
The following code may not be simpler, but it is slightly faster then the set code ...
  1. # count the character frequency in a text
  2. # a slightly faster option using a dictionary instead of a set ...
  3. from operator import itemgetter
  4.  
  5. text = 'mississippi mudslide'
  6. d = {}
  7. for c in text:
  8. if c.isalpha():
  9. d[c] = d.get(c, 0) + 1
  10.  
  11. for k, v in sorted(d.items(), key=itemgetter(1), reverse=True):
  12. print "%s --> %s" % (k, v)
  13.  
  14. """
  15. my output -->
  16. i --> 5
  17. s --> 5
  18. d --> 2
  19. m --> 2
  20. p --> 2
  21. e --> 1
  22. l --> 1
  23. u --> 1
  24. """
Last edited by vegaseat; Jan 31st, 2008 at 2:35 am. Reason: dict
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
0
  #114
Feb 15th, 2008
You have two lists, one list with all the cities you wanted to visit in your life, and another list of cities you have already visited. Now you want to create a new list of cities you have not visited yet:
  1. # subtract/remove elements of one list from another
  2.  
  3. city = ['Lisbon', 'Paris', 'Reno', 'London', 'Oslo', 'Ypsilanti']
  4.  
  5. visited = ['Reno', 'Ypsilanti']
  6.  
  7. not_visited = [c for c in city if c not in visited]
  8. # order of remaining elements has not changed
  9. print not_visited
  10.  
  11. # simpler ...
  12. not_visited = list(set(city) - set(visited))
  13. # order of remaining elements has changed
  14. print not_visited
  15.  
  16. """
  17. my result --->
  18. ['Lisbon', 'Paris', 'London', 'Oslo']
  19. ['Paris', 'Oslo', 'London', 'Lisbon']
  20. """
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 28
Reputation: alexgv14 is an unknown quantity at this point 
Solved Threads: 0
alexgv14 alexgv14 is offline Offline
Light Poster

Re: Starting Python

 
0
  #115
Feb 23rd, 2008
Originally Posted by vegaseat View Post
One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.
  1. # a function to return the numeric content of a cost item
  2. # for instance $12.99 or -$123456789.01 (deficit spenders)
  3. def getVal(txt):
  4. if txt[0] == "$": # remove leading dollar sign
  5. txt = txt[1:]
  6. if txt[1] == "$": # could be -$xxx
  7. txt = txt[0] + txt[2:]
  8.  
  9. while txt: # select float or integer return
  10. try:
  11. f = float(txt)
  12. i = int(f)
  13. if f == i:
  14. return i
  15. return f
  16. except TypeError: # removes possible trailing stuff
  17. txt = txt[:-1]
  18. return 0
  19.  
  20. # test the function ...
  21. print getVal('-$123.45')
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
So, I was trying to go through this code and understand. But I have a few questions on it. And please bear with me I'm just starting to learn python.
  1. txt = txt[0] + txt[2:]

Why did you add the two together?

I'm also confused on that while loop. Why do you retrun i, f, and 0. And what exactly is it doing line by line.

Any help would be much appreciated.

Thanks

Please follow the rules as set forth in:
http://www.daniweb.com/forums/post104844-2.html

Don't mess up this thread, start your own thread in the forum! I will anwer your questions there once you do that.
Last edited by vegaseat; Feb 24th, 2008 at 10:42 pm. Reason: follow 'start your own thread' rule
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #116
Feb 29th, 2008
You can use the local variable dictionary vars() to create new variables on the fly:
  1. food = 'bread'
  2. vars()[food] = 123
  3. print bread # --> 123
Print vars() after line 1 and 2 to follow what's happening.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
0
  #117
Mar 3rd, 2008
A function to allow for a relatively secure input of dates:
  1. # a more secure way to enter a date
  2.  
  3. import datetime as dt
  4.  
  5. def enter_date():
  6. """
  7. asks to enter year, month and day and returns
  8. date info as <type 'datetime.datetime'>
  9. """
  10. def extract_date(s):
  11. try:
  12. # month given as a decimal number
  13. date = dt.datetime.strptime(s, "%d %m %Y")
  14. except:
  15. try:
  16. # month given as a 3 letter abreviation
  17. date = dt.datetime.strptime(s, "%d %b %Y")
  18. except:
  19. return None
  20. return date
  21.  
  22. while True:
  23. year = raw_input("Enter year (eg. 1979): ")
  24. # you can enter number of month, full name or 3 letter abbreviation
  25. month = raw_input("Enter month (eg. 9 or sep): ")
  26. day = raw_input("Enter the day of the month: ")
  27. date = extract_date(day + " " + month[:3].title() + " " + year)
  28. if date == None:
  29. print "Illegal info!"
  30. continue
  31. else:
  32. return date
  33.  
  34.  
  35. date = enter_date()
  36.  
  37. # testing ...
  38. #print date, type(date) # 2001-09-11 00:00:00 <type 'datetime.datetime'>
  39. #print date.strftime("%m/%d/%Y") # 09/11/2001
  40. #print date.strftime("%d%b%Y") # 11Sep2001
  41.  
  42. # do something with it ...
  43. today = dt.datetime.today()
  44. age = today - date
  45. # assumes week starts with Monday
  46. weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  47. week_day = weekdays[dt.date.weekday(date)]
  48. print "Today is %s" % today.strftime("%d%b%Y")
  49. print "%s was %d days ago on a %s" % (date.strftime("%d%b%Y"), age.days, week_day)
  50.  
  51. """
  52. my output -->
  53. Enter year (eg. 1979): 2001
  54. Enter month (eg. 9 or sep): september
  55. Enter the day of the month: 11
  56. Today is 03Mar2008
  57. 11Sep2001 was 2365 days ago on a Tuesday
  58. """
Thanks to Jeff for the idea.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
0
  #118
Mar 5th, 2008
Sorry!
Last edited by ZZucker; Mar 5th, 2008 at 1:14 pm. Reason: bad code
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
0
  #119
Mar 5th, 2008
Here is an example how to output a formatted table from a loop:
  1. # print a table (16 columns) of ASCII characters from 1 to 127
  2.  
  3. # Bumsfeld, thanks for the dictionary
  4. controls_dic = {
  5. 1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK', 7: 'BEL',
  6. 8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO',
  7. 15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3', 20: 'DC4', 21: 'NAK',
  8. 22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS',
  9. 29: 'GS', 30: 'RS', 31: 'US'}
  10.  
  11. n = 1
  12. for k in range(1, 128):
  13. if k < 32:
  14. s = controls_dic[k]
  15. else:
  16. s = chr(k)
  17. if n % 16 > 0:
  18. print "%4s" % s,
  19. else:
  20. print "%4s" % s
  21. n += 1
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #120
Mar 9th, 2008
This modified Tkinter GUI code allows you to follow your character key strokes on the console display:
  1. # KeyLogger.py
  2. # show a character key when pressed without using Enter key
  3. # hide the Tkinter GUI window, only console shows
  4.  
  5. import Tkinter as tk
  6.  
  7. def key(event):
  8. if event.keysym == 'Escape':
  9. root.destroy()
  10. print event.char
  11.  
  12. root = tk.Tk()
  13. print "Press a key (Escape key to exit):"
  14. root.bind_all('<Key>', key)
  15. # don't show the tk window
  16. root.withdraw()
  17. root.mainloop()
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC