Netlogo: Assign variable using probabilities - list

How to assign a string or integer variable to turtle, using probabilities of the variables in a group/list? For example it is 0.4 probability that one specific variable is used from specific group/list. The function selects randomly the variable based on probability. I need to use the same method afterwards to choose a variable (string) from a list according to probability.
In python it should be:
import random
def random_value(probability_list, values):
r = random.random()
index = 0
while(r >= 0 and index < len(probability_list)):
r -= probability_list[index]
index += 1
value=values[index - 1]
value_index=index-1
return value,value_index
I tried it in Netlogo like below (get error that index is -1) but is there a better way?
globals [random_nr probabilities some_list index]
to initialize-variables
set some_list[]
set probabilities[]
end
to random_pick
set random_nr random-float 1
set probabilities [0.1 0.2 0.4 0.3]
set some_list ["String1" "String2" "String3" "String4"]
set index 0
while [(random_nr >= 0) and (length probabilities < index)] [
set random_nr random_nr - item index probabilities
set index index + 1 ]
set index index - 1
end

is there a better way?
Yes there is.
NetLogo 6.0 comes with the rnd extension bundled. (You can also download the extension separately for earlier versions of NetLogo.)
The rnd extension offers the rnd:weighted-one-of-list primitive, which does exactly what you're trying to do:
extensions [ rnd ]
to-report pick
let probabilities [0.1 0.2 0.4 0.3]
let some_list ["String1" "String2" "String3" "String4"]
report first rnd:weighted-one-of-list (map list some_list probabilities) last
end
Let me unpack the last expression a bit:
The role of (map list some_list probabilities) is to "zip" the two lists together, in order to get a list of pairs of the form: [["String1" 0.1] ["String2" 0.2] ["String3" 0.4] ["String4" 0.3]].
That list of pairs is passed as the first argument to rnd:weighted-one-of-list. We pass last as the second argument of rnd:weighted-one-of-list to tell it that it should use the second item of each pair as the probability.
rnd:weighted-one-of-list then picks one of the pairs at random, and returns that whole pair. But since we're only interested in the first item of the pair, we use first to extract it.
To understand how that code works, it helps to understand how Anonymous procedures work. Note how we make use of the concise syntax for passing list to map and for passing last to rnd:weighted-one-of-list.

Don't overlook the rnd extension:
https://github.com/NetLogo/Rnd-Extension
But it is possible to do it essentially as you propose. I'll to that here, but it would be better to use explicit arguments.
to-report random-pick
let _r random-float 1
let _ps [0.1 0.2 0.4 0.3]
let _lst ["String1" "String2" "String3" "String4"]
let _i 0
while [_r >= item _i _ps] [
set _r (_r - item _i _ps)
set _i (_i + 1) ]
report item _i _lst
end

Related

How to generate the random values of map from a given set of values and then store the key and values into separate variables in scala

