blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
7dbda26bbf64ec43bc3fd0e34f3f75a91a0c4da3 | vinhlee95/hacker_rank_python | /validate_email.py | 1,064 | 4.375 | 4 | """
You are given an integer followed by email addresses. Your task is to print a list containing only valid email addresses in lexicographical order.
Valid email addresses must follow these rules:
It must have the [email protected] format type.
The username can only contain letters, digits, dashes and underscores.
The website name can only have letters and digits.
The maximum length of the extension is 3.
⌨️ Input (n): ["3", "[email protected]", "[email protected]", "[email protected]"]
🏆 Output: ['[email protected]', '[email protected]', '[email protected]']
🖥 https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter
"""
import re
regex = "^[0-9a-zA-Z-_]+@[0-9a-zA-Z]+\.[0-9a-zA-Z]{1,3}$"
def validate_email(email):
email = str(email)
return re.match(regex, email)
def filter_mail(emails):
return list(filter(validate_email, emails))
# input_emails = [3, "[email protected]", "[email protected]", "[email protected]"]
# input_emails = ['[email protected]', 1]
input_emails = [2, "harsh@gmail", "[email protected]"]
filtered_emails = sorted(filter_mail(input_emails))
print(filtered_emails)
|
88f2e7ad524e50e464f24df75b3198ac11865077 | stinovlas/Turnaj | /Testing.py | 1,907 | 3.640625 | 4 | from Player import Move
import importlib
import sys
def pick_next():
while True:
pick = input("Pick your next move: ")
for m in Move:
if m.value[0].lower() == pick.lower():
return m
print("pick options: A,B,C,D")
def print_result(res, sc1, sc2):
print("Your move was: {}".format(res.opp_move.value[0]))
print("Your opponent's move was: {}".format(res.my_move.value[0]))
print("You scored {}".format(res.get_opp_score()), ", total: {}".format(sc2))
print("Your opponent scored {}".format(res.get_my_score()), ", total: {}".format(sc1))
print("--------------------------->")
def print_score(sc1, sc2):
print("THE GAME HAS ENDED")
print("--------------------------->")
print("You scored in total {} points.".format(sc2))
print("AI player scored in total {} points.".format(sc1))
def main():
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Argument error")
exit(1)
try:
iterations = int(sys.argv[2])
except IndexError:
iterations = 10
except ValueError:
print("The second argument should be a number!")
exit(1)
try:
name = sys.argv[1].split('.py')
strategy_name = name[0]
strategy1 = importlib.import_module(strategy_name)
except IOError:
print('An error occurred trying to read the file.')
exit(1)
except ImportError:
print("NO module found")
exit(1)
s1 = getattr(strategy1, strategy_name)()
sc1 = 0
sc2 = 0
from Result import Result
for i in range(iterations):
move1 = s1.next_move()
move2 = pick_next()
res = Result(move1, move2)
sc1 += res.get_my_score()
sc2 += res.get_opp_score()
print_result(res, sc1, sc2)
s1.reward(res)
print_score(sc1, sc2)
if __name__ == "__main__":
main()
|
30b21bd9b7009ad6413fb98386e8126cb707006f | abhimita/udacity-algorithms | /array_digits/test/test_array_digits.py | 2,743 | 4.21875 | 4 | import unittest
from array_digits import ArrayDigits
class TestArrayDigits(unittest.TestCase):
# Test when there are odd number of digits in the given array
def test_rearrange_digits_when_odd_number_of_elements(self):
array = [1, 2, 3, 4, 5]
self.assertEqual(ArrayDigits.rearrange_digits(array), [542, 31])
# Test when there are even number of digits in the given array
def test_rearrange_digits_when_even_number_of_elements(self):
array = [4, 6, 2, 5, 9, 8]
self.assertEqual(ArrayDigits.rearrange_digits(array), [964, 852])
# Test when there are only two elements in the array
def test_rearrange_digits_with_two_elements(self):
array = [4, 6]
self.assertEqual(ArrayDigits.rearrange_digits(array), [6, 4])
# Test when there is only one element. This will throw an exception.
def test_rearrange_digits_with_one_element(self):
array = [4]
with self.assertRaises(Exception) as context:
ArrayDigits.rearrange_digits(array)
self.assertTrue('Array length is not sufficient to return two numbers' in str(context.exception))
# Test when array contains string element
def test_rearrange_digits_when_one_element_is_string(self):
array = [4, 'a', 2, 5, 9, 8]
with self.assertRaises(Exception) as context:
ArrayDigits.rearrange_digits(array)
self.assertTrue('Either the array contains non integer elements or integer is more than 9' in str(context.exception))
# Test when array contains float
def test_rearrange_digits_when_one_element_is_float(self):
array = [4, 3.0, 2, 5, 9, 8]
with self.assertRaises(Exception) as context:
ArrayDigits.rearrange_digits(array)
self.assertTrue('Either the array contains non integer elements or integer is more than 9' in str(context.exception))
# Test when array is empty
def test_rearrange_digits_when_array_is_empty(self):
array = []
with self.assertRaises(Exception) as context:
ArrayDigits.rearrange_digits(array)
self.assertTrue('Array length is not sufficient to return two numbers' in str(context.exception))
# Test when array contains two digited element as integer
def test_rearrange_digits_when_one_element_is_two_digited(self):
array = [4, 30, 2, 5, 9, 8]
with self.assertRaises(Exception) as context:
ArrayDigits.rearrange_digits(array)
self.assertTrue('Either the array contains non integer elements or integer is more than 9' in str(context.exception))
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestArrayDigits)
unittest.TextTestRunner(verbosity=2).run(suite) |
8f4bc422ac9dcd175eda8803a6cb2bcc797865b4 | sresis/practice-problems | /validate-bst/validate-bst.py | 504 | 3.640625 | 4 | # This is an input class. Do not edit.
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def validateBst(tree):
def helper(tree, min_val, max_val):
if tree is None:
return True
if tree.value < min_val or tree.value >= max_val:
return False
left_is_valid = helper(tree.left, min_val, tree.value)
return left_is_valid and helper(tree.right, tree.value, max_val)
return helper(tree, float("-inf"), float("inf"))
|
5bf7e428099098f2e02b8a45deb0be6a210aa902 | jctrotter/algorithms | /hw1/problem4/mergeTime.py | 2,344 | 3.78125 | 4 | # merge logic
import random, time
def merge(array, left, right):
i = 0 # left array ptr
j = 0 # right array ptr
k = 0 # merged array ptr
while i < len(left) and j < len(right): # iterate through both l and r arrays
if left[i] < right[j]: # if left value smaller
array[k] = left[i] # put it into merged array
i = i + 1 # iterate left ptr
else:
array[k] = right[j] # otherwise right ptr is smaller, put it into merged array
j = j + 1 # iterate right ptr
k = k + 1 # iterate merged ptr
while i < len(left): # while we are still in the left array
array[k] = left[i] # slap the rest of the values in the merged array. only reach here if we know it will be valid
i = i + 1
k = k + 1
while j < len(right): # while we are still in the right array
array[k] = right[j] # slap the rest of the values in the merged array. only reach here if we know it will be valid
j = j + 1
k = k + 1
# mergesort splitting
def mergesort(array):
n = len(array)
if (n < 2):
return # we are done
mid = int(n/2) # partition array into two
left = []
right = []
for i in range(0, mid): # populate the two half arrays
value = array[i]
left.append(value)
for j in range(mid, n):
value = array[j]
right.append(value)
mergesort(left) # recur the left array, splitting until we hit base case of 2
mergesort(right) # recur the right array, splitting until we hit base case of 2
merge(array, left, right) # merge em all back, sorting along the way
# required file io
nvals = [50000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000]
for n in nvals:
array = []
for i in range(0, n):
array.append(random.uniform(0, 10000))
start = time.time()
mergesort(array)
end = time.time()
print("\nn: ", n, "\ntime: ", end-start) |
a496c348b183aa89cee2d9e4619ff51d7ab05574 | slumflower/kata_mastery | /sum-of-list-values/solution.py | 92 | 3.515625 | 4 | def sum_list(lst):
num = 0
for i in lst:
num = i + num
return num
|
ef96390796d2684622d45ec3232398479f9f5f8d | nerdjerry/python-programming | /library/search/binarysearch.py | 855 | 3.875 | 4 | def binarySearch(input, value):
return search(input,value,0,len(input))
def search(input, value, start, end):
midpoint = (start + end) // 2
if start >= end :
return -1
if input[midpoint] == value:
return midpoint
elif input[midpoint] > value :
return search(input,value,start,midpoint)
elif input[midpoint] < value :
return search(input,value,midpoint+1, end)
def iterativeBinarySearch(input, value):
start = 0
end = len(input)
while(start < end):
midpoint = (start + end) // 2
if(input[midpoint] == value):
return midpoint
elif input[midpoint] < value:
start = midpoint + 1
else:
end = midpoint
return -1
input = [12,34,56,67,89,90]
print(iterativeBinarySearch(input,56))
print(iterativeBinarySearch(input,45)) |
ddec9e37cbf553056a2dfd2970c4f9ce206a3507 | CS-UTEC/tarea1-github-ZzAZz4 | /primo.py | 2,043 | 4.1875 | 4 | import math
'''
Checking for primality by using a deterministic variant of the Miller-Rabin test in O((lg(n))^4)
'''
# class definition defines a controlled exception to continue outer loops form inner loops, which is
# really useful in this context
class Continue(Exception):
pass
def is_prime(number: int):
# checking for simple stuff
if number < 2 or number % 2 == 0:
return False
# we then need to write our input n in the form d*2^r + 1 (d is not divisible by 2)
# d is first assigned to n - 1, then subsequently divided by every factor of 2 it has, which are factored into 2^r
r, d = 0, number - 1
while d % 2 == 0:
r, d = r + 1, d // 2
# defining our outer continue
continue_a = Continue()
for a in range(2, min(number - 2, math.floor(2 * (math.log(number)) ** 2))):
try:
# assigning x to a^d modulo n. Pow does this very efficiently by using modulo arithmetic
x = pow(a, d, number)
# if its congruent to 1 or -1 mod n, we don't need the subsequent checks
if x == 1 or x == number - 1:
continue
# we square x modulo n up to r - 1 times until its congruent to -1 mod n.
# If it never achieves this, its definitively not prime
# If it does, we continue the outer loop
for _ in range(r - 1):
x = pow(x, 2, number)
if x == number - 1:
raise continue_a
return False
except Continue:
# catched in the outer loop
continue
# if a^d = 1 (mod n) or a^d*(2^k) = -1 (mod n) for every a in the range, then congrats! it is prime!
return True
# Inspired by stackOverflow answer: Calculating and printing the nth prime number
# For testing: hundred-millionth prime: 29996224275833
if __name__ == '__main__':
n = int(input("Enter a number to check for primality: "))
print("Woah! It's a prime! :O" if is_prime(n) else "Sorry, it's not prime :c")
|
ad97eb08a3163e835785e580536ac3c6fefda645 | kshintaku/100DaysOfCode | /Algo_Practice/Grokking-Algorithms/divide_n_conquer.py | 1,141 | 4.0625 | 4 | '''
Chapter 4 - Quicksort
Exercies:
4.1 - Write out the code for the earlier sum function
'''
def recursive_sum(arr):
x = 0
if len(arr) > 0:
x = arr.pop()
return x + recursive_sum(arr)
else:
return x
print('This is recursive sum: ', recursive_sum([1, 2, 3]))
'''
4.2 - Write a recursive function to count the number of items in a list
'''
def recursive_count(arr):
if len(arr) > 0:
arr.pop()
return 1 + recursive_count(arr)
else:
return 0
print('This is recursive length: ', recursive_count([1, 2, 3, 4, 5, 6]))
'''
4.3 - Find the maximunm number in a list
'''
def recursive_max(arr):
if len(arr) > 0:
return max(arr.pop(), recursive_max(arr))
else:
return 0
print('This is recursive max: ', recursive_max([1, 2, 3, 4, 5, 7, 0, -1]))
'''
4.4 - Remember binary search from chapter 1? It's a divide-and-conquer algorithm, too. Can you come up with the base case and recursive case for binary search?
Base case would be item == search
recursive case would be, item is greater than current, return right, otherwise return left side
'''
|
a221ea538c71c6c90c5350ee61cfdc604953137a | Kitrinos/Ch.11_Classes | /11.1_Classy_Boats.py | 2,679 | 4.40625 | 4 | '''
CLASSY BOATS
-----------------
Use the following Pseudocode to create this program:
1.) Create a class called Boat( )
2.) Use a constructor that sets two attibutes: name and isDocked.
3.) The name should be entered as an argument when the object is created.
4.) The isDocked attribute is a Boolean variable. Set it to True.
5.) Add a method called dock( )
6.) In this method, if the boat is already docked print "(boat name) is already docked."
7.) If it is not docked, print "(boat name) is docking" and set the isDocked attribute to True.
8.) Add another method called undock( )
9.) In this method, if the boat is already undocked print "(boat name) is already undocked."
10.) If it is docked print "(boat name) is undocking" and set the isDocked attribute to False.
11.) Add another class called Submarine( ) that will inherit the Boat( ) class.
12.) In the Submarine( ) class create a method called submerge( ) that will print "(boat name) is submerging"
if the boat is undocked and "(boat name) can't sumberge" if the boat is docked.
Let's Float the Boat
--------------------
13.) Instantiate an object of the Submarine( ) class. Don't forget to pass in a name.
14.) Call the dock( ) method once
15.) Call the undock( ) method twice
16.) Call the dock( ) method two more times
17.) Call the submerge( ) method once
18.) Call the undock( ) method once
19.) Call the submerge( ) method a final time.
OUTPUT:
USS Hermon is already docked.
USS Hermon is undocking
USS Hermon is already undocked.
USS Hermon is docking
USS Hermon is already docked.
USS Hermon can't submerge!
USS Hermon is undocking
USS Hermon is submerging!
'''
class Boat():
def __init__(self):
self.name = ""
self.isDocked = True
def dock(self):
if self.isDocked == True:
print(self.name, "is already docked")
elif self.isDocked == False:
print(self.name, "is docking")
self.isDocked = True
def undock(self):
if self.isDocked == False:
print(self.name, "is already undocked")
else:
print(self.name, "is undocking")
self.isDocked = False
class Submarine(Boat):
def __init__(self):
super().__init__()
self.name = ""
def submerge(self):
if self.isDocked == False:
print(self.name, "is submerging")
else:
print(self.name, "can't sumberge")
boat = Submarine()
boat.name = "USS Hermon"
boat.dock()
boat.undock()
boat.undock()
boat.dock()
boat.dock()
boat.submerge()
boat.undock()
boat.submerge() |
fe24cc394fcdecaeba3e02c1338bb8f8484f9e63 | pragya16/AssignmentPython | /program20.py | 433 | 4.46875 | 4 | # Question 20: Ask the user for a string and print out whether this string is a palindrome or not
word= 'madam'
word_rev = reversed(word)
def is_palindrome(word):
if list(word) == list(word_rev):
print'True, it is a palindrome'
else:
print'False, this is''t a plindrome'
is_palindrome(word)
'''
output:
[root@demo pragya_g16]# python palindrom.py
True, it is a palindrome
'''
|
a3808b6e305797174cef203933e640f90e1a91fb | tommywei110/machine-leanring-implementation | /traditional ml/Perceptron.py | 830 | 3.53125 | 4 | import numpy as np
# Perceptron
from sklearn.linear_model import Perceptron
# Get data from datasets
from sklearn.datasets import make_classification
# plt
import matplotlib.pyplot as plt
X, y = make_classification(n_features=2,
n_redundant=0,
n_informative=2,
n_clusters_per_class=1)
p = Perceptron(max_iter = 1000)
p.fit(X, y)
maxX = -1000
minX = 1000
for i in range(len(X)):
x0Value = X[i][0]
if (x0Value > maxX):
maxX = x0Value
if (x0Value < minX):
minX = x0Value
if (y[i] == 0):
plt.plot(X[i][0], X[i][1], 'bo')
else:
plt.plot(X[i][0], X[i][1], 'go')
#draw line
intercept = p.intercept_
w0 = p.coef_[0][0]
w1 = p.coef_[0][1]
x0 = np.linspace(minX * 1.1, maxX * 1., 20)
x1 = ((-intercept) - w0 * x0)/w1
plt.plot(x0, x1)
plt.show() |
728cb10c468e23925a88f3ccddf71fa8334bef1b | andrefcordeiro/Aprendendo-Python | /Uri/iniciante/3047.py | 179 | 4.03125 | 4 | # Idade da Dona Mônica
m = int(input())
a = int(input())
b = int(input())
if m - (a+b) > a and m - (a+b) > b:
print(m - (a+b))
elif a > b:
print(a)
else:
print(b) |
38942b0942d0ba382b0bc7033c4bc8d148db80f2 | khans/ProgrammingAndDataStructures | /python/repr_class.py | 279 | 3.859375 | 4 | class Point3D(object):
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def __repr__(self): # to print in a different style, this is over-riding repr
print str((self.x,self.y,self.z))
myPoint = Point3D(1,2,3)
myPoint.__repr__() |
cc7c5fa3d9be376d043f0d2382f3e004df4b75d1 | less1226/learningpython | /leetcode/1.twoSum.py | 325 | 3.671875 | 4 | from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if target - nums[i] in dic:
return [dic[target - nums[i]], i]
dic[nums[i]] = i
return []
if __name__ == "__main__":
result = twoSum([-3,1,3], 0)
print(result) |
72b8f95ba17f1f8a3f68a1fdccdd642ba7480805 | ryuo07/C4TB | /session9/minihacklist_part_VIII/sort_and_select.py | 548 | 3.671875 | 4 | highscore = [45, 67, 56, 78]
for i in range(2):
highscore.sort(reverse=True)
l = len(highscore)
print("high score:")
if l<=5:
l = l
elif l>5:
l = 5
for i in range(l):
print(i+1,highscore[i], sep=".")
c = int(input("enter your new highscore:"))
highscore.append(c)
highscore.sort(reverse=True)
l = len(highscore)
print("new high score:")
if l<=5:
l = l
elif l>5:
l = 5
for i in range(5):
print(i+1,highscore[i], sep=".") |
73a3efa24893d8c888abb09f66b1a6b05e2d319b | agrawalshivam66/python | /lab3/q6.py | 416 | 3.875 | 4 | def fib_range(x):
print("First fibonacci numbers in range 1-1000 are")
a=0
b=1
c=0
while c<x:
print(c,end=', ')
c=a+b
a=b
b=c
def fib_first():
print("First 25 fibonacci numbers are")
a=0
b=1
c=0
count=0
while count<25:
print(c,end=', ')
c=a+b
a=b
b=c
count+=1
fib_range(1000)
fib_first()
|
90565e042b953ba58c4ef08595f453827a4ef65d | BKKajita/User_registration | /Agenda.py | 7,007 | 4.125 | 4 | # Este programa possui funções do Python 3.10
# Poderá não funcionar em versões anteriores do Python
# Nenhum arquivo externo será gerado durante a execução deste programa
info_contato = {}
def menu_programa(): # Menu inicial do programa
print('*='*30)
print('Digite uma das Opções a seguir:')
print('1: Inserir novo cadastro')
print('2: Consultar nome cadastrado')
print('3: Remover cadastro')
print('4: Alterar cadastro')
print('5: Cadastros salvos')
print('6: Gerar relatório')
print('*='*30)
escolha = int(input('Digite o número correspondente a função desejada: '))
# Função match/case funciona da mesma forma que switch/case de outras linguagens
# Disponível somente a partir do Python 3.10
match escolha:
case 1:
inserirNovoCadastro()
case 2:
consultarCadastro()
case 3:
removerCadastro()
case 4:
alterarCadastro()
case 5:
listaCadastro()
case 6:
listagem_usuarios()
case _:
return 0
def inserirNovoCadastro(): # Este bloco de função permite a inserção de 2 ou mais cadastros
qt_cadastro = int(input('Informe a quantidade de cadastros que serão efetuados: '))
while qt_cadastro <= 1:
print('Valor inválido, insira um valor igual ou maior a 2.')
qt_cadastro = int(input('Informe a quantidade de cadastros que serão efetuados: '))
for numero_i in range(qt_cadastro):
nome = input('Informe o nome do usuário: ')
telefone = input('Informe o número de telefone: ')
email = input('Informe o e-mail: ')
twitter = input('Informe o nome de usuário Twitter: ')
instagram = input('Informe o nome de usuário do Instagram: ')
info_contato[nome] = [telefone, email, twitter, instagram]
print('Cadastro Efetuado!')
numero_i += 1
menu_programa()
def consultarCadastro(): # Este bloco de função efetua a consulta de cadastros efetuados no bloco acima
nome = input('Informe o nome do usuário cujo o cadastro será consultado: ')
if nome in info_contato:
print(info_contato.get(nome))
opcao = str(input('Gostaria de efetuar uma nova consulta?[S/N]: ')).upper()[0]
if opcao == 'S':
consultarCadastro()
elif opcao == 'N':
menu_programa()
else:
print("Opção incorreta. Digite somente 'S' ou 'N'.")
consultarCadastro()
else:
print('Usuário não encontrado.')
menu_programa()
menu_programa()
def removerCadastro(): # Os cadastros poderão ser removidos utilizando este bloco de função
nome = input('Informe o nome cujo o cadastro será excluído: ')
if nome in info_contato.keys():
opcao = str(input('Confirma a exclusão do cadastro deste usuário? [S/N]: ')).upper()[0]
if opcao == 'S':
info_contato.pop(nome)
print(nome + ' excluído')
nova_opcao = str(input('Gostaria de excluir outro cadastro? [S/N]: ')).upper()[0]
if nova_opcao == 'S':
removerCadastro()
else:
menu_programa()
elif opcao == 'N':
print('Eliminação de cadastro cancelada.')
menu_programa()
else:
print("Opção incorreta. Digitem somente 'S' ou 'N'.")
removerCadastro()
else:
print('Nome de usuário não encontrado. Tentar novamente? [S/N]: ')
opcao = str(input()).upper()[0]
if opcao == 'S':
removerCadastro()
elif opcao == 'N':
menu_programa()
else:
print("Opção incorreta. Digitem somente 'S' ou 'N'.")
removerCadastro()
def alterarCadastro(): # Este bloco de função permite a alteração de cadastros existentes dentro do dicionário
nome = input('Informe o Nome constante no cadastro: ')
if nome in info_contato.keys():
print('Informe o dado a ser alterado:')
print('1 - para alterar o telefone.')
print('2 - para alterar o e-mail.')
print('3 - para alterar o nome do usuário do Twitter.')
print('4 - para alterar o nome do usuário do Instagram.')
print('5 - Cancelar')
alterar_dado = int(input('Digite o número desejado: '))
match alterar_dado:
case 1:
print('Número de telefone cadastrado atualmente para o usuário:')
print(info_contato[nome][0])
telefone = input('Informe o novo número de telefone: ')
info_contato[nome][0] = telefone
print('Telefone alterado: {} {}'.format(nome, info_contato[nome][0]))
case 2:
print('E-mail cadastrado atualmente para o usuário:')
print(info_contato[nome][1])
email = input('Informe o novo e-mail: ')
info_contato[nome][1] = email
print('E-mail alterado: {} {}'.format(nome, info_contato[nome][1]))
case 3:
print('Usuário Twitter cadastrado atualmente:')
print(info_contato[nome][2])
twitter = input('Informe o novo usuário Twitter: ')
info_contato[nome][2] = twitter
print('Usuário Twitter alterado: {} {}'.format(nome, info_contato[nome][2]))
case 4:
print('Usuário Instagram cadastrado atualmente:')
print(info_contato[nome][3])
instagram = input('Informe o novo usuário Twitter: ')
info_contato[nome][3] = instagram
print('Usuário Instagram alterado: {} {}'.format(nome, info_contato[nome][3]))
case 5:
menu_programa()
opcao = str(input('Alterar outro dado? [S/N]: ')).upper()[0]
if opcao == 'S':
alterarCadastro()
elif opcao == 'N':
menu_programa()
else:
print("Opção incorreta. Digitem somente 'S' ou 'N'.")
alterarCadastro()
def listaCadastro(): # Este bloco de função mostra todos os elementos dos cadastros separados por ','
print('Cadastros salvos:')
print("Nome, Telefone, Email, Twitter, Instagram")
for cadastro in info_contato.keys():
print("{}, {}, {}, {}, {}".format(cadastro, info_contato[cadastro][0], info_contato[cadastro][1],
info_contato[cadastro][2], info_contato[cadastro][3]))
menu_programa()
def listagem_usuarios(): # Gerar o relatório
print("Nome \t\t Telefone \t Email \t\t Twitter \t Instagram")
for cadastro in info_contato.keys():
print("{} \t\t {} \t {} \t {} \t {}".format(cadastro, info_contato[cadastro][0], info_contato[cadastro][1],
info_contato[cadastro][2], info_contato[cadastro][3]))
menu_programa()
menu_programa()
|
91228313f8bdd02978fc15cc2a85f97a652d546e | sam-littlefield/EulerProject | /project/problem1/bruteSolution.py | 116 | 3.875 | 4 | total = 0
for i in range(1000):
if ((i % 3) == 0) or ((i % 5) == 0):
total += i
print('Total: ', total)
|
dc643b6440db3dac84378c3277b1b91a11642332 | DanielSoaresFranco/Aulas.py | /exercícios/ex007.py | 305 | 3.578125 | 4 | n1 = float(input('primeira nota do aluno: '))
n2 = float(input('segunda nota do aluno: '))
m = (n1+n2)/2
limpa = '\033[m'
roxo = '\033[1;35m'
ciano = '\033[1;36m'
cinza = '\033[1;37m'
print('a média entre {}{:.1f}{} e {}{:.1f}{} é {}{:.1f}{}'.format(roxo, n1, limpa, ciano, n2, limpa, cinza, m, limpa))
|
d88761b9467282797e713a351de8700f1bfbeacc | KateZi/Advent_of_Code | /Day 6 (Unused).py | 1,363 | 4 | 4 | class Planet:
def __init__(self, name):
self.name = name
self.moons = list()
self.star = None
def add_moon(self, moon):
self.moons.append(moon)
def add_star(self, star):
self.star = star
class Universe:
def __init__(self):
self.planets = list()
def iter(self):
for planet in self.planets:
yield planet
def add_planet(self, planet):
self.planets.append(planet)
def planet_names(self):
names = list()
for planet in self.planets:
names.append(planet.name)
return names
def get_planet(self, name):
for planet in self.planets:
if planet.name == name:
return planet
return -1
my_planets = Universe()
def count_orbits(instance):
planets = instance.split(')')
planets[1] = planets[1].rstrip("\n")
if planets[0] not in my_planets.planet_names():
planet = Planet(planets[0])
my_planets.add_planet(planet)
else:
planet = my_planets.get_planet(planets[0])
moon = Planet(planets[1])
moon.add_star(planet)
planet.add_moon(moon)
with open("inputs/Test Map Data", "r") as f:
for line in f:
count_orbits(line)
for planet in my_planets.iter():
print(planet.name)
print(planet.moons)
print(planet.star) |
c720aa5fbedb00ea2d6bd7cad5b29eff90f790e2 | kalehub/tuntas-hacker-rank | /designer-pdf.py | 714 | 3.78125 | 4 | from string import ascii_lowercase
def design_pdf_viewer(char_height, word):
word = word.lower()
list_of_words = list()
# dictionary to know the alphabet
ALPHABET = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=0)}
numbers = [ALPHABET[w] for w in word if w in ALPHABET]
for n in numbers:
list_of_words.append(char_height[int(n)])
return max(list_of_words)*len(word)
def main():
# result = design_pdf_viewer([1,3,1,3,1,4,1,3,2,5,5,5,5,1,1,5,5,1,5,2,5,5,5,5,5,5], "torn")
result = design_pdf_viewer([1,3,1,3,1,4,1,3,2,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], "abc")
print(f"Hasil: {result}")
if __name__ == "__main__":
main()
|
b4a482cec0058b92a7087ba4f8a8e57f69db22cf | Fazlur9/PBO | /PBO_19188/Latihan_13_angkaterbilang.py | 762 | 3.765625 | 4 | def Terbilang(bil):
angka=["","Satu","Dua","Tiga","Empat","Lima","Enam","Tujuh","Delapan","Sembilan","Sepuluh","Sebelas"]
Hasil =" "
n = int(bil)
if n >= 0 and n <= 11:
Hasil = Hasil + angka[n]
elif n < 20:
Hasil = Terbilang(n % 10) + " Belas"
elif n < 100:
Hasil = Terbilang(n / 10) + " Puluh" + Terbilang(n % 10)
elif n < 200:
Hasil = " Seratus" + Terbilang(n - 100)
elif n < 1000:
Hasil = Terbilang(n / 100) + " Ratus" + Terbilang(n % 100)
elif n == 1000 :
Hasil = " Seribu"
else:
Hasil="Angka hanya sampai seribu"
return Hasil
if __name__ == '__main__':
bil = input("Input Angka : ")
blng= Terbilang(bil )
print (bil+blng) |
1cf70bfde362453b958964f621871458ea548e5e | rafal3008/Pong_old | /pong.py | 1,206 | 3.59375 | 4 | from objects import *
from utility import *
# pyGame essentials
pygame.init()
clock = pygame.time.Clock()
# main window
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Pong:The Game')
# creating game obj
ball = Ball(WIDTH / 2 - 15, HEIGHT / 2 - 15, 30, 30, white)
player = Player(WIDTH - 20, HEIGHT / 2 - 70, 10, 120, white)
opponent = Opponent(10, HEIGHT / 2 - 70, 10, 120, white, 4)
def main():
run = True
# scores
player_score = 0
opponent_score = 0
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
player.move()
ball.move()
opponent.ai_movement(ball)
if check_collision_player(ball, player) or check_collision_opponent(ball, opponent):
ball.collide()
score(ball)
if ball.off_screen():
if ball.x <= 0:
player_score += 1
elif ball.x + ball.width >= WIDTH:
opponent_score += 1
ball.reset_pos()
redrawWindow(WINDOW, ball, player, opponent, player_score, opponent_score)
main()
|
055c2488bc740b7dd3226686b1a420617f8d86d0 | chanjun2005/ChemistryCalculators | /lussaclaw.py | 1,664 | 3.59375 | 4 |
class Conversion:
def __init__(self):
self.atmconst = 1.01325
self.mmhgconst = 0.0013332239
self.kconst = 273.15
def atm_to_bar(self, atm):
nBar = atm * self.atmconst
return nBar
def mmhg_to_bar(self, mmhg):
nBar = mmhg * self.mmhgconst
return nBar
def bar_to_atm(self, bar):
nAtm = bar / self.atmconst
return nAtm
def bar_to_mmhg(self, bar):
nMmhg = bar / self.mmhgconst
return nMmhg
def c_to_k(self, c):
return (c + self.kconst)
def k_to_c(self, k):
return (k - self.kconst)
class Lussac:
def __init__(self, temp, pressure):
self.temp = temp
self.pressure = pressure
self.kval = (self.pressure / self.temp)
self.tempType = "k"
self.pType = "bar"
def findNewPressure(self, newTemp):
nPressure = ( (self.pressure * newTemp) / self.temp )
self.pressure = nPressure
return self
def findNewTemp(self, newPressure):
nTemp = ( (self.temp * newPressure) / self.pressure )
self.temp = nTemp
return self
def main():
con = Conversion()
problem_one = Lussac( con.c_to_k(22), con.atm_to_bar(135) ).findNewPressure(con.c_to_k(50))
print(con.bar_to_atm(problem_one.pressure))
problem_two = Lussac( con.c_to_k(20), con.mmhg_to_bar(1900) ).findNewTemp(con.mmhg_to_bar(1750))
print(con.k_to_c(problem_two.temp))
problem_three = Lussac( 150, con.atm_to_bar(1) ).findNewPressure(300)
print(con.bar_to_atm(problem_three.pressure))
main()
|
2b01debca0710e0eac38863d3a0fa2008f773225 | Maryam-ask/Python_Tutorial | /Lambda/LambdaPython.py | 654 | 3.96875 | 4 | # Add 10 to argument a, and return the result.
x = lambda a: a + 10
print(x(5))
# ****************************************************************************
# Multiply argument a with argument b and return the result.
y = lambda a, b: a * b
print(y(4, 6))
# ****************************************************************************
# Summarize argument a, b, and c and return the result.
z = lambda a, b, c: a + b + c
print(z(3, 8, 6))
# ****************************************************************************
def myfunc(n):
return lambda a: a * n
mydoubler = myfunc(2) # n ra tarif mikonim
print(mydoubler(10)) # a ra tarif mikonim
|
ef67266ecc27d6a73f52e8a22942930cc50a1516 | PepSalehi/algorithms | /ML/nlp/language_identification.py | 2,259 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Identify a language, given some text."""
from nltk import wordpunct_tokenize
from nltk.corpus import stopwords
def _nltk_to_iso369_3(name):
"""
Map a country name to an ISO 369-3 code.
See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes for an overview.
"""
name = name.lower()
return {'danish': 'dan',
'dutch': 'nld',
'english': 'eng',
'french': 'fra',
'finnish': 'fin',
'german': 'deu',
'hungarian': 'hun',
'italian': 'ita',
'norwegian': 'nor',
'portuguese': 'por',
'russian': 'rus',
'spanish': 'spa',
'swedish': 'swe',
'turkish': 'tur'}.get(name, None)
def identify_language(text):
"""
Identify a language, given a text of that language.
Parameters
----------
text : str
Returns
-------
list of tuples (ISO 369-3, score)
Examples
--------
>>> identify_language('Ich gehe zur Schule.')
[('deu', 0.8)]
"""
languages_ratios = []
tokens = wordpunct_tokenize(text)
words = [word.lower() for word in tokens]
# Check how many stopwords of the languages NLTK knows appear in the
# provided text
for language in stopwords.fileids():
stopwords_set = set(stopwords.words(language))
words_set = set(words)
common_elements = words_set.intersection(stopwords_set)
score = len(common_elements)
languages_ratios.append((language, score))
# Normalize
sum_scores = float(sum(el[1] for el in languages_ratios))
languages_ratios = [(_nltk_to_iso369_3(el[0]), el[1])
for el in languages_ratios]
if sum_scores > 0:
languages_ratios = [(el[0], el[1] / sum_scores)
for el in languages_ratios]
return sorted(languages_ratios, key=lambda n: n[1], reverse=True)
if __name__ == '__main__':
print(identify_language("Ich gehe zur Schule.")[:5])
print(identify_language("I'm going to school.")[:5])
print(identify_language("Voy a la escuela.")[:5]) # Spanish
print(identify_language("Je vais à l'école.")[:5]) # French
|
adb8d7af9c6c9ea2182b9a4d9be652eb78996bc5 | ishandutta2007/ProjectEuler-2 | /eu56.py | 1,581 | 3.90625 | 4 | # ------------------------------------------------------------- Powerful digit sum ------------------------------------------------------------ #
# #
# A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: #
# one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. #
# #
# Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum? #
# --------------------------------------------------------------------------------------------------------------------------------------------- #
import time
def getDigitalSum(n):
r = 0
while (n != 0):
r += n % 10
n //= 10
return r
def eu56():
TOP = 100
max_digital_sum = 0
for a in range(TOP):
for b in range(TOP):
if ((getDigitalSum(a ** b)) > max_digital_sum):
max_digital_sum = getDigitalSum(a ** b)
return max_digital_sum
if __name__ == "__main__":
startTime = time.clock()
print (eu56())
elapsedTime = time.clock() - startTime
print ("Time spent in (", __name__, ") is: ", elapsedTime, " sec")
|
1166b0013ef7a289787ae59f49aa40967f2e80a2 | marythought/sea-c34-python | /students/MaryDickson/session02/fibnotes.py | 402 | 3.703125 | 4 | # anna's code
def fibonacci(n):
F1 = 0
F2 = 1
F = 0
for i in range(1,(n+1)):
F1 = F2
F2 = F
F = F2 + F1
return F
def lucas(m):
F1 = 2
F2 = 1
F = 2
if m == 0:
F = 2
elif m == 1:
F = 1
else:
for i in range(1,m):
F1 = F2
F2 = F
F = F2 + F1
return F
print fibonacci(5)
|
489446c52475b54abd6a2350b0abad07ea11f2c7 | lucas72466/algorithm008-class01 | /Week_02/graph/无权图/Stack.py | 444 | 3.6875 | 4 |
class Stack:
def __init__(self):
self.data = []
def is_empty(self):
return len(self.data) == 0
def push(self, element):
return self.data.append(element)
def pop(self):
ret = self.data.pop()
return ret
def peek(self):
return self.data[0]
def size(self):
return len(self.data)
def show(self):
for i in self.data:
print(i, end=' ')
|
d50bb6c976fedf9061e84efcdf518af81d6da47d | vtyagiAggies/artificialIntelligence | /blockGame/report.py | 2,129 | 3.578125 | 4 | #!/usr/bin/python
class Report:
def __init__(self, filename="report.html"):
self.obj = open(filename, "w")
self.obj.write(
"<html><head><Title>AI Homework 2 Report</Title><style>table, th, td {border: 1px solid black;border-collapse: collapse;}th, td {padding: 5px;text-align: center;}</style></head> <body><h1 align=\"center\"><u>Analysis of different heuristics for Block game!!</u></h1><br><br><br><br><br><br><table border=\"1\" align =\"center\">")
self.obj.write(
"<tr><th>Properties</th><th>Block in place Heuristic</th><th>Customized Heuristic</th></tr>")
def iterations(self, a=-1, b=-1, c=-1):
self.obj.write(
"<tr><td><b>Iterations</b></td><td>{0}</td><td>{1}</td></tr>".format(str(a), str(c)))
def pathlength(self, a=-1, b=-1, c=-1):
self.obj.write(
"<tr><td><b>Path Length</b></td><td>{0}</td><td>{1}</td></tr>".format(str(a), str(c)))
def queuesize(self, a=-1, b=-1, c=-1):
self.obj.write(
"<tr><td><b>Maximum Queue Length</b></td><td>{0}</td><td>{1}</td></tr>".format(str(a), str(c)))
def statesvisited(self, a=-1, b=-1, c=-1):
self.obj.write(
"<tr><td><b>Number of states visited</b></td><td>{0}</td><td>{1}</td></tr>".format(str(a), str(c)))
self.obj.write("</table>")
def saveandclose(self):
self.obj.write("</body></html>")
self.obj.close()
def displaystate(self,array):
self.obj.write("\n<br/><br/><br/><br/><br/><div ><h1 ><u>Initial state</u></h1><h2 align =\"left\">")
k = 1
for stack in array:
self.obj.write("Stack {0} : {1} <br>".format(k, str(stack)))
k += 1
self.obj.write("</h2></div>")
def displayfilepath(self):
self.obj.write("\n<br/><br/><br/><br/><br/><div ><h1 ><u>Path to goal state</u></h1><h2 align =\"left\">")
self.obj.write("<ul><li><a href=\"inplaceblocks_solution.txt\">In Place Blocks Heuristic</a></li> <li><a href=\"customheuristic_solution.txt\">Custom Heuristic</a></li></ul>")
self.obj.write("</h2></div>") |
6bfb01d4998d9ba703156a93a9f4dff434c41161 | wyfapril/CS6112017 | /PythonExercises/exercise7.py | 187 | 3.984375 | 4 | def print_list(list):
for i in list:
print(i)
def print_reversed_list(list):
for i in reversed(list):
print(i)
def len(list):
count = 0
for i in list:
count += 1
return count |
2dc6e7d3a331e4e9b3054f51bace71010c6024f1 | kaiwensun/leetcode | /1001-1500/1496.Path Crossing.py | 460 | 3.578125 | 4 | class Solution:
def isPathCrossing(self, path: str) -> bool:
cur = (0, 0)
seen = {cur}
deltamap = {
"N": (0, 1),
"S": (0, -1),
"E": (1, 0),
"W": (-1, 0)
}
for step in path:
delta = deltamap[step]
cur = (cur[0] + delta[0], cur[1] + delta[1])
if cur in seen:
return True
seen.add(cur)
return False
|
43dc9a88b62080a2e7667dbd1610fdaaded67586 | Rrrapture/python-the-hard-way | /ex/ex19.py | 1,268 | 4.1875 | 4 | #Python the Hard Way exercise 19
#this function takes two arguments, and prints the first argument value,
#then the second argument value, then an exclamation sentence, then a command
#sentence followd by an extra line break
#I forget what the "d" is.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Woman that's enough for a party!"
print "Get a basket.\n"
#the following command prints a sentence, then
#calls our cheese and crackers function,
#passing number values for our cheese count
#and boxes_of_crackers values
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
#the following command prints a sentence, sets the value of two
#variables to numbers, then calls our cheese and crackers function
#referencing the variables we just defined.
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print "We could also do math inside, too:"
cheese_and_crackers(10 + 20, 5 + 6)
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) |
e21995056e7e7295ca596e645dfeabf3879c35ba | minotaur423/Python3 | /Python-Scripts/prob8.py | 955 | 4.21875 | 4 | # Arithmetic Progression
# You are to calculate the sum of first members of arithmetic sequence.
# Input data: first line contains the number of test-cases. Other lines
# contain test-cases in form of triplets of values A B N where A is the first
# value of the sequence, B is the step size and N is the number of first values
# which should be accounted.
# Answer: you are to output results (sums of N first members) for each sequence,
# separated by spaces.
def sum_progression(a,b,n):
result_list = []
result_list.append(a)
for i in range(1,n):
a += b
result_list.append(a)
return sum(result_list)
values = '8 13 99 20 19 18 24 7 84 15 8 96 20 12 19 16 13 38 23 11 74 10 16 48'
values_list = values.split(' ')
total = 0
int_list = []
for value in values_list:
int_list += [int(value)]
for i in range(0,len(int_list),3):
total = sum_progression(int_list[i],int_list[i+1],int_list[i+2])
print(total, end=' ') |
764520c900f7650e5fe1cb181bf9cb31d645eebc | VCloser/CodingInterviewChinese2-python | /11_MinNumberInRotatedArray.py | 685 | 3.859375 | 4 | def find_in_order(arr, start, end):
min_ = arr[start]
for i in range(start+1,end+1):
if min_ > arr[i]:
min_ = arr[i]
return min_
def find_min_in_rotate_arr(arr):
p1 = 0
p2 = len(arr)-1
while arr[p1]>=arr[p2]:
if p2-p1==1:
return arr[p2]
mid = (p1+p2)//2
if arr[p1] == arr[p2] and arr[p1] == arr[mid]:
return find_in_order(arr,p1,p2)
if arr[p1]<=arr[mid]:
p1 = mid
elif arr[p2]>=arr[mid]:
p2 = mid
return arr[mid]
if __name__ == "__main__":
print(find_min_in_rotate_arr([3, 4, 5, 1, 2]))
print(find_min_in_rotate_arr([1, 1, 0, 1, 1])) |
e0fe6db28befd4ea87ca7f707b283ce5acb05fb2 | jfs-coder/learn-py | /comprehensions.py | 870 | 3.9375 | 4 | # comprehensions - populate a list in declaration.
# populates a list with numbers 0 to 99
x = [x for x in range(100)]
print(x)
# adds 2 to the start of the range
x = [x + 2 for x in range(10)]
print(x)
# puts 100 zeroes in a list
x = [0 for x in range(100)]
print(x)
# puts 100 'a' in a list
z = ['a' for x in range(100)]
print(z)
# populate lists of lists
d = [[7 for x in range(10)] for x in range(5)]
print(d)
# add conditions (modulo example here)
m = [i for i in range(100) if i % 5 == 0] # will print out 0, 5, 10, 15, ... 95
print(m)
# also works for dictionaries
dct = {i:0 for i in range(10) if i % 2 == 0} # will populate dict with all even numbers between 0-10
print(dct)
# and sets
st = {i for i in range(60) if i % 3 == 0} # will populate set with all modulo results
print(st)
# dont forget tuples
tp = tuple(i for i in range(40) if i % 4 == 0)
print(tp)
|
95fcf8f3a85d7fdde140eac606554cf6cefcb241 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4428/codes/1595_842.py | 313 | 3.84375 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
num = int(input("Digite um numero: "))
soma = 0
while(num > 0):
resto = num % 10
num = num//10
soma = soma+resto
print(soma) |
04c1c3bf32fcc18284b4a19e022db81aa77128f2 | youkidearitai/Arduino_LED_on_Python | /section3/hundred_push.py | 596 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class HundredPush(object):
def __init__(self):
self.count = 0
def push(self, line):
if (self.count % 100 == 9):
print("Lチカ!!: {0}".format(line.strip()))
self.count = self.count + 1
return True
print("{0}".format(self.count))
self.count = self.count + 1
return False
def closed(self):
"""
プログラムを終了するときに closed connection と出力して終わりを表示させる
"""
print("closed connection")
|
5a56d27dc11c0289d00ac654f0d7737d8422e84f | almamuncsit/Data-Structures-and-Algorithms | /Data-Structure/09-linked-lists-03-remove.py | 2,065 | 3.921875 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
def print_list(self):
print_val = self.head
while print_val is not None:
print(print_val.data)
print_val = print_val.next
def add_at_beginning(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def add_at_end(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
temp_val = self.head
while temp_val.next:
temp_val = temp_val.next
temp_val.next = new_node
def add_in_middle(self, middle_node, new_data):
new_node = Node(new_data)
new_node.next, middle_node.next = middle_node.next, new_node
def remove_node(self, remove_data):
head_val = self.head
# Remove if data is the first element
if head_val is not None:
if head_val.data == remove_data:
self.head = head_val.next
head_val = None
return
# find out the data node and previous node
while head_val is not None:
if head_val.data == remove_data:
break
prev = head_val
head_val = head_val.next
# Return if head val is empty
if head_val == None:
return
# Remove item from linked list
prev.next = head_val.next
head_val = None
if __name__ == "__main__":
linked_list = SLinkedList()
linked_list.head = Node("Sat")
e1 = Node("Sun")
e2 = Node("Mon")
linked_list.head.next = e1
e1.next = e2
linked_list.add_at_beginning('Welcome')
linked_list.add_at_end('Dhaka')
linked_list.add_in_middle(e2, 'Mid')
print("Before Remove")
linked_list.print_list()
print("After Remove")
linked_list.remove_node('Mon')
linked_list.print_list()
|
76d77c32fbd94a1dff999f894dcf26a7aa208691 | amesy/golang_note | /数组练习/数组练习.py | 341 | 3.71875 | 4 | import math
def for_(num_half, res):
for i in range(num_half):
res.append(i)
res.append(-i)
return res
def array(num, res=[]):
num_half = math.ceil(num/2)
# num为偶数
if num % 2 == 0:
return for_(num_half, res)
# num为奇数
L = for_(num_half, res)
return L[1:]
print(array(7)) |
c501ca8f0ece9587841ef244f7fad0dacc710915 | yovanycunha/P1 | /opbancarias/opbancarias.py | 500 | 3.8125 | 4 | #coding: utf-8
# Operações Bancárias
# (C) 2016, Yovany Cunha/UFCG, Programaçao I
cliente,saldo = raw_input('').split()
saldo = float(saldo)
while True:
entrada = raw_input('')
if entrada == '3': break
operacao,quantia = entrada.split()
operacao = int(operacao)
quantia = float(quantia)
if operacao == 1:
#quantia = float(raw_input(''))
saldo -= quantia
elif operacao == 2:
#quantia = float(raw_input(''))
saldo += quantia
print 'Saldo de R$ %.2f na conta de %s' % (saldo, cliente)
|
c4536d6b936c0e27d31cfcdb12162ac8edb4a10b | Nanofication/MultinomialBayes | /MultinomialBayesTutorial.py | 6,220 | 3.640625 | 4 | """
Following NLTK tutorial on classifying sentences and intents
"""
import nltk
from nltk.stem.lancaster import LancasterStemmer
#Word Stemmer. Reduce words to the root forms. Better for classifying
stemmer = LancasterStemmer()
# 3 classes of training data. Play around with this
training_data = []
training_data.append({"class":"greeting", "sentence":"how are you?"})
training_data.append({"class":"greeting", "sentence":"how is your day?"})
training_data.append({"class":"greeting", "sentence":"good day"})
training_data.append({"class":"greeting", "sentence":"how is it going today?"})
training_data.append({"class":"greeting", "sentence":"what's up?"})
training_data.append({"class":"greeting", "sentence":"hi"})
training_data.append({"class":"greeting", "sentence":"how are you doing?"})
training_data.append({"class":"greeting", "sentence":"what's new?"})
training_data.append({"class":"greeting", "sentence":"how's life?"})
training_data.append({"class":"greeting", "sentence":"how are you doing today?"})
training_data.append({"class":"greeting", "sentence":"good to see you"})
training_data.append({"class":"greeting", "sentence":"nice to see you"})
training_data.append({"class":"greeting", "sentence":"long time no see"})
training_data.append({"class":"greeting", "sentence":"it's been a while"})
training_data.append({"class":"greeting", "sentence":"nice to meet you"})
training_data.append({"class":"greeting", "sentence":"pleased to meet you"})
training_data.append({"class":"greeting", "sentence":"how do you do"})
training_data.append({"class":"greeting", "sentence":"yo"})
training_data.append({"class":"greeting", "sentence":"howdy"})
training_data.append({"class":"greeting", "sentence":"sup"})
# 20 training data
training_data.append({"class":"goodbye", "sentence":"have a nice day"})
training_data.append({"class":"goodbye", "sentence":"see you later"})
training_data.append({"class":"goodbye", "sentence":"have a nice day"})
training_data.append({"class":"goodbye", "sentence":"talk to you soon"})
training_data.append({"class":"goodbye", "sentence":"peace"})
training_data.append({"class":"goodbye", "sentence":"catch you later"})
training_data.append({"class":"goodbye", "sentence":"talk to you soon"})
training_data.append({"class":"goodbye", "sentence":"farewell"})
training_data.append({"class":"goodbye", "sentence":"have a good day"})
training_data.append({"class":"goodbye", "sentence":"take care"})
# 10 training datas
training_data.append({"class":"goodbye", "sentence":"bye!"})
training_data.append({"class":"goodbye", "sentence":"have a good one"})
training_data.append({"class":"goodbye", "sentence":"so long"})
training_data.append({"class":"goodbye", "sentence":"i'm out"})
training_data.append({"class":"goodbye", "sentence":"smell you later"})
training_data.append({"class":"goodbye", "sentence":"talk to you later"})
training_data.append({"class":"goodbye", "sentence":"take it easy"})
training_data.append({"class":"goodbye", "sentence":"i'm off"})
training_data.append({"class":"goodbye", "sentence":"until next time"})
training_data.append({"class":"goodbye", "sentence":"it was nice seeing you"})
training_data.append({"class":"goodbye", "sentence":"it's been real"})
training_data.append({"class":"goodbye", "sentence":"im out of here"})
training_data.append({"class":"sandwich", "sentence":"make me a sandwich"})
training_data.append({"class":"sandwich", "sentence":"can you make a sandwich?"})
training_data.append({"class":"sandwich", "sentence":"having a sandwich today?"})
training_data.append({"class":"sandwich", "sentence":"what's for lunch?"})
training_data.append({"class":"email", "sentence":"what's your email address?"})
training_data.append({"class":"email", "sentence":"may I get your email?"})
training_data.append({"class":"email", "sentence":"can I have your email?"})
training_data.append({"class":"email", "sentence":"what's your email?"})
training_data.append({"class":"email", "sentence":"let me get your email"})
training_data.append({"class":"email", "sentence":"give me your email"})
training_data.append({"class":"email", "sentence":"i'll take your email address"})
training_data.append({"class":"email", "sentence":"can I have your business email?"})
training_data.append({"class":"email", "sentence":"your email address?"})
training_data.append({"class":"email", "sentence":"email please?"})
training_data.append({"class":"email", "sentence":"may I have your email?"})
training_data.append({"class":"email", "sentence":"can I get your email?"})
# Capture unique stemmed words
corpus_words = {}
class_words = {}
# Turn a list into a set of unique items and then a list again to remove duplications
classes = list(set([a['class'] for a in training_data]))
for c in classes:
class_words[c] = []
# Loop through each sentence in our training data
for data in training_data:
# Tokenize each sentence into words
for word in nltk.word_tokenize(data['sentence']):
# ignore some things
if word not in ["?", "'s"]:
stemmed_word = stemmer.stem(word.lower())
# Have we not seen this word already?
if stemmed_word not in corpus_words:
corpus_words[stemmed_word] = 1
else:
corpus_words[stemmed_word] += 1
# Add the word to our words in class list
class_words[data['class']].extend([stemmed_word])
print("Corpus words and counts: {0}").format(corpus_words)
# Class words
print("Class words: {0}").format(class_words)
# We may have to weigh each word differently. What if I'm asking for your email.
def calculate_class_score(sentence, class_name, show_details = True):
score = 0
for word in nltk.word_tokenize(sentence):
if stemmer.stem(word.lower()) in class_words[class_name]:
# Treat each word with relative weight
score += (1.0 / corpus_words[stemmer.stem(word.lower())])
if show_details:
print (" match: %s (%s)" % (stemmer.stem(word.lower()), 1.0 / corpus_words[stemmer.stem(word.lower())]))
return score
sentence = ""
for c in class_words.keys():
print("Class: {0} Score: {1}").format(c, calculate_class_score(sentence, c)) |
68d8544b3bfa8c86377dd60ff99350f7e4447161 | learnables/learn2learn | /learn2learn/nn/misc.py | 3,226 | 3.65625 | 4 | #!/usr/bin/env python3
import torch
class Lambda(torch.nn.Module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/nn/misc.py)
**Description**
Utility class to create a wrapper based on a lambda function.
**Arguments**
* **lmb** (callable) - The function to call in the forward pass.
**Example**
~~~python
mean23 = Lambda(lambda x: x.mean(dim=[2, 3])) # mean23 is a Module
x = features(img)
x = mean23(x)
x = x.flatten()
~~~
"""
def __init__(self, lmb):
super(Lambda, self).__init__()
self.lmb = lmb
def forward(self, *args, **kwargs):
return self.lmb(*args, **kwargs)
class Flatten(torch.nn.Module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/nn/misc.py)
**Description**
Utility Module to flatten inputs to `(batch_size, -1)` shape.
**Example**
~~~python
flatten = Flatten()
x = torch.randn(5, 3, 32, 32)
x = flatten(x)
print(x.shape) # (5, 3072)
~~~
"""
def forward(self, x):
return x.view(x.size(0), -1)
class Scale(torch.nn.Module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/nn/misc.py)
**Description**
A per-parameter scaling factor with learnable parameter.
**Arguments**
* **shape** (int or tuple, *optional*, default=1) - The shape of the scaling matrix.
* **alpha** (float, *optional*, default=1.0) - Initial value for the
scaling factor.
**Example**
~~~python
x = torch.ones(3)
scale = Scale(x.shape, alpha=0.5)
print(scale(x)) # [.5, .5, .5]
~~~
"""
def __init__(self, shape=None, alpha=1.0):
super(Scale, self).__init__()
if isinstance(shape, int):
shape = (shape, )
elif shape is None:
shape = (1, )
alpha = torch.ones(*shape) * alpha
self.alpha = torch.nn.Parameter(alpha)
def forward(self, x):
return x * self.alpha
def freeze(module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/nn/misc.py)
**Description**
Prevents all parameters in `module` to get gradients.
Note: the module is modified in-place.
**Arguments**
* **module** (Module) - The module to freeze.
**Example**
~~~python
linear = torch.nn.Linear(128, 4)
l2l.nn.freeze(linear)
~~~
"""
for p in module.parameters():
p.detach_()
if hasattr(p, 'requires_grad'):
p.requires_grad = False
return module
def unfreeze(module):
"""
[[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/nn/misc.py)
**Description**
Enables all parameters in `module` to compute gradients.
Note: the module is modified in-place.
**Arguments**
* **module** (Module) - The module to unfreeze.
**Example**
~~~python
linear = torch.nn.Linear(128, 4)
l2l.nn.freeze(linear)
l2l.nn.unfreeze(linear)
~~~
"""
for p in module.parameters():
if hasattr(p, 'requires_grad'):
p.requires_grad = True
return module
|
75b51c3849d56dd249e2ca7b8a4a7dac2f6059a9 | balupawar/python-code | /faultyCalculator.py | 900 | 4.21875 | 4 | # create faulty calculator
# balu pawar
# 25/6 = 44
# 88+44 = 0
#10-10 =12
print("Enter first number:")
number1= int(input())
print("choose operation on number , + ,- / , *")
operator = input()
print("Enter Second Number")
number2 = int(input())
if number1 == 26 and operator == '/' and number2== 6:
print("44")
elif number1 == 88 and operator == '+' and number2 == 44:
print("0")
elif number1 == 10 and operator == '-' and number2 == 12:
print("12")
elif operator == '+':
addition = number1 + number2
print(addition)
elif operator == '-':
substraction = number1 - number2
print(substraction)
elif operator == '*':
multiplication = number1/number2
print(multiplication)
elif operator == '/':
division = number1 / number2
print(division)
elif operator == '%':
modulus = number1 % number2
print(modulus)
else:
print("please insert correct input")
|
603bba57b53d042242bad85209c65b350b96353c | bikendra-kc/pythonProject512 | /set/number6.py | 139 | 4.0625 | 4 | '''6. Write a Python program to create an intersection of sets'''
a={1,2,3,4,5,6}
b={4,5,7,8,9}
print(f'the intersection of sets is :',a&b) |
b4986bbe06c38b2228672d5ecaf22a26c10a2a6e | BeginnerA234/codewars | /задача_7_8kyu.py | 155 | 3.5625 | 4 | def positive_sum(arr):
return sum(i for i in arr if i>0)
print(positive_sum([1,2,3,4,5]))
# https://www.codewars.com/kata/5715eaedb436cf5606000381 |
8fd467a3620217d72043e9ec6857404c5d82a310 | wickedkat/KatsLair | /user_verification.py | 1,025 | 3.5 | 4 | import password_handler
from database import data_handler
def check_user_in_database(username):
'''
Function calls database query, that returns user data by username given.
If there is no username in database, it returns False
:argument
username - dictionary
:returns
user_exists - dictionary
or
False
'''
user_exists = data_handler.select_user_by_username(username)
if user_exists:
return user_exists
else:
return False
def verify_user(user):
'''
Function chcecks if username and password given in the login form are identical with
credentials in database.
:argument
user - dict
:returns
True or False
'''
username = user['username']
form_password = user['password']
user_in_base = check_user_in_database(username)
if user_in_base:
password_in_base = user_in_base['password']
verify = password_handler.verify_password(form_password, password_in_base)
if verify:
return True
return False
|
93cb47db4f8c827d1e835b3589b7c42c806bb5f9 | ericgarig/daily-coding-problem | /192-crawl-list-to-end.py | 802 | 4.03125 | 4 | """
Daily Coding Problem - 2019-04-18.
You are given an array of nonnegative integers. Let's say you start at the
beginning of the array and are trying to advance to the end. You can advance
at most, the number of steps that you're currently on. Determine whether you
can get to the end of the array.
For example, given the array [1, 3, 1, 2, 0, 1],
we can go from indices 0 -> 1 -> 3 -> 5, so return true.
Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false.
"""
def solve(arr):
"""Determine if you can reach the final element in the array."""
if len(arr) <= 1:
return True
for i in range(arr[0], 0, -1):
if solve(arr[i:]):
return True
return False
assert solve([1, 3, 1, 2, 0, 1]) is True
assert solve([1, 2, 1, 0, 0]) is False
|
ed57a10b6e3b4208cdb14a413302da3c0871588e | sunamya/Data-Structures-in-Python | /Interview Questions/LinkedList/FlattenALinkedList.py | 2,112 | 3.828125 | 4 | #User function Template for python3
'''
class Node:
def __init__(self, d):
self.data=d
self.next=None
self.bottom=None
'''
def sortedMerge(a,b):
if a is None:
return b
elif b is None:
return a
if a.data <= b.data:
result = a
result.bottom = sortedMerge(a.bottom, b)
else:
result = b
result.bottom = sortedMerge(a, b.bottom)
return result
def flatten(root):
#Your code here
if root==None:
return root
sorted = sortedMerge(root, flatten(root.next))
root.next = None
return sorted
#{
# Driver Code Starts
#Initial Template for Python 3
class Node:
def __init__(self, d):
self.data=d
self.next=None
self.bottom=None
def printList(node):
while(node is not None):
print(node.data,end=" ")
node=node.bottom
print()
if __name__=="__main__":
t=int(input())
while(t>0):
head=None
N=int(input())
arr=[]
arr=[int(x) for x in input().strip().split()]
temp=None
tempB=None
pre=None
preB=None
flag=1
flag1=1
listo=[int(x) for x in input().strip().split()]
it=0
for i in range(N):
m=arr[i]
m-=1
a1=listo[it]
it+=1
temp=Node(a1)
if flag is 1:
head=temp
pre=temp
flag=0
flag1=1
else:
pre.next=temp
pre=temp
flag1=1
for j in range(m):
a=listo[it]
it+=1
tempB=Node(a)
if flag1 is 1:
temp.bottom=tempB
preB=tempB
flag1=0
else:
preB.bottom=tempB
preB=tempB
root=flatten(head)
printList(root)
t-=1
# } Driver Code Ends |
d57870a7a45b520062d60b7fa34930a480212e3a | DAVIDMIGWI/python | /Bill.py | 777 | 4.09375 | 4 |
units = float(input("Enter your units:-"))
if units < 50:
total = units * 0.5
print("Kindly pay",total,"Rs")
print("Inc. surcharge", total + 10)
elif units > 50 and units <=150:
pay1 = 50 * 0.5
pay2 = units - 50 * 1
total = pay1 + pay2
print("pay",total)
print("Inc. surcharge", total + 10)
elif units > 150 and units < 250:
pay1 = 50 * 0.5
pay2 = 100 * 1
pay3 = units - 150 * 1.2
total = pay3 +pay1 +pay2
print("Kindly pay", total, "Rs")
print("Inc. surcharge", total + 10)
else:
pay1 = 50 * 0.5
pay2 = 100 * 1
pay3 = 100 * 1.2
pay4 = units - 250 * 1.5
total = pay3 + pay1 + pay2 + pay4
print("Kindly pay", total, "Rs")
print("Inc. surcharge", total + 10)
|
2daf6d39f903b9e208ce1e56129dd5672cfcc678 | mylgood/myl_good_demo | /new_word.py | 416 | 3.625 | 4 | import math
class my_math(object):
def __init__(self,name):
self.name = name
def my_sum(self,a):
s = 0
for i in a:
s += i
return s
def add(self,a,b):
return a+b
def cos(self,a):
return math.cos(a)
def __repr__(self):
return self.name
# a = [1,2,3]
# ma = my_math("mylll")
# print(ma)
# print(ma.add(1, 2))
# print(ma.my_sum(a)) |
272751e04480a014a0369d2c24d936b39b415c9a | rajlath/rkl_codes | /code-signal/maxTeam.py | 1,025 | 3.59375 | 4 | players = [[88, 47, 42, 21],
[40, 76, 21, 22],
[45, 92, 1, 1],
[22, 23, 10, 11],
[1, 100, 1, 0],
[40, 70, 90, 80],
[40, 12, 45, 12],
[40, 80, 81, 80],
[40, 50, 60, 70],
[0, 0, 0, 99],
[12, 54, 44, 55]]
'''
he best team could be chosen as follows:
goalkeeper: player 0 (88)
defenders: players 1, 2, 3, and 4 (76 + 92 + 23 + 100 = 291)
midfielders: players 5, 6, and 7 (90 + 45 + 81 = 216)
forwards: players 8, 9, and 10 (70 + 99 + 55 = 224)
For a grand total of 88 + 291 + 216 + 224 = 819
'''
def theBestTeam(players):
positions = (players)
max_score = 0
for i in range(11):
if i == 0:
max_score += max(positions[0])
if i in range(1,5):
max_score += positions[i][1]
if i in range(5,8):
max_score += positions[i][2]
else:
max_score += positions[i][3]
print(max_score)
return max_score
print(theBestTeam(players))
|
b6a1972792e3a1c97360aab77a7ffd96ac1a32a6 | nicholas-babcock1995/mycode | /iceAndFire04.py | 1,811 | 3.75 | 4 | #!/usr/bin/python3
"""Alta3 Research - Exploring OpenAPIs with requests"""
# documentation for this API is at
# https://anapioficeandfire.com/Documentation
import requests
import pprint
AOIF_CHAR = "https://www.anapioficeandfire.com/api/characters/"
AOIF_HOUSES = "https://www.anapioficeandfire.com/api/houses/"
def main():
## Ask user for input
got_charToLookup = input("Pick a number between 1 and 1000 to return info on a GoT character! " )
## Send HTTPS GET to the API of ICE and Fire character resource
gotresp = requests.get(AOIF_CHAR + got_charToLookup)
## Decode the response
got_dj = gotresp.json()
pprint.pprint(got_dj)
print("------------------------------------------------------------------")
print("CODE CUSTOMIZATION")
#i think we should store the requests for the house information seperatel
print("Associated HOUSES!")
if 'allegiances' in got_dj:
for allegiance in got_dj['allegiances']:
houseresp = requests.get(allegiance)
house_json = houseresp.json()
if 'name' in house_json:
print(house_json['name'])
print("Associated Books!")
if 'books' in got_dj:
for book in got_dj['books']:
bookresp = requests.get(book)
book_json = bookresp.json()
if 'name' in book_json:
print(book_json['name'])
if 'povBooks' in got_dj:
for pov_book in got_dj['povBooks']:
pov_book_resp = requests.get(pov_book)
pov_book_json = pov_book_resp.json()
if 'name' in pov_book_json:
print(pov_book_json['name'])
if __name__ == "__main__":
main()
|
bb6d644b15d64855dedf07978397a2fb7751a142 | Ameyg1/Pythonbasics | /time and dates/timing1.py | 534 | 4.25 | 4 | from datetime import date, time, datetime
def main():
today= date.today()
print("Today's date is ",today) #todays date
print("Date componenents:",today.day,today.month,today.year)#notice the comma
print("Today's weekday is :",today.weekday())
days=["mon","tue","wed","thurs","fri","sat","sun"]
print("Which is a",days[today.weekday()])
today=datetime.now()
print("Current time and date:",today)
time=datetime.time(datetime.now())
print("time is :",time)
if __name__=="__main__":
main()
|
bdfd90db7d56b98a6be6ab63ce65e57da7397923 | Griffinw15/Data-Structures | /binary_search_tree/alt_part2_bst.py | 3,652 | 4.09375 | 4 | def in_order_print(self, node):
# Base case
if node is None:
return
else:
# Start printing from the far left(lowest # always furthest to the left)
# Recursively print from low to high, left to right
# (Print order not node values)
# 4
# 2 5
# 1 3 6 7
self.in_order_print(node.left)
print(node.value)
self.in_order_print(node.right)
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
# BFT = FIFO = Queue
def bft_print(self, node):
# Instantiate the queue class
queue = Queue()
# Start the queue at the root node
queue.enqueue(node)
# While loop to check the size of the queue until its empty
while queue.size > 0:
# Pointer variable (updates beginning of each loop)
current_node = queue.dequeue()
# Iteratively print from high to low, left to right
# (Print order not node values)
# 1
# 2 3
# 4 5 6 7
print(current_node.value)
if current_node.left:
queue.enqueue(current_node.left)
if current_node.right:
queue.enqueue(current_node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
# DFT = LIFO = Stack
def dft_print(self, node):
# Instantiate the stack class
stack = Stack()
# Start the stack at the root node
stack.push(node)
# While loop to check the size of the stack until its empty
while stack.size > 0:
# Pointer variable (updates beginning of each loop)
current_node = stack.pop()
# Iteratively print from high to low, left to right
# (Print order not node values)
# 1
# 2 5
# 3 4 6 7
print(current_node.value)
if current_node.left:
stack.push(current_node.left)
if current_node.right:
stack.push(current_node.right)
# Stretch Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self, node):
# Base case
if node is None:
return
else:
# Start printing from the top
# Recursively print from high to low, left to right
# (Print order not node values)
# 1
# 2 5
# 3 4 6 7
print(node.value)
self.pre_order_dft(node.left)
self.pre_order_dft(node.right)
# Print Post-order recursive DFT
def post_order_dft(self, node):
# Base case
if node is None:
return
else:
# Start printing from the far left(lowest # always furthest to the left)
# Recursively print from low to high, left to right
# (Print order not node values)
# 7
# 5 6
# 1 2 3 4
self.post_order_dft(node.left)
self.post_order_dft(node.right)
print(node.value)
#alt dft_print
def dft_print(self, node):
stack = []
stack.append(node)
while stack:
if node.left is not None:
stack.append(node.left)
if node.right is not None:
stack.append(node.right)
print(node.value)
node = stack.pop() |
57d5566f750f28cf151dbfab9bda87156d2ca308 | cnzau/self_learning_clinic_xii_oop | /student.py | 1,199 | 3.890625 | 4 | #!/usr/bin/env python3
from datetime import date
class Person(object):
"""
This is the super class
"""
def __init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
class Instructor(Person):
"""
Inherits from Person class
"""
def __init__(self, f_name, l_name, courses):
super().__init__(f_name, l_name)
self.courses = courses
class Student(Person):
"""
Inherits from person
"""
# student class variable
current_id = 0
def __init__(self, f_name, l_name, courses):
super().__init__(f_name, l_name)
self.courses = courses
self.id = self.generate_id()
def attend_class(self, date, **kwargs):
"""
Attend class function
"""
if date == date.today():
Db.attendance_list[self.id] = [self.f_name, self.l_name]
def generate_id(self):
"""
Increment class variable with new method call for each instance
Assing it to instance
"""
Student.current_id += 1
i_d = Student.current_id
return i_d
class Db():
"""
storage class
"""
attendance_list = {}
|
a61c6aad2d30356987a373d7768ca6cf5fb8a819 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#192 Find the Remainder.py | 615 | 4.25 | 4 | # Task:
# Write a function that accepts two integers and returns the remainder of
# dividing the larger value by the smaller value.
#
# Division by zero should return an empty value.
#
# Examples:
# n = 17
# m = 5
# result = 2 (remainder of `17 / 5`)
#
# n = 13
# m = 72
# result = 7 (remainder of `72 / 13`)
#
# n = 0
# m = -1
# result = 0 (remainder of `0 / -1`)
#
# n = 0
# m = 1
# result - division by zero (refer to the specifications on how to handle this
# in your language)
def remainder(a, b):
if min(a, b) == 0:
return None
elif a > b:
return a % b
else:
return b % a
|
0618cb5f3bdf03d8d637e7626921259cff05eac4 | akrivko/learn_python | /tuple.py | 1,700 | 3.796875 | 4 | # tuple
t = 123, 'fdsf'
r = 4234, '34234sdfs', 'sdfsdf'
print (t)
t = t,r
print (t)
print (t[1][2])
l = 'lonely',
print (l)
a, b = t
print(a,'\n',b)
from math import pow
x = int(625) #int(input('Enter the Number:'))
y = 5 #int(input('Enter the root:'))
#write down your logic here
print (x,y)
p = float(pow(x,1/y))
if (x == int(625)) and (y == 5):
print('{0:.11f}'.format(p))
else:
print('{0:.1f}'.format(p))
#
# from urllib2 import urlopen as url_o
a = 5
###############################
# function
###############################
def func1():
'"first function"'
global a
a = 10
return 1
print(func1.__doc__)
func1()
print(a)
def with_param(a = 1, b = 2):
print(a, b)
with_param()
with_param(b=6)
with_param(10, 20)
def average(*args):
sum = 0.0
for arg in args:
sum += arg
return sum/len(args)
print(average(1,5,3,5,3,2,7,4,9,9,5,6,3))
# dictionaries
my_dict = {'a':1, 'b':2, 'c':3}
my_dict['d'] = 4
print(my_dict['a'])
def foo_kwards(farg, **kwargs):
print ("formal arg:", farg)
for key in kwargs:
print ( "keyword arg: %s: %s" % (key, kwargs[key]) )
foo_kwards(farg = 1, myarg2 = "two", myarg3 =3)
print(range(3,10)[1])
print(range(3,10,2))
print((lambda x: x*x)(3))
func = lambda x: x*x
print(func(7))
def make_adder(x):
def adder(n):
return x+n
return adder
adder = make_adder(10)
print(adder(5))
list = [1,5,2,5,2,8,9]
list2 = filter(lambda x: x < 5, list)
print(list2)
# list1 = [1,2,3,2,3]
# list2 = [4,5,6,7]
# map(lambda x,y: x*y, list1, list2)
# import functools
list = [2,3,4,5,6]
print(reduce(lambda res, x: res*x, list, 1))
a=4d
if a>=4:
print 4
elif a>3:
print 3
elif a>2:
print 2
else:
print 1
|
1c1a67e6a62237a7e4c2dd1f3b1868f57db74d4e | zevstravitz/Personal-projects-in-Python | /Computer Algebra and Calculus System/3Dgrapher.py | 2,575 | 3.65625 | 4 | #Zev Stravitz
#11/6/16
#3D grapher
import math
from Tkinter import *
print 'Welcome to the 3D point grapher'
x_comp = int(raw_input('X component: '))
y_comp = int(raw_input('Y component: '))
z_comp = int(raw_input('Z component: '))
def graphAxis():
canvas.create_line(250, 0, 250, 250, fill="red", width=5)
canvas.create_line(250, 250, 74, 426, fill="red", width=5)
canvas.create_line(250, 250, 500, 250, fill="red", width=5)
for i in range(1,10):
x = 25*i
canvas.create_line(250+x,245, 250+x,255, fill="blue", width=3)
for i in range(1,10):
y = 25*i
canvas.create_line(245, y, 255, y, fill="blue", width=3)
for i in range(1,10):
x = 25*i*.7
y = 25*i*.7
canvas.create_line(250-x-5, 250 + y, 250-x+5, 250 + y, fill="blue", width=3)
def graphCoor():
#Graph the y component
final_y = 250 + y_comp*25
canvas.create_line(250,250,final_y,250, fill="green", width=3)
#Graph the Z component
final_z = 250 - z_comp*25
canvas.create_line(final_y,250,final_y,final_z, fill="green", width=3)
#Finish rectangle
canvas.create_line(250,final_z,final_y,final_z, fill="green", width=3)
canvas.create_line(250,250,250,final_z, fill="green", width=3)
#Make the rectangle
canvas.create_line(final_y,final_z,(final_y+x_comp*25*.707),(final_z-x_comp*25*.707), fill="green", width=3) #important one
canvas.create_line(250,final_z,(250+x_comp*25*.707),(final_z-x_comp*25*.707), fill="green", width=3)
canvas.create_line(final_y,250,(final_y+x_comp*25*.707),(250-x_comp*25*.707), fill="green", width=3)
canvas.create_line(250,250,(250+x_comp*25*.707),(250-x_comp*25*.707), fill="green", width=3)
canvas.create_line((250+x_comp*25*.707),(250-x_comp*25*.707),(250+x_comp*25*.707),(final_z-x_comp*25*.707), fill="green", width=3)
canvas.create_line((final_y+x_comp*25*.707),(250-x_comp*25*.707),(final_y+x_comp*25*.707),(final_z-x_comp*25*.707), fill="green", width=3)
canvas.create_line((250+x_comp*25*.707),(250-x_comp*25*.707),(final_y+x_comp*25*.707),(250-x_comp*25*.707), fill="green", width=3)
canvas.create_line((250+x_comp*25*.707),(final_z-x_comp*25*.707),(final_y+x_comp*25*.707),(final_z-x_comp*25*.707), fill="green", width=3)
#Draw the vector
canvas.create_line(250,250,(final_y+x_comp*25*.707),(final_z-x_comp*25*.707), fill="black", width=4)
if __name__ == '__main__':
root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()
graphAxis()
graphCoor()
root.mainloop()
|
46a41a3a16a7603087674ea4e4c2c5faa51023c4 | jonasclaes/TM_Python_Sem_1 | /C2/EX1/triple_test.py | 158 | 4.3125 | 4 | number = int(input("Enter a number: "))
if (number % 3 > 0):
print(str(number) + " is not divisible by 3")
else:
print(str(number) + " is a triple")
|
f0a566d675c699cfa08d55fdfb4aabdfee7076d6 | kelseyMcCutcheon/OUR_Assessment | /TestAdaptationAlgorithm.py | 2,325 | 3.734375 | 4 | DIFFICULTY = 1
EASY_WRONG = 3
EASY_RIGHT = 2
MED_WRONG = 2
MED_RIGHT = 2
HARD_WRONG = 2
HARD_LIMIT = 3
class adaptAlgo:
section = 0
difficulty = DIFFICULTY
easyWrong = EASY_WRONG
easyRight = EASY_RIGHT
medWrong = MED_WRONG
medRight = MED_RIGHT
hardWrong = HARD_WRONG
hardLimit = HARD_LIMIT
nextQuestion = 0
def reset(self):
self.difficulty = DIFFICULTY
self.easyWrong = EASY_WRONG
self.easyRight = EASY_RIGHT
self.medWrong = MED_WRONG
self.medRight = MED_RIGHT
self.hardWrong = HARD_WRONG
self.hardLimit = HARD_LIMIT
def correctAnswer(self):
if self.difficulty == 0:
if self.easyRight <= 0:
self.difficulty = 1
self.easyRight = 2
else:
self.easyRight -= 1
elif self.difficulty == 1:
if self.medRight <= 0:
self.difficulty = 2
self.medRight = 3
else:
self.medRight -= 1
else:
if self.hardLimit <= 0:
print("Moving on to the next section!")
self.section += 1
self.reset()
else:
self.hardLimit -= 1
def incorrectAnswer(self):
if self.difficulty == 0:
if self.easyWrong <= 0:
print("Moving on to the next section!")
self.section += 1
self.reset()
else:
self.easyWrong -= 1
elif self.difficulty == 1:
if self.medWrong <= 0:
self.difficulty = 0
self.medWrong = 2
else:
self.medWrong -= 1
else:
if self.hardLimit <= 0:
print("Moving on to the next section!")
self.section += 1
self.reset()
elif self.hardWrong <= 0:
self.difficulty = 2
self.hardWrong = 3
else:
self.hardWrong -= 1
self.hardLimit -= 1
def getNextQuestion(self, correct: bool) -> int:
nextQuestion = 0
if correct:
self.correctAnswer()
else:
self.incorrectAnswer()
return (self.section * 3) + self.difficulty
|
4121a6247197fe56af9802ae3ade79b6a3cecff1 | ametthapa/python | /snakegame_next.py | 3,623 | 3.671875 | 4 | import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 255)
red = (255, 0, 0)
dis_width = 600
dis_height = 400
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption("snake game")
#name the screen
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 10
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 25)
def Your_score(score):
value= score_font.render("Your score : " + str(score),True, green)
dis.blit(value, [0,0])
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis,black,[int(x[0]), int(x[1]), snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [int(dis_width/6),int(dis_height/3)])
def gameloop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
foodx = int(random.randrange(0, dis_width - snake_block) / 10) * 10
foody = int(random.randrange(0, dis_width - snake_block) / 10) * 10
while not game_over:
while game_close:
dis.fill(blue)
message("You lost ! press Q-Quit or C-Play Again",red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
exit()
if event.key == pygame.K_c:
gameloop()
for event in pygame.event.get():
#event.get() returns all the action that takes place over it
if event.type == pygame.QUIT:
#exit screen when close button is clicked
game_over = True
#print(event)
#prints out all the action that takes place on the screen
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
x1_change = 0
y1_change = -snake_block
elif event.key == pygame.K_DOWN:
x1_change = 0
y1_change = snake_block
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_over = True
x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis , blue, [int(foodx),int(foody),snake_block,snake_block])
snake_head = [x1, y1]
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
our_snake(snake_block, snake_list)
Your_score(length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameloop() |
1ce39356f926f14e2e00e86b127ef1ad1a51a480 | gcdsss/Python_Script | /book_example/Section7.py | 775 | 4.25 | 4 | #! python3
# Section7.py practice on regex
import re
# Use regex to check whether input is strong string cmd
len_re = re.compile(r'.{8,}') # length at least 8
a_re = re.compile(r'[a-zA-Z]+') # must contain upper or lower chara
num_re = re.compile(r'[0-9]+') # must contain at least 1 number.
def StrongcmdCheck():
text = str(input('Input token string:'))
if num_re.search(text) and len_re.search(text) and a_re.search(text) is not None:
print('string is strong token.')
else:
print('string is not strong token.')
# Use regex to implement strip() method
def re_strip(s, t=r'\s'):
format = r'^%s*|%s*$' % (t,t)
reg = re.compile(format)
text = reg.sub('', s)
return text
StrongcmdCheck()
print(re_strip(' guichangdi ', 'g'))
|
5896d1e657a4da4da654957e1161032ec147ea68 | whiterg1/Python_Stack | /Fundamentals/oop/BankAccount/BankAccount.py | 1,087 | 3.8125 | 4 | class BankAccount:
bank_name = "The National Bank of Roy"
all_accounts = []
def __init__(self,int_rate,balance):
self.int_rate = int_rate
self.balance = balance
BankAccount.all_accounts.append(self)
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print(f' This account has a balance of: ${self.balance}')
return self
def yield_interest(self):
if self.balance > 0:
self.balance = self.balance + self.int_rate * self.balance
return self
else:
print("There are insufficient funds in the account.")
bubbas_bbq = BankAccount(0.03, 0)
ginos_barbershop = BankAccount(0.06, 0)
bubbas_bbq.deposit(30).deposit(50).deposit(10).withdraw(20).yield_interest().display_account_info()
ginos_barbershop.deposit(200).deposit(50).withdraw(100).withdraw(10).withdraw(10).withdraw(20).yield_interest().display_account_info() |
70f61132574e106c2c3953948f3c88acb8532849 | bopopescu/Daily | /calendar_test.py | 411 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import calendar
def increase_year(year, source=None):
'''
根据给定的source date, 获得增加一定天数的时间
'''
source = source if source else datetime.datetime.now()
_y = source.year + year
_m = source.month
_d = min(source.day, calendar.monthrange(_y, source.month)[1])
return type(source)(_y, _m, _d)
|
5c52a94ab7eb5074859079c53032aca1b2cd05e7 | Habibur-Rahman0927/1_months_Python_Crouse | /Python All Day Work/29-04-2021 Days Work/string.py | 1,407 | 4.40625 | 4 | # String in python are surround by ether single quotation marks or double quotation marks "Hello" is the same as 'Hello'
print("Hello python") #string
print('Hello python') #There are same
a= 'this line show string method'
print(len(a))
print(a.capitalize()) # this method uppercase first letter a sentance
print(a.casefold()) # this method make the string lowercase
print(a.index('method')) # same as find() method but index()method raise an exception if the value is not found
print(a.find('string')) # this method finds the first occurrence of the specified value
print(a.count('string')) # this method show the number of times a specified value appears in the string
print(a.center(200)) # this method wil center aling the string
myTuple = ('rock', 'joker', 'not found')
print('*#'.join(myTuple)) #join all items in a tuple into a string using a hash or star characters as separator
print(a.replace("this line show string method", 'I love myself')) # this method replace a specified phrase with another specified phrase
print(a.split()) # this method splits a string into a list
print(a.title()) # make first letter in each word uppercase
b = 'i practics python string method \n this is a new line \n show this line a list'
print(b.splitlines())
print(a.isidentifier()) # check if the string valid indentifier
print(a.translate(b)) # translate line and word 83(s) with 80(p) {83: 80}
|
61c1cb509a88a4014e8ca1da95404fbc93a7f7ac | malikyilmaz/Class4-PythonModule-Week3 | /3-alphabetical_order.py | 674 | 4.59375 | 5 | """
Write a function that takes an input of different words with hyphen (-) in between them and then:
sorts the words in alphabetical order,
adds hyphen icon (-) between them,
gives the output of the sorted words.
Example:
Input >>> green-red-yellow-black-white
Output >>> black-green-red-white-yellow
"""
def sort_alphabetical_order(text):
print('-'.join(sorted(text.split('-')))) # split ile kelimeler ayrılır. Ayrılan kelimeler sorted ile sıralanır
# join ile tekrar biraraya getirilir.
sort_alphabetical_order(input("Kelimeler arasında '-' bırakarak kelimelerinizi yazınız :"))
|
59a06d7389e876cf651c98b35a6e3649b94e54db | aganpython/laopo3.5 | /python/Error&Exception/Try_Except.py | 1,365 | 4.03125 | 4 | # -*- coding: UTF-8 -*-
#1 未加异常处理
# def loop(l):
#
# print(l[6])
#
# loop([1,2])
# print("结束了")
#2 加了异常处理
# def loop(l):
# try:
# print(l[6])
# except Exception as e:
# print("发生了错误")
#
# loop([1,2])
# print("结束了")
#3
# age = input("请输入年龄")
# int_age = int(age)
# print(int_age)
# print('其他程序执行')
#4
# age = input("请输入年龄:...")
# try:
# int_age = int(age)
# print(int_age)
# except ValueError as ve:
# print('输入类型出现错误')
# print(ve)
#
# print('其他程序执行')
#5
# l = [1,2,3]
# a, b = 0,1
#
# print(l[5])
# print(b/a)
# print(x)
# print('end.....')
#6
# l = [1,2,3]
# a, b = 0,1
#
# try:
# print(l[5])
# except IndexError as ie:
# print('索引越界')
# print(ie)
# try:
# print(b/a)
# except ZeroDivisionError as zde:
# print('除数不能为0')
# print(zde)
# try:
# print(x)
# except NameError as ne:
# print('变量没有定义')
# print(ne)
# print('end.....')
#7
l = [1,2,3]
a, b = 0,1
try:
print(l[5])
print(b / a)
print(x)
except IndexError as ie:
print('索引越界')
print(ie)
except ZeroDivisionError as zde:
print('除数不能为0')
print(zde)
except NameError as ne:
print('变量没有定义')
print(ne)
print('end.....')
|
3c30dc82bbc56080764e8feebf3315f73395d0dc | lynnpepin/socket-examples | /test_server.py | 1,585 | 3.578125 | 4 | """
test_server.py
Instantiates a SimplestServer, sends 100 pieces of data over it, and repeats the procedure 100 times.
The data is generated deterministically using random.seed, so the client can verify that the server sends the correct data.
"""
from simplest import SimplestServer
import random
if __name__ == "__main__":
random.seed(413)
for test_iter in range(100):
print(f"Server test iteration {test_iter}")
server = SimplestServer('test.sock', verbose=True)
#server = SimplestServer(('localhost', 4444), verbose=True)
for _ in range(100):
length = random.randint(1,2**18)
data = bytes([random.randint(0,255) for _ in range(length)])
server.send(data)
server.close()
# TODO: Server sometimes hangs, deletes existing socket, causing some kind of race condition...
# This is an error with the testing procedure. This is a bad way to use the socket!
# 1. One testing iteration finishes
# 2. New client loop starts
# 3. Client connects to existing socket, looks for data
# 4. New server loop starts
# 5. Server sees existing socket, deletes it, waits for connection
# (But client is still stuck on the old one...)
# Should probably test these over these variables:
# 1. Number of outer iterations
# 2. Number of inner iterations
# 3. Distributions of data length
# 4. Testing with AF_INET address too
# 5. Outer iterations for each (i.e. one big test to reduce the chance this is luck!
# Test runs in about under 30 minutes on my machine, but feel free to end it early!
|
3a238b7ed7c61a741c98283480109238d4b94969 | clivejan/python_fundamental | /data_types/alien_no_points.py | 226 | 3.5 | 4 | alien_0 = {'color': 'green', 'speend': 'slow'}
# access a key that does not exist in a dictionary
#print(alien_0['points'])
# usgin get() to set a defaut retuen value
print(alien_0.get('points', 'No point value assigned.'))
|
e3c20174ef965ece3cdbe5c2b441c875dd79dbf3 | simu217/AllCode | /EffectiveDateTypeTrial.py | 33,468 | 3.59375 | 4 | import sys
import csv
import re
import time
import datetime
def convert_month_to_num(mm):
if (mm == 'jan') or (mm == 'january'):
new_mm = '01'
elif (mm == 'feb') or (mm == 'february'):
new_mm = '02'
elif (mm == 'mar') or (mm == 'march'):
new_mm = '03'
elif (mm == 'apr') or (mm == 'april'):
new_mm = '04'
elif mm == 'may':
new_mm = '05'
elif (mm == 'jun') or (mm == 'june'):
new_mm = '06'
elif (mm == 'jul') or (mm == 'july'):
new_mm = '07'
elif (mm == 'aug') or (mm == 'august'):
new_mm = '08'
elif (mm == 'sep') or (mm == 'sept') or (mm == 'september'):
new_mm = '09'
elif (mm == 'oct') or (mm == 'october'):
new_mm = '10'
elif (mm == 'nov') or (mm == 'november'):
new_mm = '11'
elif (mm == 'dec') or (mm == 'december'):
new_mm = '12'
else:
new_mm = mm
return new_mm
def dateCleanUp(rawdate):
if ("month" or "year" or "days") in rawdate:
return rawdate
else:
for fmt in ["%m/%d/%Y", "%m /%d /%Y", "%d/%m/%Y", "%d /%m /%Y", "%Y/%m/%d",
"%m/%d/%y","%m /%d/ %y","%d/%m/%y","%d /%m /%y",
"%B %d, %Y", "%B %d,%Y", "%B%d, %Y", "%B%d,%Y", "%B %d %Y", "%B%d%Y",
"%b %d, %Y", "%b %d, %Y", "%b%d, %Y", "%b%d,%Y", "%b %d %Y", "%b%d%Y",
"%d %B, %Y", "%d %B %Y","%d %b, %Y", "%d %b %Y","%d-%m-%Y", "%d - %m - %Y", "%Y-%m-%d"]:
try:
formatdate=datetime.datetime.strptime(rawdate, fmt).date()
rawdate1=formatdate.strftime("%m-%d-%Y")
return rawdate1
except ValueError:
continue
# For extracting date only from the string
def cleanup_func(DateString):
list1 = []
if ('1201' in DateString):
new_DateString = DateString.replace('1201', '1 201')
elif '1200' in DateString:
new_DateString = DateString.replace('1200', '1 200')
elif '2201' in DateString:
new_DateString = DateString.replace('2201', '2 201')
elif '2200' in DateString:
new_DateString = DateString.replace('2200', '2 200')
else:
new_DateString = DateString
FindOption = re.findall(
'((\(([\d\d?)]+)\)|\d\d?|1st|first|third|fourth|second|2nd|3rd|4rth|5th|fifth|one|two|three|four|five|sixt?h?|sevent?h''?|eighth?|ninet?h?|tent?h?|elevent?h?|twelvet?h?|thirteent?h?|fourteent?h?|'
'fifteent?h?|sixteent?h?|seventeent?h?|eighteent?h?|nineteent?h?|twenty|twentieth'
'|twelfth)\s?(-?(calendar)?\s?months?(\s?anniversary)?|-?(calendar)?\s?years?(\s?anniversary)?|(calendar)?\s?weeks?|-?(calendar)?\s?months?|-?(calendar)?\s?days?|-?(calendar)?\s?anniversary)|'
'(\d\d?(?:(st|nd|rd|th))?\s?,?\s?-?(january|february|mar|march|april|apr|may|june|jun|jul|july|august|october|november|september|december|jan|feb|aug|sept|sep|oct|nov|dec)-?,?\s?\d{2}\d?\d?)|'
'(\d?\d?\d{2}\s?,?\s?-?(january|february|mar|march|jun|jul|sep|april|apr|may|june|july|august|october|november|september|december|jan|feb|aug|sept|oct|nov|dec)-?,?\s?\d\d?(?:(st|nd|rd|th))?)|'
'((january|february|mar|march|april|apr|may|june|jun|jul|sep|july|august|october|november|september|december|jan|feb|aug|sept|oct|nov|dec)\s?-?,?\s?\d\d?(?:(st|nd|rd|th))?\s?,?-?\s?,?\s?\d{2}\d?\d?)|'
'(\d\d?[.\/-]\d\d?[.\/-]\d{4})|(\d{4}[.\/-]\d\d?[.\/-]\d{2})|(\d{2}[.\/-]\d\d?[.\/-]\d\d?))',
new_DateString, re.I | re.M)
for i in range(0, len(FindOption)):
if (i < len(FindOption)):
rawdate = FindOption[i][0]
properDate = dateCleanUp(rawdate)
if properDate == None:
list1.append(rawdate)
else:
list1.append(properDate)
i = i + 1
return list1
# Function for getting signature block and also includes conditions for signature block
# noinspection PyUnboundLocalVariable
# For getting Date from the Signature.
def last_sign_date(content1):
text = content1.split()
str1 = ' '.join(str(e) for e in text)
content = str1.lower()
lis = ["title:",'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties", "agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below", "agreed by the parties on the dates stated below", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", "the parties hereto have caused this", "last party to subscribe below"]
contentLen = len(content)
for element in lis:
if element in content:
if element == "sincerely":
elementIndex = content.index(element)
String = content[(elementIndex):(elementIndex + 600)]
break
else:
elementIndex = content.index(element)
String = content[(elementIndex - 200):(elementIndex + 600)]
break
else:
String = content[(contentLen - 350):contentLen]
String1 = String.replace(' ','')
date = cleanup_func(String1)
return String, date
# A function for searching all the keywords in a document and checking if a date exists nearby or not
# noinspection PyUnboundLocalVariable
def keyword_process(key, content, length = 0):
result = [m.start() for m in re.finditer(key, content)]
key_len = len(key)
contentLen = len(content)
for ind in result:
if ind <= 100:
Index = 0
else:
Index = ind - 100
Index1 = ind + (key_len + 3)
Index2 = ind + 120 + length
String = content[Index:Index2] # used for checking if any date exists nearby 'effective' keyword.
String2 = content[ind:Index1] # Used for checking if tab exists after 'effective' or any other keyword.
if key == "effective":
if "\t" in String2:
CSV_Col = "No Match"
break
# elif "last sign" in String:
# Conlength = len(content)
# prevLen = content[(Conlength - 100):Conlength]
# dateObj = re.search(
# '(?:Jan(?:u)(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)',
# prevLen, re.M | re.I)
# dateObj2 = re.search(
# '[\d][\d][\s^./-]?[\d][\d]',
# prevLen,
# re.M | re.I)
#
# if dateObj:
# CSV_Col = prevLen
# break
#
# elif dateObj2:
# CSV_Col = prevLen
# break
#
# else:
# CSV_Col = "No Match"
else:
dateObj = re.search(
'(?:Jan(?:u)(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)',
String, re.M | re.I)
dateObj2 = re.search(
'([\d][\d][\s^./-]?[\d][\d])', String,
re.M | re.I)
if dateObj:
CSV_Col = String
CSV_Col1 = dateObj.group()
break
elif dateObj2:
CSV_Col = String
CSV_Col1 = dateObj2.group()
break
else:
CSV_Col = "No Match"
CSV_Col1 = "No Match"
# elif "last sign" in String:
# Conlength = len(content)
# prevLen = content[(Conlength-100):Conlength]
# dateObj = re.search(
# '(?:Jan(?:u)(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)',
# prevLen, re.M | re.I)
# dateObj2 = re.search(
# '([\d][\d][\s^./-]?[\d][\d])',
# prevLen,
# re.M | re.I)
#
# if dateObj:
# CSV_Col = prevLen
# break
#
# elif dateObj2:
# CSV_Col = prevLen
# break
#
# else:
# CSV_Col = "No Match"
else:
dateObj = re.search(
'(?:Jan(?:u)(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)',
String, re.M | re.I)
dateObj2 = re.search(
'([\d][\d][\s^./-]?[\d][\d])',
String,
re.M | re.I)
if dateObj:
CSV_Col = String
CSV_Col1 = dateObj.group()
break
elif dateObj2:
CSV_Col = String
CSV_Col1 = dateObj2.group()
break
else:
CSV_Col = "No Match"
CSV_Col1 = "No Match"
# returns date
return CSV_Col
def processing(lis, str1, content, lowredContent):
if "insertion order" in lowredContent[:100]:
total = last_sign_date(content)
dateString = total[0]
date = total[1]
edOption = "Later of the two signatures"
elif "order id#" in lowredContent[:200]:
dateString = lowredContent[:300]
date = cleanup_func(dateString)
edOption = "Specific Date"
else:
# For each keyword in list
for element in lis:
# Checking every keyword present in the list
if element in str1:
if (element == 'dear') or (element == ' re:'):
key = str1.index(element)
dateString = str1[:key]
# date = cleanup_func(dateString)
# break
elif element == 'this':
key = str1.index(element)
dateString = str1[:(key + 200)]
# date = cleanup_func(dateString)
# break
else:
key = str1.index(element)
if key < 100:
dateString = str1[:(key + 180)]
else:
dateString = str1[(key - 100): (key + 110)]
# Getting signature block to determine Effective Date
if ("first day of the month in which the last party signs" in dateString) \
or ("first day of the calendar month in which this agreement is fully executed" in dateString) \
or ("1st day of the calendar month in which this agreement is fully executed" in dateString) \
or ("1st day of the calendar month" in dateString):
edOption = "first day of the month in which the last party signs"
lastSign = last_sign_date(content)
dateString = lastSign[0]
date = lastSign[1]
break
elif ("first day of the immediately following calendar month" in dateString):
edOption = "first day of the immediately following calendar month"
lastSign = last_sign_date(content)
dateString = lastSign[0]
date = lastSign[1]
break
elif ("last signed" in dateString) \
or ("as of the date of the last party's signature" in dateString) \
or ("signature block" in dateString) \
or ("last signature" in dateString) \
or ("signed below" in dateString) \
or ("last party signs" in dateString) \
or ("final signature" in dateString) \
or ("party identified below" in dateString) \
or ("sincerely" in dateString) \
or ("kind regards" in dateString) \
or ("owner's signature below" in dateString) \
or ("executed by both partner and google" in dateString) \
or ("agreed by the parties using echosign on the dates stated below" in dateString) \
or ("date signed by the supplier" in dateString) \
or ("last date of execution" in dateString) \
or ("date that this order form is signed by" in dateString) \
or ("date that both parties have signed the contract" in dateString) \
or ("latest of the signature dates below" in dateString) \
or ("date signed by the last party below" in dateString) \
or ("association's signature below" in dateString) \
or ("the parties hereto have caused this" in dateString) \
or ("last party to subscribe below" in dateString):
edOption = "Later of the two signatures"
lastSign = last_sign_date(content)
dateString = lastSign[0]
date = lastSign[1]
break
# Getting signature block to determine Effective Date
elif ("signed by google" in dateString) \
or ("google sign" in dateString) \
or ("google signature" in dateString) \
or ("google's signature below" in dateString) \
or ("the date this agreement is signed by google" in dateString):
edOption = "Google Sign Date"
lastSign = last_sign_date(content)
dateString = lastSign[0]
date = lastSign[1]
break
else:
if (element == "effective date") \
or (element == "amendement effective date") \
or (element == "sow effective date") \
or (element == "order form effective date") \
or (element == "this") \
or (element == "entered into as of ") \
or (element == "entered into") \
or (element == "made as of") \
or (element == "made on") \
or (element == "made into") \
or (element == "effective as of")\
or (element == '(the "effective date")')\
or (element == '"effective date"')\
or (element == "effective")\
or (element == '(the "amendment date")')\
or (element == '(the "statement of work")')\
or (element == '"pilot effective date"')\
or (element == 'dear')\
or (element == 'date of work statement')\
or (element == 'date of request:')\
or (element == 'addendum effective date')\
or (element == 'this addendum')\
or (element == 'this statement of work')\
or (element == 'this amendment')\
or (element == 'this agreement')\
or (element == 'amendment three effective date')\
or (element == 'sow effective')\
or (element == '(the "addendum")')\
or (element == '"effective date" means')\
or (element == 'start date:')\
or (element == 'attn:')\
or (element == 'scheduled start date'):
result = keyword_process(element, str1)
else:
try:
result = keyword_process(element, dateString)
except Exception:
result = "skip"
if result == "No Match":
edOption = "Later of two"
date = result
elif result == "skip":
date = "skip"
else:
edOption = "Specific Date"
dateString = result
date = cleanup_func(result)
break
else:
dateString = 'No Match'
date = 'No Match'
edOption = "No Match"
return dateString, date, edOption
# noinspection PyUnboundLocalVariable
def strip_non_ascii(string):
stripped = (c for c in string if 0 < ord(c) < 127)
return ''.join(stripped)
def ORFile():
# Opening the csv file so that we can append the changes to it.
f = open('D:\MainData\csv files\Carndinal\Cardinal_EffectiveDate.csv', 'w+',
encoding="utf8",errors="ignore",
newline="")
w = csv.writer(f, quoting=csv.QUOTE_ALL, delimiter=',')
w.writerow(['Path& File Name', "filename without special char",'Date String', 'Date', 'ED Option', 'Signature Block String', 'Signature Block Date'])
# this is for writing tha names of those files which have ascii/special chars in their file names and cant be open from listing
f1 = open('D:\MainData\Brightstar_SpecialCharRemainingFileListing.csv', 'w+',
encoding="utf8", errors="ignore", newline="")
w1 = csv.writer(f1, quoting=csv.QUOTE_ALL, delimiter=',')
w1.writerow(['Path & File Name'])
# List which contains all the keywords for the desired field.
lis= ['"effective date"','made and entered', 'dear', 'date of work statement','p.o. no.', 'ref:', ' re:','date of request:', 'addendum effective date',
'this addendum','effective as of', '(the "amendment date")','amendment one effective date','amendment two effective date','amendment three effective date',
'amendment four effective date', 'amendment effective date', '(the "statement of work")', 'sow effective date', 'sow effective', '(the "addendum")', 'order form effective date',
"pilot effective date",'"effective date" means', '(the "effective date")', 'effective date', 'this statement of work', 'this amendment', 'this agreement'
'this', 'entered into as of ', 'entered into', 'made as of', 'made into', 'made on', 'commencement date', 'effective as of',
'effective', 'contract date:','start date:', 'attn:', 'scheduled start date', 'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties", "agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below", "agreed by the parties on the dates stated below", "title:", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", "the parties hereto have caused this", "last party to subscribe below"]
# Keywords for Amendment
amendment =['"effective date"','made and entered', 'effective as of','(the "amendment date")', "amendment effective date", 'amendment four effective date',
'amendment three effective date', 'amendment two effective date', 'amendment one effective date', 'is effective from', 'this amendment'
'this', 'entered into this','entered into as of ', 'entered into', 'made as of', 'made into', 'made on', '"effective date" means',
'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties",
"agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below",
"agreed by the parties on the dates stated below", "title:", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", 'commencement date', "the parties hereto have caused this",
"last party to subscribe below"
]
# Keywords for Addendum
addendum = ['"effective date"', 'made and entered','effective as of', '(the "effective date")', '(the "addendum")', 'entered into this', 'entered into as of ',
'entered into', 'made as of', 'made into', 'made on', 'is effective from', '"effective date" means', 'this addendum', 'dated',
'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties", "agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below", "agreed by the parties on the dates stated below", "title:", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", 'commencement date', "the parties hereto have caused this", "last party to subscribe below"]
# Keywords for SOW
sow = ['(the "statement of work")','made and entered', 'sow effective date', 'sow effective', '"effective date"', 'effective as of', '(the "effective date")',
'effective', 'is effective from', 'this', 'dated', 'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties",
"agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below",
"agreed by the parties on the dates stated below", "title:", "title", "last party to subscribe below",
"prepared by:", "on behalf of:", "signed on behalf of the:", 'commencement date', "the parties hereto have caused this"
]
# Keywords for Letter
letter = ['"effective date"', 'effective as of', '(the "effective date")', 'effective date', 'effective', 'dear', 'attn:',
'sent via', ' re:','for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties",
"agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below",
"agreed by the parties on the dates stated below", "title:", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", "customer signature",'commencement date',
"the parties hereto have caused this", "last party to subscribe below"
]
# Keywords for Order Form
orderForm = ["order form effective date", 'made and entered',"order effective date:", "effective date of order", "order effective", '"edo"',
'"effective date"', 'effective as of', '(the "effective date")', 'effective date', 'effective', 'this',
'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties",
"agreed and accepted",
'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below",
"agreed by the parties on the dates stated below", "title:", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", "customer signature",'commencement date', "customer signature", "last party to subscribe below"]
# Keywords for Agreement
agreement = ['"effective date"', 'made and entered','effective as of', '(the "effective date")', 'effective date', 'effective', '(hereinafter the "effective date")',
'entered into as of ', 'entered into', 'made as of', 'made into', 'made on', 'commencement date','(the "agreement")',
'this agreement','this', 'is effective from', 'agreement dated', 'dated', 'for acknowledgement and acceptance', "signed:", 'agreed and accepted by grantee:',
"provider and google hereby agree to this agreement", "in witness whereof", "signed by the parties",
"agreed and accepted", 'accepted and agreed', "supplier:", 'accepted on', 'sincerely', "kindly regards", "very truly yours",
"agreed by the parties using echosign on the dates stated below", "agreed by the parties on the dates stated below", "title:", "title",
"prepared by:", "on behalf of:", "signed on behalf of the:", "customer signature",'commencement date', "customer signature", "last party to subscribe below"]
# Keywords for Quotes
quotes = ['"effective date"','made and entered', 'effective as of', '(the "effective date")', 'effective date', 'effective', '(hereinafter the "effective date")',
'entered into as of ', 'entered into', 'made as of', 'made into', 'made on', 'commencement date', " ref:", "last party to subscribe below"]
# File which contains listing of files on which code has to run.
f = open("D:/remainingbatch1.csv","r+",errors="ignore")
reader = csv.DictReader(f)
count = 0
for row in reader:
try:
# Opening single file for editing and detecting language
file1 = open(row["File Name"], 'r+',errors="ignore")
type = str(row["Type"]).lower()
str2 = file1.read()
text=str2.split()
content = ' '.join(str(e) for e in text)
lowredContent = content.lower()
filename=strip_non_ascii(row["File Name"])
# print("THIS IS LOWERED CONTENT",lowredContent)
count = count + 1
if "this legal contract" in lowredContent:
ind = lowredContent.index("this legal contract")
newContent = content[ind+80:]
newLowredContent = newContent.lower()
if "this legal contract" in newLowredContent:
ind = newLowredContent.index("this legal contract")
newContent1 = newContent[ind + 80:]
newLowredContent1 = newContent1.lower()
if "if contract is already approved or signed" in newLowredContent1:
ind = newLowredContent1.index("if contract is already approved or signed")
newContent2 = newContent1[ind + 100:]
str1 = newContent2.lower()
else:
str1 = newContent1.lower()
elif "if contract is already approved or signed" in newLowredContent:
ind = newLowredContent.index("if contract is already approved or signed")
newContent1 = newContent[ind + 100:]
newLowredContent1 = newContent1.lower()
if "if contract is already approved or signed" in newLowredContent1:
ind = newLowredContent.index("if contract is already approved or signed")
newContent2 = newContent1[ind + 100:]
newLowredContent2 = newContent1.lower()
if "this legal contract" in newLowredContent2:
ind = newLowredContent2.index("this legal contract")
newContent3 = newContent2[ind + 100:]
str1 = newContent3.lower()
else:
str1 = newContent1.lower()
else:
str1 = newContent1.lower()
else:
str1 = newContent.lower()
elif "if contract is already approved or signed" in lowredContent:
ind = lowredContent.index("if contract is already approved or signed")
newContent = content[ind+80:]
newLowredContent = newContent.lower()
if "if contract is already approved or signed" in newLowredContent:
ind = newLowredContent.index("this legal contract")
newContent1 = newContent[ind + 80:]
newLowredContent1 = newContent1.lower()
if "this legal contract" in newLowredContent1:
ind = newLowredContent1.index("if contract is already approved or signed")
newContent2 = newContent1[ind + 100:]
str1 = newContent2.lower()
else:
str1 = newContent1.lower()
elif "this legal contract" in newLowredContent:
ind = newLowredContent.index("this legal contract")
newContent1 = newContent[ind + 100:]
newLowredContent1 = newContent1.lower()
if "this legal contract" in newLowredContent1:
ind = newLowredContent.index("this legal contract")
newContent2 = newContent1[ind + 100:]
newLowredContent2 = newContent1.lower()
if "if contract is already approved or signed" in newLowredContent2:
ind = newLowredContent2.index("this legal contract")
newContent3 = newContent2[ind + 100:]
str1 = newContent3.lower()
else:
str1 = newContent1.lower()
else:
str1 = newContent1.lower()
else:
str1 = newContent.lower()
else:
str1 = content.lower()
# For changing path
if type == "amendment":
result = processing(amendment, str1, content, lowredContent)
elif type == "addendum":
result = processing(addendum, str1, content, lowredContent)
elif type == "sow":
result = processing(sow, str1, content, lowredContent)
elif type == "order form":
result = processing(orderForm, str1, content, lowredContent)
elif type == "letter":
if "dear" in str1:
newString = str1[:2000]
result = processing(letter, newString, content, lowredContent)
elif " re:" in str1:
result = processing(letter, newString, content, lowredContent)
else:
result = processing(letter, str1, content, lowredContent)
elif (type == "agreement") or (type == "nda"):
result = processing(agreement, str1, content, lowredContent)
elif "quot" in type:
result = processing(quotes, str1, content, lowredContent)
else:
result = processing(lis, str1, content, lowredContent)
dateString = result[0]
date = result[1]
edOption = result[2]
lastDate = last_sign_date(lowredContent)
dateString1 = lastDate[0]
date1 = lastDate[1]
w.writerow([row["File Name"], filename,dateString, date, edOption, dateString1, date1])
file1.close()
print("Scanned :" + str(count) + "\tFile Name: " + row["File Name"])
except:
w1.writerow([row["File Name"]])
# ===========================================================================================#
def main():
ORFile()
if __name__ == '__main__':
main()
|
4108102b9f68e6a1e5411e6c79d26072a044820f | SeanMitchell1994/cryptography | /src/caesar/caesar_driver.py | 263 | 3.734375 | 4 | from caesar import *
word = "defend the east wall of the castle!./"
print("Original word: " + word)
encrpyted_word = Encrypt(word, 3)
print("Encrypted word: " + encrpyted_word)
decrpyted_word = Decrypt(encrpyted_word,3)
print("Decrypted word: " + decrpyted_word) |
a0312034db463adc7665f997b6f790195df2cf6d | okrek6/Smallest-Multiple | /Smallest-Multiple.py | 140 | 3.796875 | 4 | def gcd(x,y): return y and gcd(y, x % y) or x
def lcm(x,y): return x * y / gcd(x,y)
n = 1
for i in range(1,21):
n = lcm(n,i)
print(n)
|
3eba1e89c457a689f8bfe92936b662177ff74960 | abhisek08/python-lists | /list shuffle.py | 176 | 3.890625 | 4 | '''
Write a Python program to shuffle and print a specified list.
'''
import random
lst=[2,1,5,4,6,7,84,5,6,77,96,14,32,23,56,233,12,54,59,71,24]
random.shuffle(lst)
print(lst) |
ace070749d3e0550b30f032e474b1eec9c8897c3 | vasavi-test/python | /task1.py | 525 | 3.65625 | 4 | #age 18-60
entires=int(raw_input("number of entires:"))
file_out = open("details.csv","w")
header = "name,age,salary\n"
file_out.write(header)
for x in range(entires):
name=raw_input("enter name:")
age=int(raw_input("enter age:"))
if age>60 or age<18:
print "please enter valid age."
age = int(raw_input("enter age:"))
sal = float(raw_input("enter salary:"))
line = "%s,%s,%s\n"%(name,age,sal)
print line
file_out.write(line)
file_out.close()
|
fc1af0f41353976435e115c9627943eed1cf72b3 | dwaq/advent-of-code-solutions | /2016/05/2-md5.py | 1,067 | 3.5 | 4 | import hashlib
door_id = "ojvtpuvg"
m = hashlib.md5()
integer = 0
digits = 0
# 8 character password
password = [0, 1, 2, 3, 4, 5, 6, 7]
# digits we haven't found yet
available = [0, 1, 2, 3, 4, 5, 6, 7]
# find all digits
while (len(available) > 0):
# concatenate ID and integer
seed = door_id + str(integer)
# calculate MD5
h = hashlib.md5(seed).hexdigest()
# compare top 5 digits
if (h[0:5] == "00000"):
# found something that starts with 5 0's
print h[5]
# needs to fit in 8 character password length
if (h[5] < str(8)):
# h[5] is now the position in the password
# don't overwrite it, so check if available
if (int(h[5]) in available):
# replace next character into password
password[int(h[5])] = h[6]
# remove from available
available.remove(int(h[5]))
# found something good
print available
# count up
integer = integer + 1
# final password
print password |
47fba03517a23e9aebe24adfa2a3f875244dbe64 | yvettecook/TicTacToe | /tictactoe_tests.py | 2,249 | 3.890625 | 4 | import tictactoe
game = tictactoe.Tictactoe()
def test_game_has_board():
assert game.board != None
print "passed: game has a board"
def test_board_has_3_rows():
assert len(game.board) == 3
print "passed: board has 3 rows"
def test_row_has_3_squares():
assert len(game.board[0]) == 3
print "passed: board has 3 squares"
def test_board_can_place():
game.place(0, 0, 'X')
assert game.board[0][0] == "X"
print "passed: board can place a move"
def test_player_can_take_move():
game.player_move(0,0)
assert game.board[0][0] == "X"
print "passed: player can move"
def test_computer_can_take_move():
wipe_board(game)
game.computer_move()
print game.board
print "passed: computer can move"
def test_cannot_place_on_occupied_square():
game.place(0,1,'O')
game.player_move(0,1)
assert game.board[0][1] == "O"
print "passed: cannot place on occupied square"
def test_can_identify_horizontal_win():
wipe_board(game)
assert game.is_horizontal_win() == False
game.place(2,0,'X')
game.place(2,1,'X')
game.place(2,2,'X')
assert game.is_horizontal_win() == True
print "passed: horizontal win identified"
def test_can_identify_vertical_win():
wipe_board(game)
assert game.is_vertical_win() == False
game.place(0,0,'O')
game.place(1,0,'O')
game.place(2,0,'O')
assert game.is_vertical_win() == True
print "passed: vertical win identified"
def test_can_identify_diagonal_win():
wipe_board(game)
assert game.is_diagonal_win() == False
game.place(0,0,'X')
game.place(1,1,'X')
game.place(2,2,'X')
assert game.is_diagonal_win() == True
print "passed: diagonal win identified"
def test_can_identify_any_win():
assert game.is_win() == True
print "passed: one win command"
def wipe_board(game):
game.board = [[None, None, None],[None, None, None],[None, None, None]]
test_game_has_board()
test_board_has_3_rows()
test_row_has_3_squares()
test_board_can_place()
test_player_can_take_move()
test_computer_can_take_move()
test_cannot_place_on_occupied_square()
test_can_identify_horizontal_win()
test_can_identify_vertical_win()
test_can_identify_diagonal_win()
test_can_identify_any_win()
|
5933b4ff2c85a039fa6508e15315c3516afff285 | fgirardin/worldtour | /src/analyzer.py | 1,610 | 3.546875 | 4 | """Analyzer module: utilities to manipulate list of cities."""
import pandas as pd
def normalize(x):
"""Normalize longitude."""
if x < -0.2:
x += 360
return x
class Analyzer():
"""Class to analyze and manipulate list of cities."""
def __init__(self, file):
"""Init class."""
self.df = pd.read_csv(file)
self.normalize_lng("lng_srt")
def query(self, places):
"""Query a list or dataframe of places in the internal list."""
if (type(places)) is str:
places = [places]
if type(places) is list:
places = pd.DataFrame(pd.Series(places), columns=["place"])
merged = places.merge(
self.df,
how="left",
left_on="place",
right_on="city")
# Remove empty rows
indices = merged[merged.city.isnull()].index
ignored = merged.loc[indices, "place"]
return merged.drop(indices), ignored
def resolve(self, resolve_list):
"""Resolve duplicates entry based on given list."""
for r in resolve_list:
indices = self.df[
(self.df.city == r[0]) & (self.df[r[1]] != r[2])
].index
print("***", indices)
self.df.drop(indices, inplace=True)
def distill(self):
"""Remove rows with empty fields."""
indices = self.df[self.city == ""].index
self.df.drop(indices, inplace=True)
def normalize_lng(self, newcol):
"""Normalize longitude to range [0,360)."""
self.df[newcol] = self.df.lng.apply(normalize)
|
c955d0a944ce3240017d8e89d12c56c604a76a50 | madeibao/PythonAlgorithm | /PartC/Py移除重复的节点.py | 806 | 3.9375 | 4 |
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
if not head:
return head
set2 = set()
set2.add(head.val)
res= head
while res.next:
if res.next.val in set2:
res.next = res.next.next
else:
set2.add(res.next.val)
res = res.next
return head
if __name__ == "__main__":
s = Solution()
n2 = ListNode(1)
n3 = ListNode(2)
n4 = ListNode(3)
n5 = ListNode(3)
n6 = ListNode(2)
n7 = ListNode(1)
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
n7.next = None
res = s.removeDuplicateNodes(n2)
while res:
print(res.val,end=" ")
res = res.next
|
5ad73c07356baf4446dc5a8384e735e89d3ca858 | cuongnb14/python-design-pattern | /sourcecode/data_structure/linked_list.py | 1,091 | 4.09375 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return self.data
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def add_head(self, data):
node = Node(data)
node.next = self.head
self.head = node
self.length += 1
def print(self):
cursor = self.head
while cursor:
print(cursor.data, end=" ")
cursor = cursor.next
def _print_backward(self, head):
if not head:
return
else:
self._print_backward(head.next)
print(head.data, end=", ")
def print_backward(self):
self._print_backward(self.head)
def pretty_backward(self):
print("[", end="")
self._print_backward(self.head)
print("]", end="")
def __str__(self):
return "LinkedList: {} node".format(self.length)
ll = LinkedList()
ll.add_head(1)
ll.add_head(2)
ll.add_head(3)
ll.print_backward()
ll.pretty_backward()
|
59eddd29763b4ae13119b4f273c03d7155aad2c7 | iakonk/MyHomeRepos | /python/examples/leetcode/amazon/favorite-genres.py | 2,648 | 3.953125 | 4 | """
https://leetcode.com/discuss/interview-question/373006
Given a map Map<String, List<String>> userSongs with user names as keys and a list of all the songs that the user
has listened to as values.
Also given a map Map<String, List<String>> songGenres, with song genre as keys and a list of all the songs within
that genre as values. The song can only belong to only one genre.
The task is to return a map Map<String, List<String>>, where the key is a user name and the value is a list of the
user's favorite genre(s). Favorite genre is the most listened to genre. A user can have more than one favorite genre
if he/she has listened to the same number of songs per each of the genres.
Example 1:
Input:
userSongs = {
"David": ["song1", "song2", "song3", "song4", "song8"],
"Emma": ["song5", "song6", "song7"]
},
songGenres = {
"Rock": ["song1", "song3"],
"Dubstep": ["song7"],
"Techno": ["song2", "song4"],
"Pop": ["song5", "song6"],
"Jazz": ["song8", "song9"]
}
Output: {
"David": ["Rock", "Techno"],
"Emma": ["Pop"]
}
Explanation:
David has 2 Rock, 2 Techno and 1 Jazz song. So he has 2 favorite genres.
Emma has 2 Pop and 1 Dubstep song. Pop is Emma's favorite genre.
"""
import collections
class Solution1(object):
""" brute force"""
def favorite_genres(self, user_songs, song_genres):
result = {}
for user, us in user_songs.items():
for genre, gs in song_genres.items():
matches = set(us) & set(gs)
if len(matches) >= 2:
result.setdefault(user, [])
result[user].append(genre)
return result
class Solution2(object):
def favorite_genres(self, userSongs, genreSongs):
result = {}
genre_m = {s: g for g in genreSongs for s in genreSongs[g]}
for user, songs in userSongs.items():
aggr = collections.Counter(genre_m[s] for s in songs if s in genre_m) # {Rock: 1, Jazz: 2}
max_cnt = max(aggr.values())
result[user] = [s for s, cnt in aggr.items() if cnt == max_cnt]
return result
userSongs = {
"David": ["song1", "song2", "song3", "song4", "song8"],
"Emma": ["song5", "song6", "song7"]
}
songGenres = {
"Rock": ["song1", "song3"],
"Dubstep": ["song7"],
"Techno": ["song2", "song4"],
"Pop": ["song5", "song6"],
"Jazz": ["song8", "song9"]
}
assert Solution1().favorite_genres(userSongs, songGenres) == {
"David": ["Rock", "Techno"],
"Emma": ["Pop"]
}
assert Solution2().favorite_genres(userSongs, songGenres) == {
"David": ["Rock", "Techno"],
"Emma": ["Pop"]
}
|
32bc5f13c687c0b1dded2708ef26e3db5a60db36 | PhDpwnerer/Escape | /Maze.py | 4,850 | 3.796875 | 4 | import random
import copy
from Wall import *
from Floor import *
from Hatch import *
#the maze algorithm is Recursive Backtracking, which is inspired from http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking
class MazeRecursive(object):
def __init__(self, rows, cols):
#(south,east), 1 signifies there is a wall
self.board = [[(1,1)]*cols for i in range(rows)]
#self.walls = [[1]*33 for i in range(19)]
self.rows = rows
self.cols = cols
self.cellHeight = 720//rows
self.cellWidth = 1280//cols
self.cellSize = min(self.cellHeight, self.cellWidth) ### Let's figure this out later
self.startRow = random.randint(0,rows-1)
self.startCol = random.randint(0,cols-1)
#self.row = self.startRow
#self.col = self.startCol
self.directions = [(0,-1), (1,0), (0,1), (-1, 0)]
self.carvePassagesFrom(self.startRow, self.startCol)
self.wallGroup = pygame.sprite.Group()
self.wallSprites()
self.floorGroup = pygame.sprite.Group()
self.floorSprites()
self.hatchRow = random.randint(0,rows-1)
self.hatchCol = random.randint(0, cols-1)
self.hatch = Hatch(self.hatchRow, self.hatchCol, self.cellSize)
self.hatchGroup = pygame.sprite.Group(self.hatch)
self.hatchRow2 = random.randint(0,rows-1)
self.hatchCol2 = random.randint(0, cols-1)
self.hatch2 = Hatch(self.hatchRow2, self.hatchCol2, self.cellSize)
self.hatchGroup.add(self.hatch2)
def carvePassagesFrom(self, row, col, visited=None): #no need for board as parameter, because already have self
if visited == None:
visited = set()
#visited.add((row, col))
#base case
# if row == self.startRow and col == self.startCol and len(visited) != 0:
# print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
# print(visited)
# print(len(visited))
# return #to simply end the function
#else:
directions = copy.deepcopy(self.directions) #to avoid aliasing issues
random.shuffle(directions) #so that the "wall carving" is randomized
for direction in directions:
dRow, dCol = direction
newRow = row + dRow
newCol = col + dCol
if 0 <= newRow <= self.rows-1 and 0 <= newCol <= self.cols-1 and \
(newRow, newCol) not in visited:
visited.add((newRow, newCol))
if direction == (0,1): #if EAST
(south, east) = self.board[row][col]
east = 0
self.board[row][col] = (south, east)
elif direction == (1,0): #if goes SOUTH since y-axis is inverted
(south, east) = self.board[row][col]
south = 0
self.board[row][col] = (south, east)
elif direction == (0,-1): #if WEST
(south, east) = self.board[newRow][newCol]
east = 0
self.board[newRow][newCol] = (south, east)
elif direction == (-1,0): #if NORTH
(south, east) = self.board[newRow][newCol]
south = 0
self.board[newRow][newCol] = (south, east)
###???????????????????
self.carvePassagesFrom(newRow, newCol, visited)
#print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa")
#print(len(visited))
def wallSprites(self):
for row in range(len(self.board)):
for col in range(len(self.board[0])):
southWall, eastWall = self.board[row][col]
if southWall == 1:
self.wallGroup.add(Wall(row, col, self.cellSize, "south"))
if eastWall == 1:
self.wallGroup.add(Wall(row, col, self.cellSize, "east"))
for col in range(-1,len(self.board[0])):
row = -1
self.wallGroup.add(Wall(row, col, self.cellSize, "south"))
for row in range(-1,len(self.board)):
col = -1
self.wallGroup.add(Wall(row, col, self.cellSize, "east"))
def floorSprites(self):
for row in range(len(self.board)):
for col in range(len(self.board[0])):
self.floorGroup.add(Floor(row, col, self.cellSize))
# a = MazeNoLoop(18, 32)
# print(a.board) |
79e749b618ceb5fde3f82e241ca7e075fb374734 | hulaba/GeeksForGeeksPython | /Greedy/WWP.py | 564 | 3.625 | 4 | class WWP:
@staticmethod
def run_wwp(input_sequence, maximum=6):
line = ""
words = input_sequence.split(" ")
for word in words:
if len(line + word) < maximum:
line += "{0} ".format(word)
elif len(line + word) == maximum:
line += word
print(line)
line = ""
else:
print(line)
line = ""
line += "{0} ".format(word)
if len(line) > 0:
print(line)
line = ""
|
20540138558f6e01bdde498451d54750943586ba | miguel8998/pipeline | /app/src/weather/main.py | 3,365 | 3.703125 | 4 | #!/usr/bin/python
"""WeatherApp
Uses the weather openapi to display the weather in any location.
Underneath the hood this application uses an openapi library to connect and obtain
data.
The Flask framework is used to host a website that exposes the weather when a location is typed in.
"""
# flask framework imports
from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap
# configuration loader
from weather.loader import conf
# weather api wrapper
from weather.weather_api.api import WeatherApiWrapper
def create_app(config=None):
"""
Bootstraps Flask application and defines routes for web applications
"""
# create and configure the app
app = Flask(__name__)
# Basic bootstrap html / header stuffs
Bootstrap(app)
options = conf.read_yaml_file()
# define actions for a GET or POST using / uri
@app.route('/', methods=['GET', 'POST'])
def index():
# initialise variables
weather = {}
coord_weather = {}
location = ""
# extra code
longitude = ""
latitude = ""
if request.method == "POST":
# get location that the user has entered
try:
location = request.form['location']
except:
# in these cases we have no choice but to exit
print("Unable to get location in request, something has gone badly wrong!")
exit(1)
if location:
# for a api wrapper object
weather_api_wrapper = WeatherApiWrapper(options)
# return a map with weather at the desired location
weather = weather_api_wrapper.get_current_weather_at_location(location, options['temperature_unit'],
options['wind_unit'])
# if errors are found return a 500 page and carry on
if 'errors' in weather:
return render_template('500.html', errors=weather.get('errors'))
## new code block
# get the longitude and latitude
try:
latitude = int(request.form['latitude'])
longitude = int(request.form['longitude'])
except:
print("Unable to get longitude or latitude in request, something has gone badly wrong!")
exit(1)
if longitude and latitude:
coord_weather = weather_api_wrapper.get_current_weather_at_coordinates(longitude, latitude,
options['temperature_unit'])
if 'errors' in coord_weather:
return render_template('500.html', errors=coord_weather.get('errors'))
return render_template("index.html", weather=weather, coord_weather=coord_weather, location=location,
longitude=longitude, latitude=latitude)
# in cases of generic error return 500
@app.errorhandler(500)
def internal_error(error):
return render_template('500.html', errors=[error]), 500
return app
# if python runs this file directly load config, launch flask and run!
if __name__ == '__main__':
conf.read_yaml_file()
app = create_app(conf)
app.run()
|
86ab530aae5c21a6a0de602d8192a464f2b78479 | rafaelperazzo/programacao-web | /moodledata/vpl_data/88/usersdata/179/59422/submittedfiles/listas.py | 421 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def alturas(a):
diferença=0
for i in range(0,len(a),1):
diferença=diferença+((a[i])-(a[i+1]))
if diferença<0:
diferença=diferença*(-1)
else:
diferença=diferença
return (diferença)
b=[]
n=int(input('digite o valor de n :'))
for i in range(0,n,1):
valor=int(input('digite o valor :'))
b.append(valor)
c=alturas(b)
print(c)
|
1164a4aed9cb23f61f94d4088f702e595e779537 | kp1zzle/leetcode | /findDuplicateFileInSystem.py | 824 | 3.625 | 4 | import collections
from typing import List
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
map = collections.defaultdict(list)
for path in paths:
files = path.split(' ')
directory_path = files[0]
for file in files[1:]:
file_name, content = file.strip(')').split('(')
map[content].append(directory_path + '/' + file_name)
return [x for x in map.values() if len(x) > 1]
if __name__ == '__main__':
sol = Solution()
result = sol.findDuplicate(["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"])
print(result)
result2 = sol.findDuplicate(["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"])
print(result2) |
f922f93055b3bbcdfcec5e39e75a2aa1a83e52da | tianyuan23/Network-Security | /ecb.py | 2,443 | 3.609375 | 4 | # Import AES symmetric encryption cipher
from Crypto.Cipher import AES
# Immport class for hexadecimal string process
import binascii
# support command-line arguments
import sys
# define block size of AES encryption
BLOCK_SIZE = 16
# The 128-bit AES key
key = binascii.unhexlify('00112233445566778899aabbccddeeff')
#The function to apply PKCS #5 padding to a block
def pad(s):
pad_len = BLOCK_SIZE - len(s) % BLOCK_SIZE
if (pad_len == 0):
pad_len = BLOCK_SIZE
return (s + pad_len * chr(pad_len).encode('ascii')) # eg. chr(97) -> 'a'
# The function to remove padding
def unpad(s):
return s[:-ord(s[len(s) - 1:])]
# encrypt with AES ECB mode
def encrypt(key, raw):
raw = pad(raw)
cipher = AES.new(key, AES.MODE_ECB)
return cipher.encrypt(raw)
# decrypt with AES ECB mode
def decrypt(key, enc):
cipher = AES.new(key, AES.MODE_ECB)
dec = cipher.decrypt(enc)
return unpad(dec)
# a function to parse command-line arguments
def getopts(argv):
opts = {}
while argv:
if argv[0][0] == '-':
opts[argv[0]] = argv[1]
argv = argv[1:]
return opts
if __name__ == '__main__':
# parse command-line arguments
myargs = getopts(sys.argv)
#print(myargs)
if '-e' in myargs: # encrption with hexadecimal string as plaintext
plaintext = binascii.unhexlify(myargs['-e'])
ciphertext = encrypt(key, plaintext)
print('Ciphertext:' + binascii.hexlify(ciphertext))
elif '-d' in myargs: # decryption with hexadecimal string as ciphertext
ciphertext = binascii.unhexlify(myargs['-d'])
plaintext = decrypt(key, ciphertext)
print('Plaintext:' + binascii.hexlify(plaintext))
elif '-s' in myargs:
# encrption with ascii string as plaintext, output hexadecimal ciphertext
plaintext = binascii.a2b_qp(myargs['-s'])
ciphertext = encrypt(key, plaintext)
print('Ciphertext:' + binascii.hexlify(ciphertext))
elif '-u' in myargs:
# decryption with hexadecimal string as ciphertext, output ascii string
ciphertext = binascii.unhexlify(myargs['-u'])
plaintext = decrypt(key, ciphertext)
print('Plaintext:' + binascii.b2a_qp(plaintext))
else:
print("python ecb.py -e 010203040506")
print("python ecb.py -s 'this is cool'")
print("python ecb.py -d d25a16fe349cded7f6a2f2446f6da1c2")
print("python ecb.py -u 9b43953eeb6c3b7b7971a8bec1a90819")
|
fc62cc0aaee2d43fc5dee049b94213f652db370d | sishtiaq/aoc | /2020/12/12a.py | 1,469 | 3.65625 | 4 |
from input import t0, t1
# "R90 would cause the ship to turn right by 90 degrees"
# but in the test case, the ship E,R90 -> S ?!
def new_dir(cur_dir, direction, angle):
if direction == 'R':
new_dir = (cur_dir - angle) % 360
else:
new_dir = (cur_dir + angle) % 360
return new_dir
def fwd(cur_dir, x, y, v):
# cheating, knowing that cur_dir \in {(0),90,180,270)
if cur_dir == 0:
return x,y+v
if cur_dir == 90:
return x-v,y
if cur_dir == 180:
return x,y-v
if cur_dir == 270:
return x+v,y
raise ValueError('bad assumption about dir')
def final_msg(x, y, d):
l = 'east'
u = 'north'
if x < 0:
l = 'west'
if y < 0:
u = 'south'
print(f'final position: ({l} {abs(x)}, {u} {abs(y)}) facing {d}')
def run(instrs):
direction = 270
pos_x,pos_y = 0,0
for (a,v) in instrs:
if a == 'N':
pos_y += v
elif a == 'S':
pos_y -= v
elif a == 'E':
pos_x += v
elif a == 'W':
pos_x -= v
elif a == 'L' or a == 'R':
direction = new_dir(direction, a, v)
elif a == 'F':
pos_x, pos_y = fwd(direction, pos_x, pos_y, v)
else:
msg = 'bad action (' + a + ',' + string(v) + ')'
raise ValueError(msg)
print(f'{a}{v} --> east {pos_x}, north {pos_y}, dir={direction}')
final_msg(pos_x,pos_y,direction)
|
d1a51e4159137959b3427adbe1afecb60403ed4e | nogicoder/BasicFlow | /codeacademy/factorial.py | 178 | 3.984375 | 4 | def factorial(x):
result = 1
for i in range (1, x+1):
result *= i
return result
def factorial(x):
result = x
while x > 1:
result *= x-1
x -= 1
return result
|
d14cd7dc1d209c486bf4c4951cda066a87f27547 | jemg2030/Retos-Python-CheckIO | /INCINERATOR/OOP5ParentChild.py | 2,565 | 4.53125 | 5 | """
5.1. Create an ElectricCar class that inherits properties from the Car class.
5.2. Modify the __init__ method of the ElectricCar class so that it uses super() to call
the __init__ method of the Car class.
5.3. Add a new attribute battery_capacity of type int to the ElectricCar class __init__ method.
This attribute must be passing as argument. Put this argument before brand and model, because
arguments without default values must go before ones that have.
5.4. Create a my_electric_car instance of the ElectricCar class, passing battery_capacity, brand,
model with values 100, "Tesla", "Model 3" respectively
----------
----------
5.1. Crea una clase Cocheeléctrico que herede propiedades de la clase Coche.
5.2. Modifica el método __init__ de la clase ElectricCar para que utilice super() para
llamar al método __init__ de la clase Car.
5.3. Añade un nuevo atributo battery_capacity de tipo int al método __init__ de la clase ElectricCar.
Este atributo debe pasarse como argumento. Pon este argumento antes de marca y modelo, porque los
argumentos sin valores por defecto deben ir antes que los que sí los tienen.
5.4. Crea una instancia my_electric_car de la clase ElectricCar, pasando battery_capacity, brand,
model con los valores 100, "Tesla", "Model 3" respectivamente
"""
# Taken from mission OOP 4: Adding Methods
# Taken from mission OOP 3: Initializing
# Taken from mission OOP 2: Class Attributes
# Taken from mission OOP 1: First Look at Class and Object
# show me some OOP magic here
class Car:
wheels = "four"
doors = 4
working_engine = False
def __init__(self, brand="", model=""):
self.brand = brand
self.model = model
def start_engine(self):
print("Engine has started")
self.working_engine = True
def stop_engine(self):
print("Engine has stopped")
self.working_engine = False
# Creating a Car object without passing any additional arguments (using default values)
my_car = Car()
# Creating two new Car objects with specific arguments
some_car1 = Car(brand="Ford", model="Mustang")
some_car2 = Car(model="Camaro")
# Calling start_engine method for some_car1 and some_car2
some_car1.start_engine() # Output: "Engine has started"
some_car2.start_engine() # Output: "Engine has started"
class ElectricCar(Car):
def __init__(self, battery_capacity, brand="", model=""):
super().__init__(brand, model)
self.battery_capacity = battery_capacity
my_electric_car = ElectricCar(battery_capacity=100, brand="Tesla", model="Model 3")
|
de592dbfb86308ea0f08016701ce14baa31017f4 | DanieleMagalhaes/Exercicios-Python | /Mundo2/somaPAR.py | 281 | 3.703125 | 4 | print('-'*60)
soma = 0 #inicialize fora do FOR
cont = 0
for c in range(1,7):
valor = int(input('Digite um valor: '))
if (valor % 2 == 0):
soma += valor
cont +=1
print('\nVocê informou {} número(s) PARES e a soma é: {} '.format(cont, soma))
print('-'*60)
|
a81b4e692c20d7cbe9caf7f24fd1f778322ce9a4 | esinkarahan/python_projects | /tictactoe_ai/tictactoe_ai_functions.py | 4,970 | 3.875 | 4 | # useful auxiliary functions and 3 simple AIs
# for tictactoe game
# December. 2020
import random
width = 3
height = 3
def new_board():
# returns an empty w x h board
board = [[None for i in range(0, width)] for j in range(0, height)]
return board
def render(board):
# print board on screen with coordinates
print(' 0 ' + '1 ' + '2 ')
print(' ' + '-' * width * 2)
for i in range(height):
print(str(i) + '|', end='')
for j in range(width):
if board[i][j] is None:
print(' ', end=' ')
else:
print(board[i][j], end=' ')
print('|')
print(' ' + '-' * width * 2)
def make_move(old_board, move_coords, player):
# makes move and updates board by creating new variable
if not is_valid_move(old_board, move_coords):
raise Exception('Can\'t move to {}, it\'s already taken'.format(move_coords))
next_board = [i[:] for i in old_board]
if player == 'X':
next_board[move_coords[0]][move_coords[1]] = 'X'
else:
next_board[move_coords[0]][move_coords[1]] = 'O'
return next_board
def is_valid_move(board, move_coords):
# check whether move is valid
if board[move_coords[0]][move_coords[1]] is None:
return 1
else:
return 0
def _get_all_lines_value(board):
# rows
lines = board.copy()
# cols
[lines.append([board[i][j] for i in range(0, height)]) for j in range(0, width)]
# diags
lines.append([board[i][j] for i, j in zip([0, 1, 2], [0, 1, 2])])
lines.append([board[i][j] for i, j in zip([0, 1, 2], [2, 1, 0])])
return lines
def _get_all_lines_sub(board):
coords = []
# cols
[coords.append([(j, i) for i in range(0, width)]) for j in range(0, height)]
# rows
[coords.append([(i, j) for i in range(0, height)]) for j in range(0, width)]
# diags
coords.append([(i, j) for i, j in zip([0, 1, 2], [0, 1, 2])])
coords.append([(i, j) for i, j in zip([0, 1, 2], [2, 1, 0])])
return coords
def _get_all_possible_moves(board):
return [(i, j) for i in range(0, height) for j in range(0, width) if board[i][j] is None]
def get_winner(board):
# check whether any player has won and report the winner
# built a list of all lines
lines = _get_all_lines_value(board)
for line in lines:
if line == ['O', 'O', 'O']:
return 'O'
if line == ['X', 'X', 'X']:
return 'X'
return False
def check_for_draw(board):
# check for draw
k = 0
for i in range(width):
for j in range(height):
if board[i][j] is not None:
k = k + 1
if k == width * height:
return True
else:
return False
# AI
def random_ai(board, player):
# plays randomly on available positions
avail = _get_all_possible_moves(board)
r = random.randint(0, len(avail) - 1)
return avail[r]
def find_winning_moves_ai(board, player):
# finds winning moves if exists, returns random if not
if _find_winning_moves(board, player):
return _find_winning_moves(board, player)
else: # no available moves, return random
return random_ai(board, player)
def _find_winning_moves(board, player):
# winning move is the ones with perm(X,X,None) or perm(O,O,None)
# get all coordinates of the board
coords = _get_all_lines_sub(board)
for row in coords:
n_p = 0
n_none = 0
for r in row:
if board[r[0]][r[1]] == player:
n_p += 1
elif board[r[0]][r[1]] is None:
n_none += 1
coord_move = r
if n_p == 2 and n_none > 0:
return coord_move
return None
def _find_blocking_moves(board, player):
# blocking move is the opponent's winning move!
if player == 'X':
opponent = 'O'
else:
opponent = 'X'
coord_block = _find_winning_moves(board, opponent)
return coord_block
def find_winning_and_losing_moves_ai(board, player):
# a move that wins, a move that block a loss, and a random move
# first check for win
if _find_winning_moves(board, player):
return _find_winning_moves(board, player)
# then check for loss and block
if _find_blocking_moves(board, player):
return _find_blocking_moves(board, player)
# if none of them work, return a random move
return random_ai(board, player)
def human_player(board, player):
# gets input from human player
# asks user coordinates of their next move
while True:
x = int(input('Enter your next move\'s row number? '))
if x >= height:
print('You entered invalid coordinate')
else:
break
while True:
y = int(input('Enter your next move\'s column number? '))
if y >= width:
print('You entered invalid coordinate')
else:
break
return int(x), int(y)
|
bc63da75094b1b05d4578362562dfb0785b368c0 | Annamalai1995/websitecreated | /Accessset.py | 148 | 4.09375 | 4 | a={"sam","pk","anu","sathish"}
for i in a:
print(i)
#check the set is present or not
a={"sam","pk","anu","sathish"}
print("sam" in a)
|
f09534568ea2172bc506971f0c04afb2ea6b2ef0 | Anupalsi/guvi | /upper_to_lower_to_upper.py | 150 | 3.796875 | 4 | n=input()
for i in range(len(n)):
if n[i]>='a' and n[i]<='z':
print(n[i].upper(),end='')
if n[i]>='A' and n[i]<='Z':
print(n[i].lower(),end='')
|
01a47308e05fe648ab65668e8cd50ac8661414b3 | alexanderdavide/advent-of-code-2020 | /day9/9a.py | 752 | 3.515625 | 4 | from functools import reduce
PREAMBEL = 25
def get_possible_sums(numbers):
sums = []
for idx, numb in enumerate(numbers[:-1]):
for addend in numbers[idx + 1 :]:
if numb != addend:
sums.append(numb + addend)
return sums
def find_invalid_number(numbers):
for idx, numb in enumerate(numbers[PREAMBEL:]):
if numb in get_possible_sums(numbers[idx : PREAMBEL + idx]):
continue
else:
return numb
def main():
with open("9.txt") as input:
lines = input.readlines()
numbers = reduce(lambda acc, el: [*acc, int(el.rstrip("\n"))], lines, [])
print(find_invalid_number(numbers))
return 0
if __name__ == "__main__":
exit(main()) |
0989662fcba1b2f0290b50f71981cdf5cde5e4ae | iagsav/AS | /T2/SemenovaDS/2.1.py | 248 | 3.671875 | 4 | def is_prime(var):
for i in range(2,var+1):
a=0
for j in range(2,i):
if i%j==0:
a=1
break
if a==0:
print(i);
b=int(input("Введите число:"))
is_prime(b)
|
12f8dc64d4e7742264fa79654a0962a215132fdb | georgetao/comp-programming | /dualpal.py | 791 | 3.796875 | 4 | """
ID: georget2
LANG: PYTHON3
TASK: dualpal
"""
def isPalindrome(s):
if len(s) < 2:
return True
if s[0] != s[-1]:
return False
return isPalindrome(s[1:-1])
def num_in_base(num, base):
if num < base:
return str(num)
prefix = num_in_base(int(num / base), base)
if prefix[0] == "0":
prefix = prefix[1:]
return prefix + str(num - (int(num / base) * base))
def palindrome_in_2_bases(num):
count = 0
for b in range(2, 11):
s = num_in_base(num, b)
if isPalindrome(s):
count += 1
if count == 2:
return True
return False
with open("dualpal.in", "r") as fin:
n, s = map(int, fin.readline().split())
i = 1
with open("dualpal.out", "w") as fout:
while n > 0:
while not palindrome_in_2_bases(s+i):
i += 1
fout.write(str(s+i) + "\n")
n -= 1
i += 1 |
75b9091f34c258c64cd1c2da5d95768d4a5525a9 | Icetalon21/Data-Science | /scikitlearn/std.py | 1,523 | 3.5625 | 4 | import sklearn
import numpy as np
import sklearn.datasets as skdata
from matplotlib import pyplot as plt
boston_housing_data = skdata.load_boston()
print(boston_housing_data)
x = boston_housing_data.data
feat_names = boston_housing_data.feature_names
print(feat_names)
#print(boston_housing_data.DESCR)
y = boston_housing_data.target
#print(y[0],y[0, :])
crime_rate = x[:, 0]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(crime_rate, y)
nitric_oxide = x[:, 4]
ax2 = fig.add_subplot(2, 1, 2)
ax2.set_title("Nitric Oxide Concentration (PP 10M")
ax2.set_ylabel('Housing Price')
ax2.set_xlabel('Nitric Oxide ({})'.format(feat_names[4]))
ax2.scatter(nitric_oxide, y)
def standard_norm(x):
return(x-np.mean(x))/np.std(x)
crime_rate_std = standard_norm(crime_rate)
nitric_oxide_std = standard_norm(nitric_oxide)
print(np.min(crime_rate_std), np.max(crime_rate_std))
print(np.min(nitric_oxide_std), np.max(nitric_oxide_std))
#STANDARD NORMALIZATION
fig = plt.figure()
fig.suptitle('Boston Housing Data')
ax = fig.add_subplot(1, 1, 1)
ax.set_ylabel('Housing Price')
ax.set_xlabel('Standard Norm Features')
observations_std = (crime_rate_std, nitric_oxide_std)
targets = (y, y)
colors = ("blue", "red") # Crime rate will be blue and nitric oxide will be red
labels = (feat_names[0], feat_names[4])
markers =('o', '^')
for obs, tgt, col, lab, m in zip(observations_std, targets, colors, labels, markers):
ax.scatter(obs, tgt, c=col, label=lab, marker=m)
ax.legend(loc='upper right')
plt.show()
|
f72a269aba401f9db56226320b3744115f233101 | csuzll/python_DS_Algorithm | /3、基本数据结构/reverstr.py | 433 | 3.828125 | 4 | # 使用stack实现字符串反转
from stack import Stack
def revstring(mystr):
s = Stack()
revstr = ""
for c in mystr:
s.push(c)
while not s.isEmpty():
revstr = revstr + s.pop()
return revstr
if __name__ == '__main__':
# 测试
assert revstring("apple") == "elppa", "apple Error"
assert revstring("x") == "x", "x Error"
assert revstring("1234567890") == "0987654321", "error" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.