I am new to Python and need help regarding assigning numbers to variables. How would I assign a random number from 0 to 9 to the variables "a" through "j" so that each variable gets a random number with no duplicates? Thanks in advance!
Asked
Active
Viewed 445 times
-2
-
3What have you tried so far? You should always include that with your question. – Reedinationer Jan 29 '19 at 00:19
2 Answers
1
You could do something like this to return a dictionary where the letters have been randomly mapped to numbers as well. It's a bit longer than other answers, but maybe easier for a beginner to follow the logic
import random
numbers_list = []
combined = {}
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
while True:
number = random.randint(0, 9)
if number in numbers_list:
pass
else:
numbers_list.append(number)
combined.update({alphabet.pop(): number})
if len(numbers_list) == 10:
break
Reedinationer
- 5,661
- 1
- 12
- 33
0
Here's one way:
import random
vals = list(range(10))
random.shuffle(vals)
a,b,c,d,e,f,g,h,i,j = vals
-
The best way, though making many variables is ill-advised. Short and clear; it's a shame someone downvoted it. – iz_ Jan 29 '19 at 00:50
-
I agree with the many variable thing, but it's OP's request... So to OP: you probably want to restructure your code to use `vals[x]` directly rather than defining 10 variables. – Julien Jan 29 '19 at 00:51
-
1
-
Do you know how I would make it so that the program does not repeat the same assignments to all of the variables again? A number could be assigned to the same variable again, however just not all ten numbers to the same variable. – Jason Le Feb 02 '19 at 02:24
-
I don't understand, please clarify exactly (example?) what's not satisfying you with my answer. – Julien Feb 03 '19 at 04:24