compteur.py

Created by pascal-chauvin

Created on July 15, 2021

1.53 KB

Ce programme permet de représenter sous d’ascii-art (dans la console) un nombre entier naturel, en base n, sur m chiffres.


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# fichier : compteur.py
#  auteur : Pascal Chauvin
#    date : 2021-07-14

#
# Représenter sur m chiffres un nombre entier naturel en base n.
#


def nombre_en_matrice(num, base, chiffres):
  """
  Le nombre entier naturel num est exprimé (par une liste) en base "base" 
  sur "chiffres" chiffres.
  """ 
  pixels = [[0 for i in range(chiffres)] for j in range(base - 0)]

  while len(num) > 1 and num[0] == 0:
    del num[0]
  
  while len(num) < chiffres:
    num = [0] + num
    
  for x in range(chiffres):
    for y in range(base):
      if y < num[x]:
        pixels[base - 1 - y][x] = 1
      else:
        pixels[base - 1 - y][x] = 0

  return pixels
  
  
def afficher(num, base, chiffres):
  """
  Affichage matriciel (du type diodes "micro:bit").
  """
  pixels = nombre_en_matrice(num, base, chiffres)
  for y in range(base):
    ligne = ""
    for x in range(chiffres):
      p = pixels[y][x]
      if p == 1:
        c = "x" # plot(x, y)
      else:
        c = "." # unplot(x, y)
      ligne += "{} ".format(c)
    print(ligne)


def dix_vers_n(x, n=2):
  """
  Conversion du nombre entier naturel x (système décimal) vers la base n.
  """
  if x > 0:
    return dix_vers_n(x // n, n) + [x % n]
  else:
    return []


def conversion(x, base=10, chiffres=8):
  afficher(dix_vers_n(x, base), base - 1, chiffres)


#
# afficher 202 (donné en base dix) en base 5 et sur 8 chiffres
#

conversion(202, 5, 8)

#  . . . . . . . . 
#  . . . . . x . . 
#  . . . . . x . x 
#  . . . . x x . x 

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.