Difference in Selection Sort Algorithm [closed] - python

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 last year.
Improve this question
Can someone help explain if these two selection sorts have different Big O notations for worst case scenarios or are they the same? Thanks a lot.
""" Selection Sort 1: This function uses 'find_smallest' function
Question: In the worst case, will selection_sort1 be O(nlogn) since
the size of the arr decreases by 1 every time the for loop runs? """
def selection_sort1(arr):
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
""" Selection Sort 2: This function uses 'min()' function and 'remove()' method. Since these methods run for
O(n).
Question: is it cleverto conclude that selection_sort2 funtion will
runfor O(n^2)? and therefor selection_sort1 is betterthan
selection_sort2? """
def selection_sort2(arr):
new_arr = []
for i in range(len(arr)):
new_arr.append(min(arr))
arr.remove(min(arr))
return new_arr
This function is used by Selection_sort1
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
Test Case
arr = [5,2,8,5,1,9,4]
print(selection_sort1(arr))

I believe it is because selection sort #2 has more processes inside the for-loop.

Related

Running performance comparison of list slice, list.pop and del [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 days ago.
Improve this question
I want to create a new list by extract the elements after the first one from the old list. This operation frequently happens in my program, I want to know which kind of operation has better running performance.
old_list = [] (may have 1000-1000000 elements)
Option 1:
new_list = old_list[1:]
Option 2:
del old_list[0]
new_list = old_list
Option 3:
old_list.pop(0)
new_list = old_list
paste my test sample code here:
#profile
def main():
a = []
for i in range(50000):
a.append(i)
b=a[1:]
c= []
for i in range(50000):
c.append(i)
del c[0]
d=c
e= []
for i in range(50000):
e.append(i)
e.pop(0)
f=e
Based my test result. If element number in the list is bigger than 50000, option 2 and 3 have better performance. If element number in the list is smaller than 5000, option 1 has better performance.

Function to find a continuous sub-array which adds up to a given number in python [closed]

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 last month.
Improve this question
I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios?
Expected time complexity: O(n)
def subArraySum(self,arr, n, s):
if sum(arr[0:n]) == s:
return [1, n]
if sum(arr[0:n]) < s:
return [-1]
start = 0
i =1
sum_elements = 0
while i < n:
sum_elements = sum(arr[start:i+1])
if sum_elements == s:
return [start+1, i+1]
if sum_elements < s:
i += 1
continue
if sum_elements > s:
start += 1
continue
if sum_elements < s:
return [-1]
Instead of running sum(arr[start:i+1]) in each iteration of the while loop, you should use a variable and add or subtract the respective value that is included or excluded from the subarray in each iteration. That way you can avoid the O(n^2) complexity and stay within O(n).
Currently there is a lot of overhead for calculating the sum of a (potentially large) subarray that has only changed by one single value at the beginning or the end during each iteration.

How do i print every 3rd number in a list in python WITHOUT USING slice notation (square brackets)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
def every_third(lst):
'''
every_third that takes a list as a parameter and returns
a new list that contains every third element of the original
list, starting at index 0.
>>> every_third([1,2,3,4,5,6,7,8,9,10])
[1,4,7,10]
How would I do this? I know that we can use a for loop, but i just dont know how to begin.
If range is allowed with all of start, stop, step (which is not exactly slice notation), just do:
def every_third(lst):
return [lst[i] for i in range(0, len(lst), 3)]
If not, use a conditional comprehension with a condition based on modulo:
def every_third(lst):
return [lst[i] for i in range(len(lst)) if i%3 == 0]
Another trick using enumerate:
seq = [1,2,3,4,5,6,7,8,9,10]
every_three = [value for idx, value in enumerate(seq) if idx % 3 == 0]
But my first comment if code review of lines above would be: Use slice syntax, there's no need to use an enumerate here.
If the problem is just the slice notation, as in [::3] I think it should be somethink like this, I figure You are doing exercises right?
list=[1,2,3,4,5,6,7,8,9,10]
def third(list):
res=[]
count=3
res.append(list[0])
while len(list)>0:
if count>0:
list.pop(0)
else:
res.append(list[0])
list.pop(0)
count=3
count -= 1
return res
print(third(list))

Is it valid to write some code that a bit tricky as long as I get same result (fibonacci in python) [closed]

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 6 years ago.
Improve this question
In Pycharm Edu I've encountered with this code:
def fib(n):
"""This is documentation string for function. It'll be available by fib.__doc__()
Return a list containing the Fibonacci series up to n."""
result = []
a = 1
b = 1
while a < n:
result.append(a)
tmp_var = b
b = a+b
a = tmp_var
return result
Since I am still learning I tried to do something similar with lists but the problem is to get a proper fibonacci series I used [-1,1] to start calculation, but results are same. Here is my code:
x = [-1,1]
y = []
for i in range(10):
c = x[0] + x[1]
y.append(c)
x[0] = x[1]
x[1] = c
print(y)
The question is, can I get away with this ?
This question might be too opinion-based for this site, but take into consideration that your code doesn't just need to run, it also needs to be readable. Otherwise, what you have written is entirely valid.
Consider this:
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
print(fibonacci_sequence)
As I said, this may seem like opinion, but make sure you keep the beginning PEP 20 in mind:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts...
As a final note, your code is not a function, but the original code snippet is a function. Here is your code as a function:
def fibonacci():
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
return fibonacci_sequence
print(fibonacci())

Difference between for items in list and for i in range (0, len(x)) in python [closed]

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 6 years ago.
Improve this question
I'm getting to grips with lists in python but I'm stumped when it comes to the difference in using these two functions.
def print_list(x):
for j in range (0, len(x)):
print x[j]
and
def print_list(x):
for item in list:
j = 0
print x[j]
j++
Can anyone explain to a beginner? Thanks!
I assume
def print_list(x):
for j in range (0, len(x)):
print x[j]
is how loops run in C++. So you understand that intuitively. Here, range generates (look up generators) the values 0 through len(x) and the for statement iterates through them.
Your 2nd syntax, as pointed out in the comments, is wrong. I assume you meant
def print_list(x):
for item in x:
print(item)
The for statement iterates through every item in the list x.
So if your list is [1,3,5,7,9], in the 1st loop, item will have value 1. In the 2nd loop, item will have the value 3. In the 3rd loop, item will have the value 5. And so on.
When all the values have been iterated through, the for loop ends.
The first example is correct and it should be pythonic enough. The second one is incorrect.
def print_list(x):
for item in list: #where is the iterable oject called list? This shuold be x
j = 0 # if you use a counter like j you shuold be defining before the loop otherwise you keep resetting it to 0.
print x[j]
j++
A more pythonic and better way if you want to print all the elemets in a list interating over them.
def print_list(list_item):
for element in list_item:
print(element)
You don't need to use the range and len like in the first example, list are iterable object so you can just do like the above example without recuring to range().

Categories