Python Slicing and conditions - python

I need to write code that can find the middle three characters of a string and print them. If the string is even in length, it would just print the middle two.
If the string is too short, it would print the entire string.
I wrote the following but I get odd results for shorter characters, like the letter "a" for example.
text = input("Type your word: ")
length = len(text)
center = int(length / 2)
print("3 middle letters: ", text[center-1:center+2])
if length % 2 == 0:
print("2 middle letters: ", text[center-1:center+1])
if length <= 1:
print("")
Examples of output:
"a" > too short, print the whole string
"an" > even, return both characters
"can" > odd, return middle three
"cant" > even, return "an"
"canters" > return middle three, "nte"
"cant err" > return middle two, "t "

Looks like you need to review the if statement.
text = input("Type your word: ")
length = len(text)
center = int(length / 2)
if length > 2:
print("3 middle letters: ", text[center-1:center+2])
elif length == 2:
print("2 middle letters: ", text[center-1:center+1])
else:
print("")

text = input("Type your word: ")
length = len(text)
center = length // 2
print(text[center-1:center+1+length % 2])
Note that length // 2 is the same as int(length / 2).

Related

How do you replace multiple identical characters in a string based on their positions?

So i was making a program for hangman and this is it so far,
word = input("Enter a word: ").upper()
blanks = (len(word)*"_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
blanks = blanks[:word.index(letter)] + letter + blanks[word.index(letter)+1:]
print(blanks)
continue
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have", chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
I was just trying the code out so I would give the word to guess myself, but if I ever gave a word with a letter repeated , like "doggo".
If i gave the letter as "o", it would give out "_ O _ _ _ " instead of " _ O _ _ O" even if i guess "o" again.
Is there anyway I can fix this?
This worked for me:
word = input("Enter a word: ").upper()
blanks = (len(word) * "_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
for count, character in enumerate(word):
if letter == character:
blanks = blanks[:count] + letter + blanks[count + 1:]
print(blanks)
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have",
chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
The difference is that instead of making one replacement we iterate over the word to find all the coincidences and make all the necessary replacements of the same letter.
One solution is to use zip and join in a list compression. zip combines two strings pairwise. The list comprehension steps through the pairs of letters from blanks and word and compares them to the letter. join combines the result - a list of letters - back into a string.
word = "hello"
letter = 'o'
blanks = ''.join([(l if l == letter else b) for b, l in zip(blanks, word)])
#'__ll_'
You can use bytearray and memoryview or list:
# bytearray and memoryview
blank = '_' * 5
print(blank)
fill = 'abcde'
ctr = 0
ba = bytearray(blank, 'utf-8')
mv = memoryview(ba)
while ba.count(b'_') > 0:
mv[ctr] = ord(fill[ctr])
ctr += 1
blank = ba.decode()
print(blank)
Output:
_____
abcde
Second approach, list:
blank = '_____'
print(blank)
blank_list = list(blank)
fill = 'abcde'
while blank_list.count('_') > 0:
blank_list[ctr] = fill[ctr]
ctr += 1
blank = ''.join(blank_list)
print(blank)
Output:
_____
abcde

how to check repeating Vowels

I'm pretty new to python and I'm having trouble with my
if then else statements and I only get is "no repeating vowels" which mean my rep_vowel is still returning 0
so the program rules are as follows.
if no vowel appears next to itself (e.g. hello), then print:
no vowel repeats
if exactly one vowel is repeated in sequence at least once (e.g. committee) then print a message that indicates which vowel repeats:
only vowel e repeats
if more than one vowel repeats (e.g. green door) then print:
more than one vowel repeats
ignore upper case - lower case differences: assume all the input is always lowercase
answer = input("Enter a string: ")
rep_vowel = 0
i = 0
length_Answer = len(answer)
next_string = 1
curChar = answer[0+rep_vowel]
for i in range(0,length_Answer):
if answer[0 + i] in ["a","e","i","o","u"]:
i =+ 1
next_string = answer[0+i+i]
if next_string == answer:
rep_vowel =+ 1
if rep_vowel == 0:
print("no repeating vowles")
elif rep_vowel > 1:
print("more than 1 repeating vowels")
else:
print ("the letter "+ str(curChar) +" repeats")
You have a few mistakes so i'll try to address several of them:
You do a lot of [0 + something] indexing, which is useless, since 0 + something always equals to something, so yo should just do indexing with [something]
Changing the value of i with i += 1 is bad because you are already increasing it as part of the loop
All you have to do to find a match is simply match the current letter to the next one, if both are the same and they are also vowels, you've found a match.
You are initializing unnecessary variables such as i = 0 only to have them overridden in the next lines
Adding all of those together:
answer = input("Enter a string: ")
vowels = "aeiou"
repeats = [] # this list will hold all repeats of vowels
for i in range(len(answer) - 1): # i'll explain the -1 part at the end
if answer[i] in vowels and answer[i] == answer[i + 1]:
repeats.append(answer[i])
if len(repeats) == 0:
print("no repeating vowles")
elif len(repeats) > 1:
print("more than 1 repeating vowels")
else:
print("the letter " + repeats[0] + " repeats")
This still doesn't take every possible input into account, but it should get you started on a final solution (or perhaps that's enough). For example, input of teest will give the correct result but the input of teeest doesn't (depends on your definition of correct).
About the len(answer-1) range, that's only to make sure we don't go out of bounds when doing answer[i + 1], so we're stopping on the next to last letter instead.
Firstly, you have to indent your code.
to say if (condition) then do print('hello') you write it this way:
if condition:
print('hello')
Secondly, you are using i =+ 1 which is the same as i=1
I think you meant i +=1 which is i = i+1
Finally, I suggest this code:
answer = input("Enter a string: ")
vowel_repeated_count = 0
length_Answer = len(answer)
i=0
while (i <length_Answer-1):
#we check if it's a vowel
if answer[i] in ["a","e","i","o","u"]:
#we check if it's followed by the same vowel
if answer[i+1] == answer[i]:
#increment the vowel_repeated_count
vowel_repeated_count +=1
#we save the vowel for the display
vowel = answer[i]
#we skip the other same repeated vowels
#example: abceeed, we skip the third e
while (answer[i] == vowel and i < length_Answer-1):
i +=1
#we add this incrementation because we're in a while loop
i +=1
if vowel_repeated_count == 0:
print("no repeating vowles")
elif vowel_repeated_count == 1:
print("the letter "+ str(vowel) +" repeats")
else:
print ("more than 1 repeating vowels")
You have some logical errors. It's time consuming to edit that. You can try this, I have modified your code. Hope it will work for you. I have commented beside every important line.
answer = input("Enter a string: ")
is_found = {} #a dictionary that will hold information about how many times a vowel found,initially all are 0
is_found["a"]=0
is_found["e"] = 0
is_found['i']=0
is_found['o']=0
is_found['u']=0
vowels =["a","e","i","o","u"]
for i in range(0,len(answer)):
if answer[i] in vowels:
is_found[answer[i]] = is_found[answer[i]]+1 # if a vowel found then increase its counter
repeated=0 #let 0 repeated vowel
previously_repeated=False #to trace whether there is a previously repeated character found
curChar=None
for key,value in is_found.items(): #iterate over dictionary
if previously_repeated and value>1: #if a vowel found and previously we have another repeated vowel.
repeated=2
elif previously_repeated==False and value>1: # we don't have previously repeated vowel but current vowel is repeated
curChar=key
previously_repeated=True
repeated=1
if repeated== 0:
print("no repeating vowles")
elif repeated> 1:
print("more than 1 repeating vowels")
else:
print ("the letter "+ str(curChar) +" repeats")
There is no need to increment your counter i. In your for loop, it will increment itself each time it goes through the for loop. Also, you need a variable to keep track of how many times the vowel repeats.
answer = input("Enter a string: ")
rep_vowel = 0
length_Answer = len(answer)
vowelList=["a","e","i","o","u"]
vowelRepeated = []
#this will go from i=0 to length_Answer-1
for i in range(length_Answer):
if (answer[i] in vowelList) and (answer[i+1] in vowelList):
if (answer[i] == answer[i+1]):
vowelRepeated.append(answer[i])
repVowel += 1
if rep_vowel==0:
print("no repeating vowels")
elif rep_vowel==1:
print("only one vowel repeated:")
print(vowelRepeated)
else:
print("multiple vowels repeated:")
print(vowelRepeated)
for such counting, I will prefer to use a dictionary to keep the counting number. Your code has been modified for your reference
answer = input("Enter a string: ")
length_Answer = len(answer)
count = dict()
for i in range(length_Answer):
if answer[i] in ["a","e","i","o","u"]:
if answer[i+1] == answer[i]:
if answer[i] in count:
count[answer[i]] += 1
else:
count[answer[i]] = 1
rep_vowel = len(count)
if rep_vowel == 0:
print("no repeating vowles")
elif rep_vowel > 1:
print("more than 1 repeating vowels")
else:
for k in count:
vowel = k
print("the letter " + vowel + " repeats")
You have a few issues with your solution :
1) You never use curChar, i'm guessing you wanted to enter the next_string value into it after the '==' statement.
2) You compare your next_string to answer, this will always be a false statement.
3) Also no need to use [0+i], [i] is good enough
Basically what you want to do is this flow :
1) Read current char
2) Compare to next char
3) If equal put into a different variable
4) If happens again raise a flag
Optional solution :
vowel_list = ["a","e","i","o","u"]
recuring_vowel_boolean_list = [answer[index]==answer[index+1] and answer[index] in vowel_list for index in range(len(answer)-1)]
if not any(recuring_vowel_boolean_list ):
print("no repeating vowels")
elif (recuring_vowel_boolean_list.count(True) > 1):
print("More then 1 repeating vowels")
else:
print("The letter {} repeats".format(answer[recuring_vowel_boolean_list.index(True)]))

