Posts
 
Reputation
Joined
Last Seen
Ranked #360
Strength to Increase Rep
+8
Strength to Decrease Rep
-2
100% Quality Score
Upvotes Received
16
Posts with Upvotes
16
Upvoting Members
11
Downvotes Received
0
Posts with Downvotes
0
Downvoting Members
0
9 Commented Posts
0 Endorsements
Ranked #363
~158.33K People Reached
Favorite Forums
Favorite Tags

104 Posted Topics

Member Avatar for daviddoria

I don't know of one. This code requires a radial coordinate. [code=Python]class Pt(object): def __init__(self, x=0.0, y=0.0, z=0.0): self.x = x self.y = y self.z = z def __str__(self): return '(%0.4f, %0.4f, %0.4f)' % (self.x, self.y, self.z) def __repr__(self): return 'Pt(%f, %f, %f)' % (self.x, self.y, self.z) def __add__(self, other): …

Member Avatar for Ratan_2
0
6K
Member Avatar for lapo3399

I would like to share this function that converts a number in base 10 to any base between 2 and 36. Originally it was limited to bases 2-16. [code=Python]import string def convDecToBase(num, base, dd=False): if not 2 <= base <= 36: raise ValueError, 'The base number must be between 2 …

Member Avatar for vegaseat
0
2K
Member Avatar for eplymale3043

Please use code tags when posting code. Are you receiving an error message? If so, please post it. Initialize a maximum score variable (maxscore). Loop on the file object [ICODE]for line in file_obj:[/ICODE]. Strip and split each line [ICODE]lineList = line.strip().split()[/ICODE]. If the value of the score is greater than …

Member Avatar for vegaseat
0
2K
Member Avatar for ndoe

Here's a possibility: [code=Python]import string numbers = set('1234567890') alpha = set(string.ascii_letters) mixed = numbers.add(alpha) f = open(file_name) for i, line in enumerate(f): # i is the line number beginning with 0 s1 = set(line.strip()) if s1.issubset(numbers): # do something elif s1.issubset(alpha): # do something elif s1.issubset(mixed): # do something else: …

Member Avatar for munna03
0
2K
Member Avatar for Yoink

This may give you some ideas: [code]>>> 'abcdefg'.count('a') 1 >>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' >>> s = 'I have to write a program that will decode a Ceasar cypher with any possible rotation length' >>> dd = dict(zip(string.ascii_lowercase, [s.count(c) for c in string.ascii_lowercase])) >>> dd['e'] 8 >>> [/code]

Member Avatar for TrustyTony
0
354
Member Avatar for Lucaci Andrew

A Tkinter Entry widget can be configured to "show" a character such as "*". [code]Tkinter.Entry(pwframe,width=25,show="*")[/code]

Member Avatar for Lucaci Andrew
0
179
Member Avatar for unigrad101

