473,805 Members | 2,297 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Request a short code review

I am not necessarily looking to make the code shorter or more
functional or anything in particular. However if you spot something
to improve then I am happy to learn.
To give an example of what I mean I have already altered the code:

def output_random_l esson_of_type(s elf, type=None):
"""Output a lesson of a specific type.
If no type is passed in then output any type."""
output_lessons = self.lesson_dat a["lessons"]
if type:
filtered_lesson s = filter(lambda x: x["type"] == type,
self.lesson_dat a["lessons"])
if filtered_lesson s:
output_lessons = filtered_lesson s
else:
print "Unable to find lessons of type %s." % type
return self.output_ran dom(output_less ons)

Changes:
- Respected a column width of 80
- Created the output_lessons variable, assigned it to a default.
This remove an else statement and reduced the call to
self.output_ran dom to a single instance in the return statement

Cheers,
James
Jun 27 '08 #1
5 1643
On Apr 17, 7:11 pm, ja...@reggieban d.com wrote:
I am not necessarily looking to make the code shorter or more
functional or anything in particular. However if you spot something
to improve then I am happy to learn.

To give an example of what I mean I have already altered the code:

def output_random_l esson_of_type(s elf, type=None):
"""Output a lesson of a specific type.
If no type is passed in then output any type."""
output_lessons = self.lesson_dat a["lessons"]
if type:
filtered_lesson s = filter(lambda x: x["type"] == type,
self.lesson_dat a["lessons"])
if filtered_lesson s:
output_lessons = filtered_lesson s
else:
print "Unable to find lessons of type %s." % type
return self.output_ran dom(output_less ons)

Changes:
- Respected a column width of 80
- Created the output_lessons variable, assigned it to a default.
This remove an else statement and reduced the call to
self.output_ran dom to a single instance in the return statement

Cheers,
James
I prefer, especially for longer methods, to return as soon as possible
(thereby indicating that the code below is irrelevant to a particular
condition). Thus, I would replace
output_lessons = filtered lessons
by
return self.output_ran dom(filtered_le ssons)

André
Jun 27 '08 #2
ja***@reggieban d.com wrote:
>I am not necessarily looking to make the code shorter or more
functional or anything in particular. However if you spot something
to improve then I am happy to learn.

To give an example of what I mean I have already altered the code:

def output_random_l esson_of_type(s elf, type=None):
"""Output a lesson of a specific type.
If no type is passed in then output any type."""
"any" type? Perhaps you mean all types.
output_lessons = self.lesson_dat a["lessons"]
if type:
filtered_lesson s = filter(lambda x: x["type"] == type,
self.lesson_dat a["lessons"])
filter/map/reduce/lambda is not to everyone's taste; consider using a
list comprehension:

filtered_lesson s = [x for x in self.lesson_dat a["lessons"] if x["type"]
== type]

Now you need to go up a level ... when you find yourself using
dictionaries with constant string keys that are words, it's time to
consider whether you should really be using classes:

filtered_lesson s = [x for x in self.lesson_dat a.lessons if x.type == type]

if filtered_lesson s:
output_lessons = filtered_lesson s
else:
print "Unable to find lessons of type %s." % type
So the error action is to print a vague message on stdout and choose
from all lessons?
return self.output_ran dom(output_less ons)

Changes:
- Respected a column width of 80
If you really care about people who are still using green-screen
terminals or emulations thereof, make it < 80 -- some (most? all?)
terminals will produce an annoying blank line if the text is exactly 80
bytes long.

- Created the output_lessons variable, assigned it to a default.
This remove an else statement and reduced the call to
self.output_ran dom to a single instance in the return statement
.... and also makes folk who are interested in what happens in the
error(?) case read backwards to see what lessons will be used.

HTH,

John
Jun 27 '08 #3
On Thu, 17 Apr 2008 15:11:40 -0700, james wrote:
>I am not necessarily looking to make the code shorter or more
functional or anything in particular. However if you spot something to
improve then I am happy to learn.

To give an example of what I mean I have already altered the code:

def output_random_l esson_of_type(s elf, type=None):
"""Output a lesson of a specific type.
If no type is passed in then output any type."""
output_lessons = self.lesson_dat a["lessons"] if type:
filtered_lesson s = filter(lambda x: x["type"] == type,
self.lesson_dat a["lessons"])
if filtered_lesson s:
output_lessons = filtered_lesson s
else:
print "Unable to find lessons of type %s." % type
return self.output_ran dom(output_less ons)

Changes:
- Respected a column width of 80
- Created the output_lessons variable, assigned it to a default.
This remove an else statement and reduced the call to
self.output_ran dom to a single instance in the return statement

Cheers,
James
I would write it like this:

def output_random_l esson_of_type(s elf, type=None):
"""\
Output a lesson of a specific type.
If no type is passed in then output any type.
"""
if type:
return self.output_ran dom([x for x in self.lesson_dat a["lessons"]
if x["type"] == type])
return self.output_ran dom(self.lesson _data["lessons"])
--
Ivan
Jun 27 '08 #4
Thank you all for posting insightful and useful comments.