stuck on longest palindrome algorithm in python 2.7

Hey everyone I have been struggling on the longest palindrome algorithm challenge in python 2.7. I am getting close but have a small error I can't figure out. I have the palindrome working, but cannot get longest palindrome to print correct, either gives me a character buffer error or prints 0.
def palindrome(string):
string = "".join(str.split(" ")).lower()
i = 0
while i < len(string):
if string[i] != string[(len(string) - 1) - i]:
return False
i += 1
return True
print palindrome("never odd or even")
def longest_palindrome(string):
best_palindrome = 0
i1 = 0
while i1 < len(string):
length = 1
while (i1 + length) <= len(string):
substring = string.split(i1,length)
if palindrome(substring) and (best_palindrome == 0 or len(substring) > len(best_palindrome)):
best_palindrome = substring
length += 1
i1 += 1
return best_palindrome
print longest_palindrome("abcbd")
From what I understand, your first method was to check if a string is a palindrome or not and your second method is to find the longest palindrome.
The palindrome code that you posted always returned true no matter what the input was because
string = "".join(str.split(" ")).lower()
returns an empty string. I changed this part of your code to
string = string.replace(" ", "").lower()
which I believe gives you the desired effect of removing all spaces and making the string into lowercase.
Next, your second method should be looping through all possible substrings of the inputted string and check if a) its a palindrome and b) if it is longer than the previous largest palindrome.
An example for the string "doloa" would be:
doloa; is palindrome=false;
dolo; is palindrome=false;
dol; is palindrome=false;
do; is palindrome=false;
d; is palindrome=true; is bigger than previous large palindrome=true;
oloa; is palindrome=false;
olo; is palindrome=true; is bigger than previous large palindrome=true;
you would continue this loop for the whole string, and in the end, your variable 'best_palindrome' should contain the largest palindrome.
I fixed your code and I believe this should work (please tell me if this is your desired output).
def palindrome(string):
comb = string.replace(" ", "").lower()
# print(comb)
# print(len(comb))
i = 0
while i < len(comb):
# print(comb[i] + ":" + comb[(len(comb) - 1) - i] + " i: " + str(i) + ", opposite: " + str((len(comb) - 1) - i))
if comb[i] != comb[(len(comb) - 1) - i]:
return False
i += 1
return True
print palindrome("never odd or even")
def longest_palindrome(string):
best_palindrome = ""
i1 = 0
while i1 < len(string):
length = 0
while (i1 + length) <= len(string):
substring = string.replace(" ", "").lower()
substring = substring[i1:len(substring)-length]
#print("Substring: " + str(substring))
if palindrome(substring) and (best_palindrome == "" or len(substring) > len(best_palindrome)):
best_palindrome = substring
length += 1
i1 += 1
return best_palindrome
print longest_palindrome("bgologdds")
Note: I change the name of some of the variables and I also added some print strings for debugging. You can delete those or uncomment them for future debugging.

