Why does this code not print the characters backwards - python

def anti_vowel(text):
p=''
for c in text:
if c=='a' or c=='A':
break
elif c=='e' or c=='E':
break
elif c=='i' or c=='I':
break
elif c=='o' or c=='O':
break
elif c=='u' or c=='U':
break
else:
p=p+c
print(anti_vowel('Hello you'))

You forgot to return p at the end of your function:
def anti_vowel(text):
p=''
for c in text:
if c=='a' or c=='A':
break
elif c=='e' or c=='E':
break
elif c=='i' or c=='I':
break
elif c=='o' or c=='O':
break
elif c=='u' or c=='U':
break
else:
p=p+c
return p
Without that last line all you'll ever print is None, the default return value for functions without an explicit return statement.
Of course, your function will only ever print the first consonants, as break ends the loop as soon as you find any vowels. It'll not reverse the string, ever. For your sample input, the function return 'H', because the next letter in the input is a vowel, and break then ends the loop.
You could easily re-write your function to use str.lower() and a containment test:
def anti_vowel(text):
p = ''
for c in text:
if c.lower() in 'aeiou':
break
p += c
return p
This does the same thing, return the first consonants ('H' for your sample input).
If you wanted to reverse letters, and exclude vowels, don't use break and invert where you place the remaining letters. You could use continue instead, or more simply, just invert the if test and only process a chararter if it is not a vowel:
def anti_vowel(text):
p = ''
for c in text:
if c.lower() not in 'aeiou':
p = c + p
return p
Now consonants are placed before any preceding consonants, reversing the text:
>>> def anti_vowel(text):
... p = ''
... for c in text:
... if c.lower() not in 'aeiou':
... p = c + p
... return p
...
>>> anti_vowel('Hello you')
'y llH'

Related

How do I stop this from exiting after the first iteration?

I'm trying to return a statement that replaces given old characters with new characters, but the loop keeps exiting after the first iteration.
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
while (ch == old_ch):
newstring += new_ch
break
while (ch != old_ch):
newstring += ch
break
return newstring
I know that there are already defined replace functions in python, but this is the way I've been told to do it. (same with the for ch in s bits)
There are two things you need to change.
Instead of using a while-loop and breaking, just use an if-statement. Your code will still work the same way, but it'll be much more readable.
Move the return statement outside of the for-loop, i.e. unindent it. This way newstring won't be returned until the entire for-loop has been executed, which is the desired behavior.
The full corrected code is below:
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
if (ch == old_ch):
newstring += new_ch
else:
newstring += ch
return newstring
print(test("Megalovania", "a", "o"))
# Prints Megolovonio
for ch in s statement is used to loop over every character of the string.
Hence the while loop inside the for loop is not required.
def test(s, old_ch, new_ch):
"""returns the given input and replaces an old character with a new character"""
newstring = ""
for ch in s:
if(ch == old_ch):
newstring = newstring+new_ch
if(ch != old_ch):
newstring = newstring + ch
return newstring
This code does the intended work you want to achieve.
Try this, so that you will get a better understanding of the iteration.
def test(s, old_ch, new_ch):
newstring = ""
for ch in s:
print(f"ch is {ch}")
if (ch == old_ch):
print(f"if condition is True for ch {ch} and old_ch {old_ch}")
newstring += new_ch
else:
print(f"elif condition is True for ch {ch} and old_ch {old_ch}")
newstring += ch
print(newstring)
return newstring
call this function
test("New to Python", "t", "y")
Output is
ch is N
elif condition is True for ch N and old_ch t
ch is e
elif condition is True for ch e and old_ch t
ch is w
elif condition is True for ch w and old_ch t
ch is
elif condition is True for ch and old_ch t
ch is t
if condition is True for ch t and old_ch t
ch is o
elif condition is True for ch o and old_ch t
ch is
elif condition is True for ch and old_ch t
ch is P
elif condition is True for ch P and old_ch t
ch is y
elif condition is True for ch y and old_ch t
ch is t
if condition is True for ch t and old_ch t
ch is h
elif condition is True for ch h and old_ch t
ch is o
elif condition is True for ch o and old_ch t
ch is n
elif condition is True for ch n and old_ch t

printing out or returning strings between brackets

I'm trying to write a function in similar manner as started, so that I will get what it's doing. I'm assuming this can be done with one line of code, with some fancy functions, but for the sake of practice and understanding I'm trying to come up with similar solution.
The task is the following: the function takes a text once it encounters enclosed square brackets [ word ] It should print out or return all words which are between square brackets. For example, if the text string would be "[a]n example[ string]", you are expected to print out "a string".
def string():
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
for j in range(len(text)):
if text[j] == '[':
new = text.find(']')
return(text[j+1:new])
print(string())
Try this:
def extract(text, skip_chars=("\n", )):
output = ""
flag = False
for c in text:
if c == "]":
flag = False
if flag and not c in skip_chars:
output += c
if c == "[":
flag = True
return output
print(extract("""[a]n example[
stri
ng]"""))
# -> "a string"
def string():
result = []
text = "some random text [and I need this bit of txt] but I don't know how to continue [to get this bit as well]"
for i in text:
if i == '[':
new = text.find(']')
result.append(text[text.index(i) + 1:new])
return " ".join(result)
print(string())
def parse(source):
i = source.index("[") # throw an exception
result = ""
while i < len(source):
if s[i] == "[":
i += 1
while i < len(source):
temp = ""
if source[i] == "]":
result += temp
break;
temp += source[i]
i += 1
i += 1
return result

Pig latin translator not handling vowel 'a'

