7 kyu
Get the Middle Character
15,429 of 281,518Shivo
Loading description...
Fundamentals
Strings
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.
There is no mention in the challenge description on whether all the strings passed to the program contain exclusively ASCII characters or whether other unicode symbols are possible. I worked under the assumption that the function only has to work with ASCII and the tests ended up passing, but adding this to the challenge description would be nice for low-level languages like C, C++, Rust, ...
is the function is passed a non-empty string per the description, then why does the random tests pass an array?
in what language?
I'm not sure what the OP was using but I am also seeing this in Javascript
should be fixed
I was using Javascript
Description needs some cleanup: the note about error in JS tests shold be removed, and JS tests should be fixed. Examples can be made language-neutral.
done
maybe the description should specify that the string only contains ASCII characters ? most solutions would be wrong for multibyte (Rust, C++) /UTF-16 strings (Java, JavaScript, C#...)
Found this really good. Quite challening but not too challenging so I'd give up. Kept me going to find the answer. Nice one
This comment has been hidden.
Because
i
is not a number. Please stop right now. Go read the Troubleshooting section of the docs I told you.in normal python it works though.
Check this out: https://www.w3schools.com/python/python_for_loops.asp see what the example with the string
"banana"
prints.Now try this out, that's basically what you're trying to do with your code:
And see it'll fail with the same error that you get here.
Lua translation!
Approved
Impossibly difficult IQ challenge == 20000000000000000000000000000
I had to get help from chatGPT to solve it. It was a little bit difficult :( Could someone explain to me how can we solve any problem at coding alone in the most time? How can we get our own creative solution and develop one of the most difficult spirit of a coder? Cretivity to solve anything?
This comment has been hidden.
Please don't:
Not a kata suggestion. See https://docs.codewars.com/training/troubleshooting#post-discourse.
This comment has been hidden.
Cheers
Owhh, my bad.
I'm new to Codewars and still learning this platform, btw thanks for reminding me 🙏🏼
In the future, I won't let it happens again.
This comment has been hidden.
Please use appropriate markdown formatting when posting code. See https://docs.codewars.com/training/troubleshooting/#post-discourse.
See https://docs.codewars.com/training/troubleshooting#works-but-no.
This comment has been hidden.
kata has been completed by OP
This comment has been hidden.
assuming
mid
is set tolen(s) // 2
: no, these would return the first and second halves of the string, respectivelyThis comment has been hidden.
Your code is wrong, you print one thing and return another. Not a kata issue.
This comment has been hidden.
This comment has been hidden.
There is no issue with the kata:
Your code is wrong, please read this: https://docs.codewars.com/training/troubleshooting/#expected-the-same
Change "Your job is to return the middle character of the word" to "Your job is to return the middle character(s) of the word" :)
done
I suggest to add this casetest too because the string "ƒoo" contains a non-ASCII character, which may behave differently than ASCII characters in certain operations.
for example the len of
ƒoo
is 4 not 3.Just curious, why did they make the fancy f count as 2?
This comment has been hidden.
i can't find the solution, can someone help me plz?!
This comment has been hidden.
This comment has been hidden.
Exactly
heyy, the kata is working on yah browser guys?? mine keep on returning an error "This error was caused due to an issue processing the web request, not because of an issue executing your code"
Yeah man, been down most of the day :(
https://status.codewars.com/
Usually that's because of the internet. See if your connection is working alright. Continue running the code till it works.
Hi all
Can someone kindly take a look at my code for the "Get Middle Characters" challenge? I can't for the life of me, figure out why it isn't working. Are there bugs in some of the Katas?
same issue,whats ur code
D translation
Approved!
you do not need to worry about your solution timing out
I took that as a challenge.
Description is a little inaccurate. It states the input is
0 < str < 1000
but this is wrong as you are given 0 length strings in some of the tests at least for Go.change the input description to
0 =< str < 1000
Go tests fixed
Nim translation fixes
thanks!
This comment has been hidden.
Don't post solutions in Discourse.
This comment has been hidden.
Please use a spoiler flag when you post code, so that users who didn´t solve the kata cannot see it; I put the flag for you this time. Also use markdown tags to format your code or it's not usable. Refer to the documentation about this and more: https://docs.codewars.com/training/troubleshooting/#post-discourse
I'm sorry about that. Thank you for your assistance. How can I delete it?
You can't. But don't worry fot that.
Trying to compile in TypeScript. Something wrong with tests.
test.ts:6:23 - error TS7006: Parameter 'expected' implicitly has an 'any' type. 6 function test(string, expected) {
If try to add types to test function explicitly:
test.ts:7:31 - error TS2339: Property 'Challenge' does not exist on type 'typeof import("/workspace/default/solution")'. 7 assert.strictEqual(solution.Challenge.getMiddle(string), expected) ~~~~~~~~~ test.ts:1:22 - error TS6053: File '/runner/typings/main/ambient/mocha/index.d.ts' not found. 1 /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ test.ts:2:22 - error TS6053: File '/runner/typings/main/ambient/chai/index.d.ts' not found. 2 /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
the example tests weren't up to date. Copy your current code and reset the trainer, it should be ok now.
TSError: ⨯ Unable to compile TypeScript: test.ts:7:31 - error TS2339: Property 'Challenge' does not exist on type 'typeof import("/workspace/default/solution")'.
7 assert.strictEqual(solution.Challenge.getMiddle(string), expected) ~~~~~~~~~ test.ts:1:22 - error TS6053: File '/runner/typings/main/ambient/mocha/index.d.ts' not found.
1 /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ test.ts:2:22 - error TS6053: File '/runner/typings/main/ambient/chai/index.d.ts' not found.
2 /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This comment has been hidden.
substr the best ;)
This comment has been hidden.
Thanks for approving after all)))
There is something worng with the Kotlin test.
My solution workd fine in repl, but test shows errors here
On Google Colab my code works correct (also with strings from the test), but here i've catch error message (for 'test' => None not 'es')...
Were is I wrong?
Code: *** Hide. ready to show
Read this: https://docs.codewars.com/training/troubleshooting
Sorry!
My foolish mistake - forgot 'return' in result string in code.
This comment has been hidden.
This comment has been hidden.
char two_letters[2] = {a, b}; // << here's your problem
C strings are zero terminated. So allocate 3 chars and add a 0 at the end. Or better yet use string::susbtr.
dnsvee is right, you need to nul-terminate the char array for it to be a valid string.
in Kotlin the function name is Kata which is incorrect as the tests dont compile because of name mismatch
This has been resolved.
This comment has been hidden.
Your function works fine, not a kata issue. Copy it, click reset, paste it and try again.
Typescript: missing return type in solution setup ~~
Typescript 3.3 or above should be enabled
.
This comment has been hidden.
Issue for Kotlin: The given function stub is called "Kata", but "getMiddle" is expected for the tests.
This has been resolved.
Please review fixed Go translation. Approve please.
Approved
Ah, could not solve it
This comment has been hidden.
it's because round will round either up or down depending on if the number after the decimal is .5 or less. try importing the math library and using either floor or ceil function. and adjust from there.
This comment has been hidden.
When doing substring in python the "end" index is not included in the result. So in your original code for "test" the substring would be [1:2] meaning that only index 1 would be included.
I don't know where to start with this kata, can someone help? java btw
would spliting the word into an array help?
use the concept of median
I'd start by looking at the length of the string
Ruby 3.0 should be enabled.
done
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
The Kotlin-variant had misleading function name: fun Kata(). Most of the time I spent on this assignment was to figure out if the function name was correct or not. Apparently, it should be fun getMiddle()
This comment has been hidden.
This comment has been hidden.
When doing substring in python the "end" index is not included in the result.
That makes sense. Thanks for your help!
interpolation $"" does not work here, so I do it without it and it still doesn't work. I used the test cases and my code works just fine in VS but when I run it here I get errors
What makes you say
$""
doesn't work? Did you read the error messages that you're getting? I assume you're using C#,$""
works just fine. When you test things locally, make sure you're testing exactly the same thing as is failing here. Usually when I see somebody say "it works in my environment" I assume they didn't test the thing at all, so therefore there was no failure. You could for example copy the example tests and run them, and if something in the real test cases is failing, you could add those to the example tests that you copied.This comment has been hidden.
This comment has been hidden.
There are no variables there so, yes, just letters h-e-l-l-o.
If you print things out from your code to observe what steps are carried out, you can figure out what went wrong. For an input of
"testing"
, you get a result of"e"
which definitely isn't in the middle. So, which string did you use to find an'e'
? And which index was used? There is an'e'
in that string, so if it's the right string then the wrong index was used. Or if it's the right index, then it would be that the wrong string was used. One or the other.When you dig into things and find out what's happening, there is no longer such a thing as a stupid mistake.
And yeah, you weren't testing the case that the code failed on.
"testing"
This comment has been hidden.
This comment has been hidden.
For all
s
, slice indices would be evaluated to a float.This comment has been hidden.
Bluntly, your end is not correctly validating your code. You have to go with the Codewars results.
Sounds like you only passed the sample tests part. When you press SUBMIT, there are fixed and random tests you have to pass.
What do you mean by
This comment has been hidden.
get_middle("cJq")
with your code runs the code, but doesn't test it. You can create sample tests by using expected results from random tests:Test.assert_equals(get_middle("cJq"), "J")
This shows that you are returning three characters instead of one. So you have that to fix in your code now.
Thanks, ill look into it. And thanks for the heads up of the spoiler tag.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Not kata-related. And such approach is terribly slow, while the result can be trivially obtained in constant time.
I didn't know the while statement is that slow. Thank you very much. Your answer is really helpful for me.
It's not
while
loop that is slow, but the operations you do in it. (the ones you outlined in commented line, first post)Oh, I got it. While-loop is NOT slow, BUT my approach. Thank you.
any help on returnig the middle character
This comment has been hidden.
I am a beginner using Java and I do not know where the input comes from. I thought it would be input as a string and assigned to the parameter word, but when i used word.length, it said it did not recognize the word variable. What is the problem?
you need to use word.length()
I did and it still won't work
This comment has been hidden.
This comment has been hidden.
You're not using the same Python version, and there are differences between them. When posting code like that, mark your post as having spoiler content.
If you can use "markup" to presere your code's intentation, it will be much easier to read.
You're making some assumptions about floating point numbers that may or may not be true for this problem. For example, do you expect the following expression to evaluate to true? .1 * 3 == .3
It isn't true in both Python 2.x and Python 3.x.
I've updated the kata and you can select 3.6 now, your code works there.
Dart translation submitted. Follow the link and APPROVE please :)
"already approved some time ago"
This comment has been hidden.
Using legacy code is no wrong as long as you understand what those functions do and are familiar with coding libraries in your language
maybe should be 8kyu
ranks can't be changed
This comment has been hidden.
This comment has been hidden.
you've probably figured it out by now, but look into even/odd detection as a start
Ha, have indeed. Thanks for the help :-)
This comment has been hidden.
Online I see "Error code 136 - Erroneous Arithmetic Operation", which fits with what I think went wrong.
Walk through your code with a string that's one letter long, like "a"
This comment has been hidden.
I wrote my solution in C++. I also worked with the length as an odd number first and had a similar issue. When I switched everything, and checked for even lengths first, it seemed to solve the issue. Hope this helps.
May depend on what version of Python you're using. 2.x and 3.x treat division and floats very differently. Look into floor division if you're using the latter.
In the random generator (reference Javascrip solution), this line is wrong:
var x = randint(0, alph.length);
.randint(a, b)
random integer froma
tob
inclusive. It is possible that x might havealph.length ( == 52)
---->alph[52] === undefined
. So we should delete1
fromMath.floor(Math.random() * (b - a + 1) + a)
(randint function
)!Fixed.
Hello, I think that this test have mistake. When I checked my code I don't passed 1 test which had 529 symbols and test said that i have to return 2 symbols. As I understand, when all simbols of string is even number we have return 2 symbols, else 1 symbol. If I not right, please explain me why?
It's important to identify the computer language you're using... and I'm curious what the 529 char test looks like. You may post your code for inspection so long as you mark it with the spoiler tag, and that way someone might help you.
This comment has been hidden.
Julia translation
This comment has been hidden.
I see you're new, it's not a kata issue, it's a problem with your code, use Question label for that, state the language you're using and show your code here, using markdown formatting and mark your post as having spoiler content.
Your functions should return the result, not print it, here in CW.
I'm really sorry about that, thanks for helping me!
No problem.
This comment has been hidden.
Return the result, not print it.
This comment has been hidden.
Please, don't post solutions here specially if you didn't mark your post as having spoiler content.
Sorry, first time. Added spoiler - is that ok then or should I just remove the whole thing? Thank you, Chrono79
It can't be removed now, you could ask as a comment in your solution (and see other solutions in Solutions tab), but there if you write some code in the comment, remember to mark it as a spoiler too. For me your code is ok.
Thank you, I'll follow your guidance in the future.
i solved the kata and it passed all tests. i just don't see how to submit it. I just started Codewars yesterday.
This comment has been hidden.
Why are you checking whether n is odd or even? I think you want to check whether length s is odd or even
hello, sorry, i need help i have \ instead of <, when i tape in < why ?
My code works fine in PyCharm. but in kata platform some sumples says wrong answare. in pycharm the same sumple returns the correct answare
Probably a problem with different Python versions and division.
This comment has been hidden.
This comment has been hidden.
There is a problem with the question, If you do the question in Java and for the odd questions testing only return word.substring(0);
It should return the full test word back as a check, it only returns [esting] Which is incorrect with how the substring works and the indexing of the letters.
This needs to be fixed.
It's a problem with your code, the expected value for
testing
ist
(the middle one):Go back into the question and use word.substring(0) and tell me what appears in the brackets.
wouldn't we assume, [0] = T , [1] = E , [2] = S, [3] = T , [4] = I , [5] = N , [6] = G
Therefore if word.substring(0) should start from position [0] including itself so it would return testing And if we wanted the middle character for odd,
word.substring(word.length()/2 ) <--- wouldn't that be the substring from index [4] being I, not T ? 7/2 =3.5 and I would assume it rounds up? Or is that incorrect thinking would it round down on decimals to index places? Is that what it usually does?
It rounds down, read this: https://beginnersbook.com/2013/12/java-string-substring-method-example/ You also have to return 1 (if length is odd) or 2 (if it isn't) letters only.
If you mean you're returning the whole
testing
string when the input is alsotesting
being:That's how the testing framework works, it won't matter where the
t
came from, it's comparing 2 strings and the difference between one and the other is the expected only has at
and the returned (when returningtesting
) hasesting
after thet
. Nohing to fix there.Thank you for your help, it's alot clearer now.
This comment has been hidden.
Same problem here.
This comment has been hidden.
nvm, i just reload the page and it worked
My code works on visual studio but not here, why?
This comment has been hidden.
You don't return anything.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Use spoiler flag next time, and your functions should return the result, not print it.
pretty ez should be on 8 kyu
Scala translation ready for review.
"already approved some time ago"
This comment has been hidden.
Why would you even need to use
Math.abs()
? The length of a string can never be negative.This comment has been hidden.
This comment has been hidden.
It'd be an issue if the kata was broken, but it's the problem with your code. I have no idea why you have this
1
but it should the reason why it doesn't work for you (at least I removed it from the initializer and everything worked correctly). Apart from that, when I tried running your code I didn't get"t"
, there was an additional byte with the value of1
(or something close to it), but I suppose you didn't look at the error log carefully, right?Translated to Go.
Bug in tests or description
in Details: length 0 < str < 1000 but Erlang tests contain empty string so function should handle special case
You are right. I have deleted the empty string from the erlang tests.
NASM translation submitted.
Approved. Thank you!
"already approved some time ago"
Ruby (and probably Crystal and other languages too): strings are mutable and random test is vulnerable to input modification.
Yep! Unfortunately this kata has been here for so long that I'm not allowed to edit the actual problems anymore. So in this kata, you'll have to duplicate the input string before you do anything to the input string.
The 500 completions limit was lifted for power users, are you sure you can't change them anymore?
Pretty sure it's lifted for everyone.
I guess you're out of the loop for a long time, but basically, the 500 limit should've been gone since like a month ago ;-)
Oh nice! I was not paying attention then! I'll take a look and get it fixed.
The Ruby issue should hopefully be resolved. I don't use Ruby so it is possible that I didn't do something right, but from what I can tell it works. I just did
s1 = s.dup
and I send one variable to the user, and one to the random tests. If you find any other issues with mutable strings, or if I messed something up in my fix, let me know!I'm not quite sure why the random tests in ruby are expected to display values outside the middle of the string. Maybe I'm missing something. Can someone explain why expected values exclude the middle characters for random tests and not for primary tests?
Testing for bLXT It should work for random inputs too - Expected: "bT", instead got: "LX" Testing for hBRnHu It should work for random inputs too - Expected: "BH", instead got: "Rn" Testing for FSCfE It should work for random inputs too - Expected: "Sf", instead got: "C"
Did you mutate the input string?
Resolved for a better issue (raised above)
Ya, it looks like you are removing the correct answer from the string itself. I recommend duplicating the input string before you begin to modify it, that way the input stays the same.
This was fun!
This comment has been hidden.
Thanks for the suggestion. I didn't realize that the BF translator changed the description. I'll work on getting it fixed.
So I have changed the description back to the old one for now. I tried to use the coditional operator, but something funny is going on with the bf condition. Here is that section of the description:
So basically that means that everything should take the top version except for BF which would take the bottom (codewars defaults to the first codeblock when there is no condition that fits the language). However, when you go and look at the BF training, that section is just invisible instead of showing the correct examples. Any ideas why that is?
Could you mark allow collaborators so I can check if I can solve it?
@Shivo : I've published a non-functional Objective-C translation, could you try using that description and see if it works? I'll unpublish it later in case someone feels like translating it to Objective-C.
Appreciate your help Chrono. I've changed the description, and it looks correct now.
There are problems with the tests. My script runs on my PC without issues but all tests fail here.
Show your code, mark your post as having spoiler content. The tests are ok.
This comment has been hidden.
In js no string ends with
"\0"
that is only for BF (another language). Remove that from your code.This comment has been hidden.
No problem, it seems that when BF translation was added it changed the instructions for all languages and that can be confusing, I've added a suggestion so the author can fix it.
any girl here
girl here
i am looking for a girlfriend
This comment has been hidden.
sad mofo
what is a mofo?
its so cool
i like this kata
I thought my one line was good until I saw that top one heh.
That's basically my feeling evertime I finished a Kata. Momentary victory followed by instant dismay. XD
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
console.log()
returnsundefined
So I should put the console.log before the return?
Ohhh ok without the console.log, done
Thank you (y).
This comment has been hidden.
For an odd length string, you are returning the character before the middle one
Thanks so much :)
No problem :)
BF Translation kumited
Please review and let me know if there's any suggestion. My first translation ever.
I appreciate it! I have approved it.
Time: 0ms Server Execution Error:
The server timed out waiting for the request to be processed. This may be due to high server load. Please try your request again.
Request Error: Request failed with status code 500
This error was caused due to an issue processing the web request, not because of an issue executing your code. You can retry the request.
It's a server high load issue, like it says there.
Just try again later.
This comment has been hidden.
where i'm i getting it wrong?
Assuming that this is Python. I am not great at Python, but there are a couple of things to check:
First off, the problem wants you to return a string, not a char array.
Next, you are creating your variable in an if statement that is checking for evens.
Most importantly though, you are ONLY checking for evens. If there is an odd length, you never return anything.
Hopefully these will give you a little bit of help. If you still can't get it, feel free to post your next try and I'll see if I can help more.
too much hard vork
Please do not spam the discourse section like this. If this kata is too much work for you, maybe you are missing the point of this website.
wat is dis
Hi, Please help, I am new here and using C++,the processes are quite confusing. Do i solve the challenge with my own method or do i go with the way it was writing in the solution window? Also, I solved the problem and it currently bruns on my laptop but when i click on the run sample test button, it gives this error:
Log:
es
Expected: equal to es
Actual: test
Hey there. First things first, this should be marked as a question, not an issue. Issues are for when you think there is something wrong with the problem itself.
To answer your first question, usually you will work with what is given to you in the solution window. Changing what is already there can sometimes break a problem.
If you would like me to take a look at what you currently have, reply with your solution. I won't be able to help you further until then.
Hi, when testing my function I get the following error. I see no difference between the results. Time: 98ms Passed: 0 Failed: 1 Errors: 1 Test Results: Log es None should equal 'es' does the test properly work?
did you return
I got the failure. Thank you very much.
Marking as resolved.
Hi, am new here trying to figure out my first test( showing d middle char) Thanks.
Good luck. Let me know if you have any questions.
This comment has been hidden.
I have never used ruby before, so I apologize for any strange terminology I use.
Your issue seems to stem from this line:
return s[(n-(n/2)-1),(n-(n/2))]
I believe what you THINK it is doing is incorrect. You seem to be trying to use it as a range. For example, if I wanted to get position 3 and 4, I would say
s[3,4]
. That, however, is wrong. (I believe that you would just uses[3...4]
for that).What that array call actually does is that it gets the first number and then the next n numbers (s[StartingIndex,NumberOfIndexesToGrab]). So it actually looks like this:
s[3,4] = position 3, 4, 5, and 6
. That is why you are getting 3 letters on the word Middle instead of 2.To Fix this, you have 2 options. If you want to do it the way you intended, then you need to use the ... operator to get a range of numbers:
return s[(n-(n/2)-1)...(n-(n/2))+1]
or to get it the other way, you just need to change the second part to a 2 so that you only grab 2 entries:
return s[(n-(n/2)-1),2]
Both of those should give you the answer you are looking for. If you have any questions, or if I didn't explain something well enough, let me know.
Oh wow, thanks so much! Can't believe I missed that haha
how to use 'import' for Python
i.e. I want to use the floor() and ceil() methods in my code. The math 'library' is needed to do so
codewar does not seem to support: import math
Any feedback/help?
I dont know the answer to this question, but your post should have been marked as a question, not an issue.
R Translation kumited
Please review and make any suggestions for changes or approve :)
I commented the test suite to describe the reference solution, in case you're unfamiliar with R
Thanks for the comments in your kumite. I would have never figured out what you were doing otherwise. Approved :)
You're very welcome! Thanks for approving!
This comment has been hidden.
This comment has been hidden.
In python you should be using spaces, not tabs. Your python interperater most likely converts your tabs to 8 spaces automatically, but codewars does not.
Also this should have been marked as a question, not as an issue. Please only mark issues if you see something wrong with the Kata itself.
Thanks, it worked. Going to classify accordingly next time.
Tabs specifically have different meaning for different softwares, like some will have (1 Tab = 3 Spaces)OR(1 Tab = 4 Spaces). So you should be careful while using Python. Also the Tabs are not Traditionally intended to be used.
This comment has been hidden.
Did you have a question? It looks like this is a correct answer. Please refrain from posting your answer in the discourse section unless you have a question about it.
So um...it says I'm going to be given a word...so....where's the word?
It is sent to the method/function that you write. In javascript the function looks like this:
s
is the word you are being given. If you have any other questions, let me know.my word is, the letter s? I'm supposed to find the middle character in the letter s?
s
is the input argument storing the word.I suggest you to take a look what are
variables
,function arguments
andfunction parameters
:)To further what Voile has said,
s
is the variable that stores the word that you are sent. So if you get sent the wordHello
,s
would be equal toHello
. So if I decided to go:The output would be:
As Voile has said, you may want to take a look at variables and functions in general to get a better understanding of writing code.
I understand what a variable is. I understand that s is the input argument storing "the word".
My question is, WHAT IS MY WORD.
In the instructions it says "you will be given a word".
Well, I'm waiting. It hasn't "given me a word" yet. Am I just supposed to make up a word myself? Because that's not what the instructions said. It said I would be provided one. Maybe I'm just completely blind but I don't see the word anywhere.
Quote: "You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters."
The word will be different each time due to testcases and will also include random words (randomisation) to prevent cheating. The word will be named
s
which is the parameter of the function.As shown in the image above, you can print the input
s
to the console to see what it is if you want, but your code should work on every single word, not just one specific one. Therefore it is not necessary to see what the parameters
is.console.log(s)
is responsible for the log result in the left andreturn s
is responsible for returning the final value shown by "Expected: 'es', instead got: 'test'".The example testcases show you what the parameter
s
is, and what the expected result is.The site throws an error about the mb_strlen function not existing (http://php.net/manual/en/function.mb-strlen.php).
If you just use strlen then if the string includes any multibyte characters your program won't work.
It's really limited to assume that people visiting your website only come from America and only use latin characters.
This comment has been hidden.
1.) You need to return your output instead of printing to the console.
2.) You need to change
2n+1
to2*n+1
.3.) You need to sort out your logic. You put
n=0
and then do2n+1
resulting in only two pathways - 0 or 1. This means a length of greater than 1 will not branch to the if statement, meaning None will be returned.4.) While loop is unecessary. Validation of input is okay, but change it from a while loop to an if statement. Also, change it from
type == int
totype == str
.This comment has been hidden.
You should mark your comment as a spoiler :)
I just unknow how to use the website.Eh,why is the recommanded test so different from what I had learnt.
What
This comment has been hidden.
The instructions specify
0 < str < 1000
, so I add this to my test cases.However, the tests that the Kata has, go over 1000, and have no specification for how the
getMiddle(s)
function should resolve this.Looking at the test cases now, the
randInt
for string length, looks to be trying to limit to 1000, but we should specifically go over and adjust the instructions accordingly. Or remove that line from the instructions.Ya, if you look down in the comments I explain what is happening here. Basically the random number is trying to grab a character out of the character array that is out of bounds. This causes it to return
undefined
instead of just one character. I cannot change it as this kata has gone over the limit that locks it.I take it that you are missing the whole point of the excersise though. You should not care if you get a string over length 1000. That line is just there to tell newcomers that this kata will not time out on them. It shouldnt be an issue if you get one that's slightly longer. Just return the middle character(s).
I'm pressing ATTEMPT button, all tests pass, but I don't get the rank points. Does anybody know why?
Currently Codewars platform is experiencing issues.
https://github.com/Codewars/codewars.com/issues/893
This comment has been hidden.
Currently Codewars platform is experiencing issues. Please wait warmly at the moment :)
https://github.com/Codewars/codewars.com/issues/893
Thank you very much for this information :)
This comment has been hidden.
Post your code for me and I'll take a look at it.
I made the mistake of clicking "train again" and it cleared out my code...and it's been a week so I don't remember how I tried to do it :( sorry
This comment has been hidden.
Is codewars running a Python version previous to Python 3? That will explain this issue.
I found the answer myself:
Language Versions
Python 2.7.6 and 3.4.3 are supported.
Hope this helps other people :)
This comment has been hidden.
So I see a couple of things wrong here.
First things first: Remove your commented out if statement. It doesn't need to be there.
Something weird may have happened with it, but the commented out sections aren't properly commented out in your pasted solution.
Your toString call isn't calling the correct thing
So let's take a look at the if statement:
if(s.toString.length/2==0)
.toString is a function, so to use it you need to do use
toString()
instead oftoString
.Next is the big one: Your if/else statements are checking for the wrong thing
Let's continue looking at
if(s.toString.length/2==0)
.You are dividing by 2 to check if the word is an even number. This will not work. Let's say that you have an even word that is 4 characters long like the word
test
:So your if statement would not trigger even though it is an even number. What you are actually looking for is a modulo aka a
%
. Let's look at test again with a modulo:It looks like you were actually trying to use modulo in your solution, but you accidentally used
/
instead.Lastly, you should use an else rather than an else if
So in your solution you have an
if
and anelse if
. In coding we generally only useelse if
if there is a 3rd option, otherwise we just useelse
. This is because in cases where the parameters are sent that match neither theif
or theelse if
your function would throw errors.So in this solution, you have an if statement checking for even number words. If a number is not even, it is odd, so you don't need to have any other if statements in your solution. So you should just replace your
else if
with just anelse
.If you have any other issues, feel free to let me know. I ran your solution with the above changes and it worked perfectly.
I have been trying to learn for a while and no one helped me this much, you went through my whole code, I can't thank you enough Shivo. Many thanks .
No problem! Keep at it! Let me know if you have any other issues with it.
This comment has been hidden.
I'm assuming that this is in python. We're going to use the example you are having issues with to help understand what's going wrong. The word you are failing is
Test
.There are 2 things wrong with your code:
The if/else statement in the first line doesn't do anything. It can be completely removed.
The last line has
return s[evenslice:slicelen]
. In other words it is:return s[PositionLeftOfCenter:PositionCenter]
. So in our exampletest
, this would bereturn s[1,2]
. Now that may look good, but you have to remember that when slicing an array the lower bounds are inclusive, and the upper bounds are exclusive. So our examples[1,2]
would return what's in position 1, but not 2. In other words, it would returne
. So to get it to also return the s, you'll need to uses[evenslice:slicelen+1]
.Let me know if you are still having issues. I ran your code with the above changes and everything runs fine.
thank you!!
Is it normal that instructions says that maximum length is 1000, but in tests we have 8 tests with length bigger then 1000&
That may be a bug. What language was this in?
Js
Well you are absolutely 100% right. What's happening is that in my random tests, there is a function that grabs a random letter out of an array. The array is 1 shorter than the random generator's maximum value (it started as a random generator that ignored the upper bound, but I changed it and forgot to update the array). So when the random number generator tries to grab the maximum value letter, it instead gets "undefined". This greatly increases the number of letters in some of the cases pushing it over the 1000 letter limit.
I would fix it, but unfortunately codewars locks you out of editting after so many people have passed your test. So we'll unfortunately just have to deal with it sometimes haveing slightly over 1000 letters.
tldr: My bad. Random generator isnt right. Can't change it because of codewars test case locking.
This comment has been hidden.
Change
c = int((length / 2) - 0.5)
toc = int(length / 2)
P.S can you not mark your comment as an issue if there is not an issue with the Kata, mark it as a "question".
This comment has been hidden.
It seems to work fine for me. Just remove the duplicated
len
fromif (len len>0){
. Also,if(len<1000)
does not work because the testcases are random and some of the input parameters are over 1000 characters long, meaning your statement will not execute and will return undefined instead (default void value).You have to use Markdown on Codewars to format thing properly. Have a look at code highlighting for information. You have to use three backticks (`) before and after your code.
Hi, thx for the kata - I've trouble to submit my solution: the test-suite is passing but I've some output on stderr (which prevents me from submitting?):
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:11:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:12:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:13:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:23:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:24:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:25:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:26:1: Warning: Tab character
/tmp/haskell116115-18-iam4dq.uei7vcayvi/Codewars/G964/Getmiddle/Test.hs:27:1: Warning: Tab character
Hi there, it's an unfortunate compiler issue that codewars has at the moment. I have updated the things on my end now. Just make sure that your solution isn't using tabs.
This comment has been hidden.
Typescript version test contains the solution.
Thanks for letting me know. The person who translated it must have forgotten to remove it from the example test cases. It should now be removed.
randTests(MiddleTests) Log tS this is my result why wrong??? ✘ Middle of VpqjQxytKEcUDHJFMVDNJtRLNjtAAsFzrSevwWYVMgSJWuNghMNyXIAquRUSHFwWhzvCEkoYYdCRyjUQFPKEhlkyRWjOkhBAsvgEONxbFLMxhkxvEtJXZMxgdBJozEdjbezJsLMBUNQxliNUpHsyqNsSgfLnBKbpcpOAJEfegPiBxFKwtwdrgkArLnyQwLkVVcritSFSHGFQBVHdsKNkTVOQKOgrazDAyakLwLHuySjEdyBSBhpOLsJnwfuoxnEEsLazntgBEyHTFFLvduzYVplTpbAeLZsTLBFmsDVfjfQaCQuVokEEgtPkDuKeviitjNNvlkNAYsjsCAZLhIwgjaazIXXgizDIjOaXVmcBOGwPfKcBBCqFcBzLVSZoGOaeohsWcEbBWs is tS not expected:<[tS]> but was:<[]>
I can't help you without your code. Please tell me what language you are using and post your code with a spoiler tag.
This comment has been hidden.
What language was this in? If you need help with your code, post your code here with the spoiler tag.
Cannot submit this kata in ruby. It has passed all tests, but when I click "submit" btn it just goes through the tests again. Thank you in advance.
I just submitted a Ruby solution and it worked just fine. You may need to make sure that you don't have anything blocking the scripts on that page. The Submit button should change to a "Submit Final" button after the first press. If that still doesn't work, post your code here and I will give it a try.
This comment has been hidden.
Please don't mark things as issues when you can't solve a problem. The issue button is for when the Kata has an issue that needs to be looked at. You should instead use the question button when you have a question about your work.
I assume you figured out what you were doing wrong because you've submitted the solution correctly, but if you still need help, let me know and I'll take a look at it.
Hi Shivo, sorry I was doing thi late at night and meant to mark it as question. I did sort it out thanks :)
No problem! I noticed that you may be new around here and just wanted to explain the difference.
I solved this recursively, mainly because I'm a beginner and wanted to practise doing so. Any thoughts on best practice in terms of effinciency/memory/ other considerations?
This comment has been hidden.
It's a small error for sure, but in your else if statement you are checking if
m%2!==0
that m is the value of half of the word length. Instead, you need to check against the full word length.I wouldn't normally outright tell you what you did wrong, but it looks like you actually meant to check against the whole word length. You just used
m
by mistake. If you need any more help, let me know.Thank you!
This comment has been hidden.
It seems like you are only having issues with the even count words. I'm not an expert in javascript, but perhaps you should look at this section of your code:
return s.length%2 ?...
:So you are checking here if the letter count is odd or even, but you forgot to make it a conditional. Your code should say
return s.length%2 == 0 ?...
, that way it is checking if the remainder is equal to 0 (AKA if it is an even number).Hopefully that can get you set on the correct path to solving this one. Good luck!
This comment has been hidden.
Your code gives me the error
None should equal 'es'
. Looks like you just need to return your valuess
andodd
, otherwise your solution should be perfectly validRemeber to use backticks for ouptutting code in your comments (see here: https://github.com/Codewars/codewars.com/wiki/Codewars-Editor-formatting). Also next time let us know what language your working with so it'll be easier to debug :)
Happy Coding!
Wow, yeah I didn't even think about using return instead of print.. Thank you so much, and also, I will definitely read up on the formatting of my code so it can be more readable. I was using Python, sorry about that, I know that now also to put in the langauge I'm using! Thank you!
This comment has been hidden.
It was a server issue.
To format your code you can use backtick fences:
This comment has been hidden.
This comment has been hidden.
There was a server outage which is why your code was not running. Its fixed now.
Very nice, my first app i did with Python and on this website and overall feel very satisfied :D
Thanks!
Thanks for the feedback!
Great Kata! C++ Kumited :)
Thanks! Approved.
Sweet! Added Elixir + TypeScript too.
Awesome! Thank you very much!
Smtg wrong with Ruby Random test...
Random tests Testing for diFpFlyWfzXcEHNCIlz It should work for random inputs too - Expected: "fX", instead got: "z" Testing for sPSUvuIIrCZlcrYHino It should work for random inputs too - Expected: "rZ", instead got: "C" Testing for yCTuZX It should work for random inputs too - Expected: "CZ", instead got: "Tu"
You are editing the variables. So when you get the variable
yCTuZX
, you are taking the middle two (TU) and removing them from the variable. Then when I get the variable to test, it just sends my codeyCZX
because you have removed letters from it. Try duplicating the variable to a different veriable, or go with the better solution of using a method that doesn't affect the variables. If you keep changing variables that are sent to you, you are going to run into this issue a lot. So it is best to avoid doing that on Codewars. (I would speak for general coding practices, but I am not a ruby dev and I don't know if it is standard to edit incoming parameters.)Oh! Okay, thank you!
Shivo, I really liked this kata - great job
Thanks SpaceCamel!
I think you have not been notified: Clojure translation kumited-)
Thanks a ton! I was away for a few days, so I missed some of these :)
Hi. Nice Kata. But why specify an upper bound on the length of the input string?
I just like to tell people exactly what they will be testing against. I wanted this kata to be friendly for newcomers, so I gave an upper bound so that they wouldn't have to worry about run time and can focus on the problem. A lot of the higher kyu katas are 5% figuring out how to solve the problem and 95% figuring out how to solve it more efficiently. Which is fine, but with an easier question like this, I didn't want to discourage anyone who is new to programming because they can't figure out how to make a correct solution work faster.
tl:dr I wanted it to be friendly to newcomers.
Let me know if you have any other questions :)
Thank you.
Nice! Coffeescript translation kumited.
Approved!
Thanks!
Ranked, upvoted, translated :)
Please note for future katas that the function names should always start with a lowercase character in JS, as the capitalized version is usually reserved for classes.
Thanks for the tip! I'll keep that in mind in the future. I Have approved your translationso. Thank you!
My pleasure and already working on your other katas :)