Libertà vo cercando, ch'è sì cara, come sa chi per lei vita rifiuta

Categoria: programmazione Page 1 of 2

Connect to an external service on a different AKS cluster through private network

My goal is to call a service on an AKS cluster (aks1/US) from a pod on a second AKS cluster (aks2/EU).
These clusters will be on different regions and should communicate over a private network.

For the cluster networking I’m using the Azure CNI plugin.

Above you can see a schema of the two possible ending architectures. ExternalName  or ExternalIP  service on the US AKS pointing to a private EU ingress controller IP.

So, after some reading and some video listening, it seemed for me that the best option was to use an externalName service on AKS2 calling a service defined in a custom private DNS zone (ecommerce.private.eu.dev), being these two VNets peered before.

Address space for aks services:
dev-vnet  10.0.0.0/14
=======================================
dev-test1-aks   v1.22.4 - 1 node
dev-test1-vnet  11.0.0.0/16
=======================================
dev-test2-aks   v1.22.4 - 1 node
dev-test2-vnet  11.1.0.0/16 

After some trials I can get connectivity between pods networks but I was never able to reach the service network from the other cluster.

  • I don’t have any active firewall
  • I’ve peered all three networks: dev-test1-vnet, dev-test2-vnet, dev-vnet (services CIDR)
  • I’ve create a Private DNS zones private.eu.dev where I’ve put the “ecommerce” A record (10.0.129.155) that should be resolved by the externalName service

dev-test1-aks (EU cluster):

kubectl create deployment eu-ecommerce --image=k8s.gcr.io/echoserver:1.4 --port=8080 --replicas=1

kubectl expose deployment eu-ecommerce --type=ClusterIP --port=8080 --name=eu-ecommerce

kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.1.1/deploy/static/provider/cloud/deploy.yaml