Here is what I have based on your input:
def output_random_l esson_of_type(s elf, lesson_type=Non e):
"""Output a lesson of a specific type.
If no type is passed in then output all types."""
lessons = self.lesson_dat a["lessons"]
if lesson_type:
lessons = [x for x in lessons if x["type"] == lesson_type]
rand_lesson = choice(lessons)
inputs = self.create_les son_inputs(rand _lesson)
print rand_lesson["output"] % inputs
return rand_lesson, inputs

Changes:
- generator expression instead of filter
- removed keyword 'type' in favor of lesson_type
- wrap to 78 columns
- remove error-check -- allow it to fail in the choice statement.
I've decided to make a valid lesson_type an invariant anyway
so the appropriate thing would be an assert - but I'll settle for
a throw from choice if it receives an empty list
- moved self.output_ran dom logic into this function

The lesson data is loaded from YAML which explains why it is inside a
dictionary instead of a class. I am currently exploring ways to allow
me to easily switch my data providers between SQLAlchemy and YAML.

Cheers again. This is very valuable for me. I am a true believer
that if one takes care in the smallest of methods then the larger code-
base will be all the better.

James.
Jun 27 '08 #5
En Fri, 18 Apr 2008 15:10:09 -0300, <ja***@reggieba nd.comescribió:
lessons = self.lesson_dat a["lessons"]
if lesson_type:
lessons = [x for x in lessons if x["type"] == lesson_type]

Changes:
- generator expression instead of filter
The above is not a generator expression, it's a list comprehension. They look similar.
This is a list comprehension:

pya = [x for x in range(10) if x % 2 == 0]
pya
[0, 2, 4, 6, 8]

Note that it uses [] and returns a list. This is a generator expression:

pyg = (x for x in range(10) if x % 2 == 0)
pyg
<generator object at 0x00A3D580>
pyg.next()
0
pyg.next()
2
pyfor item in g:
.... print item
....
4
6
8

Note that it uses () and returns a generator object. The generator is a block of code that runs lazily, only when the next item is requested. A list is limited by the available memory, a generator may yield infinite items.
Cheers again. This is very valuable for me. I am a true believer
that if one takes care in the smallest of methods then the larger code-
base will be all the better.
Sure.

--
Gabriel Genellina

Jun 27 '08 #6

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

Similar topics

2
662
by: Dave Patton | last post by:
I'd appreciate any feedback on http://www.elac.bc.ca/ particularly in regards to how the pages are marked up. The markup is valid HTML 4.01 strict, but that doesn't mean I've done things using 'best practices'. The goal was to rewrite a site that previously had used frames, had some broken links, and was authored with frontpage. I had to use the existing content, and the goal wasn't to "redesign", but to "rewrite".
72
4499
by: B McDonald | last post by:
http://www.galtsvalley.com Hi all. I've recently made some major stylistic changes to my site and now it is essentially a new design with some new CSS plumbing. I am hoping that a few hardy souls can go check it out and tell me how it renders on their platform/browser combos. I have tested it under W2K, WXP, and System 9 on a Power Mac 8600: W2K: IE5.5 and Opera 7.1 (some small issues in Opera) WXP: IE6 and NS7.1 (in IE6 a strange...
18
2152
by: Ben Hanson | last post by:
I have created an open source Notepad program for Windows in C++ that allows search and replace using regular expressions (and a few other extras). It is located at http://www.codeproject.com/cpp/notepadre.asp I'm trying to use best practice in my C++ programming and would appreciate any advice anyone can give. As code is far more than just a one page sample, just a review of one of the source files (or even just a function or two) is...
9
1714
by: Adam Monsen | last post by:
I kindly request a code review. If this is not an appropriate place for my request, where might be? Specific questions are in the QUESTIONS section of the code. ========================================================================== #include <stdio.h> #include <stdlib.h> #include <string.h>
136
5556
by: Merrill & Michele | last post by:
A derangement is a mapping of a set onto itself leaving no element fixed. I realized that that was what I was programming when I was asked to randomly determine who buys presents for whom this year in my wife's family. Obviously, one does not buy for himself. The code is followed by some questions. #include <stdio.h> #include <stdlib.h> #include <time.h>
0
1351
by: Rick | last post by:
Hello, I'm six months into asp.net/c# and enjoying it. A couple weeks ago I needed to write a "simple" high performance counter, the short story is it turned into a mini project. Many lesson lessons learned including... static objects vs cached objects http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&th=c267acc0a0434fc0&rnum=2 performance
0
152
by: Sam | last post by:
Hello, I would personally avoid using "type" as variable name, or key, because built-in class type already exists. As I understand your code, it was not your intention to override it. ++ Sam
3
2298
by: vijaykumardahiya | last post by:
Dear Sir, I have two queries. First question is: I have a Html page. On which Have two buttons Submit and Issue. I want when I click on Sumit button request should be go to submit.jsp. and When I click on Issue button then request should be go to Issue.jsp.But When I click on submit button request do to Issue.jsp. Second Question is How I reterive the input parameter of html page to submit.jsp. Please review.. My files are: login.html:
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10370
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5545
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4328
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.