Gostaria de reagir a esta mensagem? Crie uma conta em poucos cliques ou inicie sessão para continuar.

Rimack Zelnick - Challenge 3 - Python

Ir para baixo

Rimack Zelnick - Challenge 3 - Python Empty Rimack Zelnick - Challenge 3 - Python

Mensagem  rmzelnick Qui Jul 28, 2011 7:14 pm

1 - Escolha uma das três etapas do Challenge 2 e reescreva todos os códigos feitos por você desta etapa da maneira mais resumida que você for capaz.( Obs: se esta etapa escolhida estiver incompleta ou você ainda não é participante do Challenge, você tem a opção de começar com uma das etapas do challenge 2 ou de aproveitar o momento para completar caso não tenha feito ). O objetivo é o de desenvolver maneiras de criar códigos menores, mais resumidos uma vez que escrever menos, requer menos tempo, menos prazo.

Eu escolhi hardcore.

1 - Faça um programa que imprima a sí mesmo ou seja, imprimir na tela o seu próprio código fonte. O código fonte será exibido ao abrir o arquivo onde ele está. Obs: Não é permitido o programa abrir e ler o próprio código com chamadas de manipulação de arquivo.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
#-*- coding: utf-8 -*-

# Import system module
import sys

# Global list of strings containing the whole source code in it
src_code = [
"# Import system module",
"import sys",
"",
"# Global list of strings containing the whole source code in it",
"src_code = [",
"]",
"",
"# Define a main function",
"def main(argv):",
" if type(argv) != list:",
" raise TypeError(\"Invalid parameter type\")",
"",
" # Print the first part of the source code",
" for i in range(0, 5):",
" print src_code[i]",
"",
" # Print src_code list of strings",
" for line in src_code:",
" print(chr(9) + chr(34) + line + chr(34) + chr(44))",
"",
" # Print the rest of the code",
" for i in range(5, len(src_code)):",
" print src_code[i]",
"",
" # Return zero indicading the function success",
" return 0",
"",
"# Run the script",
"if __name__ == '__main__':",
" main(sys.argv)",
"",
]

# Define a main function
def main(argv):
if type(argv) != list:
raise TypeError("Invalid parameter type")

# Print the first part of the source code
for i in range(0, 5):
print src_code[i]

# Print src_code list of strings
for line in src_code:
print(chr(9) + chr(34) + line + chr(34) + chr(44))

# Print the rest of the code
for i in range(5, len(src_code)):
print src_code[i]

# Return zero indicading the function success
return 0

# Run the script
if __name__ == '__main__':
main(sys.argv)


2 - A soma dos números primos abaixo de 10 é 2 + 3 + 5 + 7 = 17.
Faça um programa que encontre e imprima a soma de todos os números primos abaixo de dois milhões como também, imprima quantos números foram encontrados.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
#-*- coding: utf-8 -*-

# Import system and math module
import sys
import math

# Define a main function
def main(argv):
if type(argv) != list:
raise TypeError("Invalid parameter type")

# Declare a list of 2 million elements of type bool, if the element
# X of this list is False then the number is not a prime, credits
# for h0t8.
num = [True] * int(2e6);

# 0 and 1 aren't primes
num[0], num[1] = False, False

# Declare to varibles: containing the prime number, and for keeping
# the loop running if the next prime in the list is found
prime, prime_found = 2, True

while prime_found:
# Eliminate all multiples of prime starting from 2*prime
for i in range(2*prime, int(2e6), prime):
num[i] = False

# Assume that the next prime isn't found, find next prime
prime_found = False
for i in range(prime+1, int(math.sqrt(2e6))):
if num[i]:
# The prime was found, so we assign the value of the
# index to the prime
prime = i

# We say that the prime was found
prime_found = True

# Get outta here, since the prime was found
break

# Declare a variable that will sum and count all primes
s, count = 0, 0

# Sum all primes a count them aswell
for i in range(0, len(num)):
if num[i]:
s += i
count += 1

# Print the sum and count of all primes
print("Sum: %d\nCount: %d" % (s, count))

# Return zero since the function succeded
return 0

# Run the script
if __name__ == '__main__':
main(sys.argv)



3 - Faça um programa que encontre o menor número de x + y + z com inteiros x> y> z> 0 tal que x + y, x - y, x + z, x - z, y + z, y - z sejam quadrados perfeitos.

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python
#-*- coding: utf-8 -*-

# Import system and math module
import sys
import math

# Define a main function
def main(argv):
if type(argv) != list:
raise TypeError("Invalid parameter type")

# Declare a list of lists, for solutions. According to the article
# maa.org/editorial/euler/HEDI%2065%20Sums%20that%20are%20squares.pdf
# there are only 9 possibles solutions for this case
solutions = [];

# Test all coeficients: If you have read the article you will notice
# that first of all we MUST find the factors a, b, c and d give the
# f and g coeficients, that can go from 1 to 2.
for g in range(1, 3):
for f in range(1, 3):
# a = 4 * f^2 * g ^ 2
# b = f^4 - 2f^2 * g^2 + 9 * g^4
# c = f^4 + 2f^2 * g^2 + 9 * g^4
# d = 4 * f^2 * g ^ 2

a = 4 * math.pow(f, 2) * math.pow(g, 2)
b = math.pow(f, 4) - 2 * math.pow(f, 2) * math.pow(g, 2) + 9 * math.pow(g, 4)
c = math.pow(f, 4) + 2 * math.pow(f, 2) * math.pow(g, 2) + 9 * math.pow(g, 4)
d = 4 * math.pow(f, 2) * math.pow(g, 4)

# Calculate de values of p, q, r and s given a, b, c and d.
# p = a * c + b * d
# q = |a * d + b * c|
# r = a * d + b * c
# s = |a * c - b * d|

p = a * c + b * d
q = math.fabs(a * d - b * c)
r = a * d + b * c
s = math.fabs(a * c - b * d)

# Finally calculate the solution for x, y and z:
# x = p^2 + q^2
# y = 2 * p * q
# z = 2 * r * s

x = math.pow(p, 2) + math.pow(q, 2)
y = 2 * p * q
z = 2 * r * s

# Append to the solution list of lists
solutions.append([x, y, z])

# Find a solution where x != y & x != z & y != z
for i in solutions:
if i[0] != i[1] and i[0] != i[2] and i[1] != i[2]:
break

# Print the solution and the sum
print("Solution (X, Y, Z): %s\nSum: %d" % (i, sum(i)))

# Return zero since the function succeded
return 0

# Run the script
if __name__ == '__main__':
main(sys.argv)

rmzelnick
rmzelnick

Mensagens : 39
Data de inscrição : 02/07/2011
Idade : 31
Localização : Huntington, NY

http://www.markzelnick.me/

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos