Initial commit

This commit is contained in:
Abreu 2022-03-15 19:34:21 -03:00
commit 9f342c47b0
No known key found for this signature in database
GPG key ID: 64835466FF55F7E1
101 changed files with 110598 additions and 0 deletions

27
05 - Funções/circle.py Normal file
View file

@ -0,0 +1,27 @@
import turtle
def drawCircle (screen, centre_x, centre_y, radius)
cursor = turtle.Turtle()
cursor.left(90)
cursor.up()
// Draw upper arch
cursor.goto(centre_x - radius, centre_y)
cursor.down()
for x in range(-radius, radius + 1):
cursor.goto(centre_x + x, )
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
sides = int(input("Digite o número de lados do polígono regular: "))
for i in range(sides):
tess.forward(100)
tess.left(360 / sides)
wn.exitonclick()

View file

@ -0,0 +1,14 @@
import turtle
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
tess.right(90)
for i in range(121):
tess.forward(i * 6)
tess.right(108)
wn.exitonclick()

View file

@ -0,0 +1,18 @@
import turtle
def drawPoly(turtle, sides, lenght):
for i in range(sides):
turtle.forward(lenght)
turtle.left(360 / sides)
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
drawPoly(tess,
int(input("Dê o número de lados do polígono a ser desenhado: ")),
int(input("De o comprimento dos lados: ")))
wn.exitonclick()

View file

@ -0,0 +1,14 @@
import turtle
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
tess.right(90)
for i in range(121):
tess.forward(i * 6)
tess.right(92)
wn.exitonclick()

View file

@ -0,0 +1,18 @@
import turtle
def drawSquare(turtle, side):
for i in range(4):
turtle.left(90)
turtle.forward(side)
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
for i in range(19):
drawSquare(tess, 50)
tess.left(18)
wn.exitonclick()

View file

@ -0,0 +1,24 @@
import turtle
import random
wn = turtle.Screen()
wn.setworldcoordinates(-1, -1, 1, 1)
fred = turtle.Turtle()
fred.speed(0)
fred.left(90)
fred.up()
numdarts = 1000
q = 0
d = 0
for i in range(numdarts):
x = random.random() if random.randrange(2) == 0 else -random.random()
y = random.random() if random.randrange(2) == 0 else -random.random()
fred.goto(x, y)
fred.stamp()
if fred.distance(0, 0) <= 1:
q += 1
d += 1
print("Valor aproximado de π para", numdarts, "dardos: ", 4 * q/d)
wn.exitonclick()

View file

@ -0,0 +1,21 @@
import turtle
def drawStar(turtle, points, size):
angle = 360 / (points * 2)
turtle.right(angle / 2)
for i in range(1, points + 1):
turtle.forward((-1) ** i * size)
turtle.right(angle)
turtle.left(angle/2)
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
drawStar(tess, int(input("Quantas pontas? ")), 100)
wn.exitonclick()

View file

@ -0,0 +1,29 @@
#include <stdio.h>
double pi (int n) {
int i;
double pi = 0, step;
for (i = 0; i < n; i++) {
step = 4.0 / (2 * i + 1);
pi += (i % 2 == 0) ? step : -step;
}
return pi;
}
int main() {
int epsilon;
printf("Este programa calcula o valor aproximado de π fazendo uso da fórmula de Leibniz. O grau de precisão do resultado é dado pelo valor de epsilon, um número inteiro e não negativo.\nDigite um valor para epsilon e pressione ENTER: ");
if (scanf(" %d", &epsilon) == EOF) {
printf("Erro: não é um valor inteiro.\n");
return 1;
}
if (epsilon < 0) {
printf("Erro: valor negativo.\n");
return 1;
}
printf("O valor aproximado de π para epsilon = %d é: %.16lf\n", epsilon, pi(epsilon));
return 0;
}

Binary file not shown.

View file

@ -0,0 +1,26 @@
import sys
def pi(n):
pi = 0
for i in range(n):
step = 4 / (2 * i + 1)
pi += step if i % 2 == 0 else -step
return pi
print("Este programa calcula o valor aproximado de π fazendo uso da fórmula de Leibniz. O grau de precisão do resultado é dado pelo valor de epsilon, um número inteiro e não negativo.")
try:
epsilon = int(input("Digite um valor para epsilon e pressione ENTER: "))
except ValueError:
print("Erro: não é um valor inteiro.")
sys.exit()
except EOFError:
print("")
sys.exit()
if epsilon < 0:
print("Erro: valor negativo.")
sys.exit()
print("O valor aproximado de π para epsilon =", epsilon, "é", pi(epsilon))

