Home > Blockchain >  .sample seems to have a limited range
.sample seems to have a limited range

Time:05-04

I have the below code which allows a user to choose the length of a password, if I enter something silly like 2049 it breaks can you please explain to me why?

with open("accounts.txt", 'a') as acc:
    length = int(input('\nEnter the length of password: '))
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    num = string.digits
    symbols = string.punctuation
    all = lower   upper   num   symbols
    temp = random.sample(all,length)
    password = "".join(temp)
    acc.write("{} {}\n".format(nu,password))

CodePudding user response:

sample(all, length) returns a set of unique characters, so it's required that length <= len(all). You want to use random.choices instead.

temp = random.choices(all, k=length)

CodePudding user response:

Program was crashing here temp = random.sample(all,length) when length is greater then len(all).

Fix : generate the random manually temp = [all[random.randint(0, len(all)-1)] for _ in range(length)] and write it to file.

import string
import random

with open("accounts.txt", 'a') as acc:
    length = int(input('\nEnter the length of password: '))
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    num = string.digits
    symbols = string.punctuation
    _all = lower   upper   num   symbols
    #temp = random.choice(all,length)
    temp = [_all[random.randint(0, len(_all)-1)] for _ in range(length)]
    password = "".join(temp)
    #acc.write("{} {}\n".format(nu,password))
    acc.write(f"{password}")
  • Related