Pig latin translator not working properly .Not showing output for vowel 'a'.
example: input: va
the output is an error showing reference error.
working properly for all other vowels except 'a'.
UnboundLocalError: local variable 'list3' referenced before assignment.
import string
def translate(str1):
str2="eaiouy"
list2=[]
punstr=""
for c in str1:
if c in string.punctuation:
punstr=punstr+c
for c in string.punctuation:
str1= str1.replace(c,"")
if str1.isdigit():
return str1+punstr
else:
if (len(str1)==1):
if str1[0] in str2:
return str1+"yay"+punstr
else:
return str1+"ay"+punstr
elif str1[0] in str2:
return str1+"yay"+punstr
else:
for i in str2:
list1=str1.split(i)
if (len(list1[0])<len(list2)):
list3=list1[0]
list2=list1[0]
prestr=str(list3)
stem=str1.split(list3)
reqstem=stem[1]
return reqstem+prestr+"ay"+punstr
while True:
str1=raw_input("\nenter the sentance")
sentlist=str1.split(" ")
for i in range(len(sentlist)):
mystr=sentlist[i]
if i==0:
reqstring=translate(mystr)
print reqstring.capitalize(),
else:
reqstring=translate(mystr)
print reqstring,
list3 is only assigned to when len(list1[0]<len(list2), which means sometimes it isn't set, and that's when prestr=str(list3) will give you trouble.
working now!!!
import string
def translate(str1):
vowel=" eaiouy"
list2=[]
punstr=""
for c in str1:
if c in string.punctuation:
punstr=punstr+c
for c in string.punctuation:
str1= str1.replace(c,"")
if str1.isdigit():
return str1+punstr
else:
if (len(str1)==1):
if str1[0] in vowel:
return str1+"yay"+punstr
else:
return str1+"ay"+punstr
elif str1[0] in vowel:
return str1+"yay"+punstr
else:
for i in str1:
if i in vowel:
list1=str1.split(i)
print list1
break
prestr=str(list1[0])
stem=str1.split(prestr)
reqstem=stem[1]
return reqstem+prestr+"ay"+punstr
while True:
str1=raw_input("\nenter the sentance")
sentlist=str1.split(" ")
for i in range(len(sentlist)):
mystr=sentlist[i]
if i==0:
reqstring=translate(mystr)
print reqstring.capitalize(),
else:
reqstring=translate(mystr)
print reqstring,

Translating sentences into pig latin

SO i have this assignment to translate multiple words into pig latin. assume that the user will always input lowercase and only letters and spaces.
#----------------global variables
sentence = input("What do you want to translate into piglattin? ")
sentence = list(sentence)
sentence.insert(0, ' ')
length = len(sentence)
sentence.append(' ')
pigLattin = sentence
false = 0
true = 1
consonant = []
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
j = 0
x = 0
y = 0
#----------------main functions
def testSpace(sentence, i):
if sentence[i] == ' ':
a = true
else:
a = false
return a
def testVowel(sentence, i):
if sentence[i] == 'a' or sentence[i] == 'e' or sentence[i] == 'i' or sentence[i] == 'o' or sentence[i] == 'u' or sentence[i] == 'y':
b = true
else:
b = false
return b
def testStartWord(sentence, i):
x = 0
if sentence[i].isalpha() and sentence[i-1] == ' ':
c = true
x = 1
if x == 1 and sentence[i] != 'a' and sentence[i] != 'e' and sentence[i] != 'i' and sentence[i] != 'o' and sentence[i] != 'u' and sentence[i] != 'y':
c = true
else:
c = false
return c
def testWordEnd(sentence, i):
if sentence[i].isalpha() and sentence[i+1] == ' ':
d = true
else:
d = false
return d
#----------------main loop
for i in range(1,length):
x = 0
space = testSpace(sentence, i)
vowel = testVowel(sentence, i)
word = testStartWord(sentence, i)
end = testWordEnd(sentence, i)
if vowel == false and space == false and word == true:
e = i
consonant.append(sentence[i])
pigLattin.pop(e)
f = f + 1
if end == true:
consonant.append('a')
consonant.append('y')
consLength = len(consonant)
for x in range(consLength):
y = i + j - f
pigLattin.insert(y,consonant[x])
j = j + 1
del consonant[:]
pigLength = len(pigLattin)
for b in range (pigLength):
print(pigLattin[b], end='')
this is what i have so far. it gets kinda messy when trying to remove items. im sort of stuck here and its not working.
OK i got it working now this is an updated version
sentence = input("Please enter a sentence: ")
vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")
words = sentence.split()
count = 0
def find_vowel(word):
for i in range(len(word)):
if word[i] in vowels:
return i
return -1
for word in words:
vowel = find_vowel(word)
if(vowel == -1):
print(word, ' ', end='')
elif(vowel == 0):
print(word + "ay", ' ', end='')
else:
print(word[vowel:] + word[:vowel] + "ay", ' ', end='')
Instead of using testSpace eliminate the spaces by using sentence = sentence.split(). This will split all your words into strings in a list. Then iterate through the words in your list.
Instead of using testStartWord, use an if statement:
for word in sentence:
if word[0] in ["a","e","i","o","u"]:
word[:(len(word)-1)] = word[0]
#More Code...
At the end, where you print the output, use print sentence.join()
Here's an alternate version. I use a regular expression to find words in the input string, pass them to a callback function, and substitute them back into the original string. This allows me to preserve numbers, spacing and punctuation:
import re
import sys
# Python 2/3 compatibility shim
inp = input if sys.hexversion >= 0x3000000 else raw_input
VOWELS = set('aeiouyAEIOUY')
YS = set('yY')
def pig_word(word):
"""
Given a word, convert it to Pig Latin
"""
if hasattr(word, 'group'):
# pull the text out of a regex match object
word = word.group()
# find the first vowel and what it is
vowel, where = None, None
for i,ch in enumerate(word):
if ch in VOWELS:
vowel, where = ch, i
break
if vowel is None:
# No vowels found
return word
elif where == 0 and vowel not in YS:
# Starts with a vowel - end in 'way'
# (leading y is treated as a consonant)
return word + 'way'
else:
# Starts with consonants - move to end and follow with 'ay'
# check capitalization
uppercase = word.isupper() and len(word) > 1
titlecase = word[:1].isupper() and not uppercase
# rearrange word
word = word[where:] + word[:where] + 'ay'
# repair capitalization
if uppercase:
word = word.upper()
elif titlecase:
# don't use str.title() because it screws up words with apostrophes
word = word[:1].upper() + word[1:].lower()
return word
def pig_latin(s, reg=re.compile('[a-z\']+', re.IGNORECASE)):
"""
Translate a sentence into Pig Latin
"""
# find each word in the sentence, pass it to pig_word, and insert the result back into the string
return reg.sub(pig_word, s)
def main():
while True:
s = inp('Enter a sentence to translate (or Enter to quit): ')
if s.strip():
print(pig_latin(s))
print('')
else:
break
if __name__=="__main__":
main()
then
Enter a sentence to translate (or Enter to quit):
>>> Hey, this is really COOL! Let's try it 3 or 4 times...
Eyhay, isthay isway eallyray OOLCAY! Et'slay ytray itway 3 orway 4 imestay...

Capitalise and ignore comma

I have this code:
def reverse (word):
newword = ''
letterflag = -1
for numletter in word:
newword += word[letterflag]
letterflag-=1
s=newword
s.upper()
return newword
def isPalindrome(word, ignorecase=False):
"""
>>> type(isPalindrome("bob"))
<type 'bool'>
>>> isPalindrome("abc")
False
>>> isPalindrome("bob")
True
>>> isPalindrome("a man a plan a canal, panama")
True
>>> isPalindrome("A man a plan a canal, Panama")
False
>>> isPalindrome("A man a plan a canal, Panama", ignorecase=True)
True
"""
word = str (word)
newword = reverse(word)
if word == newword:
return True
else:
return False
When I type "Bob", I want it to return true because of the capital B.
Just make your input always lower case that way you can avoid that problem altogether.
word = str(word)
word = word.lower()
word = word.replace(',', '') # removes any commas from the string
newword = word[::-1] # reverse string
if word == newword:
return True
else:
return False
The best way to learn what is being done in this answer is to try individual parts of it in the Python console.
To fix your reverse() do this:
def reverse (word):
newword = ''
letterflag = -1
for numletter in word:
newword += word[letterflag]
letterflag-=1
return newword
Notice I also took out the .upper() parts since they are not effective and reverse is not the correct place to have it since you can not compare a reversed upper case word with the original word. Also s.upper() does not work like you think it does. It returns an upper case copy of s without modifying s. You would only to do return newword.upper() to make it work.
Additionally, the letterflag is not needed, you could simply do:
def reverse (word):
newword = ''
for letter in word:
newword = letter + newword #adds each new letter to beginning
return newword
However the simplest way to do a reverse functions is:
def reverse (word):
return word[::-1]
Your isPalendrome needs to be this to basically work:
def isPalindrome(word, ignorecase=False):
word = word.replace(',', '').replace(' ', '') #removes ,'s and spaces
if ignorecase:
return word.lower() == reverse(word).lower()
else:
return word == reverse(word)
Here is a more advanced solution that will ignore anything that is not a letter with an option to ignore case. This version does need reverse.
def isPalindrome(word, ignorecase=False):
abcs = 'abcdefghijklmnopqrstuvwxyz'
word = [c for c in word.lower()*ignorecase or word if c in abcs]
return word == word[::-1] #no need for reverse
If you want to have the option to be case sensitive, or the option to be case insensitive, add an IF statement in the isPalindrome() function:
if ignorecase == True:
word = word.lower()
It should look like this when you are done:
import string
def reverse (word):
newword = ''
letterflag = -1
for numletter in word:
newword += word[letterflag]
letterflag-=1
s=newword
s.upper()
return newword
def isPalindrome(word, ignorecase=False):
"""
>>> type(isPalindrome("bob"))
<type 'bool'>
>>> isPalindrome("abc")
False
>>> isPalindrome("bob")
True
>>> isPalindrome("a man a plan a canal, panama")
True
>>> isPalindrome("A man a plan a canal, Panama")
False
>>> isPalindrome("A man a plan a canal, Panama", ignorecase=True)
True
"""
if ignorecase == True:
word = word.lower()
word = word.replace(',', '')
word = word.replace(' ', '')
newword = reverse(word)
if word == newword:
return True
else:
return False
That code gives me the following feedback:
isPalindrome('Bob', ignorecase=True)
Out[34]: True
isPalindrome('Bob')
Out[35]: False

Categories