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
bfe439b3a63790c700676503d29d6d75d7822a04
wngo1337/CS1026
/CS1026Assignment3/wngo2_Assign3.py
4,965
3.84375
4
# CS 1026 Assignment 3 - Sentiment Analysis # code written by William Ngo import happy_histogram # create dictionary to store keywords with value that will be read keyWords = {} zoneValues = {} # function to read in keywords to dictionary def keyReader(): fileName = input("Please enter the name of the keywords f...
9d82a9f5aada76cc497c32e6134f08f74b437b88
Daniel296/Calcul_Numeric
/Tema1/Tema1.py
4,603
3.734375
4
import numpy as np """ Problema 1 """ def machine_precision_sum(): m = -1 while True: if 1.0 + pow(10, m) == 1.0: return pow(10, m + 1), (m + 1) m -= 1 """ Problema 2 """ def check_non_associativity(): x = 1.0 y = z = machine_precision_sum()[0] boolean_value = ((x ...
77c4a0216a5955e2116ee39e561e4f5f42fc1883
ivababukova-zz/project
/analyzers/nodesPlotMaker2.py
1,778
3.578125
4
""" Demo of table function to display a table within a plot. """ import numpy as np import matplotlib.pyplot as plt # data for SIP0 data = [[9.454, 22.222, 0, 0 ], # 1 [4.315, 1.777, 0, 0 ], # 2 [0, 0, 0, 0 ], # 3 [0, 0, 0, 0 ], # 4 ...
0f15d49f13a4ae29efb121e2df4105ac38f81e9e
johng42/sense
/Raspberry_Pi/simple_read_T_H.py
3,531
3.6875
4
# simple_read_T_H.py # Example code for using the Sense board to measure humidity # and temperature. # This example is designed to run with Python 3 on a Raspberry Pi. # Measures and displays the humidity and temperature, demonstrating # the decoding of the signed temperature value. The data are also # rea...
750effb5364d6f6fc87cba63be53a63b6a0d14a4
atupal/oj
/topcoder/contests/tco_2015/round1a/a.py
571
3.515625
4
# -*- coding: utf-8 -*- class Similars(object): def maxsim(self, L, R): s = [] for i in xrange(L, R+1): s.append( sorted( list(set([_ for _ in str(i)]) ) ) ) s.sort() ans = 0 for i in xrange(len(s)-1): t = len( set(s[i]) & set(s[i+1])) ...
3d22a708cb39d52501423f19a7c7c726cd6ba473
UESTCYangHR/leecode_test
/path-sum-ii.py
845
3.71875
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: return [] ...
532d403ec4d67fc047c9924a70973a8016de94bf
UESTCYangHR/leecode_test
/Nodes_in_a_pair_of_exchange_lists.py
658
3.859375
4
# coding=utf-8 # @Time :2019/2/17 17:05 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: ...
31b4aa5d3bdffb2be349a3254c0afb2236db7338
UESTCYangHR/leecode_test
/combination-sum.py
708
3.515625
4
# coding=utf-8 # @Time: 2/27/2019 12:32 PM from typing import List class Solution: def DFS(self, candidates, target, start, valuelist): if target == 0: return Solution.analist.append(valuelist) for i in range(start, len(candidates)): if candidates[i] > target: ...
4d851be151274b9bd6a08f1bb9a180a5367310e2
UESTCYangHR/leecode_test
/wildcard-matching.py
1,875
3.515625
4
# coding=utf-8 # @Time: 3/1/2019 12:35 PM class Solution: def isMatch(self, s: str, p: str) -> bool: # dp表,以p字符串作为列,以s作为行 dp = [[False for i in range(len(p) + 1)] for j in range(len(s) + 1)] # 双方都是空字符串,当然是true dp[0][0] = True for i in range(1, len(p) + 1): ...
1985e7d93e652a3bb71a8aac8ef9ed24835ab79c
UESTCYangHR/leecode_test
/sudoku-solver.py
1,710
3.546875
4
# coding=utf-8 # @Time: 2/26/2019 1:43 PM from typing import List class Solution: def isValue(self, board, x, y): # 检查填入的坐标是否与行中已有的元素相等 for i in range(9): if i != x and board[i][y] == board[x][y]: return False # 检查行是否符合 for j in range(9): ...
47c957965e88e0cfec3ecd3ad590029cb8e6d389
UESTCYangHR/leecode_test
/construct-binary-tree-from-preorder-and-inorder-traversal.py
882
3.828125
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: self.preorder = preorder ...
bad0daf53f8d70b234bc0ca729cb2653be03d9f2
Irisldc/Leetcode-solutions
/implementstrStr().py
585
3.53125
4
def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle=='': return 0 d={} length=len(needle) if needle in haystack: for i in range(len(haystack)): d[i]=haystac...
1c895376fad80db62221ef30a063376ce13f6c3c
yukadev6/cylinder-calculator
/cylinder.py
360
3.6875
4
class Cylinder: def __init__(self,height=1,radius=1): self.height = height self.radius = radius def volume(self): return 3.14 * ((self.radius ** 2) * self.height) def surface_area(self): return (2 * 3.14 * self.radius) * (self.height + self.radius) c = Cyl...
70ed3e204149399b43259d4fa675d705cc4d9121
yueranwu/CP1404_prac06
/programming_language.py
946
4.125
4
"""CP1404/CP5632 Practical define ProgrammingLanguage class""" class ProgrammingLanguage: """represent a programming language""" def __init__(self, name, typing, reflection, year): """Initiate a programming language instance name: string, the name of programming language typi...
3243d6f68c21831c59b9565ed5acef24f6d0b55f
mtianyan/AlgoPlay
/src/StacksQueues/queue.comparison/Main.py
729
3.515625
4
import random import time import ArrayQueue import LoopQueue def test_queue(q, count): start = time.time() for i in range(count): q.enqueue(random.randint(1, 10)) for i in range(count): q.dequeue() end = time.time() print(f'{q}, size: {count} : {end - start} s') if __name__ == '_...
1893d5c67fc23a60193a536176c822601174b66c
mtianyan/AlgoPlay
/src/SelectionSort/basic/SelectionSortTyping.py
772
3.609375
4
from typing import List from abc import abstractmethod from typing import TypeVar, Protocol class Comparable(Protocol): """Protocol for annotating comparable types.""" @abstractmethod def __lt__(self, other) -> bool: pass CT = TypeVar("CT", bound=Comparable) class SelectionSort: @staticme...
e7032cbfec442ced9e92478100f46bb0d4648ce7
mtianyan/AlgoPlay
/src/QuickSortMore/problem.in.allsamearray/QuickSort.py
1,538
3.828125
4
from random import randrange class QuickSort: def sort(self, arr): return self._sort(arr, 0, len(arr) - 1) def _sort(self, arr, l, r): if l >= r: return p = self.partition(arr, l, r) self._sort(arr, l, p - 1) self._sort(arr, p + 1, r) def partition(sel...
ba3b2bf1fed07eb1a6bc1fbd340b215d3c648b1c
mtianyan/AlgoPlay
/src/LinkedList/impl.stack/ArrayStack.py
781
3.5625
4
from Stack import StackInterface from ArrayTyping import Array class ArrayStack(StackInterface): def __init__(self, capacity): self.array = Array(capacity) def get_size(self): return self.array.get_size() def is_empty(self): return self.is_empty() def get_capacity(self): ...
97cd570f4b52052a7d233765dc0ceb24e44f9a52
cinelcio/euler-exercices
/Python/tools/fibonacci.py
2,322
3.984375
4
if __name__ == '__main__': import validator as v else: from tools import validator as v class FiboCounter(): def __init__(self): pass def CountFibonacciSequence(self, highestvalue = 10, showlist = False): counter = 0 result = 0 transfer = 1 previous = 0 ...
0a0b84db031db8b46a100547ab35683aab2e4e65
JosephZYU/Python-2-Intermediate
/test_calc.py
1,005
3.671875
4
# Jan 19 2020 # The naming convention to write test with test_ underscore # import calc -> import calc.py from the same direcotory! # 🧠 import unittest import unittest import calc # 🧠 inherit from unittest.TestCase # 🧠 self.assertRaises(ValueError, calc.divide, 10, 0) class TestCalc(unittest.TestCase): def ...
8efbeb68138e25bb288a994ce4a71bc5e4a2aec9
JosephZYU/Python-2-Intermediate
/00.Memo.py
1,939
3.78125
4
""" # ✅ Insert & extend (split all items from the list) courses = ['History', 'Math', 'Physics', 'CompSci'] new = ['Art', 'Education'] # 1st - locate the index of target item 首先定位需要目标的下标 # 🧠 list.index('item') -> list.index() # 😎 to the left # 😎 to the right +1 i = courses.index('Math') + 1 # 2nd - insert and ext...
aa38ec661c5d58c12560f9718054487cc554f227
JosephZYU/Python-2-Intermediate
/test_employee_3.classmethod.py
2,303
3.84375
4
# Jan 20 2020 """ 😎 The setUp and tearDown 1. setUp & tearDown will perform for every single test 2. testing sequence DO NOT necessarily run in the order you expect! 测试的顺序并非脚本顺序! 3. keep ALL of our test isolated from eachother 每个功能的测试必须独立,分治,自洽 # 👀 cls和self之间只能二选一!不能同时继承! # recall: @classmethod -> wor...
7804095933cc582dbff88b5369ed5d35f45e8c57
JosephZYU/Python-2-Intermediate
/27.Python Tutorial for Beginners 8: Functions.py
1,082
4.3125
4
# https://youtu.be/9Os0o3wzS_I def hello_func(name, host_name='Alexa'): return (f'How are you {name}! This is your host {host_name} speaking\nHow may I help you today?') # return (f'How are you! {name}\nHow are you twice! {name}') # return (f'How are you! {name} ' * 3) print(hello_func) print() print(he...
c226789f7c1fdecd4aabbb5b82eeb124bff6f294
ekarlso/pulp_deb
/pulp_deb_common/pulp_deb/common/utils.py
887
3.53125
4
import gzip def _read(f, empty_on_io=False, as_list=True): """ Read a file to a string or a list :param f: Either a 'file' object or a filename :type f: str or file :param empty_on_io: Return empty on IOError :type empty_on_io: bool :param as_list: Return contents as a list :type as...
2152a4052bc04e6ee2dbc8a7961d088ddc6df217
ashmgarv/My-World-of-Python
/Leet Code/leet_code_searchinsert.py
415
3.5625
4
#LeetCode SearchInsert #Timing: 56ms #Faster than 88.42% of Python3 submissions class Solution: def searchInsert(self, nums, target): if target in nums: return nums.index(target) else: ind = [index for index, number in enumerate(nums) if number > target] if len...
2addff4f09ced2f97cdeddba08a24b0d04096607
IvanCher-py/python-algorithms
/task_5.py
783
4
4
# Задание № 5 - Пользователь вводит две буквы. Определить, на каких местах # алфавита они стоят, и сколько между ними находится букв. letter_one, letter_two = input('Введитe две строчные латинские буквы через пробел: ').split() scii_starta = 96 place_one = ord(letter_one) - ascii_start place_two = ord(letter_t...
be9453c716a9a2bee40077d2833926801d0a479e
defcxz/2020_prog.algoritmos
/EjerciciosGuia6/ejercicio3.py
4,290
3.953125
4
puntUsuario = float(input("Ingrese la puntuación del usuario.\n")) if(puntUsuario == 0.0 or puntUsuario == 0.4 or puntUsuario >= 0.6): if(puntUsuario == 0.0): cantDinero = int(10500*puntUsuario) print("El nivel de rendimiento del usuario es inaceptable, la cantidad de dinero que recibirá será de"...
19022551bf06015e087431bf3c54d1ea364fe091
defcxz/2020_prog.algoritmos
/EjerciciosGuia6/ejercicio4.py
1,636
3.65625
4
edad = int(input("Ingrese la edad del cliente.")) if(edad < 4): print("El cliente puede entrar gratis :D") elif(edad > 4 and edad < 18): print("El cliente debe pagar $3000.") else: print("El usuario debe pagar $10000.") edad = int(input("Ingrese la edad del cliente.")) if(edad < 4): print("El cliente...
796f09cb09ba332000a825bc66b14569bee22f3a
defcxz/2020_prog.algoritmos
/20-03/20-03_condicionales.py
211
3.6875
4
n1 = int(input("Ingrese un número:\n")) n2 = int(input("Ingrese otro número:\n")) sum = n1+n2 if (sum>100): print("El resultado es mayor que 100: ",sum) else: print("La suma no es mayor que 100",sum)
fdbae475da03a04205e7cbf72d8f56108c890deb
defcxz/2020_prog.algoritmos
/EjerciciosGuia6/ejercicio2.py
1,587
3.734375
4
renta = int(input("Ingrese la renta de la primera persona.\n")) if(renta < 100000): print("El tipo impositivo que le corresponde es del 5%.") elif(renta > 100001 and renta < 200000): print("El tipo impositivo que le corresponde es del 15%.") elif(renta > 200001 and renta < 350000): print("El tipo impositiv...
9129a2aa9b77bf129d988779f039e7d22a09d04b
sdjunaidali/Github_Archive
/test_src/github_archive.py
1,673
3.5625
4
#! /usr/bin/env python import requests import datetime import sys inputDate = raw_input("Enter the date in format 'dd/mm/yyyy' : ") day,month,year = inputDate.split('/') isValidDate = True try : datetime.datetime(int(year),int(month),int(day)) if len(year) == 4 and len(day) == 2 and len(month) == 2 : ...
857f8f2d79407b78da6a041c3fe255247f42a87e
naitax/LeetCode---Python
/DataStructure/217_contains_duplicates.py
316
3.609375
4
#### #OOP solution class Solution: def containsDuplicate(self, nums: List[int]) -> bool: if len(nums) != len(set(nums)): return True return False ## s = input() my_list = list(map(int, s.split())) if len(my_list) == len(set(my_list)): print('false') else: print('true')
30045777a54198678c37a36aad2d982bbe6252f0
qkzk/advent_of_code
/17/conway_cubes.py
2,979
3.515625
4
from itertools import chain def read_file(filename): with open(filename) as inputs: return inputs.read().strip().splitlines() def neighbors(cell): x, y, z = cell yield x - 1, y - 1, z - 1 yield x - 1, y - 1, z yield x - 1, y - 1, z + 1 yield x - 1, y, z - 1 yield x - 1, y, z yi...
f05c4a38995194bb44e896ed079fc7603e6d92ee
qkzk/advent_of_code
/02/password_philosophy.py
1,345
3.671875
4
from collections import Counter def read_inputs(): with open("./input.txt") as inputs: return inputs.readlines() def parse_inputs(inputs: list) -> list: passwords = [] for line in inputs: splits = line.strip().split(" ") values = splits[0].split("-") values = [int(value) ...
e5cd322b04d126d2283dd2be8caed59f1985ef17
Xuehong-pdx/python-code-challenge
/caesar.py
667
4.1875
4
from string import ascii_lowercase as lower from string import ascii_uppercase as upper size = len(lower) message = 'Myxqbkdevkdsyxc, iye mbkmuon dro myno' def caesar(message, shift): """ This function returns a caesar (substitution) cipher for a given string where numbers, punctuation, and other non-alphabe...
cde0d233f7e9d53bd8e501fae8365584dadb402b
VitBomm/Algorithm_Book
/1.12/1_1_is_multiple.py
355
4.3125
4
# Write a short Python function, is_multiple(n, m), that takes two integer values and returns True if n # is a multiple of m, n = mi for some integer i, and False otherwise # def is_multiple(n, m): if n/m % 1 == 0: return True return False n = eval(input("Input your n: ")) m = eval(input("Input your ...
f2304b392ca1e5301969e97fa9ddc0f4d967e7ba
bennettbuchanan/holbertonschool-higher_level_programming
/divide_and_rule/2-main.py
534
4.03125
4
from h_reverse_str import ReverseStrThread text = '''In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.''' words = text.split(" ") reverse_str_threads = [] for word in word...
517592c38f7eec84910bfd172342c46a93b6bae2
bennettbuchanan/holbertonschool-higher_level_programming
/divide_and_rule/h_fibonacci.py
919
4
4
import threading import time import random class FibonacciThread(threading.Thread): def __init__(self, number): '''Computes the fibonnacci number on a new thread. Keyword arguments: number -- The number to find the corresponding fibonnacci number. ''' threading.Thread.__in...
ce3f8c718cd5dfaa780cade7f05ed853bfb87b4f
bennettbuchanan/holbertonschool-higher_level_programming
/mvc_let_s_interact_with_print/task_view.py
1,223
3.5
4
from task_model import TaskModel import Tkinter as tk from Tkinter import * """Class""" class TaskView(tk.Toplevel): """Close the root Tk() task window, and create a Toplevel window. This is a child class of Toplevel. Keyword arguments: master -- A Tk constructor. """ def __init__(self, master...
e1fb035396c96114dbc2b78f81f28faec0d812f0
GustavoBonet/pythonexercicios
/ex.038.py
270
4.15625
4
um = int(input('Primeiro número:')) dois = int(input('Segundo número:')) if um == dois: print('Os dois valores são IGUAIS') elif um > dois: print('O primeiro é maior') elif dois > um: print('O segundo é maior') else: print('Erro, tente novamente.')
ca92462676051d3bd3438b86f494ecb75d5042fb
GustavoBonet/pythonexercicios
/ex.034.py
198
3.65625
4
a = float (input('Digite o salário R$')) b = a*10/100 c = a*15/100 if a > 1250: print(f'O seu novo salário será de R${a+b :.2f}') else: print(f'O seu novo salário será de R${a+c:.2f}')
d3337974e5c51d67ffea1ac58ab7edee7e8ef34f
GustavoBonet/pythonexercicios
/ex.044.py
944
3.59375
4
preco = float(input('Preço total: R$')) print(' [ 1 ] DINHEIRO OU CHEQUE 10% OFF \n [ 2 ] DÉBITO 5% OFF \n [ 3 ] ATÉ 2X NO CRÉDITO') print('[ 4 ] 3X A 12X NO CRÉDITO 20% DE JUROS') opcao = int(input('Qual sua opção:')) if opcao == 1: print(f'Sua compra de {preco:.2f} vai custar {preco - (preco * 10/100):.2f}') elif...
4abb7b8a73e3eab8d40c8b74b84bd1fad431a3d0
GustavoBonet/pythonexercicios
/ex.019.py
200
3.6875
4
import random a = input('primeiro aluno:') b = input('segundo aluno:') c = input('terceiro aluno:') d = input('quarto aluno') lista = [a,b,c,d] print(f'O aluno escolhido foi {random.choice(lista)}')
6dc10852712897a19602c1a421a46f3d780b7f67
GustavoBonet/pythonexercicios
/ex.011.py
171
3.71875
4
a = float(input('digite a largura :')) b = float(input('digite a altura :')) print(f'a parede tem {a*b :.2f}m² e para pintá-la precisará de {(a*b/2) :.2f}l de tinta ')
88c0e6573add46d71375df774f52924617f8a4bd
abaruchi/tabajaraWebmon
/webmon/webmon/Probe.py
2,857
3.859375
4
import requests import re from datetime import datetime from abc import ABC, abstractmethod """ Design Patterns example that I usually look when implementing: https://refactoring.guru/design-patterns/python """ class Probe(ABC): """ This abstract class must be used to implement probes in different appli...
85c0f6f49c190b2da67234fca2d881429b0f6b52
saviodmo/Exercicio-Uri-Python
/1018.py
651
3.578125
4
valor = int(input()) print(valor) nota100 = valor // 100 valor = valor - nota100*100 nota50 = valor // 50 valor = valor - nota50*50 nota20 = valor // 20 valor = valor - nota20*20 nota10 = valor // 10 valor = valor - nota10*10 nota5 = valor // 5 valor = valor - nota5*5 nota2 = valor // 2 valor =...
d6081c1adb035339eccd22cb314e46be8a53428d
yelsangeakshay/Python
/temp_files.py
643
3.609375
4
import os #print(os.getcwd) file_name = input("Enter the file name") paths = ("/home") result=[] os.chdir(paths) #location = #print(os.getcwd()) for root,dirs,files in os.walk(paths): if file_name in files: result.append(os.path.join(root,file_name)) loc = str(result) loc = loc.replace('[','') loc = loc....
0b2068ebe731772030bf2d3c9cb025eea57d9f59
ITNerdyLed/cs9321
/labs/lab01/activity_1.py
680
3.875
4
#!/usr/bin/env python3 import pandas def get_dataframe_from_csv(filename): dataframe = pandas.read_csv(filename) return dataframe def get_columns(dataframe): columns = list(dataframe) return columns def get_rows(dataframe, columns): rows = [list(map(lambda c: row[c], columns)) for index, row in d...
8ca4afe5fe40605a44caa37ad70f1ca73b55dd82
ITNerdyLed/cs9321
/labs/lab02/activity_4.py
1,033
4
4
#!/usr/bin/env python3 import pandas from activity_2 import clean_columns def main(): # Load the dataset into a dataframe dataframe = pandas.read_csv('../common/Books.csv') # Apply the cleansing methods discussed in Activity-2 dataframe = clean_columns(dataframe) # Replace the spaces in the column ...
5e2e2da009ea8f94115cb38753d0130408e4a3d1
charlie83cl/funciones_basicas_II_python
/funciones_basicas_II.py
2,790
4
4
#1. Cuenta regresiva : crea una función que acepte un número como entrada. # Devuelve una nueva lista que cuenta hacia atrás en uno, desde el número # (como el elemento 0) hasta 0 (como el último elemento). #Ejemplo: la cuenta regresiva (5) debería devolver [5,4,3,2,1,0] def contReg(numero): lista = [] for i...
abb45b7c8eba708fa464952e28a14993794d481b
santoHide/test
/test.py
536
3.59375
4
""" このファイルに解答コードを書いてください """ # coding: utf-8 test_data = open("input.txt", "r") number = [] #数入力 s = [] #文字 dic = {} lines = test_data.readlines() for line in range(0,len(lines)-1): i, j = lines[line].split(":") dic.setdefault(int(i), j.strip()) number2 = int(lines[len(lines)-1]) #注目する値 #結果出力 result = "" f...
b23c4eba232e4ea2b5c9aea20ded74d0d0cee465
anishshriram/astar-visualization
/astar_algorithm.py
11,105
3.984375
4
import pygame import math from queue import PriorityQueue # Define width of window - square, so no height variable needed WIDTH = 800 # Setting up the display (win for window) WIN = pygame.display.set_mode((WIDTH, WIDTH)) # Caption for the display pygame.display.set_caption("A* Path Finding Algorithm") # Colors to ...
5cd5412ec20d49b09ce2b96bb3db16781a7849f7
UToledo-DataScience/Chatbots
/net.py
7,152
3.6875
4
# rnn tutorial from tensorflow import tensorflow as tf import numpy as np import os import time # NOTE: change this path to a place you want weights to be saved weights_save = "/root/python/tensorflow/projects/chatbot/weights/tutorial.tf" # get the text data to use for training (in this case it's Shakespeare) path =...
66cdc7999c7eef916f6147742bed23024c33dd79
KomaKomar/lesson1
/types.py
444
3.734375
4
a = 2 b = 0.5 print(a + b) name=' ИЛЬЯ '.strip().capitalize() otch="витальевич".capitalize() c=(f'{name} {otch}') print ("привет, " + name.strip().capitalize() +'!') print(c) v1=input('Введи число 0-10: ') v2=int(v1)+10 print(v2) name1=input('Имя:') name1=name1.capitalize() print('Привет, ' + name1 + '! ' '...
0aee2760a37cf6efccb5ed52e97f5cff171e9835
samuel108/CSF
/homework3/lab3.py
315
3.578125
4
# Name: Sam Goldsmith # Evergreen Login: Golsam27 # Computer Science Foundations # Programming as a Way of Life # Homework 3 def f(n): curent = 1 oldnum = 1 awns = 1 while (awns < n): curent, oldnum, awns = curent+oldnum, curent, awns+1 return curent for awns in range(10): print(f(awns...
1d28515f8508d908cc224043be37d6f0c3129ba6
LoganW94/Text-Adventure
/interpret.py
960
3.5625
4
import json class Interpret: 'this class takes user input, extrapulates intent, and returns a relevent function' def __init__(self, room): 'loads dictionary with commands' self.room = room filename = 'dictionary.json' with open(filename, "r") as f: text = f.read() d = json.loads(text) f.close sel...
45f2179deaa14abbb287fd2d956e12ce6bd3733e
Liam876/USEFUL_STUFF
/repos/factory.py
1,877
4.15625
4
from abc import ABC, abstractmethod import math from itertools import accumulate import random class Shape(ABC): @abstractmethod def perimeter (): pass @abstractmethod def area(): pass def __str__(self): return "This is a shape" class Triangle (S...
659497ff868971d796d23d09b223f1921aa63d06
Liam876/USEFUL_STUFF
/sorting algorithms/quicksort_algo.py
526
3.734375
4
import sys from itertools import chain from bubble_sort_algo import * import random def quick_sort(arr): if len(arr) <= 1: return arr less, great = [] , [] ind = random.randint(0,len(arr) -1) piv = arr[ind] arr.remove(arr[ind]) for i in range(len(arr)): if arr[i] > ...
ce4a2f26dff9b7aae290e08ea4e02a6054f4e650
SBCV/Blender-Addon-Photogrammetry-Importer
/photogrammetry_importer/utility/type_utility.py
385
4.15625
4
def is_int(some_str): """ Return True, if the given string represents an integer value. """ try: int(some_str) return True except ValueError: return False def is_float(some_str): """ Return True, if the given string represents a float value. """ try: float(some_str)...
07bf73f5f18d272ab2534d1338dc89b2418f9540
venkateshyadava/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/deque/deque.py
958
4.03125
4
class Deque: def __init__(self): self._deque: list = [] def add_front(self, item): self._deque.insert(0, item) def add_rear(self, item): self._deque.append(item) def remove_front(self): if self.is_empty(): raise Exception("Deque is empty") return se...
aef2c6c440276c7fa7418003e4172a64db75956b
deflox/zhaw-hm2-lab
/sep/integration/summierte_trapezregel.py
750
3.609375
4
import numpy as np def summierte_trapezregel(f, a, b, n): h = (b-a)/n f_sum = 0 for i in range(1,n): f_sum += f(a+i*h) return h * ( ( (f(a) + f(b)) / 2 ) + f_sum ) def summierte_trapezregel_verbose(f, a, b, n): h = (b-a)/n fa = f(a) fb = f(b) f_sum = "" for i in r...
a1a403aca96ec2ad2c6d16e7de5c8d90525cd7f6
kasapenkonata/programming-practice
/turtle/less 1 ex 13.py
821
3.78125
4
#less 1 ex13 import turtle turtle.shape('turtle') def point(x, y): turtle.penup() turtle.goto(x, y) turtle.pendown() def round(s): turtle.begin_fill() for i in range(1, 361): turtle.forward(s) turtle.right(1) turtle.end_fill() def circle(): for i in rang...
44cafec581a471e3856a08c8696738d3dd65b643
Maureen-1998DEV/WCPO_Visualization
/data/original data/Data_Curation_Ingestion/prepareData.py
6,591
3.5625
4
""" Modified on 2020-06-17 @author: Njeri Murage prepareData.py: connect to postgreSQL database read wcpo tables create json object and files """ import psycopg2 # PostgreSQL database adapter for the Python from psycopg2.extras import RealDictCursor # Access results returned ...
bbd1f440df86b2ea09d9ca0b32fdbf545995a71d
olawuyio/snake290
/items/item.py
2,416
3.984375
4
import pygame from arena.board import Board class Item: """Represents how all the items in the game should look. This class includes attributes and methods all items must have. Attributes: =========== x: int the x coordinate y: int the y coordinate color: t...
706db30e2ded79809eddc65188a747f6f00569f8
a332shar/Python-Projects
/Reverse order.py
450
3.90625
4
class work: @staticmethod def reverse(line): straight = line.split(" ") x = 0 while x != int(len(straight)/2): temp = straight[x] straight work straight[(len(straight) - x) - 1] = temp x += 1 answer = " ".join(straight) ...
1f4acca07ec2573314fa8bb5851afb01c10b1939
menglin0320/ECE586_project
/game/liarsdice.py
1,647
3.5
4
from util import * class liars_dice_game(): def __init__(self, n_player=2, n_dices=5, n_faces=6): self.n_player = n_player self.n_dices = n_dices self.n_faces = n_faces self.dices = [[0] * 5]*2 self.history = [[],[]] def roll_dices(self): self.dices = [] ...
911b1866e1e3f3b0c292505bf0006e033083bbe2
JujubaOhime/TreeAutomata
/verificandoLógica.py
8,187
3.578125
4
import re # estado 0 = wait # estado -1 = estado inexistente # estado -2 = estado erro # estado -3 = estado sucesso class elemento(object): def __init__(self, altura, pai, arvore, filhos, valor, estado): self.altura = altura self.pai = pai self.arvore = arvore self.valor = valor ...
f6f9665651aa5a275566afce0bd49b2afb790918
saidarahmaff/Saida-Rahma-Afifi_I0320089_Wildan_Tugas2
/I0320089_soal1_tugas2.py
972
4.09375
4
print("Menghitung Luas Persegi Panjang") panjang = int(input("Panjang persegi panjang: ")) lebar = int(input("Lebar persegi panjang: ")) luas = panjang * lebar print("Luas Persegi Panjang: ", luas) print("----------------------------------") print("Menghitung Luas Lingkaran") jarijari = float(input("Jari-jari lingkar...
83729c1ec1c01b0be07d84c670143657ef0576cc
TQCAI/crack-vectorization
/计算多边形面积.py
1,538
3.953125
4
# -*- coding: cp936 -*- import math class Point(): def __init__(self, x, y): self[0] = x self[1] = y def GetAreaOfPolyGon(points): area = 0 if (len(points) < 3): raise Exception("error") p1 = points[0] p2 = points[1] p3 = points[2] for i in range(1, len(points) - 1): # vecp1p2...
22bbe3063ee1d210deba290356de77090c52e7e5
MissPeperr/Keahua
/environments/river.py
783
3.5625
4
from environments import Environment from animals import RiverDolphin class River(Environment): def __init__(self, name): Environment.__init__(self, name) def add_animal(self, animal): try: if animal.aquatic and animal.cell_type == "hypertonic": self.animals.appen...
fb5d29cb0bcfe2bb60c17c90cd2af3fbd074a447
MissPeperr/Keahua
/animals/nene_goose.py
742
3.671875
4
from animals import Animal from animals.attributes import Flying from animals.attributes import Walking from animals.attributes import Swimming class NeneGoose(Animal, Flying, Walking, Swimming): def __init__(self): Animal.__init__(self, "Nene Goose") Flying.__init__(self) Walking.__init__...
23b7b26ad6a92c35c65c82007824a77e4afa6df6
MarkHalls/Graphs
/projects/ancestor/ancestor.py
1,261
3.765625
4
def earliest_ancestor(ancestors, starting_node): hm = {} paths = [] visited = set() # build our graph using children as keys for ancestor in ancestors: x, y = ancestor if y not in hm: hm[y] = set() hm[y].add(x) # dft looking for max parent def find_ances...
537575a3bf897377131466806df2581cb85b03a3
jeffsnguyen/Python
/Level_3/Homework/Section_3_3_Exception_Handling/Exercise_4/loan/loanpool.py
5,742
3.609375
4
# Type: Homework # Level: 2 # Section: 2.2: Intermediate Classes # Exercise: 5 # Description: This contains LoanPool class methods # Now that we have our Loan and Asset classes, let’s incorporate the asset into the loan. As a loan is # ‘on an’ asset, which is similar to ‘has a’, we use composition instead of de...
c1b576b8185d1fa6f4fe30e9ce4927ecf4a11eef
jeffsnguyen/Python
/Level_2/Lecture/shapes/line.py
647
3.921875
4
# line class lecture import math from shapes.point import Point #Line class class Line(object): # Point is a class "derived" from object def __init__(self, startP, endP): # standard initialization function x, y coordinate self._startP = startP self._endP = endP @property def startP...
52ae20a0eadb2ac4e684ef4920f6c105d6187a6d
jeffsnguyen/Python
/Level 1/Homework/Section_1_3_Functions/Exercise 5/variance_dof.py
1,003
4.40625
4
''' Type: Homework Level: 1 Section: 1.3: Functions Exercise: 4 Description: Create a function that calculates the variance of a passed-in list. This function should delegate to the mean function (this means that it calls the mean function instead of containing logic to calculate ...
44e98b083845d6ecc0f225a0039d20ddfd08b4c9
jeffsnguyen/Python
/Level 1/Homework/Section_1_4_Builtin_Functions/Exercise 3/mortgage.py
3,371
4.1875
4
''' Type: Homework Level: 1 Section: 1.4: Built-in Functions Exercise: 1 Description: You are a lender, holding onto a large number of mortgages. Create code that does the following: a. A function that returns an unsorted list of mortgage amounts, in thousands. Numbers should range f...
55568741e62e8f4da5189d2582f58916995cd8a3
jeffsnguyen/Python
/Level_3/Homework/Section_3_2_Generators_101/Exercise_1/num_iterable.py
883
4.46875
4
# Type: Homework # Level: 3 # Section: 3.2: Generators 101 # Exercise: 1 # Description: Contains the tests to iterate through a list of numbers # Create a list of 1000 numbers. Convert the list to an iterable and iterate through it. ####################### # Importing necessary packages from random import random, se...
102c237384e02f0c79159d98e89f4c5a4d69cb31
jeffsnguyen/Python
/Level_2/Homework/Section_2_2_Intermediate_Classes/Exercise_1/test_loan.py
4,531
3.875
4
# Type: Homework # Level: 2 # Section: 2.2: Intermediate Classes # Exercise: 1 # Description: This contains the test function for the Exercise 1: FixedRateLoan, VariableRateLoan, getRate # As shown in the lecture, create derived classes as follows: # a. A FixedRateLoan class which derives from Loan. # b. ...
a6948de57520137916bd17f153148e83f51d3f35
jeffsnguyen/Python
/Level 1/Homework/Section_1_5_Dicts_and_Sets/Exercise 2/name_usuk.py
2,581
4.21875
4
''' Type: Homework Level: 1 Section: 1.5 Dicts and Sets Exercise: 2 Description: Create two sets: Set 1 should contain the twenty most common male first names in the United States and Set 2 should contain the twenty most common male first names in Britain (Google it). Perform the...
92209793e197de9c33c0d3f6c219455620de4282
jeffsnguyen/Python
/Level 1/Homework/Section_1_6_Packages/Exercise 2/anything_program/hello_world_take_input/take_input_triangle/take_input/take_input.py
332
4.25
4
''' Type: Homework Level: 1 Section: 1.1 Variables/ Conditionals Exercise: 4 Description: Create a program that takes input from the user (using the input function), and stores it in a variable. ''' def take_input(): var = input('Input anything: ') # Take user's input and store in variable var ...
746e4675d9471fe307e3a43b4387fcdd248ee6cb
jeffsnguyen/Python
/Level_2/Homework/Section_2_1_Classes/Exercise_2/loan/loan_base.py
4,202
4.15625
4
# Type: Homework # Level: 2 # Section: 2.1: Classes # Exercise: 2 # Description: This contains the Loan classes and its methods # Create a basic loan class exactly as demonstrated in the lecture (including the setter/getter property # methods). Then, extend it with methods that return the following (refer to the sl...
a5dff562e692da90041704bbba49e8aaa2845862
jeffsnguyen/Python
/Level_2/Homework/Section_2_2_Intermediate_Classes/Exercise_6/test_asset.py
4,221
4.28125
4
# Type: Homework # Level: 2 # Section: 2.2: Intermediate # Exercise: 6 # Description: This contains the Asset class and its methods # This exercise focuses on creating the individual Asset derived classes. Do the following: # a. Modify the annualDeprRate method of the Asset class to trigger a not-implemented er...
c0f0fbf101b3a648ef5dfd24d760fdcca394c260
jeffsnguyen/Python
/Level_3/Homework/Section_3_3_Exception_Handling/Exercise_2/divbyzero.py
1,719
4.4375
4
# Type: Homework # Level: 3 # Section: 3.3: Exception Handling # Exercise: 2 # Description: Contains the tests for handling div/0 exception # Extend exercise 1) to handle the situation when the user inputs something other than a number, # using exception handling. If the user does not enter a number, the code s...
a1f40e6da78edd81dadd58f19b78490f33aeb4ea
jeffsnguyen/Python
/Level_4/Lecture/string_manipulation_lecture.py
1,778
4.46875
4
# string manipulation lecture def main(): s = 'This is my sample string' # indexing print(s[0]) print(s[-1]) print() # slicing print(s[0:2:3]) print(s[:3]) print() # upper: create a new string, all uppercase print(s.upper()) print() # lower: create a new string, ...
895a0ccf9c95e591b88ddd88000536b6ca73666a
jeffsnguyen/Python
/Level_4/Homework/Section_4_1_Python_Strings/Exercise_4/nameAge.py
25,479
4
4
# Type: Homework # Level: 4 # Section: 4.1 Python Strings # Exercise: 4 # Description: Contains the tests for various filepath operations # Create a program that does the following: # a. Prompts the user for name, age (integer), and country of residence. Display the information # as follows: <name> is <age> yea...
0ae3232f59ab8796d29bfc8779d03ae95ea19081
jeffsnguyen/Python
/Level_2/Lecture/line_main.py
331
3.5
4
''' line class lecture. main file ''' from shapes.point import Point from shapes.line import Line def main(): pt1 = Point(3,4) pt2 = Point(9,6) ln = Line(pt1, pt2) ln2 = Line(Point(9,-4), Point(-8,3)) print(ln.length()) print(ln2.length()) ####################### if __name__ == '__main__':...
c710bc7b0c5d96192d64af0d4e734979435518bb
jeffsnguyen/Python
/Level_2/Homework/Section_2_1_Classes/Exercise_4/test_loan.py
4,110
4.25
4
# Type: Homework # Level: 2 # Section: 2.1: Classes # Exercise: 4 # Description: This contains the test function for the Exercise 4, Loan class and its methods # To demonstrate understanding of class-level methods, do the following: # a. Implement a class-level method called calcMonthlyPmt, in the Loan base cla...
5afb09b8eb3c629211076857bfc6b1f859d28f46
jeffsnguyen/Python
/Level_4/Lecture/string_formatting_lecture.py
1,421
4.21875
4
# string formatting lecture def main(): age = 5 print('Ying is %i years old'%age) # format flag i = integer print('Ying is %f years old'%age) # format flag f = float print('Ying is %.1f years old' % age) # format flag f = floag, truncate it 1 decimal place print('Ying is %e years old' % age) # ...
8251f87063be621d270c55e3c3849c758ae2f28b
jeffsnguyen/Python
/Level 1/Homework/Section_1_3_Functions/Exercise 1/day_of_week.py
1,320
4.3125
4
''' Type: Homework Level: 1 Section: 1.3: Functions Exercise: 1 Description: Write a function that can print out the day of the week for a given number. I.e. Sunday is 1, Monday is 2, etc. It should return a tuple of the original number and the corresponding name of the day. ''' import sys #...
0e7639bd5f7fc3b37bfa0cdbcd091fd94121e827
jeffsnguyen/Python
/Level_3/Homework/Section_3_2_Generators_101/Exercise_4/fibonacci.py
2,283
4.46875
4
# Type: Homework # Level: 3 # Section: 3.2: Generators 101 # Exercise: 4 # Description: Contains the tests to modified fn() method to generate Fibonacci sequence # Modify the Fibonacci function from Exercise 1.3.2 to be a generator function. Note that the function # should no longer have any input parameter sin...
5792af4a3d9edc774bba3c6cf4bb7cba31ef6b0d
jeffsnguyen/Python
/Level_3/Homework/Section_3_1_Advanced_Functions/Exercise_1/test_hypotenuse.py
1,140
4.375
4
# Type: Homework # Level: 3 # Section: 3.1: Advanced Functions # Exercise: 1 # Description: This contains the method to test the hypotenus of a right triangle # Create a stored lambda function that calculates the hypotenuse of a right triangle; it should take # base and height as its parameter. Invoke (test) this lam...
c83172350ed7a2523246895a80fa15f1ff34a19e
ragavendranps/Python
/PyTrain-master/session1/exec-7_1.py
335
4.0625
4
input_str = input("Enter a text or paragraph") search_str = input("Enter the word to search") def count_word(statement): count = 0 for i in range(len(statement)-1): if statement[i:i+len(search_str)] == search_str: count = count+1 return count final_count = count_word(input_str) print...
9e9a0bede7acbfbe922a275afca5514c5212fbad
ragavendranps/Python
/PyTrain-master/session1/conditions.py
996
3.96875
4
name1 = "aravinth" name2 = "rakesh" num1 = 10 num2 = 20 if num1 > num2: print("num1 greater than num2") else: print("num2 greater than num1") var1 = 1+2j if type(var1) == int: print("variable is an integer") elif type(var1) == float: print("var1 is a float") else: print("variable type unknown") ...
04144da68cfc82e27fcf84d62773d6b0aad3e7d8
Shuang0420/LeetCode
/1-Two-Sum/solution.py
1,785
3.875
4
''' Check assumption: - array is not sorted - each input would have exactly one solution - duplicates in array - return index is not sorted Corner case: - len(nums)<2 or nums==None Solution: - Loop array, search target-nums[i] for each nums[j] on the right. Time complexity: O(n^2) Attention: - we cannot sort array, ...
ec28e93fee3a96f5fe585ed27f47ed381278a0e5
Shuang0420/LeetCode
/346-Moving-Average-from-Data-Stream/solution.py
1,167
3.9375
4
''' Solution: - maintain a deque of at most 'size' length, for each next call, enque the number, calculate average, check if the length of deque is 3, if it is, popleft, and finally return the average. Time complexity O(n); Space complexity O(size) Follow-up: - make it O(1), save the sum each time, that is for each ne...
4f999f411dc875269cba559dcdfdcc478f3bdd7b
BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures
/queue/queue.py
691
4.125
4
class Queue: def __init__(self): self.queue_list = [] def is_empty(self): ''' Returns a boolean indicating if the Queue is empty Wost Case Complexity O(1) ''' return self.queue_list == [] def size(self): ''' Returns the size of the Queue Worst Case Complexity ...
239a7d5a51ce925d7b03749269fecfffec6d51a8
BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures
/trees-and-tree-algorithms/min_heap.py
831
4.03125
4
class BinaryHeap: ''' A min heap Implementation of a BinaryHeap data structure ''' def __init__(self): self.heap_list = [0] self.current_size = 0 def insert(self, k): self.heap_list.append(k) self.current_size = self.current_size + 1 self.__percolate_up(self.current_size) def find_min...
61ee1f89ea4b3f3e0862c729f4bce4f91d96148a
BrandonOdiwuor/Problem-Solving-With-Algorithms-and-Data-Structures
/sorting-and-searching/sorting/insertion_sort.py
575
4.375
4
def insertion_sort(lst): ''' Sorts a list in ascending order according to Insertion Sort algorithm Time Complexity O(N^2) ''' for index in range(1, len(lst)): item = lst[index] i = index while i > 0 and item < lst[i - 1]: lst[i] = lst[i - 1] i = i - 1 lst[i] = item return lst...
cc1bfa4b1141c0052aa088a85b20f37e0d1b8b26
RafalStaszak/tf_tutorial
/system/timer.py
546
3.671875
4
import time class Timer: def __init__(self) -> None: self._started = False self._start_time = None self._elapsed = -1 def start(self): if not self._started: self._started = True self._elapsed = -1 self._start_time = time.time() def stop...
57e2789ecb73d9fb8ec72ac7a387d25e28f684d2
damingus/CMPUT174
/TicTacToe/ttt-grid.py
6,962
4.0625
4
# Pre-Poke Framework # Implements a general game template for games with animation # You must use this template for all your graphical lab assignments # and you are only allowed to inlclude additional modules that are part of # the Python Standard Library; no other modules are allowed import pygame # User-defined fu...