I am trying to generate the 1000 random key-val map pairs from the given(statically defined) 2 map key-val pairs in scala and also later i would want to break the key and value pairs and store them into separate variables
Whatever i have tried:
object methodTest extends App{
val testMap = Map("3875835"->"ABCDE","316067107"->"EFGHI")
def getRandomElement(seq: Map[String,String]): Map[String,String] = {
seq(Random.nextInt(seq.length))
}
var outList = List.empty[Map[String,String]]
for(i<-0 to 1000){
outList+=getRandomElement(testMap)
}
print(outList)
}
The Output should generate 1000 Key-val pairs of map like i am showing below
[3875835,ABCDE]
[316067107,EFGHI]
[3875835,ABCDE]
[316067107,EFGHI]
[316067107,EFGHI]
............
............
............. upto 1000 random key-val pairs
Please help me figure out where i am going wrong and let me know How to resolve it, if any issue regarding the requirement, please feel free to comment for it
You can transform your seed map testMap into sequence of key/value tuples using .toSeq and then generate key/value pairs by iterating over the list of numbers from 0 until 1000, associating each number to a random choice between first or second element of the seed:
import scala.util.Random
val testMap = Map("3875835" -> "ABCDE", "316067107" -> "EFGHI")
val seed = testMap.toSeq
val keyValuesList = (0 until 1000).map(index => seed(Random.nextInt(seed.size)))
Note: 0 until 1000 will return all the numbers from 0 to 1000 excluded, so 1000 numbers. If you use 0 to 1000 you will get all the numbers from 0 to 1000 included, so 1001 numbers.
If you want to print the resulting list, you can use .foreach method with println function as argument:
keyValuesList.foreach(println)
And you will get:
(3875835,ABCDE)
(316067107,EFGHI)
(3875835,ABCDE)
(3875835,ABCDE)
(316067107,EFGHI)
(3875835,ABCDE)
...
if you want to keep only the keys, you can iterate on the list using .map method, taking only the first element of the tuple by using ._1 method, that retrieve the first element of a tuple:
val keys = keyValuesList.map(keyValuePair => keyValuePair._1)
And if you want only a list containing all second elements of each pair:
val values = keyValuesList.map(keyValuePair => keyValuePair._2)

Find the index number of given value from the list using TCL

Need to find the index number of given value from list. I have a value from the list ,But i need to find the index number of of the value.
set i 0.0001646481396164745
set X [list 1.215647671415354e-7 1.1284486163276597e-6 4.538622670224868e-5 4.4706815970130265e-5 8.492852430208586e-6 6.077577836549608e-6 3.1041158763400745e-6 0.00015045881445985287 4.1016753016265284e-7 1.165599314845167e-6 1.8736355968940188e-6 2.9444883693940938e-5 2.5420340534765273e-5 2.0819682049477706e-6 9.529731869406532e-6 8.549810104341304e-7 1.558014082547743e-5 8.079621693468653e-6 4.868444739258848e-5 0.0001646481396164745]
have to find the index value of i from list X using TCL.
It can be easily solved with lsearch:
set c [lsearch $X $i]
If you're looking for a floating point value in a list where you only know the approximate value, you can't use lsearch. Instead you have to do it yourself:
proc findApprox {theList theValue {epsilon 1e-9}} {
set idx 0
foreach x $theList {
# Found if the difference between the list item and the target is less than epsilon
if {abs($theValue - $x) < $epsilon} {
return $idx
}
incr idx
}
return -1
# Or [error "not found"] if you prefer
}
set x [findApprox $X $i]
Note the epsilon optional argument. That's because how close you have to get depends on knowledge of the domain of the input data; it's not something that it is easy for a basic algorithm to determine for you.

Nested Foreach List NetLogo

Hi,
In Netlogo v.6, I'm trying to calculate a time-weighted measure of a peer's cooperative behavior. The point is, I can't figure out exactly how to do a nested foreach in NetLogo.
My current approach:
setup a list: reputation_peer
setup a list: reputation_peer_list, of variable 1 (behavior) and variable 2 (time tick)
Each encounter, add reputation_list to reputation_peer, making the reputation_peer a list of lists
calculate the weighted reputation:
taking item 2 of each list in reputation_peer, which is the time tick of that encounter
and dividing it by the current time tick.
This gives a fraction: tick of that encounter/total time ticks
setup a list reputation_weighted
To weigh the reputations, multiply the time fraction with the first item of reputation_peer, which is the behavior variable
Then, I want to know the reputation_current, by taking all values from reputation_weighted and adding them up.
I'm messing around with the foreach function but I can't seem to figure it out.
How would such an approach be coded in Netlogo?
My current code is (setting reputation_peer myself to test it):
to calculate_reputation
set reputation_peer [[8 4][9 2][10 3][11 2][14 1]]
if ticks > 0 [
foreach reputation_peer [x -> set reputation_peer_list list (item 0 x) ((item 1 x) / ticks )
set reputation_peer_list_2 lput reputation_peer_list reputation_peer_list_2]
foreach reputation_peer_list_2 [x -> set reputation_peer_list_list (list (item 0 x * item 1 x))]
foreach reputation_peer_list_list [x -> set reputation_peer_current reputation_peer_current + x]
]
end
I don't really know whether I'm doing it right, but mainly, this code seems a very bulky with all the list_list things going on. I'm guessing it could be a lot simpler.
Would greatly help me out if you guys have some tips.
I'm not 100% sure of what you're expecting as final output, but maybe this does what you need?
to calc-rep-2
set reputation_peer [[8 4][9 2][10 3][11 2][14 1]]
let weighted_rep_list []
if ticks > 0 [
foreach reputation_peer [ x ->
; Pull out the values from reputation_peer for ease of use
let encounter_behavior item 0 x
let encounter_time item 1 x
; Calculate the time fraction for the current item
let time_fraction encounter_time / ticks
; Calculate the weighted reputations
let weighted_rep encounter_behavior * time_fraction
; Add the weighted rep to the list of weighted reps
set weighted_rep_list lput weighted_rep weighted_rep_list
]
; Now, weighted_rep_list is a list of weighted reputations
print weighted_rep_list
; Get the sum of the list
print sum weighted_rep_list
]
tick
end

