开发者

python query - function arguments are incorrect type?

开发者 https://www.devze.com 2023-03-27 19:29 出处:网络
i\'m pretty new to python and i\'m having trouble with passing an argument into the random.choice function.

i'm pretty new to python and i'm having trouble with passing an argument into the random.choice function.

basically i'm trying to write a loop that will start off by selecting a random letter(which are all names of other lists) from the 'a' list, then input the selected letter into random.choice again to generate a sequence of random letters.

unfortunately the second call to random.choice isn't working, it just keeps repeating the inputted letter instead of pointing to a new list. any ideas how to fix this? i've been looking online for a few hours but can't find any 开发者_Python百科similar problems/solutions. any help would be much appreciated!

import random

a = ['b','c','d']
b = ['a','e']
c = ['a','d','f']
d = ['a','c','e','f','g','h']
e = ['b','d','h']
f = ['c','d','g','i']
g = ['d','f','i']
h = ['d','e','g','i']
i = ['f','h']

x = 0
answer = random.choice(f)
print "answer is %s " % answer

while x < 5:
    answer2 = random.choice(answer) 
    print "answer2 is now %s " % answer2
    x = x + 1


You've fallen into the common beginner's trap of mixing up variables and data, and trying to treat your code as data. You shouldn't typically try to do that - don't put the name of a variable into another variable and try to access it that way.

Instead, keep all the data together in a data structure, and just use your variables to access that structure, like this:

import random

DATA = {
    'a': ['b','c','d'],
    'b': ['a','e'],
    'c': ['a','d','f'],
    'd': ['a','c','e','f','g','h'],
    'e': ['b','d','h'],
    'f': ['c','d','g','i'],
    'g': ['d','f','i'],
    'h': ['d','e','g','i'],
    'i': ['f','h'],
}

x = 0
answer = random.choice(DATA['f'])
print "answer is %s " % answer

while x < 5:
    answer2 = random.choice(DATA[answer]) 
    print "answer2 is now %s " % answer2
    x = x + 1


Well... one issue is that you're always getting answer2 from the same list, since you're not doing any other assignments...


Just suppose x == 'c'. Then the second call to random.choice is actually

answer2 = random.choice('c')

This is like selecting a letter from a list containing only 'c'. This is NOT equivalent to the following:

answer2 = random.choice(c)

You need to convert the string 'c' into a list referenced by the variable c.

This mapping may work:

values = {
    "a": a, "b": b, "c": c, "d": d, "e": e,
    "f": f, "g": g, "h", h, "i": i, "j": j,
    }

Then values['c'] is the list referenced by variable c

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号