Category Archives: Linguaggi

Linguaggi di programmazione

SICP – cap. 2 – Dati gerarchici e closure – esercizi – 24

Continuo da qui, sono qui.

Exercise 2.20: The procedures +, *, and list take arbitrary numbers of arguments. One way to define such procedures is to use define with dotted-tail notation. In a procedure definition, a parameter list that has a dot before the last parameter name indicates that, when the procedure is called, the initial parameters (if any) will have as values the initial arguments, as usual, but the final parameter’s value will be a list of any remaining arguments. For instance, given the definition

(define (f x y . z) ⟨body⟩)

the procedure f can be called with two or more arguments. If we evaluate

(f 1 2 3 4 5 6)

then in the body of f, x will be 1, y will be 2, and z will be the list (3 4 5 6). Given the definition

(define (g . w) ⟨body⟩)

the procedure g can be called with zero or more arguments. If we evaluate

(g 1 2 3 4 5 6)

then in the body of g, w will be the list (1 2 3 4 5 6).

Note:  To define f and g using lambda we would write
(define f (lambda (x y . z) ⟨body⟩))
(define g (lambda w ⟨body⟩))

Use this notation to write a procedure same-parity that takes one or more integers and returns a list of all the arguments that have the same even-odd parity as the first argument. For example,

(same-parity 1 2 3 4 5 6 7)
(1 3 5 7)

(same-parity 2 3 4 5 6 7)
(2 4 6)

Forse SICP è troppo impegnativo per me; o forse devo sviscerare il senso del testo. Ho provato a vedere se Racket (nella REPL) ha la dot-tail notation  e pare di no  NO, c’è, vedi più avanti. Allora cosa devo fare? Chissà se Bill the Lizard

OK, devo costruire la procedeura same-parity come se la notazione ci fosse.

Ma aspetta: la cosa non mi convince, provo a indagare

o, meglio ancora

e ovviamente

L’esercizio non era comunque semplice, vedi sicp-ex e Drewiki.

OK, adesso lo pubblico? devo essere onesto e raccontare quello che faccio o riportare la ricostruzione finale? Siccome il blog è mio e lo leggo solo io (kwasy) la prima opzione mi sembra quella giusta 😜

Ovviamente devo impegnarmi di più: i post di SICP sono impegnativi. Molto 👽

:mrgreen:

NumPy – 39 – indicizzazione e selezione dei dati – 2

Continuo copiando qui.

Selezione in DataFrame
Recall that a DataFrame acts in many ways like a two-dimensional or structured array, and in other ways like a dictionary of Series structures sharing the same index. These analogies can be helpful to keep in mind as we explore data selection within this structure.

DataFrame come dictionary
The first analogy we will consider is the DataFrame as a dictionary of related Series objects. Let’s return to our example of areas and populations of states:

The individual Series that make up the columns of the DataFrame can be accessed via dictionary-style indexing of the column name:

Equivalently, we can use attribute-style access with column names that are strings:

This attribute-style column access actually accesses the exact same object as the dictionary-style access:

Though this is a useful shorthand, keep in mind that it does not work for all cases! For example, if the column names are not strings, or if the column names conflict with methods of the DataFrame, this attribute-style access is not possible. For example, the DataFrame has a pop() method, so data.pop will point to this rather than the “pop” column:

In particular, you should avoid the temptation to try column assignment via attribute (i.e., use data['pop'] = z rather than data.pop = z).

Like with the Series objects discussed earlier, this dictionary-style syntax can also be used to modify the object, in this case adding a new column:

This shows a preview of the straightforward syntax of element-by-element arithmetic between Series objects; we’ll dig into this further [prossimamente].

DataFrame come array bidimensionale
As mentioned previously, we can also view the DataFrame as an enhanced two-dimensional array. We can examine the raw underlying data array using the values attribute:

With this picture in mind, many familiar array-like observations can be done on the DataFrame itself. For example, we can transpose the full DataFrame to swap rows and columns:

When it comes to indexing of DataFrame objects, however, it is clear that the dictionary-style indexing of columns precludes our ability to simply treat it as a NumPy array. In particular, passing a single index to an array accesses a row:

