I'm trying to create a random map, with lists inside the main list representing the lines. The "createBlankMap" function works perfectly fine, for creating a placeholder map, and the "displayMap" function also works fine, for printing the map and changing the 0s or 1s to "." or "#". But when i try to update the blank map, using the "generateMap" function, all the nested lists get the same random generated value, instead of all of them generating random generated values.  # -*- coding: utf-8 -*- import random  def displayMap(canvas):     for i in range(len(canvas)): #LINE         for j in range(len(canvas[i])):             if canvas[i][j] == 0:                 print(".", end='')             elif canvas[i][j] == 1:                 print("#", end='')             else:                 break         print()  def createBlankMap(x,y):     MAP = []     LINE = []     for j in range(y): #COLUMN         LINE.append(0)     for i in range(x): #LINE         MAP.append(LINE)     return MAP  def generateMap(canvas):     for i in range(len(canvas)): #LINE         for j in range(len(canvas[i])): #COLUMN             choice = random.uniform(0,1)             if choice &lt; 0.5:                 canvas[i][j] = 1             else:                 canvas[i][j] = 0     return canvas  displayMap(generateMap(createBlankMap(5, 10)))   The output is always like this: (remembering those values are randomly generated, so they're different every time i run the program).  ###.##.#.# ###.##.#.# ###.##.#.# ###.##.#.# ###.##.#.#   So basically, i want all the lines to have random generated values, instead of them repeating the first one.
410
I needed to create a list of lists in Python, so I typed the following: my_list = [[1] * 4] * 3  The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]    Then I changed one of the innermost values: my_list[0][0] = 5  Now my list looks like this: [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]    which is not what I wanted or expected. Can someone please explain what's going on, and how to get around it?
3458
I'm starting/started a 2D tilemap RPG game in Java and I want to implement random map generation. I have a list of different tiles, (dirt/sand/stone/grass/gravel etc) along with water tiles and path tiles, the problem I have is that I have no idea where to start on generating a map randomly.  It would need to have terrain sections (Like a part of it will be sand, part dirt, etc.) Similar to how Minecraft is where you have different biomes and they seamlessly transform into each other. Lastly I would also need to add random paths into this as well going in different directions all over the map.  I'm not asking anyone to write me all the code or anything, just piont me into the right direction please.  tl;dr - Generate a tile map with biomes, paths and make sure the biomes seamlessly go into each other.
31694
Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.   What is a simple solution? What is an effective solution to reduce memory usage or run on a slower CPU?
12929
Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway.  I just want a very simple prime generator (nothing fancy).   import math  def main():     count = 3     one = 1     while one == 1:         for x in range(2, int(math.sqrt(count) + 1)):             if count % x == 0:                  continue             if count % x != 0:                 print count          count += 1
9898
Code like this often happens: l = [] while foo:     # baz     l.append(bar)     # qux  This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements. In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient. I understand that code like this can often be refactored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers?
61713
I'm struggling with coming up with an elegant solution to generating random events in the game that I'm working on.  Say there are 4 classes of events that can happen, with varying events in those classes that may occur.  So something along the lines of   main_events = {"common event", "not so common event", "somewhat rare event", "rare event"} sub_events[0] = {"common event 1", "common event 2",..} ...   I have a somewhat kludgey solution in place that first just has a random number generated between 0 and 100, and if the number falls within a given range then a main event will be triggered.  Then I'll do another random roll to see which sub event occurs.  Is there a better solution than something along these lines?  Like I mention, it doesn't feel very elegant, and I'd like to make it easily expandable for the addition of future events.
17563
Can you create images like this:    when you have something like  0 = green (#54ff00) 1 = white (#ffffff) 2 = red   (#ff0000) 3 = blue  (#0048ff)  Image (Python list of integers defined above): [[2,0,0,0,0,0,0],  [0,3,0,0,0,0,0],  [0,3,2,1,1,0,0],  [0,3,2,2,2,1,1],  [0,3,2,0,0,1,0],  [0,0,0,0,0,1,0],  [0,0,0,0,0,1,0]]   with TikZ?  How far I got  The following MWE defines all colors, produces a grid of the correct size (though the size is determined by hand):  \documentclass[varwidth=true, border=2pt]{standalone} \usepackage{tikz} \usepackage{xcolor}  \begin{document}     \newcommand\n{7}     \definecolor{green}{HTML}{54FF00}     \definecolor{wite}{HTML}{FFFFFF}     \definecolor{red}{HTML}{FF0000}     \definecolor{blue}{HTML}{0048FF}     \begin{tikzpicture}         \foreach \x in {1,...,\n}{             \foreach \y in {1,...,\n}{                 \begin{scope}[shift={(\x,\y)}]                   \draw [fill=green] (0,0) rectangle (1,1);                 \end{scope}             }         }     \end{tikzpicture} \end{document}   Of course, I could simpy make a lot of adjusted                   \begin{scope}[shift={(\x,\y)}]                   \draw [fill=green] (0,0) rectangle (1,1);                 \end{scope}   but I've wondered if this can (with reasonable effort) be done in TikZ / LaTeX.  My problem is giving TikZ the color array. I don't have any idea how to do this. I only know two types of looks in TikZ:  \foreach \x in {0,1,2,3,4,5}{...} \foreach \number in {1,...,\n}{...}   I have never seen a nested over a 2D-array. All I have seen so far were 1D-Arrays of tuples (with fixed tuple size).
1360
I want to create a list of lambda objects from a list of constants in Python; for instance:  listOfNumbers = [1,2,3,4,5] square = lambda x: x * x listOfLambdas = [lambda: square(i) for i in listOfNumbers]   This will create a list of lambda objects, however, when I run them:  for f in listOfLambdas:     print f(),   I would expect that it would print  1 4 9 16 25   Instead, it prints:  25 25 25 25 25   It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.  EDIT: a bit more of trying things and such came up with this:  listOfLambdas = [] for num in listOfNumbers:     action = lambda: square(num)     listOfLambdas.append(action)     print action()   Prints the expected squares from 1 to 25, but then using the earlier print statement:  for f in listOfLambdas:     print f(),   still gives me all 25s. How did the existing lambda objects change between those two print calls?  Related question:
90357
I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?  map&lt;Id,SObject&gt; mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property'); map&lt;Id,SObject&gt; mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');  for ( Lease__c l: Trigger.New ) {      if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {          lProperties = new List&lt;SObject&gt;{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};              for ( SObject p: lProperties ) {                  for ( String fm: FieldMap.keyset() ) {                      if ( p.get(FieldMap.get(fm)) != Null) {                         l.put(fm,p.get(FieldMap.get(fm)));                     }                  }             }     } }
55864
This is something I've pseudo-solved many times and have never quite found a solution for.  The problem is to come up with a way to generate N colors, that are as distinguishable as possible where N is a parameter.
90595
I have created some TikZ code to produce the diagram below (slightly simplified). This is my first real shot at TikZ and its taken me about 8 hours now to get this far. But I don't really begrudge the time, time spent learning is time well spent.  It is loosely based on .  I would like to have a different (variable) number of nodes in each layer, and would like to maintain the connection.  My current idea was to have a list of lists like {{1..3},{1..5},{1..7},{1..4},{1..3}} then I guesss i could use a nested for-each off the index. But that has 2 problems: I would lose my layer number, which I could get around by using count. Secondly, more majorly, I don't seen a good way of knowing how big the next layer is (to make the connections).     \documentclass{article} \usepackage{mathptmx} \usepackage{tikz} \usetikzlibrary{arrows} \usetikzlibrary{calc} \begin{document}   \def\layersep{3.5cm} \def\topnum{5} %\font\nullfont=cmr10 \begin{tikzpicture}[shorten &gt;=1pt,-&gt;,draw=black!50, node distance=\layersep]     \tikzstyle{neuron}=[circle,draw,fill=white!25,minimum size=25pt,inner sep=0pt]     \tikzstyle{bias neuron}=[neuron,dashed]       \foreach \y in {2,...,4}                 \foreach \x in {1,...,5}             \path   node[neuron] (L_\y_\x) at (\x cm,\y*\layersep) {$\sigma(\cdot)$};   %      \foreach  \x in {1,...,5}             \path  node[neuron] (L_1_\x) at (\x cm,1*\layersep) {$x_\x$};      \foreach  \x in {1,...,5}             \path  node[neuron] (L_5_\x) at (\x cm,5*\layersep) {$s_{m}(\cdot)$};       %Add Biases     \foreach \y in {1,...,4}     {         \path node[bias neuron] (B_\y) at (6 cm, 0.55*\layersep+\y*\layersep) {1};         \pgfmathtruncatemacro\nextlayer{\y+1}         \foreach \dest in {1,...,5}             \path (B_\y) edge[dashed] (L_\nextlayer_\dest.south);     }       % Connect every node in the input layer with every node in the     % hidden layer.     \foreach \layer in {1,...,4}         \pgfmathtruncatemacro\nextlayer{\layer+1}         \foreach \source in {1,...,5}             \foreach \dest in {1,...,5}                 \path (L_\layer_\source) edge (L_\nextlayer_\dest);   \end{tikzpicture} \end{document}
27093
I occasionally see the list slice syntax used in Python code like this:  newList = oldList[:]   Surely this is just the same as:  newList = oldList   Or am I missing something?
120783
This is what I have so far:    myArray.map!{ rand(max) }   Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?  Edit: I'd really like to see this done w/o loop - if at all possible.
80428
I have a class like this:  public class myClass {   public List&lt;myOtherClass&gt; anewlist = new List&lt;myOtherClass&gt;;    public void addToList(myOtherClass tmp)   {     anewList.Add(tmp);   }  }   So I call "addToList" a hundred times, each adding a unique item to the list.  I've tested my items to show that before I run the "addToList" method, they are unique.  I even put a line in to test "tmp" to make sure it was what I was expecting.  However, when I do this (lets say myClass object is called tmpClass):  int i = tmpClass.anewList.Count(); for (int j = 0; j&lt;i; j++) {    //write out each member of the list based on index j... }   I get the same exact item, and it's the last one that was written into my list.  It's as if when I add, I'm overwriting the entire list with the last item I've added.    Help?  This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0.  Still no dice.  Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.  :)  UPDATE: Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {         Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena    Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {     Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output...  I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena
24071
I'm trying to understand Python's approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within main(), but not the value of n?  def f(n, x):     n = 2     x.append(4)     print('In f():', n, x)  def main():     n = 1     x = [0,1,2,3]     print('Before:', n, x)     f(n, x)     print('After: ', n, x)  main()   Output:  Before: 1 [0, 1, 2, 3] In f(): 2 [0, 1, 2, 3, 4] After:  1 [0, 1, 2, 3, 4]
107210
I would like to draw a set of random functions f(x) from point A to point B with a fixed random seed for each function. In other words, I would like to have functions which look the same each time I create the document, depending on their associated random seed.  So far, I have this:  \documentclass[tikz]{standalone}  % Random path from A=(0,0) to B=(1,1) with seed #1 and color #2 \newcommand\randompath[2]{% \pgfextra{\pgfmathsetseed{#1}}% \addplot[#2,domain=0:1,samples=5,smooth] { x+rand*(x)*(1-x)};% }  \begin{document}  \begin{tikzpicture}   \begin{axis}[xmin=0,xmax=1,ymin=0,ymax=1]     \randompath{1}{red}   % 1st function     \randompath{1}{blue}  % 2nd function     \randompath{1}{green} % 3rd function   \end{axis} \end{tikzpicture}  \end{document}   However, the three functions are not identical and change their shape on recreation. Therefore, the \pgfmathsetseed does not seem to work as intended?   How can I achieve it that for a chosen seed number, the drawn \randompath function looks alway the same?
53780
I am trying to draw rectangles, each of which has a corresponding value, which will be mapped into a color from a color map based on the value. This is how I want the write the code. What is missing is the mapping from \myvalue to \mycolor.  \documentclass{standalone}  \usepackage{colortbl} \usepackage{pgfplots} \usepackage{pgfplotstable}  \pgfplotsset{compat=1.9}  \newcommand*{\ListOfRectanglesColor}{%   0/0/1/1/blue,   1/1/2/2/red, }  \newcommand*{\ListOfRectanglesValues}{%   0/0/1/1/0.3,   1/1/2/2/0.6, }  \begin{document} \begin{tikzpicture}   \foreach \sXa/\sYa/\sXb/\sYb/\mycolor in \ListOfRectanglesColor {     \fill[\mycolor] (\sXa, \sYa) rectangle (\sXb, \sYb);   }   %\foreach \sXa/\sYa/\sXb/\sYb/\myvalue in \ListOfRectanglesColor {   %  what code will define \mycolor as a color based on \myvalue?   %  and a specified color map?   %  \fill[\mycolor] (\sXa, \sYa) rectangle (\sXb, \sYb);   %} \end{tikzpicture} \end{document}   Edited in response to comment  Question: How do I map values to colors? I would appreciate it if the TeX code were commented so that I could understand how the code works.  For simplicity, the mapping function will be of the form  \valuetocolor{value-min}{value-max}{color-min}{color-max}{value}   The floating point numbers value-min and value-max will be mapped to two defined colors color-min and color-max respectively. We can assume that value-min ≤ value-max. I want to map the floating point number value to the linear interpolated value between color-min and color-max. More precisely, let λ be the value such that value = λ value-min + (1 - λ) value-max. Then I want \valuetocolor{value-min}{value-max}{color-min}{color-max}{value} to return the color λ color-min + (1 - λ) color-max.    Related TeX.SX Question  I am aware that there is a related question  where there is TeX code that accomplishes a mapping from value to color for a more complicated color map. Unfortunately, with my limited TeX/PGF knowledge, I can't understand how the code works.