8 kyu
Sum Arrays
5,463 of 192,216richardhsu
Loading description...
Arrays
Fundamentals
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
MRI 3.0.0 is not available in Ruby variant
C:
missing fixed and sample tests for empty arrays
fixed
this kind of empty arrays:
is not allowed by the C standard, it's a GCC/Clang extension. it would have been better to pass
NULL
, which has the added benefit of making incorrect solutions crash if they attempt to access it@trashy_incel, you're right, the previous test was derived from NASM, so I guess it should be updated too
JS initial code needs to not look like this:
besides the superfluous trailing semicolon, what's wrong with this setup ? the author should be free to put the strict mode directive there if they so wish, in my opinion. if you don't like it, you can easily delete it
Fixed though it is not really an issue :-)
I apologize for not elaborating.
I very much do think this is an issue - this is a beginner kata and beginners should not be presented with a sloppy mess from which they'll be trying to learn.
JS's automatic semi-colon insertion is great, it removes the need to write something that is useless. somehow though, some people still decide to use semi-colons. which .. is fine. if they do it correctly. but this is javascript, and there are no errors, so people learn to arbitrarily sprinkle them on as if though it's needed, while also not doing it correctly. it's as if they think they have to appease the machine spirit with incense and prayers.
I don't really care about semi-colons. but when used poorly it looks very embarassing. and that's the issue. let's not teach embarassing use of semi-colon. use them correctly, or leave them out.
it's still there. my fault, didn't elaborate.
that wasn't the only problem - the comment is useless, so it is also teaching useless comments to beginners, and yes, the use strict is probably not doing anything useful either, serving only to confuse, again, beginners.
I've fixed it (hopefully as what you intended to see), a lot of kata also uses this code (likely copied from some templates), so perhaps you can raise an issue everytime you've encountered them
This comment has been hidden.
Running your code, I'm getting the output 0.00 because you're adding nothing but zero/s.
Populate the array in your main function with some values.
Thankyou for the responding my friend.
Well I already did that and it was giving the sum of the values in the array, for example: 3, 2, 1, 1 this would output to 7.00, so I think it works and has a minor issue and I don't know why and what, and I don't want to skip this because I'm trying my very best to study C.
You changed the function's output type from
int
todouble
, this is why it always returns0
in the tests. The tests will interpret your return value as anint
; adouble
like6.0
is represented in memory (Little-Endian) by the bytes{0x00 0x00 0x00 0x00 0x00 0x00 0x18 0x40}
; the 32-bitint
will comprise the first 4 bytes, so it will have a value of0
. your function will work if you correct the return typeC implementation doesn't strictly follow the guidelines
can you be more explicit ?
no tiene que crear el array ni tampoco tiene que crear el valor 0, lo unico que debe hacer es la logica para que la funcion coga cualquier valor, x, y, a o b, para que obtengan la funcionalidad de sumarse y si no regresen 0.
python: Hola a todos despues de un rato logre implementar el codigo con exito pero no acepta el comando input(). Probe version 3.8 hasta 3.11.
You don't use input() here, the input is passed to the function through its arguments. Not a kata issue. Read this: https://docs.codewars.com/training/training-example
This comment has been hidden.
someone help me im pretty new to coding ....im learning javascript so if anyone could help me how to improve my self pls tell me
personally, i better practice more and that's all
there is not secret ingredient, its all about practice
This comment has been hidden.
I believe it doesn't work for empty arrays. There is a solution that shows both methods.
This comment has been hidden.
If you check the stack trace, then you can see the error is coming from reduce function itself. So, yes, problem with the code. I don't do Dart, so I don't know why, but adding
[...arr]
works somehow.I had similar problems when updating versions of some Dart kata. All I can say is that the
num
being a supertype ofint
andfloat
, connected with the way how type inference works in Dart, makes things utterly confusing.I didnt fully grasp how it works, I remmebr that I just sprinkled type annotations and casts to
num
until I got it working :)This comment has been hidden.
*Post edited for not being helpful*
I updated Dart random tests. Now
reduce
should work.Dart random tests called the solution function with an argument of type
List<int>
. I changed this type toList<num>
. Dart allowsList<int>
whenList<num>
is expected because all generic parameters are covariant in Dart and soList<int>
is a subtype ofList<num>
. On the other hand,List<E>.reduce(E combine(E, E))
has a contravariant argument (the return value ofcombine
). That's why it was impossible to usereduce
before (all generic arguments offold
are covariant so there were no issues with it).Yes, it work now. @monadius, thank you very much!
For anyone in the 8 - 7 kyu range, I recommend using for loops to practice your for loop knowledge. Do not rely on memoryzing methods that. Memorizing methods as a beginner will only imede you in the future when you need a for loop. If you need help with a solution and ar a JavaScript user but don't want the exact answer, I would be happy yo help.
im pretty new to coding ...im trying to solve but i couldnt solve can u help me how to solve problems and think abt the question and how to apply javascript
Use code academy to learn the basics of javascript. It's free. Once you learn the basics, come back to codewars and test your knowledge.
the solution setup should have
# your code here
and should be runnable withreturn
in pythonmaybe a bit like this:
i'm new to programming and i was wandering how can you write the codes in a comment like you did with that box and colors? i tried copy and paste but it comes as a text and without than box? thanks in advance!
Codewars supports using Markdown for formatting text in discussions. Here's the syntax, including one for code blocks.
If you're gonna add type hints, go all the way:
Also, the
# your code here
is 100% optional, I personally find it unnecessary. The "should be runnable" thing would be nice though.Added
pass
im sorry to everyone i did not reply to. i did not check my email and use codewars for a long time.
i just got a email about ejini closing this comment.
Instructions says array can be non ints but code: const int *values.
This comment has been hidden.
Please don't post solutions in Discourse and this is not a kata suggestion.
The best practice solution, doesn't appear to always work on the test, I originally tried this solution, and it spat errors out.
In what language?
Ah yes sorry, C#
Which exactly top voted C# solution did not work for you? I checked a couple of them and they seem to work well.
This comment has been hidden.
Disregard this message thread, I went back and retried the solution it appears to be working, so no stress :) Enjoy your christmas!
This comment has been hidden.
put let sum = 0; inside the function because everytime u call the function u add the old sum test result on the new test sum result
This comment has been hidden.
Согласна! Я так же решила) Только немного наоборот
Racket tests seem to be using strict comparison for non-integers.
Yea it is not hard
This comment has been hidden.
Your solution doesn't correctly handle all inputs.
Not a kata issue.
wo, i just noticed im pretty dumb, maybe thats the sign i should stop staying up 20 hours straight, it's messing with my head
This comment has been hidden.
Please use appropriate formatting when posting code (code blocks).
Your code fails for each call after the initial one, e.g.:
It's up to you to figure out why that is the case.
Ok right, i got it !! thank you for your hint :)
PS: sorry for that copy/paste that made my code awful, i'll do it correctly the next time ;)
ha ha, my decision was not accepted only because i moved "use strict" from the function to the first line of code, and the tests gave out all sorts of nonsense. But as soon as i returned "use strict" back inside the function, my decision immediately became correct) Funny kata(no).
who show me, pleas, how to make this one row?
idk
This comment has been hidden.
When
sumOfArrEl([18])
is called, your function returns[18]
, but it should return 18.This comment has been hidden.
The description incorrectly mentions the array can contain integer values, whereas the C translation has an
int
array.Ruby should be updated to 3.0
For solution marked as "Best Practices" the Test option throws an error: "Failed asserting that 0.0 is identical to 0."
Fixed it, please report cases like this here: https://github.com/codewars/content-issues/issues/99 if you find another kata with this problem.
This comment has been hidden.
Firstly, please use Spoiler flag when you post code - it is visible to everyone. I have done this for you this time.
Secondly - the example code given to you when you open the kata is:
If you have renamed the function
def arrlst(n):
then that's probably why it is not working - you must retain the name of the function as it is given to you (because the Codewars test will search for this named function when performing the tests)edit - update: also in the code that you are showing, the argument
n
is aninteger
- in the Codewars kata the input you are given,a
, is a Pythonlist
containingintegers
. Your function should therefore work for such an input type.This comment has been hidden.
This comment has been hidden.
Please use a spoiler flag when you post code. I've just put the flag on for you. How some code not working would be an issue? An issue is a bug in the kata.
Not work meaning even this code write properly and run properly out of Kata it not passed the test. Maybe some bug on kata. Please let me know why this happened, or label it as bag in Kata. Thanks about the spoiler mark.
If there is actually an issue, we have no way to know if it's the case, and still less how to fix it. I strongly advice you to read carefully this documentation and not to raise issues so lightly in the future: https://docs.codewars.com/training/troubleshooting/
Hello. My code corret work im my computer, but here I get error "EOFError: EOF when reading a line". I read in Internet that this mistake to appear if use code from python3 on online editor where use python2. What can I do in this situation?
Start by reading this: https://docs.codewars.com/training/troubleshooting
That's not the problem, are you using
input
somewhere? You need to use your function's argument.This comment has been hidden.
Lua translation!
approved
Why do we need the inport line 2 ?
from solution import sum_array
sum() is a built-in fonction. It seems working whitout this import
For what is use this module "solution"?
Please, help me to understand.
This import allows the tests to access to the user's solution. You don't need to care about this, just don't change it or sample tests will be broken.
Edit: well, tests work without it.
solution
is the page containing the user's solution. However you should not change this unless you know what you are doing, but this cannot bring you anything good (the only thing you could do with some profit is adding manually some tests in this window). This is just the basic tests set up, you should just edit thesolution
window.Thanks for your explanation!
My code gives the required values but I keep getting the 'None should equal 0' error. help?
You must return the result, not print it.
None
means your function returns nothing.Please see this bullet point: https://docs.codewars.com/training/troubleshooting#.print-vs-return
Thank you very much
This comment has been hidden.
This comment has been hidden.
Your code not working is not an issue (= a bug in the kata). Please refer to the documentation, we cannot help you since you give no information about what you are doing, we don't even know which language you are using: https://docs.codewars.com/training/troubleshooting/
This kata is a subject to deduplication process here: https://github.com/codewars/content-issues/issues/73 Please join the discussion to share your opinions, and help us identify duplicate kata and retire them.
This kata was decided to stay.
This comment has been hidden.
You're not using the argument of the function, and your function always returns 0.0, that's what's wrong. There are also other things wrong, but I'll let you figure it out.
thanks..
This comment has been hidden.
Duplicate issue above
This comment has been hidden.
This comment has been hidden.
Please read this.
strlen
can be called only on C-strings.values
is an array of ints, and not characters.sry, im new to this thanks for the tip
tests are evaluating int types, problem statement and return types are double
Actually it depends on language. Some languages use doubles, some use ints, and some even something else. There's too many solutions in all languages to bring them all to some common denominator. I will think how to improve this.
Fixed Go translation with resolved merge conflicts and fuzzy equality test for doubles.
PHP: random tests use strict comparison for doubles
Elixir: some tests use strict comparison for doubles
C# tests use strict comparison for doubles
Clojure: no random tests
Java translation with random tests and resolved merge conflicts. After it gets accepted, I can work on fixing other versions.
This comment has been hidden.
Fixed.
Got these errors in testing upon submission: multiple numbers should sum to correct total Expected 3921.1946752712815, but instead got 3921.194675271282
multiple numbers with negatives should sum to correct total Expected -2474.1512793585343, but instead got -2474.151279358535
Same problem.
multiple numbers should sum to correct total Expected 1927.2828119841463, but instead got 1927.2828119841465 multiple numbers with negatives should sum to correct total Expected -5147.9807804336315, but instead got -5147.980780433631
No Random tests in Python
Random tests not working! ((
Factor translation
Racket translation
approved
Thank you for reviewing the translation.
Some translations waiting: Go Java
Merge conflicts gonna pile up! :wink:
Java translation has been approved. Go translation got superseded by this fork: https://www.codewars.com/kumite/5d4da226feb62f00153941e3?sel=5fd58299148bfb0022a19ecc.
DARN this is the kata that my kata was a duplicate of. oh well..
This comment has been hidden.
if(numbers.length >= 0){ return 0; } try replacing >= with ===
'Looks like you've solved it'
This was my fitst Kata. Really enjoyed it!!
I am hoping this kick-starts my involvement in this community.
Any tips to get the best out of the community (and to put the best in), please message me. I'd love to hear from you!
Very late reply. But I'm really enjoying typing out a solution multiple time different ways! Repetition is key for me!
Go translation
Superseded by this fork: https://www.codewars.com/kumite/5d4da226feb62f00153941e3?sel=5fd58299148bfb0022a19ecc.
This comment has been hidden.
why: foldr (+) 0 fails!
it doesn't pass this test case:
should work for an arbitrary list of Doubles
Falsifiable (after 9 tests): [-1.849387446457596,8.988142271287629,-5.452834988829937,-2.11 ..]
Read the posts from 4 years ago below. I don't do Haskell tho.
// Sum Numbers function sum (numbers) { "use strict";
};
I see there is a semi colon after end curly braces. What does it means in JavaScript?
Nothing. Semicolons after braces are optional, unless you're declaring a variable (defining an arrow function):
There are 2 top-level statements, 1st:
2nd:
Empty statements can be used anywhere, like
Why would anyone do it is a different question...
how come? In ruby arr.sum
undefined method `sum' for []:Array (NoMethodError)
Array#sum
method does not exists in documentation. Maybe you intendinject
Not in Ruby 2.2 (current Ruby version on CW)
This comment has been hidden.
This comment has been hidden.
PHP Translation Kumited - please carefully review and approve :D
An exercise for beginners in order to work reduce method in the case of Javascript, is a very good thing. Reduce is a very good alternative to loops (opinion from a beginner like me)
C translation kumited. :)
This comment has been hidden.
your code works fine, I try it just now
Why cant I submit this code?
why not?
What error message did you get?
And etc.
Such error is not reproducible by now. Do raise one if you've encounter it again !
Issue on Javascript version of this kata. I have created the standard solution for this kata but it is giving 0 as a result in every test case. I've posted my solution elsewhere and others have informed me there is nothing wrong with my code.
function sum (numbers) { var total = 0; for (i=0; i>numbers.length; i++) { total+=numbers[i]; console.log(total); }; return total; console.log(numbers); };
Check the condition in your for loop again.
This comment has been hidden.
Another option would be to verify that
sum
works onRational
s rather thanDouble
s, unless they're already being tested.This comment has been hidden.
Fixed Haskell
If there are other language versions with the same issue, please raise a separate issue with a list of all of them.
This comment has been hidden.
Thanks but it's a bit disturbing: how can I know if I should do it left or right associative to comply with your test? If the algorithm is good for Int, isn't it sufficient?
I'm not the author of this kata, that's why I posted this as a suggestion. That being said…
Have a look at the languages. This kata is provided in JavaScript, Ruby and Haskell, and in JS and Ruby you usually iterate a list or array from left to right. That's a good hint to know what the kata author had in mind. Also, (s)he probably used
sum
fromPrelude
to check your solution, so you could check the implementation of that as a last resort.Depends on what's sufficient. Loss of significance is always bad, and can occur either way. If you don't want LOS, you need to take some precautions to decrease the effect. Either way, there's one lesson you should take from this kata:
(+) :: Num a => a -> a -> a
isn't associative by any definition, just because it's part of theNum
. Instead its associativity depends ona
.Seems you have a problem with your test :
Randomized Testing should work for an arbitrary list of Doubles Falsifiable (after 12 tests): [21.797230555942683,-21.209534594494976,2.973191567337694]
but my 'sum' works for every Num...
Floating point errors.
(+)
isn't associative onDouble
, it makes a huge difference whether one adds(x1 + x2) + x3
orx1 + (x2 + x3)
:IMHO, the
Double
test should have been left out.I agree, we can leave out the
Double
test. I think it's nice to have but due to the case of floating point error, it takes away from the actual challenge if one has to worry of such but it is key to make sure that the solution works for allNum
and not just sayInt
.I did not author the Haskell part of this challenge but if @jhoffner has an opinion that'd be helpful. I cannot seem to modify the test cases for Haskell, not sure if bug or feature.
As far as I know the Test cases cannot get changed after a kata has been approved, at least not from the author, only from administrators. But that's only hear-say, haven't tried it myself yet.
I'm stick on the exact same issue ...
This comment has been hidden.
Using left-associative operator works fine like foldl
Whenever I test my code, I get the following error: Any help would be grealty appreciated.
+': nil can't be coerced into Fixnum (TypeError) from
block in sum' fromeach' from
sum' from ` '.each
will only allow 1 parameter for the block so you cannot do:numbers.each {|total, i| total += i}
You can donumbers.each { |i| total += i }
but you'll need total be done in some other way.This comment has been hidden.
Sorry, I seemed to have missed an email detailing this comment. Your solution is close but realize that Array.map will return an array with the block executed on each element of the array! So you should be making sure to return the
sum
would be a good idea.i run it on irb and it get the right answer but it fail the test. Help
Sum Numbers
def sum(numbers) total = 0 if numbers.size == 0 total = 0 else numbers.each {|i| total += i} end puts total
end
You need to return the total now print to the screen.
Well, this has likely been implemented by another kata, but I'm not 100% confident of it.
Maybe in some other form but I couldn't find one.
Good problem and thorough unit testing - well done for making an excellent kata! I might suggest, however, making one or two random cases for sound testing.
add more special cases, and errors if strings are passed as array elements, example : '4', '234' etc.
What special cases are you thinking about?
I'll think about error checking but I don't want to bog the problem down for beginners with error checking.