Search Results

Search found 13534 results on 542 pages for 'python'.

Page 18/542 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Project Euler 14: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 14.  As always, any feedback is welcome. # Euler 14 # http://projecteuler.net/index.php?section=problems&id=14 # The following iterative sequence is defined for the set # of positive integers: # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate # the following sequence: # 13 40 20 10 5 16 8 4 2 1 # It can be seen that this sequence (starting at 13 and # finishing at 1) contains 10 terms. Although it has not # been proved yet (Collatz Problem), it is thought that all # starting numbers finish at 1. Which starting number, # under one million, produces the longest chain? # NOTE: Once the chain starts the terms are allowed to go # above one million. import time start = time.time() def collatz_length(n): # 0 and 1 return self as length if n <= 1: return n length = 1 while (n != 1): if (n % 2 == 0): n /= 2 else: n = 3*n + 1 length += 1 return length starting_number, longest_chain = 1, 0 for x in xrange(1, 1000001): l = collatz_length(x) if l > longest_chain: starting_number, longest_chain = x, l print starting_number print longest_chain # Slow 31 seconds print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Cross-platform desktop programming: C++ vs. Python

    - by John Wells
    Alright, to start off, I have experience as an amateur Obj-C/Cocoa and Ruby w/Rails programmer. These are great, but they aren't really helpful for writing cross-platform applications (hopefully GNUStep will one day be complete enough for the first to be multi platform, but that day is not today). C++, from what I can gather, is extremely powerful but also a huge, ugly behemoth that can take half a decade or more to master. I've also read that you can very easily not only shoot yourself in the foot, but blow your entire leg off with it since memory management is all manual. Obviously, this is all quite intimidating. Is it correct? Python seems to provide most of the power of C++ and is much easier to pick up at the cost of speed. How big is this sacrifice? Is it meaningful or can it be ignored? Which will have me writing fast, stable, highly reliable applications in a reasonable amount of time? Also, is it better to use Qt for your UI or instead maintain separate, native front ends for each platform? EDIT: For extra clarity, there are two types applications I want to write: one is an extremely friendly and convenient database frontend and the other, which no doubt will come much later on, is a 3D world editor.

    Read the article

  • Project Euler 12: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 12.  As always, any feedback is welcome. # Euler 12 # http://projecteuler.net/index.php?section=problems&id=12 # The sequence of triangle numbers is generated by adding # the natural numbers. So the 7th triangle number would be # 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms # would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle # numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # We can see that 28 is the first triangle number to have # over five divisors. What is the value of the first # triangle number to have over five hundred divisors? import time start = time.time() from math import sqrt def divisor_count(x): count = 2 # itself and 1 for i in xrange(2, int(sqrt(x)) + 1): if ((x % i) == 0): if (i != sqrt(x)): count += 2 else: count += 1 return count def triangle_generator(): i = 1 while True: yield int(0.5 * i * (i + 1)) i += 1 triangles = triangle_generator() answer = 0 while True: num = triangles.next() if (divisor_count(num) >= 501): answer = num break; print answer print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Project Euler 19: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 19.  As always, any feedback is welcome. # Euler 19 # http://projecteuler.net/index.php?section=problems&id=19 # You are given the following information, but you may # prefer to do some research for yourself. # # - 1 Jan 1900 was a Monday. # - Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on leap years, twenty-nine. # - A leap year occurs on any year evenly divisible by 4, # but not on a century unless it is divisible by 400. # # How many Sundays fell on the first of the month during # the twentieth century (1 Jan 1901 to 31 Dec 2000)? import time start = time.time() import datetime sundays = 0 for y in range(1901,2001): for m in range(1,13): # monday == 0, sunday == 6 if datetime.datetime(y,m,1).weekday() == 6: sundays += 1 print sundays print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Python or Ruby in 2011.

    - by Sleeper Smith
    What I'm really asking is, in the current services and technologies provided, which is a more "useful" language? Which one has more opportunity? Some background info first. I'm a .net C# dev for 5 years. Having done a few projects on Amazon AWS, I'm looking to start a few projects of my own. But Azure's too expensive, and AWS has too much management overhead. My current choice is Google App Engine and Python. Logical enough. But what I want to ask here is this: In Linux world, which is more useful? Recently heard about Heroku for Ruby. How viable is this? Looking at the pricing model indicates that it's more expensive. Which one has more up-to-date and exciting open source projects? For instance Trac is just plain out dated compared to Redmine. One of the big reason pulling me for Ruby is Redmine. Implementations? IronPython/IronRuby/JRuby etc etc. Which one is more standardised and more implementation agnostic? Which one is easier to port between Windows/Linux? Anyway, your input and thoughts are greatly appreciated. thanks.

    Read the article

  • (PHP vs Python vs Perl) vs Ruby [closed]

    - by Dr.Kameleon
    OK, here's what : I've programmed in over 20 different languages and now, because of a large project I'm currently working on for Mac OS X (in Objective-C/Cocoa), I need to make a final decision on which language to use for my background scripting + plugin functionality. Definitely, one factor that'll ultimately influence my decision is which one I'm most familiar with, which is PHP (one of the ugliest languages around, which I however adore... lol), then Python / Perl (the "proven values"... )... and then Ruby (which, to me, is almost confusing and I've only played with it for some time.) Now, here's my considerations : (As previously mentioned) Being familiar with it (anyway, if X is better in my case, I really don't mind studying it from scratch...) Speed Good interaction with the Shell + ease of integration with my Cocoa application Btw, some of the reasons that made me wonder if Ruby would be a good choice is : The hype around it (although, I still don't get why; but that's probably just me...) My major competitor (we're actually talking about the same type of software here) is using Ruby for its backend scripting almost exclusively (ok, along with some BASH). Isn't Ruby considered slower e.g. than Perl? Why did he choose that? Simply, a matter of personal taste? So... your thoughts?

    Read the article

  • Get external metadata with streamripper using python script

    - by user72379
    Hi I like using streamripper to rip music from the web. I have a favorite radio station that doesn't have the metadata for the songs, so I have to screen scrape it from its website manually. I created this neat python script in the format that the docs suggest, and linked the address in the GUI for streamriper. But it still doesn't work, any one know how to make it work..? I know it used to work. It gives you a sample here: http://streamripper.sourceforge.net/history.php import http import time import re u = 'SEE IMAGE FOR THIS URL' s = http.Session(0, 0) s.add_headers(h, persistent=1) while 1: c = unicode(s.get(u)) pat = r'class="title"([^<]+)([^<]+)' m = re.search(pat, c) title = m.group(1) artist = m.group(2) print 'TITLE='+title+'\n'+'ARTIST='+artist+'\n.\n' time.sleep(30) [img]http://s11.postimage.org/sok928lsz/urlstream.png[/img] I put the address to the script here: [img]http://s17.postimage.org/4bhmhi4yn/streamripper.png[/img] I've tried putting it in the root of the streamripper application and doing this: lax.py I've even compiled it to a EXE, and tried linking to that.. nothing What am I doing wrong?

    Read the article

  • Writing a DB Python or Ruby

    - by WojonsTech
    I am planning on writing a database. I know it's crazy and people will tell me there is no good reason to do so. I am really using it to get better at programming overall, this database wont be used in production. I am planning on writing it Ruby or Python. I have some experience with both languages, but no job or large project experience. I don't want this to be a this is better than that randomly I really need some facts. The things that I need to know are which of the language are better at the following things. Searching arrays/hashes? Sorting? Threading? Sockets? Memory management? Disk Reads/Writes? base64 encode/decode? Again this is just a project for myself. I will port it on github for the hell of it, but I don't expect it to be amazing or going up against mysql or mongodb any day.

    Read the article

  • How come string.maketrans does not work in Python 3.1?

    - by ShaChris23
    I'm a Python newbie. How come this doesn't work in Python 3.1? from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab); When I executed the above code, I get the following instead: Traceback (most recent call last): File "<pyshell#119>", line 1, in <module> transtab = maketrans(intab, outtab) File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/string.py", line 60, in maketrans raise TypeError("maketrans arguments must be bytes objects") TypeError: maketrans arguments must be bytes objects What does "must be bytes objects" mean? Could anyone please help post a working code for Python 3.1 if it's possible?

    Read the article

  • Using boost.python to import a method with opencv calls but failing due to symbols not being found a

    - by nmz787
    So I don't have the code right now, as I am not home... but i used the boost library for python in C++ to allow python to access a function called something like loadImageIntoMainWindow(string filepath) in the C++ source code the method calls opencv methods that are imported at the top of the file, I included opencv in my Jamroot file, and also found a way to compile and link manually on the command line... in either case when I run my python file it complains that the symbols aren't found for the first function call to an opencv method... I will update as soon as I get home with the C++, the command line compilation lines, the Jamroot, and the python files

    Read the article

  • What does Ruby have that Python doesn't, and vice versa?

    - by Lennart Regebro
    There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do. It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good! Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python. UPDATE: This is now a community wiki, so we can add the big differences here. Ruby has a class reference in the class body In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished. An example: class Kaka puts self end self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python. All classes are mutable in Ruby This lets you develop extensions to core classes. Here's an example of a rails extension: class String def starts_with?(other) head = self[0, other.length] head == other end end Ruby has Perl-like scripting features Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs. Ruby has first class continuations Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language. Ruby has blocks With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators. Ruby: amethod { |here| many=lines+of+code goes(here) } Python: def function(here): many=lines+of+code goes(here) amethod(function) Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator. Ruby: def themethod yield 5 end themethod do |foo| puts foo end Python: def themethod(): yield 5 for foo in themethod: print foo Although the principles are different, the result is strikingly similar. Python has built-in generators (which are used like Ruby blocks, as noted above) Python has support for generators in the language. In Ruby you could use the generator module that uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators. docs.python.org has this generator example: def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] Contrast this with the above block examples. Python has flexible name space handling In Ruby, when you import a file with require, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes. In Python, the file is a module, and you can import its contained names with from themodule import *, thereby polluting the namespace if you want. But you can also import just selected names with from themodule import aname, another or you can simply import themodule and then access the names with themodule.aname. If you want more levels in your namespace you can have packages, which are directories with modules and an __init__.py file. Python has docstrings Docstrings are strings that are attached to modules, functions and methods and can be introspected at runtime. This helps for creating such things as the help command and automatic documentation. def frobnicate(bar): """frobnicate takes a bar and frobnicates it >>> bar = Bar() >>> bar.is_frobnicated() False >>> frobnicate(bar) >>> bar.is_frobnicated() True """ Python has more libraries Python has a vast amount of available modules and bindings for libraries. Python has multiple inheritance Ruby does not ("on purpose" -- see Ruby's website, see here how it's done in Ruby). It does reuse the module concept as a sort of abstract classes. Python has list/dict comprehensions Python: res = [x*x for x in range(1, 10)] Ruby: res = (0..9).map { |x| x * x } Python: >>> (x*x for x in range(10)) <generator object <genexpr> at 0xb7c1ccd4> >>> list(_) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Ruby: p = proc { |x| x * x } (0..9).map(&p) Python: >>> {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} Ruby: >> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}] => {1=>"4", 3=>"16"} Python has decorators Things similar to decorators can be created in Ruby, and it can also be argued that they aren't as necessary as in Python.

    Read the article

  • Python: Remove items from a list while iterating in Python

    - by xApple
    My problem is simple: I have a long list of elements that I want to iterate through and check every element against a condition. Depending on the outcome of the condition I would like to delete the current element of the list, and continue iterating over it as usual. I have read a few other threads on this matter. Two solutions seam to be proposed. Either make a dictionary out of the list (which implies making a copy of all the data that is already filling all the RAM in my case). Either walk the list in reverse (which breaks the concept of the alogrithm I want to implement). Is there any better or more elegant way than this to do it ? def walk_list(list_of_g): g_index = 0 while g_index < len(list_of_g): g_current = list_of_g[g_index] if subtle_condition(g_current): list_of_g.pop(g_index) else: g_index = g_index + 1

    Read the article

  • retriving python objects ...python newbie

    - by gizgok
    I have a Club class and Player Class.The player class has an attribute Fav.clubs which will have unique club values.So the user is suppose to enter various club names.Based on the club names I have to retrieve those club objects and establish the relationship that this particular player has this Fav.clubs.The attribute Fav.clubs in Player class should store the names of Club .Now what I have to do is,take input from user about fav.clubs.This will be a list.After that traverse each element in the list and acc to string name find the corresponding club object and then store that object instance in Player class.

    Read the article

  • How can you print a string using raw_unicode_escape encoding in python 3?

    - by Sorin Sbarnea
    The following code with fail in Python 3.x with TypeError: must be str, not bytes because now encode() returns bytes and print() expects only str. #!/usr/bin/python from __future__ import print_function str2 = "some unicode text" print(str2.encode('raw_unicode_escape')) How can you print a Unicode string escaped representation using print()? I'm looking for a solution that will work with Python 2.6 or newer, including 3.x

    Read the article

  • Does the Python 3 interpreter have a JIT feature?

    - by guz
    I found that when I ask something more to Python, python doesn't use my machine resource at 100% and it's not really fast, it's fast if compared to many other interpreted languages, but when compared to compiled languages i think that the difference is really remarkable. It's possible to speedup things with a JIT compiler in Python 3 ? Usually a JIT compiler is the only thing that can improve performances in interpreted languages, so i'm referring to this one, if other solutions are available i would love to accept new answers.

    Read the article

  • Best online resource to learn Python?

    - by Sreenath
    I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python? Some Online Resources: http://docs.python.org/tut/tut.html - Beginners http://diveintopython.org/ - Intermediate http://www.pythonchallenge.com/ - Expert Skills http://docs.python.org/ - collection of all knowledge Some more: A Byte of Python. Python 2.5 Quick Reference Python Side bar A Nice blog for beginners Think Python: An Introduction to Software Design

    Read the article

  • Python PyBluez loses Bluetooth connection after a while

    - by Travis G.
    I am using Python to write a simple serial Bluetooth script that sends information about my computer stats periodically. The receiving device is a Sparkfun BlueSmirf Silver. The problem is that, after the script runs for a few minutes, it stops sending packets to the receiver and fails with the error: (11, 'Resource temporarily unavailable') Noticing that this inevitably happens, I added some code to automatically try to reopen the connection. However, then I get: Could not connect: (16, 'Device or resource busy') Am I doing something wrong with the connection? Do I need to occasionally reopen the socket? I'm not sure how to recover from this type of error. I understand that sometimes the port will be busy and a write operation is deferred to avoid blocking other processes, but I wouldn't expect the connection to fail so regularly. Any thoughts? Here is the script: import psutil import serial import string import time import bluetooth sampleTime = 1 numSamples = 5 lastTemp = 0 TEMP_CHAR = 't' USAGE_CHAR = 'u' SENSOR_NAME = 'TC0D' #gauges = serial.Serial() #gauges.port = '/dev/rfcomm0' #gauges.baudrate = 9600 #gauges.parity = 'N' #gauges.writeTimeout = 0 #gauges.open() filename = '/sys/bus/platform/devices/applesmc.768/temp2_input' def parseSensorsOutputLinux(output): return int(round(float(output) / 1000)) def connect(): while(True): try: gaugeSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) gaugeSocket.connect(('00:06:66:42:22:96', 1)) break; except bluetooth.btcommon.BluetoothError as error: print "Could not connect: ", error, "; Retrying in 5s..." time.sleep(5) return gaugeSocket; gaugeSocket = connect() while(1): usage = psutil.cpu_percent(interval=sampleTime) sensorFile = open(filename) temp = parseSensorsOutputLinux(sensorFile.read()) try: #gauges.write(USAGE_CHAR) gaugeSocket.send(USAGE_CHAR) #gauges.write(chr(int(usage))) #write the first byte gaugeSocket.send(chr(int(usage))) #print("Wrote usage: " + str(int(usage))) #gauges.write(TEMP_CHAR) gaugeSocket.send(TEMP_CHAR) #gauges.write(chr(temp)) gaugeSocket.send(chr(temp)) #print("Wrote temp: " + str(temp)) except bluetooth.btcommon.BluetoothError as error: print "Caught BluetoothError: ", error time.sleep(5) gaugeSocket = connect() pass gaugeSocket.close() EDIT: I should add that this code connects fine after I power-cycle the receiver and start the script. However, it fails after the first exception until I restart the receiver. P.S. This is related to my recent question, Why is /dev/rfcomm0 giving PySerial problems?, but that was more about PySerial specifically with rfcomm0. Here I am asking about general rfcomm etiquette.

    Read the article

  • XMPP— openfire,PHP and python web service

    - by mlakhara
    I am planning to integrate real time notifications into a web application that I am currently working on. I have decided to go with XMPP for this and selected openfire server which i thought to be suitable for my needs. The front end uses strophe library to fetch the notifications using BOSH from my openfire server. However the notices are the notifications and other messages are to be posted by my application and hence I think this code needs to reside at the backend. Initially I thougt of going with PHP XMPP libraries like XMPHP and JAXL but then I think that this would cause much overhead as each script will have to do same steps like connection, authentication etc. and I think this would make the PHP end a little slow and unresponsive. Now I am thinking of creating a middle-ware application acting as a web service that the PHP will call and this application will handle the stuff with XMPP service. The benefit with this is that this app(a server if you will) will have to connect just once and the it will sit there listening on a port. also I am planning to build it in a asynchronous way such that It will first take all the requests from my PHp app and then when there are no more requests; go about doing the notification publishing stuff. I am planninng to create this service in Python using SleekXMPP. This is just what I planned. I am new to XMPP and this whole web service stuff ans would like to take your comments on this regarding issues like memory and CPU usage, advantages, disadvantages, scalability issues,security etc. Thanks in advance. PS:-- also if something like this already exists(although I didn't find after a lot of Googling) Please direct me there. EDIT --- The middle-level service should be doing the following(but not limited to): 1. Publishing notifications for different level of groups and community pages. 2. Notification for single user on some event. 3. User registration(can be done using user service plugin though). EDIT --- Also it should like to create pub-sub nodes and subscribe and unsubscribe users from these pub-sub nodes. Also I want to store the notifications and messages in a database(openfire doesn't). Would that be a good choice?

    Read the article

  • Project Euler 18: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 18.  As always, any feedback is welcome. # Euler 18 # http://projecteuler.net/index.php?section=problems&id=18 # By starting at the top of the triangle below and moving # to adjacent numbers on the row below, the maximum total # from top to bottom is 23. # # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23. # Find the maximum total from top to bottom of the triangle below: # 75 # 95 64 # 17 47 82 # 18 35 87 10 # 20 04 82 47 65 # 19 01 23 75 03 34 # 88 02 77 73 07 63 67 # 99 65 04 28 06 16 70 92 # 41 41 26 56 83 40 80 70 33 # 41 48 72 33 47 32 37 16 94 29 # 53 71 44 65 25 43 91 52 97 51 14 # 70 11 33 28 77 73 17 78 39 68 17 57 # 91 71 52 38 17 14 91 43 58 50 27 29 48 # 63 66 04 68 89 53 67 30 73 16 69 87 40 31 # 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 # NOTE: As there are only 16384 routes, it is possible to solve # this problem by trying every route. However, Problem 67, is the # same challenge with a triangle containing one-hundred rows; it # cannot be solved by brute force, and requires a clever method! ;o) import time start = time.time() triangle = [ [75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 04, 82, 47, 65], [19, 01, 23, 75, 03, 34], [88, 02, 77, 73, 07, 63, 67], [99, 65, 04, 28, 06, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [04, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 04, 23]] # Loop through each row of the triangle starting at the base. for a in range(len(triangle) - 1, -1, -1): for b in range(0, a): # Get the maximum value for adjacent cells in current row. # Update the cell which would be one step prior in the path # with the new total. For example, compare the first two # elements in row 15. Add the max of 04 and 62 to the first # position of row 14.This provides the max total from row 14 # to 15 starting at the first position. Continue to work up # the triangle until the maximum total emerges at the # triangle's apex. triangle [a-1][b] += max(triangle [a][b], triangle [a][b+1]) print triangle [0][0] print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • How to refactor a Python “god class”?

    - by Zearin
    Problem I’m working on a Python project whose main class is a bit “God Object”. There are so friggin’ many attributes and methods! I want to refactor the class. So Far… For the first step, I want to do something relatively simple; but when I tried the most straightforward approach, it broke some tests and existing examples. Basically, the class has a loooong list of attributes—but I can clearly look over them and think, “These 5 attributes are related…These 8 are also related…and then there’s the rest.” getattr I basically just wanted to group the related attributes into a dict-like helper class. I had a feeling __getattr__ would be ideal for the job. So I moved the attributes to a separate class, and, sure enough, __getattr__ worked its magic perfectly well… At first. But then I tried running one of the examples. The example subclass tries to set one of these attributes directly (at the class level). But since the attribute was no longer “physically located” in the parent class, I got an error saying that the attribute did not exist. @property I then read up about the @property decorator. But then I also read that it creates problems for subclasses that want to do self.x = blah when x is a property of the parent class. Desired Have all client code continue to work using self.whatever, even if the parent’s whatever property is not “physically located” in the class (or instance) itself. Group related attributes into dict-like containers. Reduce the extreme noisiness of the code in the main class. For example, I don’t simply want to change this: larry = 2 curly = 'abcd' moe = self.doh() Into this: larry = something_else('larry') curly = something_else('curly') moe = yet_another_thing.moe() …because that’s still noisy. Although that successfully makes a simply attribute into something that can manage the data, the original had 3 variables and the tweaked version still has 3 variables. However, I would be fine with something like this: stooges = Stooges() And if a lookup for self.larry fails, something would check stooges and see if larry is there. (But it must also work if a subclass tries to do larry = 'blah' at the class level.) Summary Want to replace related groups of attributes in a parent class with a single attribute that stores all the data elsewhere Want to work with existing client code that uses (e.g.) larry = 'blah' at the class level Want to continue to allow subclasses to extend, override, and modify these refactored attributes without knowing anything has changed Is this possible? Or am I barking up the wrong tree?

    Read the article

  • Project Euler 11: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 11.  As always, any feedback is welcome. # Euler 11 # http://projecteuler.net/index.php?section=problems&id=11 # What is the greatest product # of four adjacent numbers in any direction (up, down, left, # right, or diagonally) in the 20 x 20 grid? import time start = time.time() grid = [\ [8,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,8],\ [49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00],\ [81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,03,49,13,36,65],\ [52,70,95,23,04,60,11,42,69,24,68,56,01,32,56,71,37,02,36,91],\ [22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80],\ [24,47,32,60,99,03,45,02,44,75,33,53,78,36,84,20,35,17,12,50],\ [32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70],\ [67,26,20,68,02,62,12,20,95,63,94,39,63,8,40,91,66,49,94,21],\ [24,55,58,05,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72],\ [21,36,23,9,75,00,76,44,20,45,35,14,00,61,33,97,34,31,33,95],\ [78,17,53,28,22,75,31,67,15,94,03,80,04,62,16,14,9,53,56,92],\ [16,39,05,42,96,35,31,47,55,58,88,24,00,17,54,24,36,29,85,57],\ [86,56,00,48,35,71,89,07,05,44,44,37,44,60,21,58,51,54,17,58],\ [19,80,81,68,05,94,47,69,28,73,92,13,86,52,17,77,04,89,55,40],\ [04,52,8,83,97,35,99,16,07,97,57,32,16,26,26,79,33,27,98,66],\ [88,36,68,87,57,62,20,72,03,46,33,67,46,55,12,32,63,93,53,69],\ [04,42,16,73,38,25,39,11,24,94,72,18,8,46,29,32,40,62,76,36],\ [20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,04,36,16],\ [20,73,35,29,78,31,90,01,74,31,49,71,48,86,81,16,23,57,05,54],\ [01,70,54,71,83,51,54,69,16,92,33,48,61,43,52,01,89,19,67,48]] # left and right max, product = 0, 0 for x in range(0,17): for y in xrange(0,20): product = grid[y][x] * grid[y][x+1] * \ grid[y][x+2] * grid[y][x+3] if product > max : max = product # up and down for x in range(0,20): for y in xrange(0,17): product = grid[y][x] * grid[y+1][x] * \ grid[y+2][x] * grid[y+3][x] if product > max : max = product # diagonal right for x in range(0,17): for y in xrange(0,17): product = grid[y][x] * grid[y+1][x+1] * \ grid[y+2][x+2] * grid[y+3][x+3] if product > max: max = product # diagonal left for x in range(0,17): for y in xrange(0,17): product = grid[y][x+3] * grid[y+1][x+2] * \ grid[y+2][x+1] * grid[y+3][x] if product > max : max = product print max print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Python easy_install confused on Mac OS X

    - by slf
    environment info: $ echo $PATH /opt/local/bin:/opt/local/sbin:/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/X11R6/bin:/opt/local/bin:/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:~/.utility_scripts $ which easy_install /usr/bin/easy_install specifically, let's try the simplejson module (I know it's the same thing as import json in 2.6, but that isn't the point) $ sudo easy_install simplejson Searching for simplejson Reading http://pypi.python.org/simple/simplejson/ Reading http://undefined.org/python/#simplejson Best match: simplejson 2.1.0 Downloading http://pypi.python.org/packages/source/s/simplejson/simplejson-2.1.0.tar.gz#md5=3ea565fd1216462162c6929b264cf365 Processing simplejson-2.1.0.tar.gz Running simplejson-2.1.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-Ojv_yS/simplejson-2.1.0/egg-dist-tmp-AypFWa The required version of setuptools (>=0.6c11) is not available, and can't be installed while this script is running. Please install a more recent version first, using 'easy_install -U setuptools'. (Currently using setuptools 0.6c9 (/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python)) error: Setup script exited with 2 ok, so I'll update setuptools... $ sudo easy_install -U setuptools Searching for setuptools Reading http://pypi.python.org/simple/setuptools/ Best match: setuptools 0.6c11 Processing setuptools-0.6c11-py2.6.egg setuptools 0.6c11 is already the active version in easy-install.pth Installing easy_install script to /usr/local/bin Installing easy_install-2.6 script to /usr/local/bin Using /Library/Python/2.6/site-packages/setuptools-0.6c11-py2.6.egg Processing dependencies for setuptools Finished processing dependencies for setuptools I'm not going to speculate, but this could have been caused by any number of environment changes like the Leopard - Snow Leopard upgrade, MacPorts or Fink updates, or multiple Google App Engine updates.

    Read the article

  • Generic RPM package for Python 2.x

    - by RaphDG
    I have a python application, it can run on Python = 2.6 and it's architecture independant. I need the rpm package of this application to be installed on Fedora 14 (python 2.7) and Centos 6.2 (python 2.6). I currently use mock to build one rpm package for each "flavour" and it works well. I apparently can't install the Centos compiled rpm on Fedora. It gives me this error message : error: Failed dependencies: python(abi) = 2.6 is needed by myapp-0.9.el6.noarch Here is the relevant part of my .spec file : %{!?python_sitelib: %global python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")} %{!?python_sitearch: %global python_sitearch %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(1))")} Name: myapp Version: #VERSION# Release: #RELEASE#%{dist} Summary: myapp Group: Development/Languages License: Apache v2 Source0: %{name}-%{version}-#RELEASE#.tar.gz BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) BuildArch: noarch BuildRequires: python-devel BuildRequires: python-setuptools %description myapp %prep %setup -c %build %{__python} setup.py build %install %{__rm} -rf %{buildroot} %{__python} setup.py install -O1 --skip-build --root %{buildroot} Do I really have to use mock and build 2 rpms or is there another way to create a single generic 2.x rpm package ?

    Read the article

  • Mac 10.5 Python libsvm 64 bit vs 32 bit

    - by shadowsoul
    I have a Mac 10.5 when I type "python" in terminal, it says Enthought Python Distribution -- www.enthought.com Version: 7.3-2 (64-bit) Python 2.7.3 |EPD 7.3-2 (64-bit)| (default, Apr 12 2012, 11:14:05) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "credits", "demo" or "enthought" for more information. then I go to my libsvm/python folder and type "make" which results in make -C .. lib if [ "Darwin" = "Darwin" ]; then \ SHARED_LIB_FLAG="-dynamiclib -W1,-install_name,libsvm.so.2"; \ else \ SHARED_LIB_FLAG="-shared -W1,-soname,libsvm.so.2"; \ fi; \ g++ ${SHARED_LIB_FLAG} svm.o -o libsvm.so.2 when I try to do "from svmutil import *" I get the error: OSError: dlopen(.../libsvm-3.12/python/../libsvm.so.2, 6): no suitable image found. Did find: .../libsvm-3.12/python/../libsvm.so.2: mach-o, but wrong architecture when I do "lipo -info libsvm.so.2", I get: Non-fat file: libsvm.so.2 is architecture: i386 So it looks like I'm running 64-bit python but libsvm ends up as a 32-bit program. Any way I can get it to compile as a 64-bit program?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >