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;
}

Binary file not shown.

View file

@ -0,0 +1,64 @@
import random
def cycleLength(rail, index, railCount, cycle):
if rail == 0:
return 2 * (railCount - (rail + 1))
if rail == railCount - 1:
return 2 * rail
if rail == index:
return 2 * (railCount - (rail + 1))
if cycle == 2 * (railCount - (rail + 1)):
return 2 * rail
return 2 * (railCount - (rail + 1))
def railFenceCipher(message, length, rails):
cycle = 0
cipher = ""
for j in range(rails):
k = j
while True:
cipher += message[k]
cycle = cycleLength(j, k, rails, cycle);
k += cycle
if k >= length:
break;
return cipher
def railFenceDecipher(cipher, length, rails):
i = cycle = 0
message = [None] * length
for j in range(rails):
k = j
while True:
message[k] = cipher[i]
cycle = cycleLength(j, k, rails, cycle);
k += cycle
i += 1
if k >= length:
break;
return "".join(message)
def main ():
print("This program allows for one to encrypt a message using the Rail Fence Cipher.")
message = input("Type in a message with 3 characters or more to be encrypted: ")
length = len(message)
if length < 3:
print("Error: message too short to be encrypted.")
return
# rails = 2 if length // 3 < 3 else random.randrange(2, length // 3)
rails = 5
cipher = railFenceCipher(message, length, rails)
print("Encrypted message:", cipher)
print("Decrypted message:", railFenceDecipher(cipher, length, rails))
main()

View file

@ -0,0 +1,165 @@
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct node {
wchar_t ch;
struct node *next;
} Node;
typedef struct {
Node *start;
Node *end;
} Rail;
int randRange(int min, int max) {
return rand() % (max + 1 - min) + min;
}
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 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;
}
Rail * initializeRail () {
Rail * r = malloc(sizeof(Rail));
r->start = NULL;
return r;
}
Node * createNode (wchar_t c) {
Node *n = malloc(sizeof(Node));
n->ch = c;
return n;
}
void addNode (Rail *r, wchar_t c) {
Node *n = createNode(c);
if (r->start)
r->end->next = n;
else
r->start = r->end = n;
r->end = n;
}
Rail ** loadRails(wchar_t *cipher, int length, int n) {
int i, j, counter, cycle;
Rail **rails = malloc(n * sizeof(Rail*));
for (i = j = 0; i < n; i++) {
counter = i;
rails[i] = initializeRail();
while (counter < length) {
addNode(rails[i], cipher[j++]);
cycle = cycleLength(i, counter, n, cycle);
counter += cycle;
}
}
return rails;
}
wchar_t popFirst (Rail *r) {
Node *n = r->start;
wchar_t c = n->ch;
if (n != r->end)
r->start = n->next;
else
free(r);
free(n);
return c;
}
wchar_t * unloadRails (Rail ** rails, int length, int n) {
wchar_t *message = malloc(length * sizeof(wchar_t));
int i, j;
bool forward = true;
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';
free(rails);
return message;
}
wchar_t * railFenceDecipher(wchar_t *cipher, int length, int n) {
return unloadRails(loadRails(cipher, length, n), length, n);
}
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 = randRange(2, length / 3);
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;
}

Binary file not shown.

View file

