Error with expected an indented block, any one know? - python

a = "aabb"
words = list(a)
new_words = []
count = 1
for i in range(0,len(words)-1):
if words[i] == words[i+1]:
count = count + 1
if i+2 == len(words):
print words[i+1],count
else:
print words[i],count
count = 1

You have a file with mixed tabs and spaces and it's confusing you vs the interpreter. Replace all the tab characters in your file with spaces and then correctly indent the program.

Related

Is there any way to split string into array by spaces in another string in Python?

I have two input strings. In the first one - words with spaces. In the second - the word with same count of symbols without spaces. The task is to split the second string into array by spaces in the first one.
I tried to make it with cycles but there is problem of index out of range and i can't find another solution.
a = str(input())
b = str(input())
b_word = str()
b_array = list()
for i in range(len(a)):
if a[i] != " ":
b_word += b[i]
else:
b_array += b_word
b_word = str()
print(b_array)
Input:
>>head eat
>>aaabbbb
Output:
Traceback (most recent call last):
File "main.py", line 29, in <module>
b_word += b[i]
IndexError: string index out of range
Expected output:
>> ["aaab", "bbb"]
Thanks in advance!
Consider a solution based on iterator and itertools.islice method:
import itertools
def split_by_space(s1, s2):
chunks = s1.split()
it = iter(s2) # second string as iterator
return [''.join(itertools.islice(it, len(c))) for c in chunks]
print(split_by_space('head eat or', 'aaaabbbcc')) # ['aaaa', 'bbb', 'cc']
a = input() # you don't need to wrap these in str() since in python3 input always returns a string
b = input()
output = list()
for i in a.split(' '): # split input a by spaces
output.append(b[:len(i)]) # split input b
b = b[len(i):] # update b
print(output)
Output:
['aaab', 'bbb']
You can do something like this:
a = input()
b = input()
splitted_b = []
idx = 0
for word in a.split():
w_len = len(word)
splitted_b.append(b[idx:idx+w_len])
idx += w_len
print(splitted_b)
The idea is taking consecutive sub-strings from b of the length of each word on a.
Instead of using indices, you can iterate over each character of a. If the character is not a space, add the next character of b to your b_word. If it is a space, add b_word to the b_array
b_iter = iter(b) # Create an iterator from b so we can get the next character when needed
b_word = []
b_array = []
for char in a:
# If char is a space, and b_word isn't empty, append it to the result
if char == " " and b_word:
b_array.append("".join(b_word))
b_word = []
else:
b_word.append(next(b_iter)) # Append the next character from b to b_word
if b_word: # If anything left over in b_word, append it to the result
b_array.append("".join(b_word))
Which gives b_array = ['aaab', 'bbb']
Note that I changed b_word to a list that I .append to every time I add a character. This prevents the entire string from being recreated every time you append a character.
Then join all the characters using "".join(b_word) before appending it to b_array.
So to accomodate for any number of spaces in the input it gets a bit more complex as the indexes of the letters will change with each space that is added. So to gather all of the spaces in the string I created this loop which will account of the multiple spaces and alter the index with each new space in the initial word.
indexs = []
new = ''
for i in range(len(a)):
if len(indexs) > 0:
if a[i] == ' ':
indexs.append(i-len(indexs))
else:
if a[i] == ' ':
indexs.append(i)
Then we simple concatenate them together to create a new string that includes spaces at the predetermined indexes.
for i in range(len(b)):
if i in indexs:
print(i)
new += " "
new += b[i]
else:
new += b[i]
print(new)
Hope this helps.
Code
sone = input()
stwo = 'zzzzzxxxyyyyy'
nwz = []
wrd = ''
cnt = 0
idx = 0
spc = sone.split(' ') #split by whitespace
a = [len(i) for i in spc] #list word lengths w/out ws
for i in stwo:
if cnt == a[idx]: #if current iter eq. word length w/out ws
nwz.append(wrd) #append the word
wrd = '' #clear old word
wrd = wrd + i #start new word
idx = idx + 1
cnt = 0
else:
wrd = wrd + i #building word
cnt = cnt + 1
nwz.append(wrd) #append remaining word
print(nwz)
Result
>'split and match'
['zzzzz', 'xxx', 'yyyyy']

Python list index not in order

I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why.
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i in range(len(listJoint)):
if (listJoint.index(listJoint[i]) % 2) == 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].upper())
elif (listJoint.index(listJoint[i]) % 2) != 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].lower())
print(newList2)
#newListJoint = "".join(newList2)
#print(newListJoint[::-1])
Thanks in advance
List index doesn't go 0 1 2 3 4
The function .index() finds the first occurrence of that letter. 'L' occurs at index 2 and 3 so it would return 2 for both L's.
Iterate through each character of the string and alternate upper/lower methods.
sentence = "Hello"
alternated_sentence = ''
for i, char in enumerate(sentence):
if i % 2:
alternated_sentence += char.upper()
else:
alternated_sentence += char.lower()
print(alternated_sentence)
#hElLo
sentence = input("Write a sentence:")
# Remove spaces (as per your question)
sentence = sentence.replace(' ', '')
# Reverse the string order (as per your question)
sentence = sentence[::-1]
result = []
for i in range(len(sentence)):
if(i%2==1):
result.append(sentence[i].lower())
else:
result.append(sentence[i].upper())
print(''.join(result))
Here's the solution. The above code would give output as follows:
Write a sentence: Hello world
DlRoWoLlEh
I never realised index method referenced the first instance of the character. This works:
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i, value in enumerate(newList):
if i % 2 == 0:
newList2.append(listJoint[i].upper())
elif i % 2 !=0:
newList2.append(listJoint[i].lower())
newListJoint = "".join(newList2)
print(newListJoint[::-1])

