- Strength to Increase Rep
- +8
- Strength to Decrease Rep
- -2
- Upvotes Received
- 16
- Posts with Upvotes
- 16
- Upvoting Members
- 11
- Downvotes Received
- 0
- Posts with Downvotes
- 0
- Downvoting Members
- 0
104 Posted Topics
Re: 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): … | |
Re: 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 … | |
Re: 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 … | |
Re: 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: … | |
Re: 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] | |
Re: A Tkinter Entry widget can be configured to "show" a character such as "*". [code]Tkinter.Entry(pwframe,width=25,show="*")[/code] | |
Re: 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, … | |
Re: [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 … | |
Re: 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] | |
Re: 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] | |
Re: 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] | |
Re: 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 = … | |
![]() | Re: 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' >>> … |
Re: 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. | |
Re: [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] | |
Re: 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 … | |
Re: [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. | |
Re: 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 … | |
Re: 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] | |
Re: 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 … | |
Re: 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 … | |
Re: 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. | |
Re: 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. | |
Re: 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 … | |
Re: Perhaps something like this: [code]>>> patt = r'keywords=([^&]+)[&]' >>> re.findall(patt, "keywords=james&keywords=john&keywords=brian&") ['james', 'john', 'brian'] >>> [/code] | |
Re: 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] | |
Re: 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] | |
Re: [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] | |
Re: 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 … | |
Re: 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 … | |
![]() | Re: 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, … |
Re: 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] | |
Re: 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 | |
Re: 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] | |
Re: Change[code=Python]filestring = f.read()[/code] to[code=Python]filestring = f.readlines()[/code] -BV | |
Re: 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: … | |
Re: 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] | |
Re: 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 … | |
Re: 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] | |
Re: 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] | |
Re: 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 … | |
Re: 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, … | |
Re: 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(): … | |
Re: 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] | |
Re: 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: … | |
Re: 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] | |
Re: 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 … | |
Re: The object assigned to [I]rs[/I] should evaluate False if empty. Have you tried: [code=Python]if rs: rs.moveFirst()[/code] | |
Re: 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 … | |
Re: 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, … |
The End.