Reputation: 37
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 the largest.
def largest():
f=pickAFile()
sound=makeSound(f)
for i in range(1,getLength(sound)):
value=getSampleValueAt(sound,i)
print max([value])
Upvotes: 0
Views: 7051
Reputation: 52040
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:
def largest():
f = pickAFile()
sound = makeSound(f)
max = getSampleValueAt(sound, 1) # FIX ME: exception (?) if no data
idx = 2
while idx < getLength(sound):
v = getSampleValueAt(sound, i)
if v > max:
max = v
i += 1
print max
Generator-based solution are efficient too in term of space, but for speed, nothing could beat a plain-old imperative loop in Python.
Upvotes: 1
Reputation: 1030
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)
Upvotes: 0
Reputation: 5844
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:
Upvotes: 3