xxxxxxxxxx
var pivotIndex = function(nums) {
// Initialize total sum of the given array...
let totalSum = 0
// Traverse the elements and add them to store the totalSum...
for(let i = 0; i < nums.length; i++) {
totalSum += nums[i]
}
// Initialize 'leftsum' as sum of first i numbers, not including nums[i]...
let leftSum = 0
// Again traverse all the elements through the for loop and store the sum of i numbers from left to right...
for (let i = 0; i < nums.length; i++) {
// sum to the left == leftsum.
// sum to the right === totalSum - leftsum - nums[i]..
// check if leftsum == totalSum - leftsum - nums[i]...
if (leftSum * 2 == totalSum - nums[i])
return i; // Return the pivot index...
leftSum += nums[i]
}
return -1 // If there is no index that satisfies the conditions in the problem statement...
};
console.log(pivotIndex([1,7,3,6,5,6]));
xxxxxxxxxx
# Time: O(n)
# Space: O(1)
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total = sum(nums)
left_sum = 0
for i, num in enumerate(nums):
if left_sum == (total-left_sum-num):
return i
left_sum += num
return -1
xxxxxxxxxx
table = pd.pivot_table(df, values='D', index=['A', 'B'],
columns=['C'], aggfunc=np.sum, fill_value=0)
>>> table
C large small
A B
bar one 4 5
two 7 6
foo one 4 1
two 0 6