Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to make a password generator. I've tried using a for loop to generate each digit. I then appended each digit to a list. However, I want the output to be something along the lines of:
54324
rather than:
[5, 4, 3, 2, 4]
The following is my code:
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0,9))
digit += code
What happens in this scenario is that my output is just blank. I am somewhat new to python, so I may be missing something obvious, but I would appreciate if you could explain what I've done wrong and how to fix it.
Corrected version of your code
from random import randint
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0,9))
code += digit
print(code)
by the way, you can just use
code = randint(0,99999)
print(code)
to generate your password, just saying
Your code is overwriting digit each time. You generate a random integer between 0 and 9, then turn it into a string. Then you add a code to this digit string. Then the next iteration of the for loop, you generate a new value for digit. So you shouldn't be getting a blank value- you should be getting a one-digit value for digit, a string representation of an integer between 0 - 9.
Your values should be assigned and added onto code, not digit.
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0, 9))
code += digit
print(code)
Beside the obvious error in your code, fixing it will give you an underperformant code:
ugly for loop
5 calls to the random generator
5 conversions from int to string
string concatenation
If you want to generate a password made of exactly 5 numbers, since there's no requirement of uniqueness of the digits (as seen in another similar question where this technique could not apply), you could generate a number < 100000 and format it with leading zeros using a nested format:
import random
nb_digits = 5
for _ in range(10):
print("{:0{}}".format(random.randrange(0,10**nb_digits),nb_digits))
example of output:
58260
12986
69233
42343
02760
58934
06396
22262
07662
00182
At each loop, you are erasing the previous value contained by the variable digit, and you variable code is not useful here because it is empty.
You could just do:
chars = 5
for i in range(chars):
digit += str(randint(0,9))
you were trying to print digit which is single digit random number, you have to append it to some other string to store
from random import randint
code = ''
chars = 5
for i in range(chars):
digit = str(randint(0,9))
code = code +digit
print(code)
hope this helps
Since you are appending to code it should go like:
code +=digit
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I need help on how to convert a list to integers, for example
lst = ["1", "2", "3"]
Desired output:
123
I think I explain myself, I do not speak English so I use a translator, I hope it is understood.
You need to do two things: 1. concatenate the elements of the array together into a single string, and 2. convert that string to a number.
You can do #1 with the join string method. Normally, you call join on some other string that you want to put in between the ones you're joining, but since you don't want one of those here, you can just use the empty string:
>>> lst=["1","2","3"]
>>> "".join(lst)
'123'
Since that's still a string, not a numeric value, this is where step 2 comes in. You can convert it to an integer with the int function:
>>> int("".join(lst))
123
Join the strings, then convert to an integer:
int(''.join(lst))
The alternative of converting to integer and then joining is much more complicated, and will drop any leading zeros you have:
from math import floor, log10
result = 0
for x in lst:
n = int(x)
result *= 10**((x and floor(log10(x))) + 1)
result += n
Because of how Python's and operator works, the expression x and ... returns x immediately if it is zero, and the right hand side if not, which is what you want when taking logarithms.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to make a run length decoder that doesn't use 1s. For example a string that could be passed through would be something like ''' A2C3GTA'''. I made what i thought would work and am having trouble finding where I went wrong. I'm a beginner to python so I am sorry for the simple question. Thank you!
def decode(compressed):
decoded= ""
count = 0
for x in compressed :
if x.isdigit():
count += int(x)
y = compressed
decoded += y[int(x)+1] * count
count = 0
else :
decoded += x
print (decoded)
When you find a number-letter pair, you fail to skip the letter after you expand the pair. This is because you used a for loop, which is a more restrictive structure than your logic wants. Instead, try:
idx = 0
while idx < len(compressed):
char = compressed[idx]
if char.isdigit():
# replicate next character
idx += 2
else:
decoded += char
idx += 1
That will take care of your iteration.
Your in appropriate replication, the 22 in your output, this comes from an incorrect reference to the position:
decoded += y[int(x)+1] * count
Here, x is the run length, not the position of the character. If the input were A7B, this ill-formed expression would fault because of an index out of bounds.
In the code I gave you above, simply continue to use idx as the index.
I trust you can finish from here.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
A number that equals to the sum of its own digits, where each digit raised to the power of number of digits. For example, 153 is an armstrong number
because 1^3+3^3+5^3=153
at here user enters a number
number=int(input("please enter a number: "))
Here in a while loop it puts the digits of the given number in numbers class
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
and then we want to put their qubes in qubes class
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
and now we calculate the sum of the qubes class members
result = sum(i for i in qubes)
I dont know why the if_code below doesnt work it just gives me false output I dont know why??
even when i enter 153 it prints false
if result==number:
print("true")
else:print("false")
To sum-up all suggestions from the comments:
Your main problem is:
When you create the numbers list you use number = int(number/10). This changes the number variable itself until it is equal to zero. This means that, as you experienced, result == number will always be False.
Some redundant parts of your code:
See Splitting integer in Python? to get a list of a number's digits. Most commonly you can just do numbers = [int(i) for i in str(number)]. This will actually solve the problem above as you don't change number this way.
The digits are already integers so no need for an int conversion. It is also more readable to use direct loop in Python rather than looping over indices:
qubes = []
for num in numbers:
qubes.append(num**len(numbers))
sum(i for i in qubes) is just an overly explicit way of saying sum(qubes).
You are printing either "true" or "false" according to a boolean result. There is no need for a condition and you can simply print(result == number).
Putting together all the above, you can achieve this with a single line of code:
print(number == sum(int(digit)**len(str(number)) for digit in str(number)))
This is where you are wrong. you should iterate over the integer not the iterator given by range function
Use this
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
instead of
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
Also you are referencing the number to itself number=(int(number/10)) so your result value will be 153 but number value will be 0 at the end because you have reduced the value of number. So copy the value of number to another variable (num1 in below code).
Full code:
number=int(input("please enter a number: "))
num1 = number
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
result = sum(i for i in qubes)
print(result == int(num1))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was trying to get 3 random numbers within range in python without replacement. I did this
rand_lst = []
while(True):
rand = random.randint(0, length-1 )
if(len(rand_lst) == 3):
break
if(rand not in rand_lst):
rand_lst.append(rand)
This code is inside a for loop. This returns only 0 and thus an infinite loop. I also tried numpy.random.randint but some how random is keeping track of previously generated numbers and I endup with value error.
Trying putting print(length) right before your while True. You'll almost certainly find that the value of length is not what you expect it to be. (It's probably 0 or 1, when you want it to be 3 at least.)
if i understand you correctly,
you want something like this:
import random
rand_lst = []
length = 10
while(True):
rand = random.randint(0, length-1 )
if(len(rand_lst) == 3):
break
if(rand not in rand_lst):
rand_lst.append(rand)
print(rand_lst)
this way "length" has a value and will not throw an error
Explanation: https://stackoverflow.com/a/33806926/8386640
Use random.sample. Here is code.
import random
rand_lst = []
length = 3
while(len(rand_lst) < 3):
rand_lst.append(random.sample(range(length), 3))
print rand_lst
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Here is my homework:
Write a function that repeatedly generates random integers in the range [0,n[, until two consecutively generated numbers are identical.then return the number of generated numbers.
Here is what I did:
def function(n):
for i in range(100):
random.randint(0,n)
and this outputs a hundred numbers, however I need it to stop when it detects two identical numbers, how is that done?
For this you could use two names: one for the newly generated random number, and one for the previous one.
You need also to make your loop differently, as you don't know how long it needs to iterate before getting a match:
import random
def function(n):
a = -2
b = -1
i = 0
while a != b:
a, b = random.randint(0,n), a
i += 1
return i
# Sample run
times = function(400)
print (times)
See it run on repl.it
To do it without assigning a and b strange values, use an infinite while loop, then break when the values are the same. This is similar to #trincot's solution:
import random
def function(n):
a = None
i = 0
while True:
a, b = random.randint(0,n), a
i += 1
if a == b:
return i
# Sample run
times = function(400)
print(times)