and passing a single “index” to a DataFrame accesses a column:

Thus for array-style indexing, we need another convention. Here Pandas again uses the loc, iloc, and ix indexers mentioned earlier. Using the iloc indexer, we can index the underlying array as if it is a simple NumPy array (using the implicit Python-style index), but the DataFrame index and column labels are maintained in the result:

Similarly, using the loc indexer we can index the underlying data in an array-like style but using the explicit index and column names:

The ix indexer allows a hybrid of these two approaches:

Keep in mind that for integer indices, the ix indexer is subject to the same potential sources of confusion as discussed for integer-indexed Series objects.

Any of the familiar NumPy-style data access patterns can be used within these indexers. For example, in the loc indexer we can combine masking and fancy indexing as in the following:

Any of these indexing conventions may also be used to set or modify values; this is done in the standard way that you might be accustomed to from working with NumPy:

To build up your fluency in Pandas data manipulation, I suggest spending some time with a simple DataFrame and exploring the types of indexing, slicing, masking, and fancy indexing that are allowed by these various indexing approaches.

Ulteriori convenzioni di indicizzazione
There are a couple extra indexing conventions that might seem at odds with the preceding discussion, but nevertheless can be very useful in practice. First, while indexing refers to columns, slicing refers to rows:

Such slices can also refer to rows by number rather than by index:

Similarly, direct masking operations are also interpreted row-wise rather than column-wise:

These two conventions are syntactically similar to those on a NumPy array, and while these may not precisely fit the mold of the Pandas conventions, they are nevertheless quite useful in practice.

:mrgreen:

JavaScript 8 – struttura dei programmi – 6

Continuo da qui, copio qui.

Aggiornare variabili rapidamente
Especially when looping, a program often needs to “update” a variable to hold a value based on that variable’s previous value.

counter = counter + 1;

JavaScript provides a shortcut for this:

counter += 1;

Similar shortcuts work for many other operators, such as result *= 2 to double result or counter -= 1 to count downward.

This allows us to shorten our counting example a little more (file s0.js).

for (var number = 0; number <= 12; number += 2)
  console.log(number);

For counter += 1 and counter -= 1, there are even shorter equivalents: counter++ and counter--.

Uso di switch
It is common for code to look like this:

if (variable == "value1") action1();
else if (variable == "value2") action2();
else if (variable == "value3") action3();
else defaultAction();

There is a construct called switch that is intended to solve such a “dispatch” in a more direct way. Unfortunately, the syntax JavaScript uses for this (which it inherited from the C/Java line of programming languages) is somewhat awkward—a chain of if statements often looks better. Here is an example:

switch (prompt("What is the weather like?")) {
  case "rainy":
    console.log("Remember to bring an umbrella.");
    break;
  case "sunny":
    console.log("Dress lightly.");
  case "cloudy":
    console.log("Go outside.");
    break;
  default:
    console.log("Unknown weather type!");
    break;
}

Sì, nel browser; ma ovviamente switch si può usare anche normalmente.

You may put any number of case labels inside the block opened by switch. The program will jump to the label that corresponds to the value that switch was given or to default if no matching value is found. It starts executing statements there, even if they’re under another label, until it reaches a break statement. In some cases, such as the “sunny” case in the example, this can be used to share some code between cases (it recommends going outside for both sunny and cloudy weather). But beware: it is easy to forget such a break, which will cause the program to execute code you do not want executed.

Uso delle Maiuscole
Variable names may not contain spaces, yet it is often helpful to use multiple words to clearly describe what the variable represents. These are pretty much your choices for writing a variable name with several words in it:

fuzzylittleturtle
fuzzy_little_turtle
FuzzyLittleTurtle
fuzzyLittleTurtle

The first style can be hard to read. Personally, I like the look of the underscores, though that style is a little painful to type. The standard JavaScript functions, and most JavaScript programmers, follow the bottom style—they capitalize every word except the first. It is not hard to get used to little things like that, and code with mixed naming styles can be jarring to read, so we will just follow this convention.

