Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
The question I was given requires me to get an output within 3 secs
The constraint given is 2<= len(a) <= 5000000 and 1 <= a[i] <= 10**9
Below is the code I have written. I belive that the Big O efficiency of this code is linear or O(n) as I am only using one for loop. Is that the case? If can it run the max input size within 3 secs?
line = input()
m = line.split()
m.sort()
smallest_diff = 10 ** 9
for i in range(len(m)-1):
diff = abs(int(m[i]) - int(m[i+1]))
if diff < smallest_diff:
smallest_diff = diff
else:
smallest_diff = smallest_diff
if i+1 > len(m):
break
print(smallest_diff)
Your runtime complexity is currently O(N log(N)), dominated by the sort call. You're correct that the main work loop takes only O(N) time. However, the input size of 5*10^6 will be close to the borderline for what Python can get done in 3 seconds; you
I actually suspect your input loading may be eating up a lot of time. That's not an asymptotics issue; input is just often pretty slow. Here are things I'd try:
Check whether the website you're submitting to allows you to use PyPy instead of regular Python. You could still submit the same code either way, but it'll probably run a lot faster in PyPy.
Replace your first 2 lines with m = map(int, input().split()). This stores a list of int instead of string. ints make your code less memory-intensive and ints are what you want to use anyway. There are some more advanced tricks you could try to make the input loading steps even faster, like using BytesIO, but I'm just mentioning for fun; you probably don't want to get into that right now.
You currently have a few other unnecessary lines of code that slow your program down slightly, but they won't affect the runtime much.
Bonus note: I don't know the exact problem you're trying to solve, but your code probably has a bug where you sort the data. Your m is a list of strings, not ints, so for example your code would consider this array to be already sorted: ['10', '3'] (because the string '10' comes before the string '3'). This bug would be fixed as a side effect of my suggestion (2) above, since if you store the data as ints then you'd instead get [3, 10] which I'm pretty sure is what you're intending.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've written a program calculating pi based on basel problem but this program includes a very big while repeat.
See:
import math
import decimal
sqrt=1.
sumn=0.
outerrepeat=1000000
while outerrepat>0:
repeat=10000
while repeat>0:
sumn+=1/(sqrt**2)
sqrt+=1
repeat-=1
outerrepeat-=1
print math.sqrt(sumn*6)
When I run this outputs an empty line like this without ">>>":
========================== RESTART: C:/Python/pi.py ==========================
What's the reason?
Edit: Sorry for different variables, I wrote this program in my own language and then translated the variables for you. I forgot some of them.
Second edit: I tried Luc's suggestion, also changed the place of the print math.sqrt(sumn*6) to the outer while so I could see if it was proccesing.
It did but after the 7th number of pi it stopped working and stuck at 3.14159264498
The short answer to your question, is that your while loop are too big. So when you execute your program, the time to go through the while loop is too long.
There are some typo in the code that you copy/pasted, but I will assume that there is none. You are trying to make 10 000 000 000 iterations. Do you really need that many?
I would start by simply going for 100 iterations, maximum. And then augment it if you have a need for more precision.
You algorithm would be easier to understand/debug, if you simply use a for-loop.
You can try this one for example:
import math
max_iteration = 100
sumn=0.
for n in range(1,max_iteration+1):
sumn+=1./(n**2)
print math.sqrt(sumn*6)
With max_iteration = 100 you should find 3.13207653181, and the precision is getting better if you increase your max_iteration. With 10 000 iterations your are already at 3.14149716395.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have the following question:
considering the given list :
list = ['12','8','3']
why does print('8' in list) returns True
whereas
for i in range(5):
if '8' in list == True:
(code)
doesn't execute my code inside the if loop ?
Could someone explain me why, and how could I make this work ?
Maybe this question has already been asked but I don't see with which keywords I should search for it.
Thanks for the help :-)
You seem to have some logical errors in your code, so I'll try to outline what you should be doing.
You shouldn't name variables str or list or int because they might conflict with Python's built in keywords.
Your check did if '8' in list, but that will test if the string 8 is in the list, not the number. Drop the apostrophes.
You don't have to put if 8 in list in a loop, it'll do the looping and testing for you.
Solution
To check if a number is in a list, you can use python's built in in keyword, your write your own code to do the checking.
Remember not to use keywords like list, so I've changed the name to myList in these examples.
Using in
if 8 in myList: # Note that you don't have to say == True
print('8 is in the list!')
Or using for i in myList)
for i in myList:
if i == 8:
print('8 is in the list!')**
Or using for i in range(len(myList))
for i in range(len(myList)):
if myList[i] == 8:
print('8 is in the list!')
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have some code that gets the lecture times from online courses I take. The resulting answer is in the form of [['02:29']]. I think I'd use the following code to get the number out:
time1=timeList[0]
time2=time1[0]
time3=(time2.contents[0])
(parts) = time3.split(":")
Is there a better way to do this in fewer steps? And what resources are there to help me in the future? Or is this one of those things you just learn by coding and then asking for help?
Is it a list in a list with just one item?
Then you could achieve the same with:
test = [['02:29']]
parts = test[0][0].split(':')
print parts # result: ['02', '29']
But I'am not sure if I got you right
Itertool is always available:
Itertools
And you can chain your list considering it's always in the same format:
import itertools
time1 = list(itertools.chain(*timeList))[0].split(":")[0]
This solution is very fast and it works very smooth. A bit complicated to understand but it makes the work very efficiently.
Note: it also works with more levels of subarrays, no matter if you have 1, 2 or 3 levels
Update
Due to you indicated you want to convert it to raw seconds the answer is:
time1 = list(itertools.chain(*timeList))[0].split(":")
seconds_total = (time1[0] * 60) + time1[1]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
The task is to print the odd numbers from 1-99 on separate lines.
Codeeval deemed this code partially correct (98 out of 100): (edited)
liszt = (i for i in range(1,100) if i%2!=0)
for i in liszt:
print i
Codeeval deemed the below code completely correct:
liszt = range(1,100)
for i in liszt:
if i%2!=0:
print i
New to Python, so just looking to understand why one method might be considered better than the other. Is the second method more efficient?
Thanks for the help!
In the first code you are iterating over two generators first range(1, 100) and then over liszt whereas in the second case the iteration is only over liszt. Other than that the operation is same in both the cases, so the second method is more efficient.
Since every second number after 1 would be odd, a better solution could be:
for i in range(1, 100, 2):
print(i)
print("\n".join(str(i) for i in range(1,100,2)))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
An pseudocode is required to input a series of numbers from the keyboard and to ensure that they are in ascending order even though they need not be consecutive.The number may be positive or negative and will end with a dummy value of 9999.
This is a python code I wrote and it works ok,
li=[]
num=int(raw_input("Enter number"))
while num!=9999:
li.append(num)
num=int(raw_input("Enter number"))
new=0
print "Entered sequence is "
print li
j=0
while j<len(li):
for i in range(len(li)-1):
value1=li[i]
value2=li[i+1]
if (value1>value2):
new=li[i]
li[i]=li[i+1]
li[i+1]=new
j+=1
print "ordered list is "
print li
But I have problem in writing this as an algorithm.
This is my tried algorithm:
Main
li list
num integer
new=0,j=0 integer
Begin
num=INPUT num.
while num<>9999.
append num to li.
num=INPUT num.
ENDWHILE.
DISSPLAY "Entered Sequence is".
OUTPUT li.
while j<(length of li).
FOR i=0 to (length of li-2).
value1=i th element of li
value2=(i+1) th element of li
if (value1>value2):
new=value1
value1=value2
value2=new
ENDIF
END FOR
j=j+1
ENDWHILE
DISPLAY "ORDERED LIST IS"
DISPLAY li
END
END
Can I use "list" in an algorithm because I think objects as "list" do not appear in every programming language.And shouldn't algorithm be a general code.Same way is it allowed to use arrays in writing an algorithm
And Is it okay to say "value1=ith element in li"?
And how to show that I am assigning the value entered from keyboard to the variable "num"
(This was originally a comment)
You seem to miss what the point of pseudo code is. Pseudo code is neither standardized nor somewhat defined. In general it is just a code-like representation of an algorithm, while maintaining a high level and readability. You can write pseudo code in whatever form you like. Even real Python code could be considered pseudo code. That being said, there are no thing disallowed in pseudo code; you can even write prose to explain something that happens. For example in the inner-most loop, you could just write “swap value1 and value2”.
This is approximately how I would transform your Python code into pseudo-code. I tend to leave out all language specific stuff and focus just on the actual algorithmic parts.
Input:
list: Array of input numbers
FOR j = 0 to length(list):
FOR i = 0 to length(list)-1:
if list[i] > list[i+1]:
Swap list[i] and list[i+1]
OUTPUT ordered list
So is it okay to use lists, tuples, dictionaries in a pseudocode, even if they are not common to all programming languages?
Absolutely! In more complex algorithms you will even find things like “Get minimum spanning tree for XY” which would be a whole different problem for which again multiple different solutions exist. Instead of specifying a specific solution you are keeping it open to the actual implementation which algorithm is to be used for that. It usually does not matter for the algorithm you are currently describing. Maybe later when you analyze your algorithm, you might mention things like “There are algorithms known for this who can do this in O(log n)” or something, so you just use that to continue.