This script takes a sentence and encodes it. The code takes each letter in a given word and bumps it up in the alphabet by the length of the word. So "cat" becomes "fwd", "small" becomes "xrfqq", and "small cat" becomes "xrfgg fwd".
I wanted to see if there was anything I should have done differently or if ya'll had some suggestions for improvements.
#Letter altering code
alphabet = ["a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t",
"u","v","w","x","y","z"]
textIn= ""
while textIn.lower != 'q':
textIn = input("Type a sentence to be translated ('q' to quit).\n"\
).lower()
textOut = ""
if textIn == 'q':
break
else:
for word in textIn.split():
newWord = ""
for char in word:
if char in alphabet:
pos = alphabet.index(char)
newPos = (pos + len(word))%26
newChar = alphabet[newPos]
newWord += newChar
else:
newWord += char
textOut += newWord + " "
print(textOut)
It's pretty good.
alphabet is string.ascii_lowercase
textIn.lower should be textIn.lower()
break should only be used in a loop. You want pass, which means 'do nothing'.
The loop adding the new character to the new word is clear. I like it. There are other terser ways to do it, though, which are more pythonic and can still be as clear.
Related
I have a assignment where I need to
sometimes it might be useful to convert text from lowerCamelCase to snake_case. The main trick is to find the correct place where to insert an underscore. Let's make a rule that it's right before a capital letter of the next word. If the first letter is capitalized, convert it to lowercase and don't forget to insert an underscore before it.
I wrote my code and for some reason it doesn't return anything, it's completely empty, my ide says I have no errors
word = input()
new_word = ''
for char in word:
if char.isupper():
new_word.join('_' + char.lower())
else:
new_word.join(char)
print(new_word)
The assignment runs multiple tests with different words, and here they are
Sample Input 1:
python
Sample Output 1:
python
Sample Input 2:
parselTongue
Sample Output 2:
parsel_tongue
I legitimately don't see any reason why it's not printing, any ideas why
It's because the 1st test case is all lower case.
new_word will be empty because loop's inner condition won't execute at all.
Here's the correct and cleaner code I wrote
word = input()
counter = 0
new_word = ""
for char in word:
if not(char.islower()) and counter > 0:
new_word = new_word + '_' + char.lower()
else:
new_word = new_word + char.lower()
counter += 1
print(new_word)
You are almost there. You have to concatenate the characters to new_word and not join.
This is Concatenation. char gets appended to new_word:
new_word += char
join() will just concatenate and return the strings passed to it. But it is not saved to new_word.
Use concatenation instead of join in your code.
word = input('Input: ')
new_word = ''
for char in word:
if char.isupper():
new_word += '_' + char.lower()
else:
new_word += char
print(f'Output: {new_word}')
Input: python
Output: python
Input: parselTongue
Output: parsel_tongue
As your title says "list comprehension", here is an approach that utilizes a comprehension:
snake_word = ''.join(f'_{c.lower()}' if c.isupper() else c for c in word)
I'm still a noob when it comes to coding and I'm trying to create my own hangman game. I ran into some difficulties when it comes to guessing characters of a word which occur more than once in a word.
Here's a snippet of my code:
def random_word():
#word generator
randomized = random.randint(0,(len(content_words)-1))
word_to_guess = content_words[randomized].lower()
splitted = []
word_progress = []
for character in word_to_guess:
splitted.append(character.lower())
word_progress.append("?")
counter = 0
while counter <= 5:
print(word_to_guess)
print(splitted)
print(word_progress)
#Start of the game
options = str(input("Do you want to guess the word or the characters?: ").lower())
#word
if options == "word":
guess_word = input("Please your guess of the word: ").lower()
if guess_word == word_to_guess:
print("Correct! The word was " + word_to_guess + " you only needed " + str(counter) + " tries!")
break
elif guess_word != word_to_guess:
counter += 3
print("You have entered the wrong word ! You now have " + str(5-counter) + " tries left!")
continue
#characters
elif options == "characters":
guess_character = input("Please enter the character you would like to enter!: ")
if guess_character in splitted and len(guess_character) == 1:
print("Correct! The character " + guess_character.upper() + " is in the word were looking for!" )
for char in word_to_guess:
if char == guess_character:
word_progress[word_to_guess.index(char)] = word_to_guess[word_to_guess.index(char)]
continue
....so basically in the character section only the first occurrence of the guessed character gets implemented into the word_to_guess list. What is the best way to handle this problem?
By the way this is the first question I've ever asked regarding to coding and on this platform, please excuse me if I didn't really formulate my problem in the most efficient way.
index will only return the index of the first occurence of your character.
You should use enumerate to iterate on the characters and indices at the same time:
for index, char in enumerate(word_to_guess):
if char == guess_character:
word_progress[index] = guess_character
word = input("Translate a word: ")
for char in word:
if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz":
print(char + "o" + char)
else:
print(char)
I have this code for a translator to a language where you add an "o" after each consonant followed by that same consonant again. When i run it and type in for example "stair" it would print out:
sos
tot
a
i
ror
If someone has an idea on how to print this out on the same line without spacing i would be very grateful!
Don't print each time but append the result to a string and print the final string:
word = input("Translate a word: ")
result = ''
for char in word:
if char not in "aeiouyAEIOUY":
result+=char + "o" + char
else:
result+=char
print(result)
One option is to use list comprehension to create a list with your values:
[char+'o'+char if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" else char for char in word]
and then if you need to smash them together into a string you just use a join()
''.join([char+'o'+char if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" else char for char in word])
Add records to a list and use print function with * to print records in the same line.
word = input("Translate a word: ")
data = [] #create a empty list
for char in word:
if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz":
data.append(char + "o" + char) #add elements to list
else:
data.append(char) #add elements to list
print(*data, sep='') #print list elements in single line without spaces
If you want to use the print statement as you are currently doing, just try below option of print statement which defines the ending of the print statement.
word = input("Translate a word: ")
for char in word:
if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz":
print(char + "o" + char,end="")
else:
print(char,end="")
The output of the above code on input "stair" will be "sostotairor". Hope it helps!
You can double the consonants in a list first and join the characters with o:
word = input("Translate a word: ")
for char in word.lower():
print('o'.join([char] * ((char not in 'aeiou') + 1)))
Sample input/output:
Translate a word: stair
sos
tot
a
i
ror
I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code.
import random
import urllib.request
wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-
type=text/plain"
response = urllib.request.urlopen(wp)
long_txt = response.read().decode()
words = long_txt.splitlines()
###########
# Methods #
###########
def Run():
dashes1 = "-" * len(word)
dashes2 = "-" * len(word2)
used_letter = []
dashes = dashes1 + " " + dashes2
#dashes ="-" * len(secretWord)
guessesLeft = 6
while guessesLeft > -1 and not dashes == secretWord:
print(used_letter)
print(dashes)
print (str(guessesLeft))
guess = input("Guess:")
used_letter.append(guess)
if len(guess) != 1:
print ("Your guess must have exactly one character!")
elif guess in secretWord:
print ("That letter is in the secret word!")
dashes = updateDashes(secretWord, dashes, guess)
else:
print ("That letter is not in the secret word!")
guessesLeft -= 1
if guessesLeft < 0:
print ("You lose. The word was: " + str(secretWord))
print(dashes)
else:
print ("Congrats! You win! The word was: " + str(secretWord))
print(dashes)
def updateDashes(secret, cur_dash, rec_guess):
result = ""
for i in range(len(secret)):
if secret[i] == rec_guess:
result = result + rec_guess
else:
result = result + cur_dash[i]
return result
########
# Main #
########
word = random.choice(words)
word2 = random.choice(words)
#print(word)
#print(word2)
secretWord = word + " " + word2 # can comment out the + word2 to do one
word or add more above to create and combine more words will have to adjust
abouve in Run()
splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)])
print (splitw)
Run()
any bit of help is appreciated. The website I'm using has a bunch of words that are being used for the words randomly generated. Some are capitalized, and I need to figure out how to let the input of a letter, say a capital A, accept a lowercase a and count for it.
you could compare after you converted everything to lowercase.
e.g. you could do
secretWord = word.lower() + " " + word2.lower() # that should make your secret all lowercase
for the input you should do the same:
guess = input("Guess:").lower()
after that it should not matter if it is upper or lower case. it should always match if the letter is the correct one.
hope that helps
Simply check everything in lowercase:
[...]
elif guess.lower() in secretWord.lower():
[...]
and so on.
I would just change this line:
while guessesLeft > -1 and not dashes == secretWord:
to:
while guessesLeft > -1 and not dashes.lower() == secretWord.lower():
This way you are always comparing lower-case representations of the user's input to the lower-case representation of your secretWord. Since this is the main loop for your game, you want to break out of this as soon as the user's guess matches your word regardless of case. Then later in your code, you will still check whether they had any guesses left, and print out their answer and the secret word as before.
No other changes required, I think.
You could just force all comparisons to be made in the same Case, such as lowercase.
Let’s say that your word is "Bacon". and someone enters "o".
That will be a match because quite obviously “o” equals “o” so you can cross that letter off the list of letters left to guess.
But in the case that someone enters “b” then b is NOT equal to “B”.
So why not just force all letters to be compared using the same case?
So your comparison will be like
elif guess.Lower() in secretWord.Lower()
My python is rusty as hell, but the idea here should do what you want to do
I've been working on a Pig Latin program. However, it doesn't seem to be working and I can't figure out why.
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first == "a" or "e" or "i" or "o" or "u":
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
On top of that, I was looking to utilize enumerate to find the position of the first vowel, slicing to isolate the first letter of the word and concatenation to form the word. I've read up on how to use it on a couple websites but I can't seem to figure out how to correctly apply it to this program. I think I would have to define Vowels = 'aeiou' before def translate(user_input) right??
You cannot chain if statements like that in Python, you have to do it the long way:
if first == "a" or first == "e" or first == "i" or first == "u":
or shorten it to:
if first in ["a", "e", "i", "u"]:
Here is the solution. I've made a few changes in your code which i will be explaining below.
user_input = input("Enter word to be translated:\n")
#change_1
vowels = ['a','e','i','o','u']
def translate(user_input):
first = user_input[0]
#change_2
if first in vowels:
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
#change_3
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
#change_4
user_input = user_input[index_value:] +user_input[:index_value]+ "ay"
return user_input
print(translate(user_input))
1) Create a list of vowels.
2) As our friend #zwer mentioned You cannot chain if statements like that in
Python. So
if first in vowels:
3) For every letter in user_input check if that letter is a vowel and if that letter is a vowel then find the index of it's occurrence.
For example take the word 'trash'
Here a is the first vowel and it's index is 2
if letter in vowels:
index_value = user_input.index(letter)
4) According to wikipedia
"all letters before the initial vowel are placed at the end of the word sequence"
For the word 'trash' it would be
user_string = user_input[2:] + user_input[:2]+"ay"
which would be slicing the word from that index to end, merged with letters before that index. And finally an "ay".
'ash' + 'tr' + 'ay'
Hope this helps.
You can define vowels in the outer scope.
vowels = 'a', 'e', 'i', 'o', 'u'
Then anywhere you can use:
if first in vowels:
My Solution covers the below rules:
1. A word is a consecutive sequence of letters (a-z, A-Z) or apostrophes. You may assume that the input to the function will only be a single "word". Examples: Zebra , apple
2. If a word starts with a vowel, the Pig Latin version is the original word with "way" added to the end
3. If a word starts with a consonant, or a series of consecutive consonants, the Pig Latin version transfers ALL consonants up to the first vowel to the end of the word, and adds "ay" to the end.
4. The letter 'y' should be treated as a consonant if it is the first letter of a word, but treated as a vowel otherwise.
5. If the original word is capitalized, the new Pig Latin version of the word should be capitalized in the first letter. If the original capital letter was a consonant, and thus moved, it should not be capitalized once in its new location.
Solution Starts here:
eng_to_pig_latin = {"football": "ootballfay", "Pittsburgh":"Ittsburghpay",
"Apple":"Appleway","oink":"oinkway",
"ontology":"ontologyway","yellow":"ellowyay","yttrium":"iumyttray"}
eng_word = 'yttrium'
vowels = 'aeiou'
def pig_latin(eng_word):
sub,str1 = [],''
first = eng_word[0]
second = eng_word[1]
# Rule 2
if first.lower() in vowels:
piglatin = eng_word +'way'
# Rule 3
elif first.lower() == first and second.lower() in vowels:
piglatin = eng_word[1:]+first+'ay'
elif first.lower()+second.lower() not in vowels:
# Rule 3 & 4
for l in eng_word:
if l not in vowels:
sub.append(l)
else:
str1 = eng_word[eng_word.index(l):]
break
str2 = ''.join(sub)
piglatin = str1+str2+'ay'
else:
# Rule 5
piglatin = eng_word[1:].capitalize()+first.lower()+'ay'
print(f'Test word is {eng_word} and its equivalent piglatin word is
{piglatin}. Comparison with mapping dictionary is
{eng_to_pig_latin[eng_word] == piglatin}')
pig_latin(eng_word)
Note: The dictionary uses is only to cross-check if the results are as expected, which I am doing in the last print statement.
my logic to translate given word in to Pig Latin translation
vowels=['a','e','i','o','u']
def igpay(name):
a_list=list(name)
if a_list[0] in vowels:
print("First letter is a Vowel")
apnd_letters="way"
else:
print("First letter is a Consonant")
a_list.append(a_list[0])
a_list.pop(0)
apnd_letters="ay"
print("Pig transaltion is {0}".format("".join(a_list)+str(apnd_letters)))
Output:
igpay("pig")
First letter is a Consonant
Pig transaltion is igpay
igpay("apple")
First letter is a Vowel
Pig transaltion is appleway
You can do it exactly the same as you are doing it except you will need to change the second line in translate:
if first == "a" or "e" or "i" or "o" or "u":
to:
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
or:
if first in 'aeiou':
If you want to be able to use capital letters however, I would recommend changing first to first.lower().
This becomes:
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first.lower() in 'aeiou':
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
If you want the code a bit shorter, I have managed to shorten it to:
def translate():
user_input = input('Enter a word or sentence')
for i in range(len(user_input.split())): print(str((user_input.split())[i][1::])+((user_input.split())[i])[0]+'ay', end=' ')
translate()
Here is another two ways to go about it
Method 1:
Using a function that recursively translates words
sentence = str(input('Input Sentence: '))
vowels = 'aeiouAEIOU'
# 1. strip removes whitespace before and after input
# 2. pig_word_latin deals with one word at a time
# 3. join collects all the words into one sentence with spaces
def pig_latin_word(word):
vowelStart = True
#print(word)
if word[0] not in vowels:
vowelStart = False
return pig_latin_word(word[1:] + word[:1])
elif word[0] in vowels and not vowelStart:
return word + 'ay'
elif word[0] in vowels and vowelStart:
return word + 'way'
def pig_latin(sentence):
words: list = sentence.strip().split(' ')
new_words = []
for word in words:
new_words.append(pig_latin_word(word))
print(" ".join(new_words))
pig_latin(sentence)
Method 2:
Using a function that recursively translates sentences by keeping track of spaces
sentence = str(input('Input Sentence: ')).strip()
vowels = 'aeiouAEIOU'
suffix = {}
suffix[True] = 'way'
suffix[False] = 'ay'
def pig_latin(sentence, acc='', cluster='', word=''):
#print('S:'+sentence, 'C:'+cluster, 'W:'+word)
#print('Acc:',acc)
new_word = len(word)==0
vowel_start= len(cluster)==0
#print('NW:',new_word, suffix[vowel_start])
#print('-')
if len(sentence) == 0:
return acc+word+cluster+suffix[vowel_start]
if sentence[0] == ' ':
return pig_latin(sentence[1:], acc+word+cluster+suffix[vowel_start]+' ')
if new_word == True:
if sentence[0] not in vowels:
#print('1---')
return pig_latin(sentence[1:], acc, cluster+sentence[0], '')
elif sentence[0] in vowels and not vowel_start:
#print('2---')
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
elif sentence[0] in vowels and vowel_start:
#print('3---')
return pig_latin(sentence[1:], acc, '', word+sentence[0])
else:
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
print(pig_latin(sentence))