View file

@ -0,0 +1,20 @@
import turtle
def drawSquare(turtle, side):
for i in range(4):
turtle.forward(side)
turtle.left(90)
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
for i in range(5):
drawSquare(tess, 20)
tess.up()
tess.forward(40)
tess.down()
wn.exitonclick()

View file

@ -0,0 +1,23 @@
import turtle
def drawSquare(turtle, side):
for i in range(4):
turtle.forward(side)
turtle.left(90)
def drawCenteredSquare(turtle, x, y, side):
turtle.up()
turtle.goto(-side/2, -side/2)
turtle.down()
drawSquare(turtle, side)
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
for i in range(5):
drawCenteredSquare(tess, 0, 0, 20 * (i + 1))
wn.exitonclick()

28
05 - Funções/stars.py Normal file
View file

@ -0,0 +1,28 @@
import turtle
def drawStar(turtle, size):
turtle.right(18)
for i in range(1, 6):
turtle.forward((-1) ** i * size)
turtle.right(36)
turtle.left(18)
wn = turtle.Screen()
wn.bgcolor("antiquewhite")
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensize(3)
tess.speed(1)
tess.left(90)
tess.up()
for i in range(5):
tess.forward(350)
tess.down()
drawStar(tess, 100)
tess.up()
tess.forward(350)
tess.right(36)
wn.exitonclick()

4
05 - Funções/sum.py Normal file
View file

@ -0,0 +1,4 @@
def sum (a_i, a_n):
return a_n * (a_n + a_1) // 2
print("Este programa calcula a somação dde uma progressão aritmética de início em ")

View file

@ -0,0 +1,8 @@
def toSeconds (hours, minutes, seconds):
return float(hours) * 360 + float(minutes) * 60 + float(seconds)
print("Este programa converte uma quantidade de horas, minutos e segundos em um total de segundos apenas")
print("Total em segundos:", toSeconds(
input("Digite um número de horas: "),
input("Digite um número de minutos: "),
input("Digite um número de segundos: ")))

View file

