Executing a file a large number of times - python-2.7

How do I get a file to run a large number of times, say even a million? For instance, randomly choose a number from a list a million times and find it's average. Example:
fib = [2,3,5,8,13,21,34,55,89]
i = random.choice(fib)
print i
I want the average of a million trials. It seems like the method around here is to help and not so much feed me the answer. That is greatly appreciated as well.

How about looping a million times, summing up the chosen values and dividing by a million:
from __future__ import print_function
import random
n = 1e6
fib = [2,3,5,8,13,21,34,55,89]
print(sum(random.choice(fib) for _ in range(int(n))) / n)
Output:
25.565039
The above code contains a generator expression. It is equivalent to this loop version:
sum_ = 0
for x in range(int(n)):
sum_ += random.choice(fib)
print(sum_/n)
Output:
25.576006

Related

Primes in arithmetic progressions in Sagemath

I am in need of finding prime numbers in arithmetic progression
80218110*n+8021749, n=1 to 100,000
I was told that using Sage would be a good option, since my computer is old. I happen to be new to Sage and I haven't found it to solve my problem, I guess it shouldn't be difficult, does anyone have a good reference for printing primes in arithmetic progressions?
SageMath is based on Python, and Python provides a syntax which should be comfortable for mathematicians:
[80218110*n + 8021749 for n in range(100)]
range(100) is the ordered set 0, 1, 2, ..., 99, and so the previous line evaluates 80218110*n + 8021749 for these values of n. We can also test whether the entries are prime:
INPUT: [80218110*n+8021749 for n in range(100) if (80218110*n+8021749).is_prime()]
OUTPUT:
[8021749,
489330409,
569548519,
970639069,
1050857179,
1131075289,
1772820169,
2093692609,
2173910719,
3136528039,
3617836699,
4660672129,
4740890239,
5382635119,
6425470549,
7067215429,
7227651649,
7548524089]
You can of course make the argument to range larger, but maybe it's not a good idea to print the whole list.
INPUT: len([80218110*n+8021749 for n in range(100000) if (80218110*n+8021749).is_prime()])
OUTPUT: 15273
(len returns the length of the list.) Producing this list is pretty quick, at least on my computer:
INPUT: %time L = [80218110*n+8021749 for n in range(100000) if (80218110*n+8021749).is_prime()]
OUTPUT CPU times: user 94.6 ms, sys: 1.13 ms, total: 95.8 ms
Wall time: 95.5 ms
(ms is milliseconds.)

How do I eliminate even numbers from this python code without an infinite loop occurring?

I have tried different ways to try print odd numbers only but its only causing an infinite loop to occur. Could you please assist me?
import sys
i = 1
while i < len(sys.argv):
print sys.argv[i]
i = i + 1
Your question is little bit confusing.
You should be processing all arguments and then decide which one you should print.
import sys
i = 1
while i < len(sys.argv):
number = int(sys.argv[i])
if number % 2 == 1:
print number
i = i + 1
In python, sys.argv contains only one item 'main.py' in index number 0.
So, if you run the program from index 1, you will get nothing as output. If you set it from index 0, you will get 'main.py' printed as output.
If this answer is not satisfactory, please clarify your issue with this code.

How to repeat a function in Python (complete beginner - first lines of code ever)

