Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
Add array sum
- Loading branch information
Matthias Endler
committed
Feb 14, 2017
1 parent
bd9d378
commit 8385359
Showing
2 changed files
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
def array_sum(arr): | ||
sum = 0 | ||
for item in arr: | ||
if isinstance(item, list): | ||
sum = sum + array_sum(item) | ||
else: | ||
sum = sum + item | ||
return sum | ||
|
||
print array_sum([1,2,[3,4,[5]]]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
<?php | ||
|
||
function arraySum($arr) | ||
{ | ||
$sum = 0; | ||
foreach ($arr as $item) | ||
{ | ||
if (is_array($item)) | ||
{ | ||
$sum += arraySum($item); | ||
} | ||
else | ||
{ | ||
$sum += $item; | ||
} | ||
} | ||
return $sum; | ||
} | ||
|
||
var_dump(arraySum([1,2,[3,4,[5]]])); |