Assign 0 and 1 based on values greater than in one line - python

Say I have an array with integers 1 through 10 and have to replace all integers less than 6 with 0 and all integers equal to or greater than 6 with 1. Currently, I am doing this:
arry[arry < 6] = 0
arry[arry >= 6] = 1
I was wondering what would be a way to combine these two statements into one line of code, or any other solution for that matter.

I assume that arry is a numpy array (the smart indexing that you are using seems to indicate this). In that case you can simply do:
arry = (arry >= 6).astype(int)
where astype(int) will convert the array of booleans arry >= 6 to an array of integers.

You can use a simple list comprehension:
array = [0 if num < 6 else 1 for num in arry]
Which is equivalent to the following loops:
temp = []
for num in arry:
if num < 6:
temp.append(0)
else:
temp.append(1)
arry = temp

[1 if e >= 6 else 0 for e in arry]
for numpy array, (arry >= 6) gives an array of True/False which you can multiply by 1
(arry >= 6) * 1
or add 0
(arry >= 6) + 0
or cast to int
(a >= 6).astype(int)

[int(e >= 6) for e in arry]
This works because True is defined to be the same value as 1 and False is defined to be the same value as 0.

list(map(lambda i: 0 if i<6 else 1, a))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function (n) {return n >= 6 ? 1 : 0})

Related

Python Count values simultaneously in two columns greater than N

Need help counting the occurrence that values in two columns are greater than a value in the same row. For example, if I want to count the number of times each row is greater than 4 and I have columns X & Y such that:
X Y
2 1
5 5
6 3
5 5
The output variable will be 2 since both numbers are greater than 4 in two rows, row 2 and 4.
Thank you
In [134]: df.gt(4).all(axis="columns").sum()
Out[134]: 2
check if values are greater than 4; gives True/False's (frame)
check if we have all True's per row; gives True/False's again (series)
sum to get the count as True -> 1, False -> 0
What about a comparison like this, in case you're not looking to use any additional packages.
x = [2, 5, 6, 5]
y = [1, 5, 3, 5]
counter = 0 # initialize counter variable
min_value = 4 # initialize min_value to compare
for x, y in zip(x, y):
# print(x, y)
if x > min_value and y > min_value:
counter += 1
print("Row Count: " + str(counter))
If you are using pandas, then you can use something like this:
import pandas as pd
x = [2, 5, 6, 5]
y = [1, 5, 3, 5]
df = pd.DataFrame(list(zip(x, y)), columns=["x", "y"])
min_value = 4 # initialize min_value to compare
counter = df.gt(min_value).all(axis="columns").sum()
print("Row Count: " + str(counter))

Index position of an element

So, I have this code,How to find the specific index of zero element?
arr =[1,0,2,0]
for i in arr:
if i <=0:
print(list(arr).index(i))
else:
print("greater")
prints:
greater
1
greater
1
target:
greater
1
greater
3
Use enumerate(), You will get both index and value at the same time. Compare value is greater than 0 or not.
arr = [1, 0, 2, 0]
for i, val in enumerate(arr):
if val > 0:
print('Greater!')
else:
print(i)
Output
Greater!
1
Greater!
3
in python 3 you can get all the index with the following line.
list(map(lambda x: x[0], filter(lambda enum_val: enum_val[1] > 0, enumerate(arr))))

How do I fix this program that adds up all the integers in a list except the one that equals said sum?

I am trying to solve a problem where I have to enter several integers as an input (seperated by a whitespace), and print the integer that is the sum of all the OTHER integers.
So e.g.:
1 2 3 would give: 3, because 3 = 1 + 2
1 3 5 9 would give: 9, because 5 + 3 + 1 = 9
This is the code I currently have:
x = input().split(" ")
x = [int(c) for c in x]
y = 0
for i in range(len(x)-1):
y += x[i]
del x[i]
z = sum(x)
if y == z:
print(y)
break
else:
x.insert(i,y)
As the output, it just gives nothing no matter what.
Does anyone spot a mistake? I'd be ever greatful as I'm just a beginner who's got a lot to learn :)
(I renamed your strange name x to numbers.)
numbers = input().split()
numbers = [int(i) for i in numbers]
must_be = sum(numbers) / 2
if must_be in numbers:
print(int(must_be))
The explanation:
If there is an element s such that s = (sum of other elements),
then (sum of ALL elements) = s + (sum of other elements) = s + s = 2 * s.
So s = (sum of all elements) / 2.
If the last number entered is always the sum of previous numbers in the input sequence. Your problem lies with the x.insert(i, y) statement. For example take the following input sequence:
'1 2 5 8'
after the first pass through the for loop:
i = 0
z = 15
x = [1, 2, 5, 8]
y = 1
after the second pass through the for loop:
i = 1
z = 14
x = [1, 3, 5, 8]
y = 3
after the third pass through the for loop:
i = 2
z = 12
x = [1, 3, 8, 8]
y = 8
and the for loop completes without printing a result
If it's guaranteed that one of the integers will be the sum of all other integers, can you not just sort the input list and print the last element (assuming positive integers)?
x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])
I think this is a tricky question and can be done in quick way by using a trick
i.e create a dictionary with all the keys and store the sum as value like
{1: 18, 3: 18, 5: 18, 9: 18}
now iterate over dictionary and if val - key is in the dictionary then boom that's the number
a = [1, 3, 5, 9]
d = dict(zip(a,[sum(a)]*len(a)))
print([k for k,v in d.items() if d.get(v-k, False)])

