Starting Python

Reply

Join Date: Oct 2004
Posts: 3,847
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: 865
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #41
Jan 9th, 2006
Some neat code from the forum. The question was:
... when I take a list with duplicates and make it a set then the duplicates are gone. How can I find out which were those duplicates?

A good solution came from monkeyy ...
  1. lst1 = list('a list of characterstrings')
  2. for item in set(lst1):
  3. print item, 'counted', lst1.count(item), 'times'
  4.  
  5. """
  6. result =
  7. a counted 3 times
  8. counted 3 times (space)
  9. c counted 2 times
  10. e counted 1 times
  11. ...
  12. """
Edit: changed l to lst1
Last edited by vegaseat; Mar 1st, 2007 at 3:53 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jan 2006
Posts: 3
Reputation: deeppython is an unknown quantity at this point 
Solved Threads: 0
deeppython deeppython is offline Offline
Newbie Poster

Re: Starting Python

 
0
  #42
Jan 19th, 2006
The thread regarding 'how to do input in python' is great ..
Thanks for the contribution
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,847
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: 865
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #43
Jan 19th, 2006
Just a little thing about reverse spelling I picked up from the internet ...
  1. # reverse the spelling of an input string
  2. # string reverse slice [::-1] introduced in Python23
  3. # reversed() introduced in Python24
  4.  
  5. text = raw_input("Enter a string: ")
  6. print text[::-1]
  7.  
  8. # or
  9. print raw_input("Enter a string: ")[::-1]
  10.  
  11. # or
  12. print ''.join(reversed(raw_input("Enter a string: ")))
Last edited by vegaseat; Mar 1st, 2007 at 3:54 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,847
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: 865
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #44
Jan 21st, 2006
Two small examples of sorting in Python. The first example shows you how to sort a list of numeric strings as strings or as integers. The results are quite different ...
  1. # sort a list of numeric strings:
  2.  
  3. list1 = ['0', '100', '28', '39', '1', '1003']
  4.  
  5. print "Original list of numeric strings:"
  6. print list1
  7.  
  8. print "Sort as strings:"
  9. list1.sort()
  10. print list1 # ['0', '1', '100', '1003', '28', '39']
  11.  
  12. print "Sort as integers (Python24):"
  13. list1.sort(key=int)
  14. print list1 # ['0', '1', '28', '39', '100', '1003']
The second examples shows you how to sort two related lists in parallel, so the relationships stay intact ...
  1. # sort two lists in parallel ...
  2. # create two lists of same length
  3. list1 = ['one', 'two', 'three', 'four']
  4. list2 = ['uno', 'dos', 'tres', 'cuatro']
  5.  
  6. # create a list of tuples, (english, spanish) pairs
  7. data = zip(list1, list2)
  8. print data # [('one', 'uno'), ('two', 'dos'), ('three', 'tres'), ('four', 'cuatro')]
  9.  
  10. # can use parallel looping to display result ...
  11. for english, spanish in data:
  12. print english, spanish # one uno etc.
  13.  
  14. # each whole tuple will be sorted
  15. data.sort()
  16. print data # [('four', 'cuatro'), ('one', 'uno'), ('three', 'tres'), ('two', 'dos')]
  17.  
  18. # if you need two lists again after sorting then use ...
  19. list3, list4 = map(lambda t: list(t), zip(*data))
  20. print list3 # ['four', 'one', 'three', 'two']
  21. print list4 # ['cuatro', 'uno', 'tres', 'dos']
  22.  
  23. # if you need just two tuples use ...
  24. tuple1, tuple2 = zip(*data)
  25. print tuple1 # ('four', 'one', 'three', 'two')
  26. print tuple2 # ('cuatro', 'uno', 'tres', 'dos')
Last edited by vegaseat; May 15th, 2007 at 6:59 pm. Reason: changed php tags
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #45
Feb 10th, 2006
This littel program allows you to find which key had been pressed using the Tkinter GUI.
  1. # bind and show a key event with Tkinter
  2.  
  3. from Tkinter import *
  4.  
  5. root = Tk()
  6. prompt = ' Press any key '
  7. label1 = Label(root, text=prompt, width=len(prompt))
  8. label1.pack()
  9.  
  10. def key(event):
  11. if event.char == event.keysym:
  12. msg = 'Normal Key %r' % event.char
  13. elif len(event.char) == 1:
  14. msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
  15. else:
  16. msg = 'Special Key %r' % event.keysym
  17. label1.config(text=msg)
  18.  
  19. label1.bind_all('<Key>', key)
  20.  
  21. root.mainloop()
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #46
Feb 12th, 2006
This code shows how to input a series of integers each separated by a space and then convert that input to a list of those integers:
  1. # input a sequence of integer numbers separated by a space and convert to a list
  2.  
  3. def get_integer_list():
  4. while True:
  5. # get the sequence string and strip off any trailing space (easy mistake)
  6. str1 = raw_input("Enter a sequence of integers separated by a space: ").rstrip()
  7. try:
  8. # create a list of integers from the string using list comprehension
  9. return [int(num) for num in str1.split(" ")]
  10. except ValueError:
  11. print "Error: '%s' is not an integer! Try again." % num
  12.  
  13. print get_integer_list()
