This question already has answers here:
Python Sets vs Lists
(10 answers)
Complexity of *in* operator in Python
(3 answers)
Closed 1 year ago.
I was solving a hackerrank challenge.(in Python 3)
At one point I needed to sort a list and work with it.
(2 <= len(array) <= 10^5)
The list is containing unique integers.
I used arr.sort(), but I was getting "Time limit exceeded" message
Then I found if I use set(arr), it runs fast and passes all test cases.
here's is my function for more clarification
def pairs(k, ar):
ar.sort()
c=0
for i in ar:
if i+k in ar:
c+=1
return c
This gets me "Time limit exceeded"
def pairs(k, ar):
ar=set(ar)
c=0
for i in ar:
if i+k in ar:
c+=1
return c
This one with set() runs faster.
Why is this set() is faster than sort().
Don't they use same sorting algorithm?
Related
This question already has answers here:
Identify groups of continuous numbers from consecutive list in python
(4 answers)
Closed 2 years ago.
The challenge is to find the first non-consecutive number in python. I have managed to do it with a library called more_itertools, but the challenge requires that no library be involved. How can I solve it?
This is my code:
from more_itertools import consecutive_groups
def first_non_consecutive(l):
g = []
for grp in consecutive_groups(l):
g.append(list(grp))
if len(g) > 1:
return g[1][0]
Use enumerate with start parameter to your advantage here.
def first_non_consecutive(lst):
for i, j in enumerate(lst, lst[0]):
if i!=j:
return j
first_consecutive([1,2,3,4,6,7,8])
# 6
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
How to remove list elements in a for loop in Python? [duplicate]
(6 answers)
Closed 3 years ago.
def thirdMax(nums):
highest = max(nums)
for i in nums:
if i == highest:
nums.remove(i)
print(nums)
secondHighest = max(nums)
for i in nums:
if i == secondHighest:
nums.remove(i)
thirdHighest = max(nums)
return thirdHighest
thirdMax([1,2,3,3,3,3,3,3,4,4,4,4,4,4,4])
My code is supposed to return the third highest distinct number. My code isn't seeming to work accordingly.
Sort the list (to make sure). Convert to a set. Convert back to a list and take the 3rd from the right.
l = [1,2,3,3,3,3,3,3,4,4,4,4,4,4,4]
l.sort()
s = set(l)
l = list(s)
third = l[-3]
You can combine some of these steps, but I wrote them all out for clarity :)
This question already has answers here:
How to print a generator expression?
(8 answers)
Closed 7 years ago.
When I run the code I get the following output
How do I print the print the output?
def firstn(n):
num=0
while num < n:
yield num
num=num+1
sum_of_first_n=sum(firstn(10))
print(firstn(3))
In general:
print(list(firstn(n)))
Be sure your generator is not infinite. If you are not sure, use something like:
import itertools as it
print(list(it.islice(firstn(n), 100)))
to print up to the first 100 elements.
There's different ways of doing that, but basically you have to iterate through the iterator. The simplest way is probably using list comprehension:
print(list(firstn(3)))
but if you wish you could write a for loop to do that (and get it fx one element per line):
for e in firstn(3):
print(e)
One should however be aware that iterating through the generator consumes it and if you don't have means of retrieving a new generator (for example if you got the generator as parameter to a function call) you would have to store the values - fx in an array:
l = list(firstn(3))
for e in l:
print(e)
for e in l:
do_something(e)
This question already has answers here:
Python "OverflowError" [duplicate]
(8 answers)
Closed 7 years ago.
While I was trying to find the largest prime factor of a number using the code below attached , I encountered OverflowError: Python int too large to covert to C long
def prime_factors(n):
i = 2
if prime(n)==1:
return n
while n>0 and i<n:
if n % i ==0:
n = n/i
div = i
prime_factors(n)
else:
i+=1
return div
def prime(n):
for i in xrange(2,n):
if n%i ==0:
return 0
return 1
num = int(raw_input())
print prime_factors(num)
Can anyone please help find a solution to this ?
P.S: I am a beginner in Python.
range() creates a list in memory, which will raise an error if n is too large. You should use xrange() instead, which will create a lazy-evaluated generator object.
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 8 years ago.
Here's the issue, I'm using the sorted function to arrange a list of alpha-numeric strings. The said strings have to numbers in them separated by a letter.
For instance: sortqns(['s1q1', 's10q1', 's1q2', 's10q10', 's10q2'])
def cmpqn(a, b):
if len(a) > len(b):
return 1
if len(a) < len(b):
return -1
if len(a) == len(b):
return 0
def sortqns(qnlist):
new = sorted(qnlist, cmp=cmpqn)
return new
Returns ['s1q1', 's1q2', 's10q1', 's10q2', 's10q10']
My problem is sorting the second digit:
sortqns(['s12q1', 's1q2', 's1q1'])
Returns ['s1q2', 's1q1', 's12q1']
Instead of:
Returning ['s1q1', 's1q2', 's12q1']
In the first example my desired return would be off if the first two items were swapped as well.
The sorting algorithm in list is stable. Stable sorting algorithms maintain the relative order of records with equal keys. Therefore, in your code, when two element have the same length, they will appear in the result maintained their relative order.
I think the following solution is helpful.
def sortqns(qnlist):
return sorted(qnlist, key = lambda x: (len(x), x))