Improve speed of nested loop [closed] - python

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).

Related

Perfect number function [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 7 days ago.
Improve this question
Write a program in Python that exercises the functional higher order functions via Python list comprehensions to determine if a number is perfect or not. Write a function named perfect(num) that returns true/false if the given number is/is not perfect.
Use the built in Python function called range(n) that returns a list of integers between 0 and n-1 inclusive.
Use map implemented as a Python List Comprehension to add one to each element of the list.
Use filter implemented as a Python List Comprehension to generate a list of proper factors of n.
Use the Python reduce to generate a sum of those factors
Not more than 4-5 lines of code
def is_perfect(num):
sum = 0
for x in range(0, num-1):
if num % x == 0:
sum += x
return sum == num
print(Is_perfect(28))
Here you go:
def is_perfect(num):
sum = 0
for i in range(1, num):
if num % i == 0:
sum += i
if sum == num:
return True
else:
return False
Now to test it:
x = 8
print(is_perfect(x))
This returns False.
x = 28
print(is_perfect(x))
This returns True.
Some correction in your code
You calling not a correct function name Is_perfect(),
There is also error of modulo by zero,
As written you would inclusive (n-1) in your for loop it is running till (n-2) not till (n-1),
Code:
from functools import reduce
def is_perfect(num):
# List comprehension which store all the number which can be divisible.
list_comprehension = [x for x in range(0, num) if x == 0 or num % x == 0]
print(list_comprehension)
# [0, 1, 2, 4, 7, 14] for number 28
# [0, 1, 2, 4] for number 8
# sum of list using reduce.
sum_of_divisible_numbers = reduce(lambda x, y: x + y, list_comprehension)
return sum_of_divisible_numbers == num
print(is_perfect(28)) # True
print(is_perfect(8)) # False

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 to find the longest odd-even increasing subsequence 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 10 months ago.
Improve this question
I have this problem and I'm not sure about the solution:
Given an integer array A, calculate the length of its longest odd-even increasing subsequence (LOEIS), that is the length of the longest sequence S of elements in A such that all elements of S are odd or even.
For instance, given: A=[3,9,4,8,6,13,10,26,16,18], because the longest even sequence is made of 5 elements: [4,6,10,16,18] we have LOEIS(A)=5.
How to code such a function?
Thank you!
Here a solution from https://www.geeksforgeeks.org/python-program-for-longest-increasing-subsequence/ that I've adapted to you issue:
import matplotlib.pyplot as plt
import numpy as np
# A naive Python implementation of LIS problem
""" To make use of recursive calls, this function must return
two things:
1) Length of LIS ending with element arr[n-1]. We use
max_ending_here for this purpose
2) Overall maximum as the LIS may end with an element
before arr[n-1] max_ref is used this purpose.
The value of LIS of full array of size n is stored
in * max_ref which is our final result """
# global variable to store the maximum
global maximum
def _lis(arr, n):
# to allow the access of global variable
global maximum
# Base Case
if n == 1:
return 1
# maxEndingHere is the length of LIS ending with arr[n-1]
maxEndingHere = 1
"""Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]
IF arr[n-1] is smaller than arr[n-1], and max ending with
arr[n-1] needs to be updated, then update it"""
for i in range(1, n):
res = _lis(arr, i)
if arr[i - 1] < arr[n - 1] and res + 1 > maxEndingHere:
maxEndingHere = res + 1
# Compare maxEndingHere with overall maximum. And
# update the overall maximum if needed
maximum = max(maximum, maxEndingHere)
return maxEndingHere
def lis(arr):
# to allow the access of global variable
global maximum
# length of arr
n = len(arr)
# maximum variable holds the result
maximum = 1
# The function _lis() stores its result in maximum
_lis(arr, n)
return maximum
A=np.array([3,9,4,8,6,13,10,26,16,18])
Even = A[A%2==0]
Odd = A[A%2==1]
print(Even,Odd)
print("Length of lis for Even is", lis(Even))
print("Length of lis for Odd is", lis(Odd))
Length of lis for Even is 5
Length of lis for Odd is 3

Difference in Selection Sort Algorithm [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 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.

How the looping with for in Python really works? [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 4 years ago.
Improve this question
I'm learning python and in a test, I made a class that have a list of numbers, in other class, a list of previous class. In the second class, I wrote a method for put the numbers dinamically but it put the numbers x times for the length of the list of previous class.
def make_connection(self, number):
if not self.__has_con:
for i in range(number):
self.__weight.append(1)
self.__has_con = True
The method above is from the first class, to get n numbers.
inp = len(self.__inputs)
for n in self.__hidden:
n.make_connection(inp)
This is from the second class. If __hidden has 9 objects, it put the inp 9 times for all the 9 elements.
init of second class
def __init__(self, array):
if isinstance(array, list):
if len(array) > 2:
inps = []
hidd = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[len(array)-1]):
k = kn(kn.OUTPUT)
outs.append(k)
a = array[1:]
h = a[:len(a)-1]
if len(h) > 1:
for i in h:
hd = []
for p in range(i):
k = kn(kn.HIDDEN)
hd.append(k)
hidd.append(hd)
else:
for p in range(h[0]):
k = kn(kn.HIDDEN)
hidd.append(k)
self.__inputs = inps
self.__hidden = hidd
self.__output = outs
else:
inps = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[0]):
k = kn(kn.OUTPUT)
outs.append(k)
self.__inputs = inps
self.__output = outs
The for var in collection syntax in Python uses an iterator. Instead of a for loop where you specify a starting value, an increment and a terminating value, it says iterate over all the values in the collection.
So when you say this in Python:
for x in range(4):
print x
it's like saying this in other languages:
for (x = 0; x < 4; ++x) {
print(x);
}
Python's range returns a iterator over 0..4 in this case. In your example, Python gives you each element of your collection.
See, for more details: https://www.w3schools.com/python/python_iterators.asp
In python Use the for loop like that:
for str in str_list
print (str)

Categories