I suggest using a dictionary. Using name "seq" instead for "list" avoids masking built-in function [I]list()[/I].[code]>>> seq = ['v', 3.0,1, 'etc'] >>> dd = {} >>> for item in seq: ... v = dd.get(type(item), 0) ... dd[type(item)] = v+1 ... >>> [dd[obj] for obj in (int, float, str)] [1, 1, …

Member Avatar for bumsfeld
0
136
Member Avatar for VinceW

[QUOTE=dseto200;738085]I set the amount of tries to less than 3 ,however when I make more than 3 guesses it won't up the message. What did I do wrong? [code=Python]# Guess My Number # The computer picks a random number import random print "\tWelcome to 'Guess my number'!:" print "\nI'm thinking …

Member Avatar for themoviegeek
0
332
Member Avatar for halien

I know this thread was marked "solved", but I think the following is a somewhat simpler solution: [code]f.write(",".join(["%s,%s" % (item.real, item.imag) for item in cpl1]))[/code]

Member Avatar for bvdet
0
273
Member Avatar for PascalNouma

Using minidom: [code] from xml.dom import minidom doc = '''<?xml version="1.0" ?> <countries> <country> <city capital="Paris">Paris</city> </country> <country> <city capital="Helsinki">Helsinki</city> </country> <country> <city capital="Bogota">Bogota</city> </country> </countries>''' docXML = minidom.parseString(doc) for elem in docXML.getElementsByTagName("city"): elem.removeAttribute("capital") print docXML.toprettyxml(indent=" ", newl="")[/code]

Member Avatar for bvdet
0
325
Member Avatar for kumar_k

Does this help?[code]>>> import string >>> dd = dict(zip(string.ascii_lowercase, [str(i) for i in range(1,27)])) >>> "".join([dd[s] for s in "abcdejz"]) '123451026' >>> [/code]

Member Avatar for kumar_k
0
92
Member Avatar for vegaseat

Excellent snippet vegaseat. The expanded event handler solves a common problem. Here's another working example using the default argument trick:[code=Python]from Tkinter import * from itertools import cycle class SpinLabel(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack(fill=BOTH, expand=1) self.master.title("Spin Characters") self.textList = ["/", "--", "\\", "--", "|"] buttonFrame = Frame(self) self.btnList = …

Member Avatar for bvdet
1
1K
Member Avatar for leegeorg07

Built-in function round() and string formatting. [code=Python]>>> round(math.pi, 5) 3.1415899999999999 >>> "%0.5f" % math.pi '3.14159' >>> sig_digits = 6 >>> num = 123.456789 >>> "%0.*f" % (sig_digits-len(str(num).split('.')[0]), num) '123.457' >>> num = 1.23456789 >>> "%0.*f" % (sig_digits-len(str(num).split('.')[0]), num) '1.23457' >>> num = 1234567890 >>> "%0.*f" % (sig_digits-len(str(num).split('.')[0]), num) '1234567890' >>> …

Member Avatar for vegaseat
0
490
Member Avatar for smithy40000

You cannot place a menubar inside a canvas. A menubar goes on the top level window by design. You can place Tkinter widgets on a canvas by using a canvas window object.

Member Avatar for SgtMe
-1
212
Member Avatar for gangemia

[I][B]str[/B][/I] method [I]strip()[/I] will remove leading and trailing whitespace characters. If a string only has whitespace characters, [I][B]strip()[/B][/I] will remove them all and it will evaluate False. Example:[code]>>> not 'abcdefg12345 '.strip() False >>> not ' '.strip() True >>>[/code]

Member Avatar for gangemia
0
220
Member Avatar for pythonNerd159

Following is an example where I already have defined a list of text strings (self.btnList) to be displayed on buttons. When a button is selected (actually, the sequence is ButtonRelease), the button text is assigned to instance attribute "value" and the app is destroyed. In your case, you want to …

Member Avatar for pythonNerd159
0
127
Member Avatar for pythonNerd159

[code] self.mb["menu"] = self.mb.menu self.mb.menu.add_checkbutton(label="Exit", command=self.quit)[/code]quit() stops the mainloop and destroy() destroys the parent window and it's descendants.

Member Avatar for bvdet
0
121
Member Avatar for smithy40000

Create a Tkinter.Frame to hold the checker board and another frame to hold the buttons. Pack the frames "top". If you want the buttons along the bottom, pack "left". Add internal padding to each frame to get the desired space. To eliminate duplication, initialize a list and iterate on columns …

Member Avatar for jimothy
-1
228
Member Avatar for wtzolt

I used this answer on another forum. [quote] Try the following. It may not work on child windows spawned by the process. [code]import subprocess info = subprocess.STARTUPINFO() info.dwFlags = 1 info.wShowWindow = 0 subprocess.Popen("notepad.exe", startupinfo=info)[/code][/quote]

Member Avatar for vegaseat
0
6K
Member Avatar for cnuzzo

cnuzzo, I don't want to rework your code to make it work. Instead, I will give you an example that I think you can apply to your situation in a similar way. I will only create one top level window however. It works like this: [LIST=1] Create the top level …

Member Avatar for cnuzzo
0
1K
Member Avatar for Stubaan

If the data isn't too large, consider storing it in a dictionary. It could work like this:[code]s = '''ID1 ID2 Dist 1 a 50 2 b 20 3 c 10 2 c 100 4 c 80 4 a 70 1 a 90 2 a 34 3 b 5 2 b …

Member Avatar for Stubaan
0
181
Member Avatar for txwooley

Initialize your widget attribute [I]textvariable[/I] with [I]StringVar()[/I]. Use [I]w.set()[/I] to set the value and [I]w.get()[/I] to get the value.

Member Avatar for txwooley
0
11K
Member Avatar for Tops

I assume variable [I]char[/I] is a series of words. Iterate on [I]chars[/I] as in:[code]for letter in char: if letter.isalpha(): if letter in dict: dict[letter] = dict[letter] + 1 else: dict[letter] = 1[/code] BTW, please use code tags next time.

Member Avatar for bvdet
0
106
Member Avatar for gridder

You could use a combination of re and split. Find and remove all items in quotes first then split on space. Example: [code]import re s = '''10471 'AGHADA71' 20.00 2 0.00 0.00 1 1 1.0106 0.312 'AGGTREW 45' 10475 'AGHADA75' 21.00 2 0.00 0.00 1 1 0.9940 -1.217 10810 'AHANE …

Member Avatar for gridder
0
124
Member Avatar for kadvar

Perhaps something like this: [code]>>> patt = r'keywords=([^&]+)[&]' >>> re.findall(patt, "keywords=james&keywords=john&keywords=brian&") ['james', 'john', 'brian'] >>> [/code]

Member Avatar for woooee
0
89
Member Avatar for voolvif

voolvif, You were not far off.[code]>>> pattern=re.compile(r"\%3D\%27([A-Z]+?)\%27\%3E",re.IGNORECASE) >>> pattern.findall(mystring) ['catherine', 'porter'] >>> [/code]

Member Avatar for bvdet
0
189
Member Avatar for DGXI

It appears that the first point is constant. Create a list of second point objects, then iterate on the list. [CODE]pointList = [Point(200, 200), Point(150, 200), ............... ] for pt in pointList: Line(Point(100, 100), pt).draw(win)[/CODE]

Member Avatar for vegaseat
0
183
Member Avatar for Gribouillis

[QUOTE=Gribouillis;1022251]Does anyone know how I can test if an object's type is a builtin type or a user defined type ?[/QUOTE] If it's not builtin, it must be imported from another module.[code=Python]>>> getattr(list, '__module__') '__builtin__' >>> [/code]

Member Avatar for Gribouillis
0
170
Member Avatar for liz517

I am not sure if this is what you want to accomplish, but I HTH:[code=Python]import random def roll_dice(stop=100): # roll five dice and summarize the occurrances of duplicate numbers cnt = 1 dd = {} while cnt <= stop: dice = [random.randrange(1,7) for _ in range(5)] # eliminate duplicates, Python …

Member Avatar for anatashinu
0
178
Member Avatar for Darkangelchick

If you want to determine if a number is prime or not, you should return True (if prime) or False (if not prime). Use the modulo operator to determine if the entered number is divisible by loop variable [I]i[/I]. [code=Python]if not n%i:[/code]If the statement evaluates True, return False. If the …

Member Avatar for Progressivism
0
144
Member Avatar for leegeorg07

I played around with a function that returns a list of factors a few months ago. You only need to check numbers up to sqrt(number).[code=Python]def factors(num): outList = [i for i in xrange(1, int(num**0.5)+1) if not num%i] if outList: outList.extend([num/outList[i] for i in range(len(outList)-[1, 2][outList[-1]**2 == num or 0], -1, …

Member Avatar for jlm699
0
259
Member Avatar for murnshaw

I think NineTrails solved the error. You should use code tags. Your code would be easier to read. Are you trying to print a string backwards? [code=Python]>>> x = 'something' >>> x[::-1] 'gnihtemos' >>> [/code]

Member Avatar for Arrorn
0
1K
Member Avatar for currupipi

It appears that [I]req[/I] is an open file object of some type. Try flushing the output buffers (obj.flush()) or close the file. -BV

Member Avatar for currupipi
0
117
Member Avatar for BlueNN

Here's my contribution: [code=Python]>>> def age_input(lower=1, upper=200): ... while True: ... age = raw_input("Enter an age between %d and %d" % (lower,upper)) ... if age.isdigit(): ... age = int(age) ... if lower <= age <= upper: ... return age ... print "Invalid answer. Try again."[/code]

Member Avatar for adam1122
0
113
Member Avatar for MaQleod

Change[code=Python]filestring = f.read()[/code] to[code=Python]filestring = f.readlines()[/code] -BV

Member Avatar for MaQleod
0
7K
Member Avatar for betatype

Supply a starting index for str.find() and update it each iteration. Example: [code]users = '''Users <a>User 1</a> <a>User 2</a> <a>User 3</a> <a>User 4</a> <a>User 5</a> ''' userList = [] idx = 0 while True: linkstart=users.find("<a>",idx) linkend=users.find("</a>", idx) if -1 in [linkstart,linkend]: break else: userList.append(users[linkstart+3:linkend]) idx = linkend+4 print userList[/code] Output: …

Member Avatar for mn_kthompson
0
189
Member Avatar for pinder

Create a list of file names that match your criteria: [code=Python]import os path_name = 'your_directory' key = 'journal' nameList = [os.path.join(path_name, n) for n in os.listdir(path_name) \ if os.path.isfile(os.path.join(path_name, n)) and n.startswith(key)][/code]

Member Avatar for nrupparikh
0
129
Member Avatar for tutti

I think Murtan is right about the histogram, but I never would have thought about that from reading the OP's posts. Instead of showing a solution, I will try to describe it and show some sample code. Get a list of 20 numbers from the user. You can also get …

Member Avatar for bvdet
0
121
Member Avatar for elvenstruggle

Here is one way to do it: [code=Python]>>> class test(object): ... def change_var(self, name, value): ... globals()[name] = value ... >>> var = 123 >>> obj = test() >>> obj.change_var('var', 456) >>> var 456 >>> [/code]

Member Avatar for elvenstruggle
0
117
Member Avatar for SoulMazer

An appropriate variable name in the [I]for[/I] loop would be [I]key[/I] instead of [I]value[/I], because you are iterating on the keys of the dictionary. [code=Python] if answer == testwords[key]:[/code]

Member Avatar for SoulMazer
0
309
Member Avatar for jcp200817

Not to be picky, but string method [I]isalpha()[/I] is preferable by some. This will avoid the string module:[code=Python]def phone_alpha_number(phone_num): nums = '22233344455566677778889999' alphas = 'abcdefghijklmnopqrstuvwxyz' return ''.join([[s, nums[alphas.find(s)]][s.isalpha() or 0] for s in phone_num])[/code] Example: [code=Python]>>> phone_alpha_number('(555)not-best') '(555)668-2378' >>> [/code]I know it's a ridiculous use of a list comprehension, but …

Member Avatar for jcp200817
0
450
Member Avatar for Nanz

I like using list comprehensions for this kind of task. [code]>>> cols = 4 >>> rows = 5 >>> array = [[0 for i in range(cols)] for j in range(rows)] >>> array [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, …

Member Avatar for jlm699
0
63K
Member Avatar for jcafaro10

When variables are assigned inside a function, they are always bound to the function's local namespace. The global namespace is never checked for name [I]switch[/I], therefore the error. Example: [code]>>> switch = -1 >>> def test(): ... return -switch ... >>> switch = test() >>> switch 1 >>> def test1(): …

Member Avatar for jcafaro10
0
181
Member Avatar for axn

Here's another problem: [B][I]for files in files:[/I][/B] Should be: [code]import zipfile, os, time, sys, ConfigParser, zlib def zip_fh(): zip = zipfile.ZipFile('%s.zip' % (path), 'w') for root, dirs, files in os.walk(path, topdown=True): for file in files:[/code] The file name variable can also be assigned like this: [CODE]zip_fh = r'C:\Documents and Settings\file.cfg'[/CODE]

Member Avatar for woooee
0
218
Member Avatar for Fractilion

You can encapsulate your array variables in a dictionary. [code=Python]>>> dd = {} >>> for i in range(6): ... dd['Array%s' % i] = ['-'] ... >>> dd {'Array3': ['-'], 'Array2': ['-'], 'Array1': ['-'], 'Array0': ['-'], 'Array5': ['-'], 'Array4': ['-']} >>> keys = dd.keys() >>> keys.sort() >>> for key in keys: …

Member Avatar for bvdet
0
110
Member Avatar for adam291086

It depends on the type of data and how you intend to use it. [code=Python]>>> adam = "john" >>> adam += "mike" >>> adam 'johnmike' >>> ' '.join([adam, 'fred']) 'johnmike fred' >>> [/code]

Member Avatar for paddy3118
0
93
Member Avatar for tomtetlaw

To load the values, you could do something like this: Example config file: Tom 10 9.7 [1,2,3] [code=Python]fn = 'config.txt' f = open(fn) vartypes = [str,int,float,eval] varnames = ['name','exp','score','other'] dd = {} for i,line in enumerate(f): dd[varnames[i]] = vartypes[i](line.strip()) globals().update(dd) f.close()[/code][code=Python]>>> name 'Tom' >>> other [1, 2, 3] >>> [/code]To …

Member Avatar for tomtetlaw
0
103
Member Avatar for Fionageo

The object assigned to [I]rs[/I] should evaluate False if empty. Have you tried: [code=Python]if rs: rs.moveFirst()[/code]

Member Avatar for bvdet
0
150
Member Avatar for Paramecium

If I understand the problem correctly, there is no need to pass q as an argument to enqueue() and dequeue(). [code=Python] def enqueue(self,z): self.q.append(z) return self.q[/code]To reverse the queue, you can use a for loop on a range in reverse order: range(len(self.q)-1,-1,-1) Notice the first number in the range is …

Member Avatar for bvdet
0
108
Member Avatar for ashain.boy

Here's another variation: [code=Python]lineList = ['Los Angeles 13,583 17,073 25.70%', 'Orange 3,882 5,692 46.60%', 'San Diego 5,673 7,062 24.50%', 'Riverside 9,250 11,714 26.60%', 'San Bernardino 7,038 9,110 29.40%', 'Ventura 1,377 1,676 21.70%', 'Imperial 259 568 119.30%', 'San Francisco 252 353 40.10%'] dd = {} for line in lineList: for i, …

Member Avatar for bvdet
0
90

The End.