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 |
|---|---|---|---|---|---|---|
1a9bc5b9cf2bc221663353b194fcb5c9c061a7a0 | william-james-pj/LogicaProgramacao | /URI/1 - INICIANTE/Python/1117 - ValidacaoDeNotas.py | 202 | 3.859375 | 4 | x = media = 0
while x != 2:
nota = float(input())
if(nota < 0 or nota > 10):
print('nota invalida')
else:
x += 1
media += nota
print('media = {:.2f}'.format(media/2)) |
cd76e09d0338cbd191087f3a1c67f16c85d11cfa | william-james-pj/LogicaProgramacao | /URI/1 - INICIANTE/Python/1038 - Lanche.py | 346 | 3.625 | 4 | a, b = input().split()
a = int(a)
b = int(b)
if (a == 1):
print('Total: R$ {:.2f}'.format(4.0*b))
elif (a == 2):
print('Total: R$ {:.2f}'.format(4.5 * b))
elif (a == 3):
print('Total: R$ {:.2f}'.format(5.0 * b))
elif (a == 4):
print('Total: R$ {:.2f}'.format(2.0 * b))
elif (a == 5):
print('Total: R$ {:.2f}'.format(1.5 * b)) |
3463609f2a7ca21bf9ee2dbcc802fded8788e941 | william-james-pj/LogicaProgramacao | /URI/1 - INICIANTE/Python/1080 - MaiorEPosicao.py | 172 | 3.625 | 4 | x = 1
max = 0
pos = 0
while x <= 100:
num = int(input())
if(num > max):
max = num
pos = x
x += 1
print('{}'.format(max))
print('{}'.format(pos)) |
35d59e68b0d0a7b4b2fe1198e41a5668611ab382 | william-james-pj/LogicaProgramacao | /URI/1 - INICIANTE/Python/1078 - Tabuada.py | 82 | 3.734375 | 4 | n = int(input())
for x in range(1,11):
print("{} x {} = {}".format(x, n, x*n)) |
a960e241f175b08f1900e06299450e06a8796b11 | william-james-pj/LogicaProgramacao | /URI/1 - INICIANTE/Python/1012 - Area.py | 283 | 3.75 | 4 | a,b,c = input().split(' ')
a = float(a)
b = float(b)
c = float(c)
print('TRIANGULO: {:.3f}'.format((a*c)/2))
print('CIRCULO: {:.3f}'.format(pow(c,2)*3.14159))
print('TRAPEZIO: {:.3f}'.format(((a+b)*c)/2))
print('QUADRADO: {:.3f}'.format(b*b))
print('RETANGULO: {:.3f}'.format(a * b)) |
fe2f7feb571ce5667a5a82ba4df3ac7619c99843 | Maurisan4011/cursoPython2019 | /Primeros pasos/primera.py | 1,521 | 4.09375 | 4 | """ num1 = int(input('ingrese numero: '))
num2 = int(input('ingrese numero: '))
num3
print('la suma es: ', num1+num2) """
#la condicion el if va sin parentesis
condition=True
#ojo el True de Python es con mayuscula
dia=input('Ingrese dia de la semana por favor: ')
while condition:
if dia=='lunes':
print('in english is Monday')
break
dia=False
elif dia=='martes':
print('in english is Tuesday')
break
dia=False
elif dia=='miercoles':
print('in english is Wednesday')
break
dia=False
elif dia=='jueves':
print('in english is Thursday')
break
dia=False
elif dia=='viernes':
print('in english is Friday')
break
dia=False
elif dia=='sabado':
print('in english is Saturday')
break
dia=False
elif dia=='domingo':
print('in english is Sunday')
break
dia=False
else:
print('Not a day')
dia=input('Ingrese dia de la semana por favor: ')
""" dia=input('Ingrese dia de la semana por favor: ')
if dia=='lunes':
print('in english is Monday')
elif dia=='martes':
print('in english is Tuesday')
elif dia=='miercoles':
print('in english is Wednesday')
elif dia=='jueves':
print('in english is Thursday')
elif dia=='viernes':
print('in english is Friday')
elif dia=='sabado':
print('in english is Saturday')
elif dia=='domingo':
print('in english is Sunday')
else:
print('Not a day') """ |
889c48a32ac0ad38b2700c7bf271f1a29dd17fa6 | A01377451/Mision-10 | /Mision_10.py | 2,236 | 3.546875 | 4 | import matplotlib.pyplot as plot
#1 Nombres en mayusculas
def mostrarNombresMayusculas(nombreArchivo):
entrada = open(nombreArchivo, "r")
equipos = []
entrada.readline() # Bye linea 1
entrada.readline() # Bye linea 2
for linea in entrada:
linea = linea.upper()
datos=linea.split("&")
equipos.append(datos[0])
entrada.close()
return equipos
def mostarNombresYPuntos(nombreArchivo):
entrada = open(nombreArchivo, "r")
equipos = {}
entrada.readline() # Bye linea 1
entrada.readline() # Bye linea 2
for linea in entrada:
datos = linea.split("&")
equipos[datos[0]]=int(datos[8])
entrada.close()
return equipos
def mostrarEquiposBuenos(nombreArchivo):
entrada = open(nombreArchivo, "r")
equipos = []
entrada.readline() # Bye linea 1
entrada.readline() # Bye linea 2
for linea in entrada:
datos = linea.split("&")
if datos[4]<=3:
equipos.append(datos[0])
entrada.close()
return equipos
#4 Buscar equipos con error en puntos
def buscarError(nombreArchivo):
entrada = open(nombreArchivo, "r")
equipos =[]
entrada.readline() #Bye linea 1
entrada.readline() #Bye linea 2
for linea in entrada:
datos=linea.split("&")
sumaPuntos = int(datos[2])*3 + int(datos[3])
if sumaPuntos != int(datos[8]):
equipos.append(datos[0])
entrada.close()
return equipos
#7 Gráfica
def graficarPuntos(nombreArchivo):
entrada = open(nombreArchivo, "r")
entrada.readline() #Bye linea 1
entrada.readline() #Bye linea 2
listaEquipos =[]
listaPuntos =[]
for linea in entrada:
datos = linea.split("&")
listaEquipos.append(datos[0])
listaPuntos.append(int(datos[8]))
plot.plot(listaEquipos, listaPuntos)
plot.show()
entrada.close()
def main():
archivo="LigaMX.txt"
print(mostrarNombresMayusculas(archivo))
print(mostarNombresYPuntos(archivo))
error = buscarError(archivo)
print("Equipos con error:")
if len(error)>0:
for datos in error:
print (datos)
else:
print("No hay")
graficarPuntos(archivo)
main() |
23cd8dee4b74f65b3d154d24ca58b0e7f68e3a99 | mdaqshahab/OPA-Linux-Solutions | /python_IRA_24_July.py | 1,661 | 3.53125 | 4 | from collections import defaultdict
class Book:
def __init__(self, id,name,subject,price):
self.id = id
self.name = name
self.subject = subject
self.price = price
class Library:
def __init__(self,libname, booklist):
self.libname = libname
self.booklist = booklist
def findSubjectWiseBooks(self):
# d = defaultdict(0)
d = dict()
for i in self.booklist:
if i.subject in d.keys():
d[i.subject]+=1
else:
d[i.subject] = 1
# for i in self.booklist:
# d[i.subject]+=1
return d
def checkBookCategoryByPrice(self, b_id):
for i in self.booklist:
if i.id == b_id:
if i.price >= 1000:
return "High Price"
elif i.price >= 750 and i.price < 1000:
return "Medium Price"
elif i.price >=500 and i.price < 750:
return "Average Price"
else:
return "Low Price"
return None
if __name__ == '__main__':
num = int(input())
bl = []
for i in range(num):
a = int(input())
b = input()
c = input()
d = int(input())
obj = Book(a,b,c.lower(),d)
bl.append(obj)
f_id = int(input())
l_name = "abcd"
l_obj = Library(l_name,bl)
res1 = l_obj.findSubjectWiseBooks()
res2 = l_obj.checkBookCategoryByPrice(f_id)
for keys,value in res1.items():
print(keys + " " +str(value))
if res2 != None:
print(res2)
else:
print("Book Not Found")
|
d35bd127e519ec875b6be6ce4b4ccba42965589a | nandutejaswini/basic_programs | /venv/pattern.py | 124 | 4.0625 | 4 | x=1
while x<=5:
print("#",end="")
y=1
while y<=5:
print("#",end="")
y+=1
x+=1
print( )
|
5cf5dcba61e6b0473ea9409265d49dd6f6fda071 | nandutejaswini/basic_programs | /venv/area1.py | 100 | 3.875 | 4 | x=1
while x<=100:
if x%3!=0 and x%5!=0:
print(x)
x+=1
else:
x+=1
|
4ebf82d6b21b4732960e7f096a581690865eda72 | caroljunq/hackathon-globo | /trie.py | 751 | 3.640625 | 4 |
TERM = '**'
COUNT = '//'
class Trie (object):
def __init__ (self):
self.root = {}
self.root[COUNT] = 0
def add (self, a):
n = self.root
for i in a:
if i not in n:
n[i] = {}
n[i][COUNT] = 1
else:
n[i][COUNT] += 1
n = n[i]
n[TERM] = None
def find (self, a):
n = self.root
for i in a:
if i not in n:
return 0
n = n[i]
return n[COUNT]
@staticmethod
def countTerms (n):
t = 0
for i in n:
if i == TERM:
t += 1
else:
t += Contacts.countTerms(n[i])
return t
|
b0d523e2c88a10526e3ebb98ac771ad84d352260 | TPOCTO4KA/Homework-Python | /Задание 4 Урок 1.py | 607 | 4.15625 | 4 | '''
Пользователь вводит целое положительное число.
Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.
'''
while True:
number = input('Введите положительное число, пустая строка - окончание \n')
if number == '':
print('ну ты дурной')
break
else:
m = 0
for i in number:
if m < int(i):
m = int(i)
print(m)
|
a888361d9dd3b74a13385787fb297d2246d44c43 | TPOCTO4KA/Homework-Python | /Задание 2 Урок 2.py | 868 | 4.28125 | 4 | '''
Для списка реализовать обмен значений соседних элементов, т.е.
Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input()
'''
user_answer = input 'Введите список через запятую'
user_list = user_answer.split(',') # Разделение введенного списка по заяпятой
print user_list
idx = 0 # Вводим индекс
while idx < len(user_list[:-1]):
user_list[idx], user_list[idx+1] = user_list[idx+1], user_list[idx]
idx += 2
print user_list
|
6980003d73e19f96a7ec9e902fe4422f6849b682 | khadija-94/GIZ-pass-python | /python-pass.py | 445 | 3.609375 | 4 | class Solution:
def longest_palindromic(s: str) -> str:
# Create a string to store the result
palindrome = ''
for i in range(len(s)):
for j in range(len(s), i, -1):
# break
if len(palindrome) >= j - i:
break
# Update if match is found
elif s[i:j] == s[i:j][::-1]:
palindrome = s[i:j]
break
return palindrome
print(longest_palindromic("cbaba")) |
28ed32970dea5bf709fc7f0d839eb72962b58aac | Dobrydnyk-IP02/labs6 | /Лабораторна робота 6/Лабораторна_робота_6.py | 415 | 3.875 | 4 | def user_input():
n=int(input("n = "))
return n
def fact(k):
if k==0:
return 1
else:
return k*fact(k-1)
def draw_triangle(number):
for j in range(0, n+1):
for c in range(j+1):
print(fact(j) // (fact(c) * fact(j - c)), end=" ")
print()
def do_exercise(n):
if n>0:
draw_triangle(n)
else:
print("Error!!!")
n=user_input()
do_exercise(n) |
08df597dcb7313edca3c7a3f64c58600a19ea360 | Srisomdee/Python | /4.py | 608 | 3.796875 | 4 | print('โปรแกรมร้านค้าออนไลน์')
print('-'*30)
print('1.แสดงรายการสินค้า')
print('2.หยิบสินค้าเข้าตะกร้า')
print('3.แสดงรำยจ ำนวนและรำคำของสินค้ำที่หยิบ')
print('4. ปิดโปรแกรม')
a = (input('Enter yor Number :'))
def matee():
print('1.หมูปิ้ง\n2.ไก่ปิ้ง\n3.ตับหัน\n4.หมูหัน\n5.แมวย่าง')
matee()
if a == 's':
matee()
elif a == 's':
|
94a4e95a13557630c6e6a551f297a934b01e72f1 | gadamsetty-lohith-kumar/skillrack | /N Equal Strings 09-10-2018.py | 836 | 4.15625 | 4 | '''
N Equal Strings
The program must accept a string S and an integer N as the input. The program must print N equal parts of the string S if the string S can be divided into N equal parts. Else the program must print -1 as the output.
Boundary Condition(s):
2 <= Length of S <= 1000
2 <= N <= Length of S
Example Input/Output 1:
Input:
whiteblackgreen 3
Output:
white black green
Explanation:
Divide the string whiteblackgreen into 3 equal parts as white black green
Hence the output is white black green
Example Input/Output 2:
Input:
pencilrubber 5
Output:
-1
'''
#Your code below
a=(input().split())
l=len(a[0])
k=int(a[1])
m=l/k
if(l%k==0):
for i in range (0,l):
print(a[0][i],end="")
if (i+1)%(m)==0:
print(end=" ")
else:
print("-1")
|
cb332c445ab691639f8b6fb76e25bf95ba5f7af4 | gadamsetty-lohith-kumar/skillrack | /Remove Alphabet 14-10-2018.py | 930 | 4.28125 | 4 | '''
Remove Alphabet
The program must accept two alphabets CH1 and CH2 as the input. The program must print the output based on the following conditions.
- If CH1 is either 'U' or 'u' then print all the uppercase alphabets except CH2.
- If CH1 is either 'L' or 'l' then print all the lowercase alphabets except CH2.
- For any other values of CH1 then print INVALID.
Example Input/Output 1:
Input:
U v
Output:
A B C D E F G H I J K L M N O P Q R S T U W X Y Z
Example Input/Output 2:
Input:
L C
Output:
a b d e f g h i j k l m n o p q r s t u v w x y z
'''
#Your code below
l=input().split()
if l[0] in ('UuLl'):
if l[0]=='U' or l[0]=='u':
s='A'
l[1]=l[1].upper()
elif l[0]=='L' or l[0]=='l':
s='a'
l[1]=l[1].lower()
for i in range (0,26):
if s!=l[1]:
print(s,end=" ")
s=chr(ord(s)+1)
else:
print("INVALID")
|
cafcf8fb503b66873a3c0ccf0bb0ab458364f058 | forero/paulina | /python/hw3_2.py | 438 | 3.5 | 4 | import sys
def factor(n, d = 2):
if (n%d == 0):
return [d]+factor(n/d,d)
if (d*d > n):
if (n != 1):
return [n]
return []
return factor(n,d+1)
n = int(sys.argv[1])
if (not (0 < n <= 1000000)):
print "El numero no se encuentra en el intervalo"
f = factor(n)
if (len(f) == 2):
print "%d %d"%(f[0],f[1])
else:
print "El numero no tiene una factorizacion de dos primos"
|
51edd7c35ccfe2b7d07bcbfe97395f0c88c251fa | TAMU-BMEN207/Apple_stock_analysis | /OHLC_plots_using_matplotlib.py | 2,535 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 13 21:20:18 2021
@author: annicenajafi
Description: In this example we take a look at Apple's stock prices and write a
program to plot an OHLC chart. To learn more about OHLC plots visit
https://www.investopedia.com/terms/o/ohlcchart.asp
#Dataset Source:
downloaded from Kaggle ==> https://www.kaggle.com/meetnagadia/apple-stock-price-from-19802021?select=AAPL.csv
#Make sure you have studied: Numpy, Matplotlib, Pandas
"""
#import necessary modules
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
#Read csv file using pandas
df = pd.read_csv("/Users/annicenajafi/Downloads/AAPL.csv")
#let's take a look at our data
df.head()
'''
Let's only look at recent data more specifically from 2020 to the most recent data
But first we have to convert our date column to datetime type so we would be able to
treat it as date
'''
df['Date'] = pd.to_datetime(df['Date'])
df = df[df['Date'].dt.year > 2020]
#Hold on let's look at the dataframe again
df.head()
#Hmmm... Do you see that the index starts at 10100?
#Question: what problems may it cause if we don't reset the index?!
#Let's fix it so it starts from 0 like the original df
df.reset_index(inplace=True)
df.head()
#Let's define the x axis
x_vals = np.arange(0,len(df['Date']))
fig, ax = plt.subplots(1, figsize=(50,10))
'''
Let's iterate through the rows and plot a candle stick for every date
What we do is we plot a vertical line that starts from the low point and ends
at the high point for every date
'''
for idx, val in df.iterrows():
#Change the color to red if opening price is more than closing price
#Otherwise change it to green
if val['Open'] > val['Close']:
col = 'red'
else:
col ='green'
plt.plot([x_vals[idx], x_vals[idx]], [val['Low'], val['High']], color=col)
#add a horizontal line to the left to show the openning price
plt.plot([x_vals[idx], x_vals[idx]-0.05],
[val['Open'], val['Open']],
color=col)
#add a horizontal line to the right to show the closing price
plt.plot([x_vals[idx], x_vals[idx]+0.05],
[val['Close'], val['Close']],
color=col)
#Change the x axis tick marks
plt.xticks(x_vals[::50], df.Date.dt.date[::50])
#change the y label
plt.ylabel('USD')
#Change the title of the plot
plt.title('Apple Stock Price', loc='left', fontsize=20)
#let's show the plot
plt.show()
'''
Texas A&M University
BMEN 207
Fall 2021
'''
|
9359faab8429d81535d640576345ad09008b295f | cs-richardson/greedy-mando210 | /greedy.py | 468 | 3.953125 | 4 | """
"""
# Miki Ando
change = float(input("How much change is owed? "))
coin = 0
change = change * 100
remainder = change % 25
coin = (change - remainder) / 25
change = remainder
remainder = change % 10
coin = coin + (change - remainder) / 10
change = remainder
remainder = change % 5
coin = coin + (change - remainder) / 5
change = remainder
remainder = change % 1
coin = coin + (change - remainder) / 1
coin = str(int(coin))
print ("You have " + coin + " coins")
|
561527c84748d2f7b86aa33877f75ba22d1f46d3 | ceeblet/RESTful_fibonacci_service | /fib/tests/test_fibonacci.py | 963 | 3.75 | 4 | import unittest
from fib.fibonacci import Fibonacci
class test_fibonacci(unittest.TestCase):
def setUp(self):
self.fib = Fibonacci()
def test_min(self):
self.assertEqual(self.fib.fibonacci(1), [0])
def test_2(self):
self.assertEqual(self.fib.fibonacci(2), [0, 1])
def test_5(self):
self.assertEqual(self.fib.fibonacci(5), [0, 1, 1, 2, 3])
def test_negative(self):
self.assertRaisesRegex(ValueError, "invalid input: out of range", self.fib.fibonacci, -1)
def test_max(self):
self.assertRaisesRegex(ValueError, "invalid input: out of range", self.fib.fibonacci, 10001)
#
def test_float(self):
self.assertRaisesRegex(ValueError, "invalid input: not an integer", self.fib.fibonacci, 8.25)
#
def test_string(self):
self.assertRaisesRegex(ValueError, "invalid input: not an integer", self.fib.fibonacci, "hi")
if __name__ == '__main__':
unittest.main() |
897bb22c890cf7488a644b95482b042bc1c35439 | mateusandrade98/palestra-fazendo-as-maquinas-pensarem | /projeto.py | 2,664 | 3.5625 | 4 | # importar numpy
#
# variável linhas
# variável colunas
#
# classe Estado
# função recompensa
#
# classe RL
# função qLearning
# função posicaoLivres
#
# classe Jogo
# função renderizar
import numpy as np
linhas = 3
colunas = 3
class Estado:
def __init__(self, tabela):
self.table = tabela
def recompensa(self):
for i in range(linhas):
if sum(self.table[i, :]) == 3:
return 1
elif sum(self.table[i, :]) == -3:
return -1
for i in range(colunas):
if sum(self.table[i, :]) == 3:
return 1
elif sum(self.table[i, :]) == -3:
return -1
diagonal = sum(self.table[i, i] for i in range(colunas))
diagonal_reverse = sum(self.table[i, colunas - i - 1] for i in range(colunas))
diagonalValor = max(abs(diagonal), abs(diagonal_reverse))
if diagonalValor == 3:
if diagonal == 3:
return 1
if diagonal_reverse == 3:
return 1
return -1
return 0
class RL:
def __init__(self, tabela):
self.tabela = tabela
self.tmp = None
def qLearning(self):
livres = self.posicaoLivres()
if len(livres) == 0:
exit("Fim de jogo")
self.tmp = self.tabela
p = livres[0]
for _ in livres:
self.tmp[_] = 1
estado = Estado(self.tmp)
R = estado.recompensa()
if R == 1:
return self.tmp
elif R == -1:
self.tmp = self.tabela
continue
else:
self.tmp = self.tabela
continue
return self.tabela[p]
def posicaoLivres(self):
posicoes = []
for i in range(linhas):
for j in range(colunas):
if self.tabela[i, j] == 0:
posicoes.append((i, j))
return posicoes
class Jogo:
def __init__(self, tabela):
self.tabela = tabela
def renderizar(self):
for i in range(linhas):
print('-' * 12)
out = '|'
for j in range(colunas):
if self.tabela[i, j] == 1:
s = 'X'
elif self.tabela[i, j] == -1:
s = 'O'
else:
s = ' '
out += s + ' | '
print(out)
print('-' * 12)
tabela = [
[0, 0, 1],
[1, -1, 1],
[-1, 0, 0]
]
matriz = np.array(tabela)
rl = RL(matriz)
matriz = rl.qLearning()
jogo = Jogo(matriz)
jogo.renderizar()
|
9e70b2ca95c65dded65bba4e659278954c471131 | eajose/University-coding | /Códigos da faculdade/Cadastr_alunos_professores.py | 10,530 | 3.546875 | 4 | class professor:
listaProfessores = []
def __init__(self, nome, cpf, dataNascimento, endereco, telefone, status = 'Ativo'):
self.nome = nome
self. cpf = cpf
self.dataNascimento = dataNascimento
self.endereco = endereco
self. telefone = telefone
self.status = 'Ativo'
def Cadastrar(self):
self.listaProfessores = []
self.listaProfessores.append([self.nome, self.cpf, self.dataNascimento, self.endereco, self.telefone])
with open ('professores.txt', 'a+') as Prof:
Prof.write("--------------------------------------------\n")
Prof.write("Nome do professor: {}\n" .format(self.nome))
Prof.write("CPF: {}\n" .format(self.cpf))
Prof.write("Data de nascimento: {}\n" .format(self.dataNascimento))
Prof.write("Endereço: {}\n" .format(self.endereco))
Prof.write("Telefone: {}\n" .format(self.telefone))
Prof.write("--------------------------------------------\n")
def editar(self):
continua = True
doc = input("Digite o CPF para consulta: ")
while continua:
if doc in self.cpf:
print("+-----------------------------------------+")
print("| Digite os novos dados de contato |")
print("+-----------------------------------------+")
self.endereco = input("Digite o endereço: ").upper()
self.telefone = input("Digite o telefone: ")
print("+-----------------------------------+")
print("| Cadastro alterado com sucesso! |")
print("+-----------------------------------+")
continua = False
else:
print("CPF não cadastrado")
return doc
with open ('professores.txt', 'a+') as Prof:
Prof.write("--------------------------------------------\n")
Prof.write("Nome do professor: {}\n" .format(self.nome))
Prof.write("CPF: {}\n" .format(self.cpf))
Prof.write("Data de nascimento: {}\n" .format(self.dataNascimento))
Prof.write("Endereço: {}\n" .format(self.endereco))
Prof.write("Telefone: {}\n" .format(self.telefone))
Prof.write("--------------------------------------------\n")
def cancela_cad(self):
loc_cpf1 = input("Buscar CPF para cancelar o cadastro: ")
if loc_cpf1 in self.cpf:
self.status = 'Cancelado'
print('Status do cadastro: ', self.status)
else:
print("CPF não cadastrado!")
def ativa_cad(self):
loc_cpf2 = input("Buscar CPF para ativar o cadastro: ")
if loc_cpf2 in self.cpf:
self.status = 'Ativo'
print('Status do cadastro: ', self.status)
else:
print("CPF não cadastrado!")
class disciplina:
def __init__(self, nome, cargaHoraria, percentualPratico, percentualTeorico, professor):
self.nome = nome
self.cargaHoraria = cargaHoraria
self.percentualPratico = percentualPratico
self.percentualTeorico = percentualTeorico
self.professor = professor
auxDisciplinas = []
nomeDB = {}
cargaHorariaDB = {}
percPraticoDB = {}
percTeoricoDB = {}
professorDB = {}
with open("disciplinas.txt") as f:
aux = f.read().splitlines()
f.close()
for item in aux:
auxDisciplinas = item.split(";")
nomeDB[auxDisciplinas[0]] = auxDisciplinas[0]
cargaHorariaDB[auxDisciplinas[0]] = auxDisciplinas[1]
percPraticoDB[auxDisciplinas[0]] = auxDisciplinas[2]
percTeoricoDB[auxDisciplinas[0]] = auxDisciplinas[3]
professorDB[auxDisciplinas[0]] = auxDisciplinas[4]
if self.nome in nomeDB:
print("Disciplina já cadastrada!\n")
else:
DB = open("disciplinas.txt", "a")
nomeDB[self.nome] = self.nome
cargaHorariaDB[self.nome] = self.cargaHoraria
percPraticoDB[self.nome] = self.percentualPratico
percTeoricoDB[self.nome] = self.percentualTeorico
professorDB[self.nome] = self.professor
for j in nomeDB:
DB.write(nomeDB[j] + ';' + cargaHorariaDB[j] + ';' + percPraticoDB[j] + ';' + percTeoricoDB[j] + ';' + professorDB[j] + '\n')
DB.close()
print("Disciplina cadastrada com sucesso!\n")
class curso:
listaCurso = {}
cursosCadastrados = []
def __init__(self, nome, periodo, disciplinas = [], status = "Desativado"):
self.nome = nome + "*"
self.periodo = periodo
self.disciplinas = disciplinas
self.status = "Desativado"
self.listaCurso[self.nome] = {"Nome":self.nome, "Periodo":self.periodo, "Disciplina":self.disciplinas, "Status":self.status}
def cadastraCurso(self):
if self.listaCurso[self.nome]["Nome"] == "Desativado":
self.listaCurso[self.nome]["Status"] = "Ativado"
self.cursosCadastrados.append(self.nome)
self.listaCurso[self.nome]["Status"] = "Ativado"
with open('cursos.txt', 'a+') as Cursos:
Cursos.write(self.nome + ";" + self.periodo + ";")
Cursos.close()
def Cursos(self):
with open('cursos.txt', 'r') as Cursos:
for item in Cursos:
item = item.splitlines()
for item in item:
item2 = item.split(";")
if '*' in item2:
self.cursosCadastrados.append(item2)
Cursos.close()
return self.cursosCadastrados
def exibeCursos(self):
for curso in self.cursosCadastrados:
print("*"*20)
print("Nome: {}" .format(self.listaCurso[curso]["Nome"]))
print("Periodo: {}" .format(self.listaCurso[curso]["Periodo"]))
print("Disciplinas {}" .format(self.listaCurso[curso]["Disciplina"]))
print("Status {}" .format(self.listaCurso[curso]["Status"]))
print("*"*20)
def alteraStatus(self):
if self.listaCurso[self.nome]["Status"] == "Ativado":
self.listaCurso[self.nome]["Status"] = "Desativado"
elif self.listaCurso[self.nome]["Status"] == "Desativado":
self.listaCurso[self.nome]["Status"] = "Ativado"
class Aluno:
def __init__(self, nome, cpf, dataNascimento, endereco, telefone, cadastrado = True):
self.nome = nome
self.cpf = cpf
self.dataNascimento = dataNascimento
self.endereco = endereco
self.telefone = telefone
self.cadastrado = True
def cadastrarAluno(self):
c = 0
d = 0
f = open('alunos.txt', '+a')
print("Cadastre um aluno!")
n = input("Digite o nome do(a) aluno(a): ")
m = input("Digite o RA do(a) aluno(a): ")
c = "Aluno(a): " + n + "\n"
d = "RA......: " + m + "\n"
f.write("--------------------------------------------\n")
f.write(c)
f.write(d)
f.write("--------------------------------------------\n")
def editarAluno(self):
g = open('dados_alunos.txt', '+a')
edi = str(input("Caso deseje alterar os dados do aluno, digite SIM: "))
if edi in ['sim', 's', 'S', 'SIM']:
self.nome = str(input("Nome: "))
self.cpf = str(input("CPF: "))
self.dataNascimento = str(input("Data de Nascimento: "))
self.endereco = str(input("Endereço: "))
self.telefone = str(input("Telefone: "))
g.write("--------------------------------------------\n")
g.write("Nome..............: {}\n" .format(self.nome))
g.write("CPF...............: {}\n" .format(self.cpf))
g.write("Data de Nascimento: {}\n" .format(self.dataNascimento))
g.write("Endereço..........: {}\n" .format(self.endereco))
g.write("Telefone..........: {}\n" .format(self.telefone))
g.write("--------------------------------------------\n")
print("Dados atualizados!")
else:
print("Dados não foram alterados!")
def desabilita(self):
self.cadastrado = False
#print(self.cadastrado)
def habilitar(self):
self.cadastrado = True
#print(self.cadastrado)
class MatriculaAluno:
def __init__(self, RA = None):
self.RA = None
def gera_RA(self):
with open("RA.txt", 'r') as ListaRA:
line = ListaRA.readlines()
ultimo = len(line)
guia_RA = line[ultimo - 1]
self.RA = int (guia_RA) + 1
ListaRA.close()
with open("RA.txt", 'a') as ListaRA:
ListaRA.write(str('\n{}' .format(self.RA)))
ListaRA.close()
return self.RA
class MatriculaProf:
def __init__(self, RF = None):
self.RF = None
def gera_RF(self):
with open("RF.txt", 'r') as ListaRF:
line = ListaRF.readlines()
ultimo = len(line)
guia_RF = line[ultimo - 1]
self.RF = int (guia_RF) + 1
ListaRF.close()
with open("RF.txt", 'a') as ListaRF:
ListaRF.write(str('\n{}' .format(self.RF)))
ListaRF.close()
return self.RF
RA = MatriculaAluno()
RF = MatriculaProf()
y = Aluno("Renato", 37804343850, "09/12/1989", "rua Augusto Baer", 976334348)
y.cadastrarAluno()
y.editarAluno()
y.desabilita()
y.habilitar()
p = professor("Irineu","045.548.658-98","05/04/1994","SP","994568475")
p.Cadastrar()
p.editar()
p.cancela_cad()
p.ativa_cad()
ADS = curso("ADS", "Manha",["Logica", "Programacao"])
ADS.cadastraCurso()
Banco = curso("Banco", "Noite", ["Banco de dados", "Linguagem SQL"])
Banco.cadastraCurso()
SI = curso("SI", "Tarde", ["Modelagem", "Gestao"])
SI.cadastraCurso()
Banco.alteraStatus()
SI.exibeCursos()
|
86d5a563242ff695c74d0a232a54463830ef714f | s-nilesh/Leetcode-May2020-Challenge | /18-PermutationsInString.py | 1,841 | 3.78125 | 4 | #PROBLEM
# Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
# Example 1:
# Input: s1 = "ab" s2 = "eidbaooo"
# Output: True
# Explanation: s2 contains one permutation of s1 ("ba").
# Example 2:
# Input:s1= "ab" s2 = "eidboaoo"
# Output: False
# Note:
# The input strings only contain lower case letters.
# The length of both given strings is in range [1, 10,000].
#SOLUTION-1
from collections import Counter
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
counts = Counter(s1)
l = len(s1)
for i in range(len(s2)):
if counts[s2[i]] > 0:
l -= 1
counts[s2[i]] -= 1
if l == 0:
return True
start = i + 1 - len(s1)
if start >= 0:
counts[s2[start]] += 1
if counts[s2[start]] > 0:
l += 1
return False
#SOLUTION-2
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
s1h=0
s2h=0
if len(s2)<len(s1):
return False
for i in s1:
s1h+=hash(i)
for i in range(len(s1)):
s2h+=hash(s2[i])
if s1h==s2h:
return True
if len(s2)>len(s1):
for j in range(len(s1),len(s2)):
s2h+=hash(s2[j])-hash(s2[j-len(s1)])
if s1h==s2h:
return True
return False
#SOLUTION-3
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
m=""
for i in range(0,len(s2)-len(s1)+1):
m=s2[i:i+len(s1)]
if Counter(m)==Counter(s1):
return True
return False |
68bb040d0e9828fc34660de7b3d0d4ffa6e36d2d | s-nilesh/Leetcode-May2020-Challenge | /14-ImplementTrie(PrefixTree).py | 1,854 | 4.40625 | 4 | #PROBLEM
# Implement a trie with insert, search, and startsWith methods.
# Example:
# Trie trie = new Trie();
# trie.insert("apple");
# trie.search("apple"); // returns true
# trie.search("app"); // returns false
# trie.startsWith("app"); // returns true
# trie.insert("app");
# trie.search("app"); // returns true
# Note:
# You may assume that all inputs are consist of lowercase letters a-z.
# All inputs are guaranteed to be non-empty strings.
#SOLUTION
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = {}
self.marker = '$'
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
cur = self.children
for c in word:
if c not in cur:
cur[c] = {}
cur = cur[c]
cur[self.marker] = True
def __search__(self, word):
cur = self.children
for c in word:
if c not in cur:
return False
cur = cur[c]
return cur
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
found = self.__search__(word)
return found and len(found) > 0 and self.marker in found
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
if len(prefix) == 0: return True
found = self.__search__(prefix)
return found and len(found) > 0
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix) |
d61be39fac7557857065fd0537cda8623e9486ee | maggielaughter/tester_school_dzien_5 | /conditionals.py | 189 | 3.8125 | 4 | x = -10
if x < 0 and x % 2 == 0:
print('x ujemny parzysty')
elif x < 0:
print ('x ujemny nieparzysty')
else:
print('to je inna liczba')
y = ' '
if y:
print ('y niepusty') |
f86a42e476362420a6151a09d32eac415a1b7754 | maggielaughter/tester_school_dzien_5 | /data_test.py | 519 | 3.796875 | 4 | """year = 2018
#month = 6
#day = 12
day_in_month=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 100 != 0 and year % 4 == 0:
print('rok przestępny')
elif year % 100 == 0 and year % 400 != 0:
print('rok nie jest przestępny')
day_in_month[i-1]"""
day_in_month=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day=1
month=6
year=2018
if day <= day_in_month[month-1]:
day=+1
else:
day = 1
if month <= len(day_in_month):
month = 1
else:
month = month
print(day,'-',month,'-',year) |
1bc46f78503f255096c9c50c41bc1d18df8ef11f | maggielaughter/tester_school_dzien_5 | /loop_while.py | 520 | 3.609375 | 4 | z = 0
while z < 10:
print(z)
z+=1
print(' ')
n=64
i = 0
square=False
done = False
current_sqaure=i**2
while not done:
if i**2 == n:
square=True
done=True
elif current_sqaure > n:
done = True
i +=1
current_sqaure=i**2
if square:
print('n jest kwadratem')
else:
print('n nie jest kwadratem')
####
while current_sqaure <= n:
if current_sqaure ==n:
square=True
i +=1
if square:
print('n jest kwadratem')
else:
print('n nie jest kwadratem') |
cc40241cb01e43421bb730e6f91c013434a13815 | maggielaughter/tester_school_dzien_5 | /poprawne_dni.py | 560 | 3.734375 | 4 | MONTH_LENGTHS=(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
year = 2016
month = 12
day = 31
#przestępność roku i ilość dni w lutym
if month != 2:
max_day = MONTH_LENGTHS[month-1]
elif (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
max_day = 29
else:
max_day = 28
if day < max_day:
new_year, new_month, new_day = year, month, day +1
elif month == 12:
new_year = year + 1
new_month = 1
new_day = 1
else:
new_year, new_month, new_day = year, month+1, 1
print('Następna data: ', (new_day, new_month, new_year)) |
2a68c6231ea0b26361d03e8195bb872a07f90fe5 | moidshaikh/hackerranksols | /leetcode/leetcode#6.zigzag-conversion.py | 659 | 3.53125 | 4 | # https://leetcode.com/problems/zigzag-conversion/
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
row_map = { row:"" for row in range(1,numRows+1) }
row = 1
up = True
for letter in s:
row_map[row] += letter
if (row==1) or ((row < numRows) and up):
row += 1
up = True
else:
row -= 1
up = False
converted = ''
for row in range(1, numRows +1):
converted += row_map[row]
return converted
|
fddf5b28a8d6146825ab3d2edf6f6bdea81b700c | moidshaikh/hackerranksols | /hackerrank/love-letter-mystery.py | 471 | 3.84375 | 4 | '''
Solution to hackerrank challenge
https://www.hackerrank.com/challenges/the-love-letter-mystery
'''
from itertools import islice
def count_operations(word):
diff = lambda x, y: abs(ord(x) - ord(y))
median = len(word) // 2
pairs = zip(word, reversed(word))
operations = sum(diff(x, y) for x, y in islice(pairs, median))
return operations
word_count = int(input())
for _ in range(word_count):
word = input()
print(count_operations(word)) |
70022b766cfe1edeeb269c43257befe117f61eee | moidshaikh/hackerranksols | /crazyPythonImplementations/geeks.py | 209 | 3.953125 | 4 | #Function to locate the occurrence of the string x in the string s.
def strstr(s,x):
#code here
l = r = 0
for i in range(len(x)):
print(x[i])
print(strstr('abcdfcde','cde')) |
dfe853f4fb89cbefa48f5190f50d268d0d7cdc45 | moidshaikh/hackerranksols | /leetcode/blind75/lc167_two_sum_II_input_array_is_sorted.py | 394 | 3.5 | 4 | class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l, r = 0, len(numbers) - 1 # left and right pointers
while l < r:
current_sum = numbers[l] + numbers[r]
if current_sum > target:
r -= 1
elif current_sum < target:
l += 1
else:
return l + 1, r + 1
|
976090191c9b6316fccdd2167fbb576cab178933 | moidshaikh/hackerranksols | /leetcode/lc20_valid_parantheses.py | 478 | 3.6875 | 4 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
closeOpen = { ')':'(', ']':'[', '}':'{'}
for c in s:
if c in closeOpen:
if stack and stack[-1] == closeOpen[c]:
stack.pop()
else:
return False
else:
stack.append(c)
return True if not stack else False
s = Solution()
print(s.isValid(''))
print(s.isValid('{([[()]]}'))
|
da6291311cba04b222f094c1dfb0120f089ef5b5 | moidshaikh/hackerranksols | /crazyPythonImplementations/quick_sort.py | 468 | 3.78125 | 4 | from typing import List
import random
def quick_sort(li: List) -> List:
l = len(li)
if l <= 1:
return li
else:
pivot = li.pop()
higher, lower = [], []
for i in li:
if i > pivot:
higher.append(i)
else:
lower.append(i)
return quick_sort(lower) + [pivot] + quick_sort(higher)
print(quick_sort([3,2,1]))
print(quick_sort([3,6,8,13,53,6,8,5,4,23,23,65,23,7,3,2,3,2,1]))
print(quick_sort([3,2,3,4,36,65,3,23,12,6,4,34,12,4,1]))
|
5e27c3e8302972736844b10e738aa097bdd65ea0 | moidshaikh/hackerranksols | /hackerearth/practice/implementations/min_max_3.py | 970 | 3.6875 | 4 | # Given an array of integers . Check if all the numbers between minimum and maximum number in array exist's within the array .
#
# Print 'YES' if numbers exist otherwise print 'NO'(without quotes).
#
# Input:
#
# Integer N denoting size of array
#
# Next line contains N space separated integers denoting elements in array
#
# Output:
#
# Output your answer
# l = int(input())
# n = [int(i) for i in input().split()]
# mn = min(n)
# mx = max(n)
# ary = [i for i in range(mn, mx+1)]
# # for i in range(len(ary)):
# # if n[i] in ary:
# # ary.remove(n[i])
# # if len(ary) == 0:
# # print('YES')
# # else:
# # print('NO')
# print(mn, mx)
# print('ary', ary)
# print('n', n)
# for i in range(len(ary)):
# if ary[i] not in n:
# print('NO')
# sys.exit(1)
# print("YES")
import sys
n = int(input())
a=list(map(int,input().split()))
for i in range(min(a),max(a)+1):
if i not in a:
print('NO')
sys.exit()
print('YES') |
9daee1e18f4a1ed1b117ccfe7ca5f08e7c4faeac | moidshaikh/hackerranksols | /hackerearth/test1.py | 642 | 3.734375 | 4 | # def power(num, x):
# if x == 1:
# return num
# else:
# return num ** power(num, x-1)
def power(base,exponent):
exponent = bin(exponent)[2:][::-1]
result = 1
for i in range(len(exponent)):
if exponent[i] is '1':
result *= base
base *= base
return result
def solution():
x, k, m = list(map(int, input().split()))
# print(type(x), type(k), type(m))
# print(power(x, k) % m)
res = 1
# xx = x
for __ in range(k):
res *= pow(x,res)
print(res % m)
test_cases = int(input())
while test_cases > 0:
solution()
test_cases -= 1 |
8d306396734059730f71bece06988393ebc2c3d7 | moidshaikh/hackerranksols | /interview_questions/c1.py | 835 | 3.859375 | 4 | # binary divide. if number is even half it. if no. is odd add 1 to it. count steps it takes to go to zero.
# input: 3: output: 4
def bin_divide(s):
# n = bin(s,2)
# steps = 0
# while n != 0:
# steps += 1
# input(n)
# if n == 1:
# break
# if n%2 == 0:
# n = n//2
# else:
# n += 1
steps = 0
for c in s:
if c == '0':
steps += 1
else:
steps += 2
return steps
# print(bin_divide(bin(7)[2:]))
def num_divide(n):
# n = bin(s,2)
steps = 0
while n != 0:
steps += 1
if n == 1:
break
if n%2 == 0:
n = n//2
else:
n += 1
return steps
def test(n):
print(num_divide(n))
print(bin_divide(bin(n)[2:]))
test(11)
|
63d1c88374e05f3336681af6cb9b4c67cd225020 | PykeChen/pythonBasicGramer | /zip.py | 202 | 3.8125 | 4 | matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
print(list(zip(*matrix)))
prices = [1, 3, 4, 5]
pt = [[[0 for _ in range(2)] for _ in range(2)] for i in prices]
print(prices[-1]) |
61ce86d7c0880053babdcab9d4dfc07f59e502b0 | PykeChen/pythonBasicGramer | /Function.py | 280 | 3.765625 | 4 |
valueBefore = 10
array = [2, "4", 5]
def testFunParamsValue(x):
x = 100
def modifyFunParamsValue(x):
x[1] = 444
testFunParamsValue(valueBefore)
print('valueAfter' + str(valueBefore))
modifyFunParamsValue(array)
for i in array:
print('arrary value ' + str(i))
|
d31db0c5c0344a0b306fa0a623378b2cf64f8615 | PykeChen/pythonBasicGramer | /fileio.py | 338 | 3.5625 | 4 |
for line in open("BasicGrammar/dict.py"):
# print line, #python2 用法
print(line)
with open('BasicGrammar/dict.py', 'r') as f:
# read_data = f.read()
# print(read_data)
for line in f:
print(line)
# 写入文件
with open('BasicGrammar/wirte_test.py', 'w+') as f:
f.write('This is a line by my code')
|
d532d34c6b8d7c523ec14f8dc974ffc4eef4ddf2 | shensg/porject_list | /python3/python_dx/pyc2.py | 882 | 4.125 | 4 |
class Start():
name = 'hello'
age = 0
# 区分开 '类变量' '实际变量'
# 类变量和类关联在一起的
# 实际变量是面向对象的
def __init__(self, name, age): #构造函数 __int__是双下滑线 '_'
# 构造函数
# 初始化对象的属性
self.name = name
self.age = age
# print('student')
def do_homework(self): #普通函数
print('homework')
# 行为 和 特征
# class Printer():
# def print_file(self):
# print('name:' + self.name)
# print('age:' + str(self.age))
start1 = Start('蓝色', 18)
print(start1.name)
start2 = Start('红色', 16)
print(start2.name,start2.age)
# start3 = Start('兰', 15)
print(Start.name)
# print(id(start1))
# print(id(start2))
# print(id(start3))
# start1.print_file()
|
001ad3c4641323110d64eac09317cf16a2cb8eb9 | JoyceTsiga/2020Finals | /Password_Manager_GJK.py | 3,398 | 3.734375 | 4 | import random
from GenClass import PWGenerator
passwordList = []
logInPW = []
def choice():
ui = input("do you want to create a Password (y or n) ")
if ui == "y":
userPassword = input("Put your new Password: ")
passwordList.append(userPassword)
elif ui == "n":
PWGenerator()
def logIn():
username = input("What is ur username ")
password = input("What is ur password ")
if password in logInPW:
choice()
def signUp():
first = input("What is ur First name? ")
last = input("What is ur last name ? ")
username = input("What is ur username ")
password = input("What is ur password ")
print(f'''
Your first name is {first}
Your Last name is {last}
Your UserName is {username}
Your Password is {password}
''')
logInPW.append(password)
# def category():
# def updateData():
def PWGenerator():
return PWGenerator(f'Here is your new generated password:\n{PWGenerator().createPW()}')
def pwChecker(password):
passwordToCheck=password
specialCharacters=[33,35,36,37,38,40,41,64,94]
points = 0
artPoints = ""
lossPoints = ""
# [length,lower,upper,numbers,specials]
reqList=[False, False,False,False, False ]
# abandon this idea because the for loop would reset the values everytime
passCheckList=[]
#.append() adds items to the list
for i in range(len(passwordToCheck)):
passCheckList.append(False)
# print(passCheckList)
if(len(passwordToCheck)>=6 and len(passwordToCheck)<=16):
reqList[0]=True
#iterating through passwordToCheck
for i in range(len(passwordToCheck)):
#print(passwordToCheck[i])
#a-z on ASCII is .... range(97,123) remember range(start,stopANDnotInclude)
#if the password has a lower letter then add a point
if(ord(passwordToCheck[i]) in range(97,123)):
passCheckList[i]=True
reqList[1]=True
#A-Z on ASCII is .... range(65,91)
#if the password has a Capital letter then add a point
if(ord(passwordToCheck[i]) in range(65,91)):
passCheckList[i]=True
reqList[2]=True
#0-9 on ASCII is .... range(48,58)
#if the password has a number then add a point
if(ord(passwordToCheck[i]) in range(48,58)):
passCheckList[i]=True
reqList[3]=True
#if the password has a special character then add a point
if(ord(passwordToCheck[i]) in specialCharacters):
passCheckList[i]=True
reqList[4]=True
for i in reqList:
if i == True:
points += 1
artPoints += "#"
else:
lossPoints += "-"
score = [artPoints+lossPoints]
strengthList.append(score)
print(points, "Out of 5 points =", artPoints + lossPoints)
if(False in passCheckList or False in reqList): #this calculates how many points the password would get
return "Your password did not meet the requirements"
else:
return "Your password met the requirements"
print("Welcome to your Password Manager")
ui = input("Do you need to make an account (y or n) ")
if ui == "y":
signUp()
elif ui == "n":
logIn() |
c3a179e5eb2c5046e6c241182e99b190155bd53a | dtczhl/dtc-KITTI-For-Beginners | /python/object_viewer.py | 5,883 | 3.546875 | 4 | #!/usr/bin/env python
""" Draw labeled objects in images
Author: Huanle Zhang
Website: www.huanlezhang.com
"""
import matplotlib.pyplot as plt
import matplotlib.image as mping
import numpy as np
import os
import pptk
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
MARKER_COLOR = {
'Car': [1, 0, 0], # red
'DontCare': [0, 0, 0], # black
'Pedestrian': [0, 0, 1], # blue
'Van': [1, 1, 0], # yellow
'Cyclist': [1, 0, 1], # magenta
'Truck': [0, 1, 1], # cyan
'Misc': [0.5, 0, 0], # maroon
'Tram': [0, 0.5, 0], # green
'Person_sitting': [0, 0, 0.5]} # navy
# image border width
BOX_BORDER_WIDTH = 5
# point size
POINT_SIZE = 0.005
def show_object_in_image(img_filename, label_filename):
img = mping.imread(img_filename)
with open(label_filename) as f_label:
lines = f_label.readlines()
for line in lines:
line = line.strip('\n').split()
left_pixel, top_pixel, right_pixel, bottom_pixel = [int(float(line[i])) for i in range(4, 8)]
box_border_color = MARKER_COLOR[line[0]]
for i in range(BOX_BORDER_WIDTH):
img[top_pixel+i, left_pixel:right_pixel, :] = box_border_color
img[bottom_pixel-i, left_pixel:right_pixel, :] = box_border_color
img[top_pixel:bottom_pixel, left_pixel+i, :] = box_border_color
img[top_pixel:bottom_pixel, right_pixel-i, :] = box_border_color
plt.imshow(img)
plt.show()
def show_object_in_point_cloud(point_cloud_filename, label_filename, calib_filename):
pc_data = np.fromfile(point_cloud_filename, '<f4') # little-endian float32
pc_data = np.reshape(pc_data, (-1, 4))
pc_color = np.ones((len(pc_data), 3))
calib = load_kitti_calib(calib_filename)
with open(label_filename) as f_label:
lines = f_label.readlines()
for line in lines:
line = line.strip('\n').split()
point_color = MARKER_COLOR[line[0]]
_, box3d_corner = camera_coordinate_to_point_cloud(line[8:15], calib['Tr_velo_to_cam'])
for i, v in enumerate(pc_data):
if point_in_cube(v[:3], box3d_corner) is True:
pc_color[i, :] = point_color
v = pptk.viewer(pc_data[:, :3], pc_color)
v.set(point_size=POINT_SIZE)
def point_in_cube(point, cube):
z_min = np.amin(cube[:, 2], 0)
z_max = np.amax(cube[:, 2], 0)
if point[2] > z_max or point[2] < z_min:
return False
point = Point(point[:2])
polygon = Polygon(cube[:4, :2])
return polygon.contains(point)
def load_kitti_calib(calib_file):
"""
This script is copied from https://github.com/AI-liu/Complex-YOLO
"""
with open(calib_file) as f_calib:
lines = f_calib.readlines()
P0 = np.array(lines[0].strip('\n').split()[1:], dtype=np.float32)
P1 = np.array(lines[1].strip('\n').split()[1:], dtype=np.float32)
P2 = np.array(lines[2].strip('\n').split()[1:], dtype=np.float32)
P3 = np.array(lines[3].strip('\n').split()[1:], dtype=np.float32)
R0_rect = np.array(lines[4].strip('\n').split()[1:], dtype=np.float32)
Tr_velo_to_cam = np.array(lines[5].strip('\n').split()[1:], dtype=np.float32)
Tr_imu_to_velo = np.array(lines[6].strip('\n').split()[1:], dtype=np.float32)
return {'P0': P0, 'P1': P1, 'P2': P2, 'P3': P3, 'R0_rect': R0_rect,
'Tr_velo_to_cam': Tr_velo_to_cam.reshape(3, 4),
'Tr_imu_to_velo': Tr_imu_to_velo}
def camera_coordinate_to_point_cloud(box3d, Tr):
"""
This script is copied from https://github.com/AI-liu/Complex-YOLO
"""
def project_cam2velo(cam, Tr):
T = np.zeros([4, 4], dtype=np.float32)
T[:3, :] = Tr
T[3, 3] = 1
T_inv = np.linalg.inv(T)
lidar_loc_ = np.dot(T_inv, cam)
lidar_loc = lidar_loc_[:3]
return lidar_loc.reshape(1, 3)
def ry_to_rz(ry):
angle = -ry - np.pi / 2
if angle >= np.pi:
angle -= np.pi
if angle < -np.pi:
angle = 2 * np.pi + angle
return angle
h, w, l, tx, ty, tz, ry = [float(i) for i in box3d]
cam = np.ones([4, 1])
cam[0] = tx
cam[1] = ty
cam[2] = tz
t_lidar = project_cam2velo(cam, Tr)
Box = np.array([[-l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2],
[w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2],
[0, 0, 0, 0, h, h, h, h]])
rz = ry_to_rz(ry)
rotMat = np.array([
[np.cos(rz), -np.sin(rz), 0.0],
[np.sin(rz), np.cos(rz), 0.0],
[0.0, 0.0, 1.0]])
velo_box = np.dot(rotMat, Box)
cornerPosInVelo = velo_box + np.tile(t_lidar, (8, 1)).T
box3d_corner = cornerPosInVelo.transpose()
# t_lidar: the x, y coordinator of the center of the object
# box3d_corner: the 8 corners
return t_lidar, box3d_corner.astype(np.float32)
if __name__ == '__main__':
# updates
IMG_DIR = '/home/dtc/Data/KITTI/data_object_image_2/training/image_2'
LABEL_DIR = '/home/dtc/Data/KITTI/data_object_label_2/training/label_2'
POINT_CLOUD_DIR = '/home/dtc/Data/KITTI/save'
CALIB_DIR = '/home/dtc/Data/KITTI/data_object_calib/training/calib'
# id for viewing
file_id = 0
img_filename = os.path.join(IMG_DIR, '{0:06d}.png'.format(file_id))
label_filename = os.path.join(LABEL_DIR, '{0:06d}.txt'.format(file_id))
pc_filename = os.path.join(POINT_CLOUD_DIR, '{0:06d}.bin'.format(file_id))
calib_filename = os.path.join(CALIB_DIR, '{0:06d}.txt'.format(file_id))
# show object in image
show_object_in_image(img_filename, label_filename)
# show object in point cloud
show_object_in_point_cloud(pc_filename, label_filename, calib_filename) |
b518c37abc704263af5e80be90d48cd8668f986c | koef/prometheus | /ls5/test2_counter.py | 379 | 3.53125 | 4 | #!/usr/bin/env python
def counter(a, b):
c = 0
processed = ""
for c1 in range(len(str(a))):
cur_dig_a = str(a)[c1:c1+1]
for c2 in range(len(str(b))):
cur_dig_b = str(b)[c2:c2+1]
if cur_dig_a == cur_dig_b and processed.find(cur_dig_b) == -1:
processed += cur_dig_b
c += 1
return c
print counter(1233211, 12128)
|
6b406f7baf1fb65983f39c12da8c24e0faf76d42 | koef/prometheus | /ls7/7.3/superstr_class.py | 836 | 3.65625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'koef'
class SuperStr(str):
def __init__(self, source_string):
self.src_str = source_string
def is_repeatance(self, s):
if not isinstance(s, str) or self.src_str == "":
return False
src_len = len(self.src_str)
s_len = len(s)
s_repeats = self.src_str.count(s)
if s_len * s_repeats == src_len:
return True
else:
return False
def is_palindrom(self):
s = self.src_str
if not isinstance(s, str):
return False
reversed_str = s[::-1]
if s.lower().replace(' ', '') == reversed_str.lower().replace(' ', '') or s == "":
return True
else:
return False
s2 = SuperStr('')
print s2.is_repeatance('')
print s2.is_repeatance('a') |
b321c9e98b1ed72a4f1a4ab118786d5a84fc3101 | koef/prometheus | /ls4/test4_happy.py | 580 | 3.78125 | 4 | #!/usr/bin/env python
import sys
fist_num = int(sys.argv[1])
sec_num = int(sys.argv[2])
counter = 0
for cur_num in range(fist_num, sec_num + 1):
cur_num = str(cur_num)
while len(cur_num) != 6:
cur_num = "0" + cur_num
sum_first_three_digit = 0
for digit in cur_num[0:3]:
sum_first_three_digit = sum_first_three_digit + int(digit)
sum_last_three_digit = 0
for digit in cur_num[3:6]:
sum_last_three_digit = sum_last_three_digit + int(digit)
if sum_first_three_digit == sum_last_three_digit:
counter = counter + 1
print counter
|
88329cac7ea25d94d0f83fc355cfd8bf5ff33b77 | Software-Focus-Group/SFG-20 | /Beautiful-Soup/pokemon.py | 1,883 | 3.984375 | 4 | from bs4 import BeautifulSoup #used for scraping
import requests #used to send get requests to fetch the data
from pprint import pprint #pretty print dicts
# website to be scraped ; the pokemon database
url = "https://pokemondb.net/pokedex/game/gold-silver-crystal"
# We are hoping to scrape the website and collect the following items
# -Name
# -pokedex number
# -link to its page
# Getting the contents of the website
PokeContent = requests.get(url)
# Making the soup using the html.We extract the content using the .text method variable and we're using the python inbuilt html parser
PokeSoup = BeautifulSoup(PokeContent.text,"html.parser")
# Empty list to store the pokemon
Pokemon = []
# Pokemon are in <main> --> <div class="infocard-list infocard-list-pkmn-lg"> ---> <div class=infocard>
# and since theres only one main we use the " . " to get inside it
# We also can search for partial strings to be matched , so no need to type entire class name
PokeCollection = PokeSoup.main.find("div",class_="infocard-list")
# Finds all the <div> containg the string "infocard" in their class name as they contain each individual pokemon
PokeList = PokeCollection.findAll("div",class_="infocard")
print("NUMBER OF POKEMON === ",len(PokeList),sep="",end="\n\n")
for item in PokeList:
# Temporary dictionary to hold the details
temp = {}
# All the details are found in the <span> with class name text-muted
temp["name"] = item.find("span",class_="text-muted").a.text
temp["number"] = item.find("span",class_="text-muted").small.text
# Appending the base url "https://pokemondb.net/" to the link of the pokemon so that we get the full url
temp["link"] = "https://pokemondb.net" + item.find("span",class_="text-muted").a.attrs["href"]
Pokemon.append(temp)
for pokemon in Pokemon:
pprint(pokemon)
print("--------------------------------------------------")
|
b65511f55175d9a2b431481a4f4694fb6d5ea0d7 | AmaniAbbas/Coursera-Guided-Projects | /P2_pythonDataStructure/Lists1.py | 991 | 3.9375 | 4 | # افتح الملف وخزنه بمتغير
fh = open('romeo.txt')
# انشاء قائمة فارغة
final_list = []
# استخدام الحلقة للتعامل مع سطور الملف سطرا سطرا
for line in fh:
# لتقسيم الكلمات في السطر لعناصر في قائمة split استخدم
words= line.split()
#استخدم الحلقة مرة أخرى للتعامل مع عناصر القائمة التي تحتوي على الكلمات
for word in words:
# اختبر اذا ما كانت الكلمة موجودة في القائمة النهائية أم لا
if word in final_list:
# للدوران في الحلقة إذا وجدت الكلمة في القائمة continue استخدم
continue
# قم بإضافة الكلمة للقائمة الرئيسية
final_list.append(word.lower())
# اطبع القائمة مرتبة أبجديا
final_list.sort()
print(final_list)
|
112f32096314b4e30ec1bba4037c96aba7be18c4 | manan057/python-code-exercises | /tic-tac-toe.py | 624 | 3.9375 | 4 |
# Global Variables
quit = False
grid = [[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']]
def print_grid(some_grid):
print('\n------- Tic Tac Toe -------')
print('\n col: 1 2 3')
for row in range(len(some_grid)):
print('row ' + str(row + 1) + ': ' + str(some_grid[row]) + '\n')
if __name__ == '__main__':
while not quit:
print_grid(grid)
print('You are "X". Please enter row and column number when prompt!')
row = int(input('Please enter a row number: '))
col = int(input('Please enter a column number: '))
grid[row-1][col-1] = 'X' |
e8b6ef6df71a327b6575593166873c6576f78f7b | SirazSium84/100-days-of-code | /Day1-100/Day1-10/Bill Calculator.py | 911 | 4.1875 | 4 | print("Welcome to the tip calculator")
total_bill = float(input("What was the total bill? \n$"))
percentage = int(input(
"What percentage tip would you like to give ? 10, 12 or 15?\n"))
people = int(input("How many people to split the bill? \n"))
bill_per_person = (total_bill + total_bill * (percentage)/100)/(people)
print("Each person should pay : ${:.2f}".format(bill_per_person))
# # print(123_567_789)
# # 🚨 Don't change the code below 👇
# age = input("What is your current age?")
# # 🚨 Don't change the code above 👆
# # Write your code below this line 👇
# def time_left(age):
# years_left = 90 - int(age)
# months_left = years_left * 12
# weeks_left = years_left * 52
# days_left = years_left * 365
# return days_left, weeks_left, months_left
# days, weeks, months = time_left(age)
# print(f"You have {days} days, {weeks} weeks, and {months} months left")
|
bd01fa079eecee6d85c8fe2a0517934a6cd2e6da | SirazSium84/100-days-of-code | /Day1-100/Day1-10/caeser_cipher.py | 2,628 | 3.96875 | 4 | from art import logo
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print(logo)
keep_going = "yes"
def caesar(text, shift, direction):
if direction == "encode":
cipher_text = ""
if shift > len(alphabet):
while shift > len(alphabet):
shift = shift % 26
for x in text:
if x == " ":
cipher_text += x
elif x.isalpha():
if x.isupper():
if alphabet.index(x.lower()) + shift > len(alphabet) - 1:
cipher_text += alphabet[alphabet.index(
x.lower()) + shift - 26].upper()
else:
cipher_text += alphabet[alphabet.index(
x.lower()) + shift].upper()
else:
if alphabet.index(x) + shift > len(alphabet) - 1:
cipher_text += alphabet[alphabet.index(
x) + shift - 26]
else:
cipher_text += alphabet[alphabet.index(x) + shift]
else:
cipher_text += x
print(f"The encoded text is {cipher_text}")
elif direction == "decode":
decoded_text = ""
for x in text:
if x == " ":
decoded_text += x
elif x.isalpha():
if x.isupper():
if alphabet.index(x.lower()) - shift < 0:
decoded_text += alphabet[alphabet.index(
x.lower()) - shift + 26].upper()
else:
decoded_text += alphabet[alphabet.index(
x.lower()) + shift].upper()
else:
if alphabet.index(x) - shift < 0:
decoded_text += alphabet[alphabet.index(
x) - shift + 26]
else:
decoded_text += alphabet[alphabet.index(x) - shift]
else:
decoded_text += x
print(f"The decoded text is {decoded_text}")
while keep_going == "yes":
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n")
shift = int(input("Type the shift number:\n"))
caesar(text, shift, direction)
keep_going = input(
"Type 'yes' if you want to go again. Otherwise type 'no'\n").lower()
if keep_going == "no":
print("Good Bye!")
|
c4c157cb35651a555f1ed29fe7d6d60ca45df0cf | JohTorm/IoT_Perusteet | /ovi.py | 1,682 | 3.8125 | 4 | oviKiinni = True
oviLukittu = True
oviTila = ""
if oviKiinni == False and oviLukittu == False:
oviTila = "Auki ja Avoinna"
elif oviKiinni == True and oviLukittu == False:
oviTila = "Kiinni ja Avoinna"
elif oviKiinni == True and oviLukittu == True:
oviTila = "Kiinni ja Lukittu"
print("ovi on " + oviTila)
if oviKiinni == True and oviLukittu == True:
userInput = int(input("Mitäs tehdään? Avaa lukko ja ovi = 1, avaa vain lukko = 2"))
if userInput == 1:
oviTila = "Auki ja Avoinna"
oviKiinni = False
oviLukittu = False
print("ovi on " + oviTila)
elif userInput == 2:
oviTila = "Kiinni ja Avoinna"
oviKiinni = True
oviLukittu = False
print("ovi on " + oviTila)
if oviKiinni == False and oviLukittu == False:
userInput = int(input("Ovi on auki, mitäs tehdään? Sulje ovi = 1, sulje ja lukitse = 2"))
if userInput == 1:
oviTila = "Kiinni ja Avoinna"
oviKiinni = True
oviLukittu = False
print("ovi on " + oviTila)
elif userInput == 2:
oviTila = "Kiinni ja lukittu"
oviKiinni = True
oviLukittu = True
print("ovi on " + oviTila)
if oviKiinni == True and oviLukittu == False:
oviTila = "Kiinni ja Avoinna"
userInput = int(input("Mitäs tehdään? Avaa ovi = 1, lukitse ovi = 2"))
if userInput == 1:
oviTila = "Auki ja Avoinna"
oviKiinni = False
oviLukittu = False
print("ovi on " + oviTila)
elif userInput == 2:
oviTila = "Kiinni ja Lukittu"
oviKiinni = True
oviLukittu = True
print("ovi on " + oviTila) |
e6a272e49d2ff1c46f54d851168436d9328b0952 | pddona/python_ejemplos | /PROBLEMAS resueltos/08_primo_4.py | 1,371 | 3.984375 | 4 | #!/usr/bin/env pyhton
# __*__ coding:utf-8 __*__
def main():
import time
print("NÚMERO PRIMO")
numero = int(input("Escriba un número entero mayor que 1: "))
inicio = time.time()
if numero <= 1:
print("¡Le he pedido un número entero mayor que 1!")
else:
if numero == 1 or numero == 2 or numero == 3 or numero == 5 or numero == 7:
print("{} es primo".format(numero))
else:
resto = numero % 10
if resto == 0 or resto == 2 or resto == 4 or resto == 5 or resto == 6 or resto == 8:
print("{} no es primo".format(numero))
else: # resto == 1 , 3 , 7 , 9
contador = 0
limite = round(numero ** 0.5)
for i in range(1, limite + 1):
if numero % i == 0:
contador = contador + 1
if contador > 1:######################
break ###########################
if contador == 1:
print("{} es primo".format(numero))
else:
print("{} no es primo".format(numero))
final = time.time()
print("Tiempo de ejecución = {} segundos".format(final-inicio))
if __name__ == "__main__":
main()
|
883689898073925fb628776b9b49a7be4bb5a9eb | okfn/webstore | /webstore/security.py | 2,027 | 3.5625 | 4 | """
Very simple authorization system.
The basic idea is that any request must come from a user in one of the
following three groups:
* 'world': anonymous visitors
* 'user': logged-in users
* 'self': users who want to access their own resources
For each of these events, a set of actions is queried to see if the user
is allowed to perform a given query.
"""
from flask import g
from webstore.helpers import WebstoreException
from webstore.helpers import entry_point_function
from webstore.core import app
def has(user, database, action):
has_function = entry_point_function(app.config['HAS_FUNCTION'],
'webstore.authz')
return has_function(user, database, action)
def default_has(user, database, action):
matrix = app.config['AUTHORIZATION']
if user == g.user:
capacity = 'self'
elif g.user is not None:
capacity = 'user'
else:
capacity = 'world'
capacity_actions = matrix[capacity]
return action in capacity_actions
def require(user, database, action, format):
""" Require the current user to have the right to
execute `action` on `database` of `user`. If this
right is not given, raise an exception.
"""
if not has(user, database, action):
raise WebstoreException('No permission to %s %s' % (action, database),
format, state='error', code=403)
# These are for testing and can be used as mock authentication handlers.
def always_login(request):
if 'Authorization' in request.headers:
authorization = request.headers.get('Authorization')
authorization = authorization.split(' ', 1)[-1]
user, password = authorization.decode('base64').split(':', 1)
return user
return request.environ.get('REMOTE_USER')
def never_login(request):
if 'Authorization' in request.headers:
raise WebstoreException('Invalid username or password!', None,
state='error', code=401)
return None
|
d0d4b7ee1bd93b246d31571ab880fc87c361da8c | Wolffoner/7541-Algoritmos-y-Programacion-II | /Clases/13-Salon-Python/salon.py | 1,491 | 3.59375 | 4 | #!/usr/bin/env python3
from pokemon import *
from entrenador import *
nombre = "salones/salon_estandar.txt"
class Salon:
def __init__(self):
self.entrenadores = {}
def agregarEntrenadorSiExiste(self, entrenador):
if entrenador:
self.entrenadores[entrenador.nombre] = entrenador
def mostrarSalon(self):
for entrenador in self.entrenadores.values():
print("Entrenador: {} ({})".format(entrenador.nombre, entrenador.victorias))
for pokemon in entrenador.equipo:
print("\tPokemon: " + pokemon.nombre)
def obtenerEntrenadorSi(self, condicion):
return list(filter(condicion, self.entrenadores.values()))
def obtenerMasGanadores(self, n):
return self.obtenerEntrenadorSi(lambda e: e.victorias >= n)
def leer_salon(nombre):
archivo = open(nombre, "r")
salon = Salon()
entrenadorActual = None
for linea in archivo:
campos = linea.split(";")
pokemon = parsearPokemon(campos)
entrenador = parsearEntrenador(campos)
if pokemon and entrenadorActual:
entrenadorActual.agregarPokemon(pokemon)
elif entrenador:
salon.agregarEntrenadorSiExiste(entrenadorActual)
entrenadorActual = entrenador
else:
print("Esto no deberia pasar")
salon.agregarEntrenadorSiExiste(entrenadorActual)
archivo.close()
return salon
salon = leer_salon(nombre)
salon.mostrarSalon()
|
13297b32a90ce8fb19a2e5e05a288c2f879071a7 | lingfeng23/pythonStudy | /03function/function.py | 921 | 4.03125 | 4 | import math
# 调用函数
print(abs(-100))
# 定义函数
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(-20))
# 空函数
def pop():
pass
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
xy = move(100, 100, 60, math.pi / 6)
print(x, y)
print(xy)
# 函数的参数
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5))
print(power(5, 3))
def calc(numbers):
summy = 0
for n in numbers:
summy = summy + n * n
return summy
print(calc([1, 2, 3]))
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
person('Bob', 20, city='Beijing')
# 递归函数
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(5))
|
c71ee8a7038b1215dc9d9a06e424e4d1efc83f5c | TestardR/Python-Tips_Tricks | /large_numbers.py | 174 | 3.8125 | 4 | # we wan use underscore to help us read large numbers
num1 = 10_000_000_000_0000
num2 = 1000_000_000
total = num1 + num2
# we can format numbers output
print(f'{total:,}')
|
59fe77eafe43dcfe8848c6c969f254a414573952 | kma501/JISAssasins | /question16_By_Mohiuddin.py | 311 | 3.71875 | 4 | class Find:
def get(self,val):
self.val=val
self.val=self.val+1
print(self.val,"-->",chr(self.val))
self.val=self.val-2
print(self.val, "-->", chr(self.val))
give=input("give character you want :")
print(give, "-->", ord(give))
obj=Find()
obj.get(ord(give)) |
9ceb5314cf594e5237d837a82f517375a0831be2 | kma501/JISAssasins | /question9_By_Mohiuddin.py | 519 | 3.859375 | 4 | class Calculate:
r=0
sum=0
def find(self,val):
self.val=val
self.last=(self.val)%10
self.val = int(self.val / 10)
while(self.val!=0):
self.r=(self.val)%10
self.sum=self.sum+self.r
self.val=int(self.val/10)
self.first=self.r
def display(self):
print("the value of sum of first and last digits is :",self.first+self.last)
num=int(input("enter the number :\n"))
obj=Calculate()
obj.find(num)
obj.display() |
56c921dc0d0c41fc94e8ad49f4798d1fbc84f3f5 | nickpostma/monopoly2 | /property.py | 1,467 | 3.53125 | 4 | import unittest
import player
class test(unittest.TestCase):
def test_property_class_callable(self):
self.assertIsNotNone(Property(1,''))
def test_property_should_have_id(self):
id = 5
self.assertEqual(Property(id,'').Id,id)
def test_property_should_have_Name(self):
name = 'Boardwalk'
self.assertEqual(Property(1, name).Name, name)
def test_player_should_have_money(self):
cost = 500
self.assertEqual(Property(1,'',cost).Cost, cost)
def test_player_with_funds_should_purchase(self):
p = player.Player()
prop = Property(1,'Boardwalk',200)
self.assertEqual(prop.Purchase(p), True)
def test_player_without_funds_cannot_purchase(self):
p = player.Player()
prop = Property(1,'Boardwalk',70000)
self.assertEqual(prop.Purchase(p), False)
pass
class Property_interface():
def __init__(self, index):
self.Index = index
self.Players = []
class Property():
def __init__(self, id, name, cost = 0):
self.Index = id
self.Name = name
self.Cost = cost
self.Players = []
self.Owner = {}
def Purchase(self, p):
if p.Money > self.Cost:
p.Money = p.Money - self.Cost
self.Owner = p
return True
return False
pass
if __name__ == '__main__':
import os
os.system('cls')
unittest.main(verbosity = 2)
|
b39534ece8562f881c6aae6f8da3bd1dfcc618b5 | shyaboi/fedexshippingmacro | /clipboardtest.py | 396 | 3.96875 | 4 | from tkinter import Tk
import keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print(Tk().clipboard_get())
print('You Pressed A Key!')
break # finishing the loop
except:Priscilla Contreras
break # |
beb1dafc2bc4b6acbbf4759691708ffd703ded66 | leafcis/Tensorflow | /Python and Numpy/numpy different access.py | 210 | 3.59375 | 4 | import numpy as np
matrix = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
print(matrix[np.array([0, 2, 4])]) # [1. 3. 5.]
print(matrix < 3) # [True True False False False False]
print(matrix[matrix < 3]) # [1. 2.] |
78086a49fad55a6102472216103821a2b2eeebb0 | jsmienk/BDCSH | /lesson7.9/mapper.py | 460 | 3.5 | 4 | #!/usr/bin/python
"""mapper.py"""
import sys
from datetime import datetime
# Outputs key: WEEKDAY value: SALES
def mapper():
for line in sys.stdin:
row = line.split('\t')
if len(row) < 5:
continue
# date
date = row[0]
# sales
sales = row[4]
# find weekday
weekday = datetime.strptime(date, "%Y-%m-%d").weekday()
print('{0}\t{1}'.format(weekday, sales))
mapper() |
24a69e38cdc2156452898144165634fd6579ef6c | keyurgolani/exercism | /python/isogram/isogram.py | 564 | 4.375 | 4 | def is_isogram(string):
"""
A function that, given a string, returns if the string is an isogram or not
Isogram is a string that has all characters only once except hyphans and
spaces can appear multiple times.
"""
lookup = [0] * 26
# Assuming that the string is case insensitive
string = string.lower()
for char in string:
if 'a' <= char <= 'z':
index = ord(char) - ord('a')
if lookup[index] == 0:
lookup[index] = 1
else:
return False
return True
|
cc935d4973347b1fb603cdecc5be422dcfa05a68 | andyyang777/PY_LC | /977_双指针法.py | 1,792 | 3.640625 | 4 | # Given an array of integers A sorted in non-decreasing order, return an array o
# f the squares of each number, also in sorted non-decreasing order.
#
#
#
#
# Example 1:
#
#
# Input: [-4,-1,0,3,10]
# Output: [0,1,9,16,100]
#
#
#
# Example 2:
#
#
# Input: [-7,-3,2,3,11]
# Output: [4,9,9,49,121]
#
#
#
#
# Note:
#
#
# 1 <= A.length <= 10000
# -10000 <= A[i] <= 10000
# A is sorted in non-decreasing order.
#
#
# Related Topics Array Two Pointers
# 👍 1477 👎 98
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
# 思路,双指针
# 因为就是数组已经是sort了的,排序好的,所以负数部分的话平方后是降序,而正数部分平方后就是升序
# 所以只需要搞两个指针,一个正走,一个反走即可
# 然后要考虑就是负数的走完了,正数没走完,还有正数走完了负数没走完,这两种情况
N = len(A)
positive = 0
while positive < N and A[positive] < 0:
positive += 1
negative = positive - 1 # 负指针的初始位置就是positive的左边一个
res = []
while 0 <= negative and positive < N:
if A[negative] ** 2 < A[positive] ** 2:
res.append(A[negative] ** 2)
negative -= 1
else:
res.append(A[positive] **2)
positive += 1
while negative >= 0:
res.append(A[negative] ** 2)
negative -= 1
while positive < N:
res.append(A[positive] ** 2)
positive += 1
return res
# leetcode submit region end(Prohibit modification and deletion)
|
629492dcbe85d8173cd8baac2abd8d6dcae35696 | andyyang777/PY_LC | /Tree/105_Binary Tree preorder and inorder.py | 1,890 | 4.09375 | 4 | !!!!!!!!!!!!!
超级牛逼的解释,很容易理解
https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/xiong-mao-shua-ti-python3-xian-xu-zhao-gen-hua-fen/
网址在上
# Given preorder and inorder traversal of a tree, construct the binary tree.
#
# Note:
# You may assume that duplicates do not exist in the tree.
#
# For example, given
#
#
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
#
# Return the following binary tree:
#
#
# 3
# / \
# 9 20
# / \
# 15 7
# Related Topics Array Tree Depth-first Search
# 👍 3955 👎 105
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
# 参考网址,无敌牛逼解法
# https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/xiong-mao-shua-ti-python3-xian-xu-zhao-gen-hua-fen/
if not preorder or not inorder: return
root = TreeNode(preorder[0])
root_idx = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1: 1 + root_idx], inorder[:root_idx])
root.right = self.buildTree(preorder[1 + root_idx:], inorder[root_idx + 1:])
return root
# inorder.index(preorder[0]) 这一步获取根的索引值,题目说树中的各个节点的值都不相同,也确保了这步得到的结果是唯一准确的
# 而且这个idx还能当长度用相当于 左+根 的长度,因为 左+根 和 根+左 是等长的。
# leetcode submit region end(Prohibit modification and deletion)
|
6a750dfd043559d6adcc25f3cb85ed8c3ae92840 | andyyang777/PY_LC | /79_BestwayIthink.py | 2,543 | 3.9375 | 4 | # Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where
# "adjacent" cells are those horizontally or vertically neighboring. The same let
# ter cell may not be used more than once.
#
# Example:
#
#
# board =
# [
# ['A','B','C','E'],
# ['S','F','C','S'],
# ['A','D','E','E']
# ]
#
# Given word = "ABCCED", return true.
# Given word = "SEE", return true.
# Given word = "ABCB", return false.
#
#
#
# Constraints:
#
#
# board and word consists only of lowercase and uppercase English letters.
# 1 <= board.length <= 200
# 1 <= board[i].length <= 200
# 1 <= word.length <= 10^3
#
# Related Topics Array Backtracking
# 👍 4431 👎 204
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
# (x-1,y)
# (x,y-1) (x,y) (x,y+1)
# (x+1,y)
directions = [(0,-1), (-1,0),(0,1),(1,0)]
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board) ## 行数
n = len(board[0]) ##列数
marked = [[False for _ in range(n)] for _ in range(m)] ## 一开始都设为假,说明都没有访问过
for i in range(m): #对每个格子都从头开始搜索
for j in range(n):
if self.search_word(board, word, 0, i, j, marked, m, n):
return True
return False
def search_word(self,board, word, index, x, y, marked, m, n):
if index == len(word) - 1:
return board[x][y] == word[index]
# 如果当index已经搞到word的最后一个了,就说明前面都还没出错
# 所以此时如果board里这时候的x,y还和word里最后一个匹配,就说明全都匹配
# 中间的匹配里,再继续搜索
if board[x][y] == word[index]:
# 先暂存这个位置,如果不成功的话则释放掉这个位置
marked[x][y] = True
for direction in self.directions:
new_x = x + direction[0]
new_y = y + direction[1]
if 0 <= new_x < m and 0 <= new_y < n \
and not marked[new_x][new_y] \
and self.search_word(board,word,index+1, new_x, new_y, marked, m,n):
return True
marked[x][y] = False
return False
# (x-1,y)
# (x,y-1) (x,y) (x,y+1)
# (x+1,y)
# leetcode submit region end(Prohibit modification and deletion)
|
0e096a85876325977c5da4d202736c944cdc380c | andyyang777/PY_LC | /415_AddString.py | 902 | 3.640625 | 4 | # Given two non-negative integers num1 and num2 represented as string, return th
# e sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to int
# eger directly.
#
# Related Topics String
# 👍 1193 👎 302
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
d = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
res1, res2 = 0,0
for x in num1:
res1 = res1*10 + d[x]
for x in num2:
res2 = res2*10 + d[x]
return str(res1 + res2)
# leetcode submit region end(Prohibit modification and deletion)
|
180882089ce430d730b4e37012838039dfc9a9dd | andyyang777/PY_LC | /130_SurroundedRegions.py | 2,606 | 4 | 4 | # Given a 2D board containing 'X' and 'O' (the letter O), capture all regions su
# rrounded by 'X'.
#
# A region is captured by flipping all 'O's into 'X's in that surrounded region
# .
#
# Example:
#
#
# X X X X
# X O O X
# X X O X
# X O X X
#
#
# After running your function, the board should be:
#
#
# X X X X
# X X X X
# X X X X
# X O X X
#
#
# Explanation:
#
# Surrounded regions shouldn’t be on the border, which means that any 'O' on th
# e border of the board are not flipped to 'X'. Any 'O' that is not on the border
# and it is not connected to an 'O' on the border will be flipped to 'X'. Two cell
# s are connected if they are adjacent cells connected horizontally or vertically.
#
# Related Topics Depth-first Search Breadth-first Search Union Find
# 👍 2090 👎 708
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
整体的思路就是说,找到各个边界上的O,并且dfs他们,继续找到与边界O相连的O,把这些o先变成B,然后最后遍历全部元素,把o变成x,把b变回o去
时间复杂度:O(n \times m)O(n×m),其中 nn 和 mm 分别为矩阵的行数和列数。深度优先搜索过程中,每一个点至多只会被标记一次。
空间复杂度:O(n \times m)O(n×m),其中 nn 和 mm 分别为矩阵的行数和列数。主要为深度优先搜索的栈的开销。
if not board or not board[0]:
return ## 边界条件判断
row = len(board)
column = len(board[0])
def dfs(x,y):
board[x][y] = "B"
for nx, ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 1<=nx<row and 1<=ny<column and board[nx][ny] == "O":
dfs(nx,ny)
for i in range(row):
# 第一列
if board[i][0] == "O":
dfs(i,0)
# 最后一列
if board[i][column-1] == "O":
dfs(i,column-1)
for j in range(column):
if board[0][j] == "O":
dfs(0,j)
if board[row-1][j] == "O":
dfs(row-1,j)
for i in range(row):
for j in range(column):
if board[i][j] == "O":
board[i][j] = "X"
if board[i][j] == "B":
board[i][j] = "O"
# leetcode submit region end(Prohibit modification and deletion)
|
c35a79b70e706476522bbb2d65513ab40cf115aa | andyyang777/PY_LC | /394_DecodeString.py | 1,681 | 3.796875 | 4 | # Given an encoded string, return its decoded string.
#
# The encoding rule is: k[encoded_string], where the encoded_string inside the
# square brackets is being repeated exactly k times. Note that k is guaranteed to
# be a positive integer.
#
# You may assume that the input string is always valid; No extra white spaces,
# square brackets are well-formed, etc.
#
# Furthermore, you may assume that the original data does not contain any digit
# s and that digits are only for those repeat numbers, k. For example, there won't
# be input like 3a or 2[4].
#
#
# Example 1:
# Input: s = "3[a]2[bc]"
# Output: "aaabcbc"
# Example 2:
# Input: s = "3[a2[c]]"
# Output: "accaccacc"
# Example 3:
# Input: s = "2[abc]3[cd]ef"
# Output: "abcabccdcdcdef"
# Example 4:
# Input: s = "abc3[cd]xyz"
# Output: "abccdcdcdxyz"
# Related Topics Stack Depth-first Search
# 👍 3583 👎 177
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def decodeString(self, s: str) -> str:
curnum = 0
curstring = ''
stack = []
for char in s:
if char == '[':
stack.append(curstring)
stack.append(curnum)
curstring = ''
curnum = 0
elif char ==']':
prenum = stack.pop()
prestring = stack.pop()
curstring = prestring + prenum*curstring
elif char.isdigit():
curnum = curnum * 10 + int(char)
else:
curstring += char
return curstring
# leetcode submit region end(Prohibit modification and deletion)
|
d784502cb007208ac67e4bb140d308084eee549c | SrishtiToora/DS-codes | /BST.py | 6,165 | 3.828125 | 4 | import _collections
class node:
def __init__(self,key,left=None,right=None,parent=None):
self.key=key
self.left_child = left
self.right_child = right
self.parent = parent
class binary_search_tree(node):
def __init__(self):
self.root=None
self.size=0
self.height=0
def length(self):
return self.size
def insert(self,key):
if self.root==None:
self.root=node(key)
self.height +=1
else:
self._insert(key,self.root)
self.size += 1
def _insert(self,key,currentnode):
if key<currentnode.key:
if currentnode.left_child==None:
currentnode.left_child=node(key,parent=currentnode)
else:
self._insert(key,currentnode.left_child)
elif key > currentnode.key:
if currentnode.right_child==None:
currentnode.right_child=node(key,parent=currentnode)
else:
self._insert(key,currentnode.right_child)
else:
print ("key already in tree")
def findMin(self,key):
current=self.get(key)
while current.left_child!=None:
current = current.left_child
return current.key
def findSuccessor(self,key):
currentnode=self.get(key)
succ = None
suc=None
if currentnode.right_child!=None:
succ = self.findMin(currentnode.right_child.key)
else:
if currentnode.parent!=None:
if currentnode.parent.left_child==currentnode:
suc = currentnode.parent.key
else:
currentnode.parent.right_child = None
suc = self.findSuccessor(currentnode.parent.key)
currentnode.parent.right_child =currentnode
succ=suc
return succ
def get(self, key):
if self.root!=None:
res = self._get(key, self.root)
if res.key!=None:
return res
else:
return None
else:
return None
def _get(self, key, currentnode):
if currentnode==None:
return None
elif currentnode.key == key:
return currentnode
elif key < currentnode.key:
return self._get(key, currentnode.left_child)
else:
return self._get(key, currentnode.right_child)
def contains(self, key):
if self.get(key)!=None:
return True
elif self.get(key) == None:
return False
def remove(self,currentnode):
if currentnode.right_child==None and currentnode.left_child==None:
if currentnode.parent.left_child==currentnode:
currentnode.parent.left_child=None
elif currentnode.parent.right_child==currentnode:
currentnode.parent.right_child=None
elif currentnode.right_child==None or currentnode.left_child==None:
if currentnode.left_child!=None:
if currentnode.parent.left_child==currentnode:
currentnode.left_child.parent=currentnode.parent
currentnode.parent.left_child=currentnode.left_child
if currentnode.parent.right_child==currentnode:
currentnode.left_child.parent=currentnode.parent
currentnode.parent.right_child=currentnode.left_child
elif currentnode.right_child!=None:
if currentnode.parent.left_child==currentnode:
currentnode.parent.left_child=currentnode.right_child
currentnode.right_child.parent=currentnode.parent
if currentnode.parent.right_child==currentnode:
currentnode.parent.right_child=currentnode.right_child
currentnode.right_child.parent=currentnode.parent
elif currentnode.right_child!=None and currentnode.left_child!=None:
succKey=self.findSuccessor(currentnode.key)
succ=self.get(succKey)
self.removingSuccessor(succ)
currentnode.key=succ.key
def removingSuccessor(self,rnode):
if rnode.right_child == None and rnode.left_child == None:
if rnode.parent.left_child==rnode:
rnode.parent.left_child=None
else:
rnode.parent.right_child=None
elif rnode.right_child == None or rnode.left_child == None:
if rnode.right_child!=None:
rnode.right_child.parent=rnode.parent
rnode.parent.left_child=rnode.right_child
def deletingaAKey(self,delkey):
delnode=self.get(delkey)
self.remove(delnode)
def getHeight(self,root): #node perimeter
if root!=None:
if root.left_child!=None and root.right_child!= None:
return 1+max(self.getHeight(root.left_child),self.getHeight(root.right_child))
elif root.left_child!=None:
return 1 + self.getHeight(root.left_child)
elif root.right_child!=None:
return 1+ self.getHeight(root.right_child)
else:
return 1
else:
return 0
tree = binary_search_tree()
tree.insert(5)
tree.insert(10)
tree.insert(6)
tree.insert(3)
tree.insert(4)
tree.insert(20)
tree.insert(7)
tree.insert(2)
tree.insert(1)
print(tree.root.key) #1
print(tree.root.left_child.right_child.key) #2
print(tree.root.right_child.left_child.key) #3
vgf=tree.findMin(4)
print(vgf) #4
vgf2=tree.findMin(6)
print(vgf2) #5
vgf3=tree.findSuccessor(4)
print(vgf3) #6
#tree.deletingaAKey(11)
print(tree.root.right_child.key) #7
print(tree.getHeight(tree.root)) #8
print(tree.contains(100))
|
c06e8cb62b2acbeb3edc79741d02e0f1b07aa90f | ehoversten/Python_Fundamentals | /for_loop_basic1.py | 1,242 | 4 | 4 |
# Basic - print all integers from 0 to 150
for i in range(0, 151):
print(i)
# Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000
for i in range(5, 1000000):
if i % 5 == 0:
print(i)
else:
pass
# Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If by 10, also print " Dojo".
for i in range (1, 101):
if (i % 5 == 0) and (i % 10 == 0):
print('Coding Dojo')
elif (i % 5 == 0):
print('Coding')
else:
print(i)
# Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum.
sum = 0
for i in range(0, 500000):
if i % 2 != 0:
sum += i
#print(sum)
else:
continue
print(sum)
# Countdown by Fours - Print positive numbers starting at 2018, counting down by fours (exclude 0).
for i in range(2018, 0, -4):
print(i)
# Flexible Countdown - Based on earlier "Countdown by Fours", given lowNum, highNum, mult, print multiples of mult from lowNum to highNum, using a FOR loop. For (2,9,3), print 9 6 3 (on successive lines)
lowNum = 2
highNum = 9
mult = 3
for i in range(lowNum, highNum+1):
if i % mult == 0:
print(i)
else:
continue
|
0aeeefc41b62a40a3915179f4bb4bc9c160a2897 | AlexanderNahr/mypy-ct-SESAM-pw-manager | /sesam.py | 1,549 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from hashlib import pbkdf2_hmac
uppercase_letters = list('abcdefghijklmnopqrstuvwxyz')
lowercase_letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
numbers = list('0123456789')
special_characters = list('!@#$%^&*()_+-=[]|')
password_character = uppercase_letters + \
lowercase_letters + \
numbers + \
special_characters
salt = "pepper"
def convert_bytes_to_password(hashed_bytes, length):
""" convert byte stream (non-readable chars) to password
return: password
"""
number = int.from_bytes(hashed_bytes, byteorder='big')
password = ''
while number > 0 and len(password) < length:
password = password + \
password_character[number % len(password_character)]
number = number // len(password_character) # integer division
return password
def main():
""" main functions """
master_password = input('Master password: ')
domain = input('Domain: ')
while len(domain) < 1:
print('Please enter a domain.')
domain = input('Domain: ')
hash_string = domain + master_password
hashed_bytes = pbkdf2_hmac(
'sha512', # hash algo
hash_string.encode('utf-8'), # string to encode as bytestream
salt.encode('utf-8'), # unique salt..not unique here
4096) # iterations
print('Password: ' + convert_bytes_to_password(hashed_bytes, 10))
if __name__ == '__main__':
main()
|
a32129bb92165d51bfcab5ac32cc877ca236ab38 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe037.py | 173 | 3.96875 | 4 | #Desafio.030
n = int(input('Digite um número qualquer: '))
if n%2 == 1:
print('{} é um número ímpar!'.format(n))
else:
print('{} é um número par!'.format(n))
|
f9416a68be10ff9d9cd5bf26075ca432795411a9 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe020.py | 399 | 3.75 | 4 | print('=='*20)
print(' Aluguel de Carros')
print('=='*20)
dias = float(input('Quantidade de Dias Alugados: '))
km = float(input('Quantidade de km Rodados:'))
vldias = dias*60
vlkm = km*0.15
print('O valor aluguel do carro por {:.0f} dias é R${:.2f}.'.format(dias,vldias))
print('O valor referente a {:.2f}km rodados é R${:.2f}.'.format(km,vlkm))
print('Total a Pagar: R${:.2f}'.format(vlkm+vldias))
|
4d486592b272f67a51312e94c21717e6466ca2e4 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe015a.py | 314 | 3.84375 | 4 | #desafio011
larg = float(input('Largura da Parede: '))
alt = float(input('Altura da Parede: '))
área = larg*alt
tinta = área / 2
print('Sua parede tem a dimensão {}x{} e sua área é de {:.2}m².'.format(larg,alt,área))
print('Para pintar a área dessa parede você precisará de {}l de tinta.'.format(tinta))
|
69e112189b071557ec32abb27fef83312a3b9104 | marianohtl/LogicaComPython | /Cousera/exe043.py | 554 | 3.609375 | 4 | # Exercício 1 pt.2 - Primos - Semana 7
'''
def n_primos(y):
número = teto = y
indice = 0
while indice <= teto:
if número%2 == 1 or número == 2:
print(número)
número = número - 1
indice = indice + 1
n_primos(int(input('Digite um número: ')))'''
def n_primo2(y):
número = y
indice = 2
x = 0
while indice <= número:
if indice % 2 == 1 or indice == 2:
x = x + 1
indice = indice + 1
return x
print(n_primo2(int(input('Digite um número: ')))) |
663d3437ad9137b860568da38d71e96e6c16cbfd | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe022a.py | 442 | 4.03125 | 4 | """co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hi = (co ** 2 + ca ** 2) **(1/2)
print('A hipotenusa vaimedir {:.2f}.'.format(hi))"""""
#import math
from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hi = hypot(ca,co) # import math <math.hypot>
print('A hipotenusa vai medir {:.2f}'.format(hi))
|
6cad9846462ac6a7aa725031f48f3cb593ed1815 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe042.py | 1,559 | 4.3125 | 4 | #Desafio35
from math import fabs
a = int(input('Digite um número que represente uma medida de um dos lados de um triãngulo: '))
b = int(input('Digite a medida referente ao outro lado: '))
c = int(input('Typing the mitters of other side the triangle: '))
n = 0
if fabs(a - b) < c and (a + b) > c:
print ('Temos um triângulo!')
else:
if fabs(c - b) < a and (c + b) > a:
print('Temos um triângulo!')
else:
if fabs(a - c) < b and (c + a) > b:
print('Temos um triângulo!')
else:
print('Não temos um triângulo!')
# Não compreendi o porquê da ausência da necessidade de verificar o oposto de a-b >>> (b-a)
"""
if math.fabs(a - b) < c and (a + b) > c:
print('As medidas adicionadas formam um triângulo!')
else:
if math.fabs(b - a) < c and (b + a) > c:
print('As medidas adicionadas geram um triângulo!')
else:
n = n + 1
print(n)
if math.fabs(c - b) < a and (c + b) > a:
print('As medidas adicionadas formam um triângulo!')
else:
if math.fabs(b - c) < a and (b + c) > a:
print('As medidas adicionadas geram um triângulo!')
else:
n = n+1
print(n)
if math.fabs(a - c) < a and (a + c) > a:
print('As medidas adicionadas formam um triângulo!')
else:
if math.fabs(c - a) < a and (c + a) > a:
print('As medidas adicionadas formam um triÂngulo!')
else:
n = n+1
print(n)
if n == 3:
print('Que pena! Não é possível fazer um triângulo com tais medidas... ')"""
|
c6bdb9b8bf726a10edb0ef8ecdc6d7649d77ae24 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe041.py | 299 | 3.875 | 4 | #Desafio034
s = float(input('Digite o valor do salário do funcionário: R$ '))
if s > 1250.00:
a = s*1.1
print('Você ganhou um aumento de 10%, seu salário atual é {:.2f}.'.format(a))
else:
a=s*1.15
print('Você ganhou um aumento de 15%, seu salário atual é {:.2f}.'.format(a)) |
bf3bf017e9e292af74f40125f54d4418f7cfb24c | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe018.py | 359 | 3.6875 | 4 | print(' =='*30)
print(' LOJA DO ABREU')
print(' =='*30)
print(' 10% de desconto nos Pagamentos à Vista ')
print(' 8% de Juros à Prazo')
print(' --'*30)
preço = float(input(' Preço do Produto: R$'))
vista = preço-(preço*0.1)
prazo = preço+(preço*0.08)
print(' À vista R${:.2f}\n À prazo R${:.2f}'.format(vista,prazo))
|
be5fc502a12febfdd9a27e3ad679f6e20a2ee9b2 | marianohtl/LogicaComPython | /Cousera/exe038.py | 3,122 | 3.640625 | 4 | # SEMANA 6 - Jogo do NIM - COM BUGS
def campeonato():
print('**** Rodada 1 ****\n')
partida()
print('\n**** Rodada 2 ****\n')
partida()
print('\n**** Rodada 3 ****\n')
partida()
print('\n*** Final do campeonato! ***\n')
placar = 'Placar: Você 0 X 3 Computador'
return placar
def usuario_escolhe_jogada(x,y):
z = 1
while z != 0:
j = 'a'
while j.isnumeric() != True:
j = input('\nQuantas peças você vai querer tirar? ')
if j.isnumeric() != True:
print('\nOops! Jogada inválida! Tente de novo.')
j = int(j)
print('')
if j <= y:
z = 0
else:
z = 1
print('\nOops! Jogada inválida! Tente de novo.')
return j
def computador_escolhe_jogada(x,y):
trap = y + 1
if x % trap <= y:
jpc = x % trap
elif x % trap == 0:
jpc = y
return jpc
def partida():
n = 'a'
while n.isnumeric() != True:
n = input('Quantas peças? ')
if n.isnumeric() != True:
print('\nOops! Jogada inválida! Tente de novo.')
m = 'a'
while m.isnumeric() != True:
m = input('Limite de peças por jogada? ')
if m.isnumeric() != True:
print('\nOops! Jogada inválida! Tente de novo.')
m = int(m)
n = int(n)
if n%(m+1) == 0:
print('\nVocê começa!\n')
while n != 0:
j = usuario_escolhe_jogada(n,m)
n = n - j
print('Você tirou {} peça(s).\nAgora resta apenas {} peça(s) no tabuleiro.\n'.format(j, n))
pc = computador_escolhe_jogada(n,m)
n = n - pc
print('Computador tirou {} peça(s).\nAgora resta apenas {} peça(s) no tabuleiro.\n'.format(pc, n))
print('Fim do jogo! O computador ganhou!')
else:
while n != 0:
print('\nComputador começa!\n')
pc = computador_escolhe_jogada(n,m)
n = n - pc
print('Computador tirou {} peça(s).\nAgora resta apenas {} peça(s) no tabuleiro.\n'.format(pc,n))
if n > 0:
j = usuario_escolhe_jogada(n,m)
n = n - j
print('Você tirou {} peça(s).\nAgora resta apenas {} peça(s) no tabuleiro.\n'.format(j, n))
print('Fim do jogo! O computador ganhou!')
def main():
e = 'a'
while e.isnumeric() != True:
e = input('\nBem-vindo ao jogo do NIM! Escolha: \n\n'
'1 - para jogar a partida isolada\n'
'2 - para jogar um campeonato ')
if e.isnumeric() != True:
print('\nOops! Jogada inválida! Tente de novo.')
return e
e = int(main())
passag = True
while passag == True:
if e != 1 and e != 2:
while e != 1 and e != 2:
e = int(main())
print('\nOops! Jogada inválida! Tente de novo.')
elif e == 1:
print('\nVocê escolheu uma partida isolada!\n')
partida()
passag = False
else:
print('\nVocê escolheu campeonato!\n')
print(campeonato())
passag = False |
6ae77e800f7da101d96c5a83580335421ecb71d3 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe029a.py | 672 | 4.0625 | 4 | #Desafio023
# erro com números menores que 1000
num = int(input('Digite um número: '))
n = str(num)
print('Analizando o número {} ... '.format(num))
print('Unidade: {}'.format(n[3]))
print('Dezena: {}'.format(n[2]))
print('Centena: {}'.format(n[1]))
print('Milhar: {}'.format(n[0]))
nuum = int(input('Digite um número: '))
u = nuum // 1 % 10
d = nuum // 10 % 10
c = nuum // 100 % 10
m = num // 1000 % 10
print('Unidade:',(u))
print('Dezena:',(d))
print('Centena:',(c))
print('Milhar:',(m))
#print('Analizando o número {} ... '.format(nuum))
#print('Unidade: {}'.format())
#print('Dezena: {}'.format())
#print('Centena: {}'.format())
#print('Milhar: {}'.format())
|
f0b89b93c7e0764aa70f04e355c6c56291614faf | marianohtl/LogicaComPython | /Cousera/exe018.py | 259 | 3.921875 | 4 | # Soma da Sequência dos Componentes de um Número
n = input('Digite um número: ')
c = int(len(n))
i = 0
ii = 0
soma = 0
while i < c:
num = int(n[ii])
soma = soma + num
i = i + 1
ii = ii + 1
print('A soma dos algarismos é {}.'.format(soma)) |
cf15f124c58463f62adea308835582e0d049873a | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe012.py | 173 | 3.75 | 4 | #desafio008
m = float(input('Diga a medida em metro(s): '))
cm = m*100
ml = m*1000
print('{} metro(s) tem {:.0f} centímetro(s) e {:.0f} milímetro(s).'.format(m,cm,ml))
|
794dc6aa1dea56f555cd942998bacf110dc1a943 | marianohtl/LogicaComPython | /Cousera/exe024.py | 224 | 3.90625 | 4 | #Números ímpares Com While
n = int(input('Digite o valor de n: '))
i = n*2
ii = 0
while i != 0:
if ii % 2 == 1:
print(ii)
ii = ii + 1
i = i - 1
else:
i = i - 1
ii = ii + 1
|
d1f20334f850800812350de952f64030b53f0aa7 | marianohtl/LogicaComPython | /CV Python - Mundo 1/exe023a.py | 657 | 4.09375 | 4 | import math
ângulo = float(input('Digite o angulo que você deseja: '))
seno = math.sin(math.radians(ângulo)) # converte o ângulo digitado para radianos e calcula o seno
print('O ângulo de {} tem o SENO de {:.2f}.'.format(ângulo,seno))
cosseno = math.cos(math.radians(ângulo)) # converte o ângulo digitado para radianos e calcula o cosseno
print('O ângulo de {} tem o COSSENO de {:.2}.'.format(ângulo,cosseno))
tangente = math.tan(math.radians(ângulo)) # converte o ângulo digitado para radianos e calcula o tangente
print('O ângulo de {} tem a Teangente de {:.2}.'.format(ângulo, tangente))
# possível usar apenas seno / cosseno / tangente
|
4b7d62499b73ce7ac264c1dc21660bccef757d4d | xm6264jz/lab-4-assignment-Capstone | /test_camelcase.py | 1,055 | 3.828125 | 4 | import camelCase
from unittest import TestCase
class TestCamelCase(TestCase):
def test_camel_case_sentence(self):
self.assertEqual('helloWorld', camelCase.camel_case('Hello World'))
def test_emptystring(self):
self.assertEqual("Please enter something. No empty string allowed", camelCase.camel_case(""))
def test_numbers_allowed(self):
self.assertEqual("No numbers allowed. Please enter string only", camelCase.camel_case('1234567890'))
def test_combinations_of_upper_lower_case(self):
self.assertEqual('ahmedIsGoingHome', camelCase.camel_case('aHmeD is gOIng HoME'))
def test_more_than_one_space_between_words(self):
self.assertEqual('heIsHeadingHome', camelCase.camel_case('he is heading home'))
def test_string_with_whitespace_at_the_start_and_at_the_end(self):
self.assertEqual('heToldMeToGoAway', camelCase.camel_case(' he told me to go away '))
def test_for_one_word(self):
self.assertEqual('waiting', camelCase.camel_case('waiting'))
|
db0edb58cbd19a318e94c7e33cccab7ba8de9174 | sophiaboisvert/C_in_UNIX_Environment | /guessingGame | 768 | 3.71875 | 4 | #! /user/bin/python
import random
import sys
import os
#random integer function
def randomGen(min, max):
return random.randint(min,max)
#get username from player
username = raw_input("Enter your username: ")
#generate random number
num = randomGen(-100,100)
score = 1
limit = 7
print("You can guess 7 times")
#play game
while(score <= limit):
guess = input("Enter your guess: ")
if guess > num:
print("High guess")
elif guess == num:
print("Congrats that is correct!")
break
else:
print("Low guess")
if score == limit:
print("You are out of guesses")
break
score += 1
#print out score
print("Your score was: ")
print(score)
#write to report file
reportfile = open("gamereport.txt", "a")
reportfile.write(username + " " + str(score) + "\n")
|
8af76392fb8ade32aa16f998867a9312303cd2fa | porigonop/code_v2 | /linear_solving/Complex.py | 2,070 | 4.375 | 4 | #!/usr/bin/env python3
class Complex:
""" this class represent the complex number
"""
def __init__(self, Re, Im):
"""the numer is initiate with a string as "3+5i"
"""
try:
self.Re = float(Re)
self.Im = float(Im)
except:
raise TypeError("please enter a correct number")
def __str__(self):
""" allow the user to print the complex number
"""
if self.Im < 0:
return str(self.Re) + str(self.Im) + "i"
return str(self.Re) + "+" + str(self.Im) + "i"
def __repr__(self):
""" allow the user to print the complex number
"""
if self.Im < 0:
return str(self.Re) + str(self.Im) + "i"
return str(self.Re) + "+" + str(self.Im) + "i"
def multiplicate_by(self, number):
"""allow the multiplication
"""
answerRE = 0
answerIm = 0
if type(number) is Complex:
Re = self.Re
answerRe = Re * number.Re -\
self.Im * number.Im
answerIm = Re * number.Im +\
self.Im * number.Re
else:
try:
number = float(number)
except:
raise TypeError("please enter a valid number")
answerRe = self.Re * number
answerIm = self.Im * number
return Complex(answerRe, answerIm)
def divide_by(self, number):
"""allow the division
"""
answerRE = 0
answerIm = 0
if type(number) is Complex:
numerator = self.multiplicate_by(Complex(number.Re, - number.Im))
answerRe = numerator.divide_by(number.Re **2 + number.Im **2).Re
answerIm = numerator.divide_by(number.Re **2 + number.Im **2).Im
else:
try:
number = float(number)
except:
raise TypeError("please enter a valid number")
answerRe = self.Re / number
answerIm = self.Im / number
return Complex(answerRe, answerIm)
def sum_by(self, number):
"""allow addition and subtraction
"""
answerRe = 0
answerIm = 0
if type(number) is Complex:
answerRe = self.Re + number.Re
answerIm = self.Im + number.Im
else:
try:
number = float(number)
except:
raise TypeError("please enter a valid number")
answerRe = self.Re + number
answerIm = self.Im
return Complex(answerRe, answerIm)
|
b7a522d63a5e42ecbb016d21a81b76a879fced78 | porigonop/code_v2 | /theorie_des_graphes/Aventurier_du_rail/graphTrans.py | 13,653 | 4.3125 | 4 | #!/usr/bin/env python3
from BooleanMatrix import BooleanMatrix
class GraphTrans:
"""This class is a new type for describing the graphs
"""
def __init__(self):
"""this allow the graph to be create
it is empty at the begin
self.nodes is a set wich contains all the node
self.edges is a list of every edge in the graph
self.adjency_list is a dictionnary wich have nodes as
key and the node linked as values
"""
self.nodes = set()
self.edges = list()
self.adjency_list = dict()
def add_a_node(self, node_name):
"""add a new node in the node set and refresh the adjency_list
node_name is a string which contain the new node
comming into the graph
"""
if node_name in self.nodes:
print("ce node est deja dans le graphe")
return False
self.nodes.add(node_name)
self.adjency_list[node_name] = list()
def add_an_edge(self, from_node, to_node):
"""add en edge between from_node to the node to_node
from_node is a string which contain the parent node
to_node is a string which contain the link's child
"""
if not(from_node in self.nodes):
raise NameError("node aren't in the graph : " + str(from_node))
return False
if not(to_node in self.nodes):
raise NameError("node aren't in the graph : " + str(to_node))
return False
self.edges.append((from_node, to_node))
self.adjency_list[from_node].append(to_node)
def __str__(self):
"""allow the user to display the graph in a print()
"""
nodes = ""
for node in self.nodes:
nodes += str(node) + ", \n"
edges = ""
for edge in self.edges:
edges += str(edge[0]) + "---->" + str(edge[1]) + "\n"
return \
"*************************\n"\
"* Display of the graph *\n"\
"*************************\n"\
"Nodes :\n"\
"------------\n" +\
nodes[:len(nodes)-1] +"\n"+\
"Edges :\n"\
"------------\n"+\
edges +"\n" +\
"=========================\n"
def breadth_first_search(self, departure):
"""
return a dictionnary that have node as key and node as value
the node in value is the parent of the node in the key
use the fifo methode to determine which one is the next to look at.
departure is the first starting point of the course
"""
colors = {}
for node in self.nodes:
colors[node] = "white"
parents = {}
fifo = []
fifo.append(departure)
colors[departure] = "grey"
parents[departure] = None
for node in sorted(self.nodes):
while fifo != []:
in_progress = fifo[0]
fifo.pop(0)
for neighbour \
in sorted(self.adjency_list[in_progress]):
if colors[neighbour] == "white":
parents[neighbour] = in_progress
colors[neighbour] = "grey"
fifo.append(neighbour)
colors[in_progress] = "black"
if colors[node] != "white":
continue
colors[node] = "grey"
parents[node] = None
fifo.append(node)
return parents
def recursive(self,\
colors, \
lifo = [], \
departure = None, \
parents = {}):
"""
useful for depth_first_search to always look at the last
in and change the focus with every new neighbour found
it allow to go to the next node and keep the current in another
iteration
"""
if departure != None:
lifo = []
lifo.append(departure)
parents = {}
colors[departure] = "grey"
parents[departure] = None
departure = None
if lifo != []:
in_progress = lifo[-1]
lifo.pop()
for neighbour \
in sorted(self.adjency_list[in_progress]):
if colors[neighbour] == "white":
parents[neighbour] = in_progress
colors[neighbour] = "grey"
lifo.append(neighbour)
colors[in_progress] = "black"
parents, colors = self.recursive(lifo = lifo, \
colors = colors, \
departure = None, \
parents = parents)
if lifo == []:
return parents, colors
def depth_first_search(self, departure):
"""
return a dictionnary that have node as key and node as value
the node in value is the parent of the node in the key
use the lifo methode to determine which one is the next to look at.
departure is the starting point of the course
"""
colors = {}
parents_list = []
parents = {}
for node in self.nodes:
colors[node] = "white"
in_queue, colors = self.recursive(colors = colors,\
departure = departure)
parents_list.append(in_queue)
for node in sorted(self.nodes):
if node in parents or colors[node] != "white":
continue
in_queue, colors = self.recursive(colors = colors,\
departure = node)
parents_list.append(in_queue)
for parents_ in parents_list:
for key in parents_:
parents[key] = parents_[key]
return parents
def is_bipartite(self):
"""
this methode attribut a colors at each node in the graph,
based on the parent/child combinaison given by the
breadth_first_search methode it while give a different color to the
child and the parent, if there is a problem in the attribution then
the graph isn't bipartite, after that, if it succed,
all the node have a color and we just have to test with the list of
edges if they all have a different colors
return True or False
"""
parents = self.breadth_first_search(sorted(list(self.nodes))[0])
colors = {}
for key in sorted(list(parents)):
if parents[key] == None:
continue
if key in colors and \
parents[key] in colors and\
colors[key] != colors[parents[key]]:
return False
if key in colors:
colors[parents[key]] = - colors[key]
continue
if parents[key] in colors:
colors[key] = - colors[parents[key]]
continue
colors[key] = 1
colors[parents[key]] = -1
for edge in self.edges:
from_node, to_node = edge
if colors[from_node] == colors[to_node]:
return False
return True
def articulation_point(self):
"""
find every articulation point in a non-oriented graph,
with the simple algorythm that use the facts that this point
will have 2 sons or more in a depth course algorythm
so the method test every point and test if it has more than
2sons
return a list of node
"""
articulation_point = []
for root in self.nodes:
course = self.depth_first_search(root)
if len([node for node in course.values() \
if node == root]) >= 2:
articulation_point.append(root)
return articulation_point
return articulation_point
def is_non_oriented(self):
""" return True if non oriented
return False if oriented
"""
for elt in self.edges:
if not ((elt[1], elt[0]) in self.edges):
return False
return True
def connected_component(self):
""" return a list of list with every connected component
"""
list_nodes = list(self.nodes)
if not self.is_non_oriented():
raise TypeError("graph must be non oriented")
return False
parent = self.breadth_first_search(list_nodes[0])
answer = []
in_elt = False
for key in parent:
in_elt = False
for elt in answer:
if parent[key] in elt:
elt.append(key)
in_elt = True
if not in_elt:
answer.append([key])
return answer
def is_connected(self):
""" return True if connexe
return False if not
"""
return True if len(self.connected_component()) == 1 else False
def is_oriented(self):
"""return True if the grpah is oriented
False if non oriented
"""
return not self.is_non_oriented()
def transitive_closure_V1(self):
"""
Renvoie le graph correspondant à la fermeture transitive du graph self.
La méthode utilisée est celle du calcul successif des puissances de M
(M + M^2 + ... + M^n).
:exemple:
--------
>>>graph1 = Graph()
>>>for i in range(4):
graph1.add_a_node(str(i))
>>>graph1.add_an_edge('0', '1')
>>>graph1.add_an_edge('1', '3')
>>>print(graph1)
************************
* Display of the graph *
************************
Nodes:
------
1, 2, 3, 0
Edges:
------
0 ---> 1
1 ---> 3
=========================
>>>print(graph1.transitive_closure_V1())
************************
* Display of the graph *
************************
Nodes:
------
1, 2, 3, 0
Edges:
------
0 ---> 1
0 ---> 3
1 ---> 3
=========================
"""
if len(self.nodes) == 0:
raise ValueError("On ne peut pas calculer la fermeture transitive"
+ " d'un graph sans sommets")
# On calcule d'abord M la matrice booléenne associée au graph self.
# Creation de nodes. nodes est une list contenant les sommets du graph
# self. nodes est trié par python en utilisant:
# -le nombre dans la table ascii pour les chaines de caractères
# -l'ordre des nombres pour les nombres
nodes = list(self.nodes)
nodes.sort()
# Coefficients va contenir les coefficients de M la matrice associée au
# graph self.
coefficients = []
# remplissage de coefficients.
# Parcours des lignes de la matrice.
for i in nodes:
ligne = []
#Parcours des colonnes de la matrice
for j in nodes:
# Ajout de 1 si le graph contient l'arrête i -> j
if [i, j] in self.edges:
ligne.append(1)
else:
ligne.append(0)
# Ajout de la ligne à coefficients.
coefficients.append(ligne)
# M est la matrice booléenne associée au graph self.
M = BooleanMatrix(coefficients)
# Calcul de matrix_ferm_trans la matrice de la fermeture transitive du
# graph self.
# Initialisation de matrix_ferm_trans.
matrix_ferm_trans = M
A = M # A va contenir les puissances de M successivement jusqu'a M^n
for i in range(len(M.coefficients)-1):
A = M.multiply(A)
matrix_ferm_trans.add(A)
# Création de ferm_trans la fermeture transitive du graph self à partir
# de matrix_ferm_trans
ferm_trans = GraphTrans()
# ferm_trans reprend les mêmes sommets que le graph self.
for node in nodes:
ferm_trans.add_a_node(node)
# On parcours les lignes de la matrice de la fermeture transitive.
for ligne in range(len(matrix_ferm_trans.coefficients)):
# On parcours les colonnes de la matrice de la fermeture transitive.
for colonne in range(len(matrix_ferm_trans.coefficients)):
# Si le coefficient dans la matrice est égal à 1 on ajoute à
# ferm_trans l'arrête allant du sommet associé à la ligne vers le
# sommet associé à la colonne.
if matrix_ferm_trans.coefficients[ligne][colonne] == 1:
ferm_trans.add_an_edge(nodes[ligne], nodes[colonne])
return ferm_trans
|
02aa0fb0079ed0857df0b2f9067e27629d3684b3 | porigonop/code_v2 | /perso/smartrocket/refactor/Obstacle.py | 764 | 3.703125 | 4 |
class Obstacle():
def __init__(self, posx, posy, height, width):
self.posx = posx
self.posy = posy
self.height = height
self.width = width
def collide(self, rocketpos):
# rocket is left to the obstacle
if self.posx > rocketpos[0]:
return False
# rocket is upper than obstacle
if self.posy > rocketpos[1]:
return False
# rocket is rigth to the obstacle
if self.posx + self.width < rocketpos[0]:
return False
# rocket is lower than obstacle
if self.posy + self.height < rocketpos[1]:
return False
return True
def draw(self, qp):
qp.drawRect(self.posx, self.posy, self.height, self.width)
|
5c5ae6a5a3b41516182b09b03c36fe8636dbebf7 | porigonop/code_v2 | /theorie_des_graphes/TP2/FiniteStateMachine.py | 2,199 | 3.578125 | 4 | #!/usr/bin/env python3
from Graph import Graph
#note : I set the lenght of the tab to 2 cause of some hard condition
# in the code, it allow to see all the code.
class FiniteStateMachine(Graph):
def __init__(self):
"""
init the Machine with her attribute and the one from
Graph
"""
Graph.__init__(self)
self.initial = None
self.final = None
self.position = None
def set_initial(self, node):
"""
attribute the initial value of initial and position
if node is in the "Grah" Machine, else NameError
"""
if node not in self.nodes:
raise NameError("node aren't in the automate")
return False
self.initial = node
self.position = node
def set_final(self, node):
"""
attribute the initial value of final if node is in
"Graph" machine, else return NameError
"""
if node not in self.nodes:
raise NameError("node aren't in the automate")
return False
self.final = node
def add_a_transition(self, from_node, to_node, value):
"""
allow the user to add a transition, that is the same
as creating an edges between 2 node with a value who
begin with '=' or '!=', a space and a list of character
"""
if \
( value[0:3] == "!= " and value[4::2].split() == [] )\
or \
( value[0:2] == "= " and value[1::2].split() == [])\
or \
( value == "" ):
self.add_an_edge(from_node, to_node, value)
else:
raise NameError\
("value doesn't fit the requirement")
def move(self, letter):
"""
perform a move in the machine
letter is the new character read by the program
"""
for edge in self.edges:
if (edge[0] == self.position) and (edge[2][0:2] == "= "):
for lettre in edge[2][2::2]:
if lettre == letter:
self.position = edge[1]
if self.position == self.final:
self.position = self.initial
return True
else:
return None
self.position = self.initial
return False
def look_for(self, text):
"""
return a list of position in the text where the
automate found the motive
"""
result = list()
decal = len(self.final) - 1
for pos in range(len(text)):
if self.move(text[pos]) == True:
result.append(pos - decal)
return result
|
77fe588495a88dc03c0d72ce03ea4447ffe56530 | porigonop/code_v2 | /IA/Virus/Tree.py | 1,419 | 3.9375 | 4 | """
contain the tree object
"""
class Tree(object):
"""
define the tree object with value and sons
"""
def __init__(self, value=None):
self.sons = []
self.value = value
self.position = None
def add(self, tree):
"""
add a son to the tree
"""
self.sons.append(tree)
def __repr__(self):
return self.rec_repr(0)
def rec_repr(self, nb_of_tab):
"""
run throught the tree to return a str of the current tree
"""
answer = str(self.value) + str(self.position) + "\n|"
for son in self.sons:
answer += "\t|" * nb_of_tab + "------ " + son.rec_repr(nb_of_tab + 1)
return answer
def set_pos(self, pos):
"""
set the position played
"""
self.position = pos
def set_value(self, value):
"""
set value of this node
"""
self.value = value
def write_in_file(self, name_of_file: str):
"""
write the representation of the tree in a file
"""
msg = str(self)
fhandle = open(name_of_file, "w")
fhandle.write(msg)
fhandle.close()
if __name__ == "__main__":
a = Tree(3)
b = Tree(1)
b.add(Tree(2))
c = Tree(4)
c.add(a)
c.add(b)
d = Tree(3)
d.add(Tree(2))
tr = Tree(2)
tr.add(d)
tr.add(c)
tr.add(c)
print(tr)
|
1d25d661a8799bd4829b14b2aea1ab031dc75682 | jiyuankai/algorithms | /backtrack/subset.py | 779 | 3.6875 | 4 | import copy
result = []
def subsets(nums):
track = []
backtrack(track, 0, nums)
return result
def backtrack(track, start, choices):
# 与全排列不同,子序列的解为递归过程中所有的路径集合(不论是否满足结束条件)
result.append(track)
# 结束条件choices为空,递归基
if start == len(choices):
return
for i, choice in enumerate(choices[start:]):
# 做选择
track.append(choice)
# 选择过的元素在后续路径中不再出现,全局维度
# i是基于start的索引,所以传递时要加上start
backtrack(copy.deepcopy(track), start+i+1, choices)
# 撤销选择
track.pop()
if __name__ == '__main__':
print(subsets([1, 2]))
|
f46ad294349b18d7f3fc9b17282dada936ba4864 | anamariagds/listas_remoto | /semana10/acessosenha.py | 522 | 3.78125 | 4 | def verifica(dados):
tent= 0
while tent <3:
tent +=1
nome= input('Usuário ').lower()
senha= input('password ').lower()
if nome in dados and senha == dados[nome]:
print('Bem Vinda, Programadora!')
break
else:
print(f'Senha ou usuario inválido.')
def main():
dados= {
'ana maria': 'floresatomicas',
'rui': 'fluminense',
'cat': 'peixe'
}
verifica(dados)
if __name__ == '__main__':
main() |
24bb10282f3ed65370060c11e21520d59799a8e5 | anamariagds/listas_remoto | /repeticoes/lanches.py | 928 | 3.734375 | 4 | def lanche():
conta = 0
while True:
codigo = input('''
CÓDIGO PRODUTO PREÇO (R$)
H Hamburger 5,50
C Cheeseburger 6,80
M Misto Quente 4,50
A Americano 7,00
Q Queijo Prato 4,00
X PARA TOTAL DA CONTA''').upper()[0]
if codigo == 'H':
conta += 5.50
elif codigo == 'C':
conta += 6.80
elif codigo == 'M':
conta+=4.50
elif codigo == 'A':
conta +=7.00
elif codigo == 'Q':
conta += 4.00
if codigo != 'H' and codigo != 'C' and codigo != 'M' and codigo != 'A' and codigo != 'Q' and codigo != 'X':
print("Opção inválida.")
if codigo == 'X':
return conta
break
def main():
pagar = lanche()
print(f'\nSua conta deu R${pagar:.2f}')
if __name__=='__main__':
main()
|
45f0fcb733b310eeae573f6846d3841f3ab4fb20 | anamariagds/listas_remoto | /semana7/populacaoAB.py | 576 | 3.765625 | 4 |
def maior_populacao():
t = 0
pop_A = float(input("População A: "))
pop_B = float(input("População B: "))
maior = pop_A
menor = pop_B
if pop_B > maior:
maior = pop_B
if pop_A<menor:
menor = pop_A
while maior>menor:
t +=1
maior *=1.02
menor *=1.03
if menor > maior:
return t
break
def main():
ano =maior_populacao()
print(f'Precisará de {ano} anos para a Cidade A ultrapassar a população de B.')
if __name__=='__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.