•
•
•
•
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
![]() |
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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 ...
Edit: changed l to lst1
... 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 ...
python Syntax (Toggle Plain Text)
lst1 = list('a list of characterstrings') for item in set(lst1): print item, 'counted', lst1.count(item), 'times' """ result = a counted 3 times counted 3 times (space) c counted 2 times e counted 1 times ... """
Last edited by vegaseat : Mar 1st, 2007 at 2:53 pm. Reason: [code=python] tag
May 'the Google' be with you!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
Just a little thing about reverse spelling I picked up from the internet ...
python Syntax (Toggle Plain Text)
# reverse the spelling of an input string # string reverse slice [::-1] introduced in Python23 # reversed() introduced in Python24 text = raw_input("Enter a string: ") print text[::-1] # or print raw_input("Enter a string: ")[::-1] # or 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!
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
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 ...
The second examples shows you how to sort two related lists in parallel, so the relationships stay intact ...
python Syntax (Toggle Plain Text)
# sort a list of numeric strings: list1 = ['0', '100', '28', '39', '1', '1003'] print "Original list of numeric strings:" print list1 print "Sort as strings:" list1.sort() print list1 # ['0', '1', '100', '1003', '28', '39'] print "Sort as integers (Python24):" list1.sort(key=int) print list1 # ['0', '1', '28', '39', '100', '1003']
python Syntax (Toggle Plain Text)
# sort two lists in parallel ... # create two lists of same length list1 = ['one', 'two', 'three', 'four'] list2 = ['uno', 'dos', 'tres', 'cuatro'] # create a list of tuples, (english, spanish) pairs data = zip(list1, list2) print data # [('one', 'uno'), ('two', 'dos'), ('three', 'tres'), ('four', 'cuatro')] # can use parallel looping to display result ... for english, spanish in data: print english, spanish # one uno etc. # each whole tuple will be sorted data.sort() print data # [('four', 'cuatro'), ('one', 'uno'), ('three', 'tres'), ('two', 'dos')] # if you need two lists again after sorting then use ... list3, list4 = map(lambda t: list(t), zip(*data)) print list3 # ['four', 'one', 'three', 'two'] print list4 # ['cuatro', 'uno', 'tres', 'dos'] # if you need just two tuples use ... tuple1, tuple2 = zip(*data) print tuple1 # ('four', 'one', 'three', 'two') 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!
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() 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:
For example the input 1 2 3 4 5 turns into [1, 2, 3, 4, 5]
# 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() This small code allow you to list your computer's environment, things like processor, os, user and so on:
As a bonus another small code to find the IP address of your computer:
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.
# 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])# 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]
•
•
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,337
Reputation:
Rep Power: 8
Solved Threads: 171
Here is a class that allows you to convert Fahrenheit to Celcius or the reverse.
You might need to add a few test prints to figure that one out.
python Syntax (Toggle Plain Text)
# class to convert F to C or C to F # getFahrenheit(self) would be public # __getFahrenheit(self) is private # (double underline prefix makes method private to class) class Temperature (object): """allows you to convert Fahrenheit to Celsius and vice versa""" def __init__(self): self.celsius = 0.0 def __getFahrenheit(self): return 32 + (1.8 * self.celsius) def __setFahrenheit(self, f): self.celsius = (f - 32) / 1.8 # property() combines get and set methods into one call fahrenheit = property(fget = __getFahrenheit, fset = __setFahrenheit) d = Temperature() # setting celsius value ==> getting fahrenheit value d.celsius = 25 print "%0.1f C = %0.1f F" % (d.celsius, d.fahrenheit) # setting fahrenheit value and getting celsius value d.fahrenheit = 98 print "%0.1f F = %0.1f C" % (d.fahrenheit, d.celsius)
Last edited by vegaseat : Mar 1st, 2007 at 2:59 pm. Reason: [code=python] tag
May 'the Google' be with you!
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 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 ...]"![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Snack no sound?
- Next Thread: Module error? and gasp module problem



Linear Mode