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 |
|---|---|---|---|---|---|---|
26f06216b4cf66c2bb236dccb89ae7cf0d7b2713 | rchristopfel/IntroToProg-Python-Mod07 | /Assignment07.py | 2,304 | 4.125 | 4 | # ------------------------------------------------------------------------ #
# Title: Assignment 07
# Description: using exception handling and Python’s pickling module
# ChangeLog (Who,When,What):
# Rebecca Christopfel, 11-18-19, test pickle module
# Rebecca CHristopfel, 11-20-19, create try/except block for scri... |
89a8620aabbd1c374b5f6f6a7108be1eaa3ef3fc | windowsl/lies | /test_bot.py | 362 | 3.53125 | 4 | """
unit tests for the bot library
"""
import bot
class TestBot:
def test_longest(self):
assert "four score and seven years ago" == bot.longest("something", "something else", "four score and seven years ago")
def test_shortest(self):
assert "something" == bot.shortest("something", "something... |
501051e00c396c39b49742b05d15e8ae26b05bb6 | nikopinta/PZW | /vjezba-01.py | 221 | 3.75 | 4 | #Varijabla
a = 5
b = 3
print(a)
print(b)
print(a + b)
a = 10
print(a + b)
c= 3.14
poruka1 = "Bravo hakeri"
poruka2 = "Danas učimo python"
print(poruka1)
print(poruka2)
print(poruka1+ " " + poruka2) |
4132f158f1ed03041d8849a41c7ae7ad0c9da25f | jainswati2903/BioinfoSpecl_Coursera | /Course1/Week3.py | 8,841 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
from Week1 import *
from Week2 import *
import numpy as np
import math
def MotifEnumeration(dna_strings,kmer_len,number):
'''function to return all kmers that occur in all strings in dna_strings with atmost number mismatches'''
kmers_in_all=dict() # dictionary to con... |
0b2753790f1dd067c8a4b020febdcd1b6c41d8c9 | evgnep/ArchiTanks | /game/game_actions/motions/Rotatable.py | 264 | 3.546875 | 4 | from abc import ABC, abstractmethod
class Rotatable(ABC):
@abstractmethod
def get_direction(self):
pass
@abstractmethod
def set_direction(self, new_value):
pass
@abstractmethod
def get_angle_velocity(self):
pass
|
39a68989d5bb5fb4bae0025103da79a09c6bc161 | Kwoneunhee098/START-UP-PYTHON | /사칙연산 계산기.py | 1,978 | 3.9375 | 4 | # 사칙연산 계산기 만들기(함수)
# 함수 6개의 원형 정의
def plus(a, b) :
result = a + b
return result
def minus(a, b) :
result = a - b
return result
def mul(a, b) :
result = a * b
return result
def division_f(a, b) :
result = a / b
return result
def division_i(a, b) :
result = a /... |
46e7b074db028c1067a0103502d4fcb90e4bfaf1 | BlitheG/LeetCode | /0169 多数元素/Python/0169 多数元素.py | 1,350 | 3.828125 | 4 | #!python3
#-*- coding: utf-8 -*-
"""
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
进阶:
尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
"""
class Solution:
def majorityElement(self, nums: list[int]) -> int:
... |
919d4323cdb5dd99e5aff75710d00fe279bbf712 | XavierKoen/lecture_practice_code | /guessing_game.py | 254 | 4.125 | 4 | question = input("I'm thinking of a number between 1 and 10, what is it? ")
ANSWER = '7'
print(question)
while question != ANSWER:
question = input("Oh no, please try again. ")
print (question)
print("Congrtulations! You were correct, it was 7!") |
1a8f986972d5f0ec326aaeb3f901cc259bf47ecd | XavierKoen/lecture_practice_code | /name_vowel_reader.py | 786 | 4.125 | 4 | """
Asks user to input a name and checks the number of vowels and letters in the name.
"""
def main():
name = input("Name: ")
number_vowels = count_vowels(name)
number_letters = count_letters(name)
print("Out of {} letters, {}\nhas {} vowels".format(number_letters, name, number_vowels))
def count_vo... |
04b9d41e4eb616db79b0ca3c89ad93610424738e | ernestrlee/UCSC-Machine-Learning | /Bayesian.py | 3,939 | 3.625 | 4 | import numpy as np
import math
def calculatePDF(x, sigma, mu):
"""
This function calculates the probability density of a
multinormal distribution for a single feature vector.
Args:
x : array, the single data set
sigma : array, the covariance matrix for the class
mu... |
ceb9fa241c6029ca2519e771bfeea04f1ca3486d | kuroama/dokugaku | /dokugaku7.py | 1,359 | 3.59375 | 4 | #1
list1=["ウォーキング・デッド","アントラージュ","ザ・ソプラノズ","ヴァンパイア・ダイアリーズ"]
for title in list1:
print(title)
#2
for i in range(25,50):
print(i)
#3
for i,title in enumerate(list1):
print(str(i)+":"+title)
#4
while True:
num_list = [1,5,7,34,9]
str = input("文字を入力してください:")
if str == "q":
break
if st... |
6a9ee40aee86777dca7cd0954bd09a69527cec2d | kuroama/dokugaku | /dokugaku14.py | 973 | 4.09375 | 4 |
#1
class Square():
square_list = []
def __init__(self,s):
self.sides = s
self.square_list.append(self)
def calculate_perimeter(self):
return self.sides*4
def change_size(self,l):
if l>0:
self.sides = self.sides + l
else:
if self.side... |
3482718811f7dd41e949d8ee96a61c78ec75fa16 | mdcovarr/interpreter | /interpreter.py | 9,828 | 3.5625 | 4 | """
Implementation of a C programming language interperter written in Python
"""
from pycparser import parse_file, c_parser, c_generator, c_ast
from memory import Memory
class Interpreter(c_ast.NodeVisitor):
"""
Interpreter class used to interpret the a subset of the C programming language
"""
... |
21bbeef118564eb53d4c8d8106d75ae3920099ba | AshishPandagre/Python | /backtracking/SUDOKUsolver.py | 1,941 | 3.875 | 4 | # sudoku solver with backtracking algorithm...
board = [[4,0,0,0,1,0,3,0,0],
[0,6,0,4,0,7,0,0,0],
[0,5,0,0,3,2,1,4,0],
[9,0,4,0,0,1,0,8,5],
[0,0,6,0,0,0,9,0,0],
[3,1,0,7,0,0,6,0,4],
[0,4,9,5,7,0,0,3,0],
[0,0,0,1,0,4,0,7,0],
[0,0,1,0,9,0,0,0,2]]
... |
172c58a51ac96b82f40ef138c953f9d6c69b08a6 | FluxLemur/citybash | /clients/utils.py | 1,254 | 3.515625 | 4 | import socket
def send(socket, message):
# In Python 3, must convert message to bytes explicitly.
# In Python 2, this does not affect the message.
socket.sendall(message.encode('utf-8'))
def send_command(host, port, message):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.con... |
21034288425d67283e55e7845eb3fe0332922913 | BogyMitutoyoCTL/Snake-AI-2021.1 | /code/Algorithms/RandomChoice.py | 595 | 3.546875 | 4 | from random import random
from Algorithms.Algorithms import Algorithm
from GameData import GameData
class RandomChoice(Algorithm):
def __init__(self):
super().__init__()
"""
A stupid algorithm that returns a random value.
This can be used for comparisons with other algorithms.
Best resul... |
44a2d9f8efcb129a49610962482198ff86458ba1 | webwesen/leetcode | /0121-best-time-to-buy-and-sell-stock.py | 390 | 3.515625 | 4 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n < 2:
return 0
min_p = prices[0]
max_p = 0
for i in prices:
min_p = min(min_... |
9d1475e09c0377b92894f22addeab1184fbd7ea1 | tpetersfullstack/cohort3 | /python/03_getting_user_input/code3.py | 201 | 4.03125 | 4 | size_input = input("How big is your house (in square feet): ")
square_feet = int(size_input)
square_metres = square_feet / 10.8
print(f"{square_feet} square feet is {square_metres:.2f} square metres.") |
2c4f808628a78263293126ed2473e6e54cd3c2c5 | kawing-chiu/exc | /Python/15pandas/groupby/test.py | 4,795 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
### 1. creating groups
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', '... |
1af4dd4a4cfb45b3e9ffa43362f2f61bb05f9180 | kawing-chiu/exc | /Python/05closure/basic_tests/test2.py | 1,383 | 3.609375 | 4 |
def get_closure():
x = 500
def test(data):
print("x:", x)
print("data:", data)
print("i:", i)
return test
test = get_closure()
# define AFTER function definition:
i = 200
def get_closure_closure(func):
i = 2000
return func
def get_closure_closure_closure(i):
def g... |
b656082d6511884081e58b11e004a708500d39ae | yangjiaxuan/Python_Class | /Demo/Demo_01.py | 1,189 | 3.9375 | 4 |
class Cat:
# 这是一个初始化方法 用类名()时,会自动调用初始化方法
def __init__(self, name=""):
print("cat 初始化")
# 在初始中添加一个属性,这样后面所有的对象中就都有这个属性了,并拥有初始值
self.name = name
# 析构方法
def __del__(self):
print("cat %s 被销毁了" % self.name)
def __str__(self):
return "Cat: name->%s" % self.name
... |
c5df2da9a0548d7ec24df37a931d172b7126d0be | jiucaneg/B6 | /B6.10/4.py | 742 | 4.03125 | 4 | class Person:
def __init__(self, name, city):
self.name = name
self.city = city
class Guest(Person):
def __init__(self, name, city, status):
Person.__init__(self,name, city,)
self.status = status
def add_to_list(self, g_list):
return g_list.append(f'{self... |
04cb412cecc6d49bd15ebde03cc729f51d1e19aa | milanvarghese/Python-Programming | /Internshala/Internshala Assignments/W5 Assignment - Connecting to SQLite Database/insert_data.py | 1,124 | 4.28125 | 4 | #Importing Necessary Modules
import sqlite3
#Establishing a Connection
shelf=sqlite3.connect("bookshelf.db")
curshelf=shelf.cursor()
#Creating a table with error check
try:
curshelf.execute('''CREATE TABLE shelf(number INT PRIMARY KEY NOT NULL ,title TEXT NOT NULL, author TEXT STRING, price FLOAT NOT NULL);''')
... |
5b8e7d08fe0186d0104bab64eef77b8a417ad60a | milanvarghese/Python-Programming | /Internshala/Internshala Assignments/W4 Assignment - Principles of Object-oriented Programming/M4 Assignment - Principles of Object-oriented Programming.py | 3,910 | 3.859375 | 4 | #Defining book class
class book:
def __init__(self,title="The Only Pirate at the Party",author="Lindsey Stirling",publisher="Gallery Books",price=708,quantity=1000):
#Defining variables
self._title=title
self._author=author
self._publisher=publisher
self._price=price
... |
c2e55ecefc9dfd65e05b208d90401eaf90edfeeb | CamiloBallen24/Python-PildorasInformaticas | /Script's/01 - Sintaxis Básica/Diccionarios.py | 2,878 | 3.9375 | 4 | #TEMA:DICCIONARIOS
#Es una estructura con una asociacion clave:valor.
#A cada valor que se almacena se le asigna una clave unicos
#El orden da lo mismo
#Almacena todo tipo de valor
###########################################################################
#Diccionario Basico
print("Ejemplo #1")
miDiccionario ={"Espa... |
f836c6e49812a92ebd000d20d9c82c528bce311e | CamiloBallen24/Python-PildorasInformaticas | /Script's/03 - Bucles/For.py | 856 | 4.09375 | 4 | #TEMA: FOR
#######################################################
#Recorrer una lista
print("Ejemplo #1")
for i in ["Primavera", "Verano", "Otoño", "Invierno"]:
print(i)
print()
print()
print()
#######################################################
#Recorrer un String
print("Ejemplo #2")
miEmail="Camilo@gmail.com... |
9f8ee0a39e6f550bcf65e808386b728ec0ce8236 | CamiloBallen24/Python-PildorasInformaticas | /Script's/13 - Bases de Datos/Bases de Datos - 01.py | 758 | 3.5 | 4 | #TEMA: Creacion de una tabla
#################################################################
import sqlite3
#################################################################
#################################################################
#Creamos base de datos y conexion
#Si la base de datos existe solo debemos ... |
76f3fe078aebe4ede0b70767e19ba901e4a7d7b7 | CamiloBallen24/Python-PildorasInformaticas | /Script's/00 - Otros/Metodos de Cadenas.py | 1,029 | 4.4375 | 4 | #TEMA: METODOS DE CADENA
################################################################
print("Ejemplo #1")
miCadena = "Hola"
print(miCadena.upper()) #Pasa a mayusculas tooo
print()
print()
print()
################################################################
####################################################... |
c095b9c77eeb486234c22e265bf84e6db026e270 | CamiloBallen24/Python-PildorasInformaticas | /Script's/12 - Interfaces Gráficas/Interfaces Graficas 04.py | 1,462 | 3.75 | 4 | #TEMA: Text y Button
#Text: Introducir textos largo
#Button: Botones toda la vida
####################################################################
from tkinter import *
####################################################################
####################################################################
def co... |
19cf69ce3003138a6b6cdfff3f44de031174d6dd | CamiloBallen24/Python-PildorasInformaticas | /Script's/00 - Otros/Funcion Map.py | 1,612 | 3.90625 | 4 | #TEMA: Funcion Map
#Map aplica a cada elemento de una lista una misma funcion
######################################################################################################################################################
#Ejemplo #1
class Empleado:
def __init__(self, nombre, cargo, salario):
self.nombre = n... |
4475eee82d046ab1fe1d3a8b1471c8e9f1c8b816 | CamiloBallen24/Python-PildorasInformaticas | /Script's/06 - POO/POO-02.py | 2,156 | 3.921875 | 4 | #Tema: -Estado Inicial (Constructor)
# -Encasuplacion (Atributos y Metodos)
#El estado inicial o contructor, nos permite determinar como
#sera el estado de al instancia, en el punto en el que se crea.
#La encapsulacion, nos permite ocultar al exterior (fuera de la clase)
#algunos atributos y metodos, los cuales ... |
6cb98bd1b8c1bd3d965f5b6660a629b3d20a7438 | jayeshgurbani2525/pythontutorial | /HelloWorld/primenumber.py | 203 | 4 | 4 | number = int(input('enter the number: '))
prime = True
if number < 2:
prime = False
else:
i = 2
prime = True
while i < number:
if number % i == 0:
prime = False
break
i = i + 1
print(prime) |
3ab86017e18bf82bbc97d59dea765830e72b6b9d | deep-spin/pyturbo | /turboparser/commons/reader.py | 1,243 | 3.875 | 4 | class Reader(object):
'''An object that creates readers of a specialized class.'''
def __init__(self, reader_class=None):
"""
Initialize the reader manager with the class of the specialized reader.
Once created, this reader can be used in with blocks by calling the
open() method... |
dc73601bced9a16c9b52abdb42a53b04df5da287 | Ktheara/learn-python-oop | /advaced-review/2.tuple.py | 959 | 4.5625 | 5 | # A tuple is a collection of objects which is ordered and immutable(unchangeable).
# https://www.python-engineer.com/courses/advancedpython/02-tuples/
# So similar to list but elements are protected
mytuple = ('a', 'p', 'p', 'l', 'e') #create a tuple
print(mytuple)
# number of elements
print(len(mytuple))
# number ... |
4760b49539e625d566b311c167a94b1d62adce2e | Currie32/Predicting-Credit-Card-Fraud | /Predicting_Credit_Card_Fraud.py | 17,914 | 3.53125 | 4 |
# coding: utf-8
# # Predicting Credit Card Fraud
# The goal for this analysis is to predict credit card fraud in the transactional data. I will be using tensorflow to build the predictive model, and t-SNE to visualize the dataset in two dimensions at the end of this analysis. If you would like to learn more about th... |
d7948b4af779d68ed87af1d832c4cf6c558ec274 | cuongv/LeetCode-python | /BinaryTree/PopulatingNextRightPointersInEachNode.py | 2,802 | 4.21875 | 4 | #https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
"""
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate ea... |
485181531a2401668939f0b463c9c2071fb0ee9f | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_39/remove_using_compression.py | 188 | 3.859375 | 4 | dict = {'Sudhamshu': '091', 'Akash': '093', 'Rajasudhan': None,'Vaishakh':'092','Naveen': 0}
dict = {key:value for key,value in dict.items() if value!=0 and value is not None}
print(dict)
|
221d7db18785378d0ec8fe472a051aa195e7a102 | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_32/X_pattern.py | 130 | 3.546875 | 4 | n = 3
for i in range(-n, n + 1):
print('{}*{}{}'.format((n + 1 - abs(i)) * ' ',(2 * abs(i) - 1) * ' ','' if i == 0 else '*'))
|
740e64f104d53bac498c900e78559ff47536d1df | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_2/odd_product.py | 368 | 3.859375 | 4 | def odd_product(number):
for i in range(len(number)):
for j in range(len(number)):
if i!=j:
product = number[i] * number[j]
if (product % 2) & 1:
return True
#test cases
#print(odd_product([1,6,4,7,8]))
#print(odd_pro... |
c4be6d699ae7abb1fd4d2d085c377d901a3a82c8 | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_39/remove_empty_keyvaluepair.py | 233 | 3.671875 | 4 | dict = {'Sudhamshu': '091', 'Akash': '093', 'Rajasudhan': None,'Vaishakh':'092','Naveen': 0}
new_dict = {}
for key,value in dict.items():
if value != 0 and value is not None:
new_dict[key] = value
print(new_dict)
|
1dfcc2fe5bcac12d235391d073b5991fca58960b | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_21/string_punctuation.py | 232 | 4.25 | 4 | from string import punctuation
string = "/{Python @ is actually an > interesting //language@ "
replace = '#'
for char in punctuation:
string = string.replace(char, replace)
print("String after replacement is: ", string)
|
b2bb10ae15437acde7e88af1587c7e559f2034b0 | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_36/pascal.py | 268 | 3.796875 | 4 | rows = int(input("Enter the number of rows : "))
for i in range(0, rows):
coff = 1
for j in range(1, rows-i):
print(" ", end="")
for k in range(0, i+1):
print(" ", coff, end="")
coff = int(coff * (i - k) / (k + 1))
print()
|
88fa596a897959b76862605be56a153b606f4555 | devil-cyber/Data-Structure-Algorithm | /tree/count_node_complete_tree.py | 643 | 4.125 | 4 | from tree import Tree
def height_left(root):
hgt = 0
node = root
while node:
hgt += 1
node = node.left
return hgt
def height_right(root):
hgt = 0
node = root
while node:
hgt += 1
node = node.right
return hgt
def count_node(root):
if root is None:
... |
1364bf6c974f8a7cae786179b8a9892bed0394b4 | devil-cyber/Data-Structure-Algorithm | /heap/heapsort.py | 1,555 | 3.71875 | 4 | import math
def maxheapify(i, n, arr):
largest = i
left = 2*i +1
right = 2*i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
maxhe... |
b80516f0d6b291c56490538dffbae9ae6d6079b2 | devil-cyber/Data-Structure-Algorithm | /tree/level_order_line.py | 591 | 3.90625 | 4 | from tree import Tree
from collections import deque
def __level_order_line__(root):
d = deque()
d.append(root)
while len(d)!=0:
n = len(d)
for i in range(n):
curr = d.popleft()
print(curr.data,end=" ")
if curr.left is not None:
d.append(c... |
391962d1b1b0969fca68d151242c80842ce72604 | devil-cyber/Data-Structure-Algorithm | /heap/sum_item.py | 378 | 3.765625 | 4 | # Buy itme with given price as list with bound to given price sum
import heapq as h
def buyItem(arr, _sum):
h.heapify(arr)
result = 0
count = 0
while result <= _sum:
key = h.heappop(arr)
result += key
count += 1
h.heapify(arr)
return count - 1
if __name__ == "__main... |
1f9e83ff747bc15aabf25dfe54be21d8e65992a9 | devil-cyber/Data-Structure-Algorithm | /tree/tree.py | 614 | 3.515625 | 4 | class Node:
def __init__(self, data) -> None:
self.right = None
self.left = None
self.data = data
class Tree:
def __init__(self):
pass
def create_tree(self):
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)... |
4d299bb42af6a63c1dbda2b0fa30440c1f88c622 | pwnsaur/exercism | /python/perfect-numbers/perfect_numbers.py | 389 | 3.65625 | 4 | def classify(number):
if number >= 1:
factors = 0
for num in range(1, number):
if number % num == 0:
factors += num
if factors == number:
return 'perfect'
elif factors < number:
return 'deficient'
else:
return 'a... |
2484fb95f142377eb6867ae1bd68c5cb205b7d3b | thangbk2209/natural_language_understanding | /models/text_classification/ANN_classifier.py | 6,968 | 3.515625 | 4 | import numpy as np
# from word2vec import Word2vec
import tensorflow as tf
from preprocessing_classifier import PreprocessingDataClassifier
import pickle
"""
this class training word2vec and receive a vector embedding and
use this vector to train text classification by africial neural network model
"""
class Classifie... |
47f1dc419dbc648ba795f5d279a22d896bf14a25 | full-stack-snacks/pyser | /dsa/linked_list.py | 552 | 3.859375 | 4 | class LinkedList:
def __init__(self, values=None):
self.head = None
if values:
for value in reversed(values):
self.insert(value)
def insert(self, value):
self.head = Node(value, self.head)
def to_list(self):
values = []
current = self.hea... |
06f4a145601fe45cf38dfb601039e4207f30d0f5 | riannselegar/SCwP-arithmetic-formatter | /arithmetic_arranger.py | 1,348 | 3.53125 | 4 | def arithmetic_arranger(problems, sum=False):
firstLine = ''
secondLine = ''
thirdLine = ''
fourthLine = ''
if len(problems) > 5:
return "Error: Too many problems."
for exp in problems:
splited = exp.split()
if max(len(splited[0]), len(splited[2])) > 4:
retu... |
0fb2924806558cb46d7758e491d932601491eed4 | maflorez14/Accedo_prueba | /Morce/morce.py | 2,097 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 6 02:06:42 2020
@author: PCMiguel
"""
def get_key(diccionario, val):
for key, value in diccionario.items():
if val == value:
return key
return ''
diccionario = {}
diccionario['a'] = '.-'
diccionario['b'] = '-...'
diccionario['c'] = '-.-.'
d... |
77363c0ce7122910586fe3e8c881c9cfc8c39130 | mplanchard/pydecor | /src/pydecor/decorators/generic.py | 18,873 | 3.859375 | 4 | # -*- coding: UTF-8 -*-
"""
Generic decorators help you to easily create your own decorators with simple
``@before``, ``@after``, and ``@instead`` decorators that call a function
as specified in the execution order of the decorated callable.
Additionally the ``@decorate`` decorator allows you to combine the above thre... |
7fc810b6deb0bf373ea317948a6ae0e483550bbc | felesterio/cs50_2018 | /pset6/mario/mario.py | 403 | 3.90625 | 4 | from cs50 import get_int
while True:
# prompt user
response = get_int("Height of Pyramid (between 0 and 23)?: ")
if response >= 0 and response <= 23:
break
for i in range(1, response + 1):
# left space
print(" " * (response - i), end="")
# left pyramid
print("#" * i, end="")
... |
1767fa67e54e485a8a1e9cf0a4437fa7754d8023 | axu682/SkyMap | /Constellations v4/Cardinal.py | 2,080 | 3.6875 | 4 | import math
class Cardinal(object):
def __init__(self, label, angle):
# initialize coordinates
self.initialX = math.cos(math.radians(angle))
self.initialY = 0
self.initialZ = math.sin(math.radians(angle))
self.x = self.initialX
self.y = self.initialY
... |
2647c5c943fdd610f5e8b87ed211554117f5b2f6 | peninah-odhiambo/andela-fellow | /student_data.py | 623 | 3.796875 | 4 | class student (object):
def __init__(self, name, course, fee_balance):
self.name = name
self.course = course
self.fee_balance = fee_balance
self.admission_year = admission_year
class Accounts(student):
def Accounts (self):
self.name = name
self.course = course
self.balance = balance
... |
9179d31d9eeda1d0767924c0714b62e22875fb34 | MeeSeongIm/trees | /breadth_first_search_02.py | 611 | 4.1875 | 4 | # find the shortest path from 1 to 14.
# graph in list adjacent representation
graph = {
"1": ["2", "3"],
"2": ["4", "5"],
"4": ["8", "9"],
"9": ["12"],
"3": ["6", "7"],
"6": ["10", "11"],
"10": ["13", "14"]
}
def breadth_first_search(graph, start, end):
next_start = [(node, pat... |
940e99026cac3c4f76baa1860faba0528f645971 | ruchi2ch/Python-Programming-Assignment | /week 3/3.6.py | 766 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 18:39:14 2020
@author: HP FOLIO 9480M
"""
'''Problem 3_6:
Write a program (not just a function, but a stand alone program or script) that
reads through a file and writes another file that gives the length of each line
in the first file. If line is the line tha... |
adeba685c03c3f7593c4a7bde14a28b25a21f48a | ruchi2ch/Python-Programming-Assignment | /week 1/1_3.py | 330 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 01:40:12 2020
@author: HP FOLIO 9480M
"""
'''Problem 1_3:
Write a function problem1_3(n) that adds up the numbers 1 through n and
prints out the result.
'''
def problem1_3(n):
my_sum=0
i=1
while i<=n :
my_sum +=i
i+=1
p... |
4a2605b46aad6cc2dd575b675009801c4ce6f83d | ruchi2ch/Python-Programming-Assignment | /week 4/4.1.py | 495 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 11:55:12 2020
@author: HP FOLIO 9480M
"""
'''Problem 4_1:
Write a function that will sort an alphabetic list (or list of words) into
alphabetical order. '''
firstline = ["Happy", "families", "are", "all", "alike;", "every", \
"unhappy", "family"... |
5f1adc845f1167b811d06cf4f6ad5e23f3c2bba3 | LePhilippeDucTai/LeetCode | /Problem002.py | 994 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if(self.next == None) :
return(str(self.val))
else :
return(str(self.val) + ' -> ' + str(self.next))
def toNum(l : ListNode) -> ... |
b5cf6bd963c91195f7e3e3e2358120dc9cf2139f | kodeskolen/viken_v21_april | /dag1/intro_loekker.py | 511 | 4 | 4 | """
Program som kombinerer løkker og betingelser.
"""
faktor1 = 3
faktor2 = 5
for tall in range(1, 101):
if (tall % faktor1) == 0 and (tall % faktor2) == 0:
print(f"Tallet {tall} er delelig på {faktor1} og {faktor2}.")
elif (tall % faktor1) == 0:
print(f"Tallet {tall} er delelig på {faktor... |
59ade07e90850de1c8afc01c10563867f7252118 | GDiaz16/Proyecto-ad-hoc | /Test/Utilities/Node.py | 1,176 | 3.625 | 4 | class Node:
def __init__(self, name = ""):
self.name = name
self.neighbors =[]
self.graphic_position_circle=None
self.graphic_position_title = None
self.visited = False
self.path=[]
self.distance = 0
def get_id(self):
return self.name
def add... |
55641285680227866d06b092549eac75a913e825 | mkrieger1/mutti | /mutti/util.py | 2,059 | 3.71875 | 4 | def distribute_space(available, focus_idx, give, want=None):
"""
Distribute available space to items, priority to focused item.
Result list "give" is modified in-place. It should initially contain
the minimum space required for each item.
The optional list "want" should contain the space that each ... |
15c266d75f2fbb589605acbf59fb45d33605183e | mkrieger1/mutti | /curses-tests/keys.py | 1,269 | 3.859375 | 4 | """
Program for showing the numeric code and the names within the curses and
the curses.ascii modules of pressed keys.
"""
import curses
import curses.ascii
def initkey(win):
win.addstr(2, 2, "key", curses.A_BOLD)
win.addstr(2, 12, "code", curses.A_BOLD)
win.addstr(2, 22, "curses name", curses.A_BOLD)
... |
9115dd1e8d9a3fced108ac0a8bbfcda41e799010 | hippyaki/ehamillrepo2 | /euler01.py | 129 | 3.828125 | 4 | total = 0
for number in range(1, 1001):
if number % 3 == 0 or number % 5 == 0:
total += number
print(total)
|
e6ead3b3e1f80114da04305455544169ba0ff812 | hippyaki/ehamillrepo2 | /heron.py | 165 | 3.6875 | 4 | import math
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
s = (a + b + c) / 2
d = (math.sqrt(s * (s - a) * (s - b) * (s - c)))
print(d)
|
21ef42736c7ef317b189da0dc033ad75615d3523 | LiloD/Algorithms_Described_by_Python | /insertion_sort.py | 1,505 | 4.1875 | 4 | import cProfile
import random
'''
this is the insertion sort Algorithm implemented by Python
Pay attention to the break condition of inner loop
if you've met the condition(the key value find a place to insert)
you must jump out of the loop right then
Quick Sort is Moderately fast for small input-size(<=30)
but weak for... |
87d33b843c37ffacfb06111f70dbebf1832720b3 | MohammedGhafri/data-structures-and-algorithms | /data_structures_and_algorithms/challenge one/array-reverse.py | 124 | 3.640625 | 4 | print("challenge")
arrayone=[1,2,3,4,5,6,7,8,9]
list=[]
for i in range(len(arrayone),-1,-1):
list.append(i)
print(list) |
b0db8ff61efcb222b51eb5ec8c64d2ebc95cfbe9 | ThomasJackDalby/yurt-in-my-pants | /spatial/vector2d.py | 1,225 | 3.671875 | 4 | import math
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2D(self.x - other.x, self.y - other.y)
def __mul__(self, factor):
... |
019eab9436edfc9810597493d7227f041af58a21 | mskroon/DeSDA | /Chapter 2 - Filter/Tools/levenshtein.py | 2,791 | 3.625 | 4 | def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+... |
7ab36e950e07b7c4567202f4494b441e8f59d693 | DadzieAma/MyFiles | /conditional.py | 158 | 3.953125 | 4 | def even_only(lst):
evens = 0
for number in lst:
if number%2 == 0:
evens += number
return evens
print (even_only([1,2,3,54])) |
26e8bf65b41394e6899ba9d63ef7215a6f49751c | DadzieAma/MyFiles | /num.py | 405 | 4.03125 | 4 | def int_to_roman (integer):
parts = []
for letter, value in TABLE:
while value <= integer:
integer -= value
parts.append(letter)
return ''.join(parts)
def rom_to_int(string):
result = 0
for letter, value in table:
while string.startswith(letter):
... |
b0e80018ef46c6bf104c76e860ab6d05a92b2c17 | Aliash92/loopy | /loop_ex2.py | 264 | 3.640625 | 4 | def pattern2(p_new,x=0):
for i in range(1,(int(x)+1)):
print p_new * i
pattern_content = raw_input("Please enter the pattern to be printed ")
num_times = raw_input("Please enter the number of times to be printed ")
pattern2(pattern_content,num_times) |
501eac4146e310e1d9a60ad36d650401b2dfb4cf | Vijay-03/Python_ep | /Arrays/tricky_palindrome2.py | 600 | 3.671875 | 4 | def is_palindrome(num1, num2):
check = num1 + num2
check = str(check)
if check == check[::-1]:
return check
inpnum = int(input())
res1 = []
res2 = []
num1 = 0
num2 = 0
while inpnum != 0:
for i in range(0, inpnum):
if str(i) == str(i)[::-1]:
res1.append(i)
... |
0af6de4a4f8bd71468b83324772f5ce72867d9e9 | Vijay-03/Python_ep | /Arrays/tricky_palindrome.py | 693 | 3.890625 | 4 | def is_palindrome(num1, num2):
check = num1 + num2
check = str(check)
if check == check[::-1]:
return check
inpnum = int(input())
# res1 = []
num1 = 0
num2 = 0
while inpnum != 0:
while True:
temp1 = inpnum - 1
if str(temp1) == str(temp1)[::-1]:
num1... |
eb05fed186593ad09d834d19d4af40fe957eb506 | DenisPower1/NOS | /tests/teste.py | 134 | 3.828125 | 4 | while True:
n=0
n=input("Informe o número a ser multiplicado ")
for x in [1,2,3,4,5,6,7,8,9,10,11,12] :
print(n,"X",x,"=",n*x)
|
2986cd040e430fa37e6829008edc86a4dd943638 | APysnack/CSC311_HW2 | /HW2.py | 1,058 | 3.609375 | 4 | dictionary = {"Abstemious": 'b', "Mississippi": 's', "Gregarious": 'g', "Modification": 'i', "Paramount": 'z'}
sub_string_list = ['stem', 'miss', 'gar', 'fic', 'ram']
i = 0
def location(input_str, in_char):
count = 0
location_list = []
for char in input_str:
count += 1
if char == in_char:... |
bedf86dafe10f5dc96b2ebd355040ab2fdfbd469 | jpacsai/MIT_IntroToCS | /Week5/ProblemSet_5/Problem1.py | 1,832 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 16:04:29 2018
@author: jpacsai
"""
def build_shift_dict(self, shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the a... |
7b6fa11e1fc9431f778285605a3690a8a8b0b86e | ladinu/CS350-project | /geometry/tests/Point_test.py | 880 | 3.546875 | 4 | import unittest
from math import sqrt
from ..Point import Point as P
from ..Line import Line
class PointTest(unittest.TestCase):
def testDefaultPoint(self):
p = P()
self.assertEqual(p.x, 0)
self.assertEqual(p.y, 0)
def testConstruct(self):
p = P(1, 3)
self.assertEqual(p.x, 1)
... |
f23ae456207a27bc252288b20a881634d5975fcf | bkerdsuwan/mycode | /challenge.py | 182 | 3.9375 | 4 | #!/usr/bin/env python3
user_input = input("Please enter a username: ")
user_input2 = input("What day is it? ")
print("Hello, " + user_input + "! Happy " + user_input2, end = '!\n')
|
f2e2caf83abb0e256d217e3e044f2e708e5dd1b2 | mehdilebranchu/TP11 | /EX1.py | 515 | 3.875 | 4 | class Cercle:
def __init__(self,r):
self.__r = r
def getR(self):
return self.__r
def __add__(self, other):
return Cercle(self.__r + other.__r)
def __lt__(self,other):
return self.__r < other.__r
def __gt__(self, other):
return self.__r > other.__r
def __st... |
891b8c3287b3a64754df6beeb868bd96188297d0 | GorTIm/DailyCoding | /2020-02-12-Medium-Yahoo-Done.py | 737 | 3.90625 | 4 | """
This problem was asked by Yahoo.
Write an algorithm that computes the reversal of a directed graph.
For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
"""
"""
def __init__(self,val=None):
if val is not None:
self.val=val
self.next=None
"""
from node import Node
#Metho... |
5902f17e71a3630344ab79f9c22ee2985cb80d3e | GorTIm/DailyCoding | /2020-01-17-Medium-Google-DONE.py | 987 | 4.21875 | 4 | """
This problem was asked by Google.
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, giv... |
fe545b639c06cad6a6249e33f2a6393ea8af9b82 | GuilletThomas/csi2_tp13 | /ex2.py | 2,744 | 3.8125 | 4 | from ex1 import Node
class BinaryTree:
def __init__(self, root):
self.__root = root
def getRoot(self):
return self.__root
def isRoot(self, node):
if node == self.__root:
return True
else :
return False
def size(self, node):
if node is No... |
d73c65b58d28f24a33aca7539c01202cecac03ff | 0equal2/Python_Programming | /codeup/[BFS]4503_바이러스.py | 643 | 3.515625 | 4 | ### 코드업 #4503
### 바이러스
from collections import deque
#1. 컴퓨터의 수
n=int(input())
#2. 직접 연결되어 있는 컴퓨터 쌍의 수
pair=int(input())
#3.
info=dict()
for i in range(pair):
com1,com2=map(int, input().split())
info[com1]=info.setdefault(com1,[])+[com2]
info[com2]=info.setdefault(com2,[])+[com1]
#4. 탐색한 컴퓨터 체크
c... |
1636d67592104f962326d5f8afe412311f126301 | 0equal2/Python_Programming | /algorithm/[정렬]위에서 아래로_역순정렬.py | 312 | 3.71875 | 4 | ### [정렬] 위에서 아래로
### 이것이 취업을 위한 코딩 테스트다 with 파이썬
#1. n 입력
n=int(input())
#2. 숫자 리스트 입력
arr=[]
for i in range(n):
arr.append(int(input()))
print(arr)
#3. 역순 정렬
#arr.sort(reverse=True)
arr=sorted(arr, reverse=True)
print(arr)
|
05750297592e79bbfc203ae6a346d06478f21742 | 0Sandeep12/My_codes | /paranthesis.py | 793 | 3.609375 | 4 | import sys
check_list = []
input_str = "[{()}]"
open_list = "[{("
close_list = "]})"
#print(len(input_str))
for i in range(0,len(input_str)):
ind1 = -1
ind = -2
#print(input_str[i])
if(input_str[0] == ']'):
print("unbalanced")
sys.exit()
check_list.append(input_str[i])
... |
6400a40fc732d6f19d68c24f44ac260e149a3bc6 | josephjoju2/Google-Python-class | /regex/ex1.py | 774 | 3.609375 | 4 | import re, sys, os
year_name_rank=[]
baby_list=[]
def baby_names(filename):
f=open(filename,'rU')
text=f.read()
year_match=re.search(r'Popularity\sin\s(\d\d\d\d)',text)
year=year_match.group(1)
baby_list.append(year)
tuples=re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>',tex... |
8e0f519ea8d1c1fb701a718929fb35e1319c2faf | pemburukoding/belajar_python | /part002.py | 2,128 | 4.40625 | 4 | # Get input from console
# inputString = input("Enter the sentence : ")
# print("The inputted string is :", inputString)
# Implicit Type
# num_int = 123
# num_flo = 1.23
# num_new = num_int + num_flo
# print("Value of num_new : ", num_new)
# print("datatype of num_new : ", type(num_new))
# num_int = 123
# num_str ... |
47091386a883a012b8e6f2b17c118acd9a35a372 | goodok/sympy | /doc/src/modules/galgebra/GA/conformalgeometryGAtest.py | 1,753 | 3.546875 | 4 | print '\nExample: Conformal representations of circles, lines, spheres, and planes'
metric = '1 0 0 0 0,0 1 0 0 0,0 0 1 0 0,0 0 0 0 2,0 0 0 2 0'
e0,e1,e2,n,nbar = MV.setup('e0 e1 e2 n nbar',metric,debug=0)
MV.set_str_format(1)
e = n+nbar
#conformal representation of poi... |
d2c6070cb9228b36b796aab7cb0d52dd4b8e05f9 | goodok/sympy | /sympy/physics/matrices.py | 3,229 | 3.8125 | 4 | """Known matrices related to physics"""
from sympy import Matrix, I
def msigma(i):
"""Returns a Pauli matrix sigma_i. i=1,2,3
See Also
========
http://en.wikipedia.org/wiki/Pauli_matrices
Examples
========
>>> from sympy.physics.matrices import msigma
>>> msigma(1)
[0, 1]
[... |
7a7c58fa86264c65972e892678927c610ce438c1 | goodok/sympy | /sympy/combinatorics/generators.py | 2,851 | 3.90625 | 4 | from sympy.combinatorics.permutations import Permutation
from sympy.utilities.iterables import variations, rotate_left
def symmetric(n):
"""
Generates the symmetric group of order n, Sn.
Examples
========
>>> from sympy.combinatorics.generators import symmetric
>>> list(symmetric(3))
[Per... |
7f7d48c0695869df5977d32aa2c5fd7495c4bf5d | goodok/sympy | /sympy/physics/mechanics/particle.py | 1,687 | 3.65625 | 4 | __all__ = ['Particle']
from sympy import sympify
from sympy.physics.mechanics.point import Point
class Particle(object):
"""A particle.
Particles have a non-zero mass and lack spatial extension; they take up no
space.
Values need to be supplied on initialization, but can be changed later.
Param... |
d41578309737f2b45fe3b47feeb9265d78b58139 | RafaelSetton/InsideCodeChallenges | /Inside Code Challenge/Next Greater Number.py | 804 | 3.515625 | 4 |
def next_greater(num):
list_num = [int(n) for n in str(num)]
i = len(str(num)) - 1
while True:
if i == 0:
return num
if list_num[i] > list_num[i-1]:
changes = list_num[i:]
i -= 1
buffer = list_num[i]
least = max(ch... |
56c6d32e6c37f2764e63b947e381b23730169a10 | BskyRui/Python | /16_reduce.py | 395 | 3.640625 | 4 | from functools import reduce
list_x = [1, 2, 3, 4, 5, 6]
# 连续计算, 连续调用, 第1次调用的时候会取第0和第1个元素作为lambda表示的参数, 第2次调用时x为上次lambda返回的结果(3), y为3(第2个元素)
# 每次遍历lambda的计算结果作为x的参数再次参与计算
# initial设置第一次的初始值
r = reduce(lambda x,y:x+y, list_x, 10)
print(r) |
c1efc405320b77fc56039461c3d4417ceb899322 | baluneboy/pims | /recipes/recipes_generators.py | 2,255 | 3.625 | 4 | #!/usr/bin/env python
import random
from collections import deque
# A generator to get datetimes (every 5 minutes start on 31-Dec-2012)
def nextFiveMinutes():
import datetime
dtm = datetime.datetime(2012, 12, 31, 22, 0, 0) - datetime.timedelta(minutes=5)
while 1:
dtm += datetime.timedelt... |
04d3e5a237190fec158a66a355006fc5652fbb68 | baluneboy/pims | /recipes/recipes_trayicon.py | 1,290 | 3.546875 | 4 | #! /usr/bin/python
# small script to put a logout icon in system tray
# by Tunafish, july 2011
#
# parts taken from:
# http://www.dangibbs.co.uk/journal/advanced-functionality-of-eggtrayicon
import gtk, commands,os
try:
import egg.trayicon
except:
print "You need to install the python-eggtrayicon package"
cl... |
9928903dba69361080413e71bbe58fc6a913aee0 | baluneboy/pims | /signal/rounding.py | 440 | 3.90625 | 4 | #!/usr/bin/env python
import math
def is_power_of_two(n):
"""Return True if n is a power of two."""
if n <= 0:
return False
else:
return n & (n - 1) == 0
def roundup100(x):
"""return integer value for x rounded up to next hundred"""
return int(math.ceil(x / 100.0)) * 100
def roundup... |
41f9a433abc4789534822a8f314a1cea3839eb71 | baluneboy/pims | /sandbox/why_no_switch_case.py | 1,268 | 3.921875 | 4 | #!/usr/bin/env python
################################################################################
"""For cases where you need to choose from a very large number of possibilities,
you can create a dictionary mapping case values to functions to call. For
example:"""
def function_1():
return "one"
def function... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.