blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
efcb7e7ad8bdadbbe60e67a1d675b57341ab4131 | saequus/learn-python-favorites | /Patterns/StrategyPattern.py | 1,290 | 3.6875 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Context:
def __init__(self, strategy: Strategy) -> None:
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy... |
5610a99d5ef0fc6c26b5dcf6cdeab13dd262d357 | saequus/learn-python-favorites | /Tasks/AdjacencyListGraph.py | 868 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.vertex = data
self.next = None
class Graph:
def __init__(self, verteces):
self.V = verteces
self.graph = self.V * [None]
def add_edge(self, src, dst):
node = Node(dst)
node.next = self.graph[src]
self.graph... |
f2817ece55a255b4fcba92a35384f296f8954ad9 | saequus/learn-python-favorites | /Tasks/241_DIfferentWaysToAddParentheses.py | 996 | 3.6875 | 4 | class Solution(object):
def comp(self, exp):
if len(exp) == 1:
return [int(exp[0])]
res_list = []
# [left] [i] [right]
for i in range(1, len(exp), 2):
left_list = self.comp(exp[:i])
right_list = self.comp(exp[i + 1:])
for l in left_l... |
82a2b51be110ac173653dabca2d3e17236a0d985 | saequus/learn-python-favorites | /Tasks/ReverseNumber.py | 837 | 3.9375 | 4 | # Reverse Number (Print Number Backwards)
# Given integers 1204900, 431, -453. The func must return 94021, 134, -354
def reverse_number(num) -> str: # not the fastest, optimise
""" Reverse number.
Keep negative if needed. Remove zeros if ended with 0.
:param: num
:return: str
"""
res = list()... |
d630f1c990fecd8c466c3876f0f6a34a9084c262 | saequus/learn-python-favorites | /SortTypes/CountingSort.py | 1,151 | 3.609375 | 4 | # ============================================================================
# ========================== CountSort Algorithm =============================
# ============================================================================
def count_sort(arr):
output = [0 for _ in range(256)]
# Create a count a... |
1f95015507e7f2a6137f3a4e172c384676b236e9 | saequus/learn-python-favorites | /Tasks/IsIntercalaryYear.py | 229 | 3.84375 | 4 | def isIntercalaryYear(n):
if n % 4 != 0 or (n % 100 == 0 and n % 400 != 0):
return '{} '.format(n) + 'year is usual.'
else:
return '{} '.format(n) + 'year is intercalary.'
print(isIntercalaryYear(1900))
|
96c1bae43ccfda525a075cdbccbb7751270fa77f | Bonaparto/Programming-Principles-II | /stepik/lilprojects/passwordgen.py | 1,078 | 3.90625 | 4 | import random
def generate_password(c, l):
print(*random.sample(c, l), sep='')
digits = '23456789'
lowercase_letters = 'abcdefghjkmnpqrstuvwxyz'
uppercase_letters = 'ABCDEFGHIJKMNPQRSTUVWXYZ'
punctuation = '!#$%&*+-=?@^_'
chars = ''
print('How many passwords do you need?')
amount = int(input())
print('Enter the... |
433fccd7627612b9feed8105f9860f9fa323d640 | Bonaparto/Programming-Principles-II | /weeks/week11/2.py | 2,040 | 3.609375 | 4 | import pygame
pygame.init()
White = (255, 255, 255)
Red = (255, 0, 0)
Green = (0, 255, 0)
Blue = (0, 0, 255)
Black = (0, 0, 0)
Win_Height = 600
Win_Width = 600
screen = pygame.display.set_mode((Win_Width, Win_Height))
screen.
clock = pygame.time.Clock()
block = 10
body = [[150, 150]]
def level_choose():
pass
... |
54f54e98b511674581c7f8a66443a2ef7d6e94a7 | Bonaparto/Programming-Principles-II | /practice/1.py | 336 | 3.734375 | 4 | import turtle
wn = turtle.Screen()
wn.bgcolor('lightgreen')
cherepaha = turtle.Turtle()
cherepaha.color('purple')
cherepaha.shape('turtle')
cherepaha.speed(10)
cherepaha.pensize(6)
cherepaha.down()
move = 90
angle = 72
for i in range(5):
cherepaha.forward(move)
cherepaha.stamp()
cherepaha.right(angle)
... |
26610b9a962da30ef8dbe732e2a4c4fc4034a1d2 | Bonaparto/Programming-Principles-II | /ejudge/midtermg2/h.py | 307 | 3.84375 | 4 | n = input()
l = input().split()
n = list(input())
n.clear()
l1 = input().split()
for i in l:
if i not in l1:
n.append(i)
n1 = []
for i in l1:
if i not in l:
n1.append(i)
print('Missed students:')
for i in n:
print('-', i)
print('Not in the group:')
for i in n1:
print('-', i) |
1d5f61971e8c0fd10fcbe629415ea789410a148e | Bonaparto/Programming-Principles-II | /weeks/week6/1.py | 646 | 3.671875 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def printer(self):
print(f'Name is: {self.name}', f'Age: {self.age}', sep='\n')
def summation(self, age2):
print(self.age + age2)
class Student(Person):
def __init__(self, name, age, school, g... |
69b96c77d2172ec2531e5868743ea8835483e6f5 | Bonaparto/Programming-Principles-II | /weeks/week1/informatics/types/d.py | 132 | 3.640625 | 4 | pi = 0
for i in range(0, 10):
if i % 2 == 0:
pi += (4 / (1 + i * 2))
else:
pi -= (4 / (1 + i * 2))
print(pi) |
6932fafa7b24d2bd97ed6f21dc99050fd4f85228 | Bonaparto/Programming-Principles-II | /weeks/week1/informatics/while/s.py | 165 | 3.59375 | 4 | b, a = int(input()), int(input())
while(a != b):
if(b // 2 >= a and b % 2 == 0):
b //= 2
print(':2')
else:
b -= 1
print('-1') |
8c9ae30706e1e811b6473b53120b8ca823b91410 | Bonaparto/Programming-Principles-II | /weeks/week1/informatics/funcs/n.py | 182 | 3.71875 | 4 | def sol(a, b):
if(b == 1):
return a
if(a == b or b == 0):
return 1
return (sol(a - 1, b - 1) + sol(a - 1, b))
print(int(sol(int(input()), int(input())))) |
11b9eeb47410574de7b944a6e55e61f5a5d31e88 | nmanzini/MPCSPE | /2012/raindrops/main.py | 221 | 3.78125 | 4 | from math import floor
input()
array = [int(x) for x in input().split(" ")]
validarray = [x for x in array if x >= 0]
if validarray == []:
print ("INSUFFICIENT DATA")
else:
print(floor(sum(validarray)/len(validarray))) |
713b343a06e3f6ea37971c487ee6a8c6c2eb30d0 | nmanzini/MPCSPE | /calendar/calendar_conondrum.py | 283 | 3.5625 | 4 |
import sys
line = sys.stdin.readline()
a,b,c = line.split(" ")
a = int(a)
b = int(b)
c = int(c)
if a > 31:
print ("Format #3")
elif a > 12 and a <=31:
if c > 31:
print("Format #2")
else:
print("ambiguous")
else:
if b >12:
print("Format #1")
else:
print("ambiguous") |
28b78648f715ffd78e51b9a5c234477dea70da0b | battistowx/cis1400 | /AverageGrade.py | 2,184 | 3.859375 | 4 | # Author: Chris Battisto
# Date: 10/15/2014
# Program: AverageGrade.py
# Descr:
# Program that takes an input of five percentage grades, calculates
# the average grade, and displays a letter grade for that average.
def main():
counter=4
listScores=[]
listGrades=[]
for counter in range(0,5):
... |
dd9f3e8b4ff34e53b63af387666b3b4252dfbf41 | battistowx/cis1400 | /MarsMemoryGame/Mars_Memory_Class.py | 472 | 3.65625 | 4 | # MARSMemory.py Class
# This class generates a random numbered list
from random import random
class Mars_Memory:
def setGenerateList(self, generateList):
#generate a 10-item list of random numbers between 0 and 9
generateList=[]
for i in range (10):
generateList.appen... |
8e9893c1df93bcf48ec9fec7b716b0d61c926809 | NWabuokei-Tega1/Early-days | /wordplay.py | 325 | 3.53125 | 4 | fin = open('/storage/sdcard0/crossword.txt')
for i in fin:
word = i.strip()
if len(i) == 20:
print(word)
print('-------------------------------')
#if a word has 'e', print False, else print True
text = open('/storage/sdcard0/crossword.txt')
#word = input('enter a word: ')
if 'e' not in text:
a = i
a = len(a)
prin... |
2bae5c52909db58b3f00e877dcae4934b0afe892 | rumdrums/ml | /cost_function.py | 261 | 3.734375 | 4 | import numpy as np
def cost(X, y, theta):
""" return cost, given matrices for X, y, theta """
m = y.shape[0]
predictions = X * theta
squared_errors = np.square((predictions-y))
numerator = 1.0/(2*m)
cost = numerator * squared_errors.sum()
return cost
|
fbbc647c801512f2e08097f0110f548088fdecf9 | petitlapin86/firstpython | /inputandoutput.py | 484 | 4 | 4 | #input and output
#ask for users name
name = input("what is your name? ")
#welcome user with name
print("Hi {}, get ready to play madlibs!".format(name))
verb = input("Please enter a verb: ")
noun = input("Please enter a noun: ")
adjective = input("Please enter a adjective: ")
print("I enjoy running. I find it h... |
cc943205395b920a32f5eaf3167dd1ce4338324e | blackwings001/algorithm | /leetcode/51-100/_73_setZeros.py | 821 | 3.59375 | 4 | class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
row = len(matrix)
col = len(matrix[0])
for i in range(row):
for j in range(col):
... |
468a2362832863ac15f3ee5a529e47521dcb559b | blackwings001/algorithm | /leetcode/101-150/_148_sortList.py | 1,601 | 3.953125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
re... |
2178e78961ef078f714489330030c4d623c72043 | blackwings001/algorithm | /leetcode/51-100/_86_partition.py | 1,344 | 3.984375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head == None:
... |
dbaae72f54e8385e98da8ed826394323346f7bbd | blackwings001/algorithm | /leetcode/51-100/_97_isInterleave.py | 949 | 3.84375 | 4 | class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
n = len(s1)
m = len(s2)
if n + m != len(s3):
return False
# 进行动态规划
matrix = [[False for _ in... |
9ed01210152201461b2986c96ce71a4ab126db68 | blackwings001/algorithm | /leetcode/1-50/_9_isPalindrome.py | 441 | 3.78125 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
reverse_x = 0
tmp = x
while tmp != 0:
reverse_x = reverse_x * 10 + tmp % 10
tmp = tmp // 10
retur... |
f1faf4010a554b17696fe9aaa28c217c5fe3847a | blackwings001/algorithm | /leetcode/51-100/_54_spiralOrder.py | 1,681 | 3.65625 | 4 | class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
if matrix == []:
return result
i = 0 # 第几圈,每圈的起点是matrix[i][i]
cur_row = len(matrix) # 第i圈的行数
cur_col = len(... |
4831797afb0eab49191a996103e686620e6d7dbf | blackwings001/algorithm | /leetcode/1-50/_7_reverse.py | 753 | 3.890625 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
reverse_x = self.reverse_positive(x) if x >= 0 else - self.reverse_positive(x)
return reverse_x
def reverse_positive(self, x):
positive = 1 if x >= 0 else 0
x = x if x... |
7a537e10a6c7edfe749f91ae7e6e36535f2e6c28 | blackwings001/algorithm | /leetcode/1-50/_22_generate_parenthesis.py | 987 | 3.71875 | 4 | class Solution:
def generateParenthesis(self, n):
result = []
ans = ""
l = 0
r = 0
self.parenthesis(n, l, r, ans, result)
return result
def parenthesis(self, n, l, r, ans, result):
"""
:param n: 一共几对括号
:param l: ans中左括号的数量
:param r... |
7e0233df3a54efebde03d370dd0abec31a01afbe | blackwings001/algorithm | /leetcode/151-200/_167_twoSum.py | 673 | 3.640625 | 4 | class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if not numbers:
return []
start = 0
end = len(numbers) - 1
while end > start:
if numbers[s... |
d9efa33507a47f17a078d0e26b82d7c34f9a56b1 | blackwings001/algorithm | /leetcode/101-150/_147_insertionSortList.py | 1,244 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return hea... |
4b3ec9c71382f0a099910e075a4c806825bb32b1 | blackwings001/algorithm | /leetcode/101-150/_128_longestConsecutive.py | 927 | 3.53125 | 4 | class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
# 使用哈希表让查找的速度缩短为O(1)
nums = set(nums)
longest_len = 0
# 遍历哈希表中的每一个元素,注意只有连续序列的首元素才会进行第二轮遍历
# 也就是说貌... |
32ec08abb779f7fcad9c231c179f16cbb8d593c2 | blackwings001/algorithm | /leetcode/51-100/_85_maximalRectangle.py | 1,412 | 3.515625 | 4 | class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
row = len(matrix)
col = len(matrix[0])
max_area = 0
heights = [0 fo... |
619489ae150b0edd3b2a0ca7da3f31d5b5be5bcf | blackwings001/algorithm | /sort_algorithm/binary_search.py | 684 | 3.703125 | 4 | class Solution:
def binary_search(self, nums, target):
"""
返回nums中值为target的最左元素的索引
:param nums:
:param target:
:return:
"""
if nums == []:
return -1
l = 0
r = len(nums) - 1
while l < r:
mid = (l + r) // 2
... |
d2befa34c8897f0e19a6ecf076ba08aa9d9b8e78 | blackwings001/algorithm | /leetcode/51-100/_89_grayCode.py | 518 | 3.609375 | 4 | class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n == 0:
return [0]
if n == 1:
return [0, 1]
res = [0, 1]
for i in range(1, n):
length = len(res) # 当前列表的长度
for j... |
4983ce5f51d32706025dead611acdbfdea92594c | Ramtrap/lpthw | /ex16.py | 1,284 | 4.125 | 4 | from sys import argv
print "ex16.py\n"
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. G... |
040472f6d0676e03ab3361c79003f267b46cfb06 | etiennenoel/ctf | /goals/Goal.py | 664 | 3.53125 | 4 | class Goal:
"""Classe abstraite représentant un but"""
def __init__(self, gameInfo):
"""Methode pour initialiser le but"""
self.gameInfo = gameInfo
self.goalString = ""
self.defaultValue = 0
def calculateUtility(self, bot, blackboard):
"""Methode abstraite permetta... |
1da3c1521a8a1ba2943d3268762bb8f98f9801fc | jocelynr24/PythonExamples | /Classe/voiture/voiture.py | 657 | 3.578125 | 4 | # Ma classe Voiture
class Voiture:
# Constucteur de la classe voiture
def __init__(self, marque, roues, couleur, vole):
self.marque = marque
self.roues = roues
self.couleur = couleur
self.vole = vole
# Méthode afficherVoiture() pour afficher une description de la voiture
... |
2700e8c285d5da8be1789928bc8fc91b60e24842 | aditya18/movie_trailer | /inheritance.py | 829 | 3.9375 | 4 | class Parent():
def __init__(self, last_name, eye_color):
print("Parent called")
self.lastname = last_name
self.eyecolor = eye_color
def show_info(self):
print("Last Name = "+self.lastname)
print("Eye Color ="+self.eyecolor)
class Child(Parent):
def __init_... |
8f6af55a263b766ae2f521702dbc0304f1653336 | christinajoice/begin-set11 | /uppercase.py | 85 | 3.984375 | 4 | str1=input()
str1[1].upper()
for i in str1:
if i==' ':
i+1.upper()
print(str1)
|
ea8daa797fc7f221b09b4580852a67a45e79b8d0 | brunolomba/exercicios_logica | /banco_itau.py | 1,698 | 4.03125 | 4 | # 341 - ITAU
# Tamanha da Agência - 4 dígitos
# Tamanha da conta - 5 dígitos
# Exemplo:
# Agência: 2545
# Conta: 023661
# Para Obter o DV, multiplica-se cada número da Agência e Conta em sua ordenação. Sequências PAR multiplica-se por 1 e ÍMPARES por 2. Se o número encontrado for maior que 9, soma-se as unidades da d... |
b4b8da6dd62e73b25cd334af6948c7ff2d6f582c | brunolomba/exercicios_logica | /Estrutura condicional/multiplos.py | 171 | 4.03125 | 4 | x = int(input('Digite um número'))
y = int(input('Digite outro número'))
if x % y == 0 or y % x == 0:
print('São multiplos')
else:
print('Não são multiplos') |
46ac2b687530ac76a3d5da828aec3aaed74da0a0 | brunolomba/exercicios_logica | /Matrizes/matriz_geral_pedro.py | 963 | 3.984375 | 4 | N = int(input("Qual é a ordem da matriz? "))
mat = [[0 for x in range(N)]for x in range(N)]
for i in range(0,N):
for j in range(0,N):
mat[i][j] = int(input(f"Elemento [{i},{j}]: "))
SomaPositivos = 0
for i in range(0,N):
for j in range(0,N):
if mat[i][j] > 0:
SomaPositivos = SomaP... |
b8c35c6bd26826fe250b5ed42d649fbf2af00dba | brunolomba/exercicios_logica | /Vetores/subtracao_vetores.py | 733 | 3.984375 | 4 | print('#' * 120)
print('Programa que recebe 2 vetores A e B com 5 números inteiros do usuário e soma os valores em um vetor C')
print('#' * 120)
quantidade_elementos = int(input('Digite a quantidade de elementos no vetor.'))
vetor_a = [0 for x in range(quantidade_elementos)]
vetor_b = []
vetor_soma = [0 for x in range... |
f441e2ebbcff6098d0a3e752550f770eb13ed708 | brunolomba/exercicios_logica | /banco_itau_funcao.py | 2,645 | 4.34375 | 4 | # 341 - ITAU
# Tamanha da Agência - 4 dígitos
# Tamanha da conta - 5 dígitos
# Exemplo:
# Agência: 2545
# Conta: 023661
# Para Obter o DV, multiplica-se cada número da Agência e Conta em sua ordenação. Sequências PAR multiplica-se por 1 e ÍMPARES por 2. Se o número encontrado for maior que 9, soma-se as unidades da d... |
b5ce51ae7333dd52603e1a391d78a62ab98834b8 | brunolomba/exercicios_logica | /Estruturas repetitivas/quadrante.py | 443 | 4.0625 | 4 | x = int(input('Digite a coordenada "X"'))
y = int(input('Digite a coordenada "Y"'))
while x != 0 and y != 0:
if x > 0 and y > 0:
print('Coordenada Q1')
elif x < 0 and y > 0:
print('Coordenada Q2')
elif x < 0 and y < 0:
print('Coordenada Q3')
else:
print('Coordenada Q4')
... |
862a1afa23038173122c1da925120046959b11b2 | brunolomba/exercicios_logica | /Estrutura condicional/lanchonete.py | 434 | 3.703125 | 4 | codigo = int(input('Digite o código do produto'))
quantidade = int(input('Digite a quantidade de produtos'))
valor_pago = 0
if codigo == 1:
valor_pago = 5 * quantidade
elif codigo == 2:
valor_pago = 3.5 * quantidade
elif codigo == 3:
valor_pago = 4.8 * quantidade
elif codigo == 4:
valor_pago = 8.9 * qu... |
1a6957707b3291a2158b3449f164e9d9a7b3a940 | brunolomba/exercicios_logica | /contagem_strings.py | 757 | 3.640625 | 4 | print('#' * 120)
print('Programa que conta quantas letras tem até 1000')
print('#' * 120)
zero = 'zero'
vetor_1 = ['um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove']
vetor_2 = ['dez', 'onze', 'doze', 'treze', 'quatorze', 'quize', 'dezesseis', 'dezessete', 'dezoito', 'dezenove']
vetor_3 = ['trinta... |
f6852400f5e8b2a0e35ebf7928a50d0cd37b42d3 | brunolomba/exercicios_logica | /Estrutura condicional/glicose.py | 172 | 3.625 | 4 | glicose = float(input('Digite o valor da sua glicose em mg/dl'))
if glicose < 100:
print('Normal')
elif glicose < 140:
print('Elevado')
else:
print('Diabetes') |
4831f52a0c18c7c349d3a479db10be7a6631bb73 | culvin2/Sequential-Search-Python | /sequential search.py | 364 | 3.703125 | 4 | testlist=[1,2,32,44,88,13,0]
a = 1
b = 32
def SequentialSearh(testlist,a):
for i in range(0,len(testlist)-1,1) :
if testlist[i]== a :
print("Found in index : ")
return i
break
else:
print("Sorry, not found!")
return False
print(SequentialSearh(testl... |
b2b35fe6e2a3a079b2f296538fe73528b5d52eb1 | txj44522/Phys5311TJ | /hw03/sciprog3.py | 4,221 | 3.734375 | 4 | """
This script will open DST file from KYPTO, parse the data, and load the hourly DST data into a one-dimensional
numpy array and the date-time objects into 1-D array; both arrays will print to screen.
It will also print to screen min, max, mean, median, and std of hourly DST data.
Next, import the module:
#>>>import ... |
51f28609cb8f18378556bc6ada002c97432536cf | nahalkk/learning_python | /stats.py | 981 | 3.828125 | 4 | #!/usr/bin/env python3
from math import sqrt
import fileinput
# Write a program that computes typical stats
# Count, Min, Max, Mean, Std. Dev, Median
# No, you cannot import any other modules!
scores = []
for line in fileinput.input():
if line.startswith('#'): continue
scores.append(float(line))
mean = sum(scores... |
87633563b026a250ff45f402a4162c5d996d6934 | crb8v2/3130algs_projec1 | /fibTiming.py | 954 | 4.0625 | 4 | from timeit import default_timer as timer
def fib_recursion(n):
if n == 0:
return 0
if n == 1:
return 1
return fib_recursion(n-1) + fib_recursion(n-2)
def fib_iteration(n):
if n == 0:
return 0
if n == 1:
return 1
minus_two = 0
minus_one = 1
for x in... |
266ab42bab539d38658df119958d615348fae38d | nadhiyap/pr1 | /sqr.py | 321 | 3.765625 | 4 | ax=int(input("enter a-x"))
ay=int(input("enter a-y"))
bx=int(input("enter b-x"))
by=int(input("enter b-y"))
cx=int(input("enter c-x"))
cy=int(input("enter c-y"))
dx=int(input("enter d-x"))
dy=int(input("enter d-y"))
if ax==ay and ay==bx and by==cx and cx==cy and cy==dx and dy==ax:
print("yes")
else:
print("no")... |
38a596998fe2dd4f89738c1dfc15617b83c90339 | dakelkar/pccc_general_info | /add_update_sql.py | 2,454 | 3.546875 | 4 | def update_single(conn, cursor, table, column, file_number, var):
# update a single column in a sql db. Key is file_number.
sql_update = "UPDATE " + table + " SET " + column + "= ? WHERE File_number = '" + file_number + "'"
cursor.execute(sql_update, [var])
conn.commit()
def insert(conn, cursor, table... |
1fb110f434a06cf6714d8e9c89e3d6988d425b05 | battlesysadmin/pr4e | /pr4e-final-2.py | 105 | 3.6875 | 4 | abc = None
lst = [1, 2, 3]
for val in lst:
if abc == None or val > abc:
abc = val
print abc
|
2cb6dee85b05b1b27323275f6d1db88c9522f086 | Li-Pro/Word-Search | /diclib/__init__.py | 893 | 3.578125 | 4 | """
Author: Li-Pro 2020
The main file of dictionary library.
"""
import string
import requests
from bs4 import BeautifulSoup
""" The dictionaries """
from .Dictionary import OxfordLearners
from .Dictionary import Urban
from .Dictionary import Cambridge
__all__ = ['OxfordLearners', 'Urban', 'Cambridge', 'searchWord... |
f225e2275c88d121e1bc0f268325b1dddf9e0d5a | bridgecrew-perf7/Heroku_NLP_Deployment | /Spam-Ham-Classification-NLP.py | 1,134 | 3.5 | 4 | # # SMS CLASSIFICATION USING NLP
# importing necessary libraries
import pandas as pd
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
# Loading the input dataset
dframe = pd.read_csv(r'./sms-dat... |
6a90e05a2712f070fb62e16a90c2fa4fd9424ed1 | m-119/PY111-2020-1 | /Tests/c1_test_fact.py | 1,019 | 3.5625 | 4 | import unittest
import math
import Tasks.c1_fact as fact
class MyTestCase(unittest.TestCase):
def test_fact_recursive(self):
self.assertEqual(math.factorial(7), fact.factorial_recursive(7), msg="Something gonna wrong...")
def test_fact_rec_exc(self):
with self.assertRaises(ValueError, msg="Va... |
c184bb6e001926857882bb723ce7e6ee1370633a | BigSamu-Coding-Dojo-Python-Assignments/User_with_Bank_Accounts | /user_with_bank_accounts.py | 4,231 | 3.875 | 4 | import random
import string
class BankAccount:
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
self.account_number = ''.join(random.choices(string.digits,k = 10))
def deposit(self, amount):
self.balance += amount
return s... |
b458910d53b2e63d4732adff493764bcc6ddc11d | Magorx/ray_tracing | /vector.py | 2,836 | 3.765625 | 4 | from math import sqrt, sin, cos
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector(self.y * other.z - self.z * other.... |
2b7a236fee6cd3332a3d35e8356e0a206253193c | FOSSRIT/knowledge | /knowledge/model/vertical/dictlike.py | 4,121 | 3.8125 | 4 | """Mapping a vertical table as a dictionary.
This example illustrates accessing and modifying a "vertical" (or
"properties", or pivoted) table via a dict-like interface. These are tables
that store free-form object properties as rows instead of columns. For
example, instead of::
# A regular ("horizontal") table h... |
ca47efef3c0309c33c25db8967bf9185793adac0 | muzhen321/FPIR17 | /pir_h1.py | 2,920 | 3.53125 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Rank sentences based on cosine similarity and a query."""
from argparse import ArgumentParser
from collections import Counter
import numpy as np
def get_sentences(file_path):
"""Return a list of sentences from a file."""
with open(file_path, enco... |
8d38d519cc851e7e8203fcf9d057d6f2404fe07a | maxlauhi/cspy3 | /1_7_2_mu_rec.py | 246 | 4.40625 | 4 | """determine whether a number is odd or even by mutual recursion"""
def is_even(n):
if n == 0:
return True
else:
return is_odd(n-1)
def is_odd(n):
if n == 0:
return False
else:
return is_even(n-1)
|
16b98888bf8a11bd18c57bca1c4ae572e02b9472 | maxlauhi/cspy3 | /2_3_2_Sequence.py | 431 | 3.84375 | 4 | def count(s, value):
"""Count the number of occurrences of value in sequence s.
"""
total = 0
for elem in s:
if elem == value:
total = total + 1
return total
"""
structure of FOR statment:
for <name> in <expression>:
<suite>
* <expression> must yield an iterable ... |
f8045a971b7f68e8dab65223d9478a770eeb9638 | alon-strik/localaws | /classes/class_variables.py | 742 | 3.625 | 4 | ## Logicly group a data and function for reuse
## attributes and methods assosiated with calss
# this is a class
class Employee:
## this is a constrctore or init method
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '... |
ef3e1712df8cf28034c6ab2fc8d3fd46b4683783 | shivsun/pythonappsources | /Exercises/Integers/accessing elements in the list with messages.py | 1,294 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 21:09:17 2020
@author: bpoli
"""
#Accessing Elements in a List
#Lists are ordered collections, so you can access any element in a list by
#telling Python the position, or index, of the item desired. To access an element
#in a list, write the name of the list followed... |
ff82f8cee9baae9fd747ffa2cc9eca60f1d35b01 | Shivani2601/Training_NPCI | /Python/Tower_Ques2.py | 1,201 | 3.859375 | 4 | incr=3
rows=3
first=1
n=2*rows-2
for i in range(0, rows):
for j in range(0, n):
print(end=" ")
n=n-1
y=first
for j in range(0, i+1):
print(y, end=" ")
y+=1
first+=incr
print(" ")
print("\n")
##########################################
first_ele=0
total_sum=1... |
67346fc55b06883e5bdd78ef4d7a673fd179fef6 | b26/Amazon-Reviews-CLI | /Python/Dictionary style/people.py | 916 | 3.625 | 4 | #!/usr/bin/env python3
import bsddb3
import os.path
# Create the database
if os.path.isfile("people.db"):
db = bsddb3.btopen("people.db", "w")
else:
db = bsddb3.btopen("people.db", "c")
# Add data to the database
data = {b'Ian': 'Smith', b'Carl': 'Horwitz', b'Ted': 'Smith', b'Fred': 'Torrens'}
for key, value... |
75cd0ac7964c03527eda2ef93663ee623f1e0307 | zeleksa/ALS1 | /DU4/b_tree.py | 3,261 | 3.734375 | 4 |
class B_tree():
def __init__(self, t):
self.t = t
self.root = None
def traverse(self):
if self.root is not None:
self.root.traverse()
def search(self, num):
if self.root is None:
return None
self.root.search(num)
def insert(self, num):... |
d65b8b02e60862b40c2ec1f2d03ace49f592a477 | nismojkee/RLE_encode_decode | /rle.py | 1,097 | 3.703125 | 4 | class RLE:
def rle_encode(data):
encoding = ''
previous_character = ''
counter = 1
if not data:
return ''
for character in data:
if character != previous_character:
if previous_character:
encoding += str(counter) + p... |
6533350573503fb7b0c17d2bb1d4e8f791a559d1 | Harshpatel44/RemindMe | /test.py | 442 | 3.65625 | 4 | __author__ = 'harsh'
import random
import Tkinter as tk
list=[1,2,3,4,5]
print(random.choice(list))
root = tk.Tk()
v = tk.IntVar()
tk.Label(root, text="""Choose a programming language:""",justify = tk.LEFT,padx = 20).pack()
radio1=tk.Radiobutton(root, text="Python",padx = 20, variable=v, value=1).pack(anchor=tk.W... |
23e5736c95fc1c31ec33fbd533bd72c89ff7f014 | celier/Exercism-python | /pangram/pangram.py | 928 | 3.78125 | 4 | def is_pangram(sentence):
try:
if len(sentence) < 26:
return False
else:
checker = []
for i in range(26):
checker.append(False)
for letter in sentence.lower():
# Using Unicode number representation for index... |
fb7ebd58dc36524ee88ba886fbdc238c8018aa91 | waalge/snake_cube | /tests/basic_tests.py | 1,828 | 3.546875 | 4 | #!/usr/bin/python3
import os
import sys
import unittest
sys.path.append("../snake_cube")
import cube_data
import toy
class TestSnakeCube(unittest.TestCase):
def test_solutions_pass(self):
"""
Check that known solutions work
"""
cube = cube_data.CUBES[2]
strip_lengths = cu... |
126e98cabf536543ce3ea5d9b7af10890e913857 | tareksmoubarak/Coderbyte-Challenges-Python | /longest-word.py | 192 | 4.21875 | 4 | def longestWord(string):
array = string.split()
max = ''
for word in array:
if (len(word) > len(max)):
max = word
return max
print longestWord(raw_input()) |
e083c1cbb643249c39457e466d9f37e5308ca35b | joswong13/Poetry-Tester | /poetry_functions.py | 13,850 | 4.21875 | 4 | """
A poetry pattern: tuple of (list of int, list of str)
- first item is a list of the number of syllables required in each line
- second item is a list describing the rhyme scheme rule for each line
"""
"""
A pronunciation dictionary: dict of {str: list of str}
- each key is a word (a str)
- each value is a... |
effcb1ac657055345907dc7ab1a2bef64a6ea8be | 9car/IN1000-1 | /uke5/roter_matrise.py | 339 | 3.578125 | 4 | matriseEn = [
[1,4,7],
[2,5,8],
[3,6,9]
]
matriseTo = [
[1,2,3],
[4,5,6],
[7,8,9]
]
def roter(matrise):
returMatrise = []
for i in range(0,len(matrise)):
returMatrise.append([])
for j in range(0, len(matrise[i])):
returMatrise[i].append(matrise[j][i])
return returMatrise
print... |
ae0599b2660cc5e3fb246a0ce52dd6a18093323a | 9car/IN1000-1 | /uke3/barnebarn.py | 188 | 3.703125 | 4 | person = input("Konge: ")
etterkommere = {"Oscar":"Haakon", "Haakon":"Olav", "Olav":"Harald"}
barn = etterkommere[person]
barnebarn = etterkommere[barn]
print("Barnebarn: " + barnebarn)
|
d940e6fd24a3f53c61a141ae3d4565b455261812 | 9car/IN1000-1 | /2017/kode.py | 3,021 | 3.53125 | 4 | #Oppgave 3a
"""
def hastighet(fart):
if fart <= 60:
return "fart:" + str(fart)
else:
return "fart:over 60"
print(hastighet(56))
print(hastighet(65))
"""
#Oppgave 3b
"""
def sjekkVerdier(tallene, min, max):
for tall in tallene:
if tall <= min or tall => max:
return False... |
71fcf1b193e8f96abba78167d65180f062ca59a8 | 9car/IN1000-1 | /oblig5/regnefunksjon.py | 1,523 | 4.15625 | 4 | def addisjon(tall1, tall2):
tall1 = int(tall1)
tall2 = int(tall2)
# Regner ut summen av to tall
return tall1 + tall2
print(addisjon(2, 9))
def subtraksjon(tall1, tall2):
tall1 = int(tall1)
tall2 = int(tall2)
# Regner ut differansen
return tall1 - tall2
assert subtraksjon(15, 10) ==... |
fc4f97c0c76ef25cd8efcaf8eb93dee153cf6db6 | 9car/IN1000-1 | /uke4/lokker.py | 237 | 4 | 4 | tall = int(input("Tast et heltall: "))
teller = 0
while teller < tall:
print(teller)
teller += 1
tall = 0
while tall != 10:
inp = input("Tast et heltall: ")
tall = int(inp)
print("Du tastet 10, programmet avsluttes")
|
84845b00c49ff78c0f4f06c4903ba398033865f9 | 9car/IN1000-1 | /uke4/heltallsliste.py | 279 | 3.640625 | 4 | tall1 = 0
tall2 = 1
tall3 = 2
tall4 = 3
tall5 = 4
print(tall1)
print(tall2)
print(tall3)
print(tall4)
print(tall5)
tall = []
teller = 0
while teller < 5:
tall.append(teller)
teller += 1
print(tall)
teller = 0
while teller < 5:
print(tall[teller])
teller += 1
|
4632666bba9cbf231408e080387ef5e3eacc22f5 | 9car/IN1000-1 | /uke2/minst.py | 149 | 4.03125 | 4 | tall1 = int(input("Skriv tall 1: "))
tall2 = int(input("Skriv tall 2: "))
if tall1 < tall2:
minst = tall1
else:
minst = tall2
print(minst)
|
dfd6fe415e73a1916574aaa0afcf44136ac28a7a | 9car/IN1000-1 | /oblig4/regnelokke.py | 856 | 4.03125 | 4 | #Tom liste som lagrer alle tallene brukeren taster inn
liste = []
tall = int(input("Tast inn et tall: "))
#Så lenge tallet ikke er 0 vil den kjøre i en evig loop
while tall != 0:
liste.append(tall)
print(tall)
tall = int(input("Tast inn et tall: "))
#Skriver ut alle tallene i listen på en pen måte
for i i... |
d1db5bb3eba3dbbf16385db01c338788bf802e0d | 9car/IN1000-1 | /uke2/hello_world.py | 131 | 3.578125 | 4 | hello = "Hello"
print(hello)
world = "World"
print(world)
print(hello + " " + world)
print(hello, "?", " ", world, "?", sep="")
|
a51d3197844b8fa2d3aa3f504d08d89e21df1872 | 9car/IN1000-1 | /uke4/en_plusset_opp_til_hundre.py | 95 | 3.5625 | 4 | tall = 0
summen = 0
while tall <= 100:
summen = summen + tall
tall += 1
print(summen)
|
7db4c3b683edf2b2025950cc8a01f258c2f49fac | 9car/IN1000-1 | /2019H/kode.py | 2,327 | 3.515625 | 4 | """bok = {"a":[3,4,5], "b":[6,7]}
bok["a"].append(8)
print(len(bok["a"]))
"""
"""def funk(a,b):
return a*b
c = funk(2+3,2)*4
print(c)
"""
"""#Oppgave 3a
def pris_inkl_frakt(varepris):
if varepris > 1000:
return varepris
elif varepris >= 500 and varepris <= 1000:
return varepris + 50
e... |
b8589ee02e53c0fa67f2bc5d78a820e472c82fc6 | 9car/IN1000-1 | /oblig4/funksjoner.py | 776 | 3.703125 | 4 | #lager en funksjon som returnerer to tall addert med hverandre
def adder(tall1,tall2):
return tall1 + tall2
#Skriver de ut
sum = adder(2, 4)
print("Her er summen av tallene:", sum)
sum = adder(6, 10)
print("Her er summen av tallene:", sum)
#Lager en funksjon som teller hvor mange ganger en bokstav forekommer i en... |
7bb84903c775f616e0bf51f6d883fdf722ac5627 | vbellee/python_simulation | /FiberSetup.py | 7,743 | 3.5625 | 4 | # @file FiberSetup.py
"""
.. module:: FiberSetup
:synopsis: Fiber Definition and fiber_stack definition
.. moduleauthor:: <sebastiana.giani@epfl.ch>
"""
import numpy as np
import math
import random
import ROOT
import Sipm
import MainSimulation
class Fiber(object):
"""Class to define the object fiber.
... |
0b111a4e7f476a46248db5680d9c0ab9d1aebc1d | miffymon/Python-Learning | /ex06.py | 1,210 | 4.40625 | 4 |
#Python function pulls the value although its not announced anywhere else
#string in a string 1
x = "There are %d types of people." % 10
#naming variable
binary = "binary"
#naming variable
do_not = "don't"
#assigning sentence to variable and calling other assigned variables
#string in a string 2
y = "Those who know %... |
41b9362f35f0f4f97d43258315b595cfb5ed545b | smccrave/python595 | /lec08/scientific_computing.py | 3,371 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Python Lecture 8: Scientific Computing
# ## Jarret Petrillo copyright 2020
# ## AMS 595
# # Learning Goals
#
# Review code sample to produce *deterministic chaos*.
#
# This involves solving *ordinary differential equations*, a hallmark of scientific computation and computat... |
f533dddb9e2ba1ecb1d1a7b0a4a6ceb20976d022 | ferisso/phytonexercises | /exercise7.py | 893 | 4.21875 | 4 | # Question:
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
# Note: i=0,1.., X-1; j=0,1,¡Y-1.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the progra... |
0f7140089e5db6941ebeddc8fc1796c09c5609b6 | VinPer/DiscordBot | /extensions/rng.py | 3,826 | 3.75 | 4 | # -*- coding: utf-8 -*-
import discord
import random
import math
from discord.ext import commands
"""
This extension implements basic commands based upon the use of randomly
generated numbers or choices, just to add some interactivity to the bot.
"""
class RNG:
def __init__(self, client):
self.client =... |
fb719360014e44e85e16f13ba806ec60c59eb97d | yanlingsishao/study | /day2/高阶函数.py | 3,405 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Created on 2017年5月16日
@author: WangQiyuan
'''
#高阶函数定义
#1.函数接收的参数是一个函数名
#2.函数的返回值是一个函数名
#3.满足上述条件任意一个,都可称之为高阶函数
#(1)
# import time
# def foo():
# time.sleep(3)
# print("hell,你好")
# def test(func):
# start_time=time.time()
# func()
# stop_time=time.ti... |
0fb118912300df21ec01aec163395fe8fe733a51 | yanlingsishao/study | /ATM/ATM/atm_back/main.py | 544 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Created on 2017年5月9日
@author: WangQiyuan
'''
import login
def Exit():
print("程序退出")
exit()
def Main():
msg='''
欢迎来到:
1:登录
2:退出'''
msg_dic = {
"1":login.login_user,
"2":Exit,
}
while True:
... |
4f1518f7984890d31abf3f9e0f3a96aa2f6ee478 | yanlingsishao/study | /day1/three_lv menu.py | 2,040 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Created on 2017年5月9日
@author: WangQiyuan
'''
dic = {
'山西省':{'晋城市':['高平县','泽州县','沁水县'],'长治市':['长子县']},
'河北省': {'保定市': ['雄县']},
}
e = list(dic['山西省'].keys())
f = list(dic['河北省'].keys())
e1 = list(dic["山西省"]["晋城市"])
e2 = list(dic["山西省"]["长治市"])
f1 = list(dic['河... |
0d7f58aa6c9cc2d4c4a58ad2475ad2f74d35059b | zhankun/python-orm | /Four.py | 736 | 3.703125 | 4 | import fileinput
# w = open("/Users/zhankun/Desktop/test.txt")
with open("/Users/zhankun/Desktop/test.txt") as file:
while True:
line = file.readline()
if not line:
break
print(line)
print("-----------我是万恶的分割线------------")
with open("/Users/zhankun/Desktop/test.txt") as file... |
faff1cec10dcababbf86d53ae4d01d8e1dda8b5c | jalilGJ/Ordenamiento_Mezcla | /Ordenamiento_Mezcla.py | 2,228 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 21:16:52 2021
@author: jalil
"""
import random # se importa la libreria para poder generar numeros aleatorios
def merge_sort(data):
mid = len (data) //2 # divide la mitad del arreglo
if len(data)> 1: #si la longitud del data es mayor a uno
... |
5a978d96695e8673b6e0d615957c9751288417cb | CheeseTheMonkey/AdventOfCode | /2019/day22.py | 1,857 | 3.6875 | 4 |
def new_stack(deck):
return deck[::-1]
def cut(deck, index):
return deck[index:] + deck[:index]
def deal_with_increment(deck, increment):
new_deck = [False] * len(deck)
index = 0
for card in deck:
new_deck[index] = card
index += increment
index = index % len(deck)
r... |
0408db7520cc0a1805cf0b570d550743e27b7b71 | 1ynden/CS451-FinalProject-AIsnake | /snake.py | 2,899 | 3.59375 | 4 | from pygame import display, time, draw, QUIT, init, KEYDOWN, K_LEFT, K_RIGHT, K_UP, K_DOWN, K_q
from random import randint
import pygame
from numpy import sqrt
init()
done = False
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
cols = 30
rows = 30
width = 600
height = 600
blockW = wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.