def isAlpha(c):
return (ord(c) >= 65 and ord(c) <= 95) or \
(ord(c) >= 97 and ord(c) <= 122)
# testing first function
print isAlpha("D")
print isAlpha("z")
print isAlpha("!")
s = "AEIOUaeiou"
def isVowel(c):
return s.find(c) > -1
# testing second function
print isVowel("A")
print isVowel("B")
print isVowel("c")
print isVowel(" ")
print isVowel("a")
def convPigLatin_word(word):
if isVowel(word[0]):
word += "way"
while not isVowel(word[0]):
word = word[1:] + word[0]
if isVowel(word[0]):
word += "ay"
return word
# testing third function
print convPigLatin_word("This")
print convPigLatin_word("ayyyyyylmao")
def translate(phrase):
final = ""
while phrase.find(" ") != -1:
n = phrase.find(" ")
final += convPigLatin_word(phrase[0:n]) + " "
phrase = phrase[n+1:]
if phrase.find(" ") == -1:
final += convPigLatin_word(phrase)
return final
print translate("Hello, this is team Number Juan") #Should be "elloHay, isthay isway eamtay umberNay uanJay"
I tried to create a code that transform a string into pig latin. But I got stuck on the non-alphanumeric character. The while loop only works up to the comma. How can I resolve that? I don't know where to implement the isAlpha code to check for non alphanumeric character. Any advice is helpful.
You can iterate through the words of a phrase by using .split(' '). Then you can test them for special characters using .isalpha()
pigLatin = lambda word: word[1:]+ word[0]+"ay"
def testChars(word):
text = ""
for char in list(word):
if char.isalpha():
text += char
else:
return pigLatin(text)+ char
def testWords(lis):
words = []
lis = lis.split(' ')
for word in lis:
if not word.isalpha():
words.append( testChars(word) )
else:
words.append(pigLatin(word))
return (' ').join(words)
phrase = "I, have, lots of! special> characters;"
print testWords(phrase)
Related
I am doing some CodeHS for my computer science class at my school and for some reason my program doesnt meet the criteria of the grader, and maybe someone can assist me.
The autograder is looking for this:
The things it tests with are here:
and every result returns a runtime error in the autograder but not in the console.
Heres my code:
def get_letter():
while True:
letter = str(input("Enter a letter:\n> "))
if letter.isupper() == True:
print("Character must be a lowercase letter!")
continue
if len(letter) > 1 or len(letter) < 1:
print("Must be 1 character!")
elif letter.islower() == True:
return letter
break
def get_index():
while True:
try:
index = int(input("Enter an index (-1 to quit):\n> "))
if index == -1:
break
if index > len(word) or index < 0:
print "Invalid index"
continue
if index <= len(word):
global letter
letter = get_letter()
return index
break
except ValueError:
print "Please enter a number"
continue
word = input("Enter a word\n> ")
words = list(word)
while True:
try:
indexes = get_index()
splitword = words[:indexes] + [letter] + words[indexes +1:]
joinedword = ''.join(splitword)
print joinedword
except NameError:
break
and here are the instructions:
The CodeHS lesson is 8.3.8 Word Latter
This might be a little too late. I just came up to this question on CodeHS and had trouble myself. But I found it somewhere else, not to CodeHS's requirements so I had to fix it up myself. Here it is all fixed
def get_index(Inital_Word1):
User_Input = int(input("Enter an index (-1 to quit): "))
DexNav = len(Inital_Word1)
while User_Input > DexNav or User_Input<-1:
print "Invalid index"
User_Input = input("Enter an index (-1 to quit):")
DexNav = len(Inital_Word1)
return User_Input
def get_letter():
User_Input = input("Enter a letter: ")
DexNav = len(User_Input)
while DexNav > 1:
print "Must be exactly one character!"
User_Input = input("Enter a letter: ")
DexNav = len(User_Input)
while User_Input.isupper():
print "Character must be a lowercase letter!"
User_Input = input("Enter a letter: ")
return User_Input
def replace_at_index(User_Input, num, replacement):
return User_Input[0:num] + replacement + User_Input[num + 1:]
for i in range(1):
Inital_Word = input("Enter you inital word here: ")
Index = get_index(Inital_Word)
while Index != -1:
Letter = get_letter()
Inital_Word = replace_at_index(Inital_Word, Index, Letter)
print (Inital_Word)
Index = get_index(Inital_Word)
I wanted to enter a word with upperandlower letter combination letters and then when i press enter it will change vice versa
def changer(word):
for letter in word:
if letter.isupper():
letter.lower()
elif letter.islower():
letter.upper()
print word
word = raw_input()
changer(word)
You must append the converted letters to new string, and returning the new string could be helpful, too.
def changer(word):
newWord = ""
for letter in word:
if letter.isupper():
newWord += letter.lower()
elif letter.islower():
newWord += letter.upper()
print newWord
return newWord
...you do not return anything. and strings in python are immutable; you can not change them in-place.
this is something you could try:
def swapcase(word):
return ''.join(c.lower() if c.isupper() else c.upper() for c in word)
print(swapcase(word='Hello')) # hELLO
where i use str.join to join the generator that iterates over the characters with the swapped case.
speed-wise str.translate may be the better choice:
from string import ascii_lowercase, ascii_uppercase
trans_table = str.maketrans(ascii_lowercase + ascii_uppercase,
ascii_uppercase + ascii_lowercase)
def swapcase(word):
return word.translate(trans_table)
print('Hello'.translate(trans_table)) # hELLO
I am trying to print all the occurences of character 'p' in a string "python program".It shows same index value as 0 both 'p's in the string instead of 0 and 7.
str = raw_input("enter a string:")
sub = raw_input("enter a sub string:")
for i in str:
if i.lower() == sub.lower():
print i, str.index(i)
Output :
enter a string:python program
enter a sub string:p
p 0
p 0
Here is a suggestion for a solution:
sub = raw_input("enter the sub string you're looking for: ")
string = raw_input("enter the text you're looking in: ")
def get_next(text, sub):
for i in range(len(text)+1):
pos = text.find(sub, i)
if pos == -1 : #if no occurrences, do nothing
break
if i == pos: #would print the sub and the pos only if pointer in correct position
print sub, pos
get_next(string, sub)
You can have a while loop instead of a function, but I think a function would be more convenient if you want to use the code several times.
I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")
I am trying to write a function that takes two arguments, a string and a letter. The function should then double the number of letter in the string. For example:
double_letters("Happy", "p")
Happppy
what i have done so far;
def double_letter(strng, letter):
new_word = ""
for char in strng:
if char == letter:
pos = strng.index(char)
new_word = letter+strng[pos:]
But this is giving me the output: pppy
how can i change the function to get the output: Happppy?
Use string.replace
string = 'happy'
letter = 'p'
string = string.replace(letter, letter + letter)
print string
You could use join and iterate through the characters in your string:
def double_letters(word, letter):
return "".join(2*i if i == letter else i for i in word)