2,646 Posted Topics

Member Avatar for rociel

You can use the "format" method [code=python] # This program computes right triangles import math print "This program computes the hypotenuse of a right triangle with the sides a and b." a = input("Enter the length of the first leg to the nearest inch: ") b = input("Enter the length …

Member Avatar for rociel
0
279
Member Avatar for A_Dubbs

Your move function should return the next dx and dy. You could write this [code=python] from zellegraphics import * ##Write a program to animate a circle bouncing around a window. The basic idea ##is to start the circle somewhere in the interior of the window. Use variables ##dx and dy …

Member Avatar for Gribouillis
0
384
Member Avatar for Kruptein
Member Avatar for jmark13

A shorter method [code=python] L1=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]] L2=[1,2,3,4,11] set2 = set(L2) L3 = [x for x in L1 if set2.intersection(x)] print(L3) [/code]

Member Avatar for lukerobi
0
193
Member Avatar for lukerobi

[QUOTE=lukerobi;1018593]thanks for the replies, but unfortunatly none of thee will work. I am basically trying to return a function from a library if it is not in a class. [code] import random class whatever(object): def __getattr___(self, name): if name not in locals(): return random.name [/code][/QUOTE] you should use [icode]getattr(random, name)[/icode]

Member Avatar for lukerobi
0
166
Member Avatar for lrh9

I would use the re module and substitution [code=python] import re pattern = re.compile(r"([a-z]+)|[A-Z]+") def swap(match): return match.group(0).upper() if match.group(1) else match.group(0).lower() def swapcase(msg): return pattern.sub(swap, msg) if __name__ == "__main__": print (swapcase("HellO WOrlD!")) """ my output ---> hELLo woRLd! """ [/code]

Member Avatar for lukerobi
0
253
Member Avatar for akie2741

Here is a way to get the addresses of the images [code=python] # extract the addresses of the images included in a web page # you need the modules lxml and beautifulsoup # (for linux, packages python-lxml and python-beautifulsoup) # tested with python 2.6 from lxml.html import soupparser from urllib2 …

Member Avatar for vegaseat
0
177
Member Avatar for willygstyle

@willygstyle. Perhaps you should try your first code with arguments to [icode]socket.socket()[/icode]. I'm not sure it will be any better, but calling socket without arguments is unusual.

Member Avatar for willygstyle
0
156
Member Avatar for lewashby

A few comments [CODE] # main crit = Critter("Poochie") # <---- At instance creation, the method __init__ is called. 'Poochie' is used as the parameter name in this call. THat's how Poochie knows where to go. crit.talk() print "\nMy critter's name is:", print crit.name # <---- When getting the value …

Member Avatar for Gribouillis
0
738
Member Avatar for awa

