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 15 days ago.
Improve this question
I have the following code
for (int i = 0; 1 < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
How should I convert it in Python language ?
That's two nested loops. You can directly translate it into Python, if you want:
for i in range(len(array)):
for j in range(i+1, len(array)):
...
But iterating over indexes is often unnecessary in Python, unless you need the indexes for some reason other than indexing to get the values from the array. If you just want pairs of items, use itertools.combinations:
for i_item, j_item in itertools.combinations(array, 2):
...
That's just two nested for loops, you can do the equivalent in Python like this:
array = [1,2,3,4,5]
for i in range(len(array)):
for j in range(i + 1, len(array)):
#code
The outer for loop iterates through the array using the range function and the len function to get the length of the array. The inner for loop does the same, but starts at index i+1 and goes up to the end of the array using the same range function.
Another way to do this is to use the built-in enumerate() function to get the index and element at the same time, like this:
for i, _ in enumerate(array):
for j in range(i + 1, len(array)):
#code
Related
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.
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))
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 4 years ago.
Improve this question
I need to create a python function that right shifts values in a list by a given value.
For example if the list is [1,2,3,4] and the shift is 2 it will become [2,3,4,1]. the shift value must be a non negative integer. I can only use the len and range functions.
This is what I have so far
def shift(array, value):
if value < 0:
return
for i in range(len(array)):
arr[i] = arr[(i + shift_amount) % len(arr)]
Usually you can do this with slicing
arr = arr[shift:] + arr[:shift]
Your shifted list is only shift = 1, not 2. You can't get your output by shifting 2 positions.
I make some modifications in your code (If you have to use len and range functions) :
def shift(array, shift_amount):
if shift_amount < 0:
return
ans = []
for i in range(len(array)):
ans.append(array[(i + shift_amount) % len(array)])
print ans
shift([1,2,3,4],2)
Output:
[3, 4, 1, 2]
Note:
Your's logic is correct but your overriding values in same array, So I created another list and append value to it.
If shift value is 1 then output will be [2, 3, 4, 1]. So for value 2 it will be two shifts that's why output should be [3, 4,
1, 2]
value and shift_amount are two different variables in your code, So I use only single variable.
You can use list comprehension (If you want to check in detail about list comprehension see this article Python List Comprehensions: Explained Visually) like
def shift(array, shift_amount):
if shift_amount < 0:
return
length = len(array)
print [array[(i + shift_amount) % length] for i in range(length)]
shift([1,2,3,4],0)
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().
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I am trying to improve the speed of my python code. It takes a long time to execute for large dataset. Is there a better way to do it at a faster speed?
for i in range(0,len(nodes)):
fragment = nodes[i]
for l in range(0, length1):
fragment1 = Text[l:int(l)+int(k)]
count = [0]*gen_len
for j in range( 0, gen_len ):
if fragment[j] != fragment1[j]:
count[j] = count[j]+1
if j == (gen_len-1):
if int(sum(count)) <= int(Num_mismatches):
count2[i] = count2[i]+1
result2[i] = fragment
result.append(fragment)
if count2[i] > maxval:
maxval = count2[i]
If using Python 3 replace izip with zip and xrange with range.
from itertools import islice, izip
for i in xrange(0,len(nodes)):
fragment = nodes[i]
for l in xrange(0, length1):
# fragment1 was replaced by islice to avoid list creation
# It may or may not be faster. Try timing a version
# where you replace islice(Text, 1, l+k) with Text[l:int(l)+int(k)]
count = sum(f != f1 for f, f1 in izip(fragement, islice(Text, 1, l+k)))
if count <= Num_mismatches:
count2[i] += 1
# code smell: why have both result and result2?
result2[i] = fragment
result.append(fragment)
# you are not using maxval anywhere in these loops.
# you may want to set it after these loops.
if count2[i] > maxval:
maxval = count2[i]
There were a number of places where you were casting to int. I removed those because it looks like they are already int (Num_mismatches, l, k).