User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 375,207 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,318 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 49936 | Replies: 140
Reply
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #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 2:53 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Jan 2006
Location: India
Posts: 3
Reputation: deeppython is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
deeppython deeppython is offline Offline
Newbie Poster

Re: Starting Python

  #42  
Jan 19th, 2006
The thread regarding 'how to do input in python' is great ..
Thanks for the contribution
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #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 2:54 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #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 5:59 pm. Reason: changed php tags
May 'the Google' be with you!
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 914
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 41
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Re: Starting Python

  #45  
Feb 10th, 2006
This littel program allows you to find which key had been pressed using the Tkinter GUI.
# bind and show a key event with Tkinter 

from Tkinter import *

root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def key(event):
    if event.char == event.keysym:
        msg = 'Normal Key %r' % event.char
    elif len(event.char) == 1:
        msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
    else:
        msg = 'Special Key %r' % event.keysym
    label1.config(text=msg)

label1.bind_all('<Key>', key)

root.mainloop()
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 914
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 41
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Re: Starting Python

  #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:
# input a sequence of integer numbers separated by a space and convert to a list

def get_integer_list():
    while True:
        # get the sequence string and strip off any trailing space (easy mistake)
        str1 = raw_input("Enter a sequence of integers separated by a space: ").rstrip()
        try:
            # create a list of integers from the string using list comprehension
            return [int(num) for num in str1.split(" ")]
        except ValueError:
            print "Error: '%s' is not an integer! Try again." % num
            
print get_integer_list()
For example the input 1 2 3 4 5 turns into [1, 2, 3, 4, 5]
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 914
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 41
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Re: Starting Python

  #47  
Feb 13th, 2006
This small code allow you to list your computer's environment, things like processor, os, user and so on:
# list the environmental settings of your computer

import os

keys = os.environ.keys()
keys.sort()
for item in keys:
    print "%-22s : %s" % (item, os.environ[item])
As a bonus another small code to find the IP address of your computer:
# Get the IP address of the machine this program is running on
# or go to http://www.whatismyip.com/

import socket

print socket.gethostname()
print socket.getaddrinfo(socket.gethostname(), None)
# get just the IP address from the list's tuple
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  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 171
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #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 2:59 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 914
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 41
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Re: Starting Python

  #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.
def checkInput(type_string, present_value, low, high):
    '''uses a while loop, loops until an acceptible answer is given, then returns it'''
    prompt = "Present %s is %d, enter a new value (%d-%d): " % (type_string, present_value, low, high)
    while True: 
       try:
          a = int(raw_input(prompt))
          if low <= a <= high:
             return a
       except ValueError:
          print "Enter an integer number, please!"


# modify the present strength of 10 within the range (1-18)
modified_strength = checkInput("strength", 10, 1, 18)
print modified_strength
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 914
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 41
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Solution Re: Starting Python

  #50  
Feb 25th, 2006
Code sample shows how to run a program and specified file(s) from commandline.
# using commandline to run a program and files

def process_datafile(filename):
    """load specified data file and process data"""
    # code to read file data
    # code to process data and show or return result
    print "Test only, file =", filename   # testing

if __name__ == '__main__':
    import sys

    # run the progam from the commandline and specify the data file(s) to be loaded
    # something like   myProgram data1.dat data2.dat
    if len(sys.argv) > 1:
        # sys.argv is a list eg. ['C:/Python24/Atest/myProgram.py', 'data1.dat', 'data2.dat']
        # sys.argv[0] is program filename, slice it off with sys.argv[1:]
        # using for loop, more than one datafile can be processed
        for filename in sys.argv[1:]:
            process_datafile(filename)
    else:
        print "usage myProgram datafile1 [datafile2 ...]"
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb Python Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 2:51 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC