Is there a problem with my string replacement code? - python

string = input()
for i in range(len(string)):
if i % 3 == 0:
final = string.replace(string[i], "")
print(final)
I was asked the question: "Given a string, delete all its characters whose indices are divisible by 3."
The answer for the input Python is yton. However, my code gives Pyton.
The code makes sense to me but I'm a beginner. Any help?

The problem is that while you are looping, you are overriding the final variable every time the index is divisible by 3.
Instead, try defining the final variable before you start the loop, and add the letters as you loop over them, and only when they their index is NOT divisible by 3 (thus, ignoring the ones where the index IS divisible by 3).
Something like this should work:
string = input()
final = ""
for i in range(len(string)):
if i % 3 != 0:
final += string[i]
print(final)

In your current code, final is used through each iteration of the loop. It continues updating by replacing one character. In each iteration, final is replaced by a different string with one letter from string removed. After the loop has completed, it effectively only replaced one letter, which in this case is "h".
Use this instead (thanks to Mateen Ulhaq for the idea):
print("".join(x for i, x in enumerate(input()) if i % 3 != 0))

string=input()
final=""
for i in range(len(string)):
if i % 3 != 0:
final+=string[i]
print(final)
In your code, the line final = string.replace(string[i], "") would run like this.
Supposing the input is "hellobaby":
i=0, final="ellobaby"
i=3, final="helobaby"
i=6, final="hellobby"

Related

python showing string index out of range

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2
My Code
def count_code(str):
count=0
for n in range(len(str)):
if str[n:n+2]=='co' and str[n+3]=='e':
count+=1
return count
I know the right code (just adding len(str)-3 at line 3 will work) but I'm not able to understand why str[n:n+2] works without '-3' and str[n+3]
Can someone clear my doubt regarding this ?
Say our str was "abcde".
If you didn't have the -3 in the len(str), then we would have an index of n going from 0,1,2,3,4.
str[n+3] with n being 4 would ask python to find the 7th letter of "abcde", and voila, an indexerror.
It is because the for loop will loop through all the string text so that when n is representing the last word. n+1 and n+2does not exist. Which it will tells you that the string index is out of range.
For example: 'aaacodebbb' the index of the last word is 9. So that when the for loop goes to the last word, n=9. But n+1=10 and n+2=11 index does not exist in your word. So that index 10 and 11 is out of range
loop for is an easy way to do that.
def count_code(str):
count = 0
for i in range(len(str)-3):
# -3 is because when i reach the last word, i+1 and i+2
# will be not existing. that give you out of range error.
if str[i:i+2] == 'co' and str[i+3] == 'e':
count +=1
return count

Explain in English how this code iterates over a number

What does this code mean in English? What is actually happening?
[int(n) for n in str(octal)]
It's part of a larger set of code/loop (see below.)
What I understand is that it's taking in a number as the variable input to a function. This part of the code is allowing it to loop over the number. What I need to understand is the specifics of this line of code. int(n), the for loop of n in str(octal). I need to understand it in English so that I can solve the rest of the code issue. (Which I deliberately did not state.) octal is the input variable to the entire function.
for each_number in [int(n) for n in str(octal)]:
print (octal)
print(n)
# Check for each of the permissions values
for value, letter in value_letters:
if value >= value:
print (value, letter)
result += letter
value -= value
print (result)
else:
value -= 1
result += "-"
Print ("else statment", value, letter, result)
print("end of function")
print(" ")
return result
[int(n) for n in str(octal)]
It's a list comprehension. It's usually helpful to read these right-to-left.
str(octal): Cast the variable octal to a string.
for n in str(octal): For every character n in the string:
int(n): Cast the value to an integer.
[...]: Return these results as a list.
So, the full expression returns a list of integers generated by iterating through every character in str(octal) and casting each character as an int.
It's a list comprehension. Let's look at what this code might normally look like:
my_list = []
for n in str(octal):
my_list.append(int(n))
Essentially, the list comprehension condenses this for-loop down into a single line. The statement before the for indicates what will be appended your output list. Then the for section indicates what you're looping over, just like the first line of a regular for-loop.
At a high level, this comprehension is separating the characters (presumably individual numbers) of the variable octal into a list. To do this, it's casting octal into a string so it can iterate over the individual characters, and then converting each character back into an int before putting it into the output list. So if octal = 175 then your output list would be [1, 7, 5]
lst = [int(n) for n in str(octal)]
is the equivalent of:
lst = [] # Define an empty list
# We want every digit of octal, so we need to convert it into a string
for n in str(octal): # For every digit in the octal
lst.append(int(n)) # Add the character converted into an integer to the list
In Python, it's called list comprehension:
You can translate it as:
result = []
for n in str(octal):
result.append(int(n))
So your code above can be written in a procedural way like:
for n in str(octal):
each_number = int(n)
print(octal)
print(n)
# Check for each of the permissions values
for value, letter in value_letters:
if value >= value:
print(value, letter)
result += letter
value -= value
print(result)
else:
value -= 1
result += "-"
print("else statment", value, letter, result)
print("end of function")
print(" ")
return result
Looking at your code I don't see the reason for using list comprehension since 'each_number' is not used anywhere you the code.

Print odd index in same line

I'm trying to complete challenge on HackerRank ( Day 6 : Let's review!) and I only did to print the even numbers on the same line, but I can't print the odd indexes that would be needed to complete the challenge.
This is my code:
word_check = input()
for index, char in enumerate (word_check):
if (index % 2 == 0):
print( char ,end ="" )
This is the most specific task:
Given a string, S , of length N that is indexed from 0 to N -1 , print its even-indexed and odd-indexed characters as space-separated strings on a single line.
Thanks!!!
RavDev
You can use slice notation for indexing the original string:
word_check[::2] + " " + word_check[1::2]
[::2] means "start at the beginning and skip every second element until we reach the end" and [1::2] means "start at the second element and skip every second element until we reach the end". Leaving out either start or stop arguments of the slice implies beginning or end of the sequence respectively. Leaving out the step argument implies a step size of 1.
Slice notation is a better approach, but if you want to use for loop and stick to your approach, you can do in this way:
even =''
odd=''
for index, char in enumerate (word_check):
if (index % 2 == 0):
even += char
else: odd += char
print (even, odd)
I am currently trying to solve the same problem. To get your answers on the same line, initiate two strings: one for even and one for odd. If the character's index is even, add it to the even string and vice versa. Here is my working code so far:
def indexes(word,letter):
result = list()
for i,x in enumerate(word):
if x == letter:
result.append(i)
return result
T = int(input())
if T <= 10 and T>= 1:
for i in range(T):
evenstring = ""
oddstring = ""
lastchar = False
S = input()
if len(S) >= 2 and len(S) <= 10000:
for index, char in enumerate (S):
if (index % 2 == 0):
evenstring += char
else: oddstring += char
if len(indexes(S, char)) > 1:
evenstring.replace(evenstring[evenstring.rfind(char)], '')
oddstring.replace(oddstring[oddstring.rfind(char)], '')
print(evenstring, oddstring)
Your next problem now is trying to remove any reoccurrences of duplicate letters from your final answer (they show up in other test cases)

Finding first digit index in Python loop?

found = False
position = 0
while not found and position < len(inputString):
if inputString[position].isdigit():
found = True
else:
position += 1
if found:
print('first digit is at position', position)
else:
print('There are no digits in the string')
This is a simple program I found that deals with finding the first digit in an inputted string. Something I am having trouble understanding is...
if inputString[position].isdigit():
found = True
What exactly does this expression state, specifically the inputString[position] part. Are we looking for the position/index value of the first digit and then breaking the loop into the print statement below?
Are we looking for the position/index value of the first digit and
then breaking the loop into the print statement below?
Yes, that's true. It breaks because once a digit is found, in the next iteration while not found condition will give while False and break the while loop. Worth noting and short-circuits, so the second condition is not even evaluated.
If a digit is not found, position increments until it is equal to len(inputString), at which point the while loop breaks via the second condition, i.e. position < len(inputString).
A more Pythonic / idiomiatic way to write your while loop is via for loop and enumerate:
for idx, val in enumerate(inputString, 1):
if val.isdigit():
position = idx
break
else:
position = 0
if position:
print('first digit is at position', position)
else:
print('There are no digits in the string')
Notice, in this solution, since we start counting from 1, we can take advantage of the fact if a digit is found it must be "Truthy", i.e. non-zero. Therefore, we don't need an extra found variable.
You are looking for the value of inputString at the position, position. position is first initialized as zero, and then it while loops each position (notice position += 1) to see if it .isdigit().
The position is your iteration variable like in a for loop. So every time you don't find a digit you go to the next char in the string.
The inputString[position] reads what stands the position's place in the string. So if your string is abcdefg then inputString[2]= c (not b since python starts counting from 0).
The .isdigit() then looks if at this position is a digit. If it is a digit, then found = True and the while loop is stopped. (Else it continues.)
After the loop ends, the function prints one of the two messages depending on if there was a digit in the inputString.
inputString[position] gives the character at position in inputString. For example, if inputString = "Foobar" and position = 3, inputString[position] = "b".
When we find a digit this way, then found turns True, and the evaluation condition of the while becomes False. The program leaves the loop and prints.
A string in python can be used as an sequence, which means you can use an index to access its elements. For example:
"Victor"[0] is V.
So in your example you are retrieving one of the elements (characters) of the string. The function isdigit() is a string method which can check if that character is a digit.
Gather all the indexes of possible digits, if the list is not empty print the 0 index, else if the list is empty print your no digits statement.
lst = [i for i, v in enumerate(s) if v.isdigit()]
if len(lst):
print(f'First digit is at postion {lst[0]}')
else:
print('There are no digits in the string.')

Python : Made code, doesn't know why it works

I made code that reverses a string but I don't know why it works. Would greatly appreciate if someone could help explain in detail.
str = 'hello'
newstr = ''
count = -1
for i in range (len(str)):
newstr += str[count]
count = count - 1
print (newstr)
Execute your script in a Python debugger as follows:
$ python -m pdb script.py
and use (s) and variable names to understand how does it work.
This program works because you are reading the str from the last element to the first. Your count variable points to a given element and decreases its value. In Python, negative indices mean reading from the last element.
stri = 'hello' # Make string stri
newstr = '' # Make string newstr
count = -1 # make int count
for i in range (len(stri)): # setting i to 0,1,2,3,4 -> this is a loop
newstr += stri[count] # Add letter to newstr from last letter to first
count = count - 1 # making count go down
print (newstr) # print "olleh"
Dont use str as variable name, because it's a build in function
It's quite simple if you take it one bite at a time. In python, setting count = -1 means that you want to take the last item in your string ( which can be seen as an array of characters). Your for i in range (len(str)):' means that you are looping based on the length of your string. The line newstr += str[count] will add the last letter of the string to an empty string. ( so if the word was "apple", it would ad an 'e' to newstr ). finally, your count variable will decrement each time the loop is performed, which will allow you reverse your string.
Example:
myStr = "apple"
count = len(myStr) // length is = 5
myStr[count] // this means that it will access the fifth letter
count = count - 1
myStr[count] // now it is accessing the 4th letter

Categories