@ -0,0 +1,93 @@
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <stdio.h>
int randRange(int min, int max) {
return rand() % (max + 1 - min) + min;
}
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 cycleLength(int rail, int railIndex, int rails, int cycle) {
if (rail == 0)
return 2 * (rails - (rail + 1));
if (rail == rails - 1)
return 2 * rail;
if (rail == railIndex)
return 2 * (rails - (rail + 1));
if (cycle == 2 * (rails - (rail + 1)))
return 2 * rail;
return 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 * railFenceDecipher(wchar_t *cipher, int length, int rails) {
int i, j, k, cycle;
wchar_t *message = malloc(length * sizeof(wchar_t));
for (i = k = 0; i < rails; i++) {
j = i;
do {
message[j] = cipher[k++];
cycle = cycleLength(i, j, rails, cycle);
j += cycle;
} while (j < length);
}
message[k] = '\0';
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 = (length / 3 < 3) ? 2 : randRange(2, length / 3);
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;
}

Binary file not shown.

View file

@ -0,0 +1,14 @@
def removeChar(string, char):
print("\nTexto sem o caractere \"" + char[0], end="\": ")
for c in string:
if c != char[0]:
print(c, end='')
print("")
print("Este programa recebe uma sequência de texto e remove desta um dado tipo de caractere.")
removeChar(
input("\nDigite uma sequência de texto: "),
input("\nDigite um tipo de caractere a ser removido desta: ")
)

View file

@ -0,0 +1,17 @@
def removeSubstring(text, str):
strlen = len(str)
txtlen = len(text)
i = 0
while i < txtlen - strlen and text[i:i + strlen] != str:
i += 1
if i == txtlen - strlen:
return text
return text[0:i] + "" * strlen + removeSubstring (text[i + strlen: txtlen], str)
print("This program removes a given string from a text.")
print("Resulting string: ", removeSubstring(
input("Type in a text and press ENTER: "),
input("Type in a string and press ENTER: ")
))

View file

@ -0,0 +1,9 @@
def invert(string):
for c in range(len(string) - 1, -1, -1):
print(string[c], end='')
print("")
print("Este programa recebe uma sequência de texto e a devolve invertida.")
invert(input("Digite um texto a ser invertido: "))

62
09 - Listas/L-System.py Normal file
View file

@ -0,0 +1,62 @@
import turtle
def draw_l_system(lsystem, t):
saveStates = []
for command in lsystem:
if command == '+':
t.left(25.7)
elif command == '-':
t.right(25.7)
elif command == 'F':
t.forward(50)
elif command == '[':
saveStates.append([t.heading(),t.xcor(),t.ycor()])
elif command == ']':
state = saveStates.pop()
t.setheading(state[0])
t.setposition(state[1],state[2])
def initialize_l_system(n):
lsystem = 'H'
for i in range(n):
tmp = ""
for c in lsystem:
if c == 'H':
tmp += "HFX[+H][-H]"
elif c == 'X':
tmp += "X[-FFF][+FFF]FX"
else:
tmp += c
lsystem = tmp
return lsystem
def main():
print("This program draws an L-System.")
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()
t.shape('turtle')
t.pensize(3)
lsystem = initialize_l_system(n)
print(lsystem)
draw_l_system(lsystem, t)
wn.exitonclick()
main()

60
09 - Listas/L-System2.py Normal file
View file

@ -0,0 +1,60 @@
import turtle
def draw_l_system(lsystem, t):
saveStates = []
for command in lsystem:
if command == '+':
t.left(25)
elif command == '-':
t.right(25)
elif command == 'F':
t.forward(10)
elif command == '[':
saveStates.append([t.heading(),t.xcor(),t.ycor()])
elif command == ']':
state = saveStates.pop()
t.setheading(state[0])
t.setposition(state[1],state[2])
def initialize_l_system(n):
lsystem = 'F'
for i in range(n):
tmp = ""
for c in lsystem:
if c == 'F':
tmp += "F[-F]F[+F]F"
else:
tmp += c
lsystem = tmp
return lsystem
def main():
print("This program draws an L-System.")
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()
t.shape('turtle')
t.pensize(3)
lsystem = initialize_l_system(n)
print(lsystem)
draw_l_system(lsystem, t)
wn.exitonclick()
main()

26
09 - Listas/countOdds.py Normal file
View file

@ -0,0 +1,26 @@
import sys
def countOdds(values):
odds = 0
for i in values:
try:
value = int(i)
except Exception:
continue
if value % 2 != 0:
odds += 1
return odds
def main():
print ("This program calculates the quantity of Odd numbers in a given list of numbers.")
try:
values = input("Type in values: ").split()
except EOFError:
print("")
sys.exit()
print(countOdds(values), "odd values.")
main()

View file

@ -0,0 +1,23 @@
import sys
def countToSam(words):
count = 0
for word in words:
count += 1
if word == "sam":
return count
return count
def main():
print ("This program counts the number of words until the end of the text or the occurence of the word \"sam\" (??)")
try:
words = input("Type in the text: ").split()
except EOFError:
print("")
sys.exit()
print("Word count:", countToSam(words))
main()

View file

@ -0,0 +1,31 @@
import sys
def exceptionSum(values):
sum = 0
pair_found = False
for i in values:
try:
value = float(i)
except Exception:
continue
if not pair_found and value % 2 == 0:
pair_found = True
else:
sum += value
return sum
def main():
print ("This program sums all numbers given, except for the first pair number.")
try:
values = input("Type in values: ").split()
except EOFError:
print("")
sys.exit()
print("Sum:", exceptionSum(values))
main()

34
09 - Listas/lenght5.py Normal file
View file

@ -0,0 +1,34 @@
import sys
def matchLength(words, length):
count = 0
for word in words:
if len(word) == length:
count += 1
return count
def main():
print ("This program calculates the number of words in a given text that have a given length.")
try:
length = int(input("Type in the desired length: "))
except ValueError:
print("Error: Not an integer value.")
sys.exit()
except EOFError:
print("")
sys.exit()
if length < 0:
print("Error: negative value.")
sys.exit()
try:
words = input("Type in the text: ").split()
except EOFError:
print("")
sys.exit()
print("Number of words with length " + str(length) + ":", matchLength(words, length))
main()

View file

@ -0,0 +1,27 @@
import sys
import random
def average(values):
return 0 if len(values) == 0 else sum(values) / len(values)
def main ():
print ("This program calculates the average of a given quantity of random numbers between 0 and 1000.")
try:
n = int(input("Type a quantity: "))
except ValueError:
print("Error: Not an integer value.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error: negative value.")
sys.exit()
values = [random.randrange(1,1000) for i in range(n)]
print("Values:", values)
print("Average:", average(values))
main()

32
09 - Listas/randomMax.py Normal file
View file

@ -0,0 +1,32 @@
import sys
import random
def maximum(values):
maximum = values[0]
for i in range(1, len(values)):
if values[i] > maximum:
maximum = values[i]
return maximum
def main ():
print ("This program calculates the maximum value of a given quantity of random numbers between 0 and 1000.")
try:
n = int(input("Type a quantity: "))
except ValueError:
print("Error: Not an integer value.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error: negative value.")
sys.exit()
values = [random.randrange(1,1000) for i in range(n)]
print("Values:", values)
print("Maximum:", maximum(values))
main()

View file

@ -0,0 +1,24 @@
import sys
def substituteString(source, pattern, length, substitute):
str = source.lower()
try:
i = str.index(pattern)
except Exception:
return source
return source[:i] + substitute + substituteString(source[i + length:], pattern, length, substitute)
def main():
print ("This program substitutes a substring for another in a given string (case insensitive)")
source = input("Type in a string: ")
pattern = input("Type a substring to be substituted: ").lower()
length = len(pattern)
substitute = input("Type its substitute: ")
print(substituteString(source, pattern, length, substitute))
main()

26
09 - Listas/sumPairs.py Normal file
View file

@ -0,0 +1,26 @@
import sys
def sumPairs(values):
sum = 0
for i in values:
try:
value = int(i)
except Exception:
continue
if value % 2 == 0:
sum += value
return sum
def main():
print ("This program calculates the sum of all pair numbers in a given list.")
try:
values = input("Type in values and press ENTER: ").split()
except EOFError:
print("")
sys.exit()
print("Sum of pairs:", sumPairs(values))
main()

View file

@ -0,0 +1,26 @@
import sys
def sumNegatives(values):
sum = 0
for i in values:
try:
value = int(i)
except Exception:
continue
if value < 0:
sum += value
return sum
def main():
print ("This program calculates the sum of negative numbers in a given list.")
try:
values = input("Type in values and press ENTER: ").split()
except EOFError:
print("")
sys.exit()
print("Sum of negatives:", sumNegatives(values))
main()

View file

@ -0,0 +1,32 @@
import sys
def squaresSum(values):
squares = []
for i in values:
try:
squares.append(float(i) ** 2)
except Exception:
pass
print("Squares:", squares)
if len(squares) == 0:
return -1
return sum(squares)
def main ():
print ("This program calculates the sum of squares of the numbers contained in a given list.")
try:
values = input("Type in values: ").split()
except EOFError:
print("")
sys.exit()
print("Values:", values)
sum = squaresSum(values)
if sum < 0:
print("Error: No valid values present in the list.")
else:
print("Sum of squares:", sum)
main()

View file

@ -0,0 +1,46 @@
def toint(input):
output = []
for i in input:
output.append(int(i))
return output
def average(values):
return round(sum(values) / len(values), 2)
def longestNameLength(file):
record = open(file, "r")
maxLength = 0
for line in record.readlines():
line = line.split()
if line == []:
continue
nameLength = len(line[0])
if nameLength > maxLength:
maxLength = nameLength
record.close()
return maxLength
def averageScores(file, columnLength):
record = open(file, "r")
for line in record.readlines():
line = line.split()
if line == []:
continue
padding = " " * (columnLength - len(line[0]))
print("Student: " + line[0] + padding,
"\tAverage score:", average(toint(line[1:])))
record.close()
def main():
print("This program reads a record of the students' grades and prints their average scores")
file = input("Type in the filename of the record: ")
averageScores(file, longestNameLength(file))
main()

View file

@ -0,0 +1,20 @@
def filterStudents(record, n):
for line in record.readlines():
line = line.split()
if len(line) < 2:
continue
student = line[0]
grades = line[1:]
if len(grades) >= n:
print(student)
def main():
print("This program reads a record of the students' grades and prints only the names of those that've been evaluated at least a given amount of times.")
record = open(input("Type the filename of the record: "), "r")
filterStudents(record, int(input("Type the minimum amount of evaluations: ")))
record.close()
main()

44
10 - Arquivos/minmax.py Normal file
View file

@ -0,0 +1,44 @@
def toint(input):
output = []
for i in input:
output.append(int(i))
return output
def longestNameLength(file):
record = open(file, "r")
maxLength = 0
for line in record.readlines():
line = line.split()
if line == []:
continue
nameLength = len(line[0])
if nameLength > maxLength:
maxLength = nameLength
record.close()
return maxLength
def minMaxScores(file, columnLength):
record = open(file, "r")
for line in record.readlines():
line = line.split()
if line == []:
continue
padding = " " * (columnLength - len(line[0]))
grades = toint(line[1:])
print("Student: " + line[0] + padding,
"\tLowest score:", min(grades), "\tHighest score:", max(grades))
record.close()
def main():
print("This program reads a record of the students' grades and prints their average scores")
file = input("Type in the filename of the record: ")
minMaxScores(file, longestNameLength(file))
main()

406
10 - Arquivos/misterio.dat Normal file
View file

@ -0,0 +1,406 @@
CIMA
-218 185
BAIXO
-240 189
-246 188
-248 183
-246 178
-244 175
-240 170
-235 166
-229 163
-220 158
-208 156
-203 153
-194 148
-187 141
-179 133
-171 119
-166 106
-163 87
-161 66
-162 52
-164 44
-167 28
-171 6
-172 -15
-171 -30
-165 -46
-156 -60
-152 -67
-152 -68
CIMA
-134 -61
BAIXO
-145 -66
-152 -78
-152 -94
-157 -109
-157 -118
-151 -128
-146 -135
-146 -136
CIMA
-97 -134
BAIXO
-98 -138
-97 -143
-96 -157
-96 -169
-98 -183
-104 -194
-110 -203
-114 -211
-117 -220
-120 -233
-122 -243
-123 -247
-157 -248
-157 -240
-154 -234
-154 -230
-153 -229
-149 -226
-146 -223
-145 -219
-143 -214
-142 -210
-141 -203
-139 -199
-136 -192
-132 -184
-130 -179
-132 -171
-133 -162
-134 -153
-138 -145
-143 -137
-143 -132
-142 -124
-138 -112
-134 -104
-132 -102
CIMA
-97 -155
BAIXO
-92 -151
-91 -147
-89 -142
-89 -135
-90 -129
-90 -128
CIMA
-94 -170
BAIXO
-83 -171
-68 -174
-47 -177
-30 -172
-15 -171
-11 -170
CIMA
12 -96
BAIXO
9 -109
9 -127
7 -140
5 -157
9 -164
22 -176
37 -204
40 -209
49 -220
55 -229
57 -235
57 -238
50 -239
49 -241
51 -248
53 -249
63 -245
70 -243
57 -249
62 -250
71 -250
75 -250
81 -250
86 -248
86 -242
84 -232
85 -226
81 -221
77 -211
73 -205
67 -196
62 -187
58 -180
51 -171
47 -164
46 -153
50 -141
53 -130
54 -124
57 -112
56 -102
55 -98
CIMA
48 -164
BAIXO
54 -158
60 -146
64 -136
64 -131
CIMA
5 -152
BAIXO
1 -150
-4 -145
-8 -138
-14 -128
-19 -119
-17 -124
CIMA
21 -177
BAIXO
14 -176
7 -174
-6 -174
-14 -170
-19 -166
-20 -164
CIMA
-8 -173
BAIXO
-8 -180
-5 -189
-4 -201
-2 -211
-1 -220
-2 -231
-5 -238
-8 -241
-9 -244
-7 -249
6 -247
9 -248
16 -247
21 -246
24 -241
27 -234
27 -226
27 -219
27 -209
27 -202
28 -193
28 -188
28 -184
CIMA
-60 -177
BAIXO
-59 -186
-57 -199
-56 -211
-59 -225
-61 -233
-65 -243
-66 -245
-73 -246
-81 -246
-84 -246
-91 -245
-91 -244
-88 -231
-87 -225
-85 -218
-85 -211
-85 -203
-85 -193
-88 -185
-89 -180
-91 -175
-92 -172
-93 -170
CIMA
-154 -93
BAIXO
-157 -87
-162 -74
-168 -66
-172 -57
-175 -49
-178 -38
-178 -26
-178 -12
-177 4
-175 17
-172 27
-168 36
-161 48
-161 50
CIMA
-217 178
BAIXO
-217 178
-217 177
-215 176
-214 175
-220 177
-223 178
-223 178
-222 178
CIMA
-248 185
BAIXO
-245 184
-240 182
-237 181
-234 179
-231 177
-229 176
-228 175
-226 174
-224 173
-223 173
-220 172
-217 172
-216 171
-214 170
-214 169
CIMA
-218 186
BAIXO
-195 173
-183 165
-175 159
-164 151
-158 145
-152 139
-145 128
-143 122
-139 112
-138 105
-134 95
-131 88
-129 78
-126 67
-125 62
-125 54
-124 44
-125 38
-126 30
-125 27
-125 8
-126 5
-125 -9
-122 -15
-115 -25
-109 -32
-103 -39
-95 -42
-84 -45
-72 -47
-56 -48
-41 -47
-31 -46
-18 -45
-1 -44
9 -43
34 -45
50 -52
67 -61
83 -68
95 -80
112 -97
142 -115
180 -132
200 -146
227 -159
259 -175
289 -185
317 -189
349 -190
375 -191
385 -192
382 -196
366 -199
352 -204
343 -204
330 -205
315 -209
296 -212
276 -214
252 -208
237 -202
218 -197
202 -193
184 -187
164 -179
147 -173
128 -168
116 -164
102 -160
88 -158
78 -159
69 -162
57 -164
56 -165
51 -165
CIMA
68 -144
BAIXO
83 -143
96 -141
109 -139
119 -146
141 -150
161 -155
181 -163
195 -169
208 -179
223 -187
241 -191
247 -193
249 -194
CIMA
-6 -141
BAIXO
-15 -146
-29 -150
-42 -154
-51 -153
-60 -152
-60 -152
CIMA
-90 -134
BAIXO
-85 -131
-79 -128
-78 -123
-80 -115
-82 -106
-80 -101
-76 -101
CIMA
-81 -132
BAIXO
-76 -130
-71 -126
-72 -124
CIMA
43 -118
BAIXO
44 -125
47 -135
41 -156
37 -160
40 -166
47 -171
47 -171
CIMA
-106 -153
BAIXO
-107 -167
-106 -178
-109 -192
-114 -198
-116 -201

28
10 - Arquivos/mystery.py Normal file
View file

@ -0,0 +1,28 @@
import turtle
def solve(mystery, t):
for line in mystery.readlines():
line = line.split()
if line[0] == "CIMA":
t.up()
elif line[0] == "BAIXO":
t.down()
else:
t.goto(int(line[0]), int(line[1]))
mystery.close()
def main():
print("This program solves a mystery! Uuuuhh!")
mystery = input("Type in the path of the misterious file: ")
wn = turtle.Screen()
t = turtle.Turtle()
t.shape('turtle')
t.pensize(3)
solve(open(mystery, 'r'), t)
wn.exitonclick()
main()

View file

@ -0,0 +1,6 @@
jose 10 15 20 30 40
pedro 23 16 19 22
suzana 8 22 17 14 32 17 24 21 2 9 11 17
gisela 12 28 21 45 26 10
joao 14 32 25 16 89

3761
11 - Dicionários/alice.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,22 @@
def countLetters(text, case_insensitive):
letterCount = dict()
if case_insensitive == "y" or case_insensitive == "yes":
for c in text.lower():
letterCount[c] = letterCount.get(c, 0) + 1
else:
for c in text:
letterCount[c] = letterCount.get(c, 0) + 1
return letterCount
def main():
print("This program counts how many characters of each distinct character is present in a given text.")
case_insensitive = input(
"Should this count be case insenstitive? (y)es / (n)o: ").lower()
letterCount = countLetters(
input("Type in a given text: "), case_insensitive)
for c in sorted(letterCount):
print(c, ":", letterCount[c])
main()

View file

@ -0,0 +1,50 @@
import string
def countWords(path, columnWidth):
file = open(path, 'r')
wordCount = dict()
text = ""
for c in file.read():
if c in string.ascii_letters + string.whitespace + "-":
text += c
for word in text.lower().split():
word = word.lstrip('-').rstrip('-')
if word == '':
continue
wordCount[word] = wordCount.get(word, 0) + 1
length = len(word)
if length > columnWidth[0]:
columnWidth[0] = length
file.close()
return wordCount
def selectFilename(path):
beginning = path.rfind('/')
if beginning == -1:
beginning = 0
else:
beginning += 1
end = path.rfind('.')
if end < beginning:
end = len(path)
return path[beginning:end]
def main():
print("This program counts words contained in a plain text file, and saves the results as \"wordCount_filename.dat\".")
path = input("Type in a file's path: ")
columnWidth = [0]
wordCount = countWords(path, columnWidth)
output = "word_count_" + selectFilename(path) + ".dat"
output = open(output, 'w')
output.write("Word" + ' ' * (columnWidth[0] - 4) + "\tfrequency\n")
output.write("-" * columnWidth[0] + "\t" + "-" * columnWidth[0] + "\n")
for word in sorted(wordCount):
padding = columnWidth[0] - len(word)
output.write(word + ' ' * padding + "\t" + str(wordCount[word]) + "\n")
output.close()
main()

View file

@ -0,0 +1,58 @@
import turtle
def countLetters(text):
letterCount = dict()
for c in text:
letterCount[c] = letterCount[c] + 1 if c in letterCount else 1
return letterCount
def drawBar(t, c, value, max):
percent = value / max * 100
if percent > 75:
t.color("#ec5f67")
t.fillcolor("#ec5f67")
elif percent > 25:
t.color("#fac863")
t.fillcolor("#fac863")
else:
t.color("#99c794")
t.fillcolor("#99c794")
t.begin_fill()
t.left(90)
t.forward(value)
t.write(" \"" + c + "\": " + str(value), font=("Roboto", 10, ""))
t.right(90)
t.forward(60)
t.right(90)
t.forward(value)
t.left(90)
t.end_fill()
def drawHistogram(letterCount):
letters = sorted(letterCount.keys())
height = max(letterCount.values())
length = len(letters)
padding = 10
t = turtle.Turtle()
t.pensize(3)
wn = turtle.Screen()
wn.bgcolor("#d8dee9")
wn.setworldcoordinates(0 - padding, 0 - height, 40
* length + padding, height + padding)
for c in letters:
drawBar(t, c, letterCount[c], height)
wn.exitonclick()
def main():
print("This program counts how many characters of each distinct character is present in a given text, and draws an histogram from it.")
drawHistogram(countLetters(input("Type in a given text: ")))
main()

View file

@ -0,0 +1,41 @@
import string
def findLongest(file):
longestLength = 0
longestWords = []
word = ""
length = 0
for c in file.read():
if c in string.ascii_letters + "-":
word += c
length += 1
else:
if length > longestLength:
longestWords = [word]
longestLength = length
elif length == longestLength and not word in longestWords:
longestWords.append(word)
word = ""
length = 0
return (longestWords, longestLength)
def main():
print("This program finds the longest word, or words, in a plain text file.")
file = open(input("Type in a file's path: "), 'r')
longestWords = findLongest(file)
if len(longestWords[0]) == 1:
print("The longest word in the given file is "
+ longestWords[0] + ", with a length of", longestWords[1], "characters")
else:
print("The longest words in the given file are:",
longestWords[0][0], end='')
for word in longestWords[0][1:]:
print(',', word, end='')
print("\nAll with a length of", longestWords[1], "characters")
file.close()
main()

View file

@ -0,0 +1,26 @@
def piratefy(text):
output = ""
dict = {"sir": "matey", "hotel": "fleabag inn", "student": "swabbie",
"boy": "matey", "madam": "proud beauty", "professor":
"foul blaggart", "restaurant": "galley", "your": "yer", "excuse":
"arr", "are": "be", "lawyer": "foul blaggart", "the": "th'",
"restroom": "head", "my": "me", "hello": "avast", "is": "be",
"man": "matey"}
for word in text.split():
output += " "
lower = word.lower()
if lower in dict:
output += lower.capitalize() if word[0].isupper() else dict[lower]
else:
output += word
return output.lstrip()
def main():
print("This program translates common english to its pirate dialect equivalent.")
translation = piratefy(input("Type in a message: "))
print("Translation into pirate speak:", translation)
main()

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,68 @@
import turtle
def drawLSystem(t, lsystem):
if lsystem == "":
return
if lsystem[0] == '+':
t.left(90)
elif lsystem[0] == '-':
t.right(90)
elif lsystem[0] == 'F':
t.forward(50)
drawLSystem(t, lsystem[1:])
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()

30
12 - Recursão/base10.c Normal file
View file

@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdbool.h>
bool isBinary (int n) {
if (n < 0)
return false;
while (n > 0) {
if (n % 10 > 1)
return false;
n /= 10;
}
return true;
}
int base10 (int binary) {
if (binary < 10)
return binary;
return base10(binary / 10) * 2 + binary % 10;
}
int main() {
int i;
printf("This program converts a number from base 2 to base 10.\nType a binary number and press ENTER: ");
if (!scanf(" %d", &i) || !isBinary(i)) {
printf("Invalid value passed.\n");
return 1;
}
printf("The binary %d is equivalent to the decimal %d in base 10.\n", i, base10(i));
}

BIN
12 - Recursão/base10.out Normal file

Binary file not shown.

38
12 - Recursão/base10.py Normal file
View file

@ -0,0 +1,38 @@
import sys
def isBinary(n):
if (n < 0):
return False
while n > 0:
if n % 10 > 1:
return False
n //= 10
return True
def base10(n):
if n // 10 == 0:
return n % 10
return base10(n // 10) * 2 + (n % 10)
def main():
print("This program converts a number from base 10 to base 2.")
try:
n = int(input("Type a binary number and press ENTER: "))
except ValueError:
print("Error: not a number.")
sys.exit()
except EOFError:
print("")
sys.exit()
if not isBinary:
print("Not a binary number")
sys.exit()
print("The binary", n, "is equivalent to the decimal",
base10(n), "in base 10.")
main()

18
12 - Recursão/base2.c Normal file
View file

@ -0,0 +1,18 @@
#include <stdio.h>
int base2 (int i) {
if (i < 2)
return i;
return base2(i / 2) * 10 + (i % 2);
}
int main() {
int i;
printf("This program converts a number from base 10 to base 2.\nType a non-negative integer value: and press ENTER: ");
if (!scanf(" %d", &i) || i < 0) {
printf("Invalid value passed.\n");
return 1;
}
printf("The decimal %d is equivalent to the binary %d in base 2.\n", i, base2(i));
}

BIN
12 - Recursão/base2.out Normal file

Binary file not shown.

27
12 - Recursão/base2.py Normal file
View file

@ -0,0 +1,27 @@
import sys
def base2(i):
if i < 2:
return i % 2
return base2(i // 2) * 10 + (i % 2)
def main():
print("This program converts a number from base 10 to base 2.")
try:
n = int(input("Type a non-negative 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()
print("The decimal", n, "is equivalent to the binary", base2(n), "in base 2.")
main()

View file

@ -0,0 +1,34 @@
import turtle
import random
def tree(branchLen, t):
if branchLen < 5:
return
t.color("#bdcebe" if branchLen < 45 else "#b9936c")
t.pensize(branchLen // 5)
t.forward(branchLen)
angle = random.randrange(14, 47, 2)
length = random.randrange(branchLen - 10, branchLen)
t.right(angle // 2)
tree(length, t)
t.left(angle)
tree(length, t)
t.right(angle // 2)
t.color("#bdcebe" if branchLen < 45 else "#b9936c")
t.backward(branchLen)
def main():
t = turtle.Turtle()
myWin = turtle.Screen()
t.speed(0)
t.left(90)
t.up()
t.backward(100)
t.down()
tree(75, t)
myWin.exitonclick()
main()

View file

@ -0,0 +1,28 @@
import sys
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
def main():
print("This program calculates the factorial for a non-negative integer.")
try:
n = int(input("Type in a number and press ENTER: "))
except ValueError:
print("Error: not a number.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error: negative value.")
sys.exit()
print(str(n) + "! =", factorial(n))
main()

View file

@ -0,0 +1,36 @@
import sys
def fibonacci(n):
i = 0
mem = [1, 1, 1]
while i < n and i < 2:
i += 1
while n > 2:
mem[i - 2] = mem[i - 1]
mem[i - 1] = mem[i]
mem[i] += mem[i - 2]
n -= 1
return mem[i]
def main():
print("This program displays the nth number in the fibonacci sequence.")
try:
n = int(input("Type in a value for n and press ENTER: "))
except ValueError:
print("Error: not a number.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error: negative value.")
sys.exit()
print(fibonacci(n))
main()

View file

@ -0,0 +1,28 @@
import sys
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def main():
print("This program displays the nth number in the fibonacci sequence.")
try:
n = int(input("Type in a value for n and press ENTER: "))
except ValueError:
print("Error: not a number.")
sys.exit()
except EOFError:
print("")
sys.exit()
if n < 0:
print("Error: negative value.")
sys.exit()
print(fibonacci(n))
main()

28
12 - Recursão/rebase.py Normal file
View file

@ -0,0 +1,28 @@
import sys
def rebase(n, base):
digits = "0123456789ABCDEF"
if i < 2:
return i
return base2(i // 2) * 10 + (i % 2)
def main():
print("This program converts a number from base 10 to base 2.")
try:
n = int(input("Type a non-negative 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()
print("The decimal", n, "is equivalent to the binary", base2(n), "in base 2.")
main()

16
12 - Recursão/rec1.py Normal file
View file

@ -0,0 +1,16 @@
def listSum(integers):
if integers == []:
return 0
return integers[0] + listSum(integers[1:])
def main():
strings = input().split()
integers = []
for i in strings:
integers.append(int(i))
print(listSum(integers))
main()

16
12 - Recursão/rec2.py Normal file
View file

@ -0,0 +1,16 @@
def listSum(integers):
if len(integers) == 1:
return integers[0]
return integers[0] + listSum(integers[1:])
def main():
strings = input().split()
integers = []
for i in strings:
integers.append(int(i))
print(listSum(integers))
main()

View file

@ -0,0 +1,34 @@
import turtle
def koch_curve(t, iterations, length, shortening_factor, angle):
if iterations == 0:
t.forward(length)
else:
iterations = iterations - 1
length = length / shortening_factor
koch_curve(t, iterations, length, shortening_factor, angle)
t.left(angle)
koch_curve(t, iterations, length, shortening_factor, angle)
t.right(angle * 2)
koch_curve(t, iterations, length, shortening_factor, angle)
t.left(angle)
koch_curve(t, iterations, length, shortening_factor, angle)
def main():
t = turtle.Turtle() # create the turtle
wn = turtle.Screen()
t.up()
t.back(200)
t.down()
t.speed(9)
for i in range(3):
koch_curve(t, 4, 200, 3, 60)
t.right(120)
wn.exitonclick()
main()

View file

@ -0,0 +1,33 @@
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 reverseString(str, len):
last = len - 1
if last == 0:
return str[last]
return str[last] + reverseString(str[:last])
def isPalindrome(str):
str = normalizeString(str)
if str == reverseString(str, len(str)):
return True
return False
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")

16
12 - Recursão/reverse.py Normal file
View file

@ -0,0 +1,16 @@
def reverse(list, length):
if length == 1:
return [list[0]]
return [list[length - 1]] + reverse(list, length - 1)
def main():
print("This program prints a reversed list of values in reverse order.")
list=input("Type in a comma separated list of values: ").split(',')
for i in list:
i=i.lstrip(' ')
print(reverse(list, len(list)))
main()

16
12 - Recursão/spiral.py Normal file
View file

@ -0,0 +1,16 @@
import turtle
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
def drawSpiral(myTurtle, lineLen):
if lineLen > 0:
myTurtle.forward(lineLen)
myTurtle.right(90)
drawSpiral(myTurtle, lineLen-5)
drawSpiral(myTurtle, 100)
myWin.exitonclick()

100000
12 - Recursão/test.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,110 @@
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def coordinates(self):
return (self.x, self.y)
def distance(self, point):
return ((self.x - point.x)**2 + (self.y - point.y)**2) ** 0.5
class Circle:
""" Coordinates for a circle of given center and radius """
def __init__(self, p1, p2, p3):
def repeated(p1, p2, p3):
if p1 == p2 or p1 == p3 or p2 == p3:
return True
return False
def colinear(p1, p2, p3):
if (p2.x - p1.x) == 0 or (p3.x - p1.x) == 0:
if (p1.x == p2.x and p1.x == p3.x) or \
(p1.y == p2.y and p1.y == p3.y):
return True
elif (p2.y - p1.y) / (p2.x - p1.x) == (p3.y - p1.y) / (p3.x - p1.x):
return True
return False
if repeated(p1, p2, p3) or colinear(p1, p2, p3):
self.radius = None
return
d = p1.x * (p2.y - p3.y)
d += p2.x * (p3.y - p1.y)
d += p3.x * (p1.y - p2.y)
d *= 2
x = (p1.x ** 2 + p1.y ** 2) * (p2.y - p3.y)
x += (p2.x ** 2 + p2.y ** 2) * (p3.y - p1.y)
x += (p3.x ** 2 + p3.y ** 2) * (p1.y - p2.y)
x /= d
y = (p1.x ** 2 + p1.y ** 2) * (p3.x - p2.x)
y += (p2.x ** 2 + p2.y ** 2) * (p1.x - p3.x)
y += (p3.x ** 2 + p3.y ** 2) * (p2.x - p1.x)
y /= d
self.center = Point(x, y)
self.radius = p1.distance(self.center)
def read_points():
data = input(
"Type in, separated by spaces, the x and y coordinates of the four points, respectively: ").split()
coordinates = []
for i in data:
try:
coordinate = float(i)
except ValueError:
print("Warning: \"" + i + "\" is not a number, ignored.")
else:
coordinates.append(coordinate)
count = len(coordinates)
if count < 8:
if count == 7:
print("Error: missing a coordinate.")
else:
print("Error: missing", 8 - count, "coordinates.")
return None
points = []
for i in range(0, 8, 2):
point = Point(coordinates[i], coordinates[i + 1])
if point in points:
print("Error: repeated point", point)
return None
points.append(point)
return points
def main():
print("This program calculates the center of a circle, given the location of four points on it.")
points = read_points()
if points is None:
return
circ = Circle(points[0], points[1], points[2])
print("The points", end=' ')
for p in points:
print(p, end=", ")
if circ.radius is None or points[0].distance(circ.center) != points[3].distance(circ.center):
print("do not lie on the same circle.")
else:
print("lie on a circle of center",
circ.center, "and radius", circ.radius)
main()

View file

@ -0,0 +1,42 @@
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, x, y):
self.x = x
self.y = y
def coordinates(self):
return (self.x, self.y)
def distance(self, point):
return ((self.x - point.x)**2 + (self.y - point.y)**2) ** 0.5
def main():
print("This program calculates the euclidian distance between two points")
data = input(
"Type in, separated by spaces, the x and y coordinates of the two points, respectively: ").split()
count = 0
coordinates = []
for i in data:
try:
coordinate = float(i)
except ValueError:
print("Warning: \"" + i + "\" is not a number, ignored.")
else:
coordinates.append(coordinate)
count += 1
if count < 4:
if 4 - count == 1:
print("Error: missing a coordinate.")
else:
print("Error: missing", 4 - count, "coordinates.")
return
p = Point(coordinates[0], coordinates[1])
q = Point(coordinates[2], coordinates[3])
print("The distance between", p.coordinates(),
"and", q.coordinates(), "is", p.distance(q))
main()

View file

@ -0,0 +1,46 @@
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, x, y):
self.x = x
self.y = y
def coordinates(self):
return (self.x, self.y)
def angular_coeficient(self, point):
delta_x = point.x - self.x
delta_y = point.y - self.y
return 0 if delta_x == 0 else delta_y / delta_x
def linear_coeficient(self, point):
return self.y - self.angular_coeficient(point) * self.x
def main():
print("This program calculates the angular and linear coeficients, respectively, for a line drawn crossing two points.")
data = input(
"Type in, separated by spaces, the x and y coordinates of both points, respectively: ").split()
count = 0
coordinates = []
for i in data:
try:
coordinate = float(i)
except ValueError:
print("Warning: \"" + i + "\" is not a number, ignored.")
else:
coordinates.append(coordinate)
count += 1
if count < 4:
if count == 3:
print("Error: missing a coordinate.")
else:
print("Error: missing", 4 - count, "coordinates.")
return
p = Point(coordinates[0], coordinates[1])
q = Point(coordinates[2], coordinates[3])
print((p.angular_coeficient(q), p.linear_coeficient(q)))
main()

View file

@ -0,0 +1,91 @@
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def coordinates(self):
return (self.x, self.y)
def distance(self, point):
return ((self.x - point.x)**2 + (self.y - point.y)**2) ** 0.5
def on(self, rect):
if self.x >= rect.corner.x and \
self.x <= rect.corner.x + rect.length and \
self.x >= rect.corner.x and \
self.x <= rect.corner.x + rect.length:
return True
return False
class Rectangle:
""" Performs calculations on rectangles."""
def __init__(self, point, length, height):
self.corner = point
self.length = float(length)
self.height = float(height)
def area(self):
return self.length * self.height
def perimeter(self):
return 2 * (self.length + self.height)
def transpose(self):
tmp = self.length
self.length = self.height
self.height = tmp
def collides(self, rect):
if self.corner.x < rect.corner.x + rect.length and \
self.corner.x + self.length > rect.corner.x and \
self.corner.y < rect.corner.y + rect.height and \
self.corner.y + self.height > rect.corner.y:
return True
return False
def main():
print("This program perform calculations on rectangles. Let us first decribe a rectangle:")
rect1 = Rectangle(
Point(input("Give the x coordinate of bottom left corner: "),
input("Give the y coordinate of bottom left corner: ")),
input("Give the rectangle's length: "),
input("Give the rectangle's height: "))
print("The area of this rectangle is", rect1.area(),
"and its perimeter is", rect1.perimeter())
print("Now we'll transpose such rectangle.")
rect1.transpose()
print("This rectangle's new length is", rect1.length,
"and its height is", rect1.height)
print("Test if a given point lies on the rectangle.")
point = Point(input("Give the point's x coordinate: "),
input("And its y coordinate: "))
if point.on(rect1):
print("The point is on the rectangle.")
else:
print("The point is not on the rectangle.")
print("Test if another rectangle collides with the first. Describe a new rectangle:")
rect2 = Rectangle(
Point(input("Give the x coordinate of bottom left corner: "),
input("Give the y coordinate of bottom left corner: ")),
input("Give the rectangle's length: "),
input("Give the rectangle's height: "))
if rect1.collides(rect2):
print("The rectangles are colliding.")
else:
print("The rectangles are not colliding.")
main()

View file

@ -0,0 +1,42 @@
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, x, y):
self.x = x
self.y = y
def coordinates(self):
return (self.x, self.y)
def reflect_x(self):
self.y = -self.y
def main():
print("This program calculates the coordinates of the reflection of a point along the x axis.")
data = input(
"Type in, separated by spaces, the x and y coordinates of a point, respectively: ").split()
count = 0
coordinates = []
for i in data:
try:
coordinate = float(i)
except ValueError:
print("Warning: \"" + i + "\" is not a number, ignored.")
else:
coordinates.append(coordinate)
count += 1
if count < 2:
if count == 1:
print("Error: missing a coordinate.")
else:
print("Error: no coordinates given.")
return
p = Point(coordinates[0], coordinates[1])
print("The reflection of", p.coordinates(), end=' ')
p.reflect_x()
print("is", p.coordinates())
main()

View file

@ -0,0 +1,39 @@
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, x, y):
self.x = x
self.y = y
def coordinates(self):
return (self.x, self.y)
def slope_from_origin(self):
return 0 if self.x == 0 else self.y / self.x
def main():
print("This program calculates the slope between a given point and the origin of the system ofcoordinates.")
data = input(
"Type in, separated by spaces, the x and y coordinates of a point, respectively: ").split()
count = 0
coordinates = []
for i in data:
try:
coordinate = float(i)
except ValueError:
print("Warning: \"" + i + "\" is not a number, ignored.")
else:
coordinates.append(coordinate)
count += 1
if count < 2:
if count == 1:
print("Error: missing a coordinate.")
else:
print("Error: no coordinates given.")
return
print(Point(coordinates[0], coordinates[1]).slope_from_origin())
main()

Some files were not shown because too many files have changed in this diff Show more