I'm new to python and just starting the journey to learn how to code. I answered a problem on coding bat, however my code was different than the solution. I would appreciate if someone could tell me why my code is not as good as the solution. Thanks!
Question: Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged.
My Code:
def not_string(str):
if 'not' in str[0:3]:
return str
else:
return ('not '+ str)
Answer:
def not_string(str):
if len(str) >= 3 and str[:3] == "not":
return str
return "not " + str
Your code is correct, however, there are a couple of differences between your code and the solution. To begin with, in the solution code, they check that the length of the string is greater than or equal to 3. Using the len(str) function, it will return the number of values in that string. For instance, if I had a string of value "codingbat", the length of str would be 9. It is good practice to check the length of the str before taking further action upon it. Furthermore, the solution checks from [:3], whereas your answer checks from [0:3]; these are the same thing but it is better practice to do [:3] as it shows more professionally that it is checking the first 3 values. Lastly, you had an else statement after your first if statement which was not necessary; as long as you make sure that whatever you wanted it to do if the if statement failed, is aligned with the first if command, then they will serve the same function but it is more professional to remove the "else" and rather back indent the else command saying that if the if statement failed it would do what you wanted it to do.
Keep in mind, that in any coding language, there are several ways to reach the desired solution. Other than that, great job!
Related
Hold on: It's not as easy as it sounds in the title.
I've been working on a very crude AI, and the seemingly hard bits have been easy but this one little function is being really hard.
What I want this to do is get some of the chars that occur before a chars in the string. For example,
get_piece_behind("Hello World", 5, 3) #Return the 3 chars that come before ' ' (the fifth char)
'llo'
get_piece_behind("Hello World", 4, 3) #Return the 3 chars that come before 'o' in "hello" (the fourth char)
'ell'
get_piece_behind("Hello World", 5, 2) #Return the 2 chars that come before the fifth char
'lo'
The code accepts a string, an int marking a place in the string, and an int telling the function how far back it should look.
I get the idea this should be a super-simple one-liner... but my coffee infused brain has been staring at it for the past hour, rewriting it over and over, and nothing seems to work (my current function returns small bits of string, but from the wrong place)
def get_piece_behind(string, place, length_of_piece): #My current function
string = string[(place - length_of_piece):]
string = string[:place]
return string
Does anyone know how to fix this? I get the idea that it's a tiny, stupid error that I will have completely overlooked.
Thanks!
Python strings are sequences, and as such you can use the slice-index syntax to retrieve sub-sequeces of it:
a = "hello world"
a[1:3] # retrieves the chars from the second posistion (index 1) up to the 4th.
# the same, but as you want, putting expressins to calculate the indexes:
a[5-3:5]
a[4-3:4]
I suggest you to read the following document in whole before proceeding with your task - might save you a lot of time:
https://docs.python.org/3/tutorial/introduction.html
You are overlooking in your string splicing.
Try this:
def get_piece_behind(string, place, length_of_piece):
string = string[(place-length_of_piece) : place]
return string
Just do it in one line :) since your string change after first reassignment, also character positions will change:
def get_piece_behind(_string, place, length_of_piece): #My current function
_string = _string[(place - length_of_piece):place]
return _string
The index of characters changes as you cut first with place - length_of_piece, which gives 2, so you were cutting from third char, "llo World" then 5 characters before, resulting in "llo W".
This should work for you:
def get_piece_behind(string, place, length_of_piece):
return string[place-length_of_piece:place]
Output:
llo
ell
lo
I am trying to get my hands dirty with Scala where is I am playing with scala.collection.immutable.StringOps on the terminal. In the String method drop(), I tried executing this code
"stackoverflow".drop(-12)
and the output I received was
stackoverflow
The -12 was a typo but this result is unexpected as it should truncate 12 characters from last or be an error or exception. Because when we pass an integer into the drop(), it eliminates the first characters from the string equivalent to the number of arguments. Why is this behavior kept with this method in Scala? Can this become useful in some scenarios? What is the reason for this behavior?
Scala has many other different behaviors that other languages don't support such as
true > false is true and true < false is false.
The documentation says "If n is negative, don't drop any elements". I'm guessing the reason is that in some cases it lets you skip doing some math. For instance, let's say you want to drop from the start of two strings so that they are equal length. You could do:
def makeSameLength(s1: String, s2: String): (String, String) = {
(s1.drop(s1.size-s2.size), s2.drop(s2.size-s1.size))
}
Cases like this where you have to drop some variable number of elements from a sequence come up a lot, and usually if the math works out to a negative number, that means you just don't want to drop anything at all. So this saves you from having to add in some conditional logic, or include a max(x, 0) or similar.
I do agree it's a bit surprising, but can see why it might be useful.
I have a boolean function that evaluates a 1d array of characters. It has two parameters: a 1d array of characters , and a char c. I want the function to return true if the given char c appears at least four consecutive times within the given array, otherwise it will return false.
I don't know how to start or complete this function at all. Please help! Thanks.
I hope I'm not doing you're homework for you ;). So here's the sudo-code for this problem to help you get started
The first thing you would want is the method header that returns a boolean, and has a parameter for an array of characters and a char
The next step would be to create a counter and run a loop to sift threw every character in the array. Every time you encounter that specific character in the array you would add one to the counter, if the next character isn't the one you want then you would reset the counter to 0. Then add a conditional in the loop to check if the counter reaches 4, if so you would return true. If it never reaches 4 then you would want to return false. Go ahead and try to code that up and see if you get it.
Simple problem. If this is your homework then you shouldn't be doing this. Your question needs to be changed. Firstly give it a try before asking and then once you are done trying you can post the errors or the snippets of codes that you are unsure of and then ask for help. Else you are not going to learn anything. Got a simple solution to your problems. I'm not going to give you the complete solution but instead a guide to help you with your question.
In my opinion string is always a better choice to use instead of char because of the functions that come with that package. Char is just plain old annoying (again in my opinion) unless your question or whatever you are doing this program for requires you to use char.
First,
Create your main program -> create your array and initialize it if you want or you can prompt the user for their input. whichever works.
use the "bool" data type to create your Boolean variable.
Prompt the user to input the char value to check for.
Now call the function and provide the parameters. I'm guessing the function is where you are stuck with so i'm going to provide you the snippets from the code that i wrote for this question.
bool check(char* <array_name>, char* <array_name>) //for the array list and the
//value to check for
{
int size;
size = strlen(<array_name>); //to get the size of the array (array list)
int counter=0; //to keep count of the occurrence of the char to check
for(int x=0; x<size; x++) //ar = array list and token = char to check
{
if(ar[x]==token[0]) //check for each iteration if token is in ar[x]
counter++; //if it is then counter increases by 1
else
counter = 0; //To reset the value to 0 if its not consecutive.
if(counter == 4) //to stop the loop when 4 consecutive values has been found.
break;
}
if(counter >= 4) //as per your requirement 4 or above
return true;
else
return false;
}
EDIT: This is to check the values just until 4 consecutive values of what you are searching for is found and to end the loop. If you want it in a different way then please feel free to comment on this answer. You can always add another counter or anything at all to check how many consecutive times the value is found. For example 1,1,1,1,2,3,4,1,1,1,1,2,3,4,1,1,1,1,2,3,4.
The counter for that will be 3 since it happens 3 times with each time repeating the same value for 4 times consecutively.
If this is your homework then you better study properly because it's a really simple problem and your shouldn't be asking for a solution but instead ask for guidance and try first.
Good luck! If you need further clarification or help just comment on this.
Today I've finally decided to make an account, in hope for some aid in an issue I've spent the last few hours hunting. (I've spent the past couple hours hunting down a response, from Google to here to Unity Answers. Here's everything that I've found so far, which doesn't work.)
What I'm looking for, is to change a string of purely words/letters into an integer. Therefore "Hello World", would be translated into a string of numbers accordingly. This may be surprising, but this is a lot harder than it sounds. I've found a way to do essentially everything but, thus far.
Presumably the best way would be to get the ASCII value of each letter in the string, and put them all together into a single integer. (No sequences or need to separate them, but one single number.) I have no idea where to get started or how to do that, however. Really anything that you think would work, preferably as short-hand and un-bothersome as possible.
To be as clear as possible, I need to take the letter-only variable "example" and transmorph it to be a integer/only a sequence of numbers.
If you're just trying to convert an arbitrary string into a random seed, then why not try randomSeed.GetHashCode()? That will return an int value suitable for setting the seed, which would produce the same number each time the same string is entered.
You can iterate over all characters, get their charCode and chain them together. The first method splits the string into single chars and uses Array.reduce:
var str = 'qwertzuiop';
var num = parseInt(str.split('').reduce(function(a, b) {return a + b.charCodeAt(0);}, '');
The second calls Array.forEach on the string, because it has numerical indices and a length property.
var num = ''; [].forEach.call(str, function(c) {num += c.charCodeAt(0);});
num = parseInt(num);
In stoneaged browsers you have to use for-loops instead.
the given example is really simple so I don't think it needs any explaining.
I couldn't find any references on the docs that can explain this behaviour and I've also found a couple workarrounds for this, so you don't really need to bother finding them (thanks in advance though).
I'd just really like if some1 could explain this..... doesn't make any sense to me:
// comma separated IDs to later use in SQL statement
$var = '10,20,30,40,743,102394';
$multi_intval = intval($var); // same with (int) $var
$multi_string = strval($var); // same with (string) $var
var_dump($multi_intval, $multi_string, $multi_intval == $multi_string);
// result
int(10) string(22) "10,20,30,40,743,102394" bool(true)
how is 10 equal to a 22 strlen string?
I just ran across this looking for another answer, so even though it is old Ill give an answer in case someone else comes across it.
From the php docs here: If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number
Because of this your comparison intval($var) == strval($var) is changed to something like intval($var) == intval(strval($var)) which is of course equal (I don't know what the language is using to change the string to an integer, the above is just visual representation). If you really need to know if they are identical, use ===.