logo
down
shadow

Code Trivia: optimize the code for multiple nested loops


Code Trivia: optimize the code for multiple nested loops

By : user3859253
Date : January 02 2021, 06:48 AM
Hope this helps I came across this code today and wondering what are some of the ways we can optimize it.
code :


Share : facebook icon twitter icon
Why code with multiple nested loops can finish immediately on GCC but take forever on VS?

Why code with multiple nested loops can finish immediately on GCC but take forever on VS?


By : briddl
Date : March 29 2020, 07:55 AM
I wish this help you Yes, GCC is optimizing that code.
Specifically, it knows that you aren't using the result, so it's removing all of it.
code :
cout << r << endl;
How can I optimize my R code with nested for loops to run faster?

How can I optimize my R code with nested for loops to run faster?


By : Chris
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I have the following code. I would like to optimize it to run faster. , rewritten func1:
code :
func1 <- function(l, k, N, p, bins, k_v){
  y <- vector("integer", l*k)
  y_len <- l*k
  ss <- sample.int(N)
  Mlist <- split(ss, bins)
  for (i in 1:y_len) {
    r <- Mlist[[i]]
    o <- rank(p$Y[r], ties.method = 'average')
    ii <- o == k_v[i]
    y[i] <- p$X[r][ii]
  }
  return(y)
}
start_time <- Sys.time()

combi <- expand.grid(k, l)
l_vector <- unlist(combi[2], use.names = F)
k_vector <- unlist(combi[1], use.names = F)

desired_matrix_as_vector <- vector("integer", length(l)*length(k))
nn = 5000
for (i in 1:length(desired_matrix_as_vector)) {
  l_val <- l_vector[i]
  k_val <- k_vector[i]

  combi2 <- expand.grid(1:k_val, 1:l_val)
  k_vector2 <- unlist(combi2[1], use.names = F)

  binss  <- rep(1:ceiling(N / k_val), each = k_val)
  binss <- binss[1:N]
  binss <- as.factor(binss)

  D <- replicate(n = nn, expr = func1(l_val, k_val, N, p0, binss, k_vector2),
                 simplify = FALSE)
  D <- sapply(D, func2)
  desired_matrix_as_vector[i] <- quantile(D, probs = 0.95)
}

desired_matrix = matrix(desired_matrix_as_vector,nrow = length(l), byrow = TRUE)

end_time <- Sys.time()
end_time - start_time
o <- .Internal(rank(p$Y[r], length(p$Y[r]), 'average'))
func1 <- function(l, k, N, p, k_v){
  y <- vector("integer", l*k)
  ss <- sample.int(N)
  m <- matrix(ss, k)
  for (i in 1:(l*k)) {
    r <- m[, i]
    x <- p$Y[r]
    o <- .Internal(rank(x, length(x), 'average'))
    ii <- o == k_v[i]
    y[i] <- p$X[r][ii]
  }
  return(y)
}
ss <- sample.int(N, (l*k*k))
I am writing nested while loops which are getting impractically deep (>12 nested loops), how can i code it recursivel

I am writing nested while loops which are getting impractically deep (>12 nested loops), how can i code it recursivel


By : kathy
Date : March 29 2020, 07:55 AM
I wish this helpful for you You are right that there is a limit with nested for loops in Python. I think it's about 20, so your solution cannot work. But even if the limit was larger, you would want to use recursion to make the code clearer, concise, and more flexible. Here's how recursion can solve your problem:
code :
def list_special_numbers(base, digits, starting_digit=0, partial_sum=0):
    if digits == 1:
        for i in range(starting_digit, base):
            print(partial_sum + i)
    else:
        for i in range(starting_digit, base):
            list_special_numbers(base, digits-1, i, partial_sum + i*(base**(digits-1)))

# *** Usage examples ***

# print the list of desired numbers up to 20-ternary-digit numbers
list_special_numbers(3,20)

# print the list of desired numbers up to 30-ternary-digit numbers
list_special_numbers(3,30)

# print the list of desired numbers up to 30-binary-digit numbers
list_special_numbers(2,30)

# print the list of desired numbers up to 3-decimal-digit numbers
list_special_numbers(10,3)
How to optimize multiple loops in VBA code within Excel

How to optimize multiple loops in VBA code within Excel


