2,646 Posted Topics
Re: 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 … | |
Re: 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 … | |
Re: 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] | |
Re: [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] | |
Re: 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] | |
Re: 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 … | |
Re: @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. | |
Re: 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 … | |
Re: [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, … ![]() | |
Re: [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. | |
Re: For linux, you should distribute the python file directly, because most linux distributions come with python installed. | |
Re: [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 … | |
Re: 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 … | |
Re: 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 ?). | |
Re: 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 … | |
Re: 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 … | |
Re: 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 … | |
Re: [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] | |
Re: 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]. | |
Re: Did you try [icode]eval[/icode] ? [code=python] data = "volume(50)" eval(data) [/code] | |
Re: I'm using an online dictionary. This is what I get for [url=http://dictionnaire.reverso.net/anglais-francais/potato/forced]potato[/url] :) | |
Re: 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] | |
Re: [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 = … | |
Re: 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'. | |
Re: 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 … ![]() | |
Re: 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] | |
Re: 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 … | |
Re: If you're with windows, you should probably simply rename your main program with the extension [icode].pyw[/icode] instead of [icode].py[/icode]. | |
Re: [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). … | |
Re: It could be useful to visit the [url=http://www.dlitz.net/software/pycrypto/]pycrypto[/url] page. | |
Re: 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 ? | |
Re: 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. | |
Re: 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] [ … | |
Re: [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 … | |
Re: [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. | |
Re: [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 … | |
Re: 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 … | |
Re: [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]. | |
Re: 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 … | |
Re: 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 … ![]() | |
Re: [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]. | |
Re: 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 = … | |
Re: 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] | |
Re: 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 … | |
Re: 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 ? | |
Re: 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] | |
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 … | |
Re: 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__ … |
The End.