473,395 Members | 1,783 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Please Criticize My Code

Ray
Hello,

I just wrote a short script that generates look and say sequence. What
do you Python guys think of it? Too "Java-ish"? I can't shake off the
feeling that somebody may have done this with 2-3 lines of Python
magic. Heh.

# generator for sequence
def lookAndSaySequence(firstTerm, n):
term = str(firstTerm)
for i in xrange(n):
yield term
term = lookAndSay(term)

# the method that looks, and says
def lookAndSay(number):
look_at_this = str(number)
say_this = ['0', look_at_this[0]]
for digit in look_at_this:
if say_this[-1] != digit:
say_this.extend(('1', digit))
else:
say_this[-2] = str(int(say_this[-2]) + 1)
return "".join(say_this)

# run it!
print [x for x in lookAndSaySequence(1, 30)]

Thanks,
Ray

Aug 20 '05 #1
9 1540
Ray wrote:
I just wrote a short script that generates look and say sequence. What
do you Python guys think of it? Too "Java-ish"?


Yes, but that's beside the point. :)

I think your basic design was sound enough for this application
(presumably this isn't something that needs to run at high speed). I
found it a little hard to understand what was going on. Part of this was
due to variable and function naming choices. Converting between strs and
ints all the time is confusing too.

I think this version might be a little easier to understand, and
describe() should work for any string, not just integers. I think your
original version does as well:

def describe(string):
last_char = ""
last_count = ""
res = []

for char in string:
if char == last_char:
last_count += 1
else:
res.extend([str(last_count), last_char])
last_char = char
last_count = 1

res.extend([str(last_count), last_char])

return "".join(res)

def describe_generator(start, count):
string = str(start)

for index in xrange(count):
yield string
string = describe(string)

print list(describe_generator(1, 30))

As requested, here's a more concise, but difficult to understand version
of describe() using regexes:

import re

re_describe = re.compile(r"(.)\1*")
def describe(string):
runs = re_describe.finditer(str(string))

return "".join("".join([str(len(run.group(0))), run.group(0)[0]])
for run in runs)

While it is fewer lines of code, it's not as easy to see what this
*thing* does immediately upon looking at it. So I'd try to avoid this
version, really.
--
Michael Hoffman
Aug 20 '05 #2
Two versions of mine, one of the fastest (not using Psyco) and one of
the shortest:

.. from itertools import groupby
..
.. def audioactiveFast(n):
.. strl = {("1","1","1"): "31", ("1","1"): "21", ("1",): "11",
.. ("2","2","2"): "32", ("2","2"): "22", ("2",): "12",
.. ("3","3","3"): "33", ("3","3"): "23", ("3",): "13" }
.. result = [1]
.. prec = "1"
.. for i in xrange(n-1):
.. prec = "".join( strl[tuple(l)] for e,l in groupby(prec) )
.. result.append( int(prec) )
.. return result
..
..
.. def audioactiveShort(n):
.. s = [1]
.. for i in xrange(n-1):
.. r = 0
.. for e,l in groupby(str(s[-1])):
.. r = r*100 + len(list(l))*10 + int(e)
.. s.append( r )
.. return s

Bye,
bearophile

Aug 20 '05 #3
Ray
Damn, those are cool, man. Thanks! This Python thing keeps expanding
and expanding my brain...

Ray

be************@lycos.com wrote:
<snipped>

Aug 20 '05 #4
Ray
Michael Hoffman wrote:
Ray wrote:
I just wrote a short script that generates look and say sequence. What
do you Python guys think of it? Too "Java-ish"?


Yes, but that's beside the point. :)


Well... I'm always paranoid that I'm, you know, writing Java in Python
:)

<snipped>

Thanks for the examples! That last one took me a while to understand. I
like the way you approach it though (e.g.: going after clarity first
instead of shortness).

Cheers
Ray

Aug 20 '05 #5
Ray wrote:
Well... I'm always paranoid that I'm, you know, writing Java in Python
:)
The biggest mistakes I see are wrapping everything in a class
unnecessarily, or using accessor methods instead of properties (ugh,
ugh, ugh!). CamelCasingYourVariableNames is annoyingToMe but that's
really a stylistic choice.
Thanks for the examples! That last one took me a while to understand. I
like the way you approach it though (e.g.: going after clarity first
instead of shortness).


I think that is the Pythonic way. <wink> In general, I find conciseness
in code is not worth all that much in its own right. Although sometimes
it can make things easier to understand, which is good. There is a
common belief that concise code = fast code, and it is easy to
demonstrate that this is false. See, for example, this essay:
<http://www.python.org/doc/essays/list2str.html>

Also, if you haven't done so already, start up an interactive prompt and
type "import this." Key to consider:

Simple is better than complex.
Complex is better than complicated.
Sparse is better than dense.
Readability counts.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

Best regards,
--
Michael Hoffman
Aug 20 '05 #6
i guess, it is pythonchallenge.com level 10?
if so, i used this thing:

import re
def enc(s):
return ''.join('%s%s' % (len(a[0]),a[0][0]) for a in
re.findall('((.)\\2*)', s))

Aug 20 '05 #7
Christoph Rackwitz wrote:
i guess, it is pythonchallenge.com level 10?
if so, i used this thing:

import re
def enc(s):
return ''.join('%s%s' % (len(a[0]),a[0][0]) for a in
re.findall('((.)\\2*)', s))


Don't do that!
Aug 20 '05 #8
Why not? Because the regex isn't compiled?
Don't tell me not to do something, tell me why i should'nt do it.

Aug 21 '05 #9
Ray
Christoph Rackwitz wrote:
Why not? Because the regex isn't compiled?
Don't tell me not to do something, tell me why i should'nt do it.


No it's not the regex, it's because you just spoiled the challenge for
everybody who hasn't solved level 10 yet...

Aug 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Az Tech | last post by:
Hi people, (Sorry for the somewhat long post). I request some of the people on this group who have good experience using object-orientation in the field, to please give some good ideas for...
26
by: Michael Strorm | last post by:
Hi! I posted a message a while back asking for project suggestions, and decided to go with the idea of creating an adventure game (although it was never intended to be a 'proper' game, rather an...
2
by: rked | last post by:
I get nameSPAN1 is undefined when I place cursor in comments box.. <%@ LANGUAGE="VBScript" %> <% DIM ipAddress ipAddress=Request.Servervariables("REMOTE_HOST") %> <html> <head> <meta...
7
by: x muzuo | last post by:
Hi guys, I have got a prob of javascript form validation which just doesnt work with my ASP code. Can any one help me out please. Here is the code: {////<<head> <title>IIBO Submit Page</title>...
23
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application...
1
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
5
by: settyv | last post by:
Hi, Below is the Javascript function that am trying to call from asp:Button control. <script language="javascript"> function ValidateDate(fromDate,toDate) { var fromDate=new Date();
1
PEB
by: PEB | last post by:
POSTING GUIDELINES Please follow these guidelines when posting questions Post your question in a relevant forum Do NOT PM questions to individual experts - This is not fair on them and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.