one more question. I am a first year CS student who has to do this on paper, so I am not able to import any programs to solve the problem.
I have been asked to create a psuedo-random set of integers, and then to multiply the products of the integers using a function def product (n). I know this code is really wrong but I'm not really sure what to do at all! Here is what I have so far:
def product(n):
product = j*i
for j in range (20):
i=random.randrange(1,4,1)
print ("The set of numbers is", i)
You didn't specify the range for the integers, but I think this does what you want:
import random
def product(n):
lower_bound = 1
upper_bound = 10
result = 1
for i in range(n):
result *= random.randint(lower_bound, upper_bound)
return result
I would go with
import random
def product(n):
return reduce(lambda x,y:x*y,(random.randint(1,3) for i in xrange(n)))
Several things:
you can't really generate random numbers without importing or writing your own pseudorandom generator
look up reduce. It's probably the preferred method here.
if you can import the operator module, use operator.mul instead of lambda x,y:x*y
If n is the number of generated numbers:
import random
def product(n):
random_list = [random.randint(0,n) for r in xrange(n)]
return reduce(lambda x,y : x*y, random_list)
What do you want? Multiply Integers and display their products? See this :
def product(numberOfIntegers) :
finalResult = 1
for i in range(1,numberOfIntegers) :
randomNumber = random.randrange(1,4,1)
finalResult = finalResult * randomNumber
return finalResult
Related
how to get a list of 1000 random float numbers without dublicates and find their mean value in python?
import random
rnd_number=random.random()
def a():
l=[]
m=1
for i in range(1000):
l.append(rnd_number)
return l
for i in l:
m=m+i
return m//b
print (a())
i am probably wrong with returning l before the other operation but when the code works there are 1000 of the same float numbers on the screen
Hope this would help!
import numpy as np
import random
N=10
# number of digits you want after the .dot sign
# more digits .dot ensure mo duplication
Npts=1000
# number of random numbers
num=[]
# initialize the array
for m in range(1000):
nm=round(random.random(), N)
# local variable to take the random numbers
num.append(nm)
# append the random number nm to the original num array
print(num)
# printing the random numbers
# Let's check is there is a duplication or not
my_num=set(num)
if len(num)!=len(my_num):
print("Duplication in the array")
else:
print("NO duplication in the array")
# Calculating mean
avg=sum(num)/Npts
print(avg)
If you want to have distinct random numbers, you have to draw number on every loop iteration. To avoid duplicates you can use set, which stores unique values.
import random
def a():
mySet = set()
while len(mySet) < 1000:
mySet.add(random.random())
return mySet
print(a())
import random
def a():
s=0
m=0
l=[]
for i in range(1000):
rnd_number=random.random()
l.append(rnd_number)
for n in l:
m=m+n
m=m/len(l)
for k in l:
s=s+(k-m)**2
s=(s/len(l))**(1/2)
return l,m,s
print (a())
i did like this and got the right answers for both the mean and standart devaiation of 1000 random float numbers
(i checked it with 4 actually but i think it is gonna work for 1000 too)
I generated random numbers, and easily calculated their means. My question is, however, how can I see the numbers I generated? I'd like to save these numbers to a vector. How can I do this?
This is my code:
import random
print ("#n\tmean")
for n in (1,10,100):
sum = 0
mean = 0
for i in range(n):
sum += random.random()
mean = sum / n
print ("%d\t%g\t" % (n, mean))
Thank you in advance!
Use list comprehensions,
import random
n = 100
l = [random.random() for _ in range(n)]
mean = sum(l)/100
use a list to save all the results:
results = []
for i in range(n):
sum += random.random()
mean = sum / n
results.append(mean)
then get the output array by:
np.hstack(results)
I think you need something like this, if you want to avoid numpy.
import random
print ("#n\tmean")
meansList = []
for n in (1,10,100):
sum = 0
mean = 0
for i in range(n):
sum += random.random()
mean = sum / n
meansList.append(mean)
print meansList
Try python's in-built data structure list which I think is closes to a vector and would work for you.
vector = list()
//in the for loop
r = random.random()
vector.append(r)
Also note that lists can append lists since you have two for loops. For example you can do something like
outer_vector.append(inner_vector)
Use the numpy package
import numpy as np
my_numbers = np.random.uniform(0, 1, 100)
print np.mean(my_numbers)
You can generate the mean of random for 1, 10, 100 in one line using list comprehension:
import random
result = [(n,sum(random.random() for _ in range(n))/n) for n in (1,10,100)]
print(result)
one possible output:
[(1, 0.1269484085194036), (10, 0.6572300932440089), (100, 0.4796109974064649)]
random.random() for _ in range(n) is the generator comprehension that feeds sum, divide by n to get the mean, wrapped in an outer loop and creating tuples with value/mean
Code to run smallest divisor:
def smallesteuler():
t=0
result=[]
for no in range(11,10000):
for i in range(1,11):
if (no%i==0):
t=t+1
if(t==20):
return result.append(no)
t=0
print (smallesteuler())
This looks like Euler problem 5 - find the least common multiple of 1..20.
Your code can be rewritten as
def euler5(upto=20):
"""
Find the least common multiple of 1..upto
"""
num = upto
while True:
if all(num % factor == 0 for factor in range(2, upto+1)):
return num
else:
num += 1
however a much more efficient solution would be
from fractions import gcd
from functools import reduce
def lcm(a, b):
return a * b // gcd(a, b)
def euler5(upto=20):
return reduce(lcm, range(1, upto+1))
The first solution is O(n!), the second is O(n**2).
It looks like you're trying to collect the first 20 numbers that satisfy no%i==0. You'll have to append those numbers to result, and then return result.
def smallesteuler():
t=0
result=[]
for no in range(11,10000):
for i in range(1,11):
if (no%i==0):
result.append(no)
t=t+1
if(t==20):
return result
print (smallesteuler())
Create a function addNumbers(x) that takes a number as an argument and adds all the integers between 1 and the number (inclusive) and returns the total number.
Examples :
addNumbers(10)
55
addNumbers(1)
1
So this is a question, I have done using while loop , and it worked fine. But I am not satisfied with my code, I also did this problem using for loop and that's okay for me, but I want to know what could be the best way to improve dis code using while loop.
def addNumbers(num):
total = 1
i = 1
while i < num:
i += 1
total += i
return total
print addNumbers(10)
And here is my for loop answer :
def addNumbers(num):
my_list = list(range(num+1) )
for i in my_list:
my_list.append(i)
return sum(my_list)
If you want an O(1) algorithm that isn't brute-force, you can use Gauss's method:
def sum_numbers(n):
return (n+1)*n//2
Usually SO isn't the place for such questions, but anyway..
You can use sum() and range(). range() will return a list of numbers from 0 to n and sum will, well, sum it.
def sumNumbers(n):
return sum(range(n+1))
EDIT: And using while loop:
def sumNumbers(n):
i = 0
sum = 0
while i <= n:
sum += i
i += 1
return sum
Make use of numpy's sum routine and a generator like so,
import numpy as np
maxNumber = 10
sumOfNumbers = np.sum([(x) for x in xrange(1, maxNumber+1)])
print sumOfNumbers
The generator gives you the list of numbers & the routine adds them for you.
Let's say I need a 3-digit number, so it would be something like:
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
You can use either of random.randint or random.randrange. So to get a random 3-digit number:
from random import randint, randrange
randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop
* Assuming you really meant three digits, rather than "up to three digits".
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
If you need a 3 digit number and want 001-099 to be valid numbers you should still use randrange/randint as it is quicker than alternatives. Just add the neccessary preceding zeros when converting to a string.
import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)
Alternatively if you don't want to save the random number as an int you can just do it as a oneliner:
'{:03}'.format(random.randrange(1, 10**3))
python 3.6+ only oneliner:
f'{random.randrange(1, 10**3):03}'
Example outputs of the above are:
'026'
'255'
'512'
Implemented as a function that can support any length of digits not just 3:
import random
def n_len_rand(len_, floor=1):
top = 10**len_
if floor > top:
raise ValueError(f"Floor '{floor}' must be less than requested top '{top}'")
return f'{random.randrange(floor, top):0{len_}}'
Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.
Aside: it is interesting that randint(a,b) uses somewhat non-pythonic "indexing" to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)
Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).
You could write yourself a little function to do what you want:
import random
def randomDigits(digits):
lower = 10**(digits-1)
upper = 10**digits - 1
return random.randint(lower, upper)
Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.
import random
fixed_digits = 6
print(random.randrange(111111, 999999, fixed_digits))
out:
271533
You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:
import random
def generate_random_number(length):
return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)
import random
first = random.randint(1,9)
first = str(first)
n = 5
nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs)) :
first += str(nrs[i])
print str(first)
From the official documentation, does it not seem that the sample() method is appropriate for this purpose?
import random
def random_digits(n):
num = range(0, 10)
lst = random.sample(num, n)
print str(lst).strip('[]')
Output:
>>>random_digits(5)
2, 5, 1, 0, 4
I know it's an old question, but I see many solutions throughout the years. here is my suggestion for a function that creates an n digits random string with default 6.
from random import randint
def OTP(n=6):
n = 1 if n< 1 else n
return randint(int("1"*n), int("9"*n))
of course you can change "1"*n to whatever you want the start to be.