Python String Handling Functions

Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
I have to create a program where I need to ask a user for a string and then my program must print the length of the string, the number of letters, the number of digits and the number of characters that are not letters.
counter = 0
num = 0
extra = 0
wrd = raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter + 1
print "You have " + str(counter) +" letters in your sentence."
for n in wrd:
if n.isnumeric():
num = num + 1
print "You have " + str(num) + " number(s) in your sentence"
for l in wrd:
extra = extra + 1
print "You have " + str(extra) + " characters that are not letters or numbers."
I got the first two parts figured out albeit I'm stuck on the last...I know its easier to just create one while loop but since I already started, I want to stick with three four loops.
You don't need another function. Since you've already counted the other characters, subtract them from the total:
print "You have", len(wrd) - counter - num, "characters that are not letters or numbers."
Is there a specific function that returns true if characters in the string are special characters (ex: #. #. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
No, but its pretty easy to create your own:
import string
def has_special_chars(s):
return any(c in s for c in string.punctuation)
Test:
>>> has_special_chars("ab#tjhjf$dujhf&")
True
>>> has_special_chars("abtjhjfdujhf")
False
>>>
In your case, you would use it like:
for l in wrd:
if has_special_chars(l)
extra=extra+1
But as #TigerHawkT3 has already beat me to saying, you should simply use len(wrd) - counter - num instead. Its the most canonical and obvious way.
Just to log a generic answer that will apply beyond this context -
import string
def num_special_char(word):
count=0
for i in word:
if i in string.punctuation:
count+=1
return count
print "You have " + str(num_special_char('Vi$vek!')) + " characters that are not letters or numbers."
Output
You have 2 characters that are not letters or numbers.
Use one for loop with if, elif and else:
sentence = raw_input("Please enter a short sentence.")
alpha = num = extra = 0
for character in sentence:
if character.isspace():
pass
elif character.isalpha():
alpha += 1
elif character.isnumeric():
num += 1
else:
extra += 1
print "You have {} letters in your sentence.".format(alpha)
print "You have {} number(s) in your sentence".format(num)
print "You have {} characters that are not letters or numbers.".format(extra)

Appending to the front of for statement output

I have this code;
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
print("")
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output = (chr(letter))
print(output,end='')
choice = 0
Output depending on the string something like this;
rc`rcr
qb_qbq
pa^pap
o`]o`o
n_\n_n
m^[m^m
l]Zl]l
k\Yk\k
j[Xj[j
iZWiZi
hYVhYh
gXUgXg
fWTfWf
eVSeVe
dURdUd
cTQcTc
bSPbSb
aROaRa
`QN`Q`
_PM_P_
^OL^O^
]NK]N]
\MJ\M\
[LI[L[
ZKHZKZ
YJGYJY
Now, I need some text before the output for example;
Decryption string rc`rcr
Decryption string qb_qbq
etc...
I have tried;
print("Decryption",output,end='')
and
print("Decryption"+output,end='')
However this gives me that text in front of every letter.
Please assist if you can, and explanation would also be preferred.
Thanks for your time.
Ben
You want to do something like this:
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
word = ""
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output = (chr(letter))
word = word + output
choice = 0
print("Decryption: "+word)
The problem with what you were trying is that it will print the 'Decrypting:' message for each character not for each word, so you need to build the word before printing it.
You are printing the output letter by letter, so adding print("Decryption"+output,end='') will just add the 'Decryption' part to each printout. I suggest doing a:
print("Decryption" + string, end=' ')
before you start your for loop.
You need to build your output string and then print it after the for loop
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
output_final = None
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output_final += (chr(letter))
choice = 0
print 'Description:', output_final

Categories