In a few cases, such as the Number function, the first letter of a variable is also capitalized. This was done to mark this function as a constructor. What a constructor is will become clear [prossimamente]. For now, the important thing is not to be bothered by this apparent lack of consistency.

Commenti
Often, raw code does not convey all the information you want a program to convey to human readers, or it conveys it in such a cryptic way that people might not understand it. At other times, you might just feel poetic or want to include some thoughts as part of your program. This is what comments are for.

A comment is a piece of text that is part of a program but is completely ignored by the computer. JavaScript has two ways of writing comments. To write a single-line comment, you can use two slash characters (//) and then the comment text after it.

var accountBalance = calculateBalance(account);
// It's a green hollow where a river sings
accountBalance.adjust();
// Madly catching white tatters in the grass.
var report = new Report();
// Where the sun on the proud mountain rings:
addToReport(accountBalance, report);
// It's a little valley, foaming like light in a glass.

A // comment goes only to the end of the line. A section of text between /* and */ will be ignored, regardless of whether it contains line breaks. This is often useful for adding blocks of information about a file or a chunk of program.

/*
 I first found this number scrawled on the back of one of
 my notebooks a few years ago. Since then, it has often
 dropped by, showing up in phone numbers and the serial
 numbers of products that I've bought. It obviously likes
 me, so I've decided to keep it.
*/
var myNumber = 11213;

:mrgreen:

NumPy – 38 – indicizzazione e selezione dei dati – 1

Continuando da qui oggi sono qui.

In passato we looked in detail at methods and tools to access, set, and modify values in NumPy arrays. These included indexing (e.g., arr[2, 1]), slicing (e.g., arr[:, 1:5]), masking (e.g., arr[arr > 0]), fancy indexing (e.g., arr[0, [1, 5]]), and combinations thereof (e.g., arr[:, [1, 5]]). Here we’ll look at similar means of accessing and modifying values in Pandas Series and DataFrame objects. If you have used the NumPy patterns, the corresponding patterns in Pandas will feel very familiar, though there are a few quirks to be aware of.

We’ll start with the simple case of the one-dimensional Series object, and then move on to the more complicated two-dimesnional DataFrame object.

Selezione in Series
As we saw in the previous section, a Series object acts in many ways like a one-dimensional NumPy array, and in many ways like a standard Python dictionary. If we keep these two overlapping analogies in mind, it will help us to understand the patterns of data indexing and selection in these arrays.

Series come dictionary
Like a dictionary, the Series object provides a mapping from a collection of keys to a collection of values:

We can also use dictionary-like Python expressions and methods to examine the keys/indices and values:

Series objects can even be modified with a dictionary-like syntax. Just as you can extend a dictionary by assigning to a new key, you can extend a Series by assigning to a new index value:

This easy mutability of the objects is a convenient feature: under the hood, Pandas is making decisions about memory layout and data copying that might need to take place; the user generally does not need to worry about these issues.

Series come array a una dimensione
A Series builds on this dictionary-like interface and provides array-style item selection via the same basic mechanisms as NumPy arrays – that is, slices, masking, and fancy indexing.

Among these, slicing may be the source of the most confusion. Notice that when slicing with an explicit index (i.e., data['a':'c']), the final index is included in the slice, while when slicing with an implicit index (i.e., data[0:2]), the final index is excluded from the slice.

Indicizzatori: loc, iloc e ix
These slicing and indexing conventions can be a source of confusion. For example, if your Series has an explicit integer index, an indexing operation such as data[1] will use the explicit indices, while a slicing operation like data[1:3] will use the implicit Python-style index.

Because of this potential confusion in the case of integer indexes, Pandas provides some special indexer attributes that explicitly expose certain indexing schemes. These are not functional methods, but attributes that expose a particular slicing interface to the data in the Series.

First, the loc attribute allows indexing and slicing that always references the explicit index:

The iloc attribute allows indexing and slicing that always references the implicit Python-style index:

A third indexing attribute, ix, is a hybrid of the two, and for Series objects is equivalent to standard []-based indexing. The purpose of the ix indexer will become more apparent in the context of DataFrame objects, which we will discuss [nel prossimo post].

One guiding principle of Python code is that “explicit is better than implicit.” The explicit nature of loc and iloc make them very useful in maintaining clean and readable code; especially in the case of integer indexes, I recommend using these both to make code easier to read and understand, and to prevent subtle bugs due to the mixed indexing/slicing convention.

:mrgreen:

SICP – cap. 2 – Dati gerarchici e closure – esercizi – 23

Continuando da qui ecco un altro esercizio, qui.

Exercise 2.19: Consider the change-counting program of 1.2.2. It would be nice to be able to easily change the currency used by the program, so that we could compute the number of ways to change a British pound, for example. As the program is written, the knowledge of the currency is distributed partly into the procedure first-denomination and partly into the procedure count-change (which knows that there are five kinds of U.S. coins). It would be nicer to be able to supply a list of coins to be used for making change.

We want to rewrite the procedure cc so that its second argument is a list of the values of the coins to use rather than an integer specifying which coins to use. We could then have lists that defined each kind of currency:

(define us-coins 
  (list 50 25 10 5 1))

(define uk-coins 
  (list 100 50 20 10 5 2 1 0.5))

We could then call cc as follows:

(cc 100 us-coins)
292

To do this will require changing the program cc somewhat. It will still have the same form, but it will access its second argument differently, as follows:

(define (cc amount coin-values)
  (cond ((= amount 0) 
         1)
        ((or (< amount 0) 
             (no-more? coin-values)) 
         0)
        (else
         (+ (cc 
             amount
             (except-first-denomination 
              coin-values))
            (cc 
             (- amount
                (first-denomination 
                 coin-values))
             coin-values)))))

Define the procedures first-denomination, except-first-denomination and no-more? in terms of primitive operations on list structures. Does the order of the list coin-values affect the answer produced by cc? Why or why not?

Uh! la prima parte è davvero immediata:

(define (no-more? coin-values)
  (if (null? coin-values) true false))

(define (except-first-denomination coin-values)
  (cdr coin-values))

(define (first-denomination coin-values)
  (car coin-values))

Metto tutto nel file coins.rkt per comodità:

Poi la seconda parte 👿 non ci provo perché poi mi deprimo 👿 passo subito a Bill the Lizard 🚀 , il mio nerd di riferimento 😉

OOPS! 😳 dubbio atroce, forse ho frainteso –niente dimostrazione matematica– devo stare più attento; vista fatta sembra banale: Finally, we’re asked if the order of the list coin-values affects the answer produced by cc. We can find out quickly enough by experiment.

We can see that the order doesn’t matter. This is because the procedure recursively evaluates every sub-list after subtracting the value of the first coin from the target amount. It doesn’t matter if that value is the smallest, largest, or even if the values are shuffled.

Interessanti le osservazioni di sicp-ex 🚀

Devo affrontare in modo diverso questi esercizi; questo è alla terza modifica con riscrittura parziale 😯

:mrgreen:

NumPy – 37 – introduzione agli oggetti Pandas – 3

Continuo da qui copiando qui.

L’oggetto Index di Pandas
We have seen here that both the Series and DataFrame objects contain an explicit index that lets you reference and modify data. This Index object is an interesting structure in itself, and it can be thought of either as an immutable array or as an ordered set (technically a multi-set, as Index objects may contain repeated values). Those views have some interesting consequences in the operations available on Index objects. As a simple example, let’s construct an Index from a list of integers:

Index come array immutabile
The Index in many ways operates like an array. For example, we can use standard Python indexing notation to retrieve values or slices:

Index objects also have many of the attributes familiar from NumPy arrays:

One difference between Index objects and NumPy arrays is that indices are immutable–that is, they cannot be modified via the normal means:

This immutability makes it safer to share indices between multiple DataFrames and arrays, without the potential for side effects from inadvertent index modification.

Index come set ordinato
Pandas objects are designed to facilitate operations such as joins across datasets, which depend on many aspects of set arithmetic. The Index object follows many of the conventions used by Python’s built-in set data structure, so that unions, intersections, differences, and other combinations can be computed in a familiar way:

These operations may also be accessed via object methods, for example

:mrgreen:

JavaScript 7 – struttura dei programmi – 5

Continuo da qui a copiare qui.

Indentare il codice
Cioè scriverlo bene, in modo che sia leggibile, come fanno i nerds.
Non è richiesto; si può scrivere tutto il programma in una sola lunga linea ma poi è difficile leggerlo.
With proper indentation, the visual shape of a program corresponds to the shape of the blocks inside it. I like to use two spaces (io di solito 4) for every open block, but tastes differ—some people use four spaces, and some people use tab characters.

Ciclo for
Many loops follow the pattern seen in the previous while examples. First, a “counter” variable is created to track the progress of the loop. Then comes a while loop, whose test expression usually checks whether the counter has reached some boundary yet. At the end of the loop body, the counter is updated to track progress.

Because this pattern is so common, JavaScript and similar languages provide a slightly shorter and more comprehensive form, the for loop (file f0.js).

for (var number = 0; number <= 12; number = number + 2)
  console.log(number);

This program is exactly equivalent to the earlier even-number-printing example. The only change is that all the statements that are related to the “state” of the loop are now grouped together.

The parentheses after a for keyword must contain two semicolons. The part before the first semicolon initializes the loop, usually by defining a variable. The second part is the expression that checks whether the loop must continue. The final part updates the state of the loop after every iteration. In most cases, this is shorter and clearer than a while construct.

Here is the code that computes 210, using for instead of while (file f1.js):

var result = 1;
for (var counter = 0; counter < 10; counter = counter + 1)
  result = result * 2;
console.log(result);

Note that even though no block is opened with a {, the statement in the loop is still indented two spaces to make it clear that it “belongs” to the line before it.

Uscire dal ciclo
Having the loop’s condition produce false is not the only way a loop can finish. There is a special statement called break that has the effect of immediately jumping out of the enclosing loop.

This program illustrates the break statement. It finds the first number that is both greater than or equal to 20 and divisible by 7 (f2.js).

for (var current = 20; ; current++) {
  if (current % 7 == 0)
    break;
}
console.log(current);

Using the remainder (%) operator is an easy way to test whether a number is divisible by another number. If it is, the remainder of their division is zero.

The for construct in the example does not have a part that checks for the end of the loop. This means that the loop will never stop unless the break statement inside is executed.

If you were to leave out that break statement or accidentally write a condition that always produces true, your program would get stuck in an infinite loop. A program stuck in an infinite loop will never finish running, which is usually a bad thing.

If you create an infinite loop in one of the examples on these pages, you’ll usually be asked whether you want to stop the script after a few seconds. If that fails, you will have to close the tab that you’re working in, or on some browsers close your whole browser, in order to recover.

The continue keyword is similar to break, in that it influences the progress of a loop. When continue is encountered in a loop body, control jumps out of the body and continues with the loop’s next iteration.

Visto che Marijn non fa l’esempio per continue lo faccio io: scrivo solo i numeri pari da 0 a 10, file f3.js:

for (var current = 0; current < 11 ; current++) {
  if (current % 2 == 1)
    continue;
  console.log(current);
}

:mrgreen:

NumPy – 36 – introduzione agli oggetti Pandas – 2

Continuo da qui copiando qui.

L’oggetto DataFrame di Pandas
The next fundamental structure in Pandas is the DataFrame. Like the Series object discussed in the previous section, the DataFrame can be thought of either as a generalization of a NumPy array, or as a specialization of a Python dictionary. We’ll now take a look at each of these perspectives.

DataFrames come array di NumPy generalizzato
If a Series is an analog of a one-dimensional array with flexible indices, a DataFrame is an analog of a two-dimensional array with both flexible row indices and flexible column names. Just as you might think of a two-dimensional array as an ordered sequence of aligned one-dimensional columns, you can think of a DataFrame as a sequence of aligned Series objects. Here, by “aligned” we mean that they share the same index.

To demonstrate this, let’s first construct a new Series listing the area of each of the five states discussed in the previous section:

Now that we have this along with the population Series from before, we can use a dictionary to construct a single two-dimensional object containing this information:

Like the Series object, the DataFrame has an index attribute that gives access to the index labels:

Additionally, the DataFrame has a columns attribute, which is an Index object holding the column labels:

Thus the DataFrame can be thought of as a generalization of a two-dimensional NumPy array, where both the rows and columns have a generalized index for accessing the data.

DataFrame come dictionary specializzato
Similarly, we can also think of a DataFrame as a specialization of a dictionary. Where a dictionary maps a key to a value, a DataFrame maps a column name to a Series of column data. For example, asking for the ‘area’ attribute returns the Series object containing the areas we saw earlier:

Notice the potential point of confusion here: in a two-dimesnional NumPy array, data[0] will return the first row. For a DataFrame, data['col0'] will return the first column. Because of this, it is probably better to think about DataFrames as generalized dictionaries rather than generalized arrays, though both ways of looking at the situation can be useful. We’ll explore more flexible means of indexing DataFrames in Data Indexing and Selection.

Costruire oggetti DataFrame
A Pandas DataFrame can be constructed in a variety of ways. Here we’ll give several examples.

da un singolo oggetto Series
A DataFrame is a collection of Series objects, and a single-column DataFrame can be constructed from a single Series:

da una lista di dictionaries
Any list of dictionaries can be made into a DataFrame. We’ll use a simple list comprehension to create some data:

Even if some keys in the dictionary are missing, Pandas will fill them in with NaN (i.e., “not a number”) values:

da un dictionary di oggetti Series
As we saw before, a DataFrame can be constructed from a dictionary of Series objects as well:

da un array NumPy bidimensionale
Given a two-dimensional array of data, we can create a DataFrame with any specified column and index names. If omitted, an integer index will be used for each:

da un array NumPy strutturato
We covered structured arrays in Structured Data: NumPy’s Structured Arrays. A Pandas DataFrame operates much like a structured array, and can be created directly from one:

:mrgreen:

Ancora sulle conversioni di JavaScript


OK, quasi lolloso, anzi certamente ma chissà 😙

Su Twitter si divertono con i calcoli aritmetici strani di JavaScript –troppo volonteroso– per esempio qui e qui.

Io sono del parere che dovrebbe imparare a dire di no, quando necessario.
M siccome non lo fa tocca al programmatore controllarlo, non è censura ma richiamo alla deontologia –secondo me 🐙

C’è un caso che a prima vista mi lascia perpluto


Eh!? 🤖  cosa succede a complessificare l’espressione (solo la prima parte, il resto è sensato):


non ci sono; sembra venire da qui


ma attenzione:


No, non ci sono 😡

Anche con altri linguaggi posso avere risultati errati:

Perl 5


🤖 sbagliato; la versione 6 non funziona (con questo script).

Python invece


🤖 sbagliato anche questo; tutti sanno che la risposta giusta è

41 monkeys and 1 fat snake

(qui) 🐙

:mrgreen:

SICP – cap. 2 – Dati gerarchici e closure – esercizi – 22


Continuo da qui, un esercizio, qui.

Exercise 2.18: Define a procedure reverse that takes a list as argument and returns a list of the same elements in reverse order:

(reverse (list 1 4 9 16 25))
(25 16 9 4 1)

Non ci sono riuscito, provo a giustificarmi 😯

La mia idea è di usare last-pair definita nell’esercizio precedente … c’è però il problema … non ho idea come farlo … mi sa che sbircio Bill the Lizard 😊

Arghhh!!! 👿
Come ho fatto a non pensarci! Bisogna ragionare ricorsivamente e basta appendere il car della lista al reverse del cdr della lista 😊

See how easy it is to start thinking in Scheme? dice Bill, rockz! 🚀
La mia stessa difficoltà la trovo in sicp-ex, non sono solo io 😙

OK 😡 sono troppo condizionato all’abitudine di ragionare à la Algol 🐙

Ma forse il problema (mio) è un altro: l’esercizio è semplicissimo, basta applicare quello detto “a lezione”; il guaio (mio) è che sono solo, non sono a lezione, non ho qualcuno cui confrontarmi.
E così ci ho ripensato parecchio, troppo, anche non volendo 😯

:mrgreen: