2,646 Posted Topics
Re: `makedirs()` fails if the directory already exists. In this case you don't need to create the directory: simply catch the exception try: os.makedirs(mypath) except OSError: # either dir already exists or can't create. # we can check if not os.path.isdir(mypath): # dir doesn't exist, propagate the exception raise # if … | |
Re: Here is a good [introduction to classes](http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm). | |
Re: If you only want to type python in your html files, use a template engine like Mako. | |
Re: In a test, a value is converted to a boolean using it `__nonzero__` method (in python 3 it's `__bool__`). Here is an example >>> class A(object): ... def __nonzero__(self): ... print("__nonzero__() called") ... return True ... >>> a = A() >>> if a: ... print("success") ... __nonzero__() called success >>> … | |
Re: Our rule is to only give homework help to students who show effort, so the first step is to post your attempts to solve the problem in the form of python code. Start with the code to get day, month and year from the user. | |
Re: I wrote a module anyfloat for you in a previous thread, which does exactly this, why don't you use it ? >>> from anyfloat import anyfloat >>> anyfloat.from_float(1.6875).bin((3, 4)) '0 011 1011' >>> anyfloat.from_float(-1313.3125).bin((8, 23)) '1 10001001 01001000010101000000000' >>> anyfloat.from_float(0.1015625).bin((8, 23)) '0 01111011 10100000000000000000000' | |
Re: At line 18, you're passing a Coumpound instance to `items_string()`. You should probably pass `self.items_list`. Otherwise, it's always better to post full traceback (in a code box). | |
Re: The default implementation is called C python. It is the main flavor of python, compiled from C. I would recommend C python unless you have specific needs in your apps. In practice, code written for IronPython will access microsoft .net classes, code written for Jython will access java classes, code … | |
Re: The `if resp ...` part should be indented. Between an if and a corresponding elif, all lines must be indented. | |
Re: There is also format() >>> p = 4.1895030939393 >>> print("Your total including tax is {:.2f}.".format(p)) Your total including tax is 4.19. | |
Re: First you could check the content of the folder `C:\Python27\Scripts` with the file browser to see if it contains `easy_install.exe`. You can also install this small app [locate32](http://locate32.cogit.net/) which can easily find any file in your system. If there is no easy_install, locate32 will find out. The `Path` environment variable … | |
Re: Here is a session with the find() method >>> s = '"Give me bacon and eggs", said the other man' # (Hemingway) >>> s.find("an") 15 # substring "an" found in position 15 >>> s[15:15+2] 'an' >>> s.find("an", 15+2) 42 # after position 17, "an" found in position 42 >>> s[42:42+2] … | |
Re: It's because you are only testing the search result on the last item of the sequence. Write `if result:` in the for loop. | |
Re: Your triangle condition is false as `(-1, 4, 2)` would be a triangle. A correct condition is simply `abs(b-c) < a < b+c`. I would check 'triangulity' at object creation and raise ValueError if it fails #from math import* class Triangle(object): """Checks if given sides can make a Triangle then … | |
Re: It works for me with python 2.7.2 in linux. You could try this from xml.etree import ElementTree as ET from xml.etree.ElementTree import XMLParser parser = XMLParser(encoding="utf-8") optionstree = ET.parse("test.conf", parser=parser) | |
Re: You can rewrite PyTony's snippet with only 1 variable x >>> print(list(x for x in itertools.product(range(1, 100), repeat=3) if x[0]<=x[1]<=x[2] and x[0]**2 + x[1]**2 == x[2]**2)) Another nice tool is generators def orduples(size, start, stop, step=1): if size == 0: yield () elif size == 1: for x in range(start, … | |
Re: At line 16, your program is using a value C which was not defined before. At line 18 and 20, you're using a value F which was not defined before. | |
This snippet allows one to implement an equivalent of a `__getattr__()` function in a python module. The module can then define its own way to lazily import abitrary symbols. For example the module can contain infinitely many names or load values from other modules on demand. There are many implementations … | |
Re: Implement it yourself from __future__ import generators # does your python need this ? def enumerate(iterable, start=0): i = start - 1 for item in iterable: i += 1 yield (i, item) | |
Re: try print('Player %s:' % x) | |
Re: It seems that you can change the cmd console encoding to utf8 with the command `chcp 65001`. See [here](http://wei-jiang.com/system/windows/how-to-set-unicode-encoding-in-windows-command-line) and [here](http://superuser.com/questions/269818/change-default-code-page-of-windows-console-to-utf-8). | |
Re: You can call the setx command from python using subprocess.Popen. | |
Re: I agree with tony that everything is fine if you replace Robots by Robot. However my advice is __not__ to define objects with a `__del__()` method because they can create uncollectable objects if they are part of a reference cycle (read the documentation of `gc.garbage` about this). There are other … | |
Re: I couldn't find the error, but I changed the code a little bit, this one works #!/usr/bin/env python # -*-coding: utf8-*- import math def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) def series_term(k): a=factorial(4*k) b=(1103+26390*k) c=factorial(k) d=c**4 e=396**(4*k) return float(a*b)/(d*e) def estimatePi(): k=0 final=0 while … | |
Re: Add a few print statements to see what's going on def tictactoe(moves): for r in range(len(moves)): for c in range(len(moves[r])): print("(r, c) =", (r, c)) if moves[0][c]==moves[1][c]==moves[2][c]: a="'%s' wins (%s)."%((moves[0][c]),'vertical') elif moves[r][0]==moves[r][1]==moves[r][2]: a="'%s' wins (%s)."%((moves[r][0]),'horizontal') elif moves[0][0]==moves[1][1]==moves[2][2]: a="'%s' wins (%s)."%((moves[0][0]),'diagonal') elif moves[0][2]==moves[1][1]==moves[2][0]: a="'%s' wins (%s)."%((moves[0][2]),'diagonal') else: a='Draw.' print("currently, a =", … | |
Re: You can get a list of indexes for which there is more than 1 item >>> available_troops = [[1, 0, 1], [2, 0, 1], [3, 0, 1], [4, 0, 1], [5, 0, 1], [6, 0, 1], [7, 0, 1], [8, 0, 1], [9, 0, 1], [10, 0, 1], [11, 0, … | |
Re: It won't be that easy as the code uses the python imaging library. From what I read here and there, IronPython can't use PIL because it's a C extension to python. It means that you need to replace PIL by a C# library to manipulate images. | |
Re: You can use a GUI to visualize your algorithm. Here is a program I found [HERE](http://python-turtle-demo.googlecode.com/hg-history/c04c04c020d327b9690cf1d353ec7c419ad51626/Python2.x/standalone/turtle_hanoi.py) using the turtle module to solve the hanoi problem, written by Gregor Lingl. This program contains an algorithm, but you you can use it to run your own algorithm too. For this, use the … | |
Re: I see a way, but there is some work to do. First you convert your regular expression to a NFA (non deterministic finite automaton) with a start state and an accept state. In this NFA, you add an epsilon-transition from the start state to every other state and an epsilon … | |
Re: [Pypdf](http://pybrary.net/pyPdf/) claims to have a py3k compatible branch (read the section 'Source Code Repository') The repository is [here](https://github.com/mfenniak/pyPdf/tree/py3). Try it and let us know if it works with your version of python 3. | |
Re: Replace line 7 with `sum += lines.count(word)`. You can also remove line 6. | |
Re: What's the content of buff ? socket.recv() can receive arbitrary data. | |
Re: One way is to register command handler functions with a decorator: FUNCDICT = dict() def cmd_handler(func): assert func.__name__.endswith('cmd') FUNCDICT[func.__name__[:-3]] = func return func @cmd_handler def echocmd(...): ... @cmd_handler def catcmd(...): ... # etc Functions are automatically added to FUNCDICT as you write them. Did you read about the standard [module … | |
Re: The sendto() documentation says socket.sendto(string[, flags], address): Send data to the socket. The socket **should not be connected** to a remote socket, since the destination socket is specified by address. So perhaps you should remove the first call to connect(). | |
Re: I suppose you connect a socket to ("192.168.1.50", 5149) and then invoke `sock.sendall("power=1\n")`. See the socket module documentation and try to run some code. | |
![]() | Re: There are unbalanced parenthesis at lines 1 and 3 ... SyntaxError usually means a very simple issue: most of the time an unbalanced parenthesis, sometimes a missing comma or colon ;) |
Re: `12.0.0.0` is not a valid python literal. Use `"12.0.0.0"` which creates a str instance. | |
Re: If you want to handle larger numbers, you must add a while loop which runs as long as the number is not zero. Here is a way to do it HEX_DIGITS = "0123456789ABCDEF" def hex_digit(n): """Compute the hexadecimal digit for a number n in [0, 16[. >>> hex_digit(7) '7' >>> … | |
Re: You can add a positional argument but your code must conform the rules to call the `dict()` function. For example this doesn't work >>> dict(20, 30) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: dict expected at most 1 arguments, got 2 Here is what the … | |
Re: Well, here is how you could use the abstract base classes in module `collections` to implement such custom types. Here a list type which item types are given. Notice that this class uses 'converters' instead of types, which means that complex behavior can be implemented whith regards to the conditions … | |
Re: I don't know about julian date, but google led me to [this module](https://github.com/adrn/apwlib) (under GPL) which seems to implement the desired functionality by subclassing datetime. Conversion between degrees and radians can be done with math.degrees() and math.radians() in the standard library (numpy versions exist as well). | |
Re: I found [this](http://www.ibrado.org/post/370261203). You could replace the bash script by a python script. You must learn a bit of the launchd system in mac os (which I don't know). | |
Re: It's not at all safe, the string could contain `shutil.rmtree()`. My advice is to write a true math parser, or use pyTony's snippet. | |
Re: To simulate a command line interpreter, play with the cmd module from cmd import Cmd class Interpreter(Cmd): def emptyline(self): pass def do_ECHO(self, line): print(line) def do_QUIT(self, line): return True interp = Interpreter() interp.prompt = "> " interp.cmdloop("\nWELCOME\n") """ my output --> WELCOME > ECHO hello world hello world > > … | |
Re: This project needs more than a badly put together code snippet. Learn about xmlrpclib first, by running the examples in the documentation. Your program needs a thread to start the xmlrpc server to receive the other side's messages and a user interface to forward your messages to xmlrpc calls and … | |
Re: A simple way to communicate is to use the standard module xmlrpc. This is very easy to use on your local network. | |
| |
Re: You are trying to create a configuration file. Python has a module named ConfigParser (configparser in python 3) to handle this. A configurationf file would look like this # file myconfig.cfg [user-info] # <-- this is a section header (required for configparser) username=Eugene password=eugene The code to read the file … | |
Re: You mean perhaps something like def local_hot_list(filename, day_to_extract): f1 = h5py.File(filename, 'r') data = f1['Data'] temp = data['Temperature'] temp_day = numpy.array(temp[day_to_extract]) press_head = data['Pressure_Head'] press_day = numpy.array(press_head[day_to_extract]) geo = f1['Geometry'] nodes = geo['orig_node_number'] orig_nodes = numpy.array(nodes['0']) return numpy.column_stack((orig_nodes,press_day,temp_day)) complete_hot_list = numpy.vstack(tuple(local_hot_list(name, day_to_extract) for name in local_files)) ? |
The End.