kubectl create ingress eu-ecommerce --class=nginx --rule=eu.ecommerce/*=eu-ecommerce:8080

This is the ingress rule:

❯ kubectl --context=dev-test1-aks get ingress eu-ecommerce-2 -o yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: eu-ecommerce-2
  namespace: default
spec:
  ingressClassName: nginx
  rules:
  - host: lb.private.eu.dev
    http:
      paths:
      - backend:
          service:
            name: eu-ecommerce
            port:
              number: 8080
        path: /ecommerce
        pathType: Prefix
status:
  loadBalancer:
    ingress:
    - ip: 20.xxxxx

This is one of the externalName I’ve tried on dev-test2-aks:

apiVersion: v1
kind: Service
metadata:
  name: eu-services
  namespace: default
spec:
  type: ExternalName
  externalName: ecommerce.private.eu.dev
  ports:
    - port: 8080
      protocol: TCP

These are some of my tests:

# --- Test externalName 
kubectl --context=dev-test2-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget -qO- http://eu-services:8080
: '
    wget: cant connect to remote host (10.0.129.155): Connection timed out
'

# --- Test connectivity AKS1 -> eu-ecommerce service
kubectl --context=dev-test1-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget -qO- http://eu-ecommerce:8080
kubectl --context=dev-test1-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget -qO- http://10.0.129.155:8080
kubectl --context=dev-test1-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget -qO- http://eu-ecommerce.default.svc.cluster.local:8080
kubectl --context=dev-test1-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget -qO- http://ecommerce.private.eu.dev:8080
# OK client_address=11.0.0.11

# --- Test connectivity AKS2 -> eu-ecommerce POD
kubectl --context=dev-test2-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget -qO- http://11.0.0.103:8080
#> OK


# --- Test connectivity - LB private IP
kubectl --context=dev-test1-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget --no-cache -qO- http://lb.private.eu.dev/ecommerce
#> OK
kubectl --context=dev-test2-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- wget --no-cache -qO- http://lb.private.eu.dev/ecommerce
#> KO  wget: can't connect to remote host (10.0.11.164): Connection timed out
#>> This is the ClusterIP! -> Think twice!


# --- Traceroute gives no informations
kubectl --context=dev-test2-aks  run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- traceroute -n -m4 ecommerce.private.eu.dev
: '
    *  *  *
    3  *  *  *
    4  *  *  *
'

# --- test2-aks can see the private dns zone and resolve the hostname
kubectl --context=dev-test2-aks run -it --rm --restart=Never busybox --image=gcr.io/google-containers/busybox -- nslookup ecommerce.private.eu.dev
: ' Server:    10.0.0.10
    Address 1: 10.0.0.10 kube-dns.kube-system.svc.cluster.local
    Name:      ecommerce.private.eu.dev
    Address 1: 10.0.129.155
'

I’ve also created inbound and outbound network policies for the AKS networks:

  • on dev-aks (10.0/16) allow all incoming from 11.1/16 and 11.0/16
  • on dev-test2-aks allow any outbound

SOLUTION: Set the LB as an internal LB exposing the external IP to the private subnet

kubectl --context=dev-test1-aks patch service -n ingress-nginx ingress-nginx-controller --patch '{"metadata": {"annotations": {"service.beta.kubernetes.io/azure-load-balancer-internal": "tr
ue"}}}'

This article is also in Medium 🙂


Seen docs:

Supervised learning regression analysis on Google stocks

Supervised learning on Google stock analysis and predictions

Abstract

We study some tech stock price through data visualization and some financial technique, focusing on those which are intended to give a sort of reliable prevision to permit brokers have a basis on which they could decide when it is the best moment to sell or buy stocks. We first analyze a year of data about the biggest companies as Amazon, Google, Apple and Microsoft but right after that we focus on Google stocks.

Next we leave the financial tools for supervised learning analysis. These machine learning processes learn a function from an input type to an output type using data comprising examples. Furthermore we’ll talk specifically of regression supervised learning, meaning that we’re interested in inferring a real valued function whose values corresponds to the mean of a dependant variable (stock prices).

We first applied linear regression on the last 6 years of Google Trends about the word ‘google’ specifically searched in the financial news domain, versus the last 6 years Google stock prices. From now on we change our feature domain with a multivariate input, i.e. we use other stock prices (AAPL, MSFT, TWTR, AMZN) to study the accuracy of others algorithms such as a multivariate linear regression, a SVR and a Random Forest.

keywords : Finance, Stock Price Analysis, MACD, Machine Learning, Linear Regression, SVR, Random Forest, Data Visualization, Python, R

What to do next ?

  • Do you see any error? Please tell me what to correct and why;
  • Implement these algorithms on other stocks and compare results
  • Add the r sqared to the RMSE comparison
  • Try to predict future stocks prices instead of contemporary ones

Amazon, Apple, Microsoft and Google pairplot

Amazon, Apple, Microsoft and Google pairplot

Controllo automatico della connessione rimanente, per rete 3 (tre.it)

Script per il controllo automatico (dalle 8:00 alle 23:00 ogni 30 min) della connessione  rimanente con l’abbonamento 3. In caso il valore sia inferiore ad uno preimpostato (500MB) invia un email d’allerta. E’ necessario essere connessi con la 3.

L’unica versione funzionante è la selenium, che necessita Firefox.

Ma con qualche piccola modifica sono sicuro che riusciate ad utilizzare Chrome se preferite, o a reindirizzarlo sul sito del vostro provider.

Se è effettivamente utile fatemelo sapere che si può migliorare facilmente. 🙂

Data mining – 2014 homeworks solutions

Homeworks solutions (pdf + code).

  1. Homework 1 – Sol
  2. Homework 2 – Sol
  3. Homework 3 – Sol
  4. Homework 4 – Sol
  5. Homework 5 – Sol
  6. Homework 6 – Sol

Algorithm Design / Theoretical Computer Science – 2015 – Homeworks solutions

Hi

Since often in the homeworks the questions are similar to those of the previous years, here there are my solutions.
It costed us weeks of work, too much for dying forgotten in my hard disk.

Site course

  • Homework 2 :  Solution
    Themes : Set Cover, partial set cover, max cover, linear programmming (LP), integer linear programming (ILP), maximum weight matching, game theory, approximation, steiner tree, minimum spanning tree.

For the Latex version of the solutions please donate and I will send it to you with joy. 🙂


[RDF/OWL] semantic analysis with Jena

Hi, this is a little Eclipse project I did for a course on Semantic Web.

It works with Jena API and uses some dataset for querying through SPARQL. You’ll see how to deal with the various functionalities such as loading a RDF into a model, querying it through runtime code or the Fuseki interface, how to store the model through TDB and some OWL reasoning

Download :   

Download of tweets with Python

Our goal is to download a stream of tweets in Rome as they are created and create a web page that displays their location on Google maps.
We will need the help pf two modules : twython and pygmaps. The first to connect to the Twitter servers and to read the tweets, the second one to represent these tweets on the Google map.

So you will need to

  1. Install twython
  2. download the edited pygmaps module (or you can do it by yourself adding the Title functionality to the addpoint() function)
  3. download and test my script
  4. tweetMap

Swi-Prolog : ricorsione

Learn Prolog now : Recursion
Lista dei predicati in Prolog

% -- hungry bear
isDigering(X,Y):- justAte(X,Y).
isDigering(X,Y):- justAte(X,Z),
		  isDigering(Z,Y).
					
justAte(bear, john).
justAte(bear, honey).
justAte(john, chicken).
justAte(john, potatoes).
justAte(chicken, worm).

/*
	?- isDigering(bear, Gnam).
		Gnam = john ;
		Gnam = honey ;
		Gnam = chicken ;
		Gnam = potatoes ;
		Gnam = worm ;
*/