By : user2723083
Date : March 29 2020, 07:55 AM
will be helpful for those in need You want to avoid repeating yourself. Whenever you have duplicate code you need to break it out in to it's own procedure and then call it using the variable that makes it unique. In your case the only unique part is the sheet you are operating on. So I made this example procedure that you can pass sheet objects to:
code :
Private Sub ProcessSheet(thisSheet As Worksheet)

    thisSheet.Range("KA25:KC5000").Delete

    Dim LastRow As Long, i As Long
    LastRow = thisSheet.Cells(thisSheet.Rows.Count, "A").End(xlUp).Row
    For i = 25 To LastRow
        thisSheet.Range("KA1").Offset(i - 1, 0).FormulaR1C1 = _
                               "=IF(SUMIF(DATASHEET!R2C1:R712C1," & thisSheet.Name & "!R25C2:R59C2,DATASHEET!R2C[-275]:R712C[-275])>0,SUMIF(DATASHEET!R2C1:R712C1," & thisSheet.Name & "!R25C2:R59C2,DATASHEET!R2C[-275]:R712C[-275]),"""")"

        thisSheet.Range("KB1").Offset(i - 1, 0).FormulaR1C1 = _
                               "=IF(" & thisSheet.Name & "!RC[-1]="""","""",If(" & thisSheet.Name & "!RC[-1]>1.1,""RED"",If(" & thisSheet.Name & "!RC[-1]<0.8,""GREEN"",""YELLOW"")))"

        thisSheet.Range("KC1").Offset(i - 1, 0).FormulaR1C1 = _
                               "=IF(" & thisSheet.Name & "!RC[-1]="""","""",SUMIF(DATASHEET!R2C1:R712C1," & thisSheet.Name & "!R25C2:R59C2,DATASHEET!R2C[-275]:R712C[-275]))"
    Next i

    With thisSheet
        .Range("KA25").UsedRange = Sheets("SHEET1").Range("KA25").UsedRange
        .Range("KA25", Selection.End(xlDown)).NumberFormat = "0.00"
        .Range("KC25", Selection.End(xlDown)).NumberFormat = "0.00%"
    End With
End Sub
Sub Import()
    With Application
        .EnableEvents = False             'This stops the background codes on the sheets from activating (smoothens out the process).
        .ScreenUpdating = False           'Stops the screen from switching back and forth between the Input and the Master
        .DisplayAlerts = False
    End With

    If InStr(1, Worksheets("Lookup").Range("B44").Value, "STATE1", vbTextCompare) <> 0 Then
        Sheets("SHEET2").Activate
        Range("A4").Select
    ElseIf InStr(1, Worksheets("Lookup").Range("B44").Value, "STATE2", vbTextCompare) <> 0 Then
        Sheets("SHEET2").Activate
        Range("A4").Select
    ElseIf InStr(1, Worksheets("Lookup").Range("B44").Value, "STATE3", vbTextCompare) <> 0 Then
        Sheets("SHEET2").Activate
        Range("A4").Select
    ElseIf InStr(1, Worksheets("Lookup").Range("B44").Value, "All", vbTextCompare) <> 0 Then
        Sheets("SHEET2").Activate
        Range("A4").Select
    Else
        Sheets("SHEET1").Columns("KA:KC").Hidden = True
        Sheets("SHEET2").Columns("KA:KC").Hidden = True
        Sheets("SHEET3").Columns("KA:KC").Hidden = True
        Sheets("SHEET4").Columns("KA:KC").Hidden = True
        MsgBox "Doesn't exist for these locations"
        Exit Sub
    End If

    Sheets("SHEET1").Columns("KA:KC").Hidden = False
    Sheets("SHEET2").Columns("KA:KC").Hidden = False
    Sheets("SHEET3").Columns("KA:KC").Hidden = False
    Sheets("SHEET4").Columns("KA:KC").Hidden = False

    'This removes the old DATASHEET tab from the model before starting (if it exists)
    Dim SummaryWB As Workbook
    Dim vrtSelectedItem As Variant
    For Each Sheet In ActiveWorkbook.Worksheets
        If Sheet.Name = "DATASHEET" Then
            Sheet.Delete
        End If
    Next Sheet

    ''' The below opens the RRS file from the file path defined
    Dim RRSFile As Workbook
    Set RRSFile = Workbooks.Open(Filename:="\\Template_Current.xlsx")

    '' This will allow the workbook to open before continuing
    DoEvents

    '' This copies the Data from the RRS file and moves it into the CPM model in a new tab, and renames it.
    '' It then closes the Source file.
    Dim dataRange As Range
    dataRange = RRSFile.Sheets("Data").Range("A1").UsedRange

    Dim dataSheet As Worksheet
    Windows("Report.xlsm").Activate
    Set dataSheet = Sheets.Add(After:=Sheets("YAdd"))
    dataSheet.Range("A1") = dataRange
    dataSheet.Name = "DATASHEET"
    RRSFile.Sheets("List View").Range ("D3")
    dataSheet.Range("W1") = RRSFile.Sheets("List View").Range("D3")
    RSSFile.Close True
    Windows("Report.xlsm").Activate


    '' and performs a lookup against the DATASHEET tab, matching the Account Number. It currently only
    '' shows values if they are found/non-zero.  It also clears old data from the columns
    '' This also copies the outputed data and pastes only the values.
    '' By doing so, we are saving future memory space, so that it doesn't need to recalc everytime you open
    '' the file, only when you run this macro.

    ProcessSheet Sheets("SHEET1")
    ProcessSheet Sheets("SHEET2")
    ProcessSheet Sheets("SHEET3")
    ProcessSheet Sheets("SHEET4")

    Sheets("DATASHEET").Visible = xlSheetHidden

    With Application
        .EnableEvents = True              'Turns background code back on.
        .ScreenUpdating = True            'Turns ScreenUpdating back on.
        .DisplayAlerts = True             'Turns Alerts back on.
    End With

    MsgBox "Import Complete"

End Sub
Optimize multiple nested for loops in python

Optimize multiple nested for loops in python


By : mochhk
Date : March 29 2020, 07:55 AM
Any of those help With Numpy arrays, the way to optimize the computations is to use vectorized operations as much as possible. In your example, since it looks like you're summing the elements of each array, you should keep the array 1-dimensional and just use the sum function directly:
shadow
Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk