how do i print eachother while sentence? - python

i coded 6number from1 to 45 without duplicating
from random import *
lotto = []
while True:
m = randrange(1, 46)
if m not in lotto:
lotto.append(m)
if len(lotto) == 6:
break
but I want to make different 6number as wanting
example, if i input 2 {1,21,23,43,35,26} {21,15,6,37,28,7}
but with this code,
for i in range(init(input""))
print(lotto)
same result is printed
i wanna different result
how do i add it?

you can put the lotto genrator in a function :
from random import randrange
def give_lotto():
lotto = []
while True:
m = randrange(1, 46)
if m not in lotto:
lotto.append(m)
if len(lotto) == 6:
break
return(lotto)
then print( result in the loop) in your example it gives you the same result because it doesn't generate it again it just prints the final result twie that's why putting it into a function will give your intended result
for i in range(int(input())):
print(give_lotto())

If I understand correctly you are wanting to produce a list of n lotto combinations
import random
def n_lotto(n):
lotto_draws = []
for i in range(n):
balls = random.sample(range(1, 46), 7)
lotto_draws.append(balls)
return lotto_draws
As a side note as you appear to be new a quick FYI. Python is a slow language butit has a lot of powerful builtin functions most of which are written in C and are therefore blazing fast, they are also extremely well tested meaning that it is almost always a good idea to have a quick google for a builtin if what you are trying to do is relatively simple as:
it'll be easier to read
it'll be faster
you're less likely to have bugs

I'm not completely sure what you're after but as a note using
lotto.append(m.pop())
in place of
if m not in lotto:
lotto.append(m)
Is faster and removes the poped character from m (preventing any logic errors in the future)
edit:
Apologies I haven't used the random module in a while and I thought randrange was generating a list not a number, therefore pop will not work and the original implementation is correct. However, for this purpose random.sample is a far better function to use

Related

Python random number loop with different outcomes each time

I’ve been working on a school project and need to do a loop consisting of a couple random numbers but I need them to output a different number each time. The code I’ve been using for the random numbers is this.
import random
a=random.randint(1,9)
I’m new to coding and just starting getting into python for fun and have looked everywhere for how to complete this loop but I can’t find anything that works.I know this code does not include a loop and the loop I was using before was “while True” and “for i in range” Thanks
You have not created any loop yet. You're generating random integer only once.
In order to generate more of them you have to use something like a for loop.
If you're familiar with the concept of range then this is a simple example of generating x-number of random integers.
import random
x = 10
for i in range(0, x):
a = random.randint(1, 9)
print(a)
I am assuming you are doing something like this. Your loop needs to call the random.randint function on each iteration of the loop.
a = random.randint(1,9)
for i in range(5):
print(a)
What you should be doing is this
for i in range(5):
print(random.randint(1,9))
If you want to have 5 values between 1 - 9 without repetition you can use the sample function of the random module. This will select n values from a list and store them in a new list.
array = random.sample(range(1, 9), 5)
for elem in array:
print(elem)
But if you want to have a new random value between 1 and 9 every iteration and you dont care if a number is repeated I would go with the answers the others already gave you.
Random works with a seed, with the same seed the same output
Easiest way to achieve that you want, you will have a different seed each time you run your program
import random
from datetime import datetime
random.seed(datetime.now())
for _ in range(10):
a=random.randint(1,9)

Use Random.random [30,35] to print random numbers between 30,35. Seed(70)

Probably a simple answer, not sure what I am missing. For a homework assignment I have to use random.random() to generate numbers between 30 and 35. The seed has to be set to 70 to match the pseudo-random numbers with the grader. This wasn't in my lecture so I am a little stumped as to what to do.
I have:
import random
def problem2_4():
print(random.random(30,35))
But this is clearly wrong.
The assignment says the output should look like (note: for the problem i use def problem2_4() just for the assignment grading system)
problem2_4()
[34.54884618961936, 31.470395203793395, 32.297169396656095, 30.681793552717807,
34.97530360173135, 30.773219981037737, 33.36969776732032, 32.990127772708405,
33.57311858494461, 32.052629620057274]
The output [blah, blah, blah] indicates that it is a list of numbers rather than a series of numbers printed one-by-one.
In addition, if you want random floating point values, you'll need to transform the numbers from random.random (which are zero to one) into that range.
That means you'll probably need something like:
import random # Need this module.
def problem2_4():
random.seed(70) # Set initial seed.
nums = [] # Start with empty list.
for _ in range(10): # Will add ten values.
nums += [random.random() * 5 + 30] # Add one value in desired range.
print(nums) # Print resultant list.
Of course, the Pythonic way to do this would be:
import random
random.seed(70)
print([random.random() * 5 + 30 for _ in range(10)])
Bit that might be a bit ahead of where your educator is working. Still, it's good to learn this stuff as early as possile since you'll never be a Pythonista until you do :-)
The function that you are looking for is randint, which returns an integer (whole number) between the specified minimum and maximum values.
So the solution would be
random.randint(30, 35)
Python Docs

