What happens in this while loop in python - python-3.x

So I learnt the second course of python on edx and here is a code I wrote but don't really understand the part in the while loop. Could someone explain to me like I'm 6 years old what happens there?
Code:
# [ ] Print each word in the quote on a new line
quote = "they stumble who run fast"
start = 0
space_index = quote.find(" ")
while space_index != -1: #the code in while needs to be explained to me
print(quote[start:space_index])
start = space_index +1
space_index = quote.find(" ", space_index +1)

Your code attempts to demonstrate how to retrieve a sub-string from a string by index in Python, using a while loop having as stop condition that index.
The Python documentation on the function find() of string is here. Quoting from it:
The steps are these:
How to retrieve the index of the first occurrence of a given character in the string quote. In this line: quote.find(" "), it returns the index of the first position of a whitespace. So space_index will be equal to 4 when the while loop begins.
How to retrieve a sub-string from the string. In this line: quote[start:space_index] if you translate the variables start and space_index, what you have is: quote[0,4] which is equal to "they" in the first iteration.
How to increment the index. At the end of the while, you again do quote.find(" ", space_index +1) trying to get the index of a whitespace " ". But this time the position you start to search from is space_index+1 which on the first iteration will be 5. The function quote.find will return the value 12.
So in the 2nd iteration of the while: you'll be trying to get the sub-string quote[start:space_index] or substituting the values: quote[5:12] which will be the second word "stumble".
You should try to learn how to use a debugger of the IDE you are using, or try to print all intermediate values so you can see them.

The code basically prints each word separated by space line-by-line.
Commented Snippet:
# [ ] Print each word in the quote on a new line
quote = "they stumble who run fast"
start = 0 ## index of first character
space_index = quote.find(" ")
while space_index != -1: #the code in while needs to be explained to me
print(quote[start:space_index]) ## print characters from start index to space character
start = space_index +1 ## shift the start index to just after the up-coming space character
space_index = quote.find(" ", space_index +1) ## find the index of the next space character

Related

code for finding longest substring without repeating characters not working

I have written the following code for finding the length of the longest substring without repeating characters below, but it doesn't work - would anyone know why? (I know there are other solutions on the internet that work but the following code is written in my style and I'd ideally like to adapt it)
def longestSubstring(str):
start = 0
maxLen = 1
hashSet = set()
for i in range(len(str)):
if str[i] not in hashSet:
hashSet.add(str[i])
maxLen = max(maxLen, i - start + 1)
continue
else:
while str[start] != str[i]:
hashSet.discard(str[start])
start += 1
hashSet.discard(str[start])
start += 1
return maxLen
It is just one line, remove the 2nd hashSet.discard(str[start]) you don't want to remove this character from the set, you just need to increase start, it is the character you just encountered.

need to use a 'for loop' for this one. The user has to enter a sentence and any spaces must be replaced with "%"

the input
sentence = input("Please enter a sentence:")
the for loop (incorrect here)
for i in sentence:
print(sentence)
space_loc = sentence.index(" ")
for c in sentence:
print(space_loc)
for b in range(space_loc):
print("%")
confused about how to get the answer out.
You can try using concatenation of strings and slicing in this one.
sentence = input()
After taking the input simply store the length of your string
length = len(sentence)
Then iterate through every characters in the string and when you find a " ", break the string into two halves using slicing such that each half has one side of the string from " ". And then, join it by a "%" :-
for i in range(length):
if sentence[i]==" ":
sentence = sentence[:i] + "%" + sentence[i+1:]
Here, sentence[:i] is the part of string before the space and sentence[i+1:] is the part of string after the space.
One way of solving your query:
Code
sentence = input("Please enter a sentence:")
ls=sentence.split() #Creating a list of words present in sentence
new_sentence='%'.join(ls) #Joining the list with '%'
print(new_sentence)
Output
Please enter a sentence:Hello there coders!
Hello%there%coders!
EDIT
I do not understand how exactly you want to use the for loop here. If you just want to include a for loop (no restrictions), then you can do this:
Code
ls=[]
a=0
sentence = input("Please enter a sentence:")
for i in range(0,len(sentence)): # This loop will find the words in the sentence and store them in a list. Words are determined by checking the white space. Each space is replaced with '%'
if sentence[i]==' ':
ls.append(sentence[a:i])
a=i
ls.append('%')
ls.append(sentence[a:]) # This is to save the last word
ls1=[]
for i in ls: # Removing any white space inside the list
j=i.replace(' ','')
ls1.append(j)
print(''.join(ls1)) # Displaying final output
Again, your question is very open ended and this is just one way of using for loop to get the desired result!

