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.
Related
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I was working on a list and I noticed something.
For example, this piece of code is deleting odd numbers from a list while looping over it.
numbers=[x for x in range (100)]
for nb in numbers:
if nb%2 == 1:
del numbers[numbers.index(nb)]
When you add a counter to see the total iterations you get:
numbers=[x for x in range (100)]
counter=0
for nb in numbers:
if nb%2 == 1:
del numbers[numbers.index(nb)]
counter +=1
The result is counter = 51.
However, if you add the operator list() on the for loop:
numbers=[x for x in range (100)]
counter=0
for nb in list(numbers):
if nb%2 == 1:
del numbers[numbers.index(nb)]
counter +=1
This time the result is counter = 100.
I would like to know why and what is the role of the operator list() here.
Note: if you print numbers and list(numbers) they are identical.
Your second example makes a copy of the list. You iterate through that copy, which remains at 100 elements regardless of what you do to numbers in the meantime.
Your first example alters the list as you iterate through it, a well-documented and well-know bad idea. If you print the list and current value of nb on each iteration, you'll see how the progression works. A simplistic view is that the Python interpreter walks through the list by index (position); when you shorten the list, everything shifts down one position, but that index still increments, thus skipping over one item.
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
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]
I have a list of numbers, all of which need to be divided by the same number. I can do this, no problem, but how do I create a new list featuring these new quotients?
I have tried:
for n in numbers:
newnumbers = []
newnumbers.append(n/649.00)
but it only gives me one number, the quotient of the last number in the list, back.
Instead of a loop you can also use a list comprehension (see https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
newnumbers = [n/649.00 for n in numbers]
It's executing your code literally.
for each element in numbers:
set newnumbers equal to an empty list
add a value to newnumbers
So yes, of course you'll end up with a list with only one value in it. What you want to do is move the list initialization out of the loop.
newnumbers = []
for n in numbers:
newnumbers.append(n/649.00)
Is there a way to get the last number from the range() function?
I need to get the last number in a Fibonacci sequence for first 20 terms or should I use a list instead of range()?
Not quite sure what you are after here but here goes:
rangeList = range(0,21)
lastNumber = rangeList[len(rangeList)-1:][0]
or:
lastNumber = rangeList[-1]
by in a range, do you mean last value provided by a generator? If so, you can do something like this:
def fibonacci(iterations):
# generate your fibonacci numbers here...
[x for x in fibonacci(20)][-1]
That would get you the last generated value.
I don't think anyone considered that you need fibonacci numbers. No, you'll have to store each number to build the fibonacci sequence recursively, but there is a formula to get the nth term of the fibonacci sequence.
Binet's Formula
If you need the last number of a list, use myList[-1].
Is this what you're after?
somerange = range(0,20)
print len(somerange) # if you want 20
print len(somerange)-1 # if you want 19
now if you want the number or item contained in a list...
x = [1,2,3,4]
print x[len(x)-1]
# OR
print x[-1] # go back 1 element from current index 0, takes you to list end