Meaning "if each item is within range of other item with the same index".
price = [1, 2]
budget = [5, 7]
This works:
if price[0] in range(budget[0]) and price[1] in range(budget[1]):
affordable = True
I figure there's some way to just reference the whole array though. Like so: if price in budget:
You could use:
if all(x in range(y) for x,y in zip(price,budget)):
affordable = True
This will create tuples of price[i],budget[i] and then for each of these tuples we check that price[i] is in range(budget[i]). Nevertheless, you can optimize this further to:
if all(0 <= x < y for x,y in zip(price,budget)):
affordable = True
Note that this makes the assumption that prices are all integers. If you however use x in range(y) it will fail if x is not an integer. So 0.7 in range(10) would fail whereas our second approach will succeed (but it depends of course on what you want).
Assuming that both prices and budgets must be non-negative, using in range seems to be over-complicating things. Instead, you could just use the < operator.
Regardless of whether you use < or in range, it seems like the easiest approach would be to zip both lists and apply the condition on the pairs:
if (all([x[0] >= x[1] for x in zip(budget, price)])):
affordable = True
Related
I have a list of lists. Each sub-list contains two integer elements. I would like to multiply each of these elements by 1.2 and if they are positive and bigger then a certain number, change them to be that certain number. same thing if they are smaller.
The multiplication bit I achieved using list comprehension. With these extra conditions, I'm getting a little lost - to me, it seems overly complicated and even non pythonic. I was wondering if I can get some opinions.
The multiplication bit I achieved using list comprehension. With these extra conditions, I'm getting a little lost - to me, it seems overly complicated and even non pythonic. I have a rough idea on how to put all the conditions in the list comprehension, but when I started implementing them I got confused. I was wondering if I can get some opinions.
MAX_VOL = 32767 # audio data is the list of lists
MIN_VOL = -32767
audio_list = [[int(x*1.2), int(y*1.2)] for x, y in audio_data]
# My idea was something like:
audio_list = [[int(x*1.2), int(y*1.2) if x > MAX_VOL x == MAX VOL if x < MIN_VOL....] for x, y in audio_data]
Firstly, I'm pretty sure there is a syntax issue. But, for each number, I have to check if its positive or negative, then, if it is bigger or smaller then max/min volume. So, is this possible using list comprehension? Is it efficient and pythonic?
Thank you so much!
Use min and max:
MAX_VOL = 32767 # audio data is the list of lists
MIN_VOL = -32767
audio_list = [[int(max(MIN_VOL, min(MAX_VOL, x*1.2))), int(max(MIN_VOL, min(MAX_VOL, y*1.2)))] for x, y in audio_data]
And since these are long expressions, use a function, too:
def clip(s):
return int(max(MIN_VOL, min(MAX_VOL, s)))
audio_list = [[clip(x*1.2)), clip(y*1.2)] for x, y in audio_data]
Define a bounding function that doesn't let the value exceed the max or min volume. Then you can still use list comprehension.
MAX_VOL = 32767 # audio data is the list of lists
MIN_VOL = -32767
# Ensure volume does not exceed limits.
def bounded(val):
if val > MAX_VOL:
return MAX_VOL
elif val < MIN_VOL:
return MIN_VOL
return val
audio_list = [[bounded(int(x*1.2)), bounded(int(y*1.2))] for x, y in audio_data]
If a list comprehension is too complex, then don't use it. You should try and make your solution easy for someone else to understand and for you to understand if you come back to it in a year.
for x,y in audio_data:
if x > MAX_VOL:
foo = int(x*1.2)
bar = int(y*1.2)
if x == MAX_VOL:
...
I want to iterate through a numpy ndarray and, if any values are less than X, replace one of them with X.
I have tried doing array_name[ array_name < X] = X but this replaces all of the values that are less than X.
I can use a for loop, but I feel like there's probably a more concise way already bundled with numpy.
for i in array_name:
if i < X:
i = X
break
Is there a way to do this more elegantly?
array_name < X
Returns same array but with True or False. Then you can just pick an index where the cell is True
idx = np.argwhere(array_name < X)[i]
array_name[idx] = value
Here, you can choose i arbitrarily
I have an array A = [1 - 100] and I need to find the sum of all the two digit values in this array. How would I approach this? I have tried :
def solution(A):
A =array[0-100])
while A > 9 & A < 99
total = sum(A)
print "%s" % total
)
Is there a function that given an array consisting of N integers returns the sum of all two digit numbers i.e A = [1,1000,80, -91] the function should return -11(as the two are 80 and -91). not a range, multiple array
You can use a list comprehension and check if the length of the string-format is equal to 2, like so:
sum([x if len(str(x))==2 else 0 for x in xrange(1,101)])
Use the keyword and rather than the bitwise &.
Edit: a fuller answer, as that's not the only thing wrong:
def solution():
A = range(101)
total = sum([a for a in A if 9 < a <= 99])
print total
This uses list comprehension and chained inequalities, so is pretty 'pythonic'.
There is tons of errors in your code, please next time before posting,spend some time try to figure it out yourself and be sure that your code at lest doesn't contain any obvious syntax error.
By array, I assume you're talking about a list. And change it to range(101) for every number from 0 to 100
def solution(A):
return sum([x for x in range(A) if len(str(abs(x))) == 2])
print(solution(101))
As a side note, use and instead of & since that's a bitwise-or sign.
Here are a couple of ways to go about the problem, the first is most similar to the approach you appear to be trying:
def solution1(array):
total = 0
for a in array:
if 9 < a < 100:
total += a
return total
print(solution1(range(101)))
And here's a more compact solution using a comprehension (actually, a generator expression):
def solution2(array):
return sum(a for a in array if 9 < a < 100)
print(solution2(range(101)))
Note that in your original you're confusing loops and conditionals.
Suppose I have a list of coefficients of a polynomial in descending order of exponents (if len(list) == x then the exponents would range from integers x-1 to 0). I want to delete the "small" elements of said list, meaning abs(element) > 0 and abs(element) < .000001 but keep the exponents of the polynomial that are not "small."
How do I exactly do this in Python 3.0?
Here is an example of what I want in context:
my_list = [3.000000000000000e-12, 4.99999999999948, 4.00000000000002, -0.000042535500000e-15, -0.200000000000000]
exponents = [4,3,2,1,0] #As stated previously'
``>>> newlist = [4.99999999999948, 4.00000000000002, -0.200000000000000]
``>>> nexexp = [3,2,0]
Hence, the polynomial would be in the form
4.999999999999948*x^3 + 4.000000000000002*x^2 -0.200000000000000
Any suggestions would be very helpful!
Instead of deleting the small elements, keep the large ones:
newlist,newexp = zip(*[(x,e) for x,e in zip(my_list,exponents) if abs(x) > 1e-6])
You can use a filter, too:
newlist,newexp = zip(*filter(lambda x: abs(x[0]) > 1e-6, zip(my_list,exponents))))
I have an array of numbers called data, and I want to slice it to get only the numbers between a lower limit ll and an upper limit ul. The way I've been creating indices like this is:
index1 = where(data>ll)
data2 = data[index1]
index2 = where(data2<ul)
data3 = data2[index2]
Is there a less clumsy and wasteful way to do this, with where or another command?
I'm not quite understand your question, if you just want to retrieve numbers in a range, here is a solution.
If data = [3,5,9,1,34,11,8],
[a for a in data if 1 < a < 10]
will get [3,5,9,8]
where is not any function in python. To get numbers between limits, use comprehension
[i for i in data if ll < i < ul]
or use filter:
filter(lambda x: ll < x < ul, data)