I wrote some code for a HackerRank problem (https://www.hackerrank.com/challenges/acm-icpc-team).
import time
from itertools import combinations
start_time = time.time()
n,m = raw_input().strip().split(' ') # n = no of people and m = no of topics
n,m = [int(n),int(m)]
topic = []
topic_i = 0
for topic_i in xrange(n):
topic_t = str(raw_input().strip())
topic.append(topic_t) # populate the topic[] list with the topics
counts = []
for list1, list2 in combinations(topic, 2):
if list1 != list2:
count = 0
for i in xrange(m):
if int(list1[i]) | int(list2[i]):
count += 1
counts.append(count)
print max(counts)
print counts.count(max(counts))
print time.time() - start_time
When I try to run the code, I get an execution time of 8.37576699257 seconds. But my program got over in a jiffy. I have read that the timeit() function, by default, runs the function passed to it a million times. Does something similar happen here?
You counted the time when the program waited for the user input too. You may want to move the first time.time() invocation below raw_input().
Related
I've started practicing for the USACO contest tomorrow, I'm relativly new so I'm not too familiar with their input/output methods. Here's the code I submitted to the website
n = int(input())
a = input()
b = input()
swap_number = 0
a_list = []
b_list = []
for i in range(n):
if a[i] != b[i]:
a_list.append(a[i])
b_list.append(b[i])
one_value = 0
two_value = 0
for x in range(len(a_list)):
if a_list[x] == "H":
one_value += 1
else:
two_value += 1
list = [one_value,two_value]
list.sort()
swap_number = list[0] + (list[1]-list[0])
print(swap_number)
after loading for a couple minutes, it displayed:
Your output file breedflip.out:
[File missing!]
I rewrote, retested every problem using this simple code, but still receive the same error
Would this code not create an output file and how can I put the outputted answer in the file
Try to add these two lines in your beginning of codes: (just test and it passed with my revised code) Your code might not be working!
import sys
sys.stdin = open('breedflip.in', 'r')
sys.stdout = open('breedflip.out', 'w')
n = int(input())
a = list(input()) # list
b = list(input())
...........
Well, I'm quite a beginner and need some help and advice. Sometime ago i watched this video about 100 prisoners question and wanted to write a proof program to see if the ratio really approaches to ~30%. But i got ~12%. I couldnt really find out where I did mistakes. Here is my code:
import random
from statistics import mean
prisoners = []
box_dict = {}
saved_prisoners = []
counter = 0
average = []
for i in range(1, 101):
prisoners.append(i)
for i in range(1000):
def control_list_generation():
for i in range(100):
x = random.sample(prisoners, 1)
y = x[0]
box_dict[i] = y
control_list_generation()
def open_box():
global saved_prisoners
global counter
counter = 0
for prisoner in range(100):
counter = prisoner
for turn in range(50):
if box_dict.get(counter) == (prisoner + 1):
saved_prisoners.append(1)
break
else:
counter = box_dict.get(counter) - 1
continue
open_box()
average.append(len(saved_prisoners))
saved_prisoners.clear()
print(mean(average))
P.S. range on the 13th line can be changed
Your code has a lot of superfluous lines. Just by editing out anything unneeded, you can end up with:
import random
from statistics import mean
prisoners = list(range(1, 101))
box_dict = {}
saved_prisoners = []
counter = 0
average = []
for i in range(1000):
for i in range(100):
x = random.sample(prisoners, 1)
y = x[0]
box_dict[i] = y
counter = 0
for prisoner in range(100):
counter = prisoner
for turn in range(50):
if box_dict.get(counter) == (prisoner + 1):
saved_prisoners.append(1)
break
else:
counter = box_dict.get(counter) - 1
continue
average.append(len(saved_prisoners))
saved_prisoners.clear()
print(mean(average))
However, you just use the dict more or less as a new list (the indices amount to the same as just shuffling the prisoners in a list). And when constructing it, you're accidentally duplicating prisoner tickets by sampling from the same prisoners over and over. (as user #MichaelButscher correctly points out in the comments)
If you fix those issues, your code still doesn't quite work because you have some further mistakes and moving around of numbers in your box checking.
Here's a solution that follows the pattern of your code, but shows the problem correctly:
import random
n_prisoners = 100
prisoners = list(range(n_prisoners))
boxes = []
failures = 0
attempts = 1000
for i in range(attempts):
boxes = list(prisoners)
random.shuffle(boxes)
for prisoner in prisoners:
box_nr = prisoner
for turn in range(n_prisoners // 2):
if boxes[box_nr] == prisoner:
break
box_nr = boxes[box_nr]
else:
failures += 1
break
print(f'{failures / attempts * 100}% of attempts failed')
Example output:
70.3% of attempts failed
As a general tip: don't get too hung up on numbering stuff from 1 instead of 0. That caused several coding mistakes in your code, because you kept having to correct for 'off by one' problems. Simply numbering the prisoners from 0 to 99 is far simpler, as it allows you to use the prisoner's number as an index. In case you need to print their number and need that to start at 1 - that would be the time to offset by one, not everywhere in your logic.
My task is to measure time of a function which contains an input inside (the user is to input a list).
There is the code:
import numpy
import itertools
def amount(C):
N = numpy.array(input().strip().split(" "),int)
N = list(N)
N = sorted(N)
while C < max(N):
N.remove(max(N))
res = []
for i in range(1, C):
for j in list(itertools.combinations_with_replacement(N, i)):
res.append(sum(list(j)))
m = 0
for z in range (0, len(res)):
if res[z] == C:
m += 1
if N[0] == 1:
return m + 1
else:
return m
Of course it is not optimized (but it's not the case now).
Because of the "list" standard way by which I mean:
import time
start = time.time()
amount(10)
end = time.time()
print(end - start)
does not work.
How can I measure the time? For example for:
C in range [0, 11]
N = [1, 2 , 5]
I would be grateful for any help! :)
You want somethig like this?
import time
# measure process time
t0 = time.clock()
amount(10)
print time.clock() - t0, "seconds process time"
# measure wall time
t0 = time.time()
amount(10)
print time.time() - t0, "seconds wall time"
UPDATE : The soulution maybe could be this :
times=[]
for x in range(12):
t0 = time.time()
amount(x)
times.append( time.time() - t0);
or better if you use timeit : here
What do you think about this:
import time
def time_counter(amount, n=100, M=100):
res = list(range(n))
def count_once():
start = time.perf_counter()
amount(res)
return time.perf_counter() - start
return [count_once() for m in range(M)]
It is to make M = 1000 measurements and for C in range(0, n). Is it alright?
Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?
I am starting to learn multiprocessing in python, but have arrived to a point where my code just hangs. It is simply computing 1 000 000 factorial, using multithreading.
import multiprocessing
def part(n):
ret = 1
n_max = n + 9999
while n <= n_max:
ret *= n
n += 1
print "Part "+ str(n-1) + " complete"
return ret
def buildlist(n_max):
n = 1
L = []
while n <= n_max:
L.append(n)
n += 10000
return L
final = 1
ne = 0
if __name__ == '__main__':
pool = multiprocessing.Pool()
results = [pool.apply_async(part, (x,)) for x in buildlist(1000000)]
for r in results:
x = r.get()
final *= x
ne+= 1
print ne
print final
I have included some print functions to try to diagnose where the code hangs, and it will print the string included in the part function 100 times, as expected. The "print ne" also works 100 times.
The problem is that final won't print, and the code doesn't complete.
How do I fix this problem?
Edit: Also, since this is being downvoted, could someone explain what I am doing wrong/why I am being downvoted?
The program works fine --- until the print final. Then it spends a very large amount of time trying to print this number, which is seriously huge...