I am currently doing a problem on coding bat called string_bits and have been debugging it using Thonny and putting the code into coding bat to see if it is correct. Right now I am getting an error with my code in codingbat that says string index out of range. The weird thing is when I run it in Thonny I don't get the error. What is happening here?
def string_bits(str):
new_str = [str[0]]
count = 0
for letter in str[1:]:
count += 1
if count % 2 == 0:
new_str.append(letter)
return "".join(new_str)
Maybe the test trying some different kinds of input, and not only the obvious.
for example if your input is an empty string: it will cause such an "out of range" error.
Try to add input check before any operation on the string (which is actually an array)
like so:
def string_bits(str):
# check input for empty string
if str == "":
# quit function if invalid input
return ""
new_str = [str[0]]
count = 0
for letter in str[1:]:
count += 1
if count % 2 == 0:
new_str.append(letter)
return "".join(new_str)
Related
I was given a prompt to solve and was able to write code that passed, but my question is, is there a more simplified way I could write this without having to create a new named variable (s_index = 0)? The code works just fine but I'm not sure if I solved it the way I was expected to and am open to suggestions for improvement :)
Please note that this section in the work book has us focusing on using continue and break within loops
"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y)
and the user must repeat the sequence. Create a for loop that compares the two strings.
For each match, add one point to user_score. Upon a mismatch, end the game.
Sample output with inputs: 'RRGBRYYBGY' 'RRGBBRYBGY'
User score: 4
user_score = 0
simon_pattern = input()
user_pattern = input()
s_index = 0
for letter in user_pattern:
if letter == simon_pattern[s_index]:
user_score += 1
s_index += 1
else:
break
print('User score:', user_score)
using functions to encapsulate small specific parts of your logic is often helpful
def do_score(user_pattern="1234",simon_pattern="1235"):
# using enumerate you can get the indices
for s_index,a_char in enumerate(simon_pattern):
if s_index >= len(user_pattern) or a_char != user_pattern[s_index]:
# the index should always match the "sum" so no need to track or compute the sum
return s_index
return len(simon_pattern)
this method takes 2 strings and "scores" them based on the "simon_pattern" returning the score
then just
print(do_score(user_entered_input,simon_pattern))
I will rewrite this to this way: (this way you can completely eliminate the variable index, and simon_pattern[index] to get the letter)
Note - in Python a word is just a sequence of character/letters, you can iterate it directly, no need to use index.
simon = 'RRGBRYYBGY'
user = 'RRGBBRYBGY' # User score: 4
user_score = 0
for user_char, simon_char in zip(user, simon):
if user_char == simon_char: # continue to check/and match...
user_score += 1
else: # break, if no match!
break
print('User score:', user_score)
Strictly, you never need to know the index or index into the strings, you can just use zip() to combine tuples of respective characters from the two (possibly different-length) strings:
def do_score(user_pattern='RRGBRYYBGY', simon_pattern='RRGBBRYBGY'):
score = 0
for uc,sc in zip(user_pattern, simon_pattern):
if uc == sc:
score += 1
else:
break
return score
assert do_score('', '') == 0
assert do_score('RRG', '') == 0
assert do_score('', 'RRG') == 0
assert do_score('RRG', 'RRGB') == 3
I need to write a code that does a linear search on a character within a string. I have to do it without using any inbuilt functions.
The program should output the index of the found character.
If the character isn't in the sentence it should output -1.
I have tried writing the code but it inputs the sentence and character but then doesn't work.
def linear_search(intList,target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
count = count + 1
found = True
break
return found
sentence = input('Enter a sentence: ')
character = input('Enter a character: ')
character_found = linear_search(sentence,character)
if character_found:
print("The character is", count, "on the index")
else:
print("The character is -1")
You probably want this:
def linear_search(intList, target):
count = 0
while count < len(intList):
if intList[count] == target:
return count
else:
count += 1
return -1
Problems with your code:
If the value at the current index is equal to target, then you've found it! You can just return count. If not, then you want to increase count. Currently, your code does the opposite.
Your code returns found, which means that it will only ever return True or False. There is actually no need for a found variable, since you can break out of the function by returning, but in any case you should be returning count.
Outside the function, you attempt to refer to count. That won't work, because count is a local variable: a new instance of count is created for every time you run the function, and destroyed after the function returns. Incidentally, this is another reason you should be returning count, not found: you can just check if count == -1.
You are getting stuck in an infinite loop, because you only update the count variable after the solution is found.
Proper implementation of the while loop:
def linear_search(intList, target):
found = False
count = 0
while count < len(intList):
if intList[count] == target:
found = True
break
count = count + 1
I also suggest using a for-loop instead of a while-loop to prevent this mistake:
def linear_search(intList, target):
found = False
count = 0
for i in range(len(intList)):
if intList[i] == target:
found = True
count = i
break
return found
I also noticed some other mistakes, but since they aren't a part of your question I will let you try and solve those yourself first.
This question already has an answer here:
Run Length Encoding Python
(1 answer)
Closed 4 years ago.
Need to write a python function which performs the run length encoding for a given string and returns the run length encoded String.
Went through various posts in Stack Overflow and other websites in Google to get a proper understanding in Run Length Encoding in Python. Tried coding and got some output but it doesn't match the specified output. I have stated my code and output below:
def encode(input_string):
characters = []
result = ''
for character in input_string:
# End loop if all characters were counted
if set(characters) == set(input_string):
break
if character not in characters:
characters.append(character)
count = input_string.count(character)
result += character
if count > 1:
result += str(count)
return result
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
For the above string, I am getting the output as : A2B5C8
But the expected output is :1A4B8C1A1B
It would be really great if someone tell me where to make changes in the code to get the expected format of output.
You can use the following function to get the desired output:
string = "ABBBBCCCCCCCCAB"
def encode(string):
counter = 1
result = ""
previousLetter = string[0]
if len(string)==1:
return str(1) + string[0]
for i in range(1,len(string),1):
if not string[i] == previousLetter:
result += str(counter) + string[i-1]
previousLetter = string[i]
counter = 1
else:
counter += 1
if i == len(string)-1:
result += str(counter) + string[i]
return result
result = encode(string)
print(result)
Output:
1A4B8C1A1B
I have the following code written:
Value = input("LOL")
LetterNum = 1
for Letter in Value :
pass
print("Letter ",LetterNum,"is",Letter)
LetterNum += 1
break
I can't get it to display the numbers corresponding to the letters, all I'm getting is a break outside loop, what is causing that error?
You need to spend some serous time at python tutorial sites or somehow get familiar with the language.
Your code won't work, not even close to what you want it to. I'm assuming this is what you want:
Value = "LOL"
LetterNum = 1
for Letter in Value :
print("Letter ",LetterNum,"is",Letter)
LetterNum += 1
Which will give you:
Letter 1 is L
Letter 2 is O
Letter 3 is L
Indentation, Indentation, Indentation, Indentation...
Understand how variable are assigned (very basic)
No need for break in that code if you already have a pre-set loop (start to end)
Indentation, Indentation, Indentation, Indentation...
I have been learning python through code academy. It asked me to create a if else statement that prints the users input, but if there is no input print "empty". I did pass the tutorial but when there is a user input it prints both the users input and "empty".
here is my code:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len("original")
if length > 0:
print original
else: length < 0
print "empty"
Notice that print under else is not indented. I thought you had to indented it, but when i do it gives me an error.
You seem to have a couple issues with your code. First I believe you should change your assignment of length to:
length = len(original)
That way you get the correct length of the string you binded to the name original. If you use len("original"), you will pass the string "original" to the len() function, and it will just count the characters in that string. Regardless of what the user of your program inputted, your length will always be 8, since that's how many characters are in the string "original"
Also keep in mind that the len() function will never return a negative value. So testing if length < 0 doesn't make sense. You probably wanted to test if it equals 0. It seems as if you were trying to use an elif statement.
Try:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
elif length == 0:
print "empty"
elif statements let you test conditions just like if statements. elif is short for "else if".
Furthermore, as #chepner pointed out in the comments, there is no need to even test the second condition at all. You can just as easily go with:
else:
print "empty"
The else syntax is not followed by any condition. It automatically enters the indented block of code if the other conditions evaluate to False.
Was the length < 0 intended to be a comment? You need the comment character #.
else: # length < 0
print "empty"
It's wrong anyway, it should be length <= 0.
Without a comment character it was being interpreted as the statement to use as the else clause. It didn't create an error since length < 0 just generates a boolean result that you didn't do anything with, but it prevented you from having another statement as part of the else.
else: length < 0
print "empty"
should be
elif length == 0:
print "empty"
Python has significant whitespace, things that are indented the same are in the same scope.
First off, it is not len("original") it is len(original). If you use quotes you are making it a constant value, "original", rather than a variable named original.
Second, instead of checking the length of the string you should use this
if original:
# Type here what happens if the string is not empty
else:
# Here what happens if the string is empty
By Python standard any collection, including strings, equals false if it is empty(aka contains no elements) and true if it contains any elements.
There is a a statement after else.
else: length < 0
print "empty"
Maybe you are looking for an (elif is another way to check another condition after the if if the previous if fails.)
elif length <= 0:
or just a plain
else:
print "empty"
it will never go past zero anyways you could have a == conditional for zero and it would work.
elif length == 0:
this is probably the best way there is no need to check another condition.
if length > 0:
print original
else:
print "empty"
also just a side note length = len("original")
there is not suppose to be quotation marks around original because its a variable :). You will just be getting the string "original" not the actual stuff inside of the variable.
The end result ..
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
else:
print "empty"
To check if there is an item in a list, simply do this:
if List_name:
{code here}
...
So, your code should very simply look like this:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
if original:
print original
else:
print "Empty"
It's that easy :D