Unable to assign in numpy array

I want to square even index values in numpy array and assign same in that array. I followed 2 approaches.
1 -
for i in range(len(arr)):
if i %2 == 0:
arr[i] = arr[i]**2
That is working.
2 -
arr[i] = arr[i]**2 for i in range(len(arr)) if i % 2 == 0
File "<ipython-input-149-30fc7ed25f1f>", line 1
arr[i] = arr[i]**2 for i in range(len(arr)) if i % 2 == 0
^
SyntaxError: invalid syntax
not working.
Is some syntax error?
This works with list compreension:
arr = [arr[i]**2 if i % 2 == 0 else arr[i] for i in range(len(arr))]
But you could also use the shorter:
arr[::2] = arr[::2]**2
I assume you are trying to do list comprehension, for which your syntax is slightly off, read up on the syntax of list comprehension.
It's syntax is similar to [exp1(item) if condition1 else exp2(item) for item in arr] .
The correct way to do it is as follows.
arr = [1,2,3,4,5,6]
arr = [arr[i]**2 if i % 2 == 0 else arr[i] for i in range(len(arr))]
print(arr)
#[1, 2, 9, 4, 25, 6]
What this is doing is running the for loop, checking the condition, and then picking either arr[i] or arr[i]**2, and then assigning the result to the list
Dont loop over numpy arrays you lose all the power of numpy.
Use these numpy functions to achieve the required result instead:
import numpy as np
arr = np.random.randint(0,10, size=(10,))
print(arr)
ans = np.where(np.arange(10) % 2 == 0, arr, arr**2)
print(ans)
output:
[ 1 9 1 1 0 6 5 2 1 5 ]
[ 1 81 1 1 0 36 5 4 1 25]
np.where selects the elements where the condition is true. Then outputs either the original array or the squared array.
Docs for np.where.

Finding the max element in an array, sorted ascending first and then descending

I tried an online challenge which had a question as follows:
You are given an array which increases at first and then starts decreasing.
For example: 2 3 4 5 6 7 8 6 4 2 0 -2.
Find the maximum element of these array.
Following is my code using binary search and it gives correct answer in O(log(n)) but I don't know whether there is a better solution or not.
Can anyone help me with that?
a= map(int, raw_input().split())
def BS(lo,hi):
mid = lo+ (hi-lo)/2
if a[mid]>=a[mid+1]:
if a[mid]>a[mid-1]:
return mid
else:
return BS(lo,mid)
else:
return BS(mid,hi)
print a[BS(0,len(a)-1)]
An optimised variant - twice faster in most cases:
# ® Видул Николаев Петров
a = [2, 3, 4, 5, 6, 7, 8, 10, 12, 24, 48, 12, 6, 5, 0, -1]
def calc(a):
if len(a) <= 2:
return a[0] if a[0] > a[1] else a[1]
l2 = len(a) / 2
if a[l2 + 1] <= a[l2] and a[l2] >= a[l2 - 1]:
return a[l2]
if a[l2] > a[l2 + 1]:
return calc(a[:l2+1])
else:
return calc(a[l2:])
print calc(a) # 48
i am trying your code with the following input 2 3 4 5 5 8 and the answer should be 8 but the answer is 5 i am posting an image with a few more test cases
i think u cannot run binary search on an unsorted array
the code also gives huge list of exceptions for sorted arrays
Why don't you use the max() method??
max(lst) will return the max value in a list

Categories