@ -0,0 +1,47 @@
import turtle
def drawBar(t, height):
if height >= 200:
t.color("#ec5f67")
t.fillcolor("#ec5f67")
elif height >= 100:
t.color("#fac863")
t.fillcolor("#fac863")
elif height >= 0:
t.color("#99c794")
t.fillcolor("#99c794")
else:
t.color("#d8dee9")
t.fillcolor("#343d46")
t.begin_fill()
t.left(90)
t.forward(height)
t.write(' ' + str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill()
xs = [48, 117, -200, 240, -160, 260, 220] # aqui vão os dados
height = max(xs)
lenght = len(xs)
padding = 10
tess = turtle.Turtle()
tess.pensize(3)
wn = turtle.Screen()
wn.bgcolor("#d8dee9")
wn.setworldcoordinates(0 - padding, 0 - height, 40
* lenght + padding, height + padding)
for a in xs:
drawBar(tess, a)
wn.exitonclick()

26
06 - Seleção/grades.py Normal file
View file

@ -0,0 +1,26 @@
import sys
def grade(points):
if points >= 90:
return "A"
elif points >= 80:
return "B"
elif points >= 70:
return "C"
elif points >= 60:
return "D"
return "F"
print("Este programa dá uma nota de A a F para uma quantia de pontos 0 até 100 pontos")
try:
points = float(input("Digite um valor para epsilon: "))
except ValueError:
print("Erro: não é um número real.")
sys.exit()
except EOFError:
print("")
sys.exit()
if points < 0 or points > 100:
print("Erro: valor inválido.")
sys.exit()
print("A nota para um total de", points, "pontos é", grade(points))

View file

@ -0,0 +1,16 @@
import turtle
import random
wn = turtle.Screen()
wn.setworldcoordinates(-1, -1, 1, 1)
fred = turtle.Turtle()
fred.up()
numdarts = 10
for i in range(numdarts):
x = random.random() if random.randrange(2) == 0 else -random.random()
y = random.random() if random.randrange(2) == 0 else -random.random()
fred.goto(x, y)
fred.stamp()
wn.exitonclick()

View file

@ -0,0 +1,29 @@
#include <stdio.h>
int pow (int base, int exponent) {
int result = 1;
while (exponent-- > 0)
result *= base;
return result;
}
double pi (int n) {
int i;
double pi = 0;
for (i = 0; i < n; i++)
pi += pow(-1, i) * 4.0 / (2 * i + 1);
return pi;
}
int main() {
int epsilon;
printf("Este programa calcula o valor aproximado de π fazendo uso da fórmula de Leibniz. O grau de precisão do resultado é dado pelo valor de epsilon, um número inteiro e não negativo.\nDigite um valor para epsilon: ");
if (scanf(" %d", &epsilon) == EOF || epsilon < 0) {
printf("Valor inválido");
return 1;
}
printf("O valor aproximado de π para epsilon = %d é: %lf\n", epsilon, pi(epsilon));
return 0;
}

Binary file not shown.

View file

@ -0,0 +1,22 @@
def pi(n):
pi = 0
for i in range(n):
pi += (-1)**i * 4 / (2 * i + 1)
return pi
print("Este programa calcula o valor aproximado de π fazendo uso da fórmula de Leibniz. O grau de precisão do resultado é dado pelo valor de epsilon, um número inteiro e não negativo.")
try:
epsilon = int(input("Digite um valor para epsilon: "))
except ValueError:
print("Erro: não é um valor inteiro.")
exit()
except EOFError:
print("")
exit()
if epsilon < 0:
print("Erro: valor negativo.")
exit()
print("O valor aproximado de π para epsilon =", epsilon, "é", pi(epsilon))

View file

@ -0,0 +1,3 @@
def hypotenuse(a, b):
"""Calculates the hipotenuse of a triangles with sides a and b"""
return (a**2 + b**2)**0.5

View file

@ -0,0 +1,47 @@
import sys
def approximateSqrt(n):
suplim = n
inflim = 1
while True:
root = (suplim + inflim) / 2
square = root ** 2
if square < n - 1:
inflim = root
elif square < n + 1:
return int(root)
else:
suplim = root
def isPrime(n):
if n != 2:
if n < 2 or n % 2 == 0:
return False
limit = approximateSqrt(n) + 2
for i in range(3, limit, 2):
if (n % i == 0):
return False
return True
print("This program asserts if a given no negative integer number is prime.")
try:
n = int(input("Type a given integer value: "))
except ValueError:
print("Error: not a number.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error:", n, "is negative.")
sys.exit()
if isPrime(-n if n < 0 else n):
print(n, "is prime")
else:
print(n, "is not prime")

57
07 - Iterações/root.py Normal file
View file

@ -0,0 +1,57 @@
import sys
def average(a, b):
return (a + b) / 2
def absoluteValue(n):
return -n if n < 0 else n
def displayRoot(n, epsilon):
root = n
i = delta = 0
if n != 0 and n != 1:
if n > 1:
suplim = n
inflim = 1
else:
suplim = 1
inflim = n
while True:
i += 1
root = average(suplim, inflim)
delta = absoluteValue(root**2 - n)
if root**2 > n:
suplim = root
else:
inflim = root
if delta <= epsilon:
break
print("\nNúmero de iterações:", i)
print("Diferença absoluta:", delta)
print("Raiz quadrada:", root)
print("Este programa calcula a raiz quadrada de n com uma margem de erro menor que epsilon, sendo ambos números não negativos e o último não nulo.")
try:
n, epsilon = input(
"Digite, separados por espaço, valores para n e epsilon: ").split()
n = float(n)
epsilon = float(epsilon)
except ValueError:
print("Erro: valor inválido detectado.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 1 or epsilon < 0:
print("Erro: valor inválido detectado.")
sys.exit()
displayRoot(n, epsilon)

View file

@ -0,0 +1,25 @@
def printTriangular(n):
"""Print a list of triangular numbers and their indices"""
print("Index", '\t', "Triangular number")
print("-----", '\t', "-----------------")
for i in range(1, n + 1):
print(i, '\t', i * (i + 1) // 2)
print("This program prints the first n triangular numbers.")
try:
n = int(input("Type a value for n and press ENTER: "))
except ValueError:
print("Error: n is not an integer.")
exit()
except EOFError:
print("")
exit()
if n < 0:
print("Error: n has negative value.")
exit()
printTriangular(n)

View file

@ -0,0 +1,35 @@
import random
import turtle
def isInScreen(w, t):
leftBound = - w.window_width()/2
rightBound = w.window_width()/2
topBound = w.window_height()/2
bottomBound = -w.window_height()/2
turtleX = t.xcor()
turtleY = t.ycor()
stillIn = True
if turtleX > rightBound or turtleX < leftBound:
stillIn = False
if turtleY > topBound or turtleY < bottomBound:
stillIn = False
return stillIn
t = turtle.Turtle()
wn = turtle.Screen()
i = 0
t.shape('turtle')
while i < 4:
angle = random.randrange(361)
t.left(angle)
t.forward(50)
if not isInScreen(wn, t):
t.forward(-50)
i += 1
turtle.Terminator(wn)

View file

@ -0,0 +1,75 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * axiom () {
char *str = malloc(2 * sizeof(char));
str[0] = 'A';
str[1] = '\0';
return str;
}
char * initializeNewString (char * prevStr) {
int i, size;
char *newStr;
size = i = 0;
do {
if (prevStr[i] == 'A' || prevStr[i] == 'B')
size += 11;
else
size++;
} while (prevStr[i++] != '\0');
newStr = malloc(size * sizeof(char));
newStr[0] = '\0';
return newStr;
}
char * transformString(char *prevStr) {
int i;
char *newStr = initializeNewString(prevStr);
for (i = 0; prevStr[i] != '\0'; i++)
if (prevStr[i] == 'A')
strcat(newStr, "+BF-AFA-FB+");
else if (prevStr[i] == 'B')
strcat(newStr, "-AF+BFB+FA-");
else
strncat(newStr, prevStr + i, 1);
free(prevStr);
return newStr;
}
char * HilbertCurve (char *str, int n) {
if (n == 0)
return str;
return HilbertCurve(transformString(str), --n);
}
void printInstructions (char *str) {
if (*str == '\0')
printf("\n");
else if ((str[0] == '+' && str[1] == '-') || (str[0] == '-' && str[1] == '+'))
printInstructions(str + 2);
else {
printf("%c", *str);
printInstructions(str + 1);
}
}
int main () {
int n;
char *str;
printf("This program produces instructions for drawing a Hilbert's curve of complexity n, n ∈ .\nType in a value for n and press ENTER: ");
if (scanf(" %d", &n) == EOF || n < 0) {
printf("Error: n is not a natural number.\n");
return 1;
}
str = HilbertCurve(axiom(), n);
printf("Drawing instructions:\n");
printInstructions(str);
free(str);
return 0;
}

Binary file not shown.

View file

@ -0,0 +1,62 @@
import turtle
def drawLSystem(t, lsystem):
for command in lsystem:
if command == '+':
t.left(90)
elif command == '-':
t.right(90)
elif command == 'F':
t.forward(50)
def simplifyLSystem(lsystem):
return lsystem.replace("+-","").replace("-+","")
def HilbertCurve(t, n):
lsystem = 'A'
for i in range(n):
tmp = ""
for c in lsystem:
if c == 'A':
tmp += "+BF-AFA-FB+"
elif c == 'B':
tmp += "-AF+BFB+FA-"
else:
tmp += c
lsystem = tmp
drawLSystem(t, simplifyLSystem(lsystem))
def initializeTurtle(t, wn):
wn.setup(width = 510, height = 510)
t.shape('turtle')
t.pensize(3)
t.up()
t.goto(-250, -250)
t.down()
def main():
print("This program draws Hilbert curves.")
try:
n = int(input("Choose a level of complexity by giving a non-negative integer value: "))
except ValueError:
print("Error: n is not an integer.")
exit()
except EOFError:
print("")
exit()
if n < 0:
print("Error: n has negative value.")
exit()
wn = turtle.Screen()
t = turtle.Turtle()
initializeTurtle(t, wn)
HilbertCurve(t, n)
wn.exitonclick()
main()

View file

@ -0,0 +1,120 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct instruction{
char instruction;
struct instruction *next;
} Instruction;
Instruction * newInstruction (char instruction) {
Instruction *i = malloc(sizeof(Instruction));
i->instruction = instruction;
return i;
}
Instruction * axiom () {
Instruction *HEAD = newInstruction('\0');
HEAD->next = newInstruction('A');
HEAD->next->next = NULL;
return HEAD;
}
void freeList (Instruction *list) {
Instruction *prev;
if (!list)
return;
prev = list;
list = list->next;
free(prev);
freeList(list);
}
char * char2str (char c) {
char * str = malloc(2 * sizeof(char));
str[0] = c;
str[1] = '\0';
return str;
}
Instruction * addInstructions (Instruction *j, char *instructions) {
int i;
for (i = 0; instructions[i] != '\0'; i++) {
j->next = newInstruction(instructions[i]);
j = j->next;
}
return j;
}
Instruction * transformInstruction (Instruction *list) {
Instruction *i = list->next, *j = newInstruction('\0'), *newList = j;
char *str;
while (i) {
if (i->instruction == 'A')
j = addInstructions(j, "+BF-AFA-FB+");
else if (i->instruction == 'B')
j = addInstructions(j, "-AF+BFB+FA-");
else{
str = char2str(i->instruction);
j = addInstructions(j,str);
free(str);
}
i = i->next;
}
j->next = NULL;
freeList(list);
return newList;
}
Instruction * HilbertCurve (Instruction *list, int n) {
if (n == 0)
return list;
return HilbertCurve(transformInstruction(list), --n);
}
void simplifyInstructions (Instruction *i) {
Instruction * next;
if (!i->next || !i->next->next)
return;
if ((i->next->instruction == '+' && i->next->next->instruction == '-')
|| (i->next->instruction == '-' && i->next->next->instruction == '+')) {
next = i->next->next->next;
i->next->next = NULL;
freeList(i->next);
i->next = next;
simplifyInstructions(i);
}
else
simplifyInstructions(i->next);
}
void printInstructions(Instruction *list) {
while (list->next) {
printf("%c", list->next->instruction);
list = list->next;
}
printf("\n");
}
int main () {
int n;
Instruction *HEAD;
printf("This program produces instructions for drawing a Hilbert's curve of complexity n, n ∈ .\nType in a value for n and press ENTER: ");
if (scanf(" %d", &n) == EOF || n < 0) {
printf("Error: n is not a natural number.\n");
return 1;
}
HEAD = HilbertCurve(axiom(), n);
simplifyInstructions(HEAD);
printf("Drawing instructions:\n");
printInstructions(HEAD);
freeList(HEAD);
return 0;
}

Binary file not shown.

View file

@ -0,0 +1,68 @@
import sys
import turtle
def drawLSystem(t, lsystem):
angle = 60
for command in lsystem:
if command == '+':
t.left(angle)
elif command == '-':
t.right(angle)
elif command == 'F':
t.forward(50)
def simplifyLSystem(lsystem):
return lsystem.replace("+-", "").replace("-+", "")
def PeanoGosperCurve(t, n):
lsystem = "FA"
for i in range(n):
tmp = ''
for c in lsystem:
if c == 'A':
tmp += "A+BF++BF-FA--FAFA-BF+"
elif c == 'B':
tmp += "-FA+BFBF++BF+FA--FA-B"
else:
tmp += c
lsystem = tmp
drawLSystem(t, simplifyLSystem(lsystem))
def initializeTurtle(t, wn):
wn.setup(width=510, height=510)
t.shape('turtle')
t.pensize(3)
t.up()
t.goto(-250, -250)
t.down()
def main():
print("This program draws Peano-Gosper curves.")
try:
n = int(input("Choose a level of complexity by giving a non-negative integer value: "))
except ValueError:
print("Error: n is not an integer.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error: n has negative value.")
sys.exit()
wn = turtle.Screen()
t = turtle.Turtle()
initializeTurtle(t, wn)
PeanoGosperCurve(t, n)
wn.exitonclick()
main()

View file

@ -0,0 +1,66 @@
import turtle
def drawLSystem(t, lsystem):
angle = 60
for command in lsystem:
if command == '+':
t.left(angle)
elif command == '-':
t.right(angle)
elif command == 'F':
t.forward(10)
def simplifyLSystem(lsystem):
return lsystem.replace("+-","").replace("-+","")
def SierpinskiTriangle(t, n):
lsystem = "FAF--FF--FF"
for i in range(n):
tmp = ''
for c in lsystem:
if c == 'F':
tmp += "FF"
elif c == 'A':
tmp += "-FAF++FAF++FAF--"
else:
tmp += c
lsystem = tmp
drawLSystem(t, simplifyLSystem(lsystem))
def initializeTurtle(t, wn):
wn.setup(width = 510, height = 510)
t.shape('turtle')
t.pensize(3)
t.up()
t.goto(-250, -250)
t.down()
def main():
print("This program draws Sierpinski triangles.")
try:
n = int(input("Choose a level of complexity by giving a non-negative integer value: "))
except ValueError:
print("Error: n is not an integer.")
exit()
except EOFError:
print("")
exit()
if n < 0:
print("Error: n has negative value.")
exit()
wn = turtle.Screen()
t = turtle.Turtle()
initializeTurtle(t, wn)
SierpinskiTriangle(t, n)
wn.exitonclick()
main()

30
08 - Strings/analysis.py Normal file
View file

@ -0,0 +1,30 @@
def analysis(string):
if (string == ""):
print("Seu texto encontra-se vazio.")
return
words = 0
words_with_e = 0
previous_char = " "
found_e = False
for char in string:
if (char != " " and previous_char == " ")\
or (char == "-" and previous_char != " "):
words += 1
if found_e:
words_with_e += 1
found_e = False
if char == "e":
found_e = True
previous_char = char
if found_e:
words_with_e += 1
print("Seu texto contém", words, "palavras, das quais", words_with_e,
"(", words_with_e / words * 100, "%) contém um \'e\'.")
print("Este programa recebe uma sequência de texto e apresenta uma análise deste.")
analysis(input("Digite uma sequência de texto: "))

35
08 - Strings/cipher.py Normal file
View file

@ -0,0 +1,35 @@
def cipher(message, key):
cipher = ""
for c in message:
if c.islower():
cipher += key[ord(c) - ord('a')]
elif c.isupper():
cipher += key[ord(c) - ord('A')].upper()
else:
cipher += c
return cipher
def decipher(cipher, key):
message = ""
for c in cipher:
if c.islower():
message += chr(key.find(c) + ord('a'))
elif c.isupper():
message += chr(key.find(c.lower()) + ord('a')).upper()
else:
message += c
return message
def main ():
print("This program peforms a substitution cipher on non-accentuated letters.")
key = "zoxyjdswgerkcaupmivthlbfqn"
message = cipher(input("Input message: "), key)
print("Encrypted message:", message)
print("Decrypted message:", decipher(message, key))
main()

View file

@ -0,0 +1,22 @@
def countDigits(n):
digits = 1
if (n < 0):
n = -n
while n // 10 != 0:
digits += 1
n //= 10
return digits
print("Este programa aceita um valor inteiro n e contabiliza seu número de dígitos.")
try:
n = int(input("Digite um valor inteiro para n: "))
except ValueError:
print("Erro: não é um valor inteiro.")
exit()
except EOFError:
print("")
exit()
print("O número", n, "tem", countDigits(n), "dígitos.")

View file

@ -0,0 +1,19 @@
def countSubstring(str, substr):
length = len(substr)
count = 0
str = str.lower()
substr = substr.lower()
for i in range(len(str) - length):
if str[i:i + length] == substr:
count += 1
return count
print("This program counts the occurences of a given substring in a string, while being case insensitive.")
str = input("Type in a string and press ENTER: ")
substr = input("Type in a substring and press ENTER: ")
print("The substring \"" + substr + "\" appears",
countSubstring(str, substr), "times in the given text.")

18
08 - Strings/findChar.py Normal file
View file

@ -0,0 +1,18 @@
def findChar(string, char):
"""
Find and return the index of char in string,
otherwise return -1 if not found.
"""
index = -1
for i in range(len(string)):
if string[i] == char:
index = i
break
return index
print(findChar("Compsci", "p"))
print(findChar("Compsci", "C"))
print(findChar("Compsci", "i"))
print(findChar("Compsci", "x"))

View file

@ -0,0 +1,23 @@
def multiplicationTable(n):
columnSize = 0
biggestNumber = n * n
while biggestNumber != 0:
columnSize += 1
biggestNumber //= 10
for i in range(1, n + 1):
print(str(i).ljust(columnSize), end="\t")
print("")
for i in range(n):
print("-" * columnSize, end='\t')
print("")
for i in range(1, n + 1):
for j in range(1, n + 1):
print(i * j, end='\t')
print("")
multiplicationTable(12)

29
08 - Strings/palidrome.py Normal file
View file

@ -0,0 +1,29 @@
import unidecode
def normalizeString(str):
"""Remove from the string whitespaces, accents, punctuation, and make it lowercase only."""
normalized = ""
for c in str:
if c.isalnum():
normalized += unidecode.unidecode(c.lower())
return normalized
def isPalindrome(str):
str = normalizeString(str)
length = len(str)
for i in range(length // 2):
if str[i] != str[length - 1 - i]:
return False
return True
print("This program evaluates if a given word or sentence is a palidrome.")
if isPalindrome(input("Type in a word or sentence and press ENTER: ")):
print("That's a palidrome.")
else:
print("That's not a palindrome")

View file

@ -0,0 +1,132 @@
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
#include <stdbool.h>
wchar_t * readString(int * length) {
int i = 0, size = 1;
wchar_t c, *input = malloc(sizeof(wchar_t));
while ((c = getwchar()) != WEOF && c != '\n') {
if (i == size - 1) {
size *= 2;
input = realloc(input, size * sizeof(input));
}
input[i++] = c;
}
input[i] = '\0';
*length = i;
return input;
}
int ceil (int n, int d) {
return 1 + (n - 1) / d;
}
int cycleLength(int rail, int railIndex, int rails, int cycle) {
if (rail == 0)
return cycle = 2 * (rails - (rail + 1));
if (rail == rails - 1)
return cycle = 2 * rail;
if (rail == railIndex)
return cycle = 2 * (rails - (rail + 1));
else if (cycle == 2 * (rails - (rail + 1)))
return cycle = 2 * rail;
return cycle = 2 * (rails - (rail + 1));
}
wchar_t * railFenceCipher(wchar_t *message, int length, int rails) {
int i, j, k, cycle;
wchar_t *cipher = malloc(length * sizeof(wchar_t));
for (i = k = 0; i < rails; i++) {
j = i;
do {
cipher[k++] = message[j];
cycle = cycleLength(i, j, rails, cycle);
j += cycle;
} while (j < length);
}
cipher[k] = '\0';
return cipher;
}
wchar_t popFirst (wchar_t *str) {
int i;
wchar_t c = str[0];
for (i = 0; str[i] != '\0'; i++)
str[i] = str[i + 1];
return c;
}
void freeRails(wchar_t **rails, int n) {
int i;
for (i = 0; i < n; i++)
free(rails[i]);
free(rails);
}
wchar_t * railFenceDecipher(wchar_t *cipher, int length, int n) {
int i, j, k, counter, cycle;
wchar_t **rails = malloc(n * sizeof(wchar_t*)),
*message = malloc(length * sizeof(wchar_t));
bool forward = true;
for (i = j = 0; i < n; i++) {
k = 0;
counter = i;
rails[i] = malloc((ceil(length, n - 1) + 1) * sizeof(wchar_t));
while (counter < length) {
rails[i][k++] = cipher[j++];
cycle = cycleLength(i, k, n, cycle);
counter += cycle;
}
rails[i][k] = '\0';
}
for (i = j = 0; i < length; i++) {
message[i] = popFirst(rails[j]);
if (forward) {
j++;
if (j == n - 1)
forward = false;
}
else {
j--;
if (j == 0)
forward = true;
}
}
message[i] = '\0';
freeRails(rails, n);
return message;
}
int main () {
setlocale(LC_ALL, "pt_BR.UTF-8");
wchar_t *message, *cipher;
int length, rails;
printf("This program allows for one to encrypt a message using the Rail Fence Cipher.\nType in a message with 3 characters or more to be encrypted: ");
message = readString(&length);
if (length < 3) {
printf("Error: Message too short to be encrypted.\n");
return 1;
}
rails = rand() % (length / 3 + 1 - 2) + 2;
cipher = railFenceCipher(message, length, rails);
printf("Encrypted message: %ls\n", cipher);
free(message);
message = railFenceDecipher(cipher, length, rails);
printf("Decrypted message: %ls\n", message);
free(message);
free(cipher);
return 0;
}