[Tutor] Question regarding lists and manipulating items in lists.

Steven D'Aprano steve at pearwood.info
Wed Jan 16 01:01:42 CET 2013


On 16/01/13 10:40, Scurvy Scott wrote:
[...]
> Anyways, the problem I'm having is I'm not really sure how to search a list
> for multiple elements and remove just those elements. Below is my code so
> far, and information y'all could provide would be appreciated. Thanks.

Actually, your problem so far is that you aren't even producing a list of
elements at all, you keep creating a *single* element, then throwing it
away when you generate the next Fibonacci number.

Also, you, or more likely Gmail, lost the indentation in your code, so I'm
going to have to guess what you intended rather than what you have. That's
because you are sending HTML email, which eats spaces.


> import mingus.core.notes as notes
> #fibonacci
> def fib(num1,num2):
> a, b = 0, 1
> for i in xrange(num1,num2):
> c = b % 12 #modulo 12 on each generated fibonacci number
> a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12
> numbers into notes and then (I think) storing each one as an element in a
> list?
> a, b = b, a+b #this is just the algorithm for the fibonacci numbers


Firstly, I recommend that you follow the principle "separation of concerns".
Keep a separate function for each part of the problem:

* generate Fibonacci numbers;
* turn them into notes;


So here I extract out of your code (untested!) a generator which produces
an infinite series of Fibonacci numbers, one at a time:

def fib():
     a, b = 0, 1
     while True:
         yield b
         a, b = b, a+b


This is untested, I may have got it wrong.

Next, a function to generate notes from those Fibonacci numbers:


def make_notes(num_notes):
     it = fib()
     notes = []  # start with an empty list
     for i in range(num_notes):
         n = next(it) % 12  # get the next Fibonacci number, modulo 12
         notes.append(notes.int_to_note(n))
     return notes


That returns a list of notes.


Does that help? Start with that, and see how you go.



-- 
Steven


More information about the Tutor mailing list