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))
Related
I would like to repeat elements from one list based in a second list, like this:
i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for x in j:
while i <= x:
print(x)
i += 1
I've got this result:
1
1
4
4
4
10
10
10
10
10
10
I'd like to get this result:
11.65
11.65
11.69
11.69
11.69
11.71
11.71
11.71
11.71
11.71
11.71
You may iterate on both list together, using zip, then increase i until you reach the bound of the current value
i = 0
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for bound, value in zip(j, z):
while i <= bound:
print(value)
i += 1
j = [1, 4, 10]
z = [11.65, 11.69, 11.71]
for i in range(len(j)): #assuming the lenth of both list is always the same
for k in range(j[i]):
print(z[i])
Do you mean something like this?
there is a 1, 4, and 10
so print the first item in z 1 time, second item 4 times and the third 10 times?
#Given array of integers, find the sum of some of its k consecutive elements.
#Sample Input:
#inputArray = [2, 3, 5, 1, 6] and k = 2
#Sample Output:
#arrayMaxConsecutiveSum(inputArray, k) = 8
#Explaination:
#All possible sums of 2 consecutive elements are:
#2 + 3 = 5;
#3 + 5 = 8;
#5 + 1 = 6;
#1 + 6 = 7.
#Thus, the answer is 8`
Your question is not clear but assuming you need a function to return the sum of the highest pair of numbers in your list:
def arrayMaxConsecutiveSum(inputArray, k):
groups = (inputArray[pos:pos + k] for pos in range(0, len(inputArray), 1)) # iterate through array creating groups of k length
highest_value = 0 # start highest value at 0
for group in groups: # iterate through groups
if len(group) == k and sum(group) > highest_value: # if group is 2 numbers and value is higher than previous value
highest_value = sum(group) # make new value highest
return highest_value
inputArray = [2, 3, 5, 1, 6]
print(arrayMaxConsecutiveSum(inputArray, 2))
#8
The following code generate random number of 2d arrays and I want to print how many values in each pair are divisible to 3. For example assume we have an array [[2, 10], [1, 6], [4, 8]].
So the first pair which is [2,10] has 3 ,6 and 9 which are totally 3 and second pair has 3 and 6 which are totally two and last pair[4,8] has just 1 divisible to 3 which is 6. Therefore, The final out put should print sum of total number of divisible values which is 3+2+1=6
a=random.randint(1, 10)
b = np.random.randint(1,10,(a,2))
b = [sorted(i) for i in b]
c = np.array(b)
counter = 0;
for i in range(len(c)):
d=(c[i,0],c[i,1])
if (i % 3 == 0):
counter = counter + 1
print(counter)
One way is to count how many integers in the interval are divisible by 3 by testing each one.
Another way, and this is much more efficient if your intervals are huge, is to use math.
Take the interval [2, 10].
2 / 3 = 0.66; ceil(2 / 3) = 1.
10 / 3 = 3.33; floor(10 / 3) = 3.
Now we need to count how many integers exist between 0.66 and 3.33, or count how many integers exist between 1 and 3. Hey, that sounds an awful lot like subtraction! (and then adding one)
Let's write this as a function
from math import floor, ceil
def numdiv(x, y, div):
return floor(y / div) - ceil(x / div) + 1
So given a list of intervals, we can call it like so:
count = 0
intervals = [[2, 10], [1, 6], [4, 8]]
for interval in intervals:
count += numdiv(interval[0], interval[1], 3)
print(count)
Or using a list comprehension and sum:
count = sum([numdiv(interval[0], interval[1], 3) for interval in intervals])
You can use sum() builtin for the task:
l = [[2, 10], [1, 6], [4, 8]]
print( sum(v % 3 == 0 for a, b in l for v in range(a, b+1)) )
Prints:
6
EDIT: To count number of perfect squares:
def is_square(n):
return (n**.5).is_integer()
print( sum(is_square(v) for a, b in l for v in range(a, b+1)) )
Prints:
5
EDIT 2: To print info about each interval, just combine the two examples above. For example:
def is_square(n):
return (n**.5).is_integer()
for a, b in l:
print('Pair {},{}:'.format(a, b))
print('Number of divisible 3: {}'.format(sum(v % 3 == 0 for v in range(a, b+1))))
print('Number squares: {}'.format(sum(is_square(v) for v in range(a, b+1))))
print()
Prints:
Pair 2,10:
Number of divisible 3: 3
Number squares: 2
Pair 1,6:
Number of divisible 3: 2
Number squares: 2
Pair 4,8:
Number of divisible 3: 1
Number squares: 1
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)])
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})