print

Pretty printing 2D python/numpy array

Below I show you quick and dirty way to print 2D array Column and Row labels/indexes. It is often more convenient to have those available so you can easily track visually the results of operations.

First lets try with numpy array :

import numpy as np
import pandas as pd

a = np.random.randint(0,100,(5,5))

print(a)

print()
print(pd.DataFrame(a))


print()
print(pd.DataFrame(a,columns=['A','B','C','D','E']))
[[70 40 64 22 91]
 [82 41 35 42 19]
 [21  7 42 63 85]
 [26 43 23  1 34]
 [44 79 88 46 62]]

    0   1   2   3   4
0  70  40  64  22  91
1  82  41  35  42  19
2  21   7  42  63  85
3  26  43  23   1  34
4  44  79  88  46  62

    A   B   C   D   E
0  70  40  64  22  91
1  82  41  35  42  19
2  21   7  42  63  85
3  26  43  23   1  34
4  44  79  88  46  62

Of course it is similar for normal Python arrays :

import numpy as np
import pandas as pd

b = [[1,2],[3,4]]

print()
print(pd.DataFrame(b,columns=['A','B']))
   A  B
0  1  2
1  3  4

here if you are too lazy to type : https://onecompiler.com/python/3xm3ms6fb

Java: pretty print data structures

Java lacks functionality to pretty print data structures. Let’s remedy that situation.

To make that work we will use code from some other posts : [Is scalar], [join], [List to Map].

It is simple recursive function : dump()

Below you can see an example usage.

You can also experiment with the code here.

import java.util.*;
import java.util.Map.Entry;

class Dump {
  
  	//the biggest invention in Java-world since sliced-bread ;)
	public static <ARG> void say(ARG arg) { System.out.println(arg); }

        //joins Iterable or Collection into a String
	public static <T> String join(String delimiter, Iterable<T> lst) {
		StringBuilder str = new StringBuilder();
		Iterator<T> it = lst.iterator();
		while ( it.hasNext() ) {
			str.append(it.next().toString());
			if (it.hasNext()) str.append(delimiter);
		}
		return str.toString();
	}

  	//for Classes check if the value is SCALAR
	public static boolean is_scalar(Object var) {
	    if( (var instanceof Number) || (var instanceof String) || (var instanceof Boolean)) return true;
	    return false;
	}


	public static HashMap<Integer, ?> list2map(List lst) {
		HashMap map = new HashMap();
		for (int i=0; i < lst.size(); i++) {
			map.put(i, lst.get(i));
		}
		return map;
	}	
	
	public static String dump(List lst, String... offset) {
		return dump(list2map(lst), offset);
	}
	
	// Pretty print a LoL structure, for debugging purposes
	public static String dump(Map m, String... offset) {
		if (m == null) return "";
	    StringBuilder rv = new StringBuilder();
	    String delta = offset.length == 0 ? "" : offset[0];
	    for( Entry e : (Set<Map.Entry>) m.entrySet() ) {
	        rv.append( delta + e.getKey() + " : " );
	        Object value = e.getValue();
	        if( value instanceof Map ) rv.append( ">\n" + dump((Map) value, delta + "  ") ); 
	        if( value instanceof Collection ) rv.append( "[" + join(",", (Collection) value) + "]\n" );
	        if( is_scalar(value) ) rv.append( value +"\n" );
	    } 
	    return rv.toString();
	}
	
	public static void main(String[] args) {
		  
      List lst = Arrays.asList(1,2,3,4);
      HashMap lvl2 = new HashMap() {{
       put("key2-1", "value2-1");
       put("key2-2", "value2-2");
      }};
      
      
      HashMap map = new HashMap() {{
       put("key", "value");
       put("lvl2", lvl2);
       put("lst",lst);
      }};
      
      
      say(dump(map));
	}
	
}	

here is the output :

lvl2 : >
  key2-2 : value2-2
  key2-1 : value2-1
lst : [1,2,3,4]
key : value

print() all over yourself …

There are fancy progress bars for Python, but what if you are in a hurry or don’t want to install additional modules or libraries. if that is the case then you can use a little known option of print(), namely end=”\r”.

Here goes :

import time

for i in range(100): 
  time.sleep(0.01)
  print(f'counting : {i}   ', end="\r")                                                                                         

you would use the carriage return symbol to return the cursor to the beginning of the line after every print. Then the print will overwrite the previous string.

You may also put some spaces after the number because the number is left aligned.

Easier print in Prolog

say(Lst) :- is_list(Lst), writeln(Lst).
say(S)   :- say(S,[]).
say(S,P) :- string_concat(S, '~n', S1), format(S1,P).

?- say('hello').
hello
true.

?- say('hello ~w',[world]).
hello world
true.

?- say('hello ~w ~w',[new,world]).
hello new world
true.

Java invention of the decade

Ladies and gentleman,
I present to you the biggest invention in Java since sliced bread :

public static <ARG> void say(ARG arg) { System.out.println(arg); }

Now you can do :

say("This is less annoying than System.out.whatever"; }

… where is my award :”)