2,646 Posted Topics

Member Avatar for mohsin.javaid.73

`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 …

Member Avatar for mohsin.javaid.73
0
136
Member Avatar for krystosan

Here is a good [introduction to classes](http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm).

Member Avatar for krystosan
0
192
Member Avatar for snakesonaplane
Member Avatar for snakesonaplane
0
241
Member Avatar for shanenin
Re: True

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 >>> …

Member Avatar for Gribouillis
0
112
Member Avatar for jaynew

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.

Member Avatar for jaynew
0
119
Member Avatar for Tcll

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'

Member Avatar for Tcll
0
223
Member Avatar for cruze098

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).

Member Avatar for Gribouillis
0
383
Member Avatar for silvercats

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 …

Member Avatar for Gribouillis
0
158
Member Avatar for mbh1992

The `if resp ...` part should be indented. Between an if and a corresponding elif, all lines must be indented.

Member Avatar for mbh1992
0
850
Member Avatar for hotblink

There is also format() >>> p = 4.1895030939393 >>> print("Your total including tax is {:.2f}.".format(p)) Your total including tax is 4.19.

Member Avatar for TrustyTony
0
201
Member Avatar for jacarandatree

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 …

Member Avatar for Gribouillis
0
115
Member Avatar for zeeters

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] …

Member Avatar for zeeters
0
3K
Member Avatar for krystosan

It's because you are only testing the search result on the last item of the sequence. Write `if result:` in the for loop.

Member Avatar for krystosan
0
157
Member Avatar for M.S.

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 …

Member Avatar for M.S.
0
253
Member Avatar for jakehardy

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)

Member Avatar for Gribouillis
0
317
Member Avatar for athulram

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, …

Member Avatar for athulram
0
4K
Member Avatar for PythonMonty

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.

Member Avatar for HiHe
0
795
Member Avatar for Gribouillis

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 …

Member Avatar for Gribouillis
1
529
Member Avatar for crishein14

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)

Member Avatar for M.S.
0
173
Member Avatar for rbsmith333
Member Avatar for rwe0

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).

Member Avatar for rwe0
0
234
Member Avatar for sandorlev
Member Avatar for Frensi

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 …

Member Avatar for Gribouillis
0
310
Member Avatar for fasna

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 …

Member Avatar for fasna
0
730
Member Avatar for 3e0jUn
Member Avatar for fasna

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 =", …

Member Avatar for Gribouillis
0
336
Member Avatar for toyotajon93

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, …

Member Avatar for Gribouillis
0
173
Member Avatar for Mahesh57

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.

Member Avatar for Gribouillis
0
395
Member Avatar for peterparker

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 …

Member Avatar for peterparker
0
2K
Member Avatar for aint

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 …

Member Avatar for TrustyTony
0
319
Member Avatar for rwe0

[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.

Member Avatar for rwe0
0
201
Member Avatar for munieb

Replace line 7 with `sum += lines.count(word)`. You can also remove line 6.

Member Avatar for snippsat
0
170
Member Avatar for tunisia
Member Avatar for Gribouillis
0
108
Member Avatar for Plazmotech

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 …

Member Avatar for Gribouillis
0
183
Member Avatar for deepthought

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().

Member Avatar for TrustyTony
0
651
Member Avatar for tunisia

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.

Member Avatar for tunisia
0
375
Member Avatar for HTMLperson5

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 ;)

Member Avatar for HiHe
1
176
Member Avatar for jwalajoseph

`12.0.0.0` is not a valid python literal. Use `"12.0.0.0"` which creates a str instance.

Member Avatar for ryantroop
0
130
Member Avatar for peterparker

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' >>> …

Member Avatar for peterparker
0
1K
Member Avatar for hughesadam_87

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 …

Member Avatar for hughesadam_87
0
726
Member Avatar for hughesadam_87

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 …

Member Avatar for hughesadam_87
0
441
Member Avatar for manticmadman

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).

Member Avatar for hughesadam_87
0
373
Member Avatar for Plazmotech

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).

Member Avatar for Plazmotech
0
242
Member Avatar for Frensi

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.

Member Avatar for HiHe
0
6K
Member Avatar for 3e0jUn

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 > > …

Member Avatar for TrustyTony
0
187
Member Avatar for 3e0jUn

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 …

Member Avatar for Gribouillis
0
526
Member Avatar for 3e0jUn

A simple way to communicate is to use the standard module xmlrpc. This is very easy to use on your local network.

Member Avatar for 3e0jUn
0
158
Member Avatar for p34i
Member Avatar for 3e0jUn

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 …

Member Avatar for 3e0jUn
0
245
Member Avatar for fatalaccidents

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)) ?

Member Avatar for fatalaccidents
0
365

The End.