Search Results

Search found 15187 results on 608 pages for 'boost python'.

Page 126/608 | < Previous Page | 122 123 124 125 126 127 128 129 130 131 132 133  | Next Page >

  • Resizing image with Python with locked aspect ratio

    - by David Vinklar
    How should I resize an image with Python script so that it would automatically adjust the Height ratio to the Width used? I'm using the following code: def Do(Environment): # Resize App.Do( Environment, 'Resize', { 'AspectRatio': 1.33333, 'CurrentDimensionUnits': App.Constants.UnitsOfMeasure.Pixels, 'CurrentResolutionUnits': App.Constants.ResolutionUnits.PixelsPerIn, 'Height': 1440, 'MaintainAspectRatio': True, 'Resample': True, 'ResampleType': App.Constants.ResampleType.SmartSize, 'ResizeAllLayers': True, 'Resolution': 72, 'Width': 1920, }) Using this code works perfectly if the aspect ratio of an image is the same as the one defined in the code - i.e. 1.33333. But how should I make it work with images that do not have this ratio? For me, what is important is that the new Width is 1920; Height has to be able to adjust automatically. Any ideas which part of my code should be altered and how?

    Read the article

  • Unescape _xHHHH_ XML escape sequences using Python

    - by John Machin
    I'm using Python 2.x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the _xHHHH_ convention e.g. ASCII BEL aka U+0007 is represented by the 7-character sequence u"_x0007_". Neither the functionality that allows representation of any old character in the document nor the manner of escaping is negotiable. I'm parsing the documents using cElementTree or lxml [semi-negotiable]. Here is my best attempt at unescapeing the parser output as efficiently as possible: import re def unescape(s, subber=re.compile(r'_x[0-9A-Fa-f]{4,4}_').sub, repl=lambda mobj: unichr(int(mobj.group(0)[2:6], 16)), ): if "_" in s: return subber(repl, s) return s The above is biassed by observing a very low frequency of "_" in typical text and a better-than-doubling of speed by avoiding the regex apparatus where possible. The question: Any better ideas out there?

    Read the article

  • Converting HTML special characters into their value using Python

    - by tipu
    I have a file that's littered with these: http://www.utexas.edu/learn/html/spchar.html That link just displays all sorts of HTML entities, such as – &ndash; — &mdash; ¡ &iexcl; and so on. Is it possible in Python to natively convert these characters back into their values so any occurrences of &ndash; will appear as – instead? My current approach was just to make a dict of key html entities and their utf-8 values and do search and replace, but I was wondering if there are any libraries that can take care of this for me.

    Read the article

  • difference in logging mechanism: API and application(python)

    - by zubin71
    I am currently writing an API and an application which uses the API. I have gotten suggestions from people stating that I should perform logging using handlers in the application and use a "logger" object for logging from the API. In light of the advice I received above, is the following implementation correct? class test: def __init__(self, verbose): self.logger = logging.getLogger("test") self.logger.setLevel(verbose) def do_something(self): # do something self.logger.log("something") # by doing this i get the error message "No handlers could be found for logger "test" The implementation i had in mind was as follows: #!/usr/bin/python """ .... .... create a logger with a handler .... .... """ myobject = test() try: myobject.do_something() except SomeError: logger.log("cant do something") Id like to get my basics strong, id be grateful for any help and suggestions for code you might recommend I look up. Thnkx!

    Read the article

  • Vim: Goot AutoCompletion Plugin for Python and PHP

    - by Rafid K. Abdullah
    I use Vim with ctags for development. I found ctags to be very useful in going to definitions, but I don't know a good plugin to make use of ctags for clever auto completion. It seems that the default Vim auto completion is not good. When I write set omnifunc? in Vim, I get this: omnifunction=pythoncomplete#Complete I do know about OmniComplete for C++, but I don't know any good plugin for Python and PHP. Does anybody have an idea?

    Read the article

  • math syntax checker written in python

    - by neurino
    All I need is to check, using python, if a string is a valid math expression or not. For simplicity let's say I just need + - * / operators (+ - as unary too) with numbers and nested parenthesis. I add also simple variable names for completeness. So I can test this way: test("-3 * (2 + 1)") #valid test("-3 * ") #NOT valid test("v1 + v2") #valid test("v2 - 2v") #NOT valid ("2v" not a valid variable name) I tried pyparsing but just trying the example: "simple algebraic expression parser, that performs +,-,*,/ and ^ arithmetic operations" I get passed invalid code and also trying to fix it I always get wrong syntaxes being parsed without raising Exceptions just try: >>>test('9', 9) 9 qwerty = 9.0 ['9'] => ['9'] >>>test('9 qwerty', 9) 9 qwerty = 9.0 ['9'] => ['9'] both test pass... o_O Any advice?

    Read the article

  • Python - Converting CSV to Objects - Code Design

    - by victorhooi
    Hi, I have a small script we're using to read in a CSV file containing employees, and perform some basic manipulations on that data. We read in the data (import_gd_dump), and create an Employees object, containing a list of Employee objects (maybe I should think of a better naming convention...lol). We then call clean_all_phone_numbers() on Employees, which calls clean_phone_number() on each Employee, as well as lookup_all_supervisors(), on Employees. import csv import re import sys #class CSVLoader: # """Virtual class to assist with loading in CSV files.""" # def import_gd_dump(self, input_file='Gp Directory 20100331 original.csv'): # gd_extract = csv.DictReader(open(input_file), dialect='excel') # employees = [] # for row in gd_extract: # curr_employee = Employee(row) # employees.append(curr_employee) # return employees # #self.employees = {row['dbdirid']:row for row in gd_extract} # Previously, this was inside a (virtual) class called "CSVLoader". # However, according to here (http://tomayko.com/writings/the-static-method-thing) - the idiomatic way of doing this in Python is not with a class-fucntion but with a module-level function def import_gd_dump(input_file='Gp Directory 20100331 original.csv'): """Return a list ('employee') of dict objects, taken from a Group Directory CSV file.""" gd_extract = csv.DictReader(open(input_file), dialect='excel') employees = [] for row in gd_extract: employees.append(row) return employees def write_gd_formatted(employees_dict, output_file="gd_formatted.csv"): """Read in an Employees() object, and write out each Employee() inside this to a CSV file""" gd_output_fieldnames = ('hrid', 'mail', 'givenName', 'sn', 'dbcostcenter', 'dbdirid', 'hrreportsto', 'PHFull', 'PHFull_message', 'SupervisorEmail', 'SupervisorFirstName', 'SupervisorSurname') try: gd_formatted = csv.DictWriter(open(output_file, 'w', newline=''), fieldnames=gd_output_fieldnames, extrasaction='ignore', dialect='excel') except IOError: print('Unable to open file, IO error (Is it locked?)') sys.exit(1) headers = {n:n for n in gd_output_fieldnames} gd_formatted.writerow(headers) for employee in employees_dict.employee_list: # We're using the employee object's inbuilt __dict__ attribute - hmm, is this good practice? gd_formatted.writerow(employee.__dict__) class Employee: """An Employee in the system, with employee attributes (name, email, cost-centre etc.)""" def __init__(self, employee_attributes): """We use the Employee constructor to convert a dictionary into instance attributes.""" for k, v in employee_attributes.items(): setattr(self, k, v) def clean_phone_number(self): """Perform some rudimentary checks and corrections, to make sure numbers are in the right format. Numbers should be in the form 0XYYYYYYYY, where X is the area code, and Y is the local number.""" if self.telephoneNumber is None or self.telephoneNumber == '': return '', 'Missing phone number.' else: standard_format = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{4})-(?P<local_second_half>\d{4})') extra_zero = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{4})-(?P<local_second_half>\d{4})') missing_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{4})(?P<local_second_half>\d{4})') if standard_format.search(self.telephoneNumber): result = standard_format.search(self.telephoneNumber) return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), '' elif extra_zero.search(self.telephoneNumber): result = extra_zero.search(self.telephoneNumber) return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), 'Extra zero in area code - ask user to remediate. ' elif missing_hyphen.search(self.telephoneNumber): result = missing_hyphen.search(self.telephoneNumber) return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), 'Missing hyphen in local component - ask user to remediate. ' else: return '', "Number didn't match recognised format. Original text is: " + self.telephoneNumber class Employees: def __init__(self, import_list): self.employee_list = [] for employee in import_list: self.employee_list.append(Employee(employee)) def clean_all_phone_numbers(self): for employee in self.employee_list: #Should we just set this directly in Employee.clean_phone_number() instead? employee.PHFull, employee.PHFull_message = employee.clean_phone_number() # Hmm, the search is O(n^2) - there's probably a better way of doing this search? def lookup_all_supervisors(self): for employee in self.employee_list: if employee.hrreportsto is not None and employee.hrreportsto != '': for supervisor in self.employee_list: if supervisor.hrid == employee.hrreportsto: (employee.SupervisorEmail, employee.SupervisorFirstName, employee.SupervisorSurname) = supervisor.mail, supervisor.givenName, supervisor.sn break else: (employee.SupervisorEmail, employee.SupervisorFirstName, employee.SupervisorSurname) = ('Supervisor not found.', 'Supervisor not found.', 'Supervisor not found.') else: (employee.SupervisorEmail, employee.SupervisorFirstName, employee.SupervisorSurname) = ('Supervisor not set.', 'Supervisor not set.', 'Supervisor not set.') #Is thre a more pythonic way of doing this? def print_employees(self): for employee in self.employee_list: print(employee.__dict__) if __name__ == '__main__': db_employees = Employees(import_gd_dump()) db_employees.clean_all_phone_numbers() db_employees.lookup_all_supervisors() #db_employees.print_employees() write_gd_formatted(db_employees) Firstly, my preamble question is, can you see anything inherently wrong with the above, from either a class design or Python point-of-view? Is the logic/design sound? Anyhow, to the specifics: The Employees object has a method, clean_all_phone_numbers(), which calls clean_phone_number() on each Employee object inside it. Is this bad design? If so, why? Also, is the way I'm calling lookup_all_supervisors() bad? Originally, I wrapped the clean_phone_number() and lookup_supervisor() method in a single function, with a single for-loop inside it. clean_phone_number is O(n), I believe, lookup_supervisor is O(n^2) - is it ok splitting it into two loops like this? In clean_all_phone_numbers(), I'm looping on the Employee objects, and settings their values using return/assignment - should I be setting this inside clean_phone_number() itself? There's also a few things that I'm sorted of hacked out, not sure if they're bad practice - e.g. print_employee() and gd_formatted() both use __dict__, and the constructor for Employee uses setattr() to convert a dictionary into instance attributes. I'd value any thoughts at all. If you think the questions are too broad, let me know and I can repost as several split up (I just didn't want to pollute the boards with multiple similar questions, and the three questions are more or less fairly tightly related). Cheers, Victor

    Read the article

  • vectorized approach to binning with numpy/scipy in Python

    - by user248237
    I am binning a 2d array (x by y) in Python into the bins of its x value (given in "bins"), using np.digitize: elements_to_bins = digitize(vals, bins) where "vals" is a 2d array, i.e.: vals = array([[1, v1], [2, v2], ...]). elements_to_bins just says what bin each element falls into. What I then want to do is get a list whose length is the number of bins in "bins", and each element returns the y-dimension of "vals" that falls into that bin. I do it this way right now: points_by_bins = [] for curr_bin in range(min(elements_to_bins), max(elements_to_bins) + 1): curr_indx = where(elements_to_bins == curr_bin)[0] curr_bin_vals = vals[:, curr_indx] points_by_bins.append(curr_bin_vals) is there a more elegant/simpler way to do this? All I need is a list of of lists of the y-values that fall into each bin. thanks.

    Read the article

  • How to evaluate javascript code in Python

    - by overboming
    I need to fetch some result on a webpage, which use some javascript code to generate the part I am interesting in like following eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--)d[c]=k[c]||c;k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p;}('5 11=17;5 12=["/3/2/1/0/13.4","/3/2/1/0/15.4","/3/2/1/0/14.4","/3/2/1/0/7.4","/3/2/1/0/6.4","/3/2/1/0/8.4","/3/2/1/0/10.4","/3/2/1/0/9.4","/3/2/1/0/23.4","/3/2/1/0/22.4","/3/2/1/0/24.4","/3/2/1/0/26.4","/3/2/1/0/25.4","/3/2/1/0/18.4","/3/2/1/0/16.4","/3/2/1/0/19.4","/3/2/1/0/21.4"];5 20=0;',10,27,'40769|54|Images|Files|png|var|imanhua_005_140430179|imanhua_004_140430179|imanhua_006_140430226|imanhua_008_140430242|imanhua_007_140430226|len|pic|imanhua_001_140429664|imanhua_003_140430117|imanhua_002_140430070|imanhua_015_140430414||imanhua_014_140430382|imanhua_016_140430414|sid|imanhua_017_140430429|imanhua_010_140430289|imanhua_009_140430242|imanhua_011_140430367|imanhua_013_140430382|imanhua_012_140430367'.split('|'),0,{})) The result of eval() is valuable to me, I am writing a Python script, is there any library I can use to virtually run this piece of javascript code and get the output? Thanks

    Read the article

  • Elegant setup of Python logging in Django

    - by Parand
    I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple: Different log handlers for different events - that is, I want to be able to log to different files Easy access to loggers in my modules. The module should be able to find its logger with little effort. Should be easily applicable to command-line modules. Parts of the system are stand-alone command line or daemon processes. Logging should be easily usable with these modules. My current setup is to use a logging.conf file and setup logging in each module I log from. It doesn't feel right. Do you have a logging setup that you like? Please detail it: how do you setup the configuration (do you use logging.conf or set it up in code), where/when do you initiate the loggers, and how do you get access to them in your modules, etc.

    Read the article

  • Is Using Python to MapReduce for Cassandra Dumb?

    - by UltimateBrent
    Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something? The application is stats collection, so I need to be able to sum values with grouping to increment counters. I'm not, but pretend I'm making Google analytics so I want to keep track of which browsers appear, which pages they went to, and visits vs. pageviews. I would just atomically update my counters on write, but Cassandra isn't very good at counters either. May Cassandra just isn't the right choice for this? Thanks!

    Read the article

  • Python code formatting

    - by Curious2learn
    In response to another question of mine, someone suggested that I avoid long lines in the code and to use PEP-8 rules when writing Python code. One of the PEP-8 rules suggested avoiding lines which are longer than 80 characters. I changed a lot of my code to comply with this requirement without any problems. However, changing the following line in the manner shown below breaks the code. Any ideas why? Does it have to do with the fact that what follows return command has to be in a single line? The line longer that 80 characters: def __str__(self): return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price) The line changed by using Enter key and Spaces as necessary: def __str__(self): return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)

    Read the article

  • Code completion in NetBeans' python plugin does not work properly

    - by T.K.
    I am asking on StackOverflow because surely I am doing something completely silly and I hope S.O. might provide me with a quick answer. I've installed the latest stable Python-plugin for NetBeans. It works great, and I tested code completion with various packages such as sys, os and so on. It works beautifully. However, it does not seem to pick up the code completion for the code in my own project. I created a package called mypackage (it has _init_.py as well), and in it I have a module called mymodule.py. Inside mymodule I've put a class called MyClass, complete with doc-strings and all. Please refer to this screenshot to describe what happens in code-completion: As you see, it's suggesting irrelevant things, as opposed to just MyClass. (Note that if I execute mymodule.MyClass() it works 100%, it's just that I would really like code completion on my own code) Hope I'm just doing something silly here... Any ideas?

    Read the article

  • Python Profiling in Eclipse

    - by Jordan L. Walbesser
    This questions is semi-based of this one here: http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script I thought that this would be a great idea to run on some of my programs. Although profiling from a batch file as explained in the aforementioned answer is possible, I think it would be even better to have this option in Eclipse. At the same time, making my entire program a function and profiling it would mean I have to alter the source code? How can I configure eclipse such that I have the ability to run the profile command on my existing programs? Any tips or suggestions are welcomed!

    Read the article

  • Python subprocess.Popen

    - by Albert
    I have that code: #!/usr/bin/python -u localport = 9876 import sys, re, os from subprocess import * tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT) print "** Started tunnel, waiting to be ready ..." for l in tun.stdout: sys.stdout.write(l) if re.search("Waiting for connection", l): print "** Ready for SSH !" break The "./newtunnel" will not exit, it will constantly output more and more data to stdout. However, that code will not give any output and just keeps waiting in the tun.stdout. When I kill the newtunnel process externally, it flushes all the data to tun.stdout. So it seems that I can't get any data from the tun.stdout while it is still running. Why is that? How can I get the information? Note that the default bufsize for Popen is 0 (unbuffered). I can also specify bufsize=0 but that doesn't change anything.

    Read the article

  • Representing geographical points/polygons in Python/Django

    - by Cornflake
    I'm building a website in Django, and I want one of my datatypes to be a geographical polygon. I want to mark points on a map (say, in Google Maps) and then store the resulting polygon in the database. Is there any way to do it that will save me the work of typing all the longitudes and latitudes manually? I guess I'm looking both for a geographical library for Python, and for a special website that will let me mark points on the map and save them in a standard format. Thanks!

    Read the article

  • Using set in Python inside a loop

    - by user210481
    I have the following list in Python: [[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]] I want to group them into [[1,2,7],[3,4,6,7]] My code to do this looks like this: l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]] lf=[] for li in l: for lfi in lf: if lfi.intersection(set(li)): lfi=lfi.union(set(li)) break else: lf.append(set(li)) lf is my final list. I do a loop over l and lf and when I find an intersection between an element from l and another from lf, I would like to merge them (union) But I can't figure out why this is not working. The first to elements of the list l are being inserted with the append command, but the union is not working. My final list lf looks like [set([1, 2]), set([3, 4])] It seems to be something pretty basic, but I'm not familiar with sets. I appreciate any help Thanks

    Read the article

  • Include at text file as is in (Python) Sphinx Docs

    - by Gregg Lind
    (using Python-Sphinx Documentation tool) I have a .txt log file I'd like to build into _build/html unaltered. What do I need to alter in conf.py, index.rst, etc. Here is the layout: src/ index.rst some_doc.rst somefile.txt How do I get somefile.txt into the html build? I tried adding a line like this to index.rst: Contents: .. toctree:: :maxdepth: 2 some_doc "somefile.txt" hoping it would work by magic, but no magic here! Assuming this is even possible, what would I put in some_doc.rst to refer/link to that file? Note Yes, I'm aware I could put it in /static and just be done with it, but that seems like a total hack, and ugly.

    Read the article

  • Python - Things I shouldn't be doing?

    - by cornjuliox
    I've got a few questions about best practices in Python. Not too long ago I would do something like this with my code: ... junk_block = "".join(open("foo.txt","rb").read().split()) ... I don't do this anymore because I can see that it makes code harder to read, but would the code run slower if I split the statements up like so: f_obj = open("foo.txt", "rb") f_data = f_obj.read() f_data_list = f_data.split() junk_block = "".join(f_data_list) I also noticed that there's nothing keeping you from doing an 'import' within a function block, is there any reason why I should do that?

    Read the article

  • Getting Unit Tests to work with Komodo IDE for Python

    - by devoured elysium
    I've tried to run the following code on Komodo IDE (for python): import unittest class MathLibraryTests(unittest.TestCase): def test1Plus1Equals2(self): self.assertEqual(1+1, 2) Then, I created a new test plan, pointing to this project(file) directory and tried to run it the test plan. It seems to run but it doesn't seem to find any tests. If I try to run the following code with the "regular" run command (F7) class MathLibraryTests(unittest.TestCase): def testPlus1Equals2(self): self.assertEqual(1+1, 2) if __name__ == "__main__": unittest.main() it works. I get the following output: ---------------------------------------------------------------------- Ran 1 test in 0.000s OK What might I be doing wrong?

    Read the article

  • Python overriding class (not instance) special methods

    - by André
    How do I override a class special method? I want to be able to call the __str__() method of the class without creating an instance. Example: class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' class ClassFoo: @classmethod def __str__(cls): return 'ClassBar' if __name__ == '__main__': print(Foo) print(Foo()) print(StaticFoo) print(StaticFoo()) print(ClassFoo) print(ClassFoo()) produces: <class '__main__.Foo'> Bar <class '__main__.StaticFoo'> StaticBar <class '__main__.ClassFoo'> ClassBar should be: Bar Bar StaticBar StaticBar ClassBar ClassBar Even if I use the @staticmethod or @classmethod the __str__ is still using the built in python definition for __str__. It's only working when it's Foo().__str__() instead of Foo.__str__().

    Read the article

  • Python IDE built into Visual Studio 2008?

    - by Thomaschaaf
    Hi I develop in Visual Studio 2008 a lot and would like to find an addin like vsphp which enables intellisense and debugging in Visual Studio. Is IronStudio what I am looking for? As far as I understand IronStudio is a Plugin for .NET. If there is no Plugin for Visual Studio 2008 whats a great IDE for a python newbee who loves Visual Studio (hate netbeans and eclipse sorry just don't feel the love) Also if IronPython Studio is an IDE do I want the Isolated or Integrated Version? I don't seem to understand the name. I installed integrated and got this: http://dl.getdropbox.com/u/5910/Jing/2009-02-11_1750.png :( no console like here: http://www.codeplex.com/IronPythonStudio

    Read the article

  • Using Python tuples as vectors

    - by Etaoin
    I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice. The trouble is when I need to implement things like addition and scalar multiplication. If a and b are vectors, and c is a number, the best I can think of is this: tuple(map(lambda x,y: x + y, a, b)) # add vectors 'a' and 'b' tuple(map(lambda x: x * c, a)) # multiply vector 'a' by scalar 'c' which seems inelegant; there should be a clearer, simpler way to get this done -- not to mention avoiding the call to tuple, since map returns a list. Is there a better option?

    Read the article

  • Use eval to set unknown property in Python

    - by Mahi
    I have an User class, that has multiple properties inside it, and I also have addPoint method for User class, which allows user to input points into any of it's properties. However, there can be up to like 500 properties, everyone can have different ones, etc. So it would be a pain in the ass to code every property with "if: - elif:". Now this is what I tried to do, to make it much easier and cleaner: class User: def __init__(self): self.health = 0 self.speed = 0 def addPoint(self, property, amount): eval("self."+property) = eval("self."+property) + amount And now when I'd do fe. u = User() u.addPoint("health", 5) I would like it to do this: self.health = self.health + 5, and that's what I used the eval()s for. However, Python's just giving me error: can't assign to function call. I'm not trying to assign the eval() function call itself, I'm trying to assign the returned value from eval(), so how could I do this the easiest way?

    Read the article

  • How to evaluate a custom math expression in Python

    - by taynaron
    I'm writing a custom dice rolling parser (snicker if you must) in python. Basically, I want to use standard math evaluation but add the 'd' operator: #xdy sum = 0 for each in range(x): sum += randInt(1, y) return sum So that, for example, 1d6+2d6+2d6-72+4d100 = (5)+(1+1)+(6+2)-72+(5+39+38+59) = 84 I was using regex to replace all 'd's with the sum and then using eval, but my regex fell apart when dealing with parentheses on either side. Is there a faster way to go about this than implementing my own recursive parsing? Perhaps adding an operator to eval?

    Read the article

< Previous Page | 122 123 124 125 126 127 128 129 130 131 132 133  | Next Page >