will my 6 digit number code work? - python

i need to generate all 6 digit number for a word list
will this code work?
from random import randint
list = [111111]
print ('111111')
while True:
number = randint(100000,999999)
if not number in list:
list.extend(str(number))
print(number)

Instead of randomly trying out numbers and then adding them one character at a time (look into append() rather than extend()), simply send the range() object to list():
numbers = list(range(100000, 1000000))
Note that I've called it numbers rather than list, to avoid masking list().
If you want each number as a string, map them to strings:
numbers = list(map(str, range(100000, 1000000)))

Your method would work but would be very slow. I would suggest using list comprehension to generate the list of numbers. If you need it to be randomized, there is a shuffle method as part of the random module.
from random import shuffle
#if you wanted just numbers
x_all_numbers = [i for i in range(100000, 999999)]
#if you wanted strings of different numbers
x_str_numbers = [str(i) for i in range(100000, 999999)]
print(x_all_numbers[0:10])
shuffle(x_all_numbers)
print(x_all_numbers[0:10])
To show that this will work, I included the output:
[100000, 100001, 100002, 100003, 100004, 100005, 100006, 100007, 100008, 100009]
[783780, 170070, 270425, 119709, 194098, 617834, 740368, 420370, 993130, 712673]

Related

how to use assignment operator in list comprehension

i want to create a list of random integers
I want the value of num to be a random integer The following line of code gives me a syntax error
invalid syntax
i just want to know that is there any way to do this using list comprehension
numbers = [num for num in range(1,6) num = random.randint(1,10)]
Looking at your requirements, you aren't required to assign num.
To generate a list of random numbers simply do:
numbers = [random.randint(1,10) for _ in range(1,6)]
You can alternatively do:
numbers = random.sample(range(1,11),k=5) # k is the repeating count
You don't need the num variable, just use the random.randint() call.
numbers = [random.randint(1,10) for _ in range(1,6)]

Kaprekar's constant (sorted(numbers) [duplicate]