[QUOTE=awa;1016397]Hi, I want to sort a tuple consisting of two floats and one array by the absolute value of the first float in reverse order. What I did is the following: [CODE]from numpy import * test = [(-0.02, 100.2, array([1, 0, 0])), (-4.02, 300.4, array([1, 1, 0])), (3.57, 503.7, array([1, …

Member Avatar for leegeorg07
0
253
Member Avatar for mahela007

[QUOTE=mahela007;1016459]What does "variables containing objects" mean?[/QUOTE] I think he means everything but basic datatypes like int, floats and strings. However, you can do as if it was always true.

Member Avatar for jice
0
332
Member Avatar for Dan08

For linux, you should distribute the python file directly, because most linux distributions come with python installed.

Member Avatar for Stefano Mtangoo
0
120
Member Avatar for lewashby

[QUOTE=Garrett85;1015608] So what are objects all about anyway? It looks to me like a long complicated way of walling a function or method.[/QUOTE] Objects are the result of years of programming practice by thousands of programmers. You need some time to see the benefit. The idea is that an object …

Member Avatar for lllllIllIlllI
0
121
Member Avatar for lewashby

Imagine the 2 objects like boxes containing data [code] ----------------- crit1 ---> | name: Poochie | ----------------- ----------------- crit2 ---> | name: Randolf | ----------------- [/code] You can access this data with the dot operator. For example [icode]print(crit1.name)[/icode] will print Poochie. In the methods of the class, instead of writing …

Member Avatar for Gribouillis
0
94
Member Avatar for princessotes

The best way to do it is to read your file and write a new file with the negated digits. Could you be more specific about the content of your file (attach your file to a post ?).

Member Avatar for vegaseat
0
28K
Member Avatar for saikeraku

You could write [code=python] if "7" in lucky: print lucky + " " + "is lucky!" else: print lucky + " " + "is not lucky." [/code] Also you could add some code to check if the input was an integer [code=python] try: int(lucky.strip()) except ValueError: print("Error: an integer is …

Member Avatar for vegaseat
0
158
Member Avatar for SoulMazer

You could use HTMLParser like this [code=python] import sys if sys.version_info[0] < 3: from HTMLParser import HTMLParser from urllib2 import urlopen else: from html.parser import HTMLParser from urllib.request import urlopen class MyParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.day = None def handle_starttag(self, tag, attrs): if tag == 'tr': for key, value in …

Member Avatar for SoulMazer
1
165
Member Avatar for etypaldo

Also, you could write a better line processing. In the loop [icode]for num in the_file[/icode], num is a string like [icode]'51\n'[/icode]. A good way to handle this is [code=python] for num in the_file: num = num.strip() # get rid of white space around the line's content (the \n) if not …

Member Avatar for woooee
0
107
Member Avatar for mahela007

[icode]mylist[i][/icode] will raise IndexError unless i is in the interval [-n, n[ where n is the length of mylist. When the list is empty, this interval is empty. You could use [code=python] mylist.append("hello") mylist.insert(0, "hello") [/code]

Member Avatar for mahela007
0
78
Member Avatar for thehivetyrant

It should be [code=python] def withdraw(self, amount): self.balance -= amount [/code] There is no [icode]self.amount[/icode], only the paramater [icode]amount[/icode].

Member Avatar for Gribouillis
0
138
Member Avatar for fallopiano
Member Avatar for fallopiano
0
105
Member Avatar for Stefano Mtangoo

I'm using an online dictionary. This is what I get for [url=http://dictionnaire.reverso.net/anglais-francais/potato/forced]potato[/url] :)

Member Avatar for Gribouillis
0
183
Member Avatar for Dixtosa

One way to do it is to use the subprocess module [code=python] import subprocess as SP child_process = SP.Popen(["python", "t.py"]) [/code]

Member Avatar for ov3rcl0ck
-2
265
Member Avatar for scrace89

[QUOTE=scrace89;1008693] Can anyone explain the x = (math.sqrt(8 * n + 1) - 1) / 2 triangular numbers have sums of consecutive ints like 1+2 = 3, 1+2+3=6 1+2+3+4 = 10 and ect.[/QUOTE] A number n is triangular if it has the form n = k(k+1)/2. For example 1+2 = …

Member Avatar for Gribouillis
0
582
Member Avatar for vipints

It worked with [code=python] scipy.io.savemat('/tmp/out.mat', mdict={'Num0': code[0], 'Num1':code[1]}) [/code] It seems that your problem is that you're using a tuple as the value for 'Num'.

Member Avatar for vipints
0
355
Member Avatar for CurtisEClark

Your program should be [code=python] #Program to count number of specific vowels msg = input("Enter a message:") msg_lower = msg.lower() VOWELS = list("aeiou") msg_list = list(msg_lower) x = dict() for letter in VOWELS: x[letter] = msg_list.count(letter) for letter in x: print(letter, x[letter]) [/code] When there is an error, please put …

Member Avatar for masterofpuppets
0
85
Member Avatar for elliottb

You can overwrite the [] by adding a method [icode]__getitem__[/icode] to a structure. See [url=http://www.swig.org/Doc1.3/SWIGDocumentation.html#SWIG_adding_member_functions]adding_member_functions[/url]

Member Avatar for Gribouillis
-1
133
Member Avatar for SuperMetroid

I don't know exactly what you want to compare, but here is a code which measures the time necessary to execute 1,000,000 times a dictionary lookup (the statement [icode]'7498' in D[/icode]) [code=python] from timeit import Timer D = dict() for i in range(10000): D[str(i)] = i print(Timer("'7498' in D", "from …

Member Avatar for vegaseat
-1
4K
Member Avatar for Dan08

If you're with windows, you should probably simply rename your main program with the extension [icode].pyw[/icode] instead of [icode].py[/icode].

Member Avatar for vegaseat
-1
76
Member Avatar for ihatehippies

[icode]from __main__ import *[/icode] must not be written if you want to write maintainable code. What you should do is first see if some parts of your program can be implemented as separate modules, at functional level (for example a module could be devoted to communicate with a database, etc). …

Member Avatar for Gribouillis
-1
121
Member Avatar for AutoPython

It could be useful to visit the [url=http://www.dlitz.net/software/pycrypto/]pycrypto[/url] page.

Member Avatar for ov3rcl0ck
0
574
Member Avatar for JustAnotherJoe

I took my ping.py from [url]ftp://ftp.visi.com/users/mdc/ping.py[/url]. It seems that doOne accepts a timeout argument. Why don't you use it ?

Member Avatar for JustAnotherJoe
0
7K
Member Avatar for scru

A nice LR(1) parser is [url=http://seehuhn.de/pages/wisent]wisent[/url]. Simple to use and efficient. Also it generates parsers independant of wisent, so that a user of your program wouldn't need wisent to run your wisent-generated parser.

Member Avatar for scru
0
196
Member Avatar for esash

This works for me [code=python] import numpy a=numpy.matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]], dtype=numpy.float) print a b = a ** (-1) print b print b * a """my output ---> [[ 1. 2. 3.] [ 2. 3. 4.] [ 3. 4. 5.]] [[ 4.50359963e+15 -9.00719925e+15 4.50359963e+15] [ …

Member Avatar for vegaseat
0
157
Member Avatar for Warkthogus

[QUOTE=Warkthogus;965513] I've also toyed with dictionaries, but [b]couldn't get them to work[/b] either. Any help would be greatly appreciated.[/QUOTE] When "it doesn't work" in python, most of the time, there is an exception traceback (python complains). Here is what I get in my terminal when I try to run your …

Member Avatar for Warkthogus
0
228
Member Avatar for mahela007

[QUOTE=mahela007;991473]Is it good programming practice to refer to class variables by using their instances? like mycow.numcows?[/QUOTE] Yes it's good programming practice. The purpose of classes is to hold data shared by all the instances of the class. This includes class variables, also called static fields in other languages.

Member Avatar for djidjadji
0
175
Member Avatar for AutoPython

[QUOTE=AutoPython;988381] 1. Does c1 inherit the global trait, or remain local 2. Does the global trait remained assigned to a variable named c, or would deleting the variable also delete the global statement.[/QUOTE] There is nothing special with a global variable. The statement [icode]global c[/icode] in testfunc only means that …

Member Avatar for AutoPython
0
331
Member Avatar for Benderbrau

This kind of problem has already been posted in this forum. I call this "sorting by colums". Suppose we have 2 lists [code= python] >>> jobSize = [ 5, 8, 3, 4, 1, 9, 7 ] >>> length = [ 500, 80, 300, 4, 10, 900, 70] [/code] how to …

Member Avatar for Gribouillis
0
161
Member Avatar for edward_pedro

[QUOTE=djidjadji;985939]Have a look for the "grep" tool that is available for your OS. Ignore case searching is done with the -i option[/QUOTE] There is an interesting python alternative to grep, called [icode]grin[/icode]. Have a look here [url]http://pypi.python.org/pypi/grin[/url].

Member Avatar for vegaseat
0
150
Member Avatar for chico2009

2 ways at least: you can type [code=python] >>> from xandy import xandy [/code] and then use your function. The file must be in a place where python will find it (in a folder listed in your PYTHONPATH environment variable. Second (and best) way, run python's built-in gui IDLE (look …

Member Avatar for chico2009
0
111
Member Avatar for sab786
Member Avatar for lllllIllIlllI

When you're working with strings, [icode]s in t[/icode] means that s is a substring of t. The question is what is a substring ? We could give 2 defintitions, first s is a substring of t if there are strings x and y such that t == x + s …

Member Avatar for sravan953
0
156
Member Avatar for Lingson

[QUOTE=Lingson;966960] TypeError: 'range' object does not support item assignment [/QUOTE] Usually, you can fix this by replacing [icode]range(*args)[/icode] with [icode]list(range(*args))[/icode].

Member Avatar for sneekula
0
4K
Member Avatar for squallgoh

Here is another method, using numbers, bases and generators [code=python] import sys if sys.version_info[0] > 2: xrange = range # python 3 compatibility def digits(n, base, how_many): """generate a given number of digits of n in base starting from the lower order digit""" for i in xrange(how_many): n, r = …

Member Avatar for squallgoh
0
142
Member Avatar for nomemory

In python, [icode]x = y[/icode] is a statement. It can't be used as an expression. You should write [code=python] import random a =int(random.triangular(1,100)) c = 0 while True: b = int(random.triangular(1, 100)) if b == a: break else: c += 1 print(c) [/code]

Member Avatar for woooee
1
217
Member Avatar for patto78

hm, how about using the standard lib ? (python 2.6) [code=python] from itertools import permutations letters = "abcd" for p in permutations(letters): print ''.join(p) """ my output ---> abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca …

Member Avatar for patto78
0
142
Member Avatar for alex-VX

I suggest [code=python] self.root.destroy() break [/code] to exit the while loop. edit: sorry, there are 2 while loops. What's the use of the while True ?

Member Avatar for alex-VX
0
205
Member Avatar for nunos

It's best to use a set and also generator expressions like this [code=python] exclude_set = set(exclude_list) print [f for f in main_list if not (f.order_id in exclude_set)] [/code]

Member Avatar for nunos
0
344
Member Avatar for Gribouillis

When several producer threads put items in a queue.Queue, and a consumer thread gets items from the queue, there is no way for the consumer thread to tell the producers that they should stop feeding the queue. This snippet defines a subclass of Queue with a close method. After the …

Member Avatar for Gribouillis
0
320
Member Avatar for catcit

This works for me [code=python] from progress import PB from time import sleep def main(): bar = PB(300, 50) bar.open() for i in range(10): bar.update((10.0 * i) / 100) sleep(1) bar.close() main() [/code] Also, you could replace [icode]self.__root = Tkinter.Toplevel()[/icode] by [icode]self.__root = Tkinter.Tk()[/icode] (or add an argument to __init__ …

Member Avatar for vegaseat
0
564

The End.