-1

I would like to know what's wrong with my code:

import random

dicoRdm = {}

i = 0
z = 0
for i in range(0, 7) :
    rdmLetters = str(random.sample("bmkSL35", 7))
    for z in range(0, 7) :
        rdmLetters = "".join(rdmLetters)
        z += 1
    dicoRdm[i] = rdmLetters
    i += 1

What I would like to do is a dictionary which is generating 6 random strings in an order from 1 to 6. I would like to know why is my code not working as I expected. The generation works well but it appears that the dictionnary contains only letter by letter and not an actual word randomly generated. The key (0, 1, 2, 3, etc.) association works but the issue is only in the string association with its respective key. They're all seperated as you can see in the picutre:

Print result

I was expecting to get something like

{0: 'bhdlsSLm', 1: 'bdHsSmL', ...}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Roux
  • 69
  • 1
  • 8
  • what is the reason for `z += 1` and `i += 1`? Why join the `rdmLetters` 7 times, why use the `0` in `range()` – rioV8 Aug 05 '21 at 23:42

3 Answers3

0

Okay so I just found what was wrong in my code. I just deleted the str() in rdmLetters = str(random.sample("bmkSL35", 7)) and it worked, now I get what I was expecting https://i.stack.imgur.com/QL9OI.png

I hope I helped someone who had the same issue as me (or made the same mistake as me)

If anyone could explain why this tiny thing had broke up my expectation. I think it's because I tell the code that this is a string twice and it might separates every single letters one by one but I actually don't know the exact answer.

Roux
  • 69
  • 1
  • 8
  • 4
    `random.sample(...)` gives you a *list*. It's not clear what you intended from `str(random.sample(...))`, but e.g `str(['a', 'b', 'c'])` is `"['a', 'b', 'c']"`, **not** `"abc"`. If you've solved the problem I'd suggest deleting the question, this is not at all discoverable for someone else with a similar problem. – jonrsharpe Aug 16 '20 at 08:09
  • And there is a few other anti-patterns in the code of the original question (two loops when only one is necessary to produce the expected output, incrementing manually `i` and `z`, etc.). – mgc Aug 16 '20 at 08:18
0

What jonrsharpe said in the comment of the OPs answer regarding the str() function applied on random.sample(..)) is actually the main problem which is causing the unexpected behaviour.

If you have a list a and you want to make it to a string b, you do it by b = "".join(a)

So if you will remove the str() function then rdmLetters will be a list and hence rdmLetters = "".join(rdmLetters) will work correctly.

I would suggest to read This link of str() function on stackoverflow

0

Try this

import random
dicoRdm ={i: ''.join(random.sample('bmkSLA35', 7)) for i in range(6)}
print(dicoRdm)
Kuldip Chaudhari
  • 1,112
  • 4
  • 8