Excel - Identify unique value patterns and return output in descending order across columns, optimized for 500,000+ rows

This is the third and final remaining problem to a massive data cleaning task I have been working on for over a year. Thank you Stack Overflow community for helping figure out:
Problem 1- Index multiple columns and Match distinct values....
Problem 2- Count unique values that match ID, optimized for 100,000+ cases.
I'm not 100% sure if the following is achievable in excel, but I'll do my best to describe the data cleaning and organization challenge I'm faced with.
I have a series of data markers/attributes that are in a random order across 24 columns, spanning 500,000+ rows. Image 1 below is an example of what the data looks like in raw form, presented across 12 columns and spanning 22 rows for illustrative simplicity. Columns A through L contain the raw data and Columns M through X represent the desired output.
SUMMARY OF THE TASK: What needs to be accomplished is a series of matching functions that search through all indexed columns (in this case columns A through L) to identify unique values (e.g. 1), search for the value in range (in this case A2:L21 range), identify the adjacent values to the unique value (for value 1, adjacent values are 2 and 13-XR), then output them in a descending sequence from most frequently occurring value to least frequently occurring in each row that contains any of the values in question (in this case, 1 occurs 5 times and is placed in M2 through M6; 2 occurs 3 times and is placed in N2 through N6; and 13-XR occurs 2 times and is placed in O2 through O6).
To clarify, below is a step by step description using colours to illustrate the pattern matching in the raw data (columns A through L) and how these patterns should then presented in the output (columns M through X). I've sectioned off each of the following images into the six patterns that are in the raw data.
The above image is the first pattern that would be identified by the VBA solution. It would identify "1" as a unique value and search through the A:L range for number of instances of "1" (highlighted in blue), then identify all the values that can be found adjacent in the same row: "2" in rows 3, 5, and 6 (highlighted in green); and "13-XR" in rows 4 and 5 (highlighted in pink). This would then need to be done for "2", identifying the adjacent values ("1" and "13-XR"), and then for "13-XR", identifying ("1" and "2" as adjacent values). The output would return the unique values with the most frequently occurring in Column M ("1" occurs 5 times), then the second most occurring in Column N ("2" occurs 3 times), and the third most occurring in Column O ("13-XR" occurs 2 times).
The above is little more complex. The VBA would identify "3" as a unique value, search through the A:L range for other instances of "3" and identify all the values that are adjacent to it (in this case, "4", "7", and "9"). It would then do the same for "4", identifying all adjacent values (only "3"); then for "7", identifying adjacent values ("9", "3", and "12"); then for "9" identifying ("7", and "3"); and finally, for "12" identifying adjacent values (only "7"). Then for each row where any of these values are present, the output would return a "3" in column M (occurring three times) and a "7" in column N (also occurring three times); if counts are equal, they could be presented in ascending fashion A to Z or smallest to largest... or just random, the ordering of equal counts is arbitrary for my purposes. "9" would be returned in column O as it occurs two times, then "4" in column P and "12" in column Q, as they both occur once but 12 is greater than 4.
The above image represents what is likely to be a common occurrence, where there is only one unique value. Here, "5" is not identified in any other columns in the range. It is thus returned as "5" in column M for each row where a "5" is present.
This will be another of the more common occurrences, where one value may be present in one row and two values present in another row. In this instance "6" is only identified once in the range and "8" is the only adjacent value found. When "8" is searched for it only returns one instance of an adjacent value "6". Here, "8" occurs twice and "6" only once, thus resulting in "8" imputed in column M and "6" imputed in column N wherever an "8" or a "6" are present in the row.
Here "10", "111", "112", "543", "433", "444", and "42-FG" are identified as unique values associated with one another in the A:L range. All values except "10" occur twice, which are returned in columns M through S in descending order.
This final pattern is identified in the same manner as above, just with more unique values (n=10).
FINAL NOTES: I have no idea how to accomplish this within excel, but I'm hoping someone else has the knowledge to move this problem forward. Here are some additional notes about the data that might help towards a resolution:
The first column will always be sorted in ascending order. I can do additional custom sorts if it simplifies things.
Out of the ~500,000 rows, 15% only have one attribute value (one value in column A), 30% have two attribute values (1 value in col A & 1 value in col B), 13% have three attribute values (1 value in col A, B, & C).
I have presented small numbers in this example. The actual raw data values in each cell will be closer to 20 characters in length.
A solution that does everything except present the patterns in descending order would be absolutely cool. The sorting would be great but I can live without it if it causes too much trouble.
If anything in this description needs further clarification, or if I can provide additional information, please let me know and I'll adjust as needed.
Thanks in advance to anyone who can help solve this final challenge of mine.
ADDENDUM:
There was a memory error happening with the full data set. #ambie figured out the source of the error was adjacent chains (results) numbering in the 1000s (trying to return results across 1000s of columns). Seems the problem is not with the solution or the data, just hitting a limitation within excel. A possible solution to this is (see image below) to add two new columns (ATT_COUNT as column M; ATT_ALL as column Z). ATT_COUNT in Column M would return the total number of unique values that would ordinarily be returned across columns. Only up to the top 12 most frequently occurring values would be returned in columns N through Y (ATT_1_CL through ATT_12_CL). To get around the instances where ATT_COUNT is > 12 (& upwards of 1000+), we can return all the unique values in space delimited format in ATT_ALL (column Z). For example, in the image below, rows 17, 18, 19, and 21, have 17 unique values in the chain. Only the first 12 most frequently occurring values are presented in columns N through Y. All 17 values are presented in space delimited format in column Z.
Here is a link to this mini example test data.
Here is a link to a mid sized sample of test data of ~50k rows.
Here is a link to the full sized sample test data of ~500k rows.
We don't normally provide a 'code for you service' but I know in previous questions you have provided some sample code that you've tried, and I can see how you wouldn't know where to start with this.
For your future coding work, the trick is to break the problem down into individual tasks. For your problem, these would be:
Identify all the unique values and acquire a list of all the adjacent values - fairly simple.
Create a list of 'chains' which link one adjacent value to the next - this is more awkward because, although the list appears sorted, the adjacent values are not, so a value relatively low down in the list might be adjacent to a higher value that is already part of a chain (the 3 in your sample is an example of this). So the simplest thing would be to assign the chains only after all the unique values have been read.
Map of each unique value to its appropriate 'chain' - I've done this by creating an index for the chains and assigning the relevant one to the unique value.
Collection objects are ideal for you because they deal with the issue of duplicates, allow you to populate lists of an unknown size and make value mapping easy with their Key property. To make the coding easy to read, I've created a class containing some fields. So first of all, insert a Class Module and call it cItem. The code behind this class would be:
Option Explicit
Public Element As String
Public Frq As Long
Public AdjIndex As Long
Public Adjs As Collection
Private Sub Class_Initialize()
Set Adjs = New Collection
End Sub
In your module, the tasks could be coded as follows:
Dim data As Variant, adj As Variant
Dim uniques As Collection, chains As Collection, chain As Collection
Dim oItem As cItem, oAdj As cItem
Dim r As Long, c As Long, n As Long, i As Long, maxChain As Long
Dim output() As Variant
'Read the data.
'Note: Define range as you need.
With Sheet1
data = .Range(.Cells(2, "A"), _
.Cells(.Rows.Count, "A").End(xlUp)) _
.Resize(, 12) _
.Value2
End With
'Find the unique values
Set uniques = New Collection
For r = 1 To UBound(data, 1)
For c = 1 To UBound(data, 2)
If IsEmpty(data(r, c)) Then Exit For
Set oItem = Nothing: On Error Resume Next
Set oItem = uniques(CStr(data(r, c))): On Error GoTo 0
If oItem Is Nothing Then
Set oItem = New cItem
oItem.Element = CStr(data(r, c))
uniques.Add oItem, oItem.Element
End If
oItem.Frq = oItem.Frq + 1
'Find the left adjacent value
If c > 1 Then
On Error Resume Next
oItem.Adjs.Add uniques(CStr(data(r, c - 1))), CStr(data(r, c - 1))
On Error GoTo 0
End If
'Find the right adjacent value
If c < UBound(data, 2) Then
If Not IsEmpty(data(r, c + 1)) Then
On Error Resume Next
oItem.Adjs.Add uniques(CStr(data(r, c + 1))), CStr(data(r, c + 1))
On Error GoTo 0
End If
End If
Next
Next
'Define the adjacent indexes.
For Each oItem In uniques
'If the item has a chain index, pass it to the adjacents.
If oItem.AdjIndex <> 0 Then
For Each oAdj In oItem.Adjs
oAdj.AdjIndex = oItem.AdjIndex
Next
Else
'If an adjacent has a chain index, pass it to the item.
i = 0
For Each oAdj In oItem.Adjs
If oAdj.AdjIndex <> 0 Then
i = oAdj.AdjIndex
Exit For
End If
Next
If i <> 0 Then
oItem.AdjIndex = i
For Each oAdj In oItem.Adjs
oAdj.AdjIndex = i
Next
End If
'If we're still missing a chain index, create a new one.
If oItem.AdjIndex = 0 Then
n = n + 1
oItem.AdjIndex = n
For Each oAdj In oItem.Adjs
oAdj.AdjIndex = n
Next
End If
End If
Next
'Populate the chain lists.
Set chains = New Collection
For Each oItem In uniques
Set chain = Nothing: On Error Resume Next
Set chain = chains(CStr(oItem.AdjIndex)): On Error GoTo 0
If chain Is Nothing Then
'It's a new chain so create a new collection.
Set chain = New Collection
chain.Add oItem.Element, CStr(oItem.Element)
chains.Add chain, CStr(oItem.AdjIndex)
Else
'It's an existing chain, so find the frequency position (highest first).
Set oAdj = uniques(chain(chain.Count))
If oItem.Frq <= oAdj.Frq Then
chain.Add oItem.Element, CStr(oItem.Element)
Else
For Each adj In chain
Set oAdj = uniques(adj)
If oItem.Frq > oAdj.Frq Then
chain.Add Item:=oItem.Element, Key:=CStr(oItem.Element), Before:=adj
Exit For
End If
Next
End If
End If
'Get the column count of output array
If chain.Count > maxChain Then maxChain = chain.Count
Next
'Populate each row with the relevant chain
ReDim output(1 To UBound(data, 1), 1 To maxChain)
For r = 1 To UBound(data, 1)
Set oItem = uniques(CStr(data(r, 1)))
Set chain = chains(CStr(oItem.AdjIndex))
c = 1
For Each adj In chain
output(r, c) = adj
c = c + 1
Next
Next
'Write the output to sheet.
'Note: adjust range to suit.
Sheet1.Range("M2").Resize(UBound(output, 1), UBound(output, 2)).Value = output
This isn't the most efficient way of doing it, but it does make each task more obvious to you. I'm not sure I understood the full complexities of your data structure, but the code above does reproduce your sample, so it should give you something to work with.
Update
Okay, now I've seen your comments and the real data, below is some revised code which should be quicker and deals with the fact that the apparently 'empty' cells are actually null strings.
First of all create a class called cItem and add code behind:
Option Explicit
Public Name As String
Public Frq As Long
Public Adj As Collection
Private mChainIndex As Long
Public Property Get ChainIndex() As Long
ChainIndex = mChainIndex
End Property
Public Property Let ChainIndex(val As Long)
Dim oItem As cItem
If mChainIndex = 0 Then
mChainIndex = val
For Each oItem In Me.Adj
oItem.ChainIndex = val
Next
End If
End Property
Public Sub AddAdj(oAdj As cItem)
Dim t As cItem
On Error Resume Next
Set t = Me.Adj(oAdj.Name)
On Error GoTo 0
If t Is Nothing Then Me.Adj.Add oAdj, oAdj.Name
End Sub
Private Sub Class_Initialize()
Set Adj = New Collection
End Sub
Now create another class called cChain with code behind as:
Option Explicit
Public Index As Long
Public Members As Collection
Public Sub AddItem(oItem As cItem)
Dim oChainItem As cItem
With Me.Members
Select Case .Count
Case 0 'First item so just add it.
.Add oItem, oItem.Name
Case Is < 12 'Fewer than 12 items, so add to end or in order.
Set oChainItem = .item(.Count)
If oItem.Frq <= oChainItem.Frq Then 'It's last in order so just add it.
.Add oItem, oItem.Name
Else 'Find its place in order.
For Each oChainItem In Me.Members
If oItem.Frq > oChainItem.Frq Then
.Add oItem, oItem.Name, before:=oChainItem.Name
Exit For
End If
Next
End If
Case 12 'Full list, so find place and remove last item.
Set oChainItem = .item(12)
If oItem.Frq > oChainItem.Frq Then
For Each oChainItem In Me.Members
If oItem.Frq > oChainItem.Frq Then
.Add oItem, oItem.Name, before:=oChainItem.Name
.Remove 13
Exit For
End If
Next
End If
End Select
End With
End Sub
Private Sub Class_Initialize()
Set Members = New Collection
End Sub
Finally, your module code would be:
Option Explicit
Public Sub ProcessSheet()
Dim data As Variant
Dim items As Collection, chains As Collection
Dim oItem As cItem, oAdj As cItem
Dim oChain As cChain
Dim txt As String
Dim r As Long, c As Long, n As Long
Dim output() As Variant
Dim pTick As Long, pCount As Long, pTot As Long, pTask As String
'Read the data.
pTask = "Reading data..."
Application.StatusBar = pTask
With Sheet1
data = .Range(.Cells(2, "A"), _
.Cells(.Rows.Count, "A").End(xlUp)) _
.Resize(, 12) _
.Value2
End With
'Collect unique and adjacent values.
pTask = "Finding uniques "
pCount = 0: pTot = UBound(data, 1): pTick = 0
Set items = New Collection
For r = 1 To UBound(data, 1)
If ProgressTicked(pTot, pCount, pTick) Then
Application.StatusBar = pTask & pTick & "%"
DoEvents
End If
For c = 1 To UBound(data, 2)
txt = data(r, c)
If Len(txt) = 0 Then Exit For
Set oItem = GetOrCreateItem(items, txt)
oItem.Frq = oItem.Frq + 1
'Take adjacent on left.
If c > 1 Then
txt = data(r, c - 1)
If Len(txt) > 0 Then
Set oAdj = GetOrCreateItem(items, txt)
oItem.AddAdj oAdj
End If
End If
'Take adjacent on right.
If c < UBound(data, 2) Then
txt = data(r, c + 1)
If Len(txt) > 0 Then
Set oAdj = GetOrCreateItem(items, txt)
oItem.AddAdj oAdj
End If
End If
Next
Next
'Now that we have all the items and their frequencies,
'we can find the adjacent chain indexes by a recursive
'call of the ChainIndex set property.
pTask = "Find chain indexes "
pCount = 0: pTot = items.Count: pTick = 0
Set chains = New Collection
n = 1 'Chain index.
For Each oItem In items
If ProgressTicked(pTot, pCount, pTick) Then
Application.StatusBar = pTask & pTick & "%"
DoEvents
End If
If oItem.ChainIndex = 0 Then
oItem.ChainIndex = n
Set oChain = New cChain
oChain.Index = n
chains.Add oChain, CStr(n)
n = n + 1
End If
Next
'Build the chains.
pTask = "Build chains "
pCount = 0: pTot = items.Count: pTick = 0
For Each oItem In items
If ProgressTicked(pTot, pCount, pTick) Then
Application.StatusBar = pTask & pTick & "%"
DoEvents
End If
Set oChain = chains(CStr(oItem.ChainIndex))
oChain.AddItem oItem
Next
'Write the data to our output array.
pTask = "Populate output "
pCount = 0: pTot = UBound(data, 1): pTick = 0
ReDim output(1 To UBound(data, 1), 1 To 12)
For r = 1 To UBound(data, 1)
If ProgressTicked(pTot, pCount, pTick) Then
Application.StatusBar = pTask & pTick & "%"
DoEvents
End If
Set oItem = items(data(r, 1))
Set oChain = chains(CStr(oItem.ChainIndex))
c = 1
For Each oItem In oChain.Members
output(r, c) = oItem.Name
c = c + 1
Next
Next
'Write the output to sheet.
'Note: adjust range to suit.
pTask = "Writing data..."
Application.StatusBar = pTask
Sheet1.Range("M2").Resize(UBound(output, 1), UBound(output, 2)).Value = output
Application.StatusBar = "Ready"
End Sub
Private Function GetOrCreateItem(col As Collection, key As String) As cItem
Dim obj As cItem
'If the item already exists then return it,
'otherwise create a new item.
On Error Resume Next
Set obj = col(key)
On Error GoTo 0
If obj Is Nothing Then
Set obj = New cItem
obj.Name = key
col.Add obj, key
End If
Set GetOrCreateItem = obj
End Function
Public Function ProgressTicked(ByVal t As Long, ByRef c As Long, ByRef p As Long) As Boolean
c = c + 1
If Int((c / t) * 100) > p Then
p = p + 1
ProgressTicked = True
End If
End Function

Random.randint on lists in Python

I want to create a list and fill it with 15 zeros, then I want to change the 0 to 1 in 5 random spots of the list, so it has 10 zeros and 5 ones, here is what I tried
import random, time
dasos = []
for i in range(1, 16):
dasos.append(0)
for k in range(1, 6):
dasos[random.randint(0, 15)] = 1
Sometimes I would get anywhere from 0 to 5 ones but I want exactly 5 ones,
if I add:
print(dasos)
...to see my list I get:
IndexError: list assignment index out of range
I think the best solution would be to use random.sample:
my_lst = [0 for _ in range(15)]
for i in random.sample(range(15), 5):
my_lst[i] = 1
You could also consider using random.shuffle and use the first 5 entries:
my_lst = [0 for _ in range(15)]
candidates = list(range(15))
random.shuffle(candidates)
for i in candidates[0:5]:
my_lst[i] = 1
TL;DR: Read the the Python random documentation, this can be done in multiple ways.