% -- The history of music 

descend(X,Y):- child(X,Y).
descend(X,Y):- child(X,Z),
	       descend(Z,Y).
				
child(worksong,blues).
child(blues,jazz).
child(jazz, prog).
child(blues,rockabilly).
child(rockabilly, hardRock).
child(hardRock, metal).

% -- Counting one by one

numeral(0).
numeral( succ(X) ):- numeral(X).

% -----------------------

% -- King Fibonacci 

fib(1, 1).
fib(X, Y):- X>0, Z is X-1 ,
	    fib(Z, Y2),
	    Y is X*Y2 .

% somma da una lista			
sumList([], 0).
sumList(List, Sum):- [Head| Tail] = List,
		     sumList( Tail, TempSum),
		     Sum is  TempSum + Head.


% riconosce liste con lo stesso numero di caratteri
a2b([],[]).
a2b([_|A], [_|B]) :- a2b(A, B).


% calcolo lunghezza delle stringhe 
len([],0).
len([_|T], N):- len(T,X), 
		N is X+1.

% mischia due stringhe un carattere alla volta 
combine([],[],[]).
combine(L1, L2, Result):- 	L1 = [A|T1], L2 = [B|T2],
				combine(T1, T2, R),
				append([A,B],R,Result).
				%Result = [A,B,R]. crea una lista di liste	
	/* 
		 combine([c,n],[a,e],X).
		 X = [c, a, n, e] ;
	*/

[2] SWI-Prolog + Eclipse : Parole crociate

Prima di svolgere il prossimo esercizio consiglio di installare il plugin PDT su Eclipse per avere una postazione di lavoro più comoda e potente :

Eclipse : versione successiva alla 4
SWI-Prolog : versione successiva alla 6
PDT

Attenzione a non installare la versione nel repository di ubuntu che è più vecchia

