the question asks to have to user enter a one word string, then randomize the place of the letters in the word, for example, "hello" can turn into "elhlo"
import random
def word_jumble():
word = raw_input("Enter a word: ")
new_word = ""
for ch in range(len(word)):
r = random.randint(0,len(word)-1)
new_word += word[r]
word = word.replace(word[r],"",1)
print new_word
def main():
word_jumble()
main()
I got the program from someone else, but have no idea how it works. can someone explain to me please? I understand everything before
new_word += word[r]
The code is unnecessarily complex, maybe this will be easier to understand:
import random
word = raw_input("Enter a word: ")
charlst = list(word) # convert the string into a list of characters
random.shuffle(charlst) # shuffle the list of characters randomly
new_word = ''.join(charlst) # convert the list of characters back into a string
r is a randomly selected index in the word, so word[r] is a randomly selected character in the word. What the code does is it selects a random character from word and appends it to new_word (new_word += word[r]). The next line removes the character from the original word.
If you use a bytearray, you can use random.shuffle directly
import random
word = bytearray(raw_input("Enter a word: "))
random.shuffle(word)
Related
I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)
I'm fairly new to Python and one of the practice projects I'm trying to do is converting sentences into pig latin. The original project was just converting words into pig latin, but I want to expand this into converting sentences.
Here's the code I have so far:
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
word = input ("Write a Word: ")
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
print ()
print ("{}".format(pig_Latin), file=sys.stderr)
end = input ("\n\n Press N\n")
if end.lower() == "n":
sys.exit()
The plan is to modify this so it splits all the words in the input sentence, converts each word to pig latin, and then spits it back out as one sentence but I'm not really sure how to do that.
I'm using Python 3.8. Any help is appreciated! Thank you.
You could split the sentence by the space character into separate strings each containing a word. You can then apply your current algorithm to every single word in that sentence. str has a method split which returns a list.
To get the words in a list, use listofwords = input('Write your sentence: ').split().
Then, you can combine the list of pig-latin words doing print(' '.join(listofpiglatin)).
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
listofwords = input ("Write a Sentence: ").split() # splits by spaces
listofpiglatin = []
for word in listofwords:
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
listofpiglatin.append(pig_Latin) # adds your new pig-latin word to our list
print()
print(' '.join(listofpiglatin)) # spits the words back as a sentence
end = input ("\n\n Press n")
if end.lower() == "n":
sys.exit()
I hope that this helps you learn!
Put your algorithm into a function:
def makePigLatin(word):
<your code here>
return latinWord
As other users mentioned, split the input and assign to a list:
words = input('blah').split()
Then apply your function to each word in the list:
translatedWords = map(makePigLatin, words)
Print them back out by joining them together:
print(' '.join(translatedWords))
I have this code
#Ask for word
w = input("Type in a word to create acronym with spaces between the words:")
#Seperate the words to create acronym
s = w.split(" ")
letter = s[0]
#print answer
print(s.upper(letter))
And I know that I need a for loop to loop over the words to get the first letter of each word but I can't figure out how to do it I tried many different types but I kept getting errors.
Try this. It prints a concatenated version of the first letter of each word.
w = input("Type in a word to create acronym with spaces between the words:")
print(''.join([e[0] for e in w.split()]).upper())
Try this
w = input("Type a phrase with a space between the words:")
w_up_split = w.upper().split()
acronym = ""
for i in w_up_split:
acronym += (i[0])
print(acronym)
for word in w.split(" "):
first_letter = word[0]
print(first_letter.upper())
In the code that you gave you are taking the first word in a list of lists.
s = w.split(" ")
letter = s[0]
If someone input 'Hi how are you' this s would equal
s == ["Hi"]["how"]["are"]["you"]
And then letter would equal the first index of s which would be ["Hi"]
You want to go through each word and take each letter
acronym = []
for x in s:
acronym.append(x[0])
Would get what you want.
I try write program that build new word from inputed, where letter is vise versa
# vise versa
print ("word vise versa")
word = input("Input your text ")
new_word = ""
while word:
position = len(word) - 1
for letter in word:
new_word += letter[position]
position -= 1
print(new_word)
Always have mistake
Traceback (most recent call last):
File "4_2.py", line 9, in <module>
new_word += letter[position]
IndexError: string index out of range
what I do wrong?
Thanks!
The trouble is probably what you are doing in the below lines
for letter in word:
new_word += letter[position]
where letter will be each letter within the word, first 'a' then 'b' then 'c' if word was abc. On the seconds string you are trying to use the letter 'a' as an array, which is no good. You probably want to offset into the word array instead?
First in your code, if your input is not None or a False Value, your loop will go forever because word is not a False Value.
Second, you can use reverse slice of a string or a list like this:
# vise versa
print("word vise versa")
word = raw_input("Input your text ")
new_word = ""
if word:
new_word = word[::-1]
print(new_word)
Get Input word from user by using raw_input method
Get length of input word by len method.
Use while loop to add character in new variable.
decrement length variable by 1
print "Program: word vise versa"
word = raw_input("Input your text:")
new_word = ""
wdlen = len(word)
while wdlen:
new_word += word[wdlen-1]
wdlen -= 1
print new_word
Output:
$ python test.py
Program: word vise versa
Input your text:abcdef
fedcba
use slice .
more info https://docs.python.org/2/whatsnew/2.3.html#extended-slices
>>> a = "12345"
>>> a[::-1]
'54321'
You can rewrite your code as a a oneliner like this:
new_word = "".join(reversed(input("Input your text ")))
The reversed function takes a sequence type, and returns a new one with the elements in reverse order. However, this will now be a list.
The "".join then joins them back into a string - some join string must be provided, so any empty string is used.
With fewer lines, and no temporary variables, there are fewer places for this code to break.
Below is some code from a game I am creating which scrambles the letters of a random word for a player to guess. I was wondering why when I put my letter variable (which assigns a random letter from one of the words in my word bank to the variable letter) above my while word: statement there is a string index error but if I put the same variable in the while word: statement there is no error.
I know that in the string koala, for example, k is 0 and a is 4. Why would that change within the while statement? Or is there something else going on?
This works:
while word:
letter = random.randrange(len(word))
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
This does not work:
scrambled_word = ''
letter = random.randrange(len(word))
while word:
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
Why?
With each iteration of
while word:
scrambled_word += word[letter]
word = word[:letter] + word[(letter+1):]
word is shortened by one letter:
>>> "koala"[:3]
'koa'
>>> "koala"[4:]
'a'
so eventually word[letter] will try to access a letter that's no longer there.
If you want to scramble a word, there's a built-in function for that, though:
>>> word = "koala"
>>> l = list(word)
>>> random.shuffle(l)
>>> word = "".join(l)
>>> word
'oklaa'
(taking a detour via a list object because strings themselves are immutable and can't be shuffled directly).
I'm not a python programmer, but this is probably wrong:
word = word[:letter] + word[(letter+1):]
You need to check if the letter is the last one, otherwise word[(letter+1):] is out of bound.