For example the input 1 2 3 4 5 turns into [1, 2, 3, 4, 5]
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #47
Feb 13th, 2006
This small code allow you to list your computer's environment, things like processor, os, user and so on:
  1. # list the environmental settings of your computer
  2.  
  3. import os
  4.  
  5. keys = os.environ.keys()
  6. keys.sort()
  7. for item in keys:
  8. print "%-22s : %s" % (item, os.environ[item])
As a bonus another small code to find the IP address of your computer:
  1. # Get the IP address of the machine this program is running on
  2. # or go to http://www.whatismyip.com/
  3.  
  4. import socket
  5.  
  6. print socket.gethostname()
  7. print socket.getaddrinfo(socket.gethostname(), None)
  8. # get just the IP address from the list's tuple
  9. print socket.getaddrinfo(socket.gethostname(), None)[0][4][0]
Networks using the TCP/IP protocol route messages based on the IP address of the destination. An IP address is a 32-bit numeric address written as four numbers separated by periods.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,847
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: 865
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #48
Feb 17th, 2006
Here is a class that allows you to convert Fahrenheit to Celcius or the reverse.
  1. # class to convert F to C or C to F
  2. # getFahrenheit(self) would be public
  3. # __getFahrenheit(self) is private
  4. # (double underline prefix makes method private to class)
  5.  
  6. class Temperature (object):
  7. """allows you to convert Fahrenheit to Celsius and vice versa"""
  8. def __init__(self):
  9. self.celsius = 0.0
  10. def __getFahrenheit(self):
  11. return 32 + (1.8 * self.celsius)
  12. def __setFahrenheit(self, f):
  13. self.celsius = (f - 32) / 1.8
  14. # property() combines get and set methods into one call
  15. fahrenheit = property(fget = __getFahrenheit, fset = __setFahrenheit)
  16.  
  17. d = Temperature()
  18.  
  19. # setting celsius value ==> getting fahrenheit value
  20. d.celsius = 25
  21. print "%0.1f C = %0.1f F" % (d.celsius, d.fahrenheit)
  22.  
  23. # setting fahrenheit value and getting celsius value
  24. d.fahrenheit = 98
  25. print "%0.1f F = %0.1f C" % (d.fahrenheit, d.celsius)
You might need to add a few test prints to figure that one out.
Last edited by vegaseat; Mar 1st, 2007 at 3:59 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #49
Feb 18th, 2006
This was part of a game, I modified slightly the code. The code checks that input is correct and within a supplied range.
  1. def checkInput(type_string, present_value, low, high):
  2. '''uses a while loop, loops until an acceptible answer is given, then returns it'''
  3. prompt = "Present %s is %d, enter a new value (%d-%d): " % (type_string, present_value, low, high)
  4. while True:
  5. try:
  6. a = int(raw_input(prompt))
  7. if low <= a <= high:
  8. return a
  9. except ValueError:
  10. print "Enter an integer number, please!"
  11.  
  12.  
  13. # modify the present strength of 10 within the range (1-18)
  14. modified_strength = checkInput("strength", 10, 1, 18)
  15. print modified_strength
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #50
Feb 25th, 2006
Code sample shows how to run a program and specified file(s) from commandline.
  1. # using commandline to run a program and files
  2.  
  3. def process_datafile(filename):
  4. """load specified data file and process data"""
  5. # code to read file data
  6. # code to process data and show or return result
  7. print "Test only, file =", filename # testing
  8.  
  9. if __name__ == '__main__':
  10. import sys
  11.  
  12. # run the progam from the commandline and specify the data file(s) to be loaded
  13. # something like myProgram data1.dat data2.dat
  14. if len(sys.argv) > 1:
  15. # sys.argv is a list eg. ['C:/Python24/Atest/myProgram.py', 'data1.dat', 'data2.dat']
  16. # sys.argv[0] is program filename, slice it off with sys.argv[1:]
  17. # using for loop, more than one datafile can be processed
  18. for filename in sys.argv[1:]:
  19. process_datafile(filename)
  20. else:
  21. print "usage myProgram datafile1 [datafile2 ...]"
Reply With Quote Quick reply to this message  
Reply

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