January 1st, 2013, 04:54 AM
-
Misunderstanding logic
Hey in the python book I am learning out of one of the challenges asks me to print a list of words in random order without repeating any. I accomplished it but I do not understand why my while and if statement operators work. I am still extremely new to programming and Python so if it's a stupid question, I'm sorry! Here is the code:
Code:
import random
words = ["Wordone",
"Wordtwo",
"Wordthree",
"Wordfour",
"Wordfive",
"Wordsix",
"Wordseven",
"Wordeight",
"Wordnine",
"Wordten",]
words_2 = []
words_length = len(words)
while words_length != -1:
random_word = random.choice(words)
words_length -= 1
if words_length != 9:
words_2.append(random_word)
words.remove(random_word)
for i in words_2:
print(i)
Thanks! Happy New Year!
January 1st, 2013, 08:20 AM
-
Program works because, having miscounted by 1 in the loop you inserted extra code to let the loop run an extra time. Please run your program with the "instructive print statement". 9 isn't a completely special number. You could use 2 or 7 also.
Code:
import random
words = ["Wordone",
"Wordtwo",
"Wordthree",
"Wordfour",
"Wordfive",
"Wordsix",
"Wordseven",
"Wordeight",
"Wordnine",
"Wordten",]
words_2 = []
words_length = len(words)
while words_length != -1:
# instructive print statement follows #############################
print('%d %s'%(words_length,str(words)))
random_word = random.choice(words)
words_length -= 1
if words_length != 9:
words_2.append(random_word)
words.remove(random_word)
for i in words_2:
print(i)
Let's fix the program, because yours won't work when words has 7 items.
Code:
import random
import string
words = list(string.digits)
words_2 = []
while words: # in other words, stop when the list is empty.
random_word = random.choice(words)
words_2.append(random_word)
words.remove(random_word)
print('\n'.join(words_2))
################# another way:
words = 'a b c wordsSEVEN'.split()
words_2 = words[:] # copy the words
random.shuffle(words_2) # shuffle them
print('\n'.join(words_2)) # display the words
[code]
Code tags[/code] are essential for python code and Makefiles!
January 2nd, 2013, 01:41 AM
-
January 2nd, 2013, 06:42 PM
-
Thanks for the information. I really like the:
Code:
.spilt()
.join()
random.shuffle()
I just started python like 2 weeks ago, my first programming language. I am VERY limited on the different tools I can use for certain things. My code is based off just what I learned in the first 5 chapters of the book I am reading from, lol.
I think another issue I am having is creating and understanding certain algorithms. I know this is essential and I am pretty good at math but not beyond like algebra, not because I am stupid but because I've never taken the classes. Any advice on how to learn this a little better too outside of actually taking a more advanced math class?
Thank you again! I will get much use out of the info you shared with me