My code it generates a random number it checks if it is in the list if it is it generates another random number and then it checks if it is equal or not and shows the result and repeats the process. But when I start the code it generated the normal number but it repeats the numbers and it shouldn't repeat the number. What do I do?
from random import randint
import os
n = 0
numsort = 14564487
attempt = 0
numbers = []
while n < 100:
num = randint(10000000, 99999999)
if num in numbers:
num = randint(10000000, 99999999)
numbers.append(num)
attempt += 1
if num == numsort:
print(f'{num}' + '\033[32m' + ' Right number' + '\033[0m')
print(f'After {attempt} attempts it was')
break
if num != numsort:
print(f'{num}' + '\033[31m' + ' Wrong number' + '\033[0m')
print(f'Attempt # {attempt}')
os.system('clear')
The issue here is a simple one. The primary problem is with this code snippet:
num = randint(10000000, 99999999)
if num in numbers:
num = randint(10000000, 99999999)
numbers.append(num)
Translating this to English, we have:
Generate a random seven-digit integer
If the integer is in our list of numbers then regenerate it and add it to the list
The problem you have here is that you have no guarantee that the regenerated number won't also be in the list. The chance of this happening will grow as the list grows. And, since your loop variable is never updated, this list will grow infinitely.
To fix this problem, you have two possible solutions. For small lists, you can continue on with your strategy of regenerating numbers and replace the if with a while:
num = randint(1000000, 9999999)
while num in numbers:
num = randint(1000000, 999999999)
numbers.append(num)
Note that this will only work while the desired size of your list is much smaller than the range of possible values being generated. As you fill up the list, the chance of collisions between the range of possible values and actual values will increase, causing the while loop to run longer.
Alternatively, you can use sample to choose your values, which would replace the entire loop:
numbers = random.sample(range(1000000, 10000000), n)
Note here that the use of range means that this is actually just as space efficient as the previous solution and will guarantee unique values.
Related
I am currently attempting to write a simple bit of python 3 code that allows the user to tell the program which prime number it wants to find and then return the number to the user. I have hit a roadblock because I need to check if the "newprime" value is in fact a prime, which requires me to divide the value by all the previous prime numbers ("primes") and then checking if the answer is a whole number or not. Here is the current program
import numpy
primes = [2]
print("the how many-th prime would you like to calculate?")
numberOfPrime = int( input() )
x = 0
while x <= numberOfPrime:
notprime = 0 #placeholder, should be all numbers which when divided by any of the set "primes" gives a whole number
while newprime == notprime:
newprime = primes[x] + 1
primes.append(newprime)
print(primes)
x += 1
print(primes[numberOfPrime], " is the ", numberOfPrime, "-th prime number", sep="")
As you can see, I added a comment where I would have to insert the missing part.
How do I best approach this?
Recently I was given a challenge to my coding skills by my teacher since he saw that I was already knowledgeable in what he was teaching. The question is as follows.
Create a program that prompts the user for 2 numbers. The program will then display all the prime numbers in between the two given numbers, including the given numbers. Note: You cannot assume the first input is bigger than the second input.
So I took this question and built a fairly simple algorithm and ran it and it worked. I opened it today to find out for some reason my output is occasionally wrong, for example when you input 8 and 29 I get 27. I am looking for HINTS as to what is wrong with my logic because I cannot for the life of me figure out what Im doing wrong. I dont want straight up fixes because I would like to learn as much from this and doing it as much as possible by myself.
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
numList = []
#Removing Even Numbers
for num in range(numbers[0],numbers[1] + 1):
if num % 2 != 0:
numList.append(num)
#Checking For Prime Numbers
for currNum in numList:
#Set Start number to divide
i = 2
while i < currNum:
#Checks if the currNum can be divisble by i and is a whole number
if currNum % i != 0:
i = i + 1
else :
numList.remove(currNum)
break
print(numList)
From what I have learned from testing this out it seems like 27 is never checked during my for loop or while loop even though it is in the numList array.
Never remove items form a list you are iterating over.
Instead create a new list:
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
primes = []
for num in range(numbers[0], numbers[1] + 1):
#Set Start number to divide
i = 2
while i < num:
#Checks if the currNum can be divisble by i and is a whole number
if num % i == 0:
break
i += 1
else:
primes.append(num)
print(primes)
I'm trying to create a code that will print every number in a range set by the user, and then identify how many numbers in that range are odd numbers and how many are even.
I've tried a few different formats, but I'm very much a beginner and can't seem to nail down where I'm going wrong. I'm trying to keep the code as simple as possible.
for i in range(x,y+1):
print(i)
range = (x,y+1)
count_odd = 0
count_even = 0
for n in range:
if n%2==0:
count_even = count_even+1
else:
count_odd = count_odd+1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Currently when I run this, even numbers always comes to 0 and odd to 2.
On line 4 you have:
range = (x,y+1)
This is the tuple (x, y+1) not the range between them. So when you loop through it you are only looping through those two numbers. I assume in your case they are both odd. I would recommend removing that line and starting your second for loop like this:
for n in range(x, y + 1):
range is a builtin function, which returns an iterable from [start, end). You likely want something like:
count_odd = 0
count_even = 0
for n in range(x,y+1):
if n % 2 == 0:
count_even = count_even + 1
else:
count_odd = count_odd + 1
print("Number of even numbers :", count_even)
print("Number of odd numbers :", count_odd)
There's no point for a loop. If your range consists of even elements, then half of values is even and half is odd. If it consists og odd elements and starts from odd value then half+1 is odd and half-1 is even. It starts with even value then it's opposite.
I just have to find the most and least guessed numbers in an array of random numbers in python. Here is my code by far:
import time
import random
random.seed()
def breakPIN(num):
end = 0
list = []
for i in range(0,9999):
list.append(random.randint(0,9999))
printNow(list)
if (num == 4):
end =9999
elif (num == 6):
end=999999
p2b=random.randint(0,9999)
time1=time.time()
num=random.randint(0,end)
while (num!=p2b):
num=random.randint(0,end)
list[num]=list[num]+1
time2=time.time()
lowest=list[i]
for i in range(0,len(list)):
if(lowest > list[i]):
lowest=list[i]
printNow(lowest)
highest=list[i]
for i in range(0,len(list)):
if(highest<list[i]):
highest=list[i]
printNow(highest)
return time2-time1
times=[]
for i in range(0,10):
times.append(breakPIN(6))
sum=0
for i in range(0,len(times)):
sum = sum + times[i]
printNow(sum/len(times))
printNow(times)
As you can tell I can already find the largest number as well as the smallest numbers guessed. Any pointers as to how I can find the most and least guessed numbers would be very much appreciated.
To find the most and the least guessed numbers you could use Counter:
import random
from collections import Counter
def most_least_guessed(elements):
counts = Counter(elements)
most_guessed, _ = counts.most_common(1)[0]
least_guessed, _ = counts.most_common()[-1]
return most_guessed, least_guessed
random.seed(42)
lst = []
for i in range(0, 9999):
lst.append(random.randint(0, 9999))
most, least = most_least_guessed(lst)
print(most, least)
Output
1106 9998
To determine the most and least guessed numbers you need to know how many times each number was guessed. Once you know how many times each one was guessed you can just find the min and max.
To record how many times each number was guessed you will need an array that is the same length as the count of available numbers.
This is called a histogram.
I'm doing a college project which started off with printing out all the prime numbers between two given inputs. I was later told that it had to be somewhat relevant to my course, Network Management, so I wanted to add a password generator onto the end of my script(for network security)
I have all the code written out but I have a problem with it not being able to use a random prime number in the list I have printed out. It only uses the last number printed and I understand why but is there anyway I can make it so that does use a random prime number or will I have to store the numbers somewhere?
#A program to count the prime numbers from a given start to a given end
#importing math function
import math
import os, random, string
#Input the number to start counting from
Starting_number = input("Enter the starting number: ")
#Input the number to end the count on.
Ending_number = input("Enter the number you want to count up to: ")
#if Starting_number is less than 0 it will print out a suitable message.
if Starting_number < 0:
print 'Invalid entry, please enter a positiv number. \nWill count from ',Starting_number, 'to 0 and begin prime number count to',Ending_number, '.'
#If Ending_number is less than or equals to 0 then it will print out a suitable message.
if Ending_number <= 0:
print 'Invalid entry on last input \nPlease enter two positive numbers for the count to work.'
#Starting loop as long as the current count is between Starting_number and Ending_number
for num in range(Starting_number, Ending_number):
#
if all(num%i !=0 for i in range(2,num)):
print num
if num >= 1 and num <= 100:
length = 4
chars = string.ascii_letters + string.digits + '!##$%^&*()'
random.seed = (os.urandom(1024))
print ''.join(random.choice(chars) for i in range(length))
if num >= 101 and num <= 200:
length = (Ending_number / Starting_number) * 5 + 11
if length >= num:
length = num / 100
chars = string.ascii_letters + string.digits + '!##$%^&*()'
random.seed = (os.urandom(1024))
print ''.join(random.choice(chars) for i in range(length))
As you detect prime numbers add them to a list.
Instead of just
print num
add it to a list like so:
primes.append(num)
then you can select a random item from your 'primes' list:
from random import choice
print choice(primes)
I really wanted to add this as a comment but I do not have enough credits to add a comment. For password generator, you do not want it to be a prime number. You should just randomly choose a number. If you have a 32 bit number, you have more entropy if the number is randomly in the full 32-bit space. If you limit it to only prime numbers, you have considerably reduced the space. Not directly related to what you are asking but it may be useful to know.