$ apt-cache showpkg swi-prolog
Package: swi-prolog
Versions:
6.4.1-1-g09194b7-raringppa2 ... <- da installare
5.10.4-5ubuntu1 (/var/lib/apt/lists/i

$ sudo apt-get install swi-prolog=6.4.1-1-g09194b7-raringppa2

Exercise 2.4 Here are six Italian words:
astante , astoria , baratto , cobalto , pistola , statale .
They are to be arranged, crossword puzzle fashion, in the following grid:
The following knowledge base represents a lexicon containing these words:

word(astante, a,s,t,a,n,t,e).
word(astoria, a,s,t,o,r,i,a).
word(baratto, b,a,r,a,t,t,o).
word(cobalto, c,o,b,a,l,t,o).
word(pistola, p,i,s,t,o,l,a).
word(statale, s,t,a,t,a,l,e).
Write a predicate crossword/6 that tells us how to fill in the grid. The first three arguments should be the vertical words from left to right, and the last three arguments the horizontal words from top to bottom.

% 3 verticali V1,V2,V3 e 3 orizzonatali H1,H2,H3
word(astante, a,s,t,a,n,t,e).
word(astoria, a,s,t,o,r,i,a).
word(baratto, b,a,r,a,t,t,o).
word(cobalto, c,o,b,a,l,t,o).
word(pistola, p,i,s,t,o,l,a).
word(statale, s,t,a,t,a,l,e).

crossword(V1,V2,V3, H1,H2,H3) :- 
		word(V1, _,V1H1,_,V1H2,_,V1H3,_),
		word(V2, _,V2H1,_,V2H2,_,V2H3,_),
		word(V3, _,V3H1,_,V3H2,_,V3H3,_),
		word(H1, _,V1H1,_,V2H1,_,V3H1,_),
		word(H2, _,V1H2,_,V2H2,_,V3H2,_),
		word(H3, _,V1H3,_,V2H3,_,V3H3,_),
             % non incrociare le parole con sé stesse
		H1\=V1, H2\=V2, H3\=V3.	

% chi più ne ha più ne metta :)
/*
word(scatole, s,c,a,t,o,l,e).
word(estonia, e,s,t,o,n,i,a).
word(baretto, b,a,r,e,t,t,o).
word(cavallo, c,a,v,a,l,l,o).
word(ceretta, c,e,r,e,t,t,a).
word(cintola, c,i,n,t,o,l,a).
word(pittalo, p,i,t,t,a,l,o).
word(lisbona, l,i,s,b,o,n,a).
word(funesto, f,u,n,e,s,t,o).
word(colante, c,o,l,a,n,t,e).
*/

/*
one solution :
     a   c   p
   a s t o r i a  
     t   b   s 
   b a r a t t o  
     n   l   o   
   s t a t a l e  	
     e   o   a
*/

Primo script in Prolog

SWI-Prolog è la versione qui utilizzata.
Sistema: Ubuntu 13.04.
Strumenti: Gedit, Terminale.
Per installarlo : sudo apt-get install swi-prolog

Prolog is a declarative programming language. This means that in prolog, you do not write out what the computer should do line by line, as in procedural languages such as C and Java . The general idea behind declarative languages is that you describe a situation. Based on this code, the interpreter or compiler will tell you a solution. In the case of prolog, it will tell you whether a prolog sentence is true or not and, if it contains variables, what the values of the variables need to be.

Piccolo script per iniziare a conoscere il Prolog

largeFamily.pl

% database familiare
% iniziamo da lontano definendo un insieme di esseri umani..

human(john).
human(david).
human(gino).
human(bobbysolo).
human(karen).
human(gloria).
% ora separiamoli in base al sesso :
sex(john, man). % maschietti
sex(david, man).
sex(gino, man).
sex(bobbysolo, man).
sex(karen, woman). % femminucce
sex(sasha, woman).
sex(gloria, woman).
% iniziamo a definire le coppie
partner(john, gloria).
partner(david, britney).
partner(gino, topino).
partner(john, karen).
haveChild(john, sasha). % genitori
%haveChild(john, david).
% john,karen -> sasha,bobbysolo -> rocco,brigitte -> moana
haveChild(karen, sasha).
haveChild(gloria, david).
haveChild(sasha, rocco).
haveChild(bobbysolo, rocco).
haveChild(rocco, moana).
haveChild(brigitte, moana).
% definiamo ora delle funzioni che controllino se
% - A sia il padre di B
isFather(A, B) :- sex( A, man), haveChild(A,B).
% - A sia la madre di B
isMother(A, B) :- sex( A, woman), haveChild(A,B).
% - F e M siano padre a madre di A
parents(A, F, M) :- isFather(F, A), isMother(M,A).
% - A sia un avo di B
ancestor(A,B) :- haveChild(A,B).
ancestor(A,B) :- haveChild(A,X), ancestor(X,B). % non senti puzza di ricorsione ?
% - uno dei due è il padre/madre, il figliastro, il fratello/astro o un progenitore
areRelatives(A,B) :- isFather(A,B) | isFather(B,A) | isMother(A,B) | isMother(B,A);
partner(A,C), haveChild(C,B);
partner(C,A), haveChild(C,B);
haveChild(C,A), haveChild(D,B), ( partner(C,D); partner(D,C) );
ancestor(A,B); ancestor(B,A).

