Skip to content Skip to sidebar Skip to footer

Max() Function Using Python From Loop

I am trying to write a program to determine the maximum value of a sample from a sound. The loop returns the values of all the samples, however I cannot figure out how to print th

Solution 1:

Try:

def largest():
    f = pickAFile()
    sound = makeSound(f)
    value = []
    for i in range(1, getLength(sound)):
      value.append(getSampleValueAt(sound, i))
    print max(value)

Or

def largest():
    f = pickAFile()
    sound = makeSound(f)
    print max(getSampleValueAt(sound, i) for i in range(1, getLength(sound)))

With your code, value is overwritten at each iteration. If you make a list with all the values, you can then find the max using max.

Also see:

Solution 2:

Don't remember we are dealing with audio data. With possibly millions of samples. If you want to stick with something efficient both in space and time, you have to rely on the far less sexy:

deflargest():
    f = pickAFile()
    sound = makeSound(f)
    max = getSampleValueAt(sound, 1) # FIX ME: exception (?) if no data
    idx = 2while idx < getLength(sound):
        v = getSampleValueAt(sound, i)
        if v > max:
            max = v
        i += 1printmax

Generator-based solution are efficient too in term of space, but for speed, nothing could beat a plain-old imperative loop in Python.

Solution 3:

Didn't test it but maybe:

def largest():
 f=pickAFile()
 sound=makeSound(f)
 value = [ getSampleValueAt(sound,i) for i in range(1,getLength(sound)) ]
 print max(value)

Post a Comment for "Max() Function Using Python From Loop"