[Tutor] Working with lists - why does my script not work?

Craig Cesareo ccesareo at legend3d.com
Mon Jun 25 15:28:18 CEST 2012


Try putting.    [:]      After "words" in the for loop line. What's happening is you're removing words from the list you are iterating through and it's messing with the loop. The empty indice I'm having you insert makes an in place copy of the list so your remove doesn't effect it.

--
Craig Cesareo - iPhone
Pipeline Technical Director
http://www.legend3d.com/
http://www.craigcesareo.com/
609.994.6370

On Jun 25, 2012, at 6:23 AM, "Developer Ecofunds" <ecofunds.developer at gmail.com<mailto:ecofunds.developer at gmail.com>> wrote:

Hello guys,

I'd like to ask you a little question about a script I did and isn't working properly.
It is one excercise from googles python classes <http://code.google.com/edu/languages/google-python-class/set-up.html>

I'm using python 2.5 because it's the one works with Google App Engine <https://developers.google.com/appengine/docs/python/gettingstarted/>

This is the problem:

##########################3

# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.

# This is the code I did -- Romulo.

def front_x(words):
  x_list = []
  for string in words:
    if string[0]=='x':
      x_list.append(string)
      words.remove(string)
  sorted(words)
  sorted(x_list)
  x_list.extend(words)
  return x_list

##############################

The problem with this code is that it only gets the first word beginning with x and the others remaisn on the original list, sorted at the end. I've tested on terminal many parts of the code and it whas fine, but when I run it complete, it does not work.

Following is the solution of the problem. I can understand it, I just can't understand why my code does not work.

#############################
def front_x(words):
  x_list = []
  other_list = []
  for w in words:
    if w.startswith('x'):
      x_list.append(w)
    else:
      other_list.append(w)
  return sorted(x_list) + sorted(other_list)
##############################

To download all the exercises, access: http://code.google.com/edu/languages/google-python-class/google-python-exercises.zip

Thank y'all.


_______________________________________________
Tutor maillist  -  Tutor at python.org<mailto:Tutor at python.org>
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120625/01c4c706/attachment.html>


More information about the Tutor mailing list