My code when run prints the output before it. I want it to print only what is required of that specific count number

Why does my code print the output before in the while loop. I want to print only the count # and the encrypted text for that count #.
put list_text2 inside your loop.
while count < 26:
list_text2 = []
for letter in list_text1:
I'm assuming that you're appending to list_test2 each time for a reason, so rather than sticking it outside of the loop, the following code should just slice the latest update off of the tail end of it, and print just that part only:
import string
text_to_encrypt = ('Please enter some text to encrypt: ')
offset = list(range(1,27))
alphabet = list(string.ascii_lowercase)
list_text2 = []
encrypted_text = ''
list_text1 = list(text_to_encrypt.lower())
adjusted_list = 2*alphabet
count = 1
while count < 26:
for letter in list_text1:
if letter not in alphabet:
list_text2 += letter
else:
index = adjusted_list.index(letter)
list_text2 += adjusted_list[index + offset[count]]
list_text2_len = len(list_text2)
slice_start_index = list_text2_len - len(text_to_encrypt)
print(''.join(list_text2[slice_start_index:list_text2_len]))
encrypted_text = ''.join(list_text2)
count += 1

How can I capitalize a character with an odd-numbered index in a string?

So I was doing our exercise when I came across capitalizing characters in odd indices. I tried this:
for i in word:
if i % 2 != 0:
word[i] = word[i].capitalize()
else:
word[i] = word[i]
However, it ends up showing an error saying that not all strings can be converted. Can you help me debug this code snippet?
The problem is strings in python are immutable and you cannot change individual characters. Apart fro that when you iterate through a string you iterate over the characters and not the indices. So you need to use a different approach
A work around is
(using enumerate)
for i,v in enumerate(word):
if i % 2 != 0:
word2+= v.upper()
# Can be word2+=v.capitalize() in your case
# only as your text is only one character long.
else:
word2+= v
Using lists
wordlist = list(word)
for i,v in enumerate(wordlist):
if i % 2 != 0:
wordlist[i]= v.upper()
# Can be wordlist[i]=v.capitalize() in your case
# only as your text is only one character long.
word2 = "".join(wordlist)
A short note on capitalize and upper.
From the docs capitalize
Return a copy of the string with its first character capitalized and the rest lowercased.
So you need to use upper instead.
Return a copy of the string with all the cased characters converted to uppercase.
But in your case both work accurately. Or as Padraic puts it across "there is pretty much no difference in this example efficiency or output wise"
You need enumerate and capitalise any character at any odd i where i is the index of each char in the word:
word = "foobar"
print("".join( ch.upper() if i % 2 else ch for i, ch in enumerate(word)))
fOoBaR
ch.upper() if i % 2 else ch is a conditional expression where we change the char if the condition is True or else leave as is.
You cannot i % 2 when i is the actual character from the string, you would need to use range in your code or use enumerate and concatenate the changed characters to an output string or make words a list.
Using a list you can use assignment:
word = "foobar"
word = list(word)
for i, ele in enumerate(word):
if i % 2:
word[i] = ele.upper()
print("".join(word))
Using an output string:
word = "foobar"
out = ""
for i, ele in enumerate(word):
if i % 2:
out += ele.upper()
else:
out += ele
if i % 2: is the same as writing if i % 2 != 0.
This is how I would change word letters in a word or a sentence to uppercase
word = "tester"
letter_count = 1
new_word = []
for ch in word:
if not letter_count % 2 == 0:
new_word.append(ch.upper())
else:
new_word.append(ch)
letter_count += 1
print "".join(new_word)
if I wanted to change odd words in a sentence to uppercase I would do this
sentence = "this is a how we change odd words to uppercase"
sentence_count = 1
new_sentence = []
for word in sentence.split():
if not sentence_count % 2 == 0:
new_sentence.append(word.title() + " ")
else:
new_sentence.append(word + " ")
sentence_count += 1
print "".join(new_sentence)
I think it will help...
s = input("enter a string : ")
for i in range(0,len(s)):
if(i%2!=0):
s = s.replace(s[i],s[i].upper())
print(s)

Python - I read a file but it shows me erroneous values?

def showCounts(fileName):
lineCount = 0
wordCount = 0
numCount = 0
comCount = 0
dotCount = 0
with open(fileName, 'r') as f:
for line in f:
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
comCount+=1
#i know formatting below looks off but it's right
words = line.split()
lineCount += 1
wordCount += len(words)
for word in words:
# text = word.translate(string.punctuation)
exclude = set(string.punctuation)
text = ""
text = ''.join(ch for ch in text if ch not in exclude)
try:
if int(text) >= 0 or int(text) < 0:
numCount += 1
except ValueError:
pass
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
print("Number count: " + str(numCount))
print("Comma count: " + str(comCount))
print("Dot count: " + str(dotCount) + "\n")
I have it read a .txt file containing words, lines, dots, commas, and numbers. It will give me the correct number of dots commas and numbers, but the words and lines values will be each much much higher than they actually are. Any one know why? Thanks guys.
I don't know if this is actually the answer, but my reputation isn't high enough to comment, so I'm putting it here. You obviously don't need to accept it as the final answer if it doesn't solve the issue.
So, I think it might have something to do with the fact that all of your print statements are actually outside of the showCounts() function. Try indenting the print statements.
I hope this helps.

Categories