End in for loop Python

I want to print a string with the same character repeated once right after it. For example, if the input is "hello", the program would output "hheelllloo". The code
for i in "hello":
print(i, end=i)
works, but I suppose I just do not understand it. I would expect this to give the same output as:
for i in "hello":
print(i + i)
Could anyone explain how the top code works?
The default value of end is a newline. So the second option is equivalent to:
for i in "hello":
print(i + i, end='\n')
You could do something like the second one with
for i in "hello":
print(i + i, end='')
since this explicitly sets end to the empty string so it won't print anything extra.
print(x) will append a newline character to the end of the string it prints.
One way to get rid of that is by setting end='' to have it append an empty string (equivalent to not appending anything at all) instead:
for i in "hello":
print(i + i, end='')
The other answers get to this point kind of circuitously, but the basic idea is that the default value for "end" is a newline, so each time you run through the loop it will print a newline and each successive iteration gets printed on a new line. By changing end to "end=i" or "i+i, end=''", you override this default and print each run of the loop on the same line.

Max Length Removal

The problem is If there is “100” as a sub-string in the string, then we can delete this sub-string. The task is to find the length of longest sub-string which can be make removed?
s=input('')
i=0
if '100' not in s:
print('0')
else:
st=''
while i<len(s)-2:
if s[i:i+3]=='100':
s= s.replace('100','')
a=s.find('100')
if a<=i:
st=st+'100'
i=a
else:
st='100'
i=i+1
else:
i=i+1
print(len(st))
for the input: 101001010000,this code is printing 9 instead of 12,
somehow the else part is not getting executed..
please someone help me out
s.replace() removes all occurrences of the substring, not just the first, and searching from the start.
This means that '101001010000'.replace('100', '') replaces two occurrences:
>>> '101001010000'.replace('100', '')
'101000'
but you count that as one replacement.
str.replace() takes a third argument, the number of replacements to be made, see the documentation:
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Use that to limit the number of replacements.

Get only one word from line

How can I take only one word from a line in file and save it in some string variable?
For example my file has line "this, line, is, super" and I want to save only first word ("this") in variable word. I tried to read it character by character until I got on "," but I when I check it I got an error "Argument of type 'int' is not iterable". How can I make this?
line = file.readline() # reading "this, line, is, super"
if "," in len(line): # checking, if it contains ','
for i in line:
if "," not in line[i]: # while character is not ',' -> this is where I get error
word += line[i] # add it to my string
You can do it like this, using split():
line = file.readline()
if "," in line:
split_line = line.split(",")
first_word = split_line[0]
print(first_word)
split() will create a list where each element is, in your case, a word. Commas will not be included.
At a glance, you are on the right track but there are a few things wrong that you can decipher if you always consider what data type is being stored where. For instance, your conditional 'if "," in len(line)' doesn't make sense, because it translates to 'if "," in 21'. Secondly, you iterate over each character in line, but your value for i is not what you think. You want the index of the character at that point in your for loop, to check if "," is there, but line[i] is not something like line[0], as you would imagine, it is actually line['t']. It is easy to assume that i is always an integer or index in your string, but what you want is a range of integer values, equal to the length of the line, to iterate through, and to find the associated character at each index. I have reformatted your code to work the way you intended, returning word = "this", with these clarifications in mind. I hope you find this instructional (there are shorter ways and built-in methods to do this, but understanding indices is crucial in programming). Assuming line is the string "this, line, is, super":
if "," in line: # checking that the string, not the number 21, has a comma
for i in range(0, len(line)): # for each character in the range 0 -> 21
if line[i] != ",": # e.g. if line[0] does not equal comma
word += line[i] # add character to your string
else:
break # break out of loop when encounter first comma, thus storing only first word

Resources