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 |
|---|---|---|---|---|---|---|
d834fb88ac0840283cf0c91db83b0f0e414831d3 | KitsuneNoctus/makeschool | /site/public/courses/CS-1.3/Code/Archive/all-starter-code/binarytree_test.py | 10,556 | 4.03125 | 4 | #!python
from binarytree import BinarySearchTree, BinaryTreeNode
import unittest
class BinaryTreeNodeTest(unittest.TestCase):
def test_init(self):
data = 123
node = BinaryTreeNode(data)
assert node.data is data
assert node.left is None
assert node.right is No... |
a19f68d4eb321975ff2ade6286f331747220dbfe | KitsuneNoctus/makeschool | /site/public/courses/CS-1.3/Code/Archive/all-starter-code/strings_test.py | 7,185 | 4.0625 | 4 | #!python
from strings import contains, find_index, find_all_indexes
import unittest
class StringsTest(unittest.TestCase):
def test_contains_with_matching_patterns(self):
# Positive test cases (examples) with matching patterns
assert contains('abc', '') is True # all strings contain em... |
e8e1f9d468cd828cebb5bb80ddb123039871fc66 | KitsuneNoctus/makeschool | /site/public/courses/CS-2.2/Challenges/Solutions/challenge_1/tests/test_graph_file_reader.py | 2,860 | 3.59375 | 4 | import unittest
from src.graph_file_reader import read_from_file
class FileInputTest(unittest.TestCase):
"""Test the graph output of reading from a file."""
def test_input_type_incorrect(self):
self.assertRaisesRegex(
Exception, "File must start with", read_from_file,
... |
f3c543fb60d13114cd3e3b1b80176cae8c1f4d6b | KitsuneNoctus/makeschool | /site/public/courses/CS-2.2/Challenges/Solutions/challenge_1/src/vertex.py | 1,155 | 4.25 | 4 | class Vertex(object):
""" Vertex Class
A helper class for the Graph class that defines vertices and vertex neighbors.
"""
def __init__(self, vertex_id):
"""Initialize a vertex and its neighbors.
neighbors: set of vertices adjacent to self,
stored in a dictionary with k... |
54433cda9ab97c3b60023dd046cc7aafc1f06908 | KitsuneNoctus/makeschool | /site/public/courses/CS-2.1/Code/prefixtreenode.py | 2,797 | 4.40625 | 4 | #!python3
class PrefixTreeNode:
"""PrefixTreeNode: A node for use in a prefix tree that stores a single
character from a string and a structure of children nodes below it, which
associates the next character in a string to the next node along its path from
the tree's root node to a terminal nod... |
40273f97ff9c134b84fdce614d901aa7e087e852 | mattester/moocPython | /步骤一:Python基础知识/day3/while循环.py | 97 | 3.703125 | 4 | #输出5个hello word
#定义初始值
i = 0
while i < 5 :
print("hello world")
i = i + 1 |
484d28af9a47fbb40976d28da8fe83b6f7391613 | mattester/moocPython | /步骤二:python函数与模块/day20/文件的读取.py | 1,120 | 4.125 | 4 | def read_file():
"""读取文件"""
file_name = 'test2.txt' #保存文件的名字
#使用绝对路径
file_path = 'D:\\pythontest\\python基础知识\\步骤二\\day20\\test2.txt'
#使用普通方式打开文件
f = open(file_name,encoding="utf-8")
'''
读取文件内容()所有
rest = f.read()
关闭
print(rest)
读取指定文件内容
rest = f.read(8)
print(res... |
590e7c82d91190944461d70e68472d422209c158 | mattester/moocPython | /步骤一:Python基础知识/day8/字典在项目中的应用2.py | 1,356 | 3.515625 | 4 | source = "7782,CLARK,MANAGER,SALES,5000$7934,MILLER,SALESMAN,SALES,3000$7369,SMITH,ANALYST,RESEARCH,2000"
#定义一个所有员工的字典allyg{编号:员工属性}
#定义单个员工的字典oneyg{工号:no,姓名:name,岗位:job,部门:department,工资:salary}
allyg = {}
#分割字符串
yg_list = source.split("$")
print(yg_list)
#把总员工列表里面的单个员工给取出来
#1:找到这个列表的索引值,通过索引值给列表取值然后用split进行分割
for i in... |
2aa034cfcfb507fa74832ba79b6f45b3f7d3c209 | mattester/moocPython | /步骤一:Python基础知识/day6/创建列表.py | 215 | 4.0625 | 4 | #创建一个列表
#列表的特点:顺序排列,有正序和倒序两种索引,可以存储任意类型数据,允许重复
list = ["a","b","c",1,2,3]
print(list)
#输出一个空列表
list =[]
print(list) |
ecbef819f8582d79e7f4c262518358ad33350354 | SYouJ/Chapter8-Report | /8-7.py | 863 | 3.96875 | 4 | ek_dict = dict()
while True:
stc_e = input("영어 단어 : ")
if len(stc_e) == 0:
print(ek_dict)
break
if len(stc_e) > 0 :
if stc_e in ek_dict and ek_dict != dict():
print(stc_e,":",ek_dict[stc_e])
continue
if ek_dict == d... |
16633e160ffbf20b1dbb1ad9d0d42ac0e6839ee1 | gdfurr98/project-euler-programs | /even_fibonacci_numbers.py | 344 | 3.8125 | 4 | evenList = []
evenSum = 0
def fibonacci(a, b):
print('a', a)
print('b', b)
if b % 2 == 0:
evenList.append(b)
if a >= 4000000:
return
else:
newA = b
newB = a + b
fibonacci(newA, newB)
fibonacci(1, 2)
for x in evenList:
evenSum += x
print(eve... |
dd70d396d713bfdcb8940cea98a9a308b4207503 | gdfurr98/project-euler-programs | /lattice_path.py | 294 | 3.984375 | 4 | import math
gridLen = input('What is the length of our grid?')
gridLen = int(gridLen)+1
print("The factorial of the length is:", math.factorial(int(gridLen)))
numPathDenom = math.factorial((2*(gridLen-1)))
numPathNumerat = math.factorial(gridLen-1)**2
print(numPathDenom/numPathNumerat)
|
81aeb584c905d86acf4a83ac84e40c925143b233 | MayankMaheshwar/DS-and-Algo-solving | /leetcode/lastwordlen.py | 512 | 3.875 | 4 | """
Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
A word is a maximal substring consisting of non-space characters only.
"""
class Solution:
def lengthOfLastWord(self, s: str) -> int:
l = 0
... |
817c7ab8fe572f5e832fb8a7f36fd2173212cd1b | MayankMaheshwar/DS-and-Algo-solving | /hypersonic.py | 464 | 4.09375 | 4 | """
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps.
In how many distinct ways can you climb to the top?
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Sol... |
6778ecf68c18849b683515ddc0dbd4c8f38af35c | MayankMaheshwar/DS-and-Algo-solving | /leetcode/reversefibo.py | 175 | 3.890625 | 4 | n = 21
a = 0
b = 1
def reverse(a, b, n):
if b == n:
print(b, end=" ")
return
reverse(b, a+b, n)
print(a, end=" ")
return
reverse(a, b, n)
|
81868b4439862b16518992db5c9295a32604f62c | MayankMaheshwar/DS-and-Algo-solving | /117-populating-next-right-pointers-in-each-node-ii/117-populating-next-right-pointers-in-each-node-ii.py | 898 | 3.84375 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
i... |
6e332a122b6c6a83a49e2bdcc66aaba3bfb8a191 | MayankMaheshwar/DS-and-Algo-solving | /hypersonic2.py | 585 | 4.125 | 4 | """
1) Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not a... |
8fd786796783329b65a759efbdb10bd67848713d | MayankMaheshwar/DS-and-Algo-solving | /1721-swapping-nodes-in-a-linked-list/1721-swapping-nodes-in-a-linked-list.py | 544 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
first = last = head
for i in range(1, k):
fi... |
10a0e82d2183983ea9d56a2eface4dfa728586a4 | MayankMaheshwar/DS-and-Algo-solving | /sql.py/roottoleafsum.py | 724 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
self.arr = []
cur = ''
de... |
eae8deb0d26186f795d5a7dca79b29a7ec4ae452 | MayankMaheshwar/DS-and-Algo-solving | /linkedlist1.py | 680 | 3.640625 | 4 | class node:
def __init__(self,data):
self.data=data
self.next=None
class llk:
def __init__(self):
self.head=None
def push(self,data):
new=node(data)
new.next=self.head
self.head=new
def r(self,val):
cur=self.head
temp=cur.next
... |
3582a8942a1ce9147c6b9742adf0513d506aed05 | MayankMaheshwar/DS-and-Algo-solving | /sw3.py | 417 | 3.671875 | 4 | def x(t):
z = t.swapcase()
t = list(t)
z = list(z)
for c in t:
if c not in z:
return False
return True
class Solution:
def longestNiceSubstring(self, s: str) -> str:
b = ""
for i in range(len(s)):
for j in range(i+1, len(s)):
a = ... |
5d5eec8ddc8983bcc441f23602237bcddeffb43f | MayankMaheshwar/DS-and-Algo-solving | /assignment/assign1.py | 632 | 4.03125 | 4 | """
1. Given a string of size n ( may contain duplicate characters), generate sub sequence of
size k (should contain only unique characters) and print them in lexicographic order.
Example:
1. str1=“kabccr” size(n) = 6, k=3
Solution: subsequences: abc, abk, abr, acb, ack,
acr,akb,akc,akr,arb,arc,arb,arc,ark,bac,bak,bar,... |
5f092bc75114056f7f22b7cc97625b4c01cd3807 | MayankMaheshwar/DS-and-Algo-solving | /first.py | 293 | 3.625 | 4 | s1="Hello"
s2="Hi"
s3="Good Morning"
n=0
if len(s1)>len(s2):
n=len(s1)
else:
n=len(s2)
for i in range(n):
if i in ['a','e','i','o',u] and i in s1:
s1.replace(s1[i],"/"")
elif i not in ['a','e','i','o',u] and i in s2:
s2.replace(s2[i],"/"")
print(s1)
print(s2)
|
7042d0cd19d1b081fbdc5ddbd80ea5869a7aadec | MayankMaheshwar/DS-and-Algo-solving | /leetcode/inverttree.py | 569 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
stack=[root]
while sta... |
d7f0adab1c0c087008d9d4c43727dddf23303083 | MayankMaheshwar/DS-and-Algo-solving | /2000-reverse-prefix-of-word/2000-reverse-prefix-of-word.py | 189 | 3.546875 | 4 | class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
idx=word.find(ch)
if idx:
return word[:idx+1][::-1]+ word[idx+1:]
return word |
c406cd36ccd9013812c4219f11608c9c0004ca1e | sunyutong/LogisticRegression | /LogisticRegression.py | 2,774 | 3.953125 | 4 | '''
This is a class for implementing logistic regression algorithm.
In this algorithm, it includes gradient descent function with
momentum parameter to reduce the number of iterations for optimizing
the algorithm.
'''
import numpy as np
class LogisticRegression:
# Define a constructor with 3 parameters
def __init... |
7517be2287bc89cf841a9c991eb1f367c62606e3 | BoberSA/OrbiPy | /orbipyd/correction.py | 4,511 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 14 22:56:15 2018
@author: deniszagorodnev
"""
import math
import numpy as np
class base_correction_tool():
""" A class for orbit correction mechanisms """
def __init__(self, func=None):
"""
func is correction algorithm
... |
a1fcaf556a09f43581122e608c1995ec37bbc260 | nrkavya/python-training | /1.py | 308 | 4.375 | 4 | #Create a program to compare three numbers and find the bigger numbers
no1 = int(input("Enter no1"))
no2= int(input ("Enter no2"))
no3 = int(input("enter no3"))
if(no1>no2 and no1>no3):
print("no1 is greatest")
elif(no2>no1 and no2>no3):
print("no2 is greatest")
else:
print("no3 is greatest")
|
280950a2d9068dc409b8da69b7f8b7b7088f26d0 | rewardof/expenses_app_api | /index.py | 552 | 3.765625 | 4 | #raqam = int(input("Istalgan raqam kiritng: \n >>>>> "))
#print( raqam, "ning kvadrati", raqam**2, " ga teng ")
#print(raqam,"ning kubi", raqam**3, " ga teng")
#y = int(input("Yoshingiz necida : \n----"))
#yosh = 2021-y
#print("sizning tug'ilgan yilingiz ", yosh, " da ")
#x = float(input("Birinchi raqam kiriting :"))... |
0547e25b57f678d1e298012d7cd397a048ff7631 | kcelestine/python-challenge | /ch4.py | 298 | 3.703125 | 4 | #!/usr/bin/python
import re
f = open('4_help', 'r')
lines = f.readlines()
count = 0
def check(text):
pattern="[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+"
if re.search(pattern, text):
return True
else:
return False
for line in lines:
if(check(line)):
count += 1
print line
print count
|
63dc623e20d6ef833d213d949e7a96f34032faaf | Zli123123/Waterloo-CCC | /waterloo1.py | 136 | 3.640625 | 4 |
b = int(input(""))
p = 5 * b - 400
print(p)
if p == 100:
print(0)
if p > 100:
print(-1)
if p < 100:
print(1)
|
054143378a32fe3bcfa96cf7c3808875b768628e | nathan-cutrin/praticando | /curso_em_video/aula 17 - listas - ex 80.py | 50 | 3.5 | 4 | lista = [3, 2, 1]
print(lista.sort(reverse=True)) |
525a278e26a367cb929fe12ab5f958fc9d9d8bc0 | nathan-cutrin/praticando | /curso_em_video/aula 17 - listas - ex 78.py | 729 | 3.90625 | 4 | # Ex 78: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
# No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
lista = []
posicao_maior = []
posicao_menor = []
for p in range(0, 5):
val = int(input(f'Digite um valor na posição {p}: '))
li... |
03d116f0b8586cf315384db956a11de8fa1b927b | Testsubject/Python_Projects | /Dice.py | 466 | 3.9375 | 4 | import random
def numbers():
print('This a random dice roller for any number.')
rolls = int(input('Enter the number of rolls: '))
minimum = int(input('Enter a min number: '))
maximum = int(input('Enter a max number: '))
roll_l = []
for _ in range(rolls):
roll = random.randint... |
47a1d103767c49f4225c870ee31393e1bd7bfea0 | rgrtorres/cursos_python | /Introdução à programação com Python/Verificando_Impar_Par.py | 244 | 4.09375 | 4 | while True:
numero = int(input("Insira um número:"))
for x in range(0, numero+1):
if x % 2 == 0:
print("{} é par".format(x))
else:
print("{} é impar".format(x))
print("Loop finzalizado!") |
de7e007774f92032c5045092496265f62532d500 | collins-adhola/AutomatedTests-1 | /string_compare.py | 731 | 3.875 | 4 | '''
Given two sets of string data of equal length,
calculate the positional difference between them
eg:
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
differences = 7
'''
def diff_count(string_a, string_b):
validate(string_a, string_b)
# print(list(zip(string_a, string_b)))
# [x,y] is returned ,then length is got. Simila... |
38cf8fff7a1e9448a1587f314ae534e0cc1378ae | DavAnaton/google-foobar | /level_2/lovely_lucky_lambs/solution.py | 1,413 | 3.921875 | 4 | import math
def answer(total_lambs):
if(total_lambs <= 2):
return 0
""" Generous case, with less henchmen
The payroll will look like the following [2^0, 2^1, ..., 2^biggest_power, remaining]
The sum of this array minus the last term is 2^(biggest_power + 1) - 1"""
biggest_power = int(math.floor(math.log(... |
7c344c736ab326a73c4327c5d8cfd51a2e18338b | neharani289/leet-code-problems | /gas-station/gas-station.py | 709 | 3.578125 | 4 | class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
# base case
if sum(gas) - sum(cost) < 0:
return -1
gas_tank = 0 # gas available in car till now
... |
24378cb90f29620412edfc076f0f8f9021edf613 | ycc12345/Data_Structure_and_Algortithm_Coursera-UCSD | /string/non_shared_substring.py | 2,897 | 3.578125 | 4 | # python3
import sys
class Node:
def __init__(self):
self.label = dict()
self.parent = -1
self.position = -1
def find_branch_position(text, suffix_text):
cursor = 0
length = len(text)
while text[cursor] == suffix_text[cursor]:
cursor += 1
if cursor == length:
break
return cursor
d... |
72843992840f9856524f63617bbba91b9e22a6c3 | Asdil/train_model | /Base/zip_file.py | 444 | 3.5625 | 4 | import os
import zipfile
pwd = os.getcwd()
father_path = os.path.abspath(os.path.dirname(pwd)+os.path.sep+".")
def zip_wrong_file():
startdir = pwd + '/wrong_answer'
z = zipfile.ZipFile(pwd+'/wrong_answer.zip', 'w', zipfile.ZIP_DEFLATED)
print startdir
for dirpath, dirnames, filenames in os.walk(startdi... |
2c45227559cdb611c32da60bc546839d45b19052 | Ry-Kurihara/AtCoder | /abc173wrap/abc173/a/solve.py | 519 | 3.546875 | 4 | N = input()
N_int = int(N)
# 頭悪いやり方
if N_int <= 1000:
print(1000 - N_int)
elif N_int <= 2000:
print(2000 - N_int)
elif N_int <= 3000:
print(3000 - N_int)
elif N_int <= 4000:
print(4000 - N_int)
elif N_int <= 5000:
print(5000 - N_int)
elif N_int <= 6000:
print(6000 - N_int)
elif N_int <= 7000:
... |
8f8b92d7c3704370a15b12cc450759446dc8dd87 | stefifm/TP4 | /principal_paises.py | 3,954 | 4 | 4 | """
Aquí está el programa principal del trabajo práctico
"""
import funciones_paises
def principal():
vec_paises = []
fd = "paises.csv"
carga_matriz = False
opcion = 0
while opcion != 8:
print("Menú de opciones")
print("1) Muestra del listado completo de países")... |
3130b97d8c92a8114dc639ab479a2677335bb5e3 | BojanKomazec/Python | /WebScraper/main.py | 580 | 3.75 | 4 | '''
Web page scraping example.
Original code: http://docs.python-guide.org/en/latest/scenarios/scrape/
'''
from lxml import html
import requests
def example1():
response = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
TREE = html.fromstring(response.content)
#This will create a list of buyer... |
a62481b9c1225c12781ccdc4bac07064336d7615 | muicheka/Vending_Machine | /Vending_Machine.py | 1,552 | 3.546875 | 4 | from enum import IntEnum
class Coin(IntEnum):
DOLLAR = 100
QUARTER = 25
DIME = 10
NICKEL = 5
class Item(IntEnum):
A = 100
B = 125
C = 150
D = 145
class VendingMachine:
def __init__(self):
self.inserted_coins = []
self.change_coins = []
def get_current_value... |
d7eed40f49081cb4a630609cc81fef869a83f022 | riceh3/210CT-CW | /matrix_computation.py | 2,471 | 4.0625 | 4 | import sys
# Empty matrix to store answer
answer = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]
# Matricies to store resuts of calculations
calc_first_half = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]
calc_second_half = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]
def matrix_addition(calc_first_hal... |
60308a1f2aa94fa65c89ca7461b1ec664a7beba5 | riceh3/210CT-CW | /binary_search.py | 1,358 | 4.15625 | 4 |
def binary_search(entry): # Divide and Conquer
""" Search through input for values within the given high & low parameters """
length = len(entry)
middle = length/2 # Find the middle value in the list
middle = int(middle)
if entry[middle] == low or entry[mid... |
9be396d238b1f6a519a5a68261ea75e5c204fa15 | hamologist/Code-Eval | /easy/chardonnay_or_cabernet/chardonnay_or_cabernet.py | 376 | 3.5625 | 4 | import sys
f = open(sys.argv[1])
lines = f.read().rstrip().splitlines()
f.close()
for line in lines:
wines, key = line.split(' | ')
key = set(key)
wines = wines.split(' ')
answer = []
for wine in wines:
if (key.issubset(set(wine))):
answer.append(wine)
if answer:
p... |
695d0069a70a4081b4e62660074aecc4f18510eb | hamologist/Code-Eval | /easy/mixed_content/mixed_content.py | 442 | 3.5 | 4 | import sys
f = open(sys.argv[1])
lines = f.read().strip().splitlines()
for line in lines:
words = []
nums = []
line = line.split(',')
for word in line:
if word.isdigit():
nums.append(word)
else:
words.append(word)
if (words and nums):
print(','.join(w... |
63d574920a2621a6b75f3ddf5a1d405a66fb937c | hamologist/Code-Eval | /moderate/pangrams/pangram.py | 391 | 3.625 | 4 | import sys
import string
f = open(sys.argv[1])
lines = f.read().split('\n')[:-1]
for line in lines:
test = set()
line = line.lower()
for char in line:
test |= {char}
isNull = True
for char in string.ascii_lowercase:
if char not in test:
print(char, end='')
i... |
7076a0f0ae5cbcca2e5dec42657f367e4ac8305f | saturn1101/atom-assignments | /streamlit/uber_pickups.py | 1,509 | 3.546875 | 4 |
# Refrences: https://docs.streamlit.io/en/stable/tutorial/create_a_data_explorer_app.html
import streamlit as st
import pandas as pd
import numpy as np
import datetime as dt
DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/streamlit-demo-data/uber-raw-data-sep14.csv.gz')
# Fetch Data
@st.ca... |
5a71190ae298229e82bce525537caf4b7b65b1bc | wympiel/turtles | /dots.py | 296 | 3.609375 | 4 | import turtle
t = turtle.Turtle()
dot_distance = 25
width = 5
height = 7
t.penup()
for y in range(height):
for i in range(width):
t.dot()
t.forward(dot_distance)
t.backward(dot_distance * width)
t.right(90)
t.forward(dot_distance)
t.left(90)
turtle.done() |
aea0a34f8526f109b7006422c340f9fddda66181 | HKavalos/ToGather | /build/lib/bin/group.py | 849 | 3.515625 | 4 | class Group:
"the group class contains a list of users, a list of events and a calendar"
def __init__(self, name, calendar="", users=[], events=[]):
self._name = name
self._calendar = calendar
self._users = users
self._events = events
@property
def calendar(self):
... |
ca3d91fd8720caa4ce4b19e99f1a2c91f6c55a4d | codebox/wordvis | /wordvis.py | 8,279 | 3.515625 | 4 | from __future__ import division
import math
import colorsys
import sys
import codecs
'''
Word Visualiser
---------------
This utility reads a text file containing word frequency data, and generates a Sunburst Chart illustrating the frequency
with which letters appear at each position within the words.
Each line of t... |
5c161966152630db3a9c39ce289f193f7ea2be42 | asmeurer/iterm2-tools | /iterm2_tools/images.py | 3,596 | 3.78125 | 4 | """
Functions for displaying images inline in iTerm2.
See https://iterm2.com/images.html.
"""
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
IMAGE_CODE = '\033]1337;File=name={name};inline={inline};size={size};width={width};height={height};preserveAspectRatio={pre... |
d187cee0c1bcf1ef7123a2f88ccbd831471a9c28 | tfchen2400/studyPython | /filterOdd.py | 132 | 4.0625 | 4 | #!/usr/bin/env python3
# coding=utf-8
def is_odd(x):
return x % 2 == 1
print(list(filter(is_odd, [1, 3, 5, 7, 9, 8])))
|
e3d71547f57a4bb1e85505784ca028a888d432fa | tfchen2400/studyPython | /sortName.py | 277 | 3.703125 | 4 | #!/usr/bin/env python3
# coding=utf-8
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
def bt_score(t):
return t[1]
L2 = sorted(L, key=by_name)
print(L2)
L3 = sorted(L, key=bt_score, reverse=True)
print(L3)
|
e017b2dab1565a9a6f04d0e105ef57d32b110639 | jagio0129/algorithm | /divisor.py | 122 | 3.5 | 4 | import random
i = random.randint(1, 1000)
print("Number: %s" % i)
for v in range(1, i, 1):
if i % v == 0:
print(v) |
05461970b807be5dc7bd1a2db00e4d63adb24773 | slkc0724/Password_2 | /ans3.py | 178 | 3.9375 | 4 | password = 'a123456'
x = 3
while x > 0:
x = x - 1
pwd = input('Password: ')
if pwd == password:
print('correct')
break
else:
print('wrong, u have', x, 'time to try') |
8c9febeeb51e8c53800dff0b0c97a1b548a3292d | KOOKDONGHUN/programmers | /level1/level1-10/level1-10.py | 1,479 | 3.90625 | 4 | def calc_position(n):
a = n // 3
b = (n % 3) - 1
if (b < 0):
b = 2
a -= 1
return a,b
def calc_distance(i1,j1, i2, j2):
return abs(i1 - i2) + abs(j1 - j2)
def solution(numbers, hand):
answer = ""
l = 0
if (hand == "right"):
hand = 'R'
elif (hand == "lef... |
3cf50b64a0e0a2a74ae58b353cce52d4977a3bd3 | KOOKDONGHUN/programmers | /level2/level2-5/level2-5.py | 763 | 3.734375 | 4 | from itertools import product
def solution(word):
answer = 0
answer_ = []
for i in product("AEIOU", "AEIOU", "AEIOU", "AEIOU", "AEIOU"):
answer_.append(''.join(list(i)))
for i in product("AEIOU", "AEIOU", "AEIOU", "AEIOU"):
answer_.append(''.join(list(i)))
for i in product("AEI... |
bcec4a9d4a20f21686a6124ec4790c51c5da7334 | bienseo/CNA_intern | /bien_datascience/visualizing_data.py | 1,033 | 4.03125 | 4 | '''
CNA Intern
Study name: Chap03 Visualizing data
Created by Eunseo Cho on 03/05/2017.
'''
import matplotlib.pyplot as plt
def make_line():
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# create line
plt.plot(years, gdp, color='gree... |
5307615d59aa8cbfb3ba9b69d63516c135d15fe6 | bienseo/CNA_intern | /bien_deeplearning/actFtn.py | 696 | 3.546875 | 4 | '''
CNA Intern
Study name: Activation Function
Created by Eunseo Cho on 02/05/2017.
'''
import numpy as np
import matplotlib.pyplot as plt
def step_function(x):
y = x > 0
# print(y)
# print(y.astype(np.int))
return y.astype(np.int)
def sigmoid(x):
h = 1 / (1 + np.exp(-x))
return h
def sigmoid_gr... |
352df6ef19d9ae8f85443aaf9a811a585e57bf37 | lazywhitecat/Pratical | /Prac_03/temperatures.py | 1,130 | 4.21875 | 4 | def main():
#temperature conversion system
determine_temperature_type = input('Enter your temperature type in celsius(c) or fahrenheit(f):')
while True:
if determine_temperature_type == 'c':
celsius_value = float(input('Enter your celsius number:'))
fahrenheit = convert_celsi... |
8575ec8d858af8acd49960a6a65d8c2c8aea8489 | gargpratyush/KOSS_submission | /task2.py | 1,008 | 3.546875 | 4 | import requests
import os
import urllib.parse
import time
# iterate over each url after converting the integer i to string and attaching it to the url. The JSON files downloaded contains dictionaries, so to store them, we have to convert them to a string after converting the dict keys to list.
def getList(dict):
... |
9b2dc2edb737fda6c72adfd3d39a3442296b2aca | prabhat997/demo | /hackerrank/practise here.py | 489 | 3.875 | 4 | import random
n=(random.randint(1,10))
guess_count = 0
guess_limit=4
print('you have 5 chances:')
while (guess_limit<=4):
guess_number=int(input('guess the number:\n'))
guess_limit -= 1
if guess_number > n:
print('insert lower number')
elif guess_number < n:
print('inser... |
38cf80b1361501745a8d6c6231d8761ba9ccf9fb | cosmicBboy/ml-research | /gan_gaussian/gan_gaussian.py | 10,651 | 3.71875 | 4 | #!/usr/bin/env python
"""A Basic GAN Implementation.
@author Niels Bantilan <niels.bantilan@gmail.com>
adapted from: https://github.com/devnag/pytorch-generative-adversarial-networks
GANs consist of the following components:
- R: real data distribution.
- G: the generator trying to create realistic data samples.
-... |
39b0c2b74429ed38a2eb708ab805fc0f37fb5e8d | mariafilippa/glia | /multiples.py | 390 | 3.625 | 4 | def get_multiples(base, limit):
curr = base
multiples = []
while curr < limit:
multiples.append(curr)
curr += base
return set(multiples)
def get_union_sum(set1, set2):
return sum(set1 | set2)
if __name__ == "__main__":
multiples_3 = get_multiples(3, 1000)
multiples_5 = get_... |
e2ffb07ae1dfd50fa4b50200263f458515bf0044 | zhongqin0820/coding-playground | /python/tutorials/python3DAML/chap4-2.py | 317 | 3.921875 | 4 | def guess(x, y):
if x < y:
print('bigger')
elif x > y:
print('smaller')
else:
print('correct')
return True
return False
def main():
y = input()#target
x = input()#guess
while guess(x, y) == False:
x = input()
if __name__ == '__main__':
main()
|
3ed697705a3c97ab4892b02fe0d9a40b0c4bf6e1 | zhongqin0820/coding-playground | /python/basics/03_get_attributes.py | 1,127 | 3.828125 | 4 | # define a student class
class student:
def __init__(self, age, name):
self.age = age
self.name = name
return
def get_age(self):
"""
:rtype: int
"""
return self.age
def get_name(self):
"""
:rtype: string
"""
return self... |
651edd61a27004ff9b843b6915ef0299c8f4bafe | zhongqin0820/coding-playground | /python/basics/04_lists.py | 699 | 3.65625 | 4 | a = [1, -1, 3, 2, 5, 4]
# append
a.append(6)
print('a:', a)
# sorted
b = sorted(a)
print('b:', b)
print('a:', a)
# a.sort()
# print('a:', a)
# slice
# skip step=2
c = a[::2]
print(c)
# sawp a[i], a[i+1]
c = a[::-1]
print(c)
# iterate an array
s = ', '.join([str(v) for v in a])
print('s:', s)
# list comprehensions pro
l... |
e2bd618cbeb720864a4d9e9a3f1db295f2ab9453 | ishvar99/tic-tac-toe | /TicTacToe.py | 3,071 | 3.890625 | 4 | from random import randint
test_board = [' ']*10
test_board[0]='#'
def display_board(board):
print('\t\t\t| |')
print(f'\t\t {board[1]}\t| {board[2]} | {board[3]}')
print('\t\t\t| |')
print('\t\t -----------')
print('\t\t\t| |')
print(f'\t\t {board[... |
4f5fc1077ec2136c833a7f73f6892e421b08cef3 | pildurr/sequence | /sequence.py | 608 | 3.796875 | 4 | n = int(input("Enter the length of the sequence: ")) # Do not change this line
number_1 = 1
number_2 = 2
number_3 = 3
print(number_1)
print(number_2)
print(number_3)
for x in range(0, n):
number_4 = number_1 + number_2 + number_3
print(number_4)
number_1 = number_2
number_2 = number_3
number_3 = nu... |
e66ed4d21c455f61a06ccc057ce4449e8af83305 | bodonoghuevt/fake-news | /linear_classifier.py | 4,269 | 4.125 | 4 | """
Functions for training and predicting with linear classifiers
"""
import numpy as np
import pylab as plt
from scipy.optimize import minimize, check_grad
def linear_predict(data, model):
"""
Predicts a multi-class output based on scores from linear combinations of features.
:param data: size (d, n) nd... |
e5a97348f3ca2f29272e575c2bdd1aadfd1c377c | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/Lesson 29. Coroutines/demos/game2d/app.py | 15,768 | 3.671875 | 4 | """
The primary class for 2D game support.
To implement a game, you subclass this class and override the three methods ``start``,
``update`` and ``draw``.
Author: Walker M. White (wmw2)
Date: August 1, 2017 (Python 3 version)
"""
# Basic Kivy Modules
import kivy
import kivy.app
# Lower-level kivy modules to supp... |
009616a57600fb06b2704d73090a3d8221de148d | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 20. Classes/demos/testperson.py | 2,039 | 3.984375 | 4 | """
A unit test for the Person class.
Author: Walker M. White (wmw2)
Date: October 10, 2018
"""
import introcs
import person
def build_test_tree():
"""
Returns the youngest generation Person in a complete family tree
The purpose of this function is to create a genealogical tree for testing
"""
... |
c32a8788b24dbb702f17e00c688fbc16ca75a52a | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 17. Recursion/demos/test_exp.py | 1,588 | 3.53125 | 4 | """
A test script for the exponentiation functions.
This test script illustrates the performance difference between the two functions.
Author: Walker M. White (wmw2)
Date: October 10, 2018
"""
import introcs
import com
import exp
def test_exp_slow():
"""
Tests the slow version of exponentiation
"""
... |
672359e13ab2da7bf5a2c56353e37d3df9104940 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 20. Classes/demos/worker.py | 1,383 | 4.0625 | 4 | """
A module with a simple Worker class.
Class demonstrates attributes and an initializer.
Author: Walker M. White (wmw2), Steve Marschner (srm2)
Date: October 12, 2019
"""
class Worker(object):
"""
Class to represent a worker at a company
Not all workers have an immediate boss.
Attribute lname:... |
e5e89f38ed894ac7a4da1132ecd42bac8572f3d1 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 10. Algorithm Design/demos/pseudo1.py | 853 | 3.59375 | 4 | """
A module with an unimplemented function
This module has a function stub to get us started.
Author: Walker M. White
Date: February 14, 2019
"""
import introcs
def last_name_first(n):
"""
Returns: copy of n but in the form 'last-name, first-name'
We assume that n is just two names (first and last).... |
cf981cdb74758f85e6e9801b94a2394911268a0a | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 21. Object-Oriented Design/demos/point.py | 1,932 | 4.21875 | 4 | """
A module with a simple Point3 class.
This module has a simpler version of the Point class. The primary purpose
of this module is to show off the built-in methods __str__ and __repr___
Author: Walker White (wmw2)
Date: October 20, 2019
"""
import math
class Point3(object):
"""
A class to represent a p... |
bf1dcdba5d05c326c2968f9a0d2ad361b55b6e17 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/Lesson 29. Coroutines/demos/read1.py | 3,523 | 4.0625 | 4 | """
A module to show off a long-running function as a coroutine.
The advantage of the coroutine is that we can us the yield
statement to get frequent updates on how much progress the
function is making (such as for a progress bar or a level
loading screen)
Author: Walker M. White
Date: November 2, 2020
"""
def ad... |
68c7a923a7b6d4e8a86f1484d5ce88a1a44497e7 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 17. Recursion/demos/pali.py | 3,892 | 4.4375 | 4 | """
Functions showing how helpers interact with recursion
The first version of palindrome is simple. All we have to
do is to implement the recursion as described in the
specification. However, when we want to mix it up a bit,
then we have think about integrating helpers.
Author: Walker M. White (wmw2)
Date: Octob... |
b56489fe33b248fb562a646f4fdab893c734d669 | LizzieDeng/kalman_fliter_analysis | /CSclasses/SuperClass/PigGame.py | 1,148 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@Time: 2021/1/28 16:10
@Author: LizzieDeng
@File: PigGame.py
@Description:
"""
#
#
# def range2iter(n):
# """
# Generator for the squares
# of numbers 0 to n-1
# Precon: n is an int >= 0
# """
# for x in range(n):
# yield x*x
#
# a = range2iter(10)
# print(a)
... |
c38dac91d36bb2885068bad8fd81ed517532a92e | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 18. Nested Lists/demos/image.py | 1,567 | 4.09375 | 4 | """
Module to demonstrate what an image might look like in
memory.
This module has a function that constructs a table of RGB
objects, which is what an image is in memory. The image
is the smilely face represented in smile.xlsx.
Author: Walker M. White
Date: June 7, 2019
"""
import introcs
def wh():
"""
R... |
d52820228570073946ec653e69322c7d30a2d315 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/Lesson 28. Generators/demos/filterer.py | 1,139 | 4.1875 | 4 | """
Module to demonstrate the idea behind filter
This module implements the filter function. It also has
several support functions to show how you can leverage it
to process data. You may want to run this one in the
Python Tutor for full effect.
Author: Walker M. White (wmw2)
Date: May 24, 2019
"""
def filter(f,... |
b8c892c6b0b2938b3a521dcecaa6a93e38562d3c | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 14. Error Handling/demos/tryfunc.py | 655 | 4.03125 | 4 | """
A function to test whether a string is a number.
This module is complete. It shows how try-except makes it easy.
Author: Walker M. White
Date: March 30, 2019
"""
def is_number(s):
"""
Returns True if the string s can be cast to a float.
Examples:
is_number('1') is True
is_number(... |
c1478e4316bf8c3c4c764d4192dcb54b7d1140fa | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 17. Recursion/demos/com.py | 1,950 | 4.53125 | 5 | """
A recursive function adding commas to integers.
These functions show the why the choice of division at the recursive step matters.
Author: Walker M. White (wmw2)
Date: October 10, 2018
"""
import sys
# Allow us to go really deep
#sys.setrecursionlimit(999999999)
# COMMAFY FUNCTIONS
def commafy(s):
"""
... |
84f6b45e41a601e5878f6b414792b13db557cfae | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 22.Subclasses &Inheritance/demos/initialize.py | 719 | 4.09375 | 4 | """
A CS1110 lecture example for initialization of subclasses
This is just demonstrating syntax, so there are no specifications.
Authors: Steve Marschner (srm2), Lillian Lee (ljl2), and Walker M. White (wmw2)
Date: October 28, 2017 (Python 3 Version)
"""
class A(object):
def __init__(self):
self.x = ... |
0ff7c36732279dd198f5034931b84041c0ac45d4 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 16. For-Loops/demos/mut.py | 906 | 4.40625 | 4 | """
Module to demonstrate how to modify a list in a for-loop.
This function does not use the accumulator pattern, because we are
not trying to make a new list. Instead, we wish to modify the
original list. Note that you should never modify the list you are
looping over (this is bad practice). So we loop over the ran... |
e633be9b864b2ae81f2275718708f73f9aff44e6 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 26. While-Loops/demos/newton.py | 1,256 | 4.40625 | 4 | """
A module to show while-loops and numerical computations.
This is one of the most powerful uses of a while loop: using it to run
a computation until it converges. There are a lot of algorithms from
Calculus and Numerical Analysis that work this way.
Author: Walker M. White
Date: April 15, 2019
"""
def sqrt(c,... |
c1ed8081996e85bf6f06c97f17294ca787449d79 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 26. While-Loops/demos/pattern2.py | 1,033 | 4 | 4 | """
A module showing off the second while-loop pattern.
Here we are using a while-loop that stops when a goal in the specification
is true.
Author: Walker M. White
Date: April 15, 2019
"""
def prompt(prompt,valid):
"""
Returns: the choice from a given prompt.
This function asks the user a questio... |
ba620c5dbd4f2dfe96d7c26412d1f95cb8a40b3d | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 18. Nested Lists/demos/stubs.py | 1,770 | 4 | 4 | """
Immutable (accumulator) functions on a 2d list of numbers.
This version of the module shows off the stubs (before the functions are completed).
Author: Walker M. White
Date: June 7, 2019
"""
def all_nums(table):
"""
Returns True if table contains only numbers (False otherwise)
Example: all_nu... |
74445166d367c8c0e5ecf807b725d6c362d61b22 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/Lesson 28. Generators/demos/accums.py | 1,510 | 3.9375 | 4 | """
A module showing off some classic for-loops
This module is for comparison with gens.py. This
module shows the old way of doing things.
Author: Walker M. White (wmw2)
Date: October 28, 2020
"""
def add_one(input):
"""
Returns the list with 1 added to every element of input
Example: add_one([1,2,3,1... |
76942d5babc61134a409f8eac498b7efe90fa291 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/Lesson 29. Coroutines/demos/inyield1.py | 765 | 4.0625 | 4 | """
A module to show off a yield expression (not a statement)
A yield expression receives data instead of sending it as output.
You write the word yield in parentheses and assign it to a variable.
Author: Walker M. White
Date: November 2, 2020
"""
def receive(n):
"""
Receives n values as input and prints... |
cb35550231866abfbadca029a1c91a125a2e9e2f | gunishj/python_async_multiprocessing | /AsyncIO/implementing_asyncio.py | 1,157 | 4.5625 | 5 | import asyncio
import time
def sync_f():
print('one', end=' ')
time.sleep(1) # I'm simulating an expensive task like working with an external resource. I want it to wait for 1 sec
print('two', end=' ')
# ASYNCHRONOUS
async def async_f():
print('one', end=' ')
await asyncio.sleep(1)
print('two',... |
a8c6293249694d8ecc4be1b1e3a31a204fa18229 | Regenyi/python | /torpedo_generator.py | 1,907 | 3.515625 | 4 | import random
import pprint
board_ai = [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
]
# allowed_chars = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5),
# (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5... |
d0b10155a5fea50e349d21c7ad7167f747d58ce8 | Regenyi/python | /simplecalc.py | 1,026 | 4.34375 | 4 | #Regényi Ádám / CC , Python 1st SI Assignment
while True:
nr1 = input("Enter a number (or a letter to exit:) ")
if nr1.isdigit():
nr1int = int(nr1)
else:
exit()
list1 = ["+", "-", "*", "/"]
operation = input("Enter an operation (+, -, *, /) : ")
while operation not in list1... |
64808dbc7d43cd9d3a57c56597319caaff627b38 | Regenyi/python | /TicTacToeZoli2.py | 2,379 | 3.890625 | 4 | import re
import os
import random
winning = False
os.system("clear")
board=[1,2,3,4,5,6,7,8,9]
def print_board():
print(board[0], "|" ,board[1], "|" ,board[2], "|")
print("––––––––––––")
print(board[3], "|" ,board[4], "|" ,board[5], "|")
print("––––––––––––")
print(board[6], "|" ,board[7], "|" ,... |
b0e6525bb742e5b52bccfec030e8f3a51fcd2439 | Regenyi/python | /TicTacToeZoli2+.py | 2,850 | 3.671875 | 4 | import re
import os
import random
import time
import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl-C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
winning = False
board=[1,2,3,4,5,6,7,8,9]
os.system("clear")
def print_board():
print(board[0], "|" ,board[1], ... |
0fcd16dcfa157c95f8ff55b16fb8e8f687a96e62 | Regenyi/python | /Thonny_continue.py | 729 | 4.15625 | 4 | menu = """-- Calculator Menu --
0. Quit
1. Add two numbers
2. Subtract two numbers
3. Multiply two numbers
4. Divide two numbers"""
selection = None
while selection != 0:
print(menu)
selection = int(input("Select an option: "))
if selection not in range(5):
print("Invalid option: %d" % selection)... |
fa669ab56fb32241a23d3f9d00857001571cb2b2 | Regenyi/python | /sorting.py | 1,608 | 4.1875 | 4 | #Sorting algo - RA CC Python SI1 A3
import re
#getting the number from the user:
input_numbers = []
input_numbers = input("\nTell me positive integers that you want to sort, by separting them with a coma (so for example: 10,2,45):\n\n")
#exception handler for wrong format:
while True:
if (len(input_numbers)<6 or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.