Generate Random List of Random Length (sort of)

I'm working on a problem from this website:
https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
The exercise I'm working on asks us to generate two random integer lists of different lengths. Here is what I've got:
import random
n1 = random.sample(range(1,30), random.randint(5,20))
n2 = random.sample(range(1,40), random.randint(21,40))
n3 = set(n1) & set(n2)
print(n3)
For some reason this runs sometimes and not others.
Here is a screenshot of it not running.
It clearly has something to do with the size of the ranges because the larger I make them the less often I return an Error. But, I'd like to understand why it throws the error in the first place so I can avoid it all together.
Thanks in advance.
random.sample(population,k) returns unique k elements from population
In your case, your population is [1,2,3,...39]. Your k = random.randint(21,40). So you will be getting an exception whenever the k value chosen is 40.
This is documented for random.sample:
Return a k length list of unique elements chosen from the population
sequence. Used for random sampling without replacement.
Your screenshots show you use:
n2 = random.sample(range(1, 30), random.randint(21, 40))
That means you could try to take up to 40 samples from a pool of 30 numbers which, without replacement, is not possible. The examples you gave in code in the actual question don't represent what you're trying to do in reality.

Python memory error in CPU and wall time

I am trying to do a function to calculate the modular exponential of three variables and compare the CPU and wall time when:
e=2^n and e=2^n-1
Here is my code:
from random import choice
import random
def question_3(m,n):
list = []
for i in range(2,2**m):
flag=True
for num in list:
if(i%num==0):
flag=False
if(flag):
list.append(i)
p = choice(list)
a = randint(1,int(p)-1)
e = pow(2,n)
return pow(a,e,p)
time t = question_3(150,100)
But when I enter m and n with huge numbers, it gives me:
range() result has too many items
That's because you're forcing range to generate too much data. For example, range(2, 2*1234567891011) will generate a list with the length of 2*1234567891011-2, isn't it a bit too much?
Try using xrange() instead, it generates the data when needed, instead of making all of the data when you call it.
Change it to this:
for i in xrange(2,2**m):
Looks simple, but it has a huge difference. Hope this helps!

In python is it better to have a series of += or to append to a list and then sum?

Both of these bits of code do the same thing:
g = 1
g += 2
g += 17
print g
g = []
g.append(1)
g.append(2)
g.append(17)
print sum(g)
I was just wondering if one of these ways is "better" or more Python than the other.
My own testing with the following bit of code:
import time
n = 1000000
A = time.clock()
w = 0
for i in range(n):
w += i
print w, time.clock() - A
A = time.clock()
g = []
for i in range(n):
g.append( i )
print sum(g), time.clock() - A
seems to indicate that the first method is slightly faster, but I may be missing something.
Or I may be missing an entirely better way to perform this type of operation. Any input would be welcome.
It's not a matter of being Pythonic, it's a matter of what you want to achieve.
Do you want to save the values that constitute the sum so they can be referred to later? If so, use a list. If not, then why even bother with a list? It would just be a convoluted and less efficient way to do the same thing -- just add the values up. The direct addition method will obviously be faster because all you're doing is adding to a variable (very cheap), instead of mutating a list (which has a greater cost). Not to mention the evident memory advantage of using the direct addition approach, since you wouldn't be storing useless numbers.
Method A is
Add the integers
Method B is
Create a list of integers
Add the integers
If all you want to do is
Add the integers
I'd go with method A.
The only reason to have the second method is if you plan to use the list g elsewhere in the code. Otherwise, there isn't a reason to do it the second way. Making a list and then summing its values is a lot more costly then just incrementing a variable.
Moreover, if incrementing g is your goal, then why not do that? "Explicit is better than implicit" is a motto of Python. The first method explicitly increments g.
Also, the list may confuse people. When they see your code, they will think you need the list and plan to use it elsewhere. Not to mention that g is now a list. If g is supposed to be a number, having it be a list is not good and can lead to problems.
Finally, the first solution has less syntax (always a plus if it does the same job efficiently).
So, I'd go with method 1.
Absolutely the first, for many reason, first of all memory allocation (N integer instead just one) and performance: in real world application the GC overhead would pop out.
edit: disregard this, I can see now that it is not generally true, and is only true for specific values of x.
Ok, so I can see that making a list should be inefficient, but then why does fun2 run more quickly in this instance? Doesn't it essentially create a list and then sum over it?
import timeit
def fun1(x):
w = 0
for i in range(x):
w += i
return w
def fun2(x):
return sum([i for i in range(x)])
timer = timeit.Timer(stmt='fun1(10000)', setup='from __main__ import fun1')
print timer.timeit(number=10000)
timer = timeit.Timer(stmt='fun2(10000)', setup='from __main__ import fun2')
print timer.timeit(number=10000)

Categories

Resources