I'm currently learning Python from a book by Michael Dawson. Everything was clear and concise except when i got to an exercise called the 'Word Jumble Game'.
This is the code that is confusing me.
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
What i don't understand is how the while:word works. This is the explanation given:
I set the loop up this way so that it will continue until word is
equal to the empty string. This is perfect, because each time the loop
executes, the computer creates a new version of word with one letter
“extracted” and assigns it back to word. Eventually, word will become
the empty string and the jumbling will be done.
I tried tracing the program (maybe its an obvious oversight on my behalf) but i cannot see how the 'word' eventually breaks out of the loop because as long as it has characters in it surely it would evaluate to True and be an infinite loop.
Any help is hugely appreciated guys as i have looked for answers everywhere and its been fruitless. Thanks in advance.
This three statement is what you are suffering to understand
jumble += word[position] # adding value of the index `position` to jumble
word[:position] # items from the beginning through position-1
word[(position + 1):] # items position+1 through the rest of the array
So, after each iteration, exactly one item is cut down from the original string word. (word[position])
So, eventually you will end up with an empty word string.
if you are not convinced yet, add a print statement at the end of every iteration. This should help you.
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print word
while word: Loop block will be executed until word length is zero.
Note: This code acts like random.shuffle. from random import shuffle; shuffle(word)
Related
I have written this code in python to count the number of occurrence of each word in python. I just want to do that using for loop. No other inbuilt datatype like sets or dictionary. I think I have done wrong indentation.
mystring="Virat plays cricket. Virat is a batsman."
mylist=mystring.split(' ')
j=0
#the i outer loop that will iterate each element in list
for i in range(0,len(mylist)):
count=1
'''the j loop is to check whether value at j has occurred previously or not,
Like Virat at index 3 has occured previously also at index 0, so it should
not count that and it should break the loop because virat has counted previously
'''
for j in range(i-1,-1,-1):
if mylist[i]==mylist[j]:
break
if j==-1:
'''if a word hasn't founded previously then it should start iterating
next element from mylist[i]'''
for j in range(i+1,len(mylist)):
if mylist[i]==mylist[j]:
count=count+1
print(mylist[i]," has occured ",count)
I think it's way easier than this.
word = "tree"
phrase = "We must count how many times the word tree is included in this phrase. If I write tree again, then it's two"
counter = phrase.count(word)
print(f"The word {word} appears {counter} times")
And the output will, of course, be 2.
I suggest you to learn writing posts on Stackoverflow if you want to avoid downvotes. I also suggest you to only use # comments and not multiline strings and browsing a little bit more before asking for help. I admit I didn't know there was a direct way to do this task, but a fast research did the trick.
Edit: if you're looking for a manual check, you can try out this:
word_to_check = "tree"
counter = 0
phrase = "We must count how many times the word tree is included in this phrase. If I write tree again, then it's two"
phrase_array = phrase.split(" ")
for word in phrase_array:
if word == word_to_check:
counter = counter + 1
print(f"The word {word} appears {counter} times")
I was trying to extract the first letter of every 5th word and after doing a bit of research I was able to figure out how to obtain every 5th word. But, how do I know extract the first letters of every 5th word and put them together to make a word out of them. This is my progress so far:
def extract(text):
for word in text.split()[::5]:
print(word)
extract("I like to jump on trees when I am bored")
As the comment pointed out, split it and then just access the first character:
def extract(text):
for word in text.split(" "):
print(word[0])
text.split(" ") returns an array and we are looping through that array. word is the current entry (string) in that array. Now, in python you can access the first character of a string in typical array notation. Therefore, word[0] returns the first character of that word, word[-1] would return the last character of that word.
I don't know how did you solve the first part and can not solve the second one,
but anyway, strings in python are simply a list of characters, so if you want to access the 1st character you get the 0th index. so applying that to your example, as the comment mentioned you type (word[0]),
so you can print the word[0] or maybe collect the 1st characters in a list to do any further operations (I do believe that what you want to do, not just printing them!)
def extract(text):
mychars=[]
for word in text.split()[::5]:
mychars.append(word[0])
print(mychars)
extract("I like to jump on trees when I am bored")
The below code might help you out. Just an example idea based on what you said.
#
# str Text : A string of words, such as a sentence.
# int split : Split the string every nth word
# int maxLen : Max number of chars extracted from beginning of each word
#
def extract(text,split,maxLen):
newWord = ""
# Every nth word
for word in text.split()[::split]:
if len(word) < maxLen:
newWord += word[0:] #Entire word (if maxLength is small)
else:
newWord += word[:maxLen] #Beginning of word until nth letter
return (None if newWord=="" else newWord)
text = "The quick brown fox jumps over the lazy dog."
result = extract(text, split=5, maxLen=2) #Use split=5, maxLen=1 to do what you said specifically
if (result):
print (result) #Expected output: "Thov"
I made this simple Pyglatin translator in a Codeacademy learning exercise. Code is working fine, but need help understanding why.
The variable new_word is defined twice in the if statement. How does the code know to print the second definition of new_word instead of the first. Seems like it would make more sense for the final two lines of the if statement to read like-
final_word = new_word[1:len(new_word)]
print final_word
Full working code below-
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word
else:
print 'empty'
Can you keep redefining the same variable and it will always take the last definition given?
That's how imperative programming works. It says set the value of new_word to X. Then set the value of new_word to Y. Each statement does a particular thing, and the statements are followed one by one, modifying the program's state one by one.
You can contrast that with something like declarative programming in which you only define everything once, and the computer figures out in which order it needs to execute what in order to arrive at the result you described.
In this line you assign the concatenation of word, first and pyg to new_word:
new_word = word + first + pyg
After that, in this line, you chop off the first char:
new_word = new_word[1:len(new_word)]
You indeed use the same var new_word twice,
and the newest value (first char chopped off) overwrites the first one (first char still present).
B.T.W. the second line is needlessly complicated, it could also have been:
new_word = new_word[1:]
Maybe it helps to realize that a program variable isn't a mathematical variable, and the = in your program isn't a mathematical =.
a = 3 isn't a proposition meaning that a is equal to 3.
It is an action that puts the number 3 into a memory location labeled a.
So you can always put something else there.
Early languages used := (becomes) instead of = (is), and some languages still use <- to denote this assignment action.
guys. Thanks for taking the time to look through this. I've been having some trouble trying to figure out how exactly Python is creating this new string variable. The initial code is with a tuple full of random words. There is a random module that was imported and used the choice method to pull a random word out. Then, a while loop was created from that given variable that housed the random word that was just pulled. The objective was to completely randomize the lettering of the word. After words it prints the variable that holds the randomized indexed word. Here is the code I'm talking about
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(jumble)
My question is, how exactly is python creating a brand new jumbled word? I understand the code and what is happening up until it reaches to this given part that has me confused on what's going on.
jumble += word[position]
word = word[:position] + word[(position + 1):]
During each iteration, you "move" one character from the original word to the jumbled one. This is actualy quite simple when you understand the syntax:
jumble += word[position] - Add to the jumbled word the character at the random position
word = word[:position] + word[(position + 1):] - Remove the character at position position from the original word word
If you add print word, jumble as the first line inside your while loop, you could see the words come to life :)
I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly guessed letters are put into at the position they are in the randomly selected word.
The problem I am having is that if the word has a letter within it more than once, it will only find the first letter and add that. How would I go about looking for all instances of a letter and adding them?
This is the code I'm using to map guessed letters against the randomly selected word.
if user_input in choose_word:
print "Good guess!"
print trys_remaining, "trys remaining!"
word_index = letter_list.index(user_input)
correct_letters[word_index] = user_input
If anyone could point me in the right direction, it would be great.
You need to loop over all matching indices:
for word_index, letter in enumerate(letter_list):
if letter == user_input:
correct_letters[word_index] = user_input
Note: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enumerate() function allows to get the index at the same time.
See also the enumerate documentation.
You can use a list comprehension:
correct_letters = [letter if user_input == letter else correct
for (correct, letter) in zip(correct_letters, letter_list)]
Note that this will create a new correct_letters list, instead
of modifying the original one.