Mentre queste sono delle possibili interrogazioni da terminale

?- isFather(john,_).
true.
?- isFather(john,B).
B = david.
?- parents(david,Father,Mother).
Father = john,
Mother = gloria ;
false.

?- ancestor(john, Discendente).
Discendente = sasha ;
Discendente = rocco ;
Discendente = moana ;
false.

?- areRelatives(gloria, sasha).
true .
?- areRelatives(john,david).
true .
?- areRelatives(karen, moana).
true ;

[java] la classe Pila

Un semplice esempio sulla gestione di un oggetto di tipo Pila

  • Con controllo d’errore :

[java] Client-Server multithread, lettura file XML

Qui oltre al codice troverete anche la documentazione (javadoc e pdf), è un’applicazione Java sia lato client che server con le seguenti caratteristiche:

Scopo:
Si vuole realizzare un applicazione che permetta ad un client di consultare un database presente
su un server, per poter effettuare alcune letture, che siano dell’intero file o il risultato di una
selezione al suo interno.
Lo scambio dei messaggi tra le due parti applicative deve avvenire attraverso una connessione
affidabile.
Caso in esame:
Si è preso come esempio uno studente che voglia consultare gli stage disponibili attualmente nel
mondo del lavoro, a cui deve essere data la possibilità di avere una visione globale e di poter
effettuare una selezione dei campi attraverso il numero dei posti disponibili, la durata dello stage
o il relativo salario offerto.

Il codice è stato aggiornato rispetto alla documentazione.
Ricordatevi di mettere il file xml nella stessa cartella degli eseguibili.

[java] Client-Server Echo su UDP

1/04/2012 – Aggiornato

Classi Java che impostano una connessione UDP tra loro, il server rimane in attesa di connessione sulla porta che gli viene passata come parametro, così come il client invece si connette alla porta e all’indirizzo indicato nei parametri.

Il server restituisce al client lo stesso messaggio inviato, ma con una percentuale d’errore e un ritardo minimo modificabile.

Server
Client

[java] Primi passi con le Stringhe

Un semplice esercizio per iniziare a capire come si comporta il Java con le stringhe.

Consegna :

  1. Realizzate una classe java che vi permetta di implementare le seguenti operazioni:
  2. acquisizione di una stringa da tastiera e stampa della stringa
  3. verifica se una stringa contiene il dittongo “ae”;
  4. verifica del valore del primo carattere di una stringa inserita da tastiera; ed il quinto (se c’e’)
  5. produzione di un nuovo array di byte usando l’insieme di caratteri di default sulla piattaforma (getBytes());
  6. trovare la prima occorrenza in cui si trova un carattere in una stringa acquisita da tastiera e stamparla
  7. trovare la prima occorrenza in cui si trova una sottostringa in una stringa acquisita da tastiera e stamparla
  8. trovare la lunghezza di una stringa letta da tastiera
  9. realizzare una nuova stringa che sia la sottostringa della prima, partendo dal 5 carattere;
  10. realizzare una nuova stringa che sia la sottostringa della prima, partendo dal 5 carattere e terminando al carattere 8;
  11. realizzare una nuova stringa che porti in minuscolo TUTTI i caratteri della stringa di partenza letta da tastiera;
  12. realizzare una copia della stringa immessa da tastiera ma senza spazi iniziali e finali;
  13. realizzare una stringa che rappresenti il valore intero dell’intero letto da tastiera;
