blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3cb0a1c8508872b40294d2a65f1fb0b704abdc93 | alfreh/mi-primera-bici | /adivina_numero.py | 883 | 3.890625 | 4 |
number_to_guess = 2
user_number = int(input("Adivina el numero: "))
if number_to_guess== user_number:
print("Menuda Potra")
else:
print("Ni de coña, ")
number_to_guess = 2
user_number = int(input("Sigue rascando: "))
if number_to_guess == user_number:
print("Menuda Potra")
else:
print("Ni de coña, ")
number_to_guess = 2
user_number = int(input("Sigue rascando: "))
if number_to_guess == user_number:
print("Menuda Potra")
else:
print("Ni de coña, ")
number_to_guess = 2
user_number = int(input("Sigue rascando: "))
if number_to_guess == user_number:
print("Menuda Potra")
else:
print("Ni de coña, ")
number_to_guess = 2
user_number = int(input("Sigue rascando: "))
if number_to_guess == user_number:
print("Por Fin")
else:
print("Se acabaron las balas vaquero") |
9fd3bdb51590d4804d419812a901a68acd906ad6 | pblvll/Coffee_Machine_2 | /Problems/What day is it?/task.py | 164 | 3.65625 | 4 | time = int(input())
reference = 10.5
if (reference + time) < 0:
print("Monday")
elif (reference + time) > 24:
print("Wednesday")
else:
print("Tuesday")
|
f225d41903b92b6539f9355a9464ba852ac6241c | pblvll/Coffee_Machine_2 | /Problems/Keep on sailing/task.py | 401 | 4.03125 | 4 | # our class Ship
class Ship:
def __init__(self, name, capacity, city):
self.name = name
self.capacity = capacity
self.cargo = 0
self.city = city
# the old sail method that you need to rewrite
def sail(self):
return print("The {} has sailed for {}!".format(self.name, self.city))
black_pearl = Ship("Black Pearl", 800, input())
black_pearl.sail()
|
a28553af5ad0aa6eda20aba7bcaf09fffb6b0925 | Olks/MITx6.00.1x_IntroductionToCSandProgrammingUsingPython | /Queue.py | 569 | 3.96875 | 4 | class Queue(object):
"""An Queue is a list of objects"""
def __init__(self):
"""Create an empty list"""
self.objects = []
def insert(self, e):
"""Inserts e into self"""
self.objects.append(e)
def remove(self):
"""Removes first element from the list"""
try:
return self.objects.pop(0)
except:
raise ValueError
def __str__(self):
"""Returns a string representation of self"""
return '{' + ','.join([str(e) for e in self.objects]) + '}' |
f9192d47aaf79939fdfc46ef904624a4ccff1739 | eamuntz/Project-Euler | /problem023.py | 1,542 | 4 | 4 | '''
Problem 23
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
'''
import math
def factor_sum(number):
total=1
sqrt=math.sqrt(number)
for each in range(2,int(math.ceil(sqrt))):
if number%each==0:
total+=each+(number/each)
if int(sqrt)**2==number:
total+=int(sqrt)
return total
abundant=[]
for each in range(12,28101):
if factor_sum(each)>each:
abundant.append(each)
abu_sums=set()
a=abundant.pop(0)
while a<28124/2:
abu_sums.add(a+a)
for each in abundant:
temp_sum=a+each
if temp_sum<28124:
abu_sums.add(temp_sum)
else:
break
a=abundant.pop(0)
finish=set.difference(set(range(28124)),abu_sums)
print sum(finish)
|
5676d0940615be51eb22e1c525d732f764edb199 | eamuntz/Project-Euler | /problem025.py | 288 | 3.65625 | 4 | '''
Problem 25
What is the first term in the Fibonacci sequence to contain 1000 digits?
'''
def fibGen():
a=1
b=2
c=0
while True:
c= a+b
a,b=b,c
yield b
fibGen=fibGen()
count = 4
while True:
fib = fibGen.next()
if len(str(fib))>999:
print count
break
else:
count+=1 |
295c652e48cd661baedc8d43b61d5b8a9419b42a | eamuntz/Project-Euler | /prime.py | 2,011 | 3.859375 | 4 | import math
import random
#tools to help with questions involving prime numbers
#code from other sources is noted with url's leading to source
'''
http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Primality_Testing
pseudo-prime checks that should hold for numbers below
When the number n to be tested is small, trying all a < 2(ln n)2 is not necessary, as much smaller sets of potential witnesses are known to suffice. For example, Pomerance, Selfridge and Wagstaff[8] and Jaeschke[9] have verified that
if n < 1,373,653, it is enough to test a = 2 and 3;
if n < 9,080,191, it is enough to test a = 31 and 73;
if n < 4,759,123,141, it is enough to test a = 2, 7, and 61;
if n < 1,122,004,669,633, it is enough to test a = 2, 13, 23, and 1662803;
if n < 2,152,302,898,747, it is enough to test a = 2, 3, 5, 7, and 11;
if n < 3,474,749,660,383, it is enough to test a = 2, 3, 5, 7, 11, and 13;
if n < 341,550,071,728,321, it is enough to test a = 2, 3, 5, 7, 11, 13, and 17.
'''
def miller_rabin(m, k = 3):
s=1
t = (m-1)/2
while t%2 == 0:
t /= 2
s += 1
for r in range(0,k):
rand_num = random.randint(1,m-1)
y = pow(rand_num, t, m)
prime = False
if (y == 1):
prime = True
for i in range(0,s):
if (y == m-1):
prime = True
break
else:
y = (y*y)%m
if not prime:
return False
return True
'''generate primes up to a limit using the Sieve of Eratosthenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)'''
def sieve(limit):
primes = []
output = []
upperLimit = int(math.sqrt(limit))
for i in range(0,limit):
primes.append(True)
for i in range(2,upperLimit+1):
if primes[i]:
j = i * i
while j<limit:
primes[j] = False;
j += i
#for(var j = i*i; j<limit; j+=i):
# primes[j] = false;
for i in range(2,limit):
if(primes[i]==True):
output.append(i)
return output
|
1af4310b3d1fd0868304e58ba0f613e1c4518f1a | fabriciohenning/aula-pec-2020 | /08-1_ex01.py | 495 | 3.8125 | 4 | def ler_numeros(n):
numeros = []
for i in range(n):
numeros.append(int(input(f'Digite o {i+1}º número: ')))
return numeros
def main():
numeros = ler_numeros(10)
print(f'Os números da lista são {numeros}.')
soma = 0
mult = 1
for c in numeros:
soma = soma + c
mult = mult * c
print(f'A soma e a multiplicação desses 10 números são {soma} e {mult}, respectivamente.')
if __name__ == '__main__':
main()
|
eb6452965abbd30e508d47f7cbd1a4205fadcc6e | fabriciohenning/aula-pec-2020 | /09-1_04.py | 764 | 3.71875 | 4 | def carrega_cidades():
resultado = []
with open('cidades.csv', 'r', encoding='utf-8') as arquivo:
for linha in arquivo:
uf, ibge, nome, dia, mes, pop = linha.split(';')
resultado.append(
(uf, int(ibge), nome, int(dia), int(mes), int(pop))
)
arquivo.close()
return resultado
def main():
populacao = int(input('Informe uma população para receber as cidades com população maior: '))
cidades = carrega_cidades()
print(f'CIDADES COM MAIS DE {populacao} HABITANTES:')
for uf, ibge, nome, _, _, pop in cidades:
if pop > populacao:
print(f'IBGE: {ibge} - {nome}({uf}) - POPULAÇÃO: {pop}')
if __name__ == '__main__':
main()
|
d751374d8f906bef6832cd867362d10e66d26a14 | fabriciohenning/aula-pec-2020 | /05-1_ex04.py | 153 | 3.609375 | 4 | # Sequência de 10 em 10, até 1000
for n in range(10, 1001, 10):
if n != 1000:
print(n, end=', ')
else:
print(n, end='.')
|
cfe652544d5b776725be43b10cf987aef73f91c6 | fabriciohenning/aula-pec-2020 | /e.reforma.py | 429 | 3.859375 | 4 | alt = float(input('Digite a altura das paredes da sala, em metros: '))
compr = float(input('Digite o comprimento da sala, em metros: '))
larg = float(input('Digite a largura da sala, em metros: '))
print(f'A área do piso é de {compr * larg:.2f} metros quadrados.')
print(f'O volume é de {alt * compr * larg:.2f} metros cúbicos.')
print(f'A área das paredes é de {2 * alt * larg + 2 * alt * compr} metros quadrados.')
|
1dcf032300eca48738fc78502ca779c94e1bbd0f | fabriciohenning/aula-pec-2020 | /Atividade Remota – 02-1/4. maior-numero.py | 427 | 3.828125 | 4 | n1 = int(input('Digite o 1º número: '))
n2 = int(input('Digite o 2º número: '))
n3 = int(input('Digite o 3º número: '))
n4 = int(input('Digite o 4º número: '))
n5 = int(input('Digite o 5º número: '))
print(f'O maior número entre eles é {max(n1, n2, n3, n4, n5)}.')
print(f'O menor número entre eles é {min(n1, n2, n3, n4, n5)}.')
print(f'A média aritmética dos números lidos é {(n1+n2+n3+n4+n5)/5}.')
|
ef55a172a73edcf2fdc3d7dec4dec1105c83c7de | fabriciohenning/aula-pec-2020 | /07-2_ex02.py | 350 | 4.0625 | 4 | # Sequência de Fibonacci com n termos
num = int(input('Digite um valor maior que 2: '))
termo1 = 0
termo2 = 1
cont = 3
print(f'A sequência de Fibonacci com {num} termos é {termo1}, {termo2}', end='')
while cont <= num:
termo3 = termo1 + termo2
print(f', {termo3}', end='')
termo1 = termo2
termo2 = termo3
cont += 1
|
c8abcc93b79ab776f635fd051787fc70af79d93b | fabriciohenning/aula-pec-2020 | /06-2_ex01.py | 184 | 4.0625 | 4 | soma = 0
while True:
n = int(input('Digite um número: '))
if n != 0:
soma += n
if n == 0:
break
print(f'A soma dos números digitados é {soma}.')
|
a891ee5380c54a475737976341d776b9ef44e15c | ShubhamGarg01/Faulty-Calculator | /faultycalci.py | 619 | 4.1875 | 4 | print("enter 1st number")
num1= int(input())
print("enter 2nd number")
num2= int(input())
print("so what u weant" ,"+,*,/,-,%")
num3= input()
if num1 == 45 and num2==3 and num3== "*":
print("555")
elif num1 ==56 and num2==9 and num3=="+":
print("77")
elif num1== 56 and num2==6 and num3=="/":
print("4")
elif num3 == "*":
multiply =num1*num2
print(multiply)
elif num3=="+":
plus= num1+num2
print(plus)
elif num3 == "-":
subtrt = num2 - num1
print(subtrt)
elif num3== "/":
percent=num2%num1
print(percent)
else:
print("out of range")
|
ec8e20416881e145b678ad339752f45538570d43 | sengeiou/python | /数字/质数/所有.py | 277 | 3.65625 | 4 | x = 1
def main():
num = x
# 质数大于 1
if num > 1:
# 查看因子
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,'\n')
print('')
while True:
main()
x += 1
|
0da2d34f91c985c72585e201cb26b29eeb84160e | GodNarcissus/FinalProject17 | /options_in_different_locations_test.py | 2,226 | 3.75 | 4 | import time
s=0
class Character(object):
def __init__(self,name,location):
self.name = name
self.location = location
myself = Character("me" , "A")
#uber = Character("Uber Driver" , myself.location)
map = ["A", "B", "C"]
visited = ["A"]
def gps():
print("|", end=" ")
for x in map:
print(x, end=" | ")
print('\x1b[1;37;40m' + "MAP" + '\x1b[0m')
#gives a list of locations on the same line
def uber():
print("calling your uber driver...")
time.sleep(2)
print("...")
time.sleep(2)
print('\x1b[0;30;47m' + f"What's up, {myself.name}? Where you wanna go?" + '\x1b[0m')
time.sleep(1)
print('\x1b[0;30;47m' + "Just tell me where." + '\x1b[0m')
time.sleep(1)
while True:
gps()
d = input(">>> ")
if d == myself.location:
print('\x1b[0;30;47m' + "My dude we're already here!" + '\x1b[0m')
time.sleep(s)
print('\x1b[0;30;47m' + "Don't make me waste my time!" + '\x1b[0m')
elif d in map:
print('\x1b[0;30;47m' + "Going there now, my dude." + '\x1b[0m')
time.sleep(1)
print("traveling...")
time.sleep(1)
myself.location=d
uber.location=d
print('\x1b[0;30;47m' + "Aight we here now. I'll be waiting here if you need me." + '\x1b[0m')
time.sleep(1)
print(f"you are now at '{myself.location}.'")
break
else:
print('\x1b[0;30;47m' + "I can't find that location in my gps." + '\x1b[0m')
time.sleep(s)
print('\x1b[0;30;47m' + "Make sure you tell me the location exactly as it is on your map. Copy & paste it if you need to." + '\x1b[0m')
while True:
if myself.location == "A":
a = input(">>> ")
if a == "call uber":
uber()
elif myself.location == "B":
if "B" not in visited:
visited.append("B")
print("this is 'B'")
else:
print("you've been here before")
a = input(">>> ")
if a == "call uber":
uber()
elif myself.location == "C":
a = input(">>> ")
if a == "call uber":
uber()
|
b1c9434f2d4e939565f78de69d4a3774db16c67c | zotochev/VSHE | /week_06/tasks_06/06_01_list_merge2.py | 453 | 3.703125 | 4 | def to_sort(a, b, c):
s_list = []
if len(a) != 0 and len(b) != 0:
if a[-1] > b[-1]:
s_list.append(a.pop())
to_sort(a, b, c)
else:
s_list.append(b.pop())
to_sort(a, b, c)
elif len(a) == 0:
s_list.extend(b)
else:
s_list.extend(a)
c += s_list
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
c = []
to_sort(s1, s2, c)
print(*c)
|
7f89b06b9d91d8136247fe38ad5d6877ac426e0c | zotochev/VSHE | /week 02/tasks_02/02_41_fib_num_num.py | 243 | 3.71875 | 4 | a = int(input())
count = 1
fib_num = 0
fib_num_2 = 0
fib_num_1 = 1
while fib_num < a:
count += 1
fib_num = fib_num_1 + fib_num_2
fib_num_2 = fib_num_1
fib_num_1 = fib_num
if fib_num_1 != a:
print(-1)
else:
print(count)
|
cce3783549111bdc61d9b11580c52b1636c39f86 | zotochev/VSHE | /week 02/tasks_02/02_20_icecreame3.py | 144 | 3.515625 | 4 | k = int(input())
# k = 3
m = (k % 10) + 10
if k < 10:
m = k
if m == 7 or m == 4 or m == 2 or m == 1:
print('NO')
else:
print('YES')
|
b7323b374c21bb4430ed3b5538443bf99c402daa | zotochev/VSHE | /week 04/notes_04/notes_week_04_02.py | 305 | 3.90625 | 4 | # def max2 (a, b):
# if a > b:
# return a
# else:
# return b
#
# print(max2(2, 5))
def max2 (a, b):
if a > b:
return a
return b
#
# print(max2(2, 5))
# print(max2(7, 3))
# print(max2(2, 2))
def max3 (a, b, c):
return max2(max2(a, b), c)
print(max3(2, 5, 3))
|
abfa38888111fc1fb385083c50cb5f2e01ce138f | zotochev/VSHE | /week 02/tasks_02/02_16_samenum.py | 158 | 3.8125 | 4 | a = int(input())
b = int(input())
c = int(input())
# a = 1
# b = 2
# c = 3
d = 0
if a == b or b == c or a == c:
d = 2
if a == b == c:
d = 3
print(d)
|
af80cbb112dec035bc2c2bcd5cfd7d520dd0a441 | zotochev/VSHE | /week 02/tasks_02/02_23_matches.py | 941 | 3.53125 | 4 | # l1 = int(input())
# r1 = int(input())
# l2 = int(input())
# r2 = int(input())
# l3 = int(input())
# r3 = int(input())
l1 = 7
r1 = 9
l2 = 5
r2 = 11
l3 = 15
r3 = 19
answer = 0
# сортировка левых координат
if l1 >= l2 and l1 >= l3:
(g, k1, k2) = (l1, l2, l3)
elif l2 >= l3 and l2 >= l1:
(g, k1, k2) = (l2, l1, l3)
else:
(g, k1, k2) = (l3, l1, l2)
if k1 > k2:
(k1, k2) = (k2, k1)
print(k1, k2, g)
# сортировка правых координат
if r1 >= r2 and r1 >= r3:
(g2, k21, k22) = (r1, r2, r3)
elif r2 >= r3 and r2 >= r1:
(g2, k21, k22) = (r2, r1, r3)
else:
(g2, k21, k22) = (r3, r1, r2)
if k21 > k22:
(k21, k22) = (k22, k21)
print(k21, k22, g2)
gap_left = k2 - k21
gap_right = g - k22
print(gap_left, gap_right)
# if gap_left <= 0 and gap_right <= 0:
# answer = 0
#
# m1 = r1 - l1
# m2 = r2 - l2
# m3 = r3 - l3
#
# if gap_left and gap_right > 0:
#
# print(answer)
|
c0b5abff622feb30c68e98d76a7780d7f41ce6d4 | zotochev/VSHE | /week 02/tasks_02/02_40_fib_num.py | 202 | 3.8125 | 4 | n = int(input())
count = 1
fib_num = 0
fib_num_2 = 0
fib_num_1 = 1
while count < n:
count += 1
fib_num = fib_num_1 + fib_num_2
fib_num_2 = fib_num_1
fib_num_1 = fib_num
print(fib_num_1)
|
f5b21b829f1ec73ef71cfe24b06106554576f0ac | zotochev/VSHE | /week 02/tasks_02/02_46_ton_line3.py | 717 | 3.625 | 4 | n = int(input())
n_prev = n
count = 1
count_plus = 1
count_minus = 1
check_plus = 0
while n != 0:
count_plus = 1 + check_plus
count_minus = 1
# if n > n_prev
check_plus = 0
# ввод значания
n_prev = n
n = int(input())
while n > n_prev and n != 0:
# print('w+')
count_plus += 1
n_prev = n
n = int(input())
while n < n_prev and n != 0:
# print('w-')
count_minus += 1
n_prev = n
n = int(input())
if n > n_prev:
check_plus = 1
# запись результата
if count_plus >= count:
count = count_plus
if count_minus > count:
count = count_minus
print(count)
|
14ab832d029b836f0961f547ddd9173ce9d83119 | zotochev/VSHE | /week 05/tasks_05/05_10_fac.py | 110 | 3.53125 | 4 | n = int(input())
# n = 5
count = 1
le = 0
for x in range(1, n + 1):
count *= x
le += count
print(le)
|
c4f2ea03be514143bbc8425d4e2d7c8feb244df2 | zotochev/VSHE | /week 05/tasks_05/05_05_flag.py | 701 | 3.609375 | 4 | n = int(input())
# n = 5
my_flag = [('+___ '), ('|', ' / '), ('|__\ '), ('| ')]
# print(range(1, n))
for i in range(0, 4):
if i != 1:
for j in range(0, n):
print(*my_flag[i], sep='', end='')
else:
for j in range(0, n):
print(*my_flag[i][0], j + 1, my_flag[i][1], sep='', end='')
print()
# print('\n')
# print(my_flag[i + 1])
# print(my_flag[0])
# print(my_flag[1])
# print(my_flag[2])
# print(my_flag[3])
# print(*my_flag[6])
# for flag in my_flag:
# print my_flag[1]
# for i in my_flag:
# for j in range(1, n):
# print(my_flag[j])
# print()
# for color in ('red', 'green', 'yellow'):
# print(color, 'apple')
|
a24d97dfc86481d4c1b1efe5dfa596521ab2868d | zotochev/VSHE | /week 02/notes_02/notes_week_02_08_continue.py | 202 | 3.8125 | 4 | now = int(input())
sum_seq = now
while now != 0:
now = int(input())
sum_seq += now
print(sum_seq)
now = int(input())
while now != 0:
if now > 0:
print(now)
now = int(input())
|
682ea5cc15860f84a416469dbefa81c3d60ba54e | DariaMinieieva/sudoku_project | /crossword/crossword_backtracking/backtracking.py | 5,176 | 4.09375 | 4 | """This module implements backtracking algorithm to solve crossword."""
class CrosswordSolver:
"""Class for crossword solving representation."""
def __init__(self, matrix: 'Array2D', words=None):
"""Creates a new crossword solver."""
self.matrix = matrix
self.num_rows = self.matrix.num_rows()
self.num_cols = self.matrix.num_cols()
self.words = words
self.matrix_results = set()
self.possible_placements = []
def set_words(self, words: list):
"""Sets the words to be in the crossword from list."""
self.words = words
def place_words(self):
"""
Main function that implements backtracking algorithm to find
possible ways to solve the crossword. Uses recursive helper function.
"""
words = self.words.copy()
placements = self.place_possible()
def helper(ind, placements, matrix, words):
if ind < len(words):
for place in placements:
matrix_copy = matrix.copy()
curr_word = words[ind]
if place[2] >= len(curr_word) and place[3] == "f":
if place[0] == "h":
count = 0
for i in range(place[1][1], len(curr_word)+place[1][1]):
if matrix_copy[place[1][0], i] != "-" and \
matrix_copy[place[1][0], i] != curr_word[count]:
break
count += 1
else:
count = 0
for i in range(place[1][1], len(curr_word)+place[1][1]):
matrix_copy[place[1][0],
i] = curr_word[count]
count += 1
helper(ind+1, placements,
matrix_copy, words)
else:
count = 0
for i in range(place[1][0], len(curr_word)+place[1][0]):
if matrix_copy[i, place[1][1]] != "-" and \
matrix_copy[i, place[1][1]] != curr_word[count]:
break
count += 1
else:
count = 0
for i in range(place[1][0], len(curr_word)+place[1][0]):
matrix_copy[i, place[1][1]
] = curr_word[count]
count += 1
helper(ind+1, placements,
matrix_copy, words)
else:
self.matrix_results.add(CrosswordSolver(matrix))
helper(0, placements, self.matrix, words)
def place_possible(self):
"""Describes the crossword grid by finding free places
to set the words and returns them as a list."""
for i in range(self.num_rows):
cont_word = 0
ind_y = 0
for j in range(self.num_cols):
if self.matrix[i, j] == "-":
cont_word += 1
else:
if cont_word >= 3:
self.possible_placements.append(
["h", (i, ind_y), cont_word, "f"])
ind_y = j+1
cont_word = 0
if cont_word >= 3:
self.possible_placements.append(
["h", (i, ind_y), cont_word, "f"])
for i in range(self.num_cols):
cont_word = 0
ind_x = 0
for j in range(self.num_rows):
if self.matrix[j, i] == "-":
cont_word += 1
else:
if cont_word >= 3:
self.possible_placements.append(
["v", (ind_x, i), cont_word, "f"])
ind_x = j+1
cont_word = 0
if cont_word >= 3:
self.possible_placements.append(
["v", (ind_x, i), cont_word, "f"])
return self.possible_placements
def __str__(self):
"""Returns a string representation of a crossword."""
res = []
for i in range(self.num_rows):
temp = ""
for j in range(self.num_cols):
temp += self.matrix[i, j]
res.append(temp)
return "\n".join(res)
def __eq__(self, other):
"""Compares two crosswords and returns True if they are the same or False otherwise."""
for i in range(self.num_rows):
for j in range(self.num_cols):
if self.matrix[i, j] != other.matrix[i, j]:
return False
return True
def __hash__(self):
"""Returns a hashable object of crossword."""
return hash(str(self))
|
7aadcf9b4d857e5ec2481a2d940eb797245ace3c | Heilmittel/Himmel | /Python27/2016/03.py | 335 | 4 | 4 | import random
number = random.randint(1,55)
guess = int(raw_input("Enter an integer:"))
if guess == number :
print "Congratulations,you guessed it."
print "(But you do not win any prize!)"
elif guess < number :
print "No,it is a little higher than that."
else :
print "No,it is a little lower than that."
print "Done."
|
6304a7d474fa930d66888b031b2a07d21012b678 | YChanHuang/Learn_Python | /py4e_note.py | 396 | 3.859375 | 4 | x = list()
x.append('1')
dir(x)
print(x)
# split() function
string.split() # split a string into a list default on space
test_string = ' abc, so abc.split, and this returns a list'
test_list = test_string.split()
# test string as following example
# ['abc,', 'so', 'abc.split,', 'and', 'this', 'returns', 'a', 'list']
string.split(';') # split on specific character
|
047a5ee66cbf8c42a7677535ccbab44b5345f190 | medishettyabhishek/Abhishek | /Abhishek/Section 9/Section 9-1/Star meta Charcater.py | 148 | 3.65625 | 4 | #* is the important star metacharacter
import re
pattern = r"bread(eggs)*bread"
if re.match(pattern ,"breadeggsbread"):
print("macth found")
|
9abdcd0a0ffb12c4a719f24c355029ca504e03df | medishettyabhishek/Abhishek | /Abhishek/Section 9/Section 9-1/Regular Expression.py | 195 | 4.125 | 4 | import re
pattern = r"eggs"
if re.findall(pattern,"baconeggseggseggsbacon"):
print("match found")
else:
print("match not found")
print(re.findall(pattern,"baconeggseggseggsbacon"))
|
881d4baaeb0e626ca7607dd0ed38fd7e2cb93035 | ss6231/pyGames | /calendarApp.py | 3,841 | 4.5 | 4 |
# Asks user to enter date while program outputs whether that day is a holiday or a regular working day.
month = int(input("Enter an month as an integer from 1-12: ")) # input month
if (month>12) or (0>=month): # only 12 months
print ("Invalid input. Months are numbered from 1 to 12")
else:
date = int(input("Enter a date from 1-31: ")) # input date
if (date>31) or (0>=date): # no month has more than 31 days
print ("Invalid input. No month has more than 31 days/less than 0 days")
elif ((month==4) or (month==6) or (month==9) or (month==11)) and (date>30):
print ("Invalid input. Input month does not have more than 30 days")
# These months only have 30 days
elif (month==2) and (date>28): # Feb only has 28 days
print ("Invalid input. February only has 28 days")
elif (month==9) and (date==2): # Labor day
print ("September 9th is Labor Day")
elif (month==9) and ((1==date) or (2<date<30)): # No holidays in Sept
print ("September",date,"is not a holiday")
elif (month==10) and (date==15): # Fall break
print ("October",date,"is part of fall break")
elif (month==10) and (date==16):# Fall break and Eid
print ("October",date,"is part of fall break")
print ("October",date,"is also Eid ul Adha")
elif (month==10) and ((1<=date<15) or (16<date<=31)): # No holidays in Oct
print ("October",date,"is not a holiday")
elif (month==11) and (28<=date<=29): # Thanksgiving break
print ("November",date,"is part of Thanksgiving break")
elif (month==11) and (1<=date<28 or date==30): # No holidays in Nov
print ("November",date,"is not a holiday")
elif (month==12) and (21<=date<=31): # Winter break
print ("December",date,"is part of winter recess")
elif (month==12) and (1<=date<21): # No holidays in Dec
print ("December",date, "is not a holiday")
elif (month==1) and ((1<=date<20) or (20<date<=26)): # Winter break in Jan
print("January",date,"is part of winter recess")
elif (month==1) and (date==20): # Winter break and MLK day
print ("January",date,"is part of winter recess")
print ("January",date,"is also Martin Luter King Day")
elif (month==1) and (26<date<=31): # No holidays in Jan
print ("January",date,"is not part of a holiday")
elif (month==2) and (date==17): # President's day and my bday
print ("February",date,"is President's day")
print ("February",date,"is also Sana's birthday")
elif (month==2) and ((1<=date<17) or (17<date<=28)): # No holidays in Feb
print ("February",date,"is not a holiday")
elif (month==3) and (17<=date<=23): # Spring break
print ("March",date,"is part of spring break")
elif (month==3) and ((1<=date<17) or (23<date<=31)): # No holidays in Mar
print ("March",date,"is not part of a holiday")
elif (month==4) and (1<=date<=30): # No holidays in April
print ("April",date,"is not part of a holiday")
elif (month==5) and (date==28): # Memorial day
print ("May",date,"is Memorial Day")
elif (month==5) and (date!=28): # No holidays in May
print ("May",date,"is not part of a holiday")
elif (month==6) and (date==29): # First day of Ramadan
print ("June",date, "is the first day of Ramadan")
elif (month==6) and (date!=29): # No holidays in June
print ("June",date,"is not part of a holiday")
elif (month==7) and (date==4): # Independence day
print ("July",date,"is Independence Day")
elif (month==7) and ((1<=date<4) or (4<date<28) or (28<date<=31)):
print ("July",date,"is not part of a holiday") # No holidays in July
elif (month==8) and (1<=date<=31): # No holidays in Aug
print ("August",date,"is not part of a holiday")
|
59edb404aaa2da4d555033041c589bcdcf390a90 | JazzyJas0911/IEEE754_FloatingPoint | /Assn13.py | 2,161 | 3.9375 | 4 | import struct
def convertFloat (number):
#using the struct library interpret a string as packed binary data. allowing me to manipulate the bits
num = struct.unpack('I', struct.pack('f', number))[0]
#gets sign bit 31
signBit = (num & 0x80000000) >> 31
#gets exponent bits 30-23
exponentBits = (num & 0x7f800000) >> 23
#gets mantissa bits 22-0
mantissaBits = (num & 0x007fffff)
#returns the float in the correct format
return '(' + str(signBit) + "," + str(exponentBits) + "," + str(mantissaBits) + ')'
def nextFloat (number):
#formatting the number
num = struct.unpack('I', struct.pack('f', number))[0]
#incrementing num to the next number
nextNum = num + 1
# returning the incremented formatted number
return (struct.unpack('f', struct.pack('I', nextNum)))[0]
def countBetween (lower, upper):
#reading in both numbers in the correct formatting and subtracting them
theLowerValue = struct.unpack('I', struct.pack('f', lower))[0]
theUpperValue = struct.unpack('I', struct.pack('f', upper))[0]
return (theUpperValue - theLowerValue)
def main():
#given main statements
#part 1
print("i. Floating point number converter.")
pi = 3.14159265358979
print("3.14159 -> ", convertFloat(pi))
#part 2
print("\nii. Floating point number enumeration.")
fp = 0.0
i = 0
while fp < 1.4E-44:
#must calculate these before hand to use the str() method in order for an out of bounds to not be thrown
fp = nextFloat(fp)
i = i + 1
print (str(i), "th number: ", str(fp))
#part 3
print("\niii. Floating point number counting")
#max value store in a float
posFPs = countBetween(0.0, 3.4028235E38)
zeroOneFPs = countBetween(0.0, 1.0)
print("Number of positive floating point numbers:", str(posFPs))
print("Number of floating point numbers between 0 and 1:", str(zeroOneFPs))
print("Proportion (# of 0~1) / (# of positive):", str(float(zeroOneFPs) / float(posFPs) * 100.0), "%")
main() |
3039f34b6133a21332e579974006582c13942aa4 | christopherwj/compe560 | /testTwo/shortest_distance_dij.py | 1,539 | 3.953125 | 4 | from queue import PriorityQueue
class Graph:
def __init__(self, num_of_vertices):
self.v = num_of_vertices
self.edges = [[-1 for i in range(num_of_vertices)] for j in range(num_of_vertices)]
self.visited = []
def add_edge(self, u, v, weight):
self.edges[u][v] = weight
self.edges[v][u] = weight
def dijkstra(self, start_vertex):
D = {v:float('inf') for v in range(self.v)}
D[start_vertex] = 0
pq = PriorityQueue()
pq.put((2, start_vertex))
while not pq.empty():
(dist, current_vertex) = pq.get()
self.visited.append(current_vertex)
for neighbor in range(self.v):
if self.edges[current_vertex][neighbor] != -1:
distance = self.edges[current_vertex][neighbor]
if neighbor not in self.visited:
old_cost = D[neighbor]
new_cost = D[current_vertex] + distance
if new_cost < old_cost:
pq.put((new_cost, neighbor))
D[neighbor] = new_cost
return D
g = Graph(9)
g.add_edge(2,1,3)
g.add_edge(2,8,2)
g.add_edge(1,4,1)
g.add_edge(1,3,2)
g.add_edge(3,5,1)
g.add_edge(5,4,4)
g.add_edge(4,6,5)
g.add_edge(4,8,1)
g.add_edge(8,7,4)
g.add_edge(7,6,3)
##vertexes
#A=1
#B=2
#C=3
#so forth and so on
D = g.dijkstra(7)
for vertex in range(len(D)):
print("Distance from starting vertex to ending vertex:", vertex, "is", D[vertex])
|
999b197b98ada31bd27936eb2cc4f71dcee49113 | heyhello89/openbigdata | /03_Data Science/1. Collection/1. CSV Handle/csv_practice.py | 4,817 | 3.515625 | 4 | import csv, math
def get_cvs_colInstance(access_key):
col_instance=[]
col_index=data[0].index(access_key)
for row in data[1:]:
col_instance.append(row[col_index])
return col_instance
def type(access_key): # 예외처리를 통하여 보다 범용적으로 바꿔볼것
if access_key[0:5]=='COUNT':
type='int'
elif access_key[0:7]=="PERCENT":
type='float'
return type
def get_cvs_rowInstance(access_key):
for row in data[:]:
if row[0]==access_key:
for row_element in row:
print(row_element, end=' ')
print("\n")
def map_row(col_instance, type):
if type=="int":
col_instance=list(map(int, col_instance))
elif type=="float":
col_instance=list(map(float, col_instance))
return col_instance
def print_row(col_instance):
for row_element in col_instance:
print(row_element)
def sum(col_instance):
sum=0
for row_element in col_instance:
sum+=row_element
return sum
def avg(col_instance):
avg=sum(col_instance)/len(col_instance)
return avg
def maximum(col_instance):
maximum=col_instance[0]
for row_element in col_instance:
if maximum < row_element:
maximum = row_element
return maximum
def minimum(col_instance):
minimum=col_instance[0]
for row_element in col_instance:
if minimum > row_element:
minimum = row_element
return minimum
def deviation(col_instance):
deviation=[]
for row_element in col_instance:
deviation.append(row_element-avg(col_instance))
return deviation
def variance(col_instance):
sum=0
for dev_element in deviation(col_instance):
sum+=dev_element*dev_element
variance=sum/len(deviation(col_instance))
return variance
def standard_deviation(col_instance):
standard_deviation=math.sqrt(variance(col_instance))
return standard_deviation
def ascend(col_instance):
ascend=sorted(col_instance)
for asc in ascend:
print(asc)
def descend(col_instance):
descend=reversed(sorted((col_instance)))
for desc in descend:
print(desc)
with open('Demographic_Statistics_By_Zip_Code.csv', newline='') as infile:
data=list(csv.reader(infile))
while True:
input_num=input("0.종료 1.행 2.열 3.총합 4.평균 5.최대값 6.최소값 7.편차 8.분산 9.표준편차 10.오름차순 정렬 11.내림차순 정렬\n메뉴를 선택하세요: ")
if input_num=='0': #0인 조건을 따로 분리하는 것을 추천
break
else:
access_key=input("Access Key를 입력하세요: ")
if input_num=='1':
get_cvs_rowInstance(access_key)
elif input_num=='2':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print()
elif input_num=='3':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print("총합: "+str(sum(map_row(get_cvs_colInstance(access_key),type(access_key))))+"\n")
elif input_num=='4':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print("평균: "+str(avg(map_row(get_cvs_colInstance(access_key),type(access_key))))+"\n")
elif input_num=='5':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print("최대값: "+str(maximum(map_row(get_cvs_colInstance(access_key),type(access_key))))+"\n")
elif input_num=='6':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print("최소값: "+str(minimum(map_row(get_cvs_colInstance(access_key),type(access_key))))+"\n")
elif input_num=='7':
for row in range(0,len(map_row(get_cvs_colInstance(access_key),type(access_key)))):
print(str(map_row(get_cvs_colInstance(access_key),type(access_key))[row])+" \t\t"+str(deviation(map_row(get_cvs_colInstance(access_key),type(access_key)))[row]))
print("편차 = 표본 - 평균\n")
elif input_num=='8':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print("분산 (공식: (∑(표본-평균)^2)/표본수): "+str(variance(map_row(get_cvs_colInstance(access_key),type(access_key))))+"\n")
elif input_num=='9':
print_row(map_row(get_cvs_colInstance(access_key),type(access_key)))
print("표준편차 (공식: √분산): "+str(standard_deviation(map_row(get_cvs_colInstance(access_key),type(access_key))))+"\n")
elif input_num=='10':
ascend(map_row(get_cvs_colInstance(access_key),type(access_key))+"\n")
elif input_num=='11':
descend(map_row(get_cvs_colInstance(access_key),type(access_key))+"\n") |
e8b87943e39a6d8d62ec64f517517612b49ab321 | heyhello89/openbigdata | /01_jumptopy/chap05/practice/sum_except.py | 587 | 3.6875 | 4 | def sum(a, b):
return print(a+b)
while True:
num=input("안녕하세요 두 수를 입력하세요. (종료: 프로그램 종료) : ")
if num=="종료":
break
try:
a=int(num.split()[0])
except ValueError:
a=num.split()[0]
a=int(input("죄송합니다. 첫번째 입력이 [%s]입니다. 숫자를 입력하세요. : "%a))
try:
b=int(num.split()[1])
except ValueError:
b=num.split()[1]
b=int(input("죄송합니다. 두번째 입력이 [%s]입니다. 숫자를 입력하세요. : "%b))
sum(a, b)
|
7722ba989d25df43052f42321b6c7062c62398af | heyhello89/openbigdata | /01_jumptopy/chap04/practice/visitor_2.py | 730 | 3.71875 | 4 | name=input("이름을 입력하세요.: ")
a=1
f=open('방명록.txt', 'r', encoding='UTF8')
visitor = f.readlines()
def insert_birth(a):
if a==1:
birth = input("생년월일을 입력하세요 (예:801212):")
print(name + "님 환영합니다. 아래 내용을 입력하셨습니다.\n" + name + " " + birth)
with open('방명록.txt', 'a', encoding='UTF8') as f:
f.writelines(name + " " + birth + "\n")
def search_visitor(name):
for i in visitor:
if name==i[:3]:
print(name+"님 다시 방문해 주셔서 감사합니다. 즐거운 시간되세요.")
global a
a=0
if not visitor:
insert_birth(a)
search_visitor(name)
insert_birth(a) |
95f50ba39e115aa3a9b208267e25f8604ba931ad | heyhello89/openbigdata | /01_jumptopy/chap05/230_try_except_type3.py | 498 | 3.703125 | 4 | num1, num2 = input("두개의 숫자를 입력하세요.").split()
is_calculate=True
try:
f = open('나없는 파일','r')
result = int(num1)/int(num2)
except FileNotFoundError:
print("파일이존재하지 않습니다.")
print("System Error Message"+str(e))
is_calculate=False
except ZeroDivisionError:
print("연산을 할 수 없습니다.")
print("System Error Message: "+str(e))
is_calculate=False
if is_calculate:
print("%s/%s=%s"%(num1,num2,result))
|
fdc377bf57149c28f1d45c59462c368a748222b9 | heyhello89/openbigdata | /01_jumptopy/chap02/True_False_type.py | 983 | 4.03125 | 4 | # coding: cp949
my_str="̽"
# my_str=" "
my_list=[1,2,3]
# my_list=[]
my_tuple=(1,2,3)
# my_tuple=()
my_dic={"߹̾":"Ҿ ִ","ö":"ٸ ̷"}
# my_dic={}
my_num=100
# my_num=0
print("1] ڿ(String) Ÿ True/False")
if my_str:
print("True")
else:
print("False")
print("\n2] Ʈ(List) Ÿ True/False")
print("my_list: ",end='')
print(my_list)
if my_list:
print("True")
else:
print("False")
print("\n3] Ʃ(Tuple) Ÿ True/False")
print("my_tuple: ",end='')
print(my_tuple)
if my_tuple:
print("True")
else:
print("False")
print("\n4] ųʸ(Dictionary) Ÿ True/False")
print("my_dic: ",end='')
print(my_dic)
if my_dic:
print("True")
else:
print("False")
print("\n5] (Integer) Ÿ True/False")
print("my_num: ",end='')
print(my_num)
if my_num:
print("True")
else:
print("False")
print("\nα ")
|
2e11462c1860ae4958eda578555663d5e4ae1d52 | heyhello89/openbigdata | /01_jumptopy/chap06/practice/2_multiple.py | 1,360 | 3.890625 | 4 | def print_num(ans):
for i in ans:
if i==ans[-1]:
print(str(i)+" ",end="")
else:
print(str(i)+", ",end="")
def multiple(a, b):
ans=[]
for count in range(1, (int(a)//int(b))+1):
result=int(b)*count
ans.append(result)
return ans
def set_mul(a, b, c):
list_mul=[]
list_mul.extend(multiple(a, b))
list_mul.extend(multiple(a, c))
set_mul=set(list_mul)
mul=list(set_mul)
return mul
def sum(mul):
result=0
for num in mul:
result+=num
print(result, end="")
input_num=input("범위, 첫 번째 수, 두 번째 수를 입력하세요. (종료: 프로그램 종료): ").split()
print("0 부터"+input_num[0],"이하의 범위를 선택하셨습니다. 이 중에서")
print(input_num[1]+"의 배수는 ", end="")
print_num(multiple(input_num[0], input_num[1]))
print("입니다.")
print(input_num[2]+"의 배수는 ", end="")
print_num(multiple(input_num[0], input_num[2]))
print("입니다.")
print(input_num[1]+"과 "+input_num[2]+"의 배수는 ", end="")
print_num(set_mul(input_num[0], input_num[1], input_num[2]))
print("입니다.")
print("따라서 0부터 "+input_num[0]+"이하의 범위내에서 "+input_num[1]+"과 "+input_num[2]+"배수의 총합은 ", end="")
sum(set_mul(input_num[0], input_num[1], input_num[2]))
print("입니다.") |
2e1785ec7697bba4c1b0711bb9cca8fa0138aa9d | heyhello89/openbigdata | /01_jumptopy/chap04/142.py | 391 | 3.8125 | 4 | def my_sum(num1,num2):
print("덧셈 연산")
internal_result = num1 + num2
if internal_result > 0:
print("연산 결과가 양수로 분석됩니다.")
elif internal_result ==0:
print("연산 결과가 양수로 분석됩니다.")
else:
return num1+num2
result=my_sum(1,2)
print("최종 연산 결과: ",result)
print("계산기 ver1.0 종료") |
a8e03c84a5af22a421a2d5cc320eb101ef3cd178 | heyhello89/openbigdata | /01_jumptopy/chap04/147_sum_many.py | 177 | 3.609375 | 4 | def sum_many(*args):
sum=0
for i in args:
sum=sum+i
return sum
result = sum_many(1,2,3)
print(result)
result=sum_many(1,2,3,4,5,6,7,8,9,10)
print(result) |
ca8c9a39cf2df9cdf9818c9842eaed27eb4f352b | lilia-k/Project | /toyrobot.py | 2,920 | 3.953125 | 4 | ##############
# Created on 12/12/2017
# Version 001: Modified on 12/12/2017 by xxxxx
# This is an application which enables the movement of a toy robot based on a set of action commands
# These action commands are contained in a file, and should be placed in the folder C:\Python\input.txt
###############
# List of valid moves
VALID_MOVES = ["NORTH",
"SOUTH",
"EAST",
"WEST",
"PLACE",
"MOVE","LEFT","RIGHT","REPORT"]
# Place action
PLACE=["PLACE"]
# Possible rotation actions
ROTATION_MOVE =["LEFT","RIGHT"]
# Create dictionary of actions to determine function for an action
# Key value lookup is the starting facing direction
# [0] entry is the step movement for valid move 'MOVES'
# [1] entry is result for valid move 'LEFT'
# [2] entry is result for valid move 'RIGHT'
ACTIONS = {'NORTH' : (lambda x, y: (x, y + 1), "WEST", "EAST"),
'EAST' : (lambda x, y: (x + 1, y), "NORTH", "SOUTH"),
'SOUTH' : (lambda x, y: (x, y - 1), "EAST", "WEST"),
'WEST' : (lambda x, y: (x - 1, y), "SOUTH", "NORTH")}
# set default for x,y,f
x=-99.99
y=-99.99
direction='NORTH'
# Create class function to determine outcome of action
class ToyRobot(object):
def __init__(self,x,y,direction,move):
self.direction = direction
self.x = x
self.y = y
self.move=move
# define board limits
def valid_position(self):
# Limit here has been hardcoded for simplicty, but can be easily changed to be variable driven
if 5 > x >= 0 and 5 > y >= 0:
return True
else:
return False
# define 'MOVE' action function
def movement(self):
move_func = ACTIONS[self.direction][0]
new_pos =move_func(self.x,self.y)
self.x=new_pos[0]
self.y=new_pos[1]
return new_pos
# define 'LEFT' action function
def left(self):
if self.move =='LEFT':
new_direct = ACTIONS[self.direction][1]
self.direction = new_direct
return new_direct
# define 'RIGHT' action function
def right(self):
if self.move =='RIGHT':
new_direct = ACTIONS[self.direction][2]
self.direction = new_direct
return new_direct
# define output of action
def report(self):
if self.move =='MOVE':
self.movement()
if self.move =='LEFT':
self.left()
if self.move =='RIGHT':
self.right()
return (self.x,self.y , self.direction)
# open input file
# loop each line of the input file and perform action
# Check valid move
# if action is a 'PLACE' movement, define the x and y position
# if action is a 'PLACE' movement, define the x and y position
# execute action commands |
272e273e15b0df254e2ab8295924c6ed091eb894 | ian-gallmeister/python_utils | /append_to_file.py | 1,319 | 3.5 | 4 | #!/usr/bin/env python
#Assumed encoding is utf-8
#If text uses a different one, please specify
#encode -> bytes
#decode -> specified encoding
import sys
#python2 - turn into bytes, write
#python3 - write as encoding
def append_to_file( name, text, encoding='utf-8' ):
version = sys.version_info[0]
if version == 2 and isinstance(text, str):
open( name, 'ab' ).write( text ) #Is bytes already
elif version == 2 and isinstance(text, unicode):
open( name, 'ab' ).write( text.encode(encoding) ) #Turn to bytes
elif version != 2:
open( name, 'a', encoding=encoding ).write( text )
return True
def write_file2( name, lines, encoding='utf-8' ): #This one takes a list
version = sys.version_info[0]
if os.name == 'nt':
text = '\r\n'.join( lines )
elif os.name == 'posix':
text = '\n'.join( lines )
else:
print( 'Unexpected OS. To fix, please\nadd the output of os.name to\na new elif: statement' )
print( 'Exiting ...' )
exit( 1 )
version = sys.version_info[0]
if version == 2 and isinstance(text, str):
open( name, 'ab' ).write( text ) #Is bytes already
elif version == 2 and isinstance(text, unicode):
open( name, 'ab' ).write( text.encode(encoding) ) #Turn to bytes
elif version != 2:
open( name, 'a', encoding=encoding ).write( text )
return True
|
2d366a66a851d016563b27ffbddfd1f0a3d753ae | ajit116/DrAiveX | /excel_Pandas.py | 1,420 | 3.6875 | 4 | import pandas as pd
import excel
var1=pd.read_excel("C:\\Users\\DELL\\Desktop\\dataset.xlsx",0)
var2=pd.read_excel("C:\\Users\\DELL\\Desktop\\dataset.xlsx",0)
CE_ME=0 #Number of civil and mechanical students
l1=var1.describe()
l2=var2.describe()
req=0
#var1 is the original sheet and var2 is the final sheet after applying all constraint
for i in range(l2.Name[0]):
if(var2["Year"][i]>=str("3rd")):
#Accessing name and email in separate variables
name=var2["Name"][i]
mail=var2["Email"][i]
firstName=name.split(' ')[0]
lastName=name.split(' ')[1]
#Now removing all the 3rd and 4th year students whose first or last name matches with email id.
if firstName.lower() in mail:
var2.drop([i],axis= 0, inplace=True)
elif lastName.lower() in mail:
var2.drop([i],axis= 0, inplace=True)
#rearranging the sheet after the deletion of row, (reindexing)
var2=var2.reset_index(drop=True)
l2=var2.describe()
for i in range(l2.Department[0]):
if(var2["Department"][i]=='CE'):
CE_ME=CE_ME+1
continue
if(var2["Department"][i]=='ME'):
CE_ME=CE_ME+1
continue
# 10% of the attending student(req)
req=l2.Name[0]*(0.1)
#applying the constraints
if(l2.Name[0]>30):
if(CE_ME>=req):
print("DrAiveX will EXIST")
else:
print("DrAiveX will not EXIST")
else:
print("DrAiveX will not EXIST")
|
9c2085df70fce10bc3d049be9a8b7c6b5169fcf5 | jaebooker/2C-2S | /challenge/three.py | 2,064 | 4 | 4 | from two import *
"""place everything in iterable sets,
check if already visted,
traversing call recursively, getting as far away from node before visting"""
def dfs_r(nodes, node, visited=None):
if visited == None:
visited = set()
visited.add(node)
for i in nodes.node_dict[node] - visited:
dfs(nodes, i, visited)
return visited
"""place everything in iterable sets,
check if already visted, add to stack
traversing while stack is not empty, getting as far away from node before visting"""
def dfs_i(nodes, node):
visited, stack = set(), [node]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(nodes.node_dict[vertex]-visited)
return visited
"""Inspiration for code thanks to LOFAR788"""
def dijkstra_x(graph,start,goal):
shortest_distance = {}
predecessor = {}
unseenNodes = graph
infinity = 9999999
path = []
for node in unseenNodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
while unseenNodes:
minNode = None
for node in unseenNodes:
if minNode is None:
minNode = node
elif shortest_distance[node] < shortest_distance[minNode]:
minNode = node
for childNode, weight in graph[minNode].items():
if weight + shortest_distance[minNode] < shortest_distance[childNode]:
shortest_distance[childNode] = weight + shortest_distance[minNode]
predecessor[childNode] = minNode
unseenNodes.pop(minNode)
currentNode = goal
while currentNode != start:
try:
path.insert(0,currentNode)
currentNode = predecessor[currentNode]
except KeyError:
print('Path not reachable')
break
path.insert(0,start)
if shortest_distance[goal] != infinity:
print('Shortest distance is ' + str(shortest_distance[goal]))
print('And the path is ' + str(path))
|
b702815ac61cc728566eba1e4c1463e0fcec3143 | KenMunk/csc131-hw3 | /code/participants.py | 506 | 3.828125 | 4 | # Welcome to Coding using Git! We all have to edit this same file.
# Update the students list with your name in alphabetical order by first name.
# Example: students = ['Fiz Ban', 'Foo bar']
students = []
professor = ['Gary Kane']
course = ['CSC 131']
print("%s's %s is the best!" % (professor[0], course[0]))
print("Students: %s" % ', '.join(map(str, students)))
# Run the program and make sure it works!
# You can use a simple online IDE if you don't have a Python3
# Example: https://ideone.com/l/python-3 |
972787571305981557fa4a34a38ee9b9d3f9da40 | pubudu08/algorithms | /security/salt_hashing_passwords.py | 1,191 | 3.90625 | 4 | import uuid, hashlib
"""
you can get slightly more efficient storage in your database by storing the salt and hashed password as raw bytes
rather than hex strings. To do so, replace hex with bytes and hexdigest with digest.
how do you reverse it to get the password back?
You don't reverse it, you never reverse a password. That's why we hash it and we don't encrypt it.
If you need to compare an input password with a stored password, you hash the input and compare the hashes.
If you encrypt a password anyone with the key can decrypt it and see it. It's not safe
Salts are not considered secret. You store them alongside the username and password hash.
See here for a fantastic explanation about password hashing in general.
https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords/31846#31846
resources
http://stackoverflow.com/questions/536584/non-random-salt-for-password-hashes/536756#536756
"""
password = "test_password"
salt = uuid.uuid4().hex
# For this to work in Python 3 you'll need to UTF-8 encode
hashed_password = hashlib.sha512(password.encode('utf-8') + salt.encode('utf-8')).hexdigest()
print(hashed_password)
|
f47f382687ee2b7da8147a7a4423cbc8180dbebd | misrayazgan/METU-CENG-Coursework | /Ceng435 - Data Communications and Networking/Term Project - Part1/b.py | 1,980 | 3.5 | 4 | ip = "10.10.1.2" # ip address of the b-interface for receiving a message from s
ip_r1 = "10.10.2.2" # ip address of the next hop(r1)
ip_r2 = "10.10.4.2" # ip address of the next hop(r2)
port = 12346
chunk_size = 39 # To send the messages in chunks of 39 bytes
import socket
import threading
import sys
from datetime import datetime
# Receives messages from s, sends them to the next hop address (r1 or r2)
# in an alternating way by using the turn variable
def receiveMsg(client, sockbr1, sockbr2, turn):
received_message = client.recv(chunk_size) # received_message contains the data sent from s
if received_message:
print "Msg is received, forwarding: ", received_message
if turn % 2 == 0:
sockbr2.sendto(received_message, (ip_r2, port)) # Directly send the data to the next hop(r2)
else:
sockbr1.sendto(received_message, (ip_r1,port)) # Directly send the data to the next hop(r1)
# Create TCP socket for receiving messages from s
# Create UDP socket to send the messages to the next hop address
def connection():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create TCP socket for receiving the message from s
sock.bind((ip, port)) # Bind to s
sockbr1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create UDP socket for sending the message to r1
sockbr2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create UDP socket for sending the message to r2
sock.listen(4)
turn = 0 # When this number is even, send to r2
# When odd, send to r1
while True:
client, address = sock.accept() # Accept the TCP connection request from s
receiveMsg(client, sockbr1, sockbr2, turn)
turn += 1
if __name__ == "__main__":
connection()
|
03d9fdd8afb04824150ea95bd1d913de71b0609e | ttopac/AeroSandbox | /aerosandbox/tools/string_formatting.py | 1,515 | 3.671875 | 4 | import math
import aerosandbox.numpy as np
import hashlib
def eng_string(x: float, format='%.3g', si=True):
'''
Taken from: https://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6/40691220
Returns float/int value <x> formatted in a simplified engineering format -
using an exponent that is a multiple of 3.
format: printf-style string used to format the value before the exponent.
si: if true, use SI suffix for exponent, e.g. k instead of e3, n instead of
e-9 etc.
E.g. with format='%.2f':
1.23e-08 -> 12.30e-9
123 -> 123.00
1230.0 -> 1.23e3
-1230000.0 -> -1.23e6
and with si=True:
1230.0 -> 1.23k
-1230000.0 -> -1.23M
'''
sign = ''
if x < 0:
x = -x
sign = '-'
exp = int(math.floor(math.log10(x)))
exp3 = exp - (exp % 3)
x3 = x / (10 ** exp3)
if si and exp3 >= -24 and exp3 <= 24 and exp3 != 0:
exp3_text = 'yzafpnum kMGTPEZY'[(exp3 + 24) // 3]
elif exp3 == 0:
exp3_text = ''
else:
exp3_text = 'e%s' % exp3
return ('%s' + format + '%s') % (sign, x3, exp3_text)
def hash_string(string: str) -> int:
"""
Hashes a string into a quasi-random 32-bit integer! (Based on an MD5 checksum algorithm.)
"""
md5 = hashlib.md5(string.encode('utf-8'))
hash_hex = md5.hexdigest()
hash_int = int(hash_hex, 16)
hash_int64 = hash_int % (2 ** 32)
return hash_int64
|
1242ada6bfcdafe60fb55fba6777a93a75019bb6 | gustavomello9600/projeto_euler | /python/problem10.py | 423 | 3.6875 | 4 | from itertools import cycle
relevant_primes = [3, 7, 11, 13, 17, 19]
def is_prime(n):
for p in relevant_primes:
if n % p == 0:
return False
return True
p = 21
steps = cycle([2, 4, 2, 2])
soma = sum(relevant_primes) + 7
while p < 2_000_000:
if is_prime(p):
relevant_primes.append(p)
soma += p
p += next(steps)
print(f"Sum of all primes up to 2,000,000 is: {soma}")
|
576beb85deb3f37430eb6da9b57d8908ef157fe2 | theDreamer911/10dayspython | /VI/handle.py | 306 | 4.09375 | 4 | try:
age = int(input('Age: '))
if age > 1:
print(f"You are {age} years old")
elif age == 1 or age == 0:
print(f"You are {age} year old")
else:
print(f"You input {age}, age invalid")
except ValueError:
print('You put an invalid age')
print('Execution continues')
|
fa3c3d50712dc715eed01d03362ba25b3fab2e3f | theDreamer911/10dayspython | /VI/app.py | 194 | 3.890625 | 4 |
age = int(input('Age: '))
numbers = [*range(18, 40, 2)]
if age in numbers:
print(f"Your age is {age}, you're allowed here")
else:
print(f"Your age is {age}, you're not allowed here")
|
eb2686085823bbf3612d49155cb69de2fc37e6f8 | theDreamer911/10dayspython | /VII/properties.py | 776 | 3.859375 | 4 | # class Product:
# def __init__(self, price):
# # self.set_price(price)
# self.price = price
# @property
# def price(self):
# return self.__price
# # @price.setter
# # def price(self, value):
# # if value < 0:
# # raise ValueError('Price cannot be negative')
# # self.__price = value
# # price = property(get_price, set_price)
# product = Product(10)
# # product.price(-1)
# product.price = 2
# print(product.price)
def noon_meal(
opening, dessert): return f"Food: {opening.title()} {dessert.title()}"
print(noon_meal('Ice cream', 'Chocolate'))
print(noon_meal)
def the_meal(
food, drink): return f"I have eat {food.title()} and {drink.title()}"
the_meal('Soup', 'Oxygen Water')
|
efd0231107a64e5e0b75741280c1f5682f8fc190 | theDreamer911/10dayspython | /VIII/regex.py | 411 | 3.921875 | 4 | import re
TraceStudent = '''
Agung is 175cm and Adenta is 171cm
Aljevon is 172cm and Agra is 165cm
'''
tall = re.findall(r'\d{1,3}', TraceStudent) # d{1,3} mengambil 3 angka
names = re.findall(r'[A-Z][a-z]*', TraceStudent)
# [A-Z][a-z] mengambil karakter yang mengandung huruf besar dan kecil
tallDict = {}
x = 0
for eachname in names:
tallDict[eachname] = tall[x]
x += 1
print(tallDict)
|
61d6a9cd835dbd3b99d9df77476f44a6f674d19d | Lotoh/The-Lost-Forest | /menu.py | 4,353 | 3.640625 | 4 | import world
import sys
import setup
import os
import colour
from tkinter import *
root = Tk()
Console = Text(root)
Console.pack()
def write(*message, end = "\n", sep = " "):
text = ""
for item in message:
text += "{}".format(item)
text += sep
text += end
Console.insert(INSERT, text)
root.mainloop()
def main_menu_options():#menu choices
option = input("> ")
if option.lower() == ("new"):
setup.game_setup() # begin new game
elif option.lower() == ('load'):
world.load_game() # load saved game
elif option.lower() == ('help'):
main_menu_help() #show help menu
elif option.lower() == ('quit'):
os.system('cls') # clear terminal
sys.exit() # exit program
while option.lower() not in ['new', 'load', 'help', 'quit']: #catch invalid input
print(f"{colour.red}Invalid command!{colour.end}")
option = input(f"> ")
if option.lower() == ("new"):
setup.game_setup()
elif option.lower() == ('load'):
world.load_game()
elif option.lower() == ('help'):
main_menu_help()
elif option.lower() == ('quit'):
os.system('cls')
sys.exit()
def main_menu():#show main menu
print("")
print("Welcome to...")
print("")
print(f"{colour.purple}{colour.bold} The Lost Forest{colour.end}")
print("")
print(f" -- {colour.blue}{colour.bold}new{colour.end} -- ")
print(f" -- {colour.blue}{colour.bold}load{colour.end} -- ")
print(f" -- {colour.blue}{colour.bold}help{colour.end} -- ")
print(f" -- {colour.blue}{colour.bold}quit{colour.end} -- ")
print("")
print("# Type your command and press Enter! #")
main_menu_options()
def main_menu_help():# help menu
os.system('cls')
print("")
print(f" --- {colour.purple}{colour.bold}Help{colour.end} --- ")
print("")
print("Follow the instructions on screen!")
print("")
print(f"Pick from the list of given {colour.blue}commands{colour.end}. Type the {colour.blue}command{colour.end} and then press enter to execute!")
print("")
print(f"E.g. To navigate the world, type {colour.blue}move{colour.end} and press enter. Then type '{colour.blue}north{colour.end}', '{colour.blue}south{colour.end}', '{colour.blue}west{colour.end}' or '{colour.blue}east{colour.end}' as prompted and press enter. You will then move in that direction to a new location. You can only move when the option is given")
print("")
print("A grid map will show your current position. You are the 'x'")
print("")
print(f"Use the '{colour.blue}search{colour.end}' command to find items and add them to you inventory!")
print("")
print(f"Choose the '{colour.blue}use{colour.end}' command to use an item that is in your inventory. Some items do different things depending on your situation...")
print("")
print(f"Use '{colour.blue}save{colour.end}' to store your character and game state.")
print("")
print(f"Your save games can be loaded from the main menu by selecting '{colour.blue}load{colour.end}' and typing the name of the character whose game you want to load")
print("")
print("Good luck!")
print("")
print("# Type your command and press Enter! #")
print("")
option = input(f" -- Please type '{colour.blue}new{colour.end}' to start a new game, '{colour.blue}load{colour.end}' to load an existing game, or '{colour.blue}back{colour.end}' to return to the main menu --\n \n> ")
print("")
if option.lower() == ("new"):
setup.game_setup() # begin new game
elif option.lower() == ('load'):
world.load_game() # load saved game
elif option.lower() == ('back'):
os.system('cls') # clear terminal
main_menu() # back to main menu
while option.lower() not in ['new', 'load', 'back']: #catch invalid input
print(f"{colour.red}Invalid command!{colour.end}")
option = input(f"> ")
if option.lower() == ("new"):
setup.game_setup()
elif option.lower() == ('load'):
world.load_game()
elif option.lower() == ('back'):
os.system('cls')
main_menu()
|
2a193af76f5592ed5ebd8811fd5bb71b28ff23e4 | chrngb/Machine-Learning | /Polynomial Regression/PoR.py | 1,018 | 3.71875 | 4 | #Polynomial Regression
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
data = pd.read_csv(r"C:\Users\Rising IT\PycharmProjects\Pos_Salaries.csv")
#print(data)
x = data.iloc[:,1:2].values #if only 1 written then it is vector not matrix
y = data.iloc[:,2].values
#x = x.reshape(-1,1)
#y = y.reshape(-1,1)
#print(y)
lin = LinearRegression()
lin.fit(x,y)
pol = PolynomialFeatures(degree = 5) #default value 2, change to fit the values, 5 seemed to fit
x_pol = pol.fit_transform(x)
#print(x_pol)
pol.fit(x_pol,y)
lin2 = LinearRegression()
lin2.fit(x_pol,y)
pred_y = lin2.predict(x_pol)
pred_y1 = lin.predict(x)
plt.scatter(x,y)
plt.plot(x,pred_y)
#plt.show()
#print(pred_y[6])
print(lin2.predict(pol.fit_transform([[6.5]])))
print(lin.predict([[6.5]]))
#print(pred_y(6.5))
#print(lin2.predict(pol.fit_transform(6)))
#no test train split as the dataset is very small |
421a3a05798ec7bfdfd104994e220ffb9f2613f7 | Tornike-Skhulukhia/IBSU_Masters_Files | /code_files/__PYTHON__/lecture_2/two.py | 1,401 | 4.1875 | 4 |
def are_on_same_side(check_p_1, check_p_2, point_1, point_2):
'''
returns True, if check points are on the same side of a line
formed by connecting point_1 and point_2
arguments:
1. check_p_1 - tuple with x and y coordinates of check point 1
2. check_p_2 - tuple with x and y coordinates of check point 2
2. point_1 - tuple with x and y coordinates of point 1
3. point_2 - tuple with x and y coordinates of point 2
'''
(x_3, y_3), (x_4, y_4), (x_1, y_1), (x_2, y_2) = check_p_1, check_p_2, point_1, point_2
value_1 = (x_3 - x_1) * (y_2 - y_1) - (y_3 - y_1) * (x_2 - x_1)
value_2 = (x_4 - x_1) * (y_2 - y_1) - (y_4 - y_1) * (x_2 - x_1)
# will be True only when value_1 * value_2 > 0, False otherwise
result = (value_1 * value_2 > 0)
return result
# test | run only if file is executed directly
if __name__ == "__main__":
point_1 = (1, 2)
point_2 = (5, 6)
check_points = [
(3, 4),
(1, 1),
(2, 0),
(0, 2),
]
# check point to every other point
for index_1, check_p_1 in enumerate(check_points):
for check_p_2 in check_points[index_1 + 1:]:
check_result = are_on_same_side(check_p_1, check_p_2, point_1, point_2)
print(f'Points {check_p_1} and {check_p_2} are {"not " if not check_result else ""}on the same side of a line')
|
a56844b77ebb2b8dba937e215097e2f72aae59a3 | JChen1717/ud120-projects | /datasets_questions/explore_enron_data.py | 3,804 | 3.703125 | 4 | #!/usr/bin/python3
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You should explore features_dict as part of the mini-project,
but here's an example to get you started:
enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000
"""
import pickle
with open("../final_project/final_project_dataset.pkl", "rb") as f:
enron_data = pickle.load(f)
# Q1: How many data points (people) are in the dataset?-----------------------
print('Totally '+ str(len(enron_data)) +' people are in the dataset.')
# Q2: For each person, how many features are available?------------------------
count_features = str(len(enron_data['METTS MARK']))
print('For each person, ' + count_features + ' features are available.')
# Q3: How many POIs are there in the E+F dataset? -----------------------------
count_poi = 0
for _, value in enron_data.items():
if value['poi'] == True:
count_poi += 1
print(count_poi, 'POIs are in the dataset.')
# Q4: How many POI’s were there total from news papaer? -----------------------
with open('../final_project/poi_names.txt','r') as f:
count_poi_name = 0
for line in f:
if line[0] == '(':
count_poi_name += 1
print(count_poi_name, 'POIs were there total according to media.')
# Q5: What is the total value of the stock belonging to James Prentice?--------
stock_jp = enron_data['PRENTICE JAMES']['total_stock_value']
print('Total stock value for James Prentice is ', stock_jp)
# Q6: How many email messages do we have from Wesley Colwell to persons of interest?
email_to_poi_wc = enron_data['COLWELL WESLEY']['from_this_person_to_poi']
print(email_to_poi_wc, 'emails from Wesley Colwell to persons of interest.')
# Q7: What’s the value of stock options exercised by Jeffrey K Skilling?--------
exercised_stock_options_js = enron_data['SKILLING JEFFREY K']['exercised_stock_options']
print('The value of stock options exercised by Jeffrey K Skilling is',
exercised_stock_options_js)
# Q8: How many folks in this dataset have a quantified salary? What about a known email address?
count_salary = 0
count_email = 0
for _,value in enron_data.items():
if value['salary'] != 'NaN':
count_salary += 1
if value['email_address'] != 'NaN':
count_email += 1
print(count_salary, 'persons have a qualified salary,',
count_email, 'persons have a known email_address.')
# Q9: How many people in the E+F dataset (as it currently exists) have “NaN” for their total payments?
# What percentage of people in the dataset as a whole is this?--------------------------------
count_missing_finicial = 0
for _, value in enron_data.items():
if value['total_payments'] == 'NaN':
count_missing_finicial += 1
print(count_missing_finicial,"persons in the E+F dataset have 'NaN' for their total payments,",
"{:.2f}%".format(100*count_missing_finicial/len(enron_data)),
"of people in the dataset is missing total payments.")
# Q10: How many POIs in the E+F dataset have “NaN” for their total payments?
# What percentage of POI’s as a whole is this?-----------------------------
count_missing_finicial_poi = 0
count_poi = 0
for _, value in enron_data.items():
if value['poi'] == True:
count_poi += 1
if value['total_payments'] == 'NaN':
count_missing_finicial_poi += 1
print(count_missing_finicial_poi, " POIs in the E+F dataset have 'NaN' for their total payments,",
"{:.2f}%".format(100*count_missing_finicial_poi/count_poi),
"of POIs is missing total payments.")
print(enron_data['METTS MARK'])
|
f6e94ae84231ee30eebb8171cd4bae538515652b | diesgaro/holbertonschool-web_back_end | /0x00-python_variable_annotations/6-sum_mixed_list.py | 379 | 3.84375 | 4 | #!/usr/bin/env python3
'''
6. Complex types - mixed list
'''
from typing import List, Union
def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float:
'''
Function that sum mixed list
Arguments:
mxd_lst (List): A List with float and integer values
Return:
float: the result of sum
'''
return sum(mxd_lst)
|
fc3f2c70558cac7bba02a2ae4443608744cd463a | diesgaro/holbertonschool-web_back_end | /0x02-python_async_comprehension/1-async_comprehension.py | 394 | 3.515625 | 4 | #!/usr/bin/env python3
'''
1. Async Comprehensions
'''
import asyncio
import random
from typing import List
async_generator = __import__("0-async_generator").async_generator
async def async_comprehension() -> List[float]:
'''
Coroutine that will collect 10 random numbers using an
async comprehensing over async_generator
'''
return [i async for i in async_generator()]
|
424668ef3077df50ba211f166a3c00980fb7d4a4 | matheuszei/Python_DesafiosCursoemvideo | /0068_desafio.py | 1,194 | 4.0625 | 4 | #Faça um programa que jogue par ou ímpar com o computador.
# O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas
# que ele conquistou no final do jogo.
import random
win = 0
print('=-' * 15)
print('VAMOS JOGAR PAR OU ÍMPAR')
print('=-' * 15)
while True:
v = int(input('Digite um valor: '))
c = input('Par ou Ímpar? [P/I]: ').upper()
n = num = random.randint(1, 10)
if (v + n) % 2 == 0:
print(f'Você jogou {v} e o computador {n}. Total de {v + n} DEU PAR')
print('-' * 15)
if c == 'P':
print('VOCÊ GANHOU')
win += 1
else:
print('VOCÊ PERDEU')
print('=-' * 15)
print(f'GAME OVER! Você venceu {win} vezes.')
break
else:
print(f'Você jogou {v} e o computador {n}. Total de {v + n} DEU IMPAR')
print('-' * 15)
if c == 'I':
print('VOCÊ GANHOU')
win += 1
else:
print('VOCÊ PERDEU')
print('=-' * 15)
print(f'GAME OVER! Você venceu {win} vezes.')
break
print('-' * 15)
|
4e6f19c0decd6743ac9219d6084d8f66e17f47ec | matheuszei/Python_DesafiosCursoemvideo | /0078_desafio.py | 730 | 3.875 | 4 | #Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
#No final, mostre qual foi o maior e o menor valor digitados e as suas respectivas posições na lista.
valores = []
maior = menor = 0
for c in range(0, 5):
valores.append(int(input(f'({c}) Digite um valor: ')))
maior = max(valores)
menor = min(valores)
print('=-' * 15)
print(f'Você digitou os valores {valores}')
print(f'O maior valor digitado foi {maior} nas posições ', end='')
for i, v in enumerate(valores):
if v == maior:
print(f'{i}... ', end='')
print(f'\nO menor valor digitado foi {menor} nas posições ', end ='')
for i, v in enumerate(valores):
if v == menor:
print(f'{i}... ', end='')
|
d30db0f82f5497eb7a95916e8868f4ce4107325d | matheuszei/Python_DesafiosCursoemvideo | /0046_desafio.py | 185 | 3.578125 | 4 | #Crie um programa que faça o computador jogar Jokenpô com você.
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print('FELIZ ANO NOVOOOOOO!!!!!!') |
70b1c146606022a6a3c9abf15e3aee2b7b760e30 | matheuszei/Python_DesafiosCursoemvideo | /0044_desafio.py | 1,191 | 3.859375 | 4 | #Elabore um programa que calcule o valor a ser pago por um produto,
# considerando o seu preço normal e condição de pagamento:
# à vista dinheiro/cheque: 10% de desconto
# à vista no cartão: 5% de desconto
# em até 2x no cartão: preço formal
# 3x ou mais no cartão: 20% de juros
preco = float(input('Informe o preço do produto: '))
print('='*35)
print('ESCOLHA A FORMA DE PAGAMENTO')
print('='*35)
print('1- À Vista (dinheiro) \n2- À Vista (cartão) \n3- Em até 2x no cartão \n4- 3x ou mais no cartão')
print('-' * 35)
opcao = int(input('OPCAO: '))
precofinal = 0
#PROCESSAMENTO
if opcao == 1:
precofinal = (preco * 0.90)
print('Desconto de 10% incluso')
print('Preço final: {:.2f}'.format(precofinal))
elif opcao == 2:
precofinal = (preco * 0.95)
print('Desconto de 5% incluso')
print('Preço final: {:.2f}'.format(precofinal))
elif opcao == 3:
precofinal = preco
print('Sem desconto')
print('Preço final: {:.2f}'.format(precofinal))
elif opcao == 4:
precofinal = preco * 1.20
print('Juros de 20% incluso')
print('Preço final: {:.2f}'.format(precofinal))
else:
print('Opção inválida!') |
4cd244592bd39514d627fd2eea224af3edd60a48 | matheuszei/Python_DesafiosCursoemvideo | /0014_desafio.py | 231 | 4.34375 | 4 | #Escreva um programa que converta uma temperatura digitada em °C e converta para °F.
c = float(input('Informe a temperatura em C: '))
f = (c * 1.80) + 32
print('A temperatura de {}°C corresponde a {:.1}°F!'.format(c, f))
|
7a778a84ca61b99672feeeeeacebf287b5a84122 | matheuszei/Python_DesafiosCursoemvideo | /0031_desafio.py | 418 | 3.953125 | 4 | #Desenvolva um programa que pergunte a distância de uma viagem em Km.
# Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45
# parta viagens mais longas.
km = int(input('Digite a distância da viagem: '))
preco = 0
if km < 200:
preco = km * 0.50
else:
preco = km * 0.45
print('Esta viagem derá {} KM, devido a isto você pagará {:.2f} reais'.format(km, preco)) |
9469f6954e175e0cb02f09cc77161e44eb046a15 | matheuszei/Python_DesafiosCursoemvideo | /0025_desafio.py | 188 | 4.03125 | 4 | #Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome.
nome = input('Digite um nome: ')
print('A pessoa possui SILVA? {}'.format('Silva' in nome.upper()))
|
3862cdfa0ba22cebb714557f79b764ff512d90e0 | matheuszei/Python_DesafiosCursoemvideo | /0006_desafio.py | 288 | 3.9375 | 4 | #Crie um algoritmo que leia um número e mostre o seu dobro, tripo e raiz quadrada.
n1 = int(input('Digite o valor de N1: '))
print('O dobro de N1 é igual a {} \nO triplo de N1 é igual a {}'.format(n1 * 2, n1 * 3))
print('A raiz quadrada de N1 é igual a {}'.format(n1**(1/2)))
|
dd7d5203f18be05982adc9b1cd3f5ab72bd7c23a | matheuszei/Python_DesafiosCursoemvideo | /0007_desafio.py | 238 | 4.09375 | 4 | #Desenvolva um programa que leia as duas notas de um aluno, e calcule e mostre a sua média
nota1 = int(input('Digite a sua NOTA 1: '))
nota2 = int(input('Digite a sua NOTA 2: '))
print('Média final: {}'.format((nota1 + nota2) / 2)) |
c958cb5a82f6c8104bc7e0444032862e11459094 | matheuszei/Python_DesafiosCursoemvideo | /0050_desafio.py | 323 | 3.84375 | 4 | #Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles
# que forem pares. Se o valor digitado for ímpar, desconsidere-o.
soma = 0
for c in range(0, 6):
n = int(input('({}) Digite um valor: '.format(c)))
if n % 2 == 0:
soma += n
print('Soma total: {}'.format(soma))
|
ea4ddee2e65ca23a0797ebe195850eb412074168 | kosamati/pythoncw | /cw2/zadanie.py | 420 | 3.578125 | 4 | class animal:
def __init__(self, n, t, c):
self.name = n
self.type = t
self.color = c
def eat(self):
print(f'{self.type} {self.name} zjadł obiad')
def move(self):
print(f'{self.type} {self.name} zmienił położenie')
if __name__ == "__main__":
cat1 = animal("Pusia", "kot", "czarny")
dog1 = animal("Azor", "Pies", "czarny")
cat1.eat()
dog1.move()
|
75bbe2ec9d613543d12e963a3c16a90c9a9eb09f | racine101/palindrome_question | /palindrome.py | 487 | 3.71875 | 4 | def isValidChar(c):
return c.isalpha()
def isPalindrome(S):
start =0
end = len(S)-1
while start < end:
c1 = S[start].lower()
c2 = S[end].lower()
if isValidChar(c1) and isValidChar(c2):
if c1 != c2:
return False
start += 1
end -= 1
if not isValidChar(c1):
start += 1
if not isValidChar(c2):
end -= 1
return True
S = "abba"
print(isPalindrome(S)) |
dbf1b74b7b31ff3fd949142bd9c53ef74c38f34f | yangjingfeng/python-note | /test/day2/2.py | 90 | 3.671875 | 4 | while True:
for i in range(5):
print(i)
if i == 3:
exit(3) |
35c5023e9e1a88f32a4787c098137996f73fc368 | ramda-phi/PyPrac | /Queue.py | 783 | 3.6875 | 4 | class Queue:
class Cell:
def __init__(self, data, link=None):
self.data = data
self.link = link
def __init__(self):
self.size = 0
self.front = None
self.rear = None
def enqueue(self, x):
if self.size == 0:
self.front = self.rear = Queue.Cell(x)
else:
new_cell = Queue.Cell(x)
self.rear.link = new_cell
self.rear = new_cell
self.size += 1
def dequeue(self):
if self.size == 0:
raise IndexError
value = self.front.data
self.front = self.front.link
self.size -= 1
if self.size == 0:
self.rear = None
return value
def isEmpty(self):
return self.size == 0
|
b1c95880af1365ab630544adc2eb774a7b2ea2c0 | ramda-phi/PyPrac | /test_Set.py | 329 | 3.5 | 4 | import Set
s = Set
a = s.Set([1, 2, 3, 4, 5])
b = s.Set([4, 5, 6, 7, 8])
print a
print b
c = a.union(b)
print c
d = a.intersection(b)
print d
e = a.difference(b)
print e
print a.issubset(c)
print c.issubset(a)
print a.isequal(a)
a.insert(1)
print a
a.insert(10)
print a
b.remove(5)
print b
print c
print '-----'
f = b.union(a)
|
95f4a8102e352f350d08b93f4bfe31f421d8ee0d | ramda-phi/PyPrac | /Deque.py | 2,083 | 3.84375 | 4 | # Double ended queue
class Deque:
# define Cell
class Cell2:
def __init__(self, x, y=None, z=None):
self.data = x
self.next = y
self.prev = z
def __init__(self):
head = Deque.Cell2(None) # header
head.next = head # circular linked list
head.prev = head
self.size = 0
self.head = head
def push_front(self, x):
h = self.head
q = h.next
p = Deque.Cell2(x, q, h)
h.next = p
q.prev = p
self.size += 1
def push_back(self, x):
h = self.head
p = h.prev
q = Deque.Cell2(x, h, p)
h.prev = q
p.next = q
self.size += 1
def pop_front(self):
if self.size == 0:
raise IndexError
h = self.head
q = h.next
p = q.next
p.prev = h
h.next = p
self.size -= 1
return q.data
def pop_back(self):
if self.size == 0:
raise IndexError
h = self.head
q = h.prev
p = q.prev
p.next = h
h.prev = p
self.size -= 1
return q.data
def peek_front(self):
if self.size == 0:
raise IndexError
return self.head.next.data
def peek_back(self):
if self.size == 0:
raise IndexError
return self.head.prev.data
def isEmpty(self):
return self.size == 0
def __str__(self):
if self.size == 0:
return 'Deque()'
buff = 'Deque('
n = self.size
cp = self.head.next
while n > 1:
buff += '%s, ' % cp.data
cp = cp.next
n -= 1
buff += '%s)' % cp.data
return buff
if __name__ == '__main__':
q = Deque()
print q.isEmpty()
for x in range(5):
q.push_front(x)
q.push_back(x * 10)
print q
print q.peek_front()
print q.peek_back()
print q.isEmpty()
for x in range(5):
print q.pop_front()
print q.pop_back()
print q
|
a1ce03551a3b1839cb451e637937175def056737 | marcgrant21/Client_and_Server_Python | /vote_server.py | 4,095 | 3.578125 | 4 | # Server to implement simple program to get votes tallied from two different
# clients. The server will wait until two different clients connect, before
# sending a message down to each client.
# Author: Marc Grant 2019-09-26
# Version: 0.1
#!/usr/bin/python3
import random
import string
import socket
import sys
def clientACK():
"""Generates client acknowledgment"""
status = "200 OK"
return status
def candidatesHello(str1,str2):
"""Generates client hello message"""
status = "105 Candidates "+ str1 + "," + str2
return status
def WinnerMsg(strWinner, votes):
"""Sends message with winner identified"""
status = "220 Winner. " + strWinner + " " + votes
return status
def RunnerUpMsg(strRunnerUp, votes):
"""Sends message with runner-up identified"""
status = "221 Runner-up. " + strRunnerUp + " " + votes
return status
klist=[11,12]
# s = socket
# msg = initial message being processed
# state = dictionary containing state variables
def processMsgs(s, msg, status):
"""This function processes messages that are read through the socket. It
returns a status, which is an integer indicating whether the operation
was successful"""
strWinner=''
votes=''
runnerup=''
Rvote=''
status =2
str1="jack"
str2="jill"
if msg== "100 Hello":
print("100 Hello.")
res= candidatesHello(str1,str2)
s.send(res.encode())
status=1
msg = msg.split('. ')
if msg[0]=='110 Vote':
print(msg[0])
if msg[1]== 'jack':
klist.insert(0,klist[0]+1)
klist.remove(klist[1])
elif msg[1] == 'jill':
klist.insert(1,klist[1]+1)
klist.remove(klist[2])
ty=clientACK()
s.send(ty.encode())
status =1
if msg[0]=='120 Poll closed':
print(msg[0])
if klist[0]>klist[1]:
strWinner=str1
votes=str(klist[0])
runnerup=str2
Rvote=str(klist[1])
elif klist[1]>klist[0]:
strWinner=str2
votes=str(klist[1])
runnerup=str1
Rvote=str(klist[0])
des=WinnerMsg(strWinner, votes)
des1=RunnerUpMsg(runnerup, Rvote)
# print(des)
s.send(des.encode())
#print(des1)
s.send(des1.encode())
status=-1
if status==-1:
print("Thanks for voting")
return status
def main():
"""Driver function for the project"""
args = sys.argv#['localhost',12000]
if len(args) != 2:
print ("Please supply a server port.")
sys.exit()
HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = int(args[1]) # The port on which the server is listening
if PORT < 1023 or PORT > 65535:
print("Invalid port specified.")
sys.exit()
print("Server of MR. Brown")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))# Bind socket
s.listen(1) # listen
print("Waiting for 2 connections")
conn, addr = s.accept()# accept connection using socket
print("Client_A has connected")
conn1,addr = s.accept()# accept connection1 using socket
print("Client_B has connected")
with conn,conn1:
print('Connected by', addr)
status = 1
while (status==1):
msg = conn.recv(1024).decode('utf-8')
msg = conn1.recv(1024).decode('utf-8')
if not msg:
status = -1
else:
status = processMsgs(conn, msg, status)
status = processMsgs(conn1, msg, status)
if status < 0:
print("Invalid data received. Closing")
conn.close()
print("Closed connection socket")
if __name__ == "__main__":
main()
|
58dce10e602f32b280194b1d66c08e3d36a786b4 | sjhonatan/introPython | /20-class/00-classes.py | 480 | 3.8125 | 4 | """
Jhonatan da Silva
Last Updated version :
Tue Jan 31 22:35:52 2017
Number of code lines:
19
"""
# First we initiate the class
class Functions():
def __init__(self):
self.numFunctions = 3
def firstFunction(self):
print("I'm in the first function")
def secondFunction(self):
print("I'm in the second function")
def numberFunctions(self):
print(self.numFunctions)
F = Functions()
F.firstFunction()
F.secondFunction()
F.numberFunctions()
|
e71d9a91ed72bfa8ae16bdda03fccacfd7e80583 | iyee20/FinalProject18 | /projectcode.py | 55,762 | 3.546875 | 4 | #the game is heavily based on Fire Emblem Heroes, the mobile game of the Fire Emblem series
import random #import random to use
import sys, pygame #import pygame and sys to use
pygame.font.init() #initialize font module so font functions work
size = width, height = 500, 500 #define size as a certain px area
screen = pygame.display.set_mode(size) #create a Surface called "screen" with pygame (the screen the computer displays)
bg = screen.convert() #bg is a separate Surface based on screen
#define colors by name for convenience
black = (0, 0, 0) #rgb value of black
white = (255, 255, 255) #rgb value of white
fe_blue = (72, 117, 139) #color of Fire Emblem textboxes, midway between the gradient endpoints...ish
light_blue = (112, 172, 201) #a blue to stand out against Fire Emblem blue
red = (223, 29, 64) #a red to represent red-colored characters
blue = (36, 101, 224) #a blue to represent blue-colored characters
green = (6, 165, 41) #a green to represent green-colored characters
gray = (100, 117, 126) #a gray to represent colorless characters
#Anna's image
anna = pygame.image.load("Images/NPC/Anna.png").convert_alpha() #load file as surface
class Player:
"""The class for the Player's stats."""
def __init__(self, name, appearance, eye_color, hair_color, weapon, color, image, equipped=None):
self.chartype = "player"
self.name = name #name is always Player, but this attribute is for consistency
self.appearance = appearance
self.eye_color = eye_color
self.hair_color = hair_color
self.weapon = weapon
self.color = color
self.image = image
self.equipped = equipped #which weapon is equipped
#base stats based on the first summoned hero in Fire Emblem Heroes, Takumi, at 4 star rarity, except for range
self.hp = 17 #health
self.a = 8 #attack
self.d = 5 #defense
self.res = 4 #resistance
self.spd = 7 #speed
self.rng = 1 #range
self.breadcrumbs = 0 #obtained breadcrumbs
self.bread = 0 #obtained bread
self.x = 0 #x square on screen
self.y = 0 #y square on screen
class Foe:
"""The class for the enemy stats."""
def __init__(self, name, weapon, color, image, hp, a, d, res, rng, drop):
self.chartype = "foe"
self.name = name
self.weapon = weapon
self.color = color
self.image = image
self.hp = hp
self.a = a
self.d = d
self.res = res
self.rng = rng
self.drop = drop #how many breadcrumbs are dropped by the enemy
self.x = 0
self.y = 0
roll_imp_img = pygame.image.load("Images/NPC/roll_imp.png").convert_alpha() #load images as Surfaces
bun_dragon_img = pygame.image.load("Images/NPC/bun_dragon.png").convert_alpha()
baguette_devil_img = pygame.image.load("Images/NPC/baguette_devil.png").convert_alpha()
loaf_archer_img = pygame.image.load("Images/NPC/loaf_archer.png").convert_alpha()
roll_imp = Foe("Roll Imp", "lance", "blue", roll_imp_img, 18, 11, 6, 3, 1, 10) #based on Blue Fighter, 1 star with Iron Lance
bun_dragon = Foe("Bun Dragon", "dragonstone", "green", bun_dragon_img, 16, 13, 5, 4, 1, 25) #based on Green Manakete, 2 star with Fire Breath
baguette_devil = Foe("Baguette Devil", "sword", "red", baguette_devil_img, 18, 11, 6, 3, 1, 10) #based on Sword Fighter, 1 star with Iron Sword
loaf_archer = Foe("Loaf Archer", "bow", "colorless", loaf_archer_img, 17, 10, 5, 1, 2, 10) #based on Bow Fighter, 1 star with Iron Bow
def get_bread(defeated, mc):
"""Obtain breadcrumbs from defeating an enemy."""
mc.breadcrumbs += defeated.drop #add to Player's breadcrumb count
return
def breadify(mc):
"""Convert breadcrumbs to bread."""
converted = mc.breadcrumbs // 15 #calculate how much whole bread can be made
mc.breadcrumbs -= (converted * 15) #subtracted converted breadcrumbs from Player's breadcrumbs
mc.bread += converted #add converted bread to Player's bread
return
class Bread:
"""The class for the Fire Emblem characters with cutscenes."""
def __init__(self, name, bread):
self.name = name
self.bread = bread #how much bread is required to unlock their cutscene
self.unlocked = False
marth_img = pygame.image.load("Images/Bread/FEH_Marth.png").convert_alpha()
lucina_img = pygame.image.load("Images/Bread/FEH_Lucina.png").convert_alpha()
masked_marth_img = pygame.image.load("Images/Bread/FEH_Masked_Marth.png").convert_alpha()
marth = Bread("Marth", 3) #Marth - the main character of many FE games
lucina = Bread("Lucina", 5) #Lucina - Marth's descendant
masked_marth = Bread("Masked Marth", 7) #Masked Marth - Lucina, but disguised as Marth to save your timeline... but that's another can of worms
def unlock(character, mc, menu_box_size):
"""Unlock (or try to unlock) a character's cutscene."""
global bg, screen
font = pygame.font.Font(None, 20)
if character.unlocked == True:
None #if character has already been unlocked, nothing happens
elif character.bread > mc.bread: #message if Player doesn't have enough bread
bg.fill(fe_blue, menu_box_size)
text = font.render(f"You don't have enough bread to unlock {character.name} yet.", 1 , black)
text_pos = text.get_rect()
text_pos.center = menu_box_size.center
bg.blit(text, text_pos)
elif character.bread <= mc.bread: #unlock character
bg.fill(fe_blue, menu_box_size)
text = font.render(f"{character.name} unlocked!", 1, black)
text_pos = text.get_rect()
text_pos.center = menu_box_size.center
bg.blit(text, text_pos)
mc.bread -= character.bread #subtract spent bread from current bread
character.unlocked = True #character is now unlocked
screen.blit(bg, (0,0))
pygame.display.flip()
return
def bread_dialogue(dialogue, line2, line3):
"""Print a bread character's dialogue during a cutscene."""
global screen, bg
text_box = pygame.Rect(0, 400, bg.get_width(), 100)
bg.fill(fe_blue, text_box) #fill text box
white_box = pygame.Rect(10, 400, bg.get_width()-20, 100)
bg.fill(white, white_box) #fill white box
font = pygame.font.Font(None, 20)
text = font.render(dialogue, 1, black)
text_pos = text.get_rect()
text_pos.left = 20
text_pos.top = text_box.top + 10
bg.blit(text, text_pos) #print line 1
if line2 != None:
t2 = font.render(line2, 1, black)
t2_pos = t2.get_rect()
t2_pos.left = 20
t2_pos.top = text_pos.top + 25
bg.blit(t2, t2_pos) #print line 2
if line3 != None:
t3 = font.render(line3, 1, black)
t3_pos = t3.get_rect()
t3_pos.left = 20
t3_pos.top = t2_pos.top + 25
bg.blit(t3, t3_pos) #print line 3
screen.blit(bg, (0,0))
pygame.display.flip()
return
def marth_scene():
"""Run through Marth's cutscene."""
global bg
bg.fill(white)
bg.blit(marth_img, (0,0)) #print Marth's image
bread_dialogue("There you are. Anna said that you wanted to talk to me.", None, None)
pygame.time.delay(3000)
bread_dialogue("You know that you can come over whenever you want to talk, right? If you", "need any advice, you can ask me directly.", None)
pygame.time.delay(5000)
bread_dialogue("Oh, I see... you wanted to speak in private?", None, None)
pygame.time.delay(3000)
bread_dialogue("What seems to be the matter?", None, None)
pygame.time.delay(3000)
bread_dialogue("...That's very kind of you to say. I, too, am grateful for the support that", "you have given me. It is thanks to you that I have been able to help so", "many people.")
pygame.time.delay(8000)
bread_dialogue("I am glad that we can be a beacon of hope for Mantou together.", None, None)
pygame.time.delay(4000)
return
def lucina_scene():
"""Run through Lucina's cutscene."""
global bg
bg.fill(white)
bg.blit(lucina_img, (0,0)) #print Lucina's image
bread_dialogue("Here you are. I should have known that you would be training.", None, None)
pygame.time.delay(3000)
bread_dialogue("What? My hat? It is a bear. I thought it was cute.", None, None)
pygame.time.delay(3000)
bread_dialogue("...I see. I will keep that in mind.", None, None)
pygame.time.delay(3000)
bread_dialogue("Anna told me that you wanted to talk to me. What is it?", None, None)
pygame.time.delay(3000)
bread_dialogue("...Oh, you want to train with me?", None, None)
pygame.time.delay(3000)
bread_dialogue("...It's not that I wouldn't like to! I just... I assumed that you would rather", "practice with someone else.", None)
pygame.time.delay(5000)
bread_dialogue("...Thank you. It means a lot to me that you would say that, really. You", "remind me of-- of someone I once knew.", None)
pygame.time.delay(5000)
bread_dialogue("I look forward to spending more time with you.", None, None)
pygame.time.delay(4000)
return
def masked_marth_scene():
"""Run through Masked Marth's cutscene."""
global bg
bg.fill(white)
bg.blit(masked_marth_img, (0,0)) #print Masked Marth's image
bread_dialogue("Thank you for inviting me to talk. What is on your mind?", None, None)
pygame.time.delay(4000)
bread_dialogue("You wanted to ask about my mask? It was a gift from someone dear to me.", "I wear it to remember them.", None)
pygame.time.delay(5000)
bread_dialogue("...I understand your concern, but I can see perfectly well through it.", "There's no need to worry.", None)
pygame.time.delay(5000)
bread_dialogue("Hm? You were not referring to its effect on my sight?", None, None)
pygame.time.delay(4000)
bread_dialogue("...Oh! Oh. I-- I see. It is very kind of you to say that.", None, None)
pygame.time.delay(4000)
bread_dialogue("...To tell the truth, I had never thought of my eyes as pretty before.", None, None)
pygame.time.delay(4000)
bread_dialogue("It makes me happy to think that we will spend more time together. I look", "forward to it.", None)
pygame.time.delay(5000)
return
def in_range(attacker, defender):
"""Check if the defender is within the attacker's range."""
x_dif = abs(attacker.x - defender.x) #difference in x squares
y_dif = abs(attacker.y - defender.y) #difference in y squares
if x_dif + y_dif <= attacker.rng: #this allows attackers with range 2 to attack within 2 spaces
return True
else:
return False
weapon_triangle = { #the value to each key is the color it has an advantage over
"red": "green",
"blue": "red",
"green": "blue",
"colorless": ""
}
def advantage(attacker, defender):
"""Factor the weapon-triangle advantages into attacks."""
if defender.color == weapon_triangle[attacker.color]:
return 1.2 #20% increase for advantage
elif attacker.color == weapon_triangle[defender.color]:
return 0.8 #20% decrease for disadvantage
else:
return 1
physical_weapons = ["sword", "lance", "axe", "bow", "dagger"]
magic_weapons = ["tome", "dragonstone"]
def attack(attacker, defender, menu_box_size):
"""The attacker attacks the defender."""
if attacker.weapon in physical_weapons:
dmg = attacker.a - defender.d #use defense against physical weapons
if attacker.weapon in magic_weapons:
dmg = attacker.a - defender.res #use resistance against magic weapons
dmg *= advantage(attacker, defender) #alter damage based on the weapon-triangle advantage multiplier
if dmg > defender.hp:
dmg = defender.hp #max damage is all of the defender's hp
if dmg <= 0:
dmg = 0 #min damage is 0
defender.hp -= int(dmg)
display_health(menu_box_size, [attacker, defender]) #display results of attack
return
def check_defeat(defeated):
"""Check if a character has been defeated."""
if defeated.hp == 0:
return True
else:
return False
def reset_hp(character):
"""Reset a character's hp after battle."""
if character.chartype != "foe":
character.hp = 17 #Player hp is reset
else: #reset foe hp
if character.name == "Roll Imp" or character.name == "Baguette Devil":
character.hp = 18
elif character.name == "Bun Dragon":
character.hp = 16
elif character.name == "Loaf Archer":
character.hp = 17
return
class Weapon:
"""The class for weapons that can be equipped by the Player."""
def __init__(self, name, might, rng):
self.name = name
self.might = might #the attack power of the weapon
self.rng = rng #the range of the weapon
def equip(self, mc):
"""Equip a weapon and modify mc's stats."""
mc.a += self.might
mc.rng = self.rng
mc.equipped = self.name
return
sword_img = pygame.image.load("Images/Weapons/sword.png")
lance_img = pygame.image.load("Images/Weapons/lance.png")
axe_img = pygame.image.load("Images/Weapons/axe.png")
bow_img = pygame.image.load("Images/Weapons/bow.png")
dagger_img = pygame.image.load("Images/Weapons/dagger.png")
dragonstone_img = pygame.image.load("Images/Weapons/dragonstone.png")
tome_img = pygame.image.load("Images/Weapons/tome.png")
iron_sword = Weapon("Iron Sword", 6, 1)
iron_lance = Weapon("Iron Lance", 6, 1)
iron_axe = Weapon("Iron Axe", 6, 1)
iron_bow = Weapon("Iron Bow", 4, 2)
iron_dagger = Weapon("Iron Dagger", 3, 2)
fire_breath = Weapon("Fire Breath", 6, 1) #dragonstone
fire_tome = Weapon("Fire", 4, 2) #red tome
light_tome = Weapon("Light", 4, 2) #blue tome
wind_tome = Weapon("Wind", 4, 2) #green tome
def print_question(question, q_box, bg):
"""Print a question on q_box."""
q_font = pygame.font.Font(None, 25)
q_text = q_font.render(question, 1, black)
q_text_position = q_text.get_rect()
q_text_position.center = q_box.center #question text is at center of q_box
bg.blit(q_text, q_text_position) #print question text
q_font_sub = pygame.font.Font(None, 20)
q_text = q_font_sub.render("Type the number on the button.", 1, black) #instructions - subtext
q_text_position = q_text.get_rect()
q_text_position.center = q_box.centerx, q_box.bottom - 20
bg.blit(q_text, q_text_position) #print subtext
return
def print_button_text(text, button, bg):
"""Print text on a button."""
font = pygame.font.Font(None, 20)
text = font.render(text, 1, black)
text_position = text.get_rect()
text_position.center = button.center #print button text at center of button
bg.blit(text, text_position)
return
def spawn(character, spawned):
"""Spawn a character on the screen, but not on spawned."""
global screen, bg
#location is based on a 6 x 5 tile map
squarex = random.randint(0, 5)
squarey = random.randint(1, 5) #the top row is taken up by the menu box, so spawn starting at the second row down
if spawned != None:
if squarex == spawned.x and squarey == spawned.y: #re-spawn a character if they would spawn on top of another character
squarex = random.randint(0, 5)
squarey = random.randint(1, 5)
location = (screen.get_width() * squarex / 6) + 100/6, (screen.get_height() * squarey / 6) + 100/6
character.x = squarex
character.y = squarey #record x, y location
bg.blit(character.image, location)
screen.blit(bg, (0,0))
pygame.display.flip()
return
def move(character, tilexmove, tileymove, other):
"""Move a character on the screen."""
global screen, bg
position = pygame.Rect((screen.get_width() * character.x / 6) + 100/6, (screen.get_height() * character.y / 6) + 100/6, screen.get_width()/6, screen.get_height()/6)
if character.x + tilexmove > 5 or character.x + tilexmove < 0: #character can't move beyond the screen
tilexmove = 0
if character.y + tileymove > 5 or character.y + tileymove < 1:
tileymove = 0
if character.x + tilexmove == other.x and character.y + tileymove == other.y:
tilexmove = 0
tileymove = 0 #nullify movement if it would move on top of another character
character.x += tilexmove
character.y += tileymove
tilexmove *= screen.get_width()/6
tileymove *= screen.get_height()/6
new_pos = position.move(tilexmove, tileymove)
clean_map(other) #re-draw the map with other on it
bg.blit(character.image, new_pos) #draw character at new position
screen.blit(bg, (0,0))
pygame.display.flip()
return
def draw_map():
"""Draw the battle map on the screen."""
global screen, bg
fill_space = pygame.Rect(0, bg.get_height()/6, bg.get_width(), bg.get_height()*5/6) #only fill the 5 x 6 grid below the menu
bg.fill((250, 250, 250), fill_space)
for x in range(1,6): #draw grid lines
linespace = screen.get_width() * x / 6
pygame.draw.line(bg, (0,0,0), (linespace, bg.get_height()/6), (linespace, bg.get_height()))
for y in range(1,6):
linespace = screen.get_height() * y / 6
pygame.draw.line(bg, (0,0,0), (0, linespace), (bg.get_width(), linespace))
screen.blit(bg, (0,0))
pygame.display.flip()
return
def anna_box(menu_box_size, dialogue, line2):
"""Draw Anna's dialogue box on the screen and draw her dialogue."""
global screen, bg, anna
bg.fill(fe_blue, menu_box_size)
white_box = pygame.Rect(10, 0, screen.get_width() - 20, menu_box_size.height)
bg.fill(white, white_box)
bg.blit(anna, (10,0)) #print Anna's image
font = pygame.font.Font(None, 20)
text = font.render("ANNA", 1, black) #print Anna's name
text_position = text.get_rect()
text_position.left = 60
bg.blit(text, text_position)
dialogue_text = font.render(dialogue, 1, black) #print first line of dialogue
dialogue_text_pos = dialogue_text.get_rect()
dialogue_text_pos.left = 60
dialogue_text_pos.top = text_position.height + 5
bg.blit(dialogue_text, dialogue_text_pos)
if line2 != None: #if there is a second line of dialogue, print it
line2_text = font.render(line2, 1, black)
line2_text_pos = line2_text.get_rect()
line2_text_pos.left = 60
line2_text_pos.top = dialogue_text_pos.top + 25
bg.blit(line2_text, line2_text_pos)
screen.blit(bg, (0,0))
pygame.display.flip()
return
def display_health(menu_box_size, characters):
"""Display the health of all characters on the screen."""
global screen, bg
bg.fill(fe_blue, menu_box_size) #fill menu-sized area
white_box = pygame.Rect(10, 0, bg.get_width()-20, 100)
bg.fill(white, white_box) #fill white box
font = pygame.font.Font(None, 20)
above = -20
for character in characters:
above += 30 #add 30px to the above line, resulting in a 10px space between the lines
text = font.render(f"{character.name}: {character.hp} HP", 1, black)
text_pos = text.get_rect()
text_pos.left = 10
text_pos.top = above
bg.blit(text, text_pos)
screen.blit(bg, (0,0))
pygame.display.flip()
return
def draw_menu(menu_box_size):
"""Draw the menu on the screen."""
global screen, bg
bg.fill(fe_blue, menu_box_size) #fill menu bg
check_bread_box = pygame.Rect(10, 10, menu_box_size.width/3 - 10, menu_box_size.height - 20)
unlock_bread_box = pygame.Rect(menu_box_size.width/3 + 6, 10, menu_box_size.width/3 - 10, menu_box_size.height - 20)
new_lvl_box = pygame.Rect(menu_box_size.width*2/3, 10, menu_box_size.width/3 - 10, menu_box_size.height - 20)
bg.fill(light_blue, check_bread_box)
bg.fill(light_blue, unlock_bread_box)
bg.fill(light_blue, new_lvl_box) #fill buttons
font = pygame.font.Font(None, 20)
t1 = font.render("1. Check Bread", 1, black) #check bread button
t1_pos = t1.get_rect()
t1_pos.center = check_bread_box.center
bg.blit(t1, t1_pos)
t2 = font.render("2. Unlock Bread", 1, black) #unlock bread button
t2_pos = t2.get_rect()
t2_pos.center = unlock_bread_box.center
bg.blit(t2, t2_pos)
t3 = font.render("3. New Level", 1, black) #new level button
t3_pos = t3.get_rect()
t3_pos.center = new_lvl_box.center
bg.blit(t3, t3_pos)
screen.blit(bg, (0,0))
pygame.display.flip()
return
def bread_menu(menu_box_size, mc):
"""Draw the bread menu on the screen and interact with it."""
global screen, bg
bg.fill(fe_blue, menu_box_size) #fill menu bg
breadcrumb_box = pygame.Rect(10, 10, menu_box_size.width/3 - 10, menu_box_size.height/2 - 11)
bread_box = pygame.Rect(10, menu_box_size.height/2 + 2, menu_box_size.width/3 - 10, menu_box_size.height/2 - 11)
convert_bread_box = pygame.Rect(menu_box_size.width/3 + 6, 10, menu_box_size.width/3 - 10, menu_box_size.height - 20)
go_back_box = pygame.Rect(menu_box_size.width*2/3, 10, menu_box_size.width/3 - 10, menu_box_size.height - 20)
bg.fill(light_blue, breadcrumb_box) #fill buttons
bg.fill(light_blue, bread_box)
bg.fill(light_blue, convert_bread_box)
bg.fill(light_blue, go_back_box)
font = pygame.font.Font(None, 20)
t1 = font.render(f"Breadcrumbs: {mc.breadcrumbs}", 1, black) #display number of breadcrumbs
t1_pos = t1.get_rect()
t1_pos.center = breadcrumb_box.center
bg.blit(t1, t1_pos)
t2 = font.render(f"Bread: {mc.bread}", 1, black) #display amount of bread
t2_pos = t2.get_rect()
t2_pos.center = bread_box.center
bg.blit(t2, t2_pos)
t3 = font.render("1. Convert Bread", 1, black) #convert breadcrumbs to bread button
t3_pos = t3.get_rect()
t3_pos.center = convert_bread_box.center
bg.blit(t3, t3_pos)
t4 = font.render("2. Exit Menu", 1, black) #exit bread menu button
t4_pos = t4.get_rect()
t4_pos.center = go_back_box.center
bg.blit(t4, t4_pos)
screen.blit(bg, (0,0))
pygame.display.flip()
wait_to_start = True
while wait_to_start == True: #wait for Player input
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] == True:
breadify(mc) #convert bread if the button is "pressed"
bg.fill(light_blue, convert_bread_box)
converted_message = font.render("Bread converted!", 1, black)
bg.blit(converted_message, t3_pos) #replace button with success message
bg.fill(light_blue, breadcrumb_box)
bg.fill(light_blue, bread_box)
t1 = font.render(f"Breadcrumbs: {mc.breadcrumbs}", 1, black) #display number of breadcrumbs
bg.blit(t1, t1_pos)
t2 = font.render(f"Bread: {mc.bread}", 1, black) #display amount of bread
bg.blit(t2, t2_pos)
screen.blit(bg, (0,0))
pygame.display.flip()
pygame.time.delay(2000)
elif pressed[pygame.K_2] == True:
wait_to_start = False #exit function if button is "pressed"
return
def unlock_menu(menu_box_size, mc):
"""Draw the bread unlocking menu on the screen."""
global screen, bg
bg.fill(fe_blue, menu_box_size) #fill menu bg
marth_box = pygame.Rect(10, 10, menu_box_size.width/4 - 10, menu_box_size.height - 20)
lucina_box = pygame.Rect(menu_box_size.width/4 + 5, 10, menu_box_size.width/4 - 10, menu_box_size.height - 20)
masked_marth_box = pygame.Rect(menu_box_size.width/2, 10, menu_box_size.width/4 - 10, menu_box_size.height - 20)
go_back_box = pygame.Rect(menu_box_size.width*3/4, 10, menu_box_size.width/4 - 10, menu_box_size.height - 20)
if marth.unlocked == True:
bg.fill(light_blue, marth_box) #fill button blue if unlocked
else:
bg.fill(gray, marth_box) #fill button gray if not unlocked
if lucina.unlocked == True:
bg.fill(light_blue, lucina_box)
else:
bg.fill(gray, lucina_box)
if masked_marth.unlocked == True:
bg.fill(light_blue, masked_marth_box)
else:
bg.fill(gray, masked_marth_box)
bg.fill(light_blue, go_back_box)
font = pygame.font.Font(None, 20)
t1 = font.render("1. Marth", 1, black) #Marth cutscene button
t1_pos = t1.get_rect()
t1_pos.center = marth_box.center
bg.blit(t1, t1_pos)
if marth.unlocked == False: #print cost to unlock if Marth is not unlocked
sub1 = font.render("3 Bread", 1, black)
sub1_pos = sub1.get_rect()
sub1_pos.centerx = marth_box.centerx
sub1_pos.top = t1_pos.top + 25
bg.blit(sub1, sub1_pos)
t2 = font.render("2. Lucina", 1, black) #Lucina cutscene button
t2_pos = t2.get_rect()
t2_pos.center = lucina_box.center
bg.blit(t2, t2_pos)
if lucina.unlocked == False: #print cost to unlock if Lucina is not unlocked
sub2 = font.render("5 Bread", 1, black)
sub2_pos = sub2.get_rect()
sub2_pos.centerx = lucina_box.centerx
sub2_pos.top = t2_pos.top + 25
bg.blit(sub2, sub2_pos)
t3 = font.render("3. Masked Marth", 1, black) #Masked Marth cutscene button
t3_pos = t3.get_rect()
t3_pos.center = masked_marth_box.center
bg.blit(t3, t3_pos)
if masked_marth.unlocked == False: #print cost to unlock if Masked Marth is not unlocked
sub3 = font.render("7 Bread", 1, black)
sub3_pos = sub3.get_rect()
sub3_pos.centerx = masked_marth_box.centerx
sub3_pos.top = t2_pos.top + 25
bg.blit(sub3, sub3_pos)
t4 = font.render("4. Exit Menu", 1, black) #exit unlock menu button
t4_pos = t4.get_rect()
t4_pos.center = go_back_box.center
bg.blit(t4, t4_pos)
screen.blit(bg, (0,0))
pygame.display.flip()
running = True
while running == True: #wait for keyboard input
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] == True:
if marth.unlocked == False:
unlock(marth, mc, menu_box_size) #try to unlock Marth if he isn't already
pygame.time.delay(2000)
running = False
elif marth.unlocked == True:
marth_scene() #run through Marth's scene
running = False
elif pressed[pygame.K_2] == True:
if lucina.unlocked == False:
unlock(lucina, mc, menu_box_size) #try to unlock Lucina if she isn't already
pygame.time.delay(2000)
running = False
elif lucina.unlocked == True:
lucina_scene() #run through Lucina's scene
running = False
elif pressed[pygame.K_3] == True:
if masked_marth.unlocked == False:
unlock(masked_marth, mc, menu_box_size) #try to unlock Masked Marth if they aren't already
pygame.time.delay(2000)
running = False
elif masked_marth.unlocked == True:
masked_marth_scene() #run through Masked Marth's scene
running = False
elif pressed[pygame.K_4] == True:
running = False
return
def highlight(square, color):
"""Highlight a square with a colored outline."""
global bg, screen
pygame.draw.rect(bg, color, square, 5) #draw a colored rectangle with width 5
screen.blit(bg, (0,0))
pygame.display.flip()
return
def move_options(character, other):
"""Highlight the player's move options in green."""
square_width = screen.get_width()/6
square_height = screen.get_height()/6
character_left = character.x * square_width
character_top = character.y * square_height
#characters can only move 1 space. otherwise, I would die from writing instructions.
upsquare = pygame.Rect(character_left, character_top - square_height, square_width, square_height)
leftsquare = pygame.Rect(character_left - square_width, character_top, square_width, square_height)
rightsquare = pygame.Rect(character_left + square_width, character_top, square_width, square_height)
downsquare = pygame.Rect(character_left, character_top + square_height, square_width, square_height)
squares = [upsquare, leftsquare, rightsquare, downsquare] #possible places to move
for option in squares: #for each square...
squarex = option.left * square_width
squarey = option.top * square_height
if squarex == other.x and squarey == other.y:
None #if the square is occupied, don't highlight it
else:
if squarey != 0:
highlight(option, green) #highlight unoccupied squares green
return
def move_player(mc, other):
"""Move the Player on the map."""
global bg, screen
choosing = True
while choosing == True: #wait for keyboard input
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN: #if a key is pressed...
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP] == True: #move up if up key is pressed, etc.
move(mc, 0, -1, other)
choosing = False
elif pressed[pygame.K_LEFT] == True:
move(mc, -1, 0, other)
choosing = False
elif pressed[pygame.K_RIGHT] == True:
move(mc, 1, 0, other)
choosing = False
elif pressed[pygame.K_DOWN] == True:
move(mc, 0, 1, other)
choosing = False
elif pressed[pygame.K_KP_ENTER] == True or pressed[pygame.K_RETURN] == True:
choosing = False #don't move if the Player presses ENTER
return
def move_npc(character, other):
"""Move an enemy on the map."""
direction = random.randint(1,4) #randomly pick a direction
if direction == 1:
move(character, 0, -1, other) #1 = move up
elif direction == 2:
move(character, 1, 0, other) #2 = move right
elif direction == 3:
move(character, 0, 1, other) #3 = move down
elif direction == 4:
move(character, -1, 0, other) #4 = move left
return
def clean_map(char):
"""Draw the map with a character placed on it."""
global bg, screen
draw_map()
location = pygame.Rect((screen.get_width() * char.x / 6) + 100/6, (screen.get_height() * char.y / 6) + 100/6, screen.get_width()/6, screen.get_height()/6)
bg.blit(char.image, location) #place character on map
screen.blit(bg, (0,0))
pygame.display.flip()
return
def new_level(foes, mc, menu_box_size):
"""Generate and play through a level."""
global bg, screen
bg.fill(fe_blue, menu_box_size) #cover up menu while level is in progress
white_box = pygame.Rect(10, 0, bg.get_width()-20, 100)
bg.fill(white, white_box)
draw_map() #draw bg map
spawn(mc, None) #spawn Player
to_spawn = random.choice(foes) #spawn a random foe
spawn(to_spawn, mc)
font = pygame.font.Font(None, 20)
notif = font.render(f"A {to_spawn.name} appeared!", 1, black)
notif_pos = notif.get_rect()
notif_pos.center = white_box.center
bg.blit(notif, notif_pos) #display notif
screen.blit(bg, (0,0))
pygame.display.flip()
fighting = True
turn = "mc" #start with Player's turn
while fighting == True:
if check_defeat(to_spawn) == True:
draw_map() #clean map
get_bread(to_spawn, mc)
reset_hp(to_spawn)
reset_hp(mc)
fighting = False
elif turn == "mc":
move_options(mc, to_spawn) #view move options
move_player(mc, to_spawn) #Player moves
if in_range(mc, to_spawn) == True:
attack(mc, to_spawn, menu_box_size) #Player attacks if to_spawn is in range
turn = "foe"
else:
move_npc(to_spawn, mc) #foe moves
pygame.time.delay(1000)
if in_range(to_spawn, mc) == True:
attack(to_spawn, mc, menu_box_size) #to_spawn attacks if Player is in range
if check_defeat(mc) == True:
reset_hp(to_spawn) #no reward is gained from losing, but HP is reset for the next level
reset_hp(mc)
fighting = False
turn = "mc"
draw_menu(menu_box_size)
return
def main():
"""The code of the game."""
#opening screen
global screen, bg
bg.fill(white) #the opening bg is white
pygame.display.flip()
#title words
title_font = pygame.font.Font(None, 35) #title font is the default font at 35px size
title_text = title_font.render("Fire Emblem: Let's Get This Bread", 1, black) #title text is antialiasing and black
title_text_position = title_text.get_rect() #position of title text
title_text_position.centerx = screen.get_rect().centerx #center of title text is at center of the screen's width
title_text_position.bottom = screen.get_rect().bottom * 3 / 8 #title text is at 3/8 of screen's height
bg.blit(title_text, title_text_position) #draw title text at title_text_position
#opening instructions
font = pygame.font.Font(None, 25) #instructions are default font at 25px size
text = font.render("Press any key to start.", 1, black)
text_position = text.get_rect() #position of instructions
text_position.center = screen.get_rect().center #text is at center of screen
bg.blit(text, text_position) #draw instructions at text_position
screen.blit(bg, (0, 0)) #draw bg with text on screen
pygame.display.flip()
intro = True
while intro == True: #event loop - start after a key is pressed
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT: #if the Player tries to close the window...
return #exit (close game)
elif event.type == pygame.KEYDOWN: #if the Player presses a key...
intro = False #continue
#start Player customization
bg.fill(white)
pygame.display.flip()
q_box_size = pygame.Rect(0, 0, 500, 100)
q_box = bg.fill(fe_blue, q_box_size) #question box is a filled rectangle
#question text
name = "You" #Player is always referred to as "You"
#Player appearance (gender)
print_question("Do you identify as male, female, or nonbinary?", q_box, bg)
screen.blit(bg, (0,0))
pygame.display.flip()
#define the size of buttons
a_box_size = pygame.Rect(0, 0, 500, 50) #a_box is a Rect, 500 x 50 px
a_box_width = a_box_size.width
a_box_height = a_box_size.height #the height of a_box is used as the button height
button_width = (a_box_width / 3) - 10
button_top = bg.get_height() - a_box_height
c_button_left = (a_box_width / 2) - (button_width / 2)
r_button_left = a_box_width - button_width
l_button_size = pygame.Rect(0, button_top, button_width, a_box_height) #define button sizes
c_button_size = pygame.Rect(c_button_left, button_top, button_width, a_box_height)
r_button_size = pygame.Rect(r_button_left, button_top, button_width, a_box_height)
l_button = bg.fill(light_blue, l_button_size) #left button
print_button_text("1. Male", l_button, bg)
c_button = bg.fill(light_blue, c_button_size) #center button
print_button_text("2. Female", c_button, bg)
r_button = bg.fill(light_blue, r_button_size) #right button
print_button_text("3. Nonbinary", r_button, bg)
screen.blit(bg, (0,0))
pygame.display.flip()
choosing = True
while choosing == True: #wait until Player chooses
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed() #check if a key has been pressed
if pressed[pygame.K_1] == True:
appearance = "male"
choosing = False
elif pressed[pygame.K_2] == True:
appearance = "female"
choosing = False
elif pressed[pygame.K_3] == True:
appearance = "nonbinary"
choosing = False
#Player eye color
q_box = bg.fill(fe_blue, q_box_size) #clear q_box and re-fill
print_question("What color are your eyes?", q_box, bg)
l_button = bg.fill(light_blue, l_button_size) #clear buttons and re-fill
c_button = bg.fill(light_blue, c_button_size)
r_button = bg.fill(light_blue, r_button_size)
print_button_text("1. Red", l_button, bg) #new button text
print_button_text("2. Green", c_button, bg)
print_button_text("3. Blue", r_button, bg)
screen.blit(bg, (0,0))
pygame.display.flip()
choosing = True
while choosing == True: #wait for Player to choose
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] == True:
eye_color = "red"
choosing = False
elif pressed[pygame.K_2] == True:
eye_color = "green"
choosing = False
elif pressed[pygame.K_3] == True:
eye_color = "blue"
choosing = False
#Player hair color
q_box = bg.fill(fe_blue, q_box_size) #clear q_box and re-fill
print_question("What color is your hair?", q_box, bg)
l_button = bg.fill(light_blue, l_button_size) #clear buttons and re-fill
c_button = bg.fill(light_blue, c_button_size)
r_button = bg.fill(light_blue, r_button_size)
print_button_text("1. Red", l_button, bg)
print_button_text("2. Green", c_button, bg)
print_button_text("3. Blue", r_button, bg)
screen.blit(bg, (0,0))
pygame.display.flip()
choosing = True
while choosing == True: #wait for Player to choose
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] == True:
hair_color = "red"
choosing = False
elif pressed[pygame.K_2] == True:
hair_color = "green"
choosing = False
elif pressed[pygame.K_3] == True:
hair_color = "blue"
choosing = False
#mc_appearance_eye color_hair color - load file as surface
mc_m_r_r = pygame.image.load("Images/Player/mc_m_r_r.png").convert_alpha() #yes, I lost a few brain cells while copying and pasting these lines
mc_m_r_g = pygame.image.load("Images/Player/mc_m_r_g.png").convert_alpha() #I lost a few more while coloring and saving all of the images, too
mc_m_r_b = pygame.image.load("Images/Player/mc_m_r_b.png").convert_alpha()
mc_m_b_r = pygame.image.load("Images/Player/mc_m_b_r.png").convert_alpha()
mc_m_b_b = pygame.image.load("Images/Player/mc_m_b_b.png").convert_alpha()
mc_m_b_g = pygame.image.load("Images/Player/mc_m_b_g.png").convert_alpha()
mc_m_g_r = pygame.image.load("Images/Player/mc_m_g_r.png").convert_alpha()
mc_m_g_b = pygame.image.load("Images/Player/mc_m_g_b.png").convert_alpha()
mc_m_g_g = pygame.image.load("Images/Player/mc_m_g_g.png").convert_alpha()
mc_f_r_r = pygame.image.load("Images/Player/mc_f_r_r.png").convert_alpha()
mc_f_r_g = pygame.image.load("Images/Player/mc_f_r_g.png").convert_alpha()
mc_f_r_b = pygame.image.load("Images/Player/mc_f_r_b.png").convert_alpha()
mc_f_b_r = pygame.image.load("Images/Player/mc_f_b_r.png").convert_alpha()
mc_f_b_b = pygame.image.load("Images/Player/mc_f_b_b.png").convert_alpha()
mc_f_b_g = pygame.image.load("Images/Player/mc_f_b_g.png").convert_alpha()
mc_f_g_r = pygame.image.load("Images/Player/mc_f_g_r.png").convert_alpha()
mc_f_g_b = pygame.image.load("Images/Player/mc_f_g_b.png").convert_alpha()
mc_f_g_g = pygame.image.load("Images/Player/mc_f_g_g.png").convert_alpha()
mc_n_r_r = pygame.image.load("Images/Player/mc_n_r_r.png").convert_alpha()
mc_n_r_g = pygame.image.load("Images/Player/mc_n_r_g.png").convert_alpha()
mc_n_r_b = pygame.image.load("Images/Player/mc_n_r_b.png").convert_alpha()
mc_n_b_r = pygame.image.load("Images/Player/mc_n_b_r.png").convert_alpha()
mc_n_b_b = pygame.image.load("Images/Player/mc_n_b_b.png").convert_alpha()
mc_n_b_g = pygame.image.load("Images/Player/mc_n_b_g.png").convert_alpha()
mc_n_g_r = pygame.image.load("Images/Player/mc_n_g_r.png").convert_alpha()
mc_n_g_b = pygame.image.load("Images/Player/mc_n_g_b.png").convert_alpha()
mc_n_g_g = pygame.image.load("Images/Player/mc_n_g_g.png").convert_alpha()
#image logic - which icon is used
if appearance == "male":
if eye_color == "red":
if hair_color == "red":
image = mc_m_r_r
elif hair_color == "blue":
image = mc_m_r_b
elif hair_color == "green":
image = mc_m_r_g
elif eye_color == "blue":
if hair_color == "red":
image = mc_m_b_r
elif hair_color == "blue":
image = mc_m_b_b
elif hair_color == "green":
image = mc_m_b_g
elif eye_color == "green":
if hair_color == "red":
image = mc_m_g_r
elif hair_color == "blue":
image = mc_m_g_b
elif hair_color == "green":
image = mc_m_g_g
elif appearance == "female":
if eye_color == "red":
if hair_color == "red":
image = mc_f_r_r
elif hair_color == "blue":
image = mc_f_r_b
elif hair_color == "green":
image = mc_f_r_g
elif eye_color == "blue":
if hair_color == "red":
image = mc_f_b_r
elif hair_color == "blue":
image = mc_f_b_b
elif hair_color == "green":
image = mc_f_b_g
elif eye_color == "green":
if hair_color == "red":
image = mc_f_g_r
elif hair_color == "blue":
image = mc_f_g_b
elif hair_color == "green":
image = mc_f_g_g
elif appearance == "nonbinary":
if eye_color == "red":
if hair_color == "red":
image = mc_n_r_r
elif hair_color == "blue":
image = mc_n_r_b
elif hair_color == "green":
image = mc_n_r_g
elif eye_color == "blue":
if hair_color == "red":
image = mc_n_b_r
elif hair_color == "blue":
image = mc_n_b_b
elif hair_color == "green":
image = mc_n_b_g
elif eye_color == "green":
if hair_color == "red":
image = mc_n_g_r
elif hair_color == "blue":
image = mc_n_g_b
elif hair_color == "green":
image = mc_n_g_g
#Player weapon
bg.fill(white) #refill background to start a new question
pygame.display.flip()
q_box = bg.fill(fe_blue, q_box_size)
print_question("Pick a weapon.", q_box, bg) #print new question
button_top_1 = q_box.height + 10 #define top row of buttons
button_top_2 = bg.get_rect().centery + (a_box_height / 2) #define center row of buttons
b1_size = pygame.Rect(0, button_top_1, button_width, a_box_height) #define new button sizes
b2_size = pygame.Rect(r_button_left, button_top_1, button_width, a_box_height)
b3_size = pygame.Rect(0, button_top_2, button_width, a_box_height)
b4_size = pygame.Rect(r_button_left, button_top_2, button_width, a_box_height)
b5_size = pygame.Rect(0, button_top, button_width, a_box_height)
b6_size = pygame.Rect(c_button_left, button_top, button_width, a_box_height)
b7_size = pygame.Rect(r_button_left, button_top, button_width, a_box_height)
b1 = bg.fill(light_blue, b1_size) #define buttons as filled Rects
b2 = bg.fill(light_blue, b2_size)
b3 = bg.fill(light_blue, b3_size)
b4 = bg.fill(light_blue, b4_size)
b5 = bg.fill(light_blue, b5_size)
b6 = bg.fill(light_blue, b6_size)
b7 = bg.fill(light_blue, b7_size)
print_button_text("1. Sword", b1, bg) #print button text
print_button_text("2. Lance", b2, bg)
print_button_text("3. Axe", b3, bg)
print_button_text("4. Bow", b4, bg)
print_button_text("5. Dagger", b5, bg)
print_button_text("6. Dragonstone", b6, bg)
print_button_text("7. Tome", b7, bg)
bg.blit(sword_img, pygame.Rect(bg.get_rect().centerx-50, button_top_1+15, 20, 20)) #display weapon images
bg.blit(lance_img, pygame.Rect(bg.get_rect().centerx+50, button_top_1+15, 20, 20))
bg.blit(axe_img, pygame.Rect(bg.get_rect().centerx-50, button_top_2+15, 20, 20))
bg.blit(bow_img, pygame.Rect(bg.get_rect().centerx+50, button_top_2+15, 20, 20))
bg.blit(dagger_img, pygame.Rect(button_width/2, button_top-30, 20, 20))
bg.blit(dragonstone_img, pygame.Rect(bg.get_rect().centerx, button_top-30, 20, 20))
bg.blit(tome_img, pygame.Rect(bg.get_width()-(button_width/2)-20, button_top-30, 20, 20))
screen.blit(bg, (0,0))
pygame.display.flip()
choosing = True
while choosing == True: #wait for Player to choose
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] == True:
weapon = "sword"
choosing = False
elif pressed[pygame.K_2] == True:
weapon = "lance"
choosing = False
elif pressed[pygame.K_3] == True:
weapon = "axe"
choosing = False
elif pressed[pygame.K_4] == True:
weapon = "bow"
choosing = False
elif pressed[pygame.K_5] == True:
weapon = "dagger"
choosing = False
elif pressed[pygame.K_6] == True:
weapon = "dragonstone"
choosing = False
elif pressed[pygame.K_7] == True:
weapon = "tome"
choosing = False
colors = ["red", "blue", "green"] #I've elected to remove the colorless option for daggers, bows, and dragonstones
if weapon == "sword": #swords are red
color = "red"
elif weapon == "lance": #lances are blue
color = "blue"
elif weapon == "axe": #axes are green
color = "green"
elif weapon == "dagger" or weapon == "bow" or weapon == "dragonstone" or weapon == "tome": #these can be any color
color = random.choice(colors) #random color assignment, to be fair
mc = Player(name, appearance, eye_color, hair_color, weapon, color, image, None) #mc = Player ("you")
bg.fill(white)
q_box = bg.fill(white, q_box_size) #q_box is white for the equipment screen
if weapon == "sword":
print_button_text("You received a red Iron Sword!", q_box, bg) #print text on q_box (q_box is the "button")
iron_sword.equip(mc) #equip weapon
elif weapon == "lance":
print_button_text("You received a blue Iron Lance!", q_box, bg)
iron_lance.equip(mc)
elif weapon == "axe":
print_button_text("You received a green Iron Axe!", q_box, bg)
iron_axe.equip(mc)
elif weapon == "dagger":
print_button_text(f"You received a {color} Iron Dagger!", q_box, bg)
iron_dagger.equip(mc)
elif weapon == "bow":
print_button_text(f"You received a {color} Iron Bow!", q_box, bg)
iron_bow.equip(mc)
elif weapon == "dragonstone":
print_button_text(f"You received a {color} Fire Breath dragonstone!", q_box, bg)
fire_breath.equip(mc)
elif weapon == "tome":
if color == "red":
print_button_text("You received a red Fire tome!", q_box, bg)
fire_tome.equip(mc)
elif color == "blue":
print_button_text("You received a blue Light tome!", q_box, bg)
light_tome.equip(mc)
elif color == "green":
print_button_text("You received a green Wind tome!", q_box, bg)
wind_tome.equip(mc)
bottom_text = font.render("Press any key to continue.", 1, black) #font = size of instructions on opening screen, 25px
bg.blit(bottom_text, text_position)
screen.blit(bg, (0,0))
pygame.display.flip()
wait_to_start = True
while wait_to_start == True: #wait for Player to press a key
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN:
wait_to_start = False
draw_map() #draw the bg
spawn(mc, None) #spawn mc on map
spawn(roll_imp, mc) #spawn Roll Imp on map, not on mc
menu_box_size = pygame.Rect(0, 0, screen.get_width(), screen.get_height()/6) #define Rect for size of menu
anna_box(menu_box_size, "Good morning! It's good to see that you're finally awake.", None)
pygame.time.delay(2000) #Player gets 2 seconds to read
anna_box(menu_box_size, "The forces of Brioche have invaded Mantou. We need your help!", None)
pygame.time.delay(4000)
#tutorial dialogue
square = pygame.Rect((screen.get_width() * roll_imp.x / 6), (screen.get_height() * roll_imp.y / 6), screen.get_width()/6, screen.get_height()/6)
highlight(square, red)
anna_box(menu_box_size, "That's a Roll Imp.", None)
pygame.time.delay(2000)
anna_box(menu_box_size, "The Roll Imp has a lance, which is a BLUE weapon.", None)
pygame.time.delay(4000)
anna_box(menu_box_size, "Keep the weapon-triangle advantages in mind when you", "attack enemies.")
pygame.time.delay(5000)
anna_box(menu_box_size, "BLUE weapons are effective against RED weapons, which are", "effective against GREEN weapons,")
pygame.time.delay(7000)
anna_box(menu_box_size, "and GREEN weapons are effective against BLUE weapons.", None)
pygame.time.delay(5000)
anna_box(menu_box_size, "Let's try attacking the Roll Imp!", None)
pygame.time.delay(2000)
anna_box(menu_box_size, "Swords, lances, axes, and dragonstones have a range of 1 tile.", "Bows, daggers, and tomes have a range of 2 tiles.")
pygame.time.delay(10000)
anna_box(menu_box_size, "Move using the arrow keys until you get in range to attack.", "Press ENTER if you don't need to move.")
fight1 = True
turn = "mc" #start with Player's turn
while fight1 == True:
if check_defeat(roll_imp) == True: #if Roll Imp is defeated...
clean_map(mc)
get_bread(roll_imp, mc) #win breadcrumbs
reset_hp(roll_imp) #hp is reset
reset_hp(mc)
fight1 = False
elif turn == "mc":
move_options(mc, roll_imp) #show Player their move options
move_player(mc, roll_imp) #the Player moves
if in_range(mc, roll_imp) == True:
attack(mc, roll_imp, menu_box_size) #the Player automatically attacks if the Roll Imp is in range
turn = "foe"
else:
move_npc(roll_imp, mc) #the Roll Imp moves
pygame.time.delay(1000)
if in_range(roll_imp, mc) == True:
attack(roll_imp, mc, menu_box_size)
if check_defeat(mc) == True: #this most likely won't happen, but the Player can be defeated by the first enemy
clean_map(mc)
get_bread(roll_imp, mc) #the Player wins breadcrumbs anyway, however
reset_hp(roll_imp) #hp is reset
reset_hp(mc)
fight1 = False
turn = "mc"
anna_box(menu_box_size, "Nice work!", None)
pygame.time.delay(2000)
anna_box(menu_box_size, "Every time you defeat an enemy, you collect breadcrumbs.", None)
pygame.time.delay(4000)
anna_box(menu_box_size, "Press 1 to open the breadcrumb menu.", None)
wait_to_start = True
while wait_to_start == True: #wait for Player to press a key
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN: #the Player doesn't actually have to press 1 this time, but... they don't have to know that
wait_to_start = False
bread_menu(menu_box_size, mc) #display Bread Menu
anna_box(menu_box_size, "Breadcrumbs can be converted in the Check Bread menu.", "It takes 15 breadcrumbs to make 1 bread.")
pygame.time.delay(5000)
anna_box(menu_box_size, "Bread is used to unlock bread characters. Press 2 to open", "the Unlock Bread menu.")
wait_to_start = True
while wait_to_start == True: #wait for Player to press a key
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.KEYDOWN: #the Player doesn't actually have to press 2 this time, but... they don't have to know that
wait_to_start = False
unlock_menu(menu_box_size, mc) #display Unlock Menu
anna_box(menu_box_size, "After you complete one level, press 3 to start a new level.", None)
pygame.time.delay(4000)
anna_box(menu_box_size, "Alright! Let's get this bread!", None)
pygame.time.delay(2000)
while True: #running levels and choices loop
new_level([roll_imp, bun_dragon, baguette_devil, loaf_archer], mc, menu_box_size) #run a new level
wait_to_start = True
while wait_to_start == True: #after battle, wait until a key is pressed
pygame.event.pump()
#hehe. 1257.
for event in pygame.event.get():
if event.type == pygame.QUIT:
return #exit game if Player closes the window
elif event.type == pygame.KEYDOWN:
pressed = pygame.key.get_pressed() #check if a key is pressed
if pressed[pygame.K_1] == True:
bread_menu(menu_box_size, mc) #display Bread Menu
draw_menu(menu_box_size) #display regular menu
elif pressed[pygame.K_2] == True:
unlock_menu(menu_box_size, mc) #display Unlock Menu
draw_map() #redraw map (in case a Bread scene was played)
draw_menu(menu_box_size)
elif pressed[pygame.K_3] == True:
wait_to_start = False #start a new level
return
main() #run game |
00d29dce519eade07f3269e7eb83ddc4426721eb | XinchaoGou/MyLeetCode | /283. Move Zeros.py | 831 | 3.609375 | 4 | from typing import List
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = 0
cnt = 0
length = len(nums)
for i in range(length):
if nums[i] != 0:
nums[k] = nums[i]
k += 1
else:
cnt += 1
for i in range(length - cnt, length, 1):
nums[i] = 0
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i]:
nums[i], nums[j] = nums[j], nums[i]
j += 1
nums = [0,1,0,3,12]
Solution().moveZeroes(nums)
print(nums)
|
6f4519015aea40f4bd3cc64bd22d8e5b8e02d238 | XinchaoGou/MyLeetCode | /102. Binary Tree Level Order Traversal.py | 825 | 3.515625 | 4 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
cur_layer = [root]
res = []
while cur_layer: #判断是否该层为空
next_layer = []
layer_val = []
while cur_layer: #遍历该层所有节点
node = cur_layer.pop(0)
layer_val.append(node.val)
if node.left:
next_layer.append(node.left)
if node.right:
next_layer.append(node.right)
if layer_val:
res.append(layer_val)
cur_layer = next_layer
return res |
68bbf7f74f4783f7ce0de2f80e3b61f364082057 | XinchaoGou/MyLeetCode | /654. Maximum Binary Tree.py | 1,137 | 3.515625 | 4 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
def dfs(left, right):
if left > right or left <0 or right>len(nums)-1:
return None
max_idx = left
for i in range(left, right+1, 1):
if nums[i] > nums[max_idx]:
max_idx = i
root = TreeNode(nums[max_idx])
root.left = dfs(left, max_idx-1)
root.right = dfs(max_idx+1, right)
return root
return dfs(0, len(nums)-1)
# 单调栈
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
stack = []
for num in nums:
node = TreeNode(num)
while stack and stack[-1].val < num:
node.left = stack.pop()
if stack:
stack[-1].right = node
stack.append(node)
return stack[0]
nums = [3,2,1,6,0,5]
Solution().constructMaximumBinaryTree(nums) |
9c62ed0761e46b3afed7b1493f6c915019fb4df3 | XinchaoGou/MyLeetCode | /116. Populating Next Right Pointers in Each Node.py | 700 | 3.9375 | 4 | class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
# 从根节点开始
leftmost = root
while leftmost.left:
# 遍历这一层节点组织成的链表,为下一层的节点更新 next 指针
head = leftmost
while head:
# CONNECTION 1
head.left.next = head.right
# CONNECTION 2
if head.next:
head.right.next = head.next.left
# 指针向后移动
head = head.next
# 去下一层的最左的节点
leftmost = leftmost.left
return root |
19ff9bc8c6cc955f306cfee5142a8cbcc6dbc75d | XinchaoGou/MyLeetCode | /169. Majority Element.py | 927 | 3.5625 | 4 | from typing import List
class Solution:
# def majorityElement(self, nums: List[int]) -> int:
# length = len(nums)
# half_len = length//2
# # l_me = self.majorityElement(nums[:half_len])
# # r_me = self.majorityElement(nums[half_len:])
# num_dict = {}
# maj_ele = nums[0]
# for i in range(length):
# key = nums[i]
# num_dict[key]= num_dict.get(key, 0) + 1
# if num_dict[key] > half_len:
# maj_ele = nums[i]
# break
# return maj_ele
def majorityElement(self, nums: List[int]) -> int:
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += 1 if num == candidate else -1
return candidate
# input = [2,2,1,1,1,2,2]
input = [6,5,5]
output = Solution().majorityElement(input)
print(output) |
b1b4fb1cf58cc7559993ef272e554218a468d118 | XinchaoGou/MyLeetCode | /217. Contains Duplicate.py | 237 | 3.6875 | 4 | from typing import List
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
l1 = len(nums)
l2 = len(set(nums))
return not l1 == l2
input = [1,2,3]
print(Solution().containsDuplicate(input))
|
26f3b93307fa96e97f6df8c0e492a58fbe16b028 | XinchaoGou/MyLeetCode | /167. Two Sum II - Input array is sorted.py | 1,351 | 3.578125 | 4 | from typing import List
class Solution:
# def twoSum(self, numbers: List[int], target: int) -> List[int]:
# def search_helper(l, t: int):
# r = len(numbers) - 1
# while (l <= r):
# mid = int(l + (r - l) / 2)
# mid_val = numbers[mid]
# if mid_val == t:
# return mid
# elif mid_val > t:
# r = mid - 1
# else:
# l = mid + 1
# return None
#
# res = []
# for i in range(len(numbers)):
# t = target - numbers[i]
# if (t >= numbers[i]):
# searched = search_helper(i+1, t)
# if searched:
# res = [i + 1, searched + 1]
# break
# else:
# break
# return res
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l = 0
r = len(numbers)-1
while(l < r):
sum_val = numbers[l] + numbers[r]
if sum_val == target:
return [l+1, r+1]
elif sum_val > target:
r -= 1
else:
l +=1
return []
numbers = [1,2,3,4,4,9,56,90]
target = 8
output = Solution().twoSum(numbers, target)
print(output)
|
952e289c81f0cfb51890177403e90f75cd1dfdd1 | XinchaoGou/MyLeetCode | /61. Rotate List.py | 573 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not (head and head.next and k) :
return head
fast = head
cnt = 1
while fast.next:
fast = fast.next
cnt += 1
fast.next = head
slow = head
for i in range(cnt - k%cnt - 1):
slow = slow.next
second = slow.next
slow.next = None
return second
|
11a7aad67da703d501dfc08e7fb3481fcf58317c | XinchaoGou/MyLeetCode | /56. Merge Intervals.py | 512 | 3.59375 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
sorted_intervals = sorted(intervals, key=lambda x: x[0])
res = [sorted_intervals[0]]
for i in range(1, len(sorted_intervals)):
last = res[-1]
x= sorted_intervals[i]
if x[0]<=last[1]:
res[-1][1] = max(last[1],x[1])
else:
res.append(x)
return res |
9cce47566dda73cb3987370a9dc6007e2dd2ec87 | XinchaoGou/MyLeetCode | /23. Merge k Sorted Lists.py | 2,187 | 3.765625 | 4 | from typing import List
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 顺序合并
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def merge2Lists(a, b):
if not a or not b:
return a or b
head = ListNode()
p = head
while a and b:
if a.val < b.val:
p.next = a
a = a.next
else:
p.next = b
b = b.next
p = p.next
p.next = a or b
return head.next
if not lists:
return None
res = lists[0]
for i in range(1, len(lists)):
res = merge2Lists(res, lists[i])
return res
# 分治合并
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
def merge2List(a,b):
if not a or not b:
return a or b
head = ListNode()
p = head
while a and b:
if a.val < b.val:
p.next = a
a = a.next
else:
p.next = b
b = b.next
p = p.next
p.next = a or b
return head.next
if not lists:
return None
gap = 1
n = len(lists)
while gap < n:
for i in range(0, n, gap*2):
if i + gap < n:
lists[i] = merge2List(lists[i], lists[i+gap])
gap *= 2
return lists[0]
# 优先队列 (堆)
ListNode.__lt__ = lambda a, b: a.val < b.val
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
hpq = []
for i in range(len(lists)):
node =lists[i]
if node: heapq.heappush(hpq, node)
head = ListNode()
p = head
while hpq:
node = heapq.heappop(hpq)
p.next = node
p = p.next
node = node.next
if node: heapq.heappush(hpq, node)
return head.next |
6812bae562d763adea7d6d83b81c11aeaf6b149e | rohan1218/code | /greatest.py | 189 | 3.921875 | 4 | a=int(input())
b=int(input())
c=int(input())
def greatest(a,b,c):
if a>=b and a>=c:
print(a)
elif b>=a and b>=c:
print(b)
else:
print(c)
greatest(a,b,c)
|
a10d9793d9d91e801f2327cc19ea8dea2f93600d | MrPratik07/Amazon-Dataset | /amazon_dataset.py | 4,501 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Jobs available in Banglore and Seattle
# In[4]:
import csv
count1=0
count2=0
with open('Datasets/amazon_jobs_dataset.csv','r',encoding="utf8") as file_obj:
file_data=csv.reader(file_obj,skipinitialspace=True)
file_list=list(file_data)
location=[]
for row in file_list[1:]:
value=row[2]
if 'Bangalore' in value:
count1+=1
elif 'Seattle' in value:
count2+=1
print("Jobs in banglore",count1)
print("Jobs in Seattle",count2)
# # Jobs available as a Computer Vision
# In[6]:
import csv
count1=0
with open('Datasets/amazon_jobs_dataset.csv','r',encoding="utf8") as file_obj:
file_data=csv.reader(file_obj,skipinitialspace=True)
file_list=list(file_data)
jobs=[]
for row in file_list[1:]:
value=row[1]
if 'Computer Vision' in value:
count1+=1
print("jobs in Computer Vision",count1)
# # jobs available in Canada
# In[3]:
import csv
count1=0
with open('Datasets/amazon_jobs_dataset.csv','r',encoding="utf8") as file_obj:
file_data=csv.reader(file_obj,skipinitialspace=True)
file_list=list(file_data)
jobs=[]
for row in file_list[1:]:
value=row[2].split(",")
if(value[0]=='CA') :
count1+=1
print("jobs in canada are",count1)
# # Highest no of job openings in month
# In[9]:
import csv
count1=0
with open('Datasets/amazon_jobs_dataset.csv','r',encoding="utf8") as file_obj:
file_data=csv.reader(file_obj,skipinitialspace=True)
file_list=list(file_data)
dict={}
for row in file_list[1:]:
value=row[3].split(",")
if(value[1].strip()=='2018'):
value2 = value[0].split(' ')
month = value2[0].strip()
if month in dict:
dict[month] += 1
else:
dict[month] = 1
v = list(dict.values())
k = list(dict.keys())
print("The no of jobs openings are in month",k[v.index(max(v))],"with no of openings",max(v))
# # No of jobs available for Bachelors degree
# In[2]:
import csv
with open('Datasets/amazon_jobs_dataset.csv','r',encoding="utf8") as file_obj:
file_data=csv.reader(file_obj,skipinitialspace=True)
file_list=list(file_data)
count=0
for row in file_list[1:]:
#p=row['BASIC QUALIFICATIONS']
p=row[5]
if "Bachelor" in p:
count+=1
elif "BS" in p:
count+=1
elif "BA" in p:
count+=1
print("No of jobs available for bachelors degree is",count)
# # Among Java, C++ and Python, which of the language has more job openings in India for Bachelor Degree Holder?
# In[5]:
## Open and read data file as specified in the question
## Print the required output in given format
import csv
with open('Datasets/amazon_jobs_dataset.csv','r',encoding="utf8") as file_obj:
file_data=csv.reader(file_obj,skipinitialspace=True)
file_list=list(file_data)
count=0
count1=0
count2=0
for row in file_list[1:]:
if row[2][:2] == 'IN':
p=row[5]
if "Bachelor" in p or "BS" in p or "BA" in p:
if "Java" in p:
count+=1
if "C++" in p:
count1+=1
if "Python" in p:
count2+=1
ans = max(count, max(count1, count2))
if ans == count:
print('Java', ans)
elif ans == count1:
print('C++', ans)
else:
print('Python', ans)
# # Most No of Java developers openings in Country
# In[2]:
## Open and read data file as specified in the question
## Print the required output in given format
import csv
path='Datasets/amazon_jobs_dataset.csv'
country_basic_qualifications=[]
with open(path,'r',encoding='utf-8') as csvFile:
reader=csv.DictReader(csvFile)
for row in reader:
country_basic_qualifications.append([row['location'],row['BASIC QUALIFICATIONS']])
## Get Java Developer from the different country
def getTheJavaDeveloper(arr):
arrlist=[]
for i in arr:
if 'Java' in i[1]:
arrlist.append(i[0].split(',')[0])
return arrlist
java_developer=getTheJavaDeveloper(country_basic_qualifications)
def createDictionary(arr):
dictionary={i:0 for i in set(arr)}
for i in arr:
dictionary[i]=dictionary.get(i)+1
return dictionary
def convertDictToList(dictionary):
arrlist=[]
for i in dictionary:
arrlist.append([dictionary.get(i),i])
arrlist.sort(reverse=True)
return arrlist
java_dict=createDictionary(java_developer)
java_list=convertDictToList(java_dict)
print(java_list[0][1],java_list[0][0])
# In[ ]:
|
292a9fcfaafd9bf4242e7361e1a14186a445e3be | adityamon11/Python-Assignment-5 | /Assignment5_1.py | 183 | 3.703125 | 4 | def main():
x = int(input("Enter a number"));
pattern(x);
def pattern(x):
if(x>0):
print("*",end = " ");
x= x-1
pattern(x);
if __name__ == '__main__':
main(); |
d5567719ef9ffab667950a2aae828f15e31173a8 | hajikasasar/ProgrammingClass | /tugas_1.py | 327 | 3.578125 | 4 | A = int(input("Masukan Nilai pertama = "))
B = int(input("Masukan Nilai kedua = "))
C = int(input("Masukan Nilai ketiga = "))
D = A + B + C
E = A - B - C
F = A * B * C
G = A //B // C
print(" %d + %d + %d = "%(A,B,C),D)
print(" %d - %d - %d = "%(A,B,C),E)
print(" %d x %d x %d = "%(A,B,C),F)
print(" %d / %d / %d = "%(A,B,C),G) |
6a179ed75e88b38240b9e613989f4aa419189f77 | xellmann/SN_WD21_lektion-11-python-datenstrukturen | /guess_game_list.py | 1,028 | 3.734375 | 4 | import random
import json
secret = random.randint(1, 30)
count = 0
low_score = 0
with open("score.json", "r") as score:
score_list = json.loads(score.read())
score_list.sort()
out_list = ""
for x in range(len(score_list)):
out_list = out_list + str(score_list[x])
if x != len(score_list) - 1:
out_list += ", "
print("Guesses so far: {0}".format(out_list))
while True:
guess = int(input("Guess the secret number (between 1 and 30): "))
count += 1
if guess == secret:
print("You've guessed it - congratulations! It's number " + str(secret) + "!")
print("You have guessed {0} times.".format(count))
score_list.append(count)
with open("score.json", "w") as score:
score.write(json.dumps(score_list))
break
elif guess < secret:
print("Sorry, your guess is too small... The secret number is not " + str(guess))
else:
print("Sorry, your guess is too big... The secret number is not " + str(guess))
|
2a6b2f58988d3c4ed1833af008701244d218fd00 | Joseph-Antoun/Basic-ML | /src/Pr1.py | 4,976 | 3.609375 | 4 | import numpy as np
class LogisticRegression:
def __init__(self, X, y, x_labels, y_label, alpha=1, num_iters=100, stopping_criteria=1e-50):
"""
Constructor for the logistic regression class
:param X: the features data used for train
:param y: the classification data used for train
:param x_labels: the label of the features
:param y_label: the label for the results
:param alpha: learning rate
:param num_iters: number of iterations
:param stopping_criteria: threshold to stop the iterations of gradient descent
"""
self.n, self.m = np.shape(X)
self.X = X
self.y = y
self.x_labels = x_labels,
self.y_label = y_label,
self.w = np.random.rand(self.m, 1) # random weights initialization
self.num_iters = num_iters
self.alpha = alpha
self.epsilon = stopping_criteria
self.w_learned = np.zeros((self.m, 1))
self.h_cost = np.zeros((self.num_iters, 1))
def __repr__(self):
"""
This method overrides print(LogisticRegression) - as in line 129
"""
str_ = """
LogisticRegression\n
n = %s
m = %s
weights = %s
#iterations = %s
alpha = %s
epsilon = %s
x_labels = %s
y_label = %s
X = %s,
y = %s
""" % (self.n, self.m, self.w, self.num_iters, self.alpha, self.epsilon,
self.x_labels, self.y_label, self.X, self.y)
return str_
@staticmethod
def sigmoid(t):
"""
Calculate the sigmoid of the respective scalar
:param t: w^t.x_i
:return: sigmoid(t)
"""
sig = 1/(1+np.exp(-t))
return sig
def fit(self, X, y):
"""
This method is used to train (fit) the weight of the logistic regression model
:param X: training features data
:param y: classification training data
"""
x = X # this should get the features matrix without the results y
y = y # This should get the results of trained features
alpha = self.alpha
n, m = np.shape(X)
w_init = np.zeros((m, 1))
epsilon = self.epsilon
stop = 1
for i in range(0, self.num_iters):
z = y - self.sigmoid(np.matmul(x, w_init))
w = w_init + ((alpha / n) * (np.matmul(x.T, z)))
self.h_cost[i] = self.cost_computation(x, y, w)
if i != 0:
ar_stop = abs(w_init - w)
stop = np.amax(ar_stop)
w_init = w
if stop < epsilon:
print("threshold reached.\n")
break
self.w_learned = w_init
def predict(self, X):
"""
This method is used to predict the classification of the test data or new acquired features
:param X: features test or newly acquired
:return: the predicted classification of each set of features
"""
x = X
w = self.w_learned
predicted_y = np.around(self.sigmoid(np.matmul(x, w)))
return predicted_y
def cost_computation(self, X, y, w):
"""
This method is used to calculate the cost function for each iteration and record it
:param X: the data used to train
:param y: the classification used to train
:param w: the weight parameters calculated in that iteration
:return: the cost
"""
n, m = np.shape(X)
corr = 1e-5
q = self.sigmoid(np.matmul(X, w))
cost = (1/n) * ((np.matmul((-y).T, np.log(q + corr)))-(np.matmul((1-y).T, np.log(1-q + corr))))
return cost
# def main():
#
# # Load & clean the data
# file_path = '../data/wine/winequality-red.csv'
# raw_data = pd.read_csv(file_path, delimiter=';')
# clean_data = data_cleaning.get_clean_data(raw_data, verbose=False)
#
# # Create categoric y column
# # this is to skip SettingWithCopyWarning from Pandas
# clean_df = data_cleaning.get_clean_data(raw_data, verbose=False)
# clean_data = clean_df.copy()
# # Create the binary y column
# clean_data['y'] = np.where(clean_df['quality'] >= 6.0, 1.0, 0.0)
# # Drop the 'quality' column as it shouldn't be used to predict the wine binary rating
# clean_data.drop('quality', axis=1, inplace=True)
#
#
# # Split between X and y and create the numpy arrays
# y_vars = ['quality', 'y']
# x_vars = [var for var in clean_data.columns.tolist() if not var in y_vars]
# X, y = dataframe_to_narray(clean_data, x_vars, 'y')
#
# # Instanciate LogisticRegression
# lr = LogisticRegression(X, y, x_vars, 'y')
# print(lr)
#
#
# if __name__ == "__main__":
# main()
|
0fdc190bda0f1af4caf7354f380ce94134c70c78 | cizamihigo/guess_game_Python | /GuessTheGame.py | 2,703 | 4.21875 | 4 | print("Welcome To Guess: The Game")
print("You can guess which word is that one: ")
def check_guess(guess, answer):
global score
Still = True
attempt = 0
var = 2
global NuQuest
while Still and attempt < 3 :
if guess.lower() == answer.lower() :
print("\nCorrect Answer " + answer)
Still = False
score += 1
NuQuest += 1
else :
if attempt < 2 :
guess = input("Wrong answer. Try again. {0} chance(s) reamining . . .".format(var))
var = 2 - 1
attempt += 1
pass
if attempt == 3 :
print("The correct answer is " + answer)
NuQuest += 1
score = 0
NuQuest = 0
guess1 = input("Designe une oeuvre littéraire en vers: ")
check_guess(guess1,'Poème')
guess1 = ""
guess1 = input("Designe ce qui est produit par un ouvrier un artisan un travail quelconque: ")
check_guess(guess1,'Ouvrage')
guess1 = ""
guess1 = input("En anglais DOOM quelle est sa variance en français???: ")
check_guess(guess1,'destin')
guess1 = ""
guess1 = input("Désigne Un Habittant de Rome: ")
check_guess(guess1,'Romain')
guess1 = ""
guess1 = input("Ce qui forme Un angle droit est dit: ")
check_guess(guess1,'Perpendiculaire')
guess1 = ""
guess1 = input("Adjectif, désignant ce qui est rélatif aux femmes: ")
check_guess(guess1,'Féminin')
guess1 = ""
guess1 = input("Nom masculin désignant le corps céleste: ")
check_guess(guess1,'astre')
guess1 = ""
guess1 = input("Ma messe, la voici ! c'est la Bible, et je n'en veux pas d'autre ! de qui on tient cette citation ")
check_guess(guess1,"Jean Calvin")
guess1 = ""
guess1 = input("Le vin est fort, le roi est plus fort, les femmes le sont plus encore, mais la vérité est plus forte que tout. ! de qui tenons-nous cette citation ")
check_guess(guess1,"Martin Luther")
guess1 = ""
mpt = "plrboèem"
guess1 = input("Voici Un anagramme: " + str(mpt.upper()) +" Trouvez en un mot complet : ")
check_guess(guess1,"Problème")
guess1 = ""
mpt = "uonjcgnaiso"
guess1 = input("Voici Un anagramme: " + str(mpt.upper()) +" Trouvez en un mot complet : ")
check_guess(guess1,"conjugaison")
guess1 = ""
guess1 = input("Which is the fastest land animal?")
check_guess(guess1,"Cheetah")
##################################################
# OTHER QUESTIONS CAN BE ADDED LATERLY. #
##################################################
Prcentage = (score * 100 ) / NuQuest
print("Votre Pourcentage a ce test a ete de : {0}".format(Prcentage))
print("Your score is : " +str(score) + " Sur " + str(NuQuest))
######################################## THE END ###################################### |
ea51e701d670bd2039b3a5d624baa7f93852eaf2 | it3s/mootiro_form | /src/mootiro_form/utils/text.py | 389 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals # unicode by default
import random
def random_word(length, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
'abcdefghijklmnopqrstuvwxyz' \
'0123456789'):
'''Returns a random string of some `length`.'''
return ''.join((random.choice(chars) for i in xrange(length)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.