Why is my input variable adding to itself? Python - python

I have made this simple password generator with the option to choose the length of the password. It seems to randomly add the length to itself however, so if I keep choosing a length of 5 it will occasionally output a password of 10 characters and then go back to 5.
import random
randomnums = []
checker = [0, 0, 0, 0] ##Make sure there are upper, lower case, symbols and numbers.
while True:
length = input("How long do you want your password?: ")
if length.isdigit() == False:
print("please enter a number..\n")
elif int(int(length)) < 4:
print("Please enter a length of 4 or greater...\n")
else:
break
while checker[0] == 0 or checker[1] == 0 or checker[2] == 0 or checker[3] == 0:
for i in range(0,int(length)):
x = random.randrange(0, 4)
if x == 1:
randomnums.append(random.randrange(0, 10))
checker[0] = 1
elif x == 2:
randomnums.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
checker[1] = 1
elif x == 3:
randomnums.append(random.choice('ABCDEFGHIJKLMNPQRSTUVWXYZ'))
checker[2] = 1
else:
randomnums.append(random.choice('!##$%^&*()_+:"}|<>?'))
checker[3] = 1
password = ''.join(map(str, randomnums)) ##join list to string
print(password)`

You could get any multiple of length with this code. It adds length characters in the body until you got the required length. You should instead generate a password and check it, and if it is bad, repeat.

Related

Ways to execute this code under 4 seconds given large inputs?

NOTE: I CAN NOT use any external module that is not built-in to python.
Problem:
A new and upcoming artist has a unique way to create checkered patterns. The idea is to
use an M-by-N canvas which is initially entirely black. Then the artist repeatedly chooses
a row or column and runs their magic brush along the row or column. The brush changes
the colour of each cell in the row or column from black to gold or gold to black.
Given the artist’s choices, your job is to determine how much gold appears in the pattern
determined by these choices.
Input Specification
The first line of input will be a positive integer M. The second line of input will be a positive
integer N. The third line of input will be a positive integer K. The remaining input will be
K lines giving the choices made by the artist. Each of these lines will either be R followed
by a single space and then an integer which is a row number, or C followed by a single space
and then an integer which is a column number. Rows are numbered top down from 1 to M.
Columns are numbered left to right from 1 to N.
Output Specification
Output one non-negative integer which is equal to the number of cells that are gold in the
pattern determined by the artist’s choices.
Limitations
M and N can be up to 5 000 000
K can be up to 1 000 000
My Solution
import sys
raw_input = sys.stdin.readline
m = int(raw_input())
n = int(raw_input())
brushes = raw_input()
stroke = []
colors = [['B' for _ in range(n)] for _ in range(m)]
for i in range(int(brushes)):
g = raw_input().split(' ')
if stroke.count(g) == 1:
stroke.remove(g)
else:
stroke.append(g)
def changeColumn(num,colors,index):
if num == 0:
return colors
colors[num-1][index] = 'G' if colors[num-1][index] == 'B' else 'B'
num -= 1
changeColumn(num,colors,index)
def countGold(c,options,i):
if options == []:
s = 0
for l in c:
s += l.count("G")
print(s)
return
area = options[i][0]
times = int(options[i][1]) - 1
if area == "R":
c[times] = list(''.join(c[times]).replace("G","A").replace("B","G").replace("A","B"))
elif area == "C":
changeColumn(m,c,times)
options.remove(options[i])
countGold(c,options,i)
countGold(colors,stroke,0)
Got everything right except for some problems. I exceeded the Time Limit of 4 seconds. I know that making colors takes up a lot of time. Is there any way to do this without generating the 2d array?
UPDATED CODE (doesn't work)
import sys
M = int(input())
N = int(input())
K = int(input())
dup = []
numR = 0
numC = 0
for i in range(K):
choice = input().split()
if choice not in dup:
if choice[0] == "R":
numR += 1
elif choice[0] == "C":
numC += 1
dup.append(choice)
print((M * numR) + (N * numC) - (2*numR*numC))
Let me put all that discussion in comments into the code:
import sys
M = int(input())
N = int(input())
K = int(input())
dup = set()
result = {'numR': 0, 'numC': 0}
def update(char, num):
if char == 'R':
result['numR'] += num
elif char == 'C':
result['numC'] += num
for i in range(K):
choice = input().split()
if choice in dup:
dup.remove(choice)
update(choice[0], -1)
else:
dup.add(choice)
update(choice[0], 1)
numR = result['numR']
numC = result['numC']
print((M * numR) + (N * numC) - (2*numR*numC))
The code sent by Freakish still doesn't work for some reason. Here is an updated code that works:
import sys
rw = sys.stdin.readline
M = int(rw())
N = int(rw())
choices = set()
K = int(rw())
for i in range(K):
g = input()
if g in choices:
choices.remove(g)
else:
choices.add(g)
numR = 0
numC = 0
s = 0
for choice in choices:
if choice[0] == "R":
numR += 1
elif choice[0] == "C":
numC += 1
for choice in choices:
if choice[0] == "R":
# numR += 1
s += N - numC
elif choice[0] == "C":
# numC += 1
s += M - numR
print(s)

The last value in my list will not convert into integer

I am writing a code in which I take values from a user until they enter 'q'. I then have to print the EVEN numbers out in ascending order. I how to do the program, I just have run into a minor problem I do not know how to solve.
My code is:
integer = []
g = 7
while g > 1: # Initiate loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
integer = list(map(int, integer))
if num % 2 == 0:
integer.append(num)
integer.sort()
print(integer)
Running this code gives me the error that not all strings have converted. So I then erased the second if statement:
if num % 2 == 0:
integer.append(num)
Erasing this I can see that the last value in the list will not convert into an integer. I do not know why that is and I have tried numerous string-list to integer-list conversions and they all never convert the last value. Does anybody know why this is?
you can do this:
evens = []
while True: # Initiate infinite loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
num = int(num) #convert the num to int
if num % 2 == 0:
evens.append(num)
evens.sort()
print(evens)
Corrected code:
integer = []
g = 7
while g > 1: # Initiate loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
num = int(num) #convert input to integer
if num % 2 == 0:
integer.append(num)
integer.sort()
print(integer)
the issue is num is a string from user input, you must convert it to an integer like this
if int(num) % 2 == 0:
integer.append(int(num))

Python - creating random number string without duplicates [duplicate]

This question already has answers here:
How do I create a list of random numbers without duplicates?
(21 answers)
Closed 5 years ago.
I need help with creating a random string of 4 numbers without having duplicates.
Code:
from random import randint
correct = [randint(1,8), randint(1,8), randint(1,8), randint(1,8)]
usr_guess = [0, 0, 0, 0]
usr_guess_output = []
usr_guess_output_n = []
print(correct)
Also, if you could help me get the user input without needing commas that would be great!
Full code:
from random import randint
correct = [randint(1,8), randint(1,8), randint(1,8), randint(1,8)]
usr_guess = [0, 0, 0, 0]
usr_guess_output = []
usr_guess_output_n = []
print(correct)
guesses = 0
print('Welcome to Mastermind. Guess the combination of numbers between 1 and 8. If you get the correct number and place, a \'*\' will be printed. If you get the correct number but wrong place, a \'-\' will be printed. If you get it wrong completely, a \'#\' will be printed. The position of the output does not correlate to the positions in the actual list of numbers.')
while(True):
usr_guess_output_n = []
usr_guess_output = []
correct_count = 0
guesses += 1
# try: #Makes sure that the program still works even if the user messes up the input
usr_guess = input('Guess at the numbers (separate with commas) > ').split(',') #Splits the user input into a list of integers
usr_guess = [int(x) for x in usr_guess ] #Converts all list items into integers for comparisons
print('')
i = 0
for i in range(0,4): #Iterates the lists to check for comparisons
if correct[i] == usr_guess[i]:
usr_guess_output.append('*')
correct_count += 1
elif correct[i] in usr_guess:
usr_guess_output.append('-')
else:
usr_guess_output.append('#')
if(correct_count > 3):
break
for i in usr_guess_output:
if i == '*':
usr_guess_output_n.append('*')
for i in usr_guess_output:
if i == '-':
usr_guess_output_n.append('-')
for i in usr_guess_output:
if i == '#':
usr_guess_output_n.append('#')
print(str(usr_guess_output_n).replace(',','').replace('[','').replace(']','').replace('\'',''))
# except:
# print('something went wrong. you probably input something other than an integer')
# guesses -= 1
print('\nIt took you ' + str(guesses) + ' guesses!')
input('Press enter to exit')
How about utilising a while loop?
correct = []
#list long enough?
while len(correct) < 4:
#create random number
rand_num = randint(1, 8)
#not in the list?
if rand_num not in correct:
#include in list
correct.append(rand_num)

Computer guessing a user-selected number within a defined range

This is my code for a game in which the computer must guess a user defined number within a given range. This is a challenge from a beginners course/ book.
I'd like to draw your attention to the 'computerGuess()' function. I think there must be a more eloquent way to achieve the same result? What I have looks to me like a botch job!
The purpose of the function is to return the middle item in the list (hence middle number in the range of numbers which the computer chooses from). The 0.5 in the 'index' variable equation I added because otherwise the conversion from float-int occurs, the number would round down.
Thanks.
Code:
# Computer Number Guesser
# By Dave
# The user must pick a number (1-100) and the computer attempts to guess
# it in as few attempts as possible
print("Welcome to the guessing game, where I, the computer, must guess your\
number!\n")
print("You must select a number between 1 and 100.")
number = 0
while number not in range(1, 101):
number = int(input("\nChoose your number: "))
computerNumber = 0
computerGuesses = 0
higherOrLower = ""
lowerNumber = 1
higherNumber = 101
def computerGuess(lowerNumber, higherNumber):
numberList = []
for i in range(lowerNumber, higherNumber):
numberList.append(i)
index = int((len(numberList)/2 + 0.5) -1)
middleValue = numberList[index]
return middleValue
while higherOrLower != "c":
if computerGuesses == 0:
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "l":
higherNumber = computerNumber
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "h":
lowerNumber = computerNumber + 1
computerNumber = computerGuess(lowerNumber, higherNumber)
print("\nThankyou. My guess is {}.".format(computerNumber))
computerGuesses += 1
higherOrLower = input("\nHow did I do? If this is correct, enter\
'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ")
print("\nHaha! I got it in {} attempt(s)! How great am I?".format\
(computerGuesses))
input("\n\nPress the enter key to exit.")
Like this ?
import math
def computerGuess(lowerNumber, higherNumber):
return int((lowerNumber+higherNumber)/2)

Broken binary converter. Index error

i have no idea why this is broken. Also dont tell me to use python's built in function because this is designed for some practice not to actually be used. It is binary to decimal that is broken. It has a index error with the variable 'index'
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu
this doesn't seem right
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
you never enter this loop, do you?
a better loop would be something like
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
also, since you're just practicing, you should find a better way to jump from menu to functions and back. you're doing recursive calls, which is a waste of stack, i.e. your functions actually never finish but just call more and more functions.
Some fixes:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION

Categories