/home/alex/workspace/stringhe/src/Stringhe.java

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class Stringhe {

    /**
     @author Alessandro Affinito
     */
    public static void main(String[] argsthrows IOException {
     
        InputStreamReader reader new InputStreamReader (System.in);
        BufferedReader in new BufferedReader (reader);
     
        // acquisizione di una stringa da tastiera e stampa
        String str new String();
        System.out.println(” Iserisci uno o piu’ caratteri: “);
        try{
            str in.readLine();
        }catch (IOException e){
            System.out.println(” Si è verificato un errore : “+e);
        }
        System.out.println(” Hai inserito : “+str );
     
        // 2. verifica se una stringa contiene il dittongo “ae”;
        String trovami=“ae”;
        System.out.println(“\n La stringa di prova contiene \”ae\”? “str.containstrovami ));
     
//      3. verifica del valore del primo carattere di una stringa inserita da tastiera; ed il quinto (se c’e’)
        System.out.println(“\n il primo carattere della stringa e’ : “str.charAt(0));
        if (str.length()>4)
            System.out.println(” ed il quinto e’ : “str.charAt(4));
        else
            System.out.println(” La stringa inserita ha meno di cinque caratteri.”);
     
//      4. produzione di un nuovo array di byte usando l’insieme di caratteri di default sulla piattaforma (getBytes());
        byte []vettoreBites str.getBytes();
     
//      5. trovare la prima occorrenza in cui si trova un carattere in una stringa acquisita da tastiera e stamparla
        System.out.println(” prima occorrenza della \’a\’: “str.indexOf(‘a’) );
     
//      6. trovare la prima occorrenza in cui si trova una sottostringa in una stringa acquisita da tastiera e stamparla
        String substring “asd”;
        System.out.println(” prima occorrenza della \'”+substring+“\’: “str.indexOf(substring) );
     
     
//      7. trovare la lunghezza di una stringa letta da tastiera
        System.out.println(” Dimensione della stringa inserita = “str.length() );
     
//      8. realizzare una nuova stringa che sia la sottostringa della prima, partendo dal 5 carattere;
        String substr1 str.substring(4);
     
//      9. realizzare una nuova stringa che sia la sottostringa della prima, partendo dal 5 carattere e terminando al carattere 8;
        String substr2 str.substring(47);
     
//      10.realizzare una nuova stringa che porti in minuscolo TUTTI i caratteri della stringa di partenza letta da tastiera;
        String strLow str.toLowerCase();
     
//      11.realizzare una copia della stringa immessa da tastiera ma senza spazi iniziali e finali;
        String cleaned str.trim();
     
//      12.realizzare una stringa che rappresenti il valore intero dell’intero letto da tastiera;
        System.out.println(“Inserisci un intero : “);
        String intValue in.readLine();
        intValue intValue.valueOfintValue );
        System.out.println(“\t Rappresentazione dell’intero come stringa : “+intValue );
     
        System.out.println();
    //endMain

}//endClass

[Python3.1] Trova la pepita 2.0 !

Ed ecco la seconda versione del gioco più appasionante del momento!
Tutti lo vogliono!
Migliorato con la collaborazione di Risca.
Controlla che sia ancora l’ultima versione qui !

  • Migliorata grafica schema;
  • risolto problemi di rilevamento vicinanza alla pepita;
  • inseriti indici numerici del campo;
  • memorizzazione e visualizzazione dei tentativi falliti;
  • eliminata la possibilità di fare più volte lo stesso errore;

 

#! /usr/bin/env python3.1
# -*- coding: utf-8 -*-
"""
Gioco dimostrativo creato per l'Accademia debianizzati.

Copyright 2011 risca
Copyright 2011 TuxErrante

GPLv2 or later

"""

import sys
import random

errore = []
benvenuto = "\n \n \n \n \n \nBenvenuto nella miniera TuxErrante & Risca co.!\n\
Sarò lieto di condividere con te il nostro oro, a patto che \
tu riesca a trovarlo!\n\
Hai {0} cariche di esplosivo e {1} cave da esplorare.\n\
Sei pronto?\nEcco lo schema del cantiere\n"
#pepita = [-10, -10]
def stampaCantiere(campo,pepita=[-10,-10], errore=[]):
# se passo la pepita allora deve controllare cella per cella
# quale sia quella giusta dove metterla
print("-"*50)
print(" ", end=' ')
for i in range(campo):
if i < 9:
print("{} ".format(i+1), end=' ')
else:
print("{}".format(i+1), end=' ')
print()
for r in range(campo):
if r < 9:
print(' {}'.format(r + 1), end=' ')
else:
print(r + 1, end=' ')
for c in range(campo):
if [r , c] in errore:
print(" O ",end='')
elif r == pepita[0] and c == pepita[1]:
print(" X ",end='')
else:
print(" . ",end='')
print() # manda a capo per ogni nuova riga



def trovaPepita(tent,campo):
"""\nCrea una matrice di dimensione campo*campo dove pone una 'pepita' in modo
casuale attraverso la funzione randomint(), che bisognerà cercare di trovare
per vincere. Se la distanza tra la 'cava' inserita e quella della pepita è di
uno, ci avvertirà della vicinanza. \n
Puo' essere invocato senza argomenti, nel caso in cui i valori di default
saranno 6 tentativi e una matrice 6x6, altrimenti accetta due numeri dove
il numero dei tentativi deve essere inferiore al numero delle cave."""
if tent >= campo * campo:
exit(" Così non si puo' giocare! ")
print(benvenuto.format(tent,campo*campo))
# prendi le coordinate della pepita casualmente tra 0
# e la dimensione del campo-1
pepita = [random.randint(0,campo-1), random.randint(0,campo-1)]
stampaCantiere(campo) # stampa il campo vuoto
while tent > 0:
bangx = input("\n Inserisci le coordinate in cui vuoi piazzare la mina \
comprese tra [1 ..{}] \n x = ".format(campo))
bangy = input(" y = ")
if not bangx.isnumeric() or not bangy.isnumeric():
print(" Inserisci delle coordinate numeriche per favore! \n")
continue
else:
bangx, bangy = int(bangx), int(bangy)
bangx -= 1
bangy -= 1
if bangx < 0 or bangx >= campo or bangy < 0 or bangy >= campo:
print(" Per favore inserisci delle coordinate corrette ! \n \
Ricorda che quelli che hai in mano sono esplosivi !! \n")
continue
else: # coordinate inserite ammissibili
if (pepita[0] == bangx) and (pepita[1] == bangy):
# svela dove è la pepita !
print("coordinate segrete {},{}".format(pepita[0],pepita[1]))
stampaCantiere(campo,pepita,errore)
exit(" Complimenti!! L'hai trovata! Siamo ricchiiiii \n \
Ci devi una percentuale, ricordatelo!!")
elif ([bangx,bangy] in errore):
print(" errare è umano perseverare è diabolico!")
continue
else: # dice se si è lontani o meno dalla pepita
tent -=1
errore.append([bangx, bangy]) # inserisco nella lista errori
print("\n")
stampaCantiere(campo,[-10,-10],errore)
testX = abs(pepita[0] - bangx)
testY = abs(pepita[1] - bangy)
if (testX == 1 or testX == 0) and (testY == 1 or testY == 0):
print(" Ci sei vicino !!")
else:
print(" No, no, non ci siamo. \n")
if tent >= 1:
print(" Dai ritenta !!")
else:
print("\n Peccato che abbia finito l'esplosivo !!\n Ecco dov'era :")
stampaCantiere(campo,pepita,errore)




# chiamata della funzione principale
# se viene chiamata senza argomenti gli verranno passati di default 6 e 6
# chiamare lo script con '-h' per vedere la documentazione
if len(sys.argv) == 3:
trovaPepita(int(sys.argv[1]), int(sys.argv[2]))
elif len(sys.argv) == 2 and sys.argv[1] == '-h':
print (trovaPepita.__doc__)
else:
trovaPepita(6,6)

  • puoi trovarlo anche qui

Page 1 of 2

Powered by WordPress & Theme by Anders Norén