I have the following code which I have to build upon (i.e. it can't be written a different way). I know there are other better ways of achieving the end result, but I want to use this code and then repeat it to make a list.
from random import choice
number_list = range(1,1001) # Creates a list from 1 to 1000
random_from_list = choice(number_list) # Chooses a random number from the list
I want to now repeat the choice function above 100 times, then print that list of 100 random numbers that I have chosen from my list of 1000 numbers. I have read up on "for" loops but I can't see how to apply it here.
If you don't need to build up your list you could just print them one at a time:
for _ in range(100):
print(choice(number_list))
If you want to build your list first you can use a "list comprehension":
choices = [choice(number_list) for _ in range(100)]
print(choices)
for i in range(100):
print(choice(number_list))

Finding length of list without using the 'len' function in python

In my High school assignment part of it is to make a function that will find the average number in a list of floating points. We can't use len and such so something like sum(numList)/float(len(numList)) isn't an option for me. I've spent an hour researching and racking my brain for a way to find the list length without using the len function, and I've got nothing so I was hoping to be either shown how to do it or to be pointed in the right direction. Help me stack overflow, your my only hope. :)
Use a loop to add up the values from the list, and count them at the same time:
def average(numList):
total = 0
count = 0
for num in numList:
total += num
count += 1
return total / count
If you might be passed an empty list, you might want to check for that first and either return a predetermined value (e.g. 0), or raise a more helpful exception than the ZeroDivisionError you'll get if you don't do any checking.
If you're using Python 2 and the list might be all integers, you should either put from __future__ import division at the top of the file, or convert one of total or count to a float before doing the division (initializing one of them to 0.0 would also work).
Might as well show how to do it with a while loop since it's another opportunity to learn.
Normally, you won't need counter variable(s) inside of a for loop. However, there are certain cases where it's helpful to keep a count as well as retrieve the item from the list and this is where enumerate() comes in handy.
Basically, the below solution is what #Blckknght's solution is doing internally.
def average(items):
"""
Takes in a list of numbers and finds the average.
"""
if not items:
return 0
# iter() creates an iterator.
# an iterator has gives you the .next()
# method which will return the next item
# in the sequence of items.
it = iter(items)
count = 0
total = 0
while True:
try:
# when there are no more
# items in the list
total += next(it)
# a stop iteration is raised
except StopIteration:
# this gives us an opportunity
# to break out of the infinite loop
break
# since the StopIteration will be raised
# before a value is returned, we don't want
# to increment the counter until after
# a valid value is retrieved
count += 1
# perform the normal average calculation
return total / float(count)
def length_of_list(my_list):
if not my_list:
return 0
return 1+length_of_list(my_list[1:])

Time based rotation

I'm trying to figure out the best way of doing the following:
I have a list of values: L
I'd like to pick a subset of this list, of size N, and get a different subset (if the list has enough members) every X minutes.
I'd like the values to be picked sequentially, or randomly, as long as all the values get used.
For example, I have a list: [google.com, yahoo.com, gmail.com]
I'd like to pick X (2 for this example) values and rotate those values every Y(60 for now) minutes:
minute 0-59: [google.com, yahoo.com]
minute 60-119: [gmail.com, google.com
minute 120-179: [google.com, yahoo.com]
etc.
Random picking is also fine, i.e:
minute 0-59: [google.com, gmail.com]
minute 60-119: [yahoo.com, google.com]
Note: The time epoch should be 0 when the user sets the rotation up, i.e, the 0 point can be at any point in time.
Finally: I'd prefer not to store a set of "used" values or anything like that, if possible. i.e, I'd like this to be as simple as possible.
Random picking is actually preferred to sequential, but either is fine.
What's the best way to go about this? Python/Pseudo-code or C/C++ is fine.
Thank you!
You can use the itertools standard module to help:
import itertools
import random
import time
a = ["google.com", "yahoo.com", "gmail.com"]
combs = list(itertools.combinations(a, 2))
random.shuffle(combs)
for c in combs:
print(c)
time.sleep(3600)
EDIT: Based on your clarification in the comments, the following suggestion might help.
What you're looking for is a maximal-length sequence of integers within the range [0, N). You can generate this in Python using something like:
def modseq(n, p):
r = 0
for i in range(n):
r = (r + p) % n
yield r
Given an integer n and a prime number p (which is not a factor of n, making p greater than n guarantees this), you will get a sequence of all the integers from 0 to n-1:
>>> list(modseq(10, 13))
[3, 6, 9, 2, 5, 8, 1, 4, 7, 0]
From there, you can filter this list to include only the integers that contain the desired number of 1 bits set (see Best algorithm to count the number of set bits in a 32-bit integer? for suggestions). Then choose the elements from your set based on which bits are set to 1. In your case, you would use pass n as 2N if N is the number of elements in your set.
This sequence is deterministic given a time T (from which you can find the position in the sequence), a number N of elements, and a prime P.