1

作为我大学课程的一部分,我正在学习 python。我一直在尝试完成的一项任务是编写一个程序,该程序将打印出随机字母及其在“反建制主义”中的对应位置。然后它将在一行上打印剩余的字母。

我一直在尝试以一种疯狂怪异的迂回方式来做到这一点 - 用所选值填充列表并从原始值中删除这些字符。

我意识到我的程序可能都是错误的和损坏的;我今天才开始学习清单!

import random
word = "antidisestablishmentarianism"
wordList =["antidisestablishmentarianism"]

print("The Word is:",word,"\n")

lengthWord = len(word)
usedValues=[]
for i in range(5):
    position = random.randrange(0,lengthWord)
    print("word[",position, "]\t", word [position])
    usedValues=[position]
for ch in wordList:
    wordList.remove([usedValues])
print("The remaining letters are",WordList, sep='')
4

2 回答 2

2

I think part of the problem is that you're creating and manipulating your worldList and usedValues lists incorrectly.

To create a list of characters as wordList use list(word). To add a used index to usedValues use usedValues.append(position). There's also an issue with how you remove the used values from the word list.

Here's your code with those errors fixed:

import random
word = "antidisestablishmentarianism"
wordList = list(word)

print("The Word is:",word,"\n")

lengthWord = len(word)
usedValues=[]
for i in range(5):
    position = random.randrange(0,lengthWord)
    print("word[",position, "]\t", word[position])
    usedValues.append(position)

for index in usedValues:
    wordList.pop(index)

print("The remaining letters are",WordList, sep='')

This will mostly work. However, there's still a logic error. If you get the same random position twice in the first loop, you'll report the same character each time. However, when you remove them from the list later, you'll end up popping two different letters. Similarly, if you remove an letter from near the start of the word, the indexes you remove later on will be incorrect. You can even get a IndexError if one of the last positions selected was near the end of the word.

One fix would be to remove the selected values from the list immediately, within the first loop. You'll need to explicitly call len each cycle then (since it changes each time through) but other than that everything should work correctly.

Or here's how I'd solve the problem. Instead of picking five specific indexes and removing them from the list, I'd random.shuffle a list of all the indexes and take the first five. The rest can then be either printed out in their random order, or sorted first to give the impression of the letters being removed from the original word.

import random
word = "antidisestablishmentarianism"

indexes = list(range(len(word)))
random.shuffle(indexes)

for i in indexes[:5]:
    print("word[%d] is '%s'" % (i, word[i]))

rest = sorted(indexes[5:]) # or just use indexes[5:] to keep random order
print("The remaining letters are '%s'" % "".join(word[i] for i in rest))
于 2012-11-08T19:51:07.910 回答
0

There are a few problems with your code as it stands. Firstly, this line:

wordList =["antidisestablishmentarianism"]

doesn't do what you think - it actually creates a list containing the single item "antidisestablishmentarianism". To convert a string into a list of characters, you can use list() - and since you've already have the variable word, there's no need to type the word in again.

On a side note, wordList isn't a very good variable name. Apart from the fact that it uses camelCase rather than the more pythonic underscore_separated style, what you actually want here is a list of the characters in the word.

So, that line can be replaced with:

characters = list(word)

Moving on ... this line:

lengthWord = len(word)

is redundant - you only reference lengthWord once in your code, so you might as well just replace that reference with len(word) where you use it.

Your line:

    usedValues=[position]

also isn't doing what you think: it's replacing usedValues entirely, with a list containing only the latest position in your loop. To append a value to a list, use list.append():

    used_positions.append(position)

(I've given the variable a more accurate name). Your next problem is this block:

for ch in wordList:
    wordList.remove([usedValues])

First of all, you really want to check each of the positions you've previously stored, not each of the characters in the word. Your use of list.remove() is also wrong: you can't give a list of values to remove like that, but anyway list.remove() will remove the first instance of a value from a list, and what you want to do is remove the item at a particular position, which is what list.pop() is for:

for position in sorted(used_positions, reverse=True):
    characters.pop(position)

We're using a copy of used_positions sorted in reverse so that when we remove an item, the remaining positions in used_positions don't slide out of alignment with what's left of characters[*].

Your final problem is the last line:

print("The remaining letters are",WordList, sep='')

If you want to print the contents of a list separated by '', this isn't the way to do it. Instead, you need str.join():

print("The remaining letters are", "".join(characters))

Putting all of those changes into practice, and tidying up a little, we end up with:

import random
word = "antidisestablishmentarianism"
characters = list(word)

print("The Word is:", word, "\n")

used_positions = []

for i in range(5):
    position = random.randrange(0, len(word))
    print("word[",position, "]\t", word[position])
    used_positions.append(position)

for position in sorted(used_positions, reverse=True):
    characters.pop(position)

print("The remaining letters are", "".join(characters))

[*] In fact, this throws up another problem: what if your code chooses the same position twice? I'll leave you to think about that one.

于 2012-11-08T20:15:39.660 回答