≡ Menu

Calendar module in python

The calendar module in python enables us to print calendars on the terminal and other cool functions with the calendar.

Import the calendar module to access all these functions.

import calendar

The prmonth() method helps us to print a month’s calendar. It requires the year and the month in the form of integers as arguments.

import calendar
calendar.prmonth(2001,9)

Check leap years

We can check whether a given year is a leap year by using the isleap() method of the calendar. This method takes a year as an argument and returns “True” or “False”.

If you think only dividing the year by 4 gives you a leap year, then you are absolutely wrong. A year is a leap year only if it satisfies the following three conditions:

  1. Firstly, check its divisibility by 4, if it’s divisible then follow the next steps, otherwise, it is not a leap year.
  2. If the no. is divisible by 400, then definitely it’s a leap year. If not, check its divisibility by 100.
  3. If the no. is divisible by 100, then it is not a leap year.

So, instead of writing all these conditions, we can just use this method.

Get the day of a date

If we wish to know what day a particular date is we can use the weekday() method. This method takes a day, month, and a year as arguments. This will return an integer value from 0–6. 0 -Monday, 1 — Tuesday, … 6 — Sunday, and so on.

It receives arguments in the format of (year, month, day).

It returns 2 for April 4th, 2021 which is Wednesday.

Print entire year

We can print an entire year using the prcal() method. This method takes the year as an argument. We can also specify the column width and spacing in the arguments.

{ 0 comments }

Using AnimatPlot for Animating Graphs & Plots

Data Visualization helps in understanding different patterns, associations, visual insights from the data, etc. It is important because it uncovers the mystery behind the data tables in form of charts, graphs, and plots. There are tons of python libraries that help in visualizing the data like Matplotlib, Seaborn, etc.

AnimatPlot is an open-source python library that is built on top of Matplotlib and is used for creating highly interactive animated plots. Now, we will explore some of the functionalities that AnimatPlot provides.

Installing required libraries

We will start by installing AnimatPlot using pip. The command given below will do that.

pip install animatplot

Animatplot is built on the concept of blocks. We’ll start by animating a Line block.

First we need some imports.

Interactivity is not available in the static docs. Run the code locally to get interactivity.

So, we will use JupyterLab for our simulations.

We will import the required libraries for creating animated plots.

We will animate the function:

\(y=\cos (2 \pi(x+t)) \text { over the range } x=[0,1] \text {, and } t=[0,1]\)

Let’s generate the data:

In order to tell animatplot how to animate the data, we must pass it into a block. By default, the Line block will consider each of the rows in a 2D array to be a line at a different point in time.

We then pass a list of all our blocks into an Animation, and show the animation.

We’ll use the same data to make a new animation with interactive controls.

block = amp.blocks.Line(X, Y)
anim = amp.Animation([block])

anim.controls() # creates a timeline_slider and a play/pause toggle
anim.save_gif('images/line2') # save animation for docs
plt.show()

Displaying the Time

The above animation didn’t display the time properly because we didn’t tell animatplot what the values of time are. Instead it displayed the frame number. We can simply pass our values of time into our call to Animation.

block = amp.blocks.Line(X, Y)
anim = amp.Animation([block], t) # pass in the time values

anim.controls()
anim.save_gif('line3') # save animation for docs
plt.show()

Similarly, now we will add more data and create multiple plots in a single chart.

and once again:

{ 0 comments }

Insieme di Mandelbrot…

L’insieme di Mandelbrot o frattale di Mandelbrot è l’insieme dei numeri complessi \(c \in \displaystyle{C}\) per i quali la successione definita da:

{\displaystyle {\begin{cases}z_{0}=0\\z_{n+1}=z_{n}^{2}+c\end{cases}}}

è limitata.

Nonostante la semplicità della definizione, l’insieme ha una forma complessa il cui contorno è un frattale.

Qui, la funzione per la costruzione della matrice da diagrammare:

def plotter(n, vallim, itlim, xi,xs,yi,ys):
    image = np.full((n,n),0)
    Xp = np.linspace(xi,xs,n)
    Yp = np.linspace(yi,ys,n)
    for x in range(n):
        for y in range(n):
            image[y][x] = divergetest(complex(Xp[x],Yp[y]),vallim, itlim)
    return image

Di seguito, invece, la routine per verificare la convergenza della successione:

def divergetest(c, vallim, itlim):
    z = c
    i = 0
    while i < itlim and np.sqrt((z.real)**2 + (z.imag)**2)< vallim:
        z = z**2 + c
        i = i + 1
    return i

Il programma principale:

n = 5000
xi,xs,yi,ys = -3,1,-2,2
vallim = 5
itlim = 30
mandelbrot = plotter(n,vallim,itlim,xi,xs,yi,ys)

plt.figure(1,figsize=[8,8])
plt.title('Mandelbrot Set')
plt.imshow(mandelbrot,extent=[-3,1,-2,2])
plt.xlabel('Real')
plt.ylabel('Complex')
plt.show()

Di seguito, l’output del programma:

{ 0 comments }

Project Euler: Problem 9

That is the problem:

We can solve the problem by writing a Python code.

Let’s start with a function that checks if the three numbers \(a,b,c\), with \(a<b<c\), are a Pythagorean triplet.

def is_triplet(a,b,c):
	if (a**2 + b**2) == c**2:
		return(True)
	else:
		return(False)

Now, let’s move on to defining the main function:

def main(sum_value):
	for c in range(sum_value):
		for b in range(c):
			for a in range (b):
				if (a+b+c) == sum_value:
					if is_triplet(a,b,c):
						print(a,b,c)
						print(a*b*c)

and then, the main program:

sum_total = 1000
main(sum_total)

This is the answer:

{ 0 comments }

#spigolatricedisapri

Guardommi, e mi rispose: “O mia sorella,
Vado a morir per la mia patria bella”.
Io poi buttai i miei occhi un po’ da fora,
né potei dirgli: “Che culo, oh mia Signora!”

[*]

{ 0 comments }

Chi controlla chi

in russo la parola “spione” viene dal verbo “bussare”. E che dunque quando in russo dici spione, subito, vedi il bambino che bussa alla porta del maestro per accusare il compagno che ha copiato il compito, l’insegnante che bussa alla porta del direttore per denunciare un collega, il direttore che bussa alla porta di un ufficio anonimo per avvertire che qualcuno dietro una parete di notte scrive a macchina per ore e ore qualcosa che è certamente letteratura antisovietica.

Chiara Valerio da La Repubblica in edicola

{ 0 comments }