This question already has answers here:
How to sort digits in a number?
(5 answers)
Closed 10 months ago.
Okay I've broken down step by step what the function needs to do.
create random number, sort ascending and descending(needs both), subtract, sort the new number ascending and descending and repeat this until the number you get from subtraction is 6174 (preferably I'd like it to loop a time or two after as it should stay at 6174 "which is why it's called Kaprekar's constant".
What I currently have is a random number between 1000,9999. I kept getting (TypeError: 'int' object is not iterable) so I created a list and appended the random number to the list. I'm having issue with sorting the number ascending/descending.
import random
numbers = []
n = random.randint(1000,9999)
print(n)
numbers.append(n)
sorted(numbers)
print(numbers)
So I create a blank list, random number is generated and then printed, the number is then .append to the list and should sort and print the list.
The current output I get is
6988
[6988]
The expected output of what is written is
6988
[6889]
I attempted to use
print(numbers.sort(reverse=True))
this gave "None"
I was expecting it to give [9886]
The only reason this is happening is that it wants to sort multiple items in the list opposed to sorting the numbers in the single item. I'm just not sure how to resolve it.
I'm not quite following you but I think you would like to have the individual digits of the randomly generated number as a list.
If so try doing:
my_str = str(n)
for my_char in my_str:
numbers.append(int(my_char))
instead of:
numbers.append(n)
The first problem is a list.sort method returns None.
import random
numbers = []
n = random.randint(1000,9999)
numbers.append(n)
numbers.sort(reverse=True)
print(numbers)
Also reverse=True does not reverse the element but it reverses the list.
You can check this by this
import random
numbers = []
n = random.randint(1000,9999)
numbers.append(n)
numbers.append(10)
print(sorted(numbers))
print(sorted(numbers,reverse=True))
If you want to reverse element then use this one
import random
lst = []
num = random.randint(1000,9999)
print(num)
lst.append(num)
func = lambda e:int(str(e)[::-1]) # lambda function
lst = list(map(func,sorted(lst)))
print(lst)
NOTE:
1000 after reversing become 1 'cause int('0001') is 1.
4590 after reversing become 954 'cause int('0954') is 954.

How to get items from a list > than X

I have a function called "first_funtion()" that returns a list of 100 instances of a class.
Then I want to define a second function that is going to create a new list with random instances taken from the output list of first_function(), something like:
first_funtion()
def second_function(list2, N):
list2 = list2(random.choice(first_function()))
The thing is that I want list2 to be always greater than N, so if N = 5 I want the random list2 to be more than 5 instances. If N = 10 then I want the list to be more that 10 instances.
How can I do that?
You can first create the list using first_function, then draw a random integer in the range between N and the length of the list and then draw a random sample from the list.
import random
def second_function(list2, N):
len_list = len(list2)
length = random.randint(N, len_list)
return random.sample(list2, length)
You can do it by using two random function;
Use first one to choose a value of N from the range excluding N to including lenght of list1, i.e, (N, len(list1)]
x = random.randint(N+1, len(list1)
And use second one to choose x number of values from list_1;
random.choices(list1, k=x)
So, the code will look something like this:
import random
def second_function(list1, N):
x = random.randint(N+1, len(list1))
y = random.choices(list1, k=x)
print(y)
Here randint(start, stop) includes both start and stop numbers while generating random integer. It will generate a random number from the inclusive range.
Andrandom.choices () function returns total k number of random items from any list.
Note: You may get repeated values if you're using random.choices (). So, use random.sample() function when you want to choose multiple random items from a list without repetition or duplicates.
You can visit on this link and explore more related to this.
As the random.choice() function always picks one element from the list, so you can iterate through the list more than N number of times and use random.choice() each time. And you can also use random.randint() to get a random number above N, to be used in the range function for the for loop.
import random
def second_function(list2, N):
for i in range(N,random.randint(N,len( first function() ))) :
list2.append(random.choice(first_function()))
return list2

How to get the position of a random number generated in a python list.?

I have a numeric list. I need pick a random number in a numeric list and know position number found in list.
random.choice(name_list) just find a random number but I am at the same time in need of a random number position
generate random indexes to use instead.
import random
a = [1,2,3,4,5]
rand_num = random.randrange(len(a))
print(a[rand_num])
You could also get the index and the random number in one operation using enumerate()
index,number = random.choice(list(enumerate(a)))
This not very efficient however and, if you're doing this often or on a very big list, you should do it in two steps
index = random.randrange(len(a))
number = a[index]
import random
sample_list = [1,2,3,4,5]
# this should be work for multiple same value indexes
# EX: sample_list = [1,2,3,2,2]
# if random number is 2 than below code will print indexes 1, 3, 4
random_number = random.choice(sample_list)
for i in [i for i,x in enumerate(sample_list) if x == random_number]:
print(i) # print the indexes or random number

Randomly generate list of tuples of random numeric string of random length

For simulation purposes, I would like to generate a list of string pairs. Each string pair consists of two strings. Each string consists of numerical digits generated randomly. The length of string is of random number as well. How to achieve this function using Numpy?
This is an infinite generator. You can either take a slice of it (shown in the last line), or iterate over it directly:
import itertools
import random
def one_string():
l = random.randint(1, 5)
return "".join(random.choice("0123456789") for _ in range(l))
def string_pairs():
while True:
yield one_string(), one_string()
print(list(itertools.islice(string_pairs(), 10)))
produces:
[('840', '452'), ('20', '4651'), ('784', '589'), ('1', '08211'), ('809', '2103'), ('48975', '46884'), ('307', '83913'), ('88512', '212'), ('57', '11772'), ('38', '14')]
You don't need numpy to get such simple result. All you need is the list comprehension with random.randint as:
>>> from random import randint
>>> [(str(randint(0, 99999)), str(randint(0, 99999))) for _ in range(10)]
Above solution will return 10 pairs of random number strings, with maximum length of each string to be 5 digit. random.randint here will generate random number between 0 to 99999, and since the selection is random, the number of digits will be random too. Then simply type-cast them to string to get your desired result.
Sample result:
[('8655', '9023'), ('7398', '7465'), ('8595', '4994'), ('8532', '9251'), ('196', '5911'), ('4219', '6240'), ('7628', '8162'), ('256', '9675'), ('4466', '4814'), ('6459', '3798')]

Categories