### Thread: What's wrong with this array?

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
May 2013
Posts
7
Rep Power
0

#### What's wrong with this array?

Code:
```num = [0] * size
guess = [0] * size
k=0
i=0
while i < size:
var = random.randint(1,9)
k=i-1
while(k>=0):
if var == num[k]:
k=-2
k-=1
if k>-2:
num[i] = var
i+=1```
Problem: The array is loading a duplicated number when it shouldn't be.

Thank you.
2. #### Run your code with pdb.

Single step with s.

Print values with p, as in
p i,k,var,num
Code:
```import pdb
pdb.set_trace()
size = 4
num = [0] * size
for i in range(len(num)):
var = 1  # assume random.randint returns 1 size times.  It can.
k = i-1
while k>=0:
if var == num[k]:
k=-2
k-=1
if k>-2:
num[i] = var```
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2012
Posts
194
Rep Power
6
It would probably be better if you explained what you are trying to accomplish. What you are doing there with the all the while loops and index counters is pretty goofy.

Do you just want a random ordered list of non-repeating numbers of a certain size?
python Code:
```import random
nums = list(range(10))
random.shuffle(nums)
print(nums)```

-Mek
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
May 2013
Posts
7
Rep Power
0
Originally Posted by Mekire
It would probably be better if you explained what you are trying to accomplish. What you are doing there with the all the while loops and index counters is pretty goofy.

Do you just want a random ordered list of non-repeating numbers of a certain size?
python Code:
```import random
nums = list(range(10))
random.shuffle(nums)
print(nums)```

-Mek
I'm making code for the Bulls and Cows game if you're familiar with that. I can't use random.shuffle because I have to compare my random numbers to the user input.

This is for school, and we're going over array's and indexing so that's why I'm coding it the way I am.
5. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2012
Posts
194
Rep Power
6
I don't really see what having to compare to user input has to do with it. I also actually think it would be easier to work with strings than lists of integers in this case, but it makes little difference.

Generate a string of unique numbers of length size:
python Code:
```number = ""
size = 4
while len(number) != size:
num = str(random.randint(1,9))
if num not in number:
number += num```

After getting your user input check results:
python Code:
```cows,bulls = 0,0
for i,attempt in enumerate(guess):
for j,solution in enumerate(number):
if attempt == solution:
if i == j:
bulls += 1
else:
cows += 1```

-Mek