blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f46f61ee7c243f6d8f44468e37468c4195fb962c
nsibal/Design-6
/PhoneDirectory.py
1,933
3.609375
4
''' Time Complexity: O(n) (for the constructor) O(1) (for all the other operations) Space Complexity: O(n) Did this code successfully run on LeetCode?: Yes Problems faced while coding this: None Approach: Maintain a Queue of available numbers and a...
0584bce918a7534ecfb44a507125581210ef698c
monkeylyf/interviewjam
/recursion/leetcode_Strobogrammatic_Number_III.py
1,924
4.15625
4
"""Strobogrammatic number III leetcode A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high. For example, Given low = "50", high = "100", return 3. Because 6...
1d77e64da5a169bd74dee1803a3c7edf41f4f1b4
zhao907219202/python-1st
/python-advance/object/slots.py
1,554
4.21875
4
""" 1. 动态给实例绑定属性和方法,给一个实例绑定的方法,对另一个实例是不起作用的 但也可以动态给类绑定方法 2. 想要限制实例的属性怎么办?比如,只允许对Student实例添加name和age属性。 为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量, 来限制该class实例能添加的属性 注意: __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的: 除非在子类中也定义__slots__,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__ """ from types import MethodTy...
5eae6dc4a32cd722a748f6f4e4e23d979fee1bb7
tp-yan/PythonScript
/liaoxuefeng/class_variable.py
574
3.5
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 18 13:40:31 2019 @author: cv """ """ 类变量 """ class C: print("Class C being defined!") counter = 0 # 类变量,**只能通过类来改变,实例只能读取而无法改变** def init(self): C.counter += 1 c1 = C() c1.init() c2 = C() c2.init() print(c1.counter) print(c2.counte...
03533ad6d6c23465b558d13d921119c920b6c907
Aqib04/tathastu_week_of_code
/Day2/2.py
109
3.8125
4
a=0 b=1 n=int(input("Enter Number ")) for i in range (n): print(a,end= "...") c=a+b a=b b=c
52d2b85c03a6d70b10c87d835dfc3c06c3e43687
TankingItOneStep/Temme
/src/utils/TimeUtil.py
1,551
4.0625
4
# Built-in imports import datetime def formatted_now(include_date=False): """ Pretty-prints the current time float Returns: str: formatted now time string in "HH:MM:SS:_MS" """ now = datetime.datetime.now() return f"{now.month}/{now.day}/{now.year} {now.hour:02d}:{now.minute:02d}:{now...
033965e476d2a12ddb2e882bee959a2f10f20173
ChrisMarriner/cp1404practicals
/prac_05/hex_colours.py
564
4.03125
4
""" Christopher Marriner CP1404 Practical Hex Colours Program """ HEX_COLOURS = {"black": "#000000", "blue": "#0000ff", "brown": "#a52a2a", "gray": "#bebebe", "green": "#00ff00", "orange": "ffa500", "pink": "#ffc0cb", "purple": "#a020f0", "red": "#ff0000", "Yellow": "#ffff00"} print(HEX_COLOURS) colour...
6b24fe621c6d1c38fd623b55aa4b100ec504907f
mmrubayet/python_scripts
/python_instittue_problems/sudoku.py
496
3.84375
4
import numpy as np def check_sudoku(grid): for i in range(9): # j, k index top left hand corner of each 3x3 tile j, k = (i // 3) * 3, (i % 3) * 3 if len(set(grid[i,:])) != 9 or len(set(grid[:,i])) != 9\ or len(set(grid[j:j+3, k:k+3].ravel())) != 9: return Fal...
76bb0552304d4dd2fed774da18e8298dfae0934c
benbenguo/python-tutorial
/d_python/test.py
139
3.625
4
#/usr/bin/python3 #_*_ coding:utf-8 _*_ arrel = [] mapel = {} for x in range(2): arrel = [x+1, x+2] mapel[x] = arrel print(mapel)
f610b1bf7118db0f2c1f591e1cf005310c2a2319
daniel-reich/turbo-robot
/GAbxxcsKoLGKtwjRB_12.py
631
4.15625
4
""" Create a function that takes a list of numbers and returns the **sum** of all **prime numbers** in the list. ### Examples sum_primes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ➞ 17 sum_primes([2, 3, 4, 11, 20, 50, 71]) ➞ 87 sum_primes([]) ➞ None ### Notes * Given numbers won't exceed 101. * A...
65c45dff5fe68ff783633fd9b45ecf78aa2ac0c7
tylerprehl/Computer-Science-Club
/Competitive Programming/ICPC_Regionals_Mar21/LongestCommonSubsequence.py
847
3.5625
4
''' You are given n strings, each a permutation of the first k upper-case letters of the alphabet. String s is a subsequence of string t if and only if it is possible to delete some (possibly zero) characters from the string t to get the string s. Compute the length of the longest common subsequence of all n stri...
cbf7788c604a7196377da4a80c67d571c7ae492c
jahick/pythonSamples
/myRange_noComments.py
1,099
4.03125
4
# File: testmyrange.py # Project 6.10 # Defines a function that behaves like Python's range function. def myRange (stop, start = 0, step = 1): if start == "" or start == None: start = 0 else: start = int(star...
2a034387c373102b1fb929210f907b3c8aade65e
nihalgaurav/pythonprep
/patternPrint.py
553
3.875
4
N = int(input()) for i in range(0, N): print(("*"*(2*i+1)).ljust(2*N, " ")) for i in range(0, N): print(("*"*(2*i+1)).rjust(2*N, " ")) for i in range(0, N): print(("*"*(2*i+1)).center(2*N, " ")) for i in range(0,N//2 +1): print(("*"*(2*i+1)).center(N, " ")) n = N for i in range(n): print(("*"*...
15a2f3d43785492602560433de0cd5df89842e1c
tonymontaro/Algorithmic-Problem-Solving
/Hackerrank/algorithms - practice/implementation/angry-professor.py
196
3.53125
4
def angryProfessor(k, a): n = 0 for i in a: if i <= 0: n += 1 print('YES' if n < k else 'NO') angryProfessor(3, [-1, -3, 4, 2]) angryProfessor(2, [0, -1, 2, 1])
8ca9e98fd282ab896258af2f90647db365274fa3
mohammedsameer99/python-learning
/bill.py
387
4
4
uscno = int(input("Enter the uscno: ")) name = input("Enter name: ") units = int(input("Enter the number of units: ")) if units <= 100: amount = units * 1.50 elif units <= 300: amount = 150 + (units - 100) * 2.50 else: amount = 650 + (units - 300) * 3.50 print('uscno: ', uscno) print("Name: ", name) pr...
3ce00c1b5e7efb0e291f30bbefe698caa35cda58
brennobrenno/udemy-python-masterclass
/Section 10/67.py
1,405
3.796875
4
## Writing Binary Files Manually ## # with open("binary", 'bw') as bin_file: # for i in range(17): # # bin_file.write(i) throws error # bin_file.write(bytes([i])) # Must use this form ([i]) # with open("binary", 'bw') as bin_file: # better, shorter # bin_file.write(bytes(...
9bb08347087393d2b9760a7ee23b44d46aaf74c3
MarDrugge/kyh-practice
/uppgift30.py
632
3.640625
4
def reg_plat(): reg_nr = input("Skriv Reg. Nr: ") print(f'Bokstäver: {reg_nr[0:3]}\nSiffror: {reg_nr[3:6]}') def numbers(): numbers = input("Ange tal med komma imellan: ") string_nr = numbers.split(',') num = [] for elem in string_nr: num.append(int(elem)) print(f'Första talet: {nu...
2f405369608f2fbd4e7e8db63ff07bbce0a384dc
Mike-Xie/LearningPython
/ex15.py
518
3.828125
4
from sys import argv #imports argument variable which olds arguments script, filename = argv # unpacks the arguments into seperate containers txt = open(filename) print "Here's your file %r: " %filename print txt.read() print "Let's mess around with it! What's the new first line?" txtChange = open(filen...
966e2097e4d21fcc0e3bc2b0302a424b458b40d2
sree-varma/CodeSignal
/Arcade/Core/extraNumber.py
447
4.03125
4
""" You're given three integers, a, b and c. It is guaranteed that two of these integers are equal to each other. What is the value of the third integer? """ def extraNumber(a, b, c): return a^b^c def extraNumber(a, b, c): for i in [a,b,c]: if [a,b,c].count(i)==1: return i def extraNumber(a...
daad5c687ec6f8c821077d1f4171260605651d9a
emerisly/python_learn
/python_learn/ShoppingCart_John.py
1,277
4.09375
4
# add n to arr n times def buildArr(arr, n, item): for x in range (n): arr+=item # increase capacity by 3 def increaseSize(capacity): capacity += 3 totalPrice = {} # add a quantity of item to cart def addToCart(item, unitPrice, quantity): cart = [] cart += item totalPrice = unitPrice * quantity * cart # pr...
36022c44b7fed4a84cf531324372fbc77c19ab78
adamtlee/python_playground
/fizzbuzz.py
461
4.125
4
''' FizzBuzz challenge: - For multiples of 3 print "Fizz" - for multiples of 5 print "Buzz" - If the number is a multiple of 3 and 5 print "FizzBuzz" ''' class FizzBuzz: def fizz_buzz(self, num): if num % 3 and num % 5 == 0: print("FizzBuzz") elif num % 3 == 0: print("Fizz...
1551574b7e406d85cf8281d8769b4c67c27b1e21
Nilutpal-Gogoi/DataStructures-Algorithms
/Two Pointers/4_RemoveTargetKeys.py
516
3.921875
4
# Given an unsorted array of numbers and a target ‘key’, remove all instances of # ‘key’ in-place and return the new length of the array. def removeTarget(nums, target): if len(nums) == 0 or len(nums) == 1: return len(nums) j = 0 for i in range(1,len(nums)): if nums[j] == target and nums[i...
12f04c827109c3fc787c97d5ecfac29ab2c32982
EduardoMachadoCostaOliveira/Python
/Calculadora.py
753
4
4
cabecalho = ' Python Calculator ' print(cabecalho.center(50, '*'), '\n\n', 'Selecione o número da operação desejada:') print('1 - Soma') print('2 - Subtração') print('3 - Multiplicação') print('4 - Divisão') opcao = int(input('Digite sua opção (1/2/3/4): ')) opcao if (opcao not in [1, 2 ,3, 4]): print('Opção Invá...
4aedb67767003929bd6105798feb0f683688e403
ccasil/AlgorithmPractice
/Algorithm Challenges (The Dojo Collection)/Python/Chapter1/Fundamentals-Part1/settingAndSwapping.py
289
3.5
4
def settingAndSwapping(): myNumber = 29 myName = 'Kyle' print ('My name is:', myName) print ('My number is:', myNumber) temp = myNumber myNumber = myName myName = temp print ('My name is:', myName) print ('My number is:', myNumber) settingAndSwapping()
9743257c9338d394f22a115716d8c4aa4215a78e
daniel-reich/ubiquitous-fiesta
/MNePwAcuoKG9Cza8G_20.py
147
3.78125
4
def build_staircase(height, block): op = [] for i in range(1, height+1): s = block*i + "_"*(height-i) op.append(list(s)) return op
9e93bad8c06df0df6de6c413b5e074c1b732e257
Akshay7016/Python-codes
/42 MethodOverloading.py
538
4
4
# Method overloading bydefault doesnt support in python we perform in different way class Overload: def __init__(self): self.m1=98 self.m2=48 #MEthod overloading def add(self,a=None, b=None ,c=None): s=0 if(a!=None and b!=None and c!=None): s=a+b+c ...
a1edd494571a8f487357b53f44020af096e791e3
jjudykim/MayaPractice
/maya_script_practice/for.py
2,429
3.828125
4
sum = 0 for i in range(11): sum += i print(sum) # 리스트의 내용을 출력하기 =================================== list = ["object_1", "object_2", "object_3"] for x in list: print(x) # for문을 사용해서 평균 구하기 input_list = [1, 2, 3, 4] avg = 0.0 for val in input_list: avg = avg + val print(val) avg /= len(input_list) pri...
e5f9878c3f698419ae25cca8a06cda83289f7bef
chintaujhwal/Python
/count_characters_1.py
89
3.5625
4
s = input("enter a string : ") for n in sorted(set(s)): print(f"{n} - {s.count(n)}")
2977c60d654ecc51a1def174a9126c9deedbcfef
fernandomarques/LaboratorioProgramacao
/Repetição/Lista/exercicio5.py
263
4.0625
4
# 1. Altere o programa anterior para mostrar no final a soma dos números. lim_inf = int(input("Limite inferior")) lim_sup = int(input("Limite superior")) soma = 0 for i in range(lim_inf, lim_sup+1): print(i,end=" ") soma += i print("Soma ", soma)
74c7055e0e9bd5dafaab14c394482e6a6fe47ee0
CraftedEngineer/code
/python_code/machine_learning_Lesson/set.py
568
4.3125
4
''' set数据类型的特点:无序的不重复元素的序列 1.可以使用大括号{} 2.set_param1 = set() ''' # set_param = {"1","2","3"} # print(set_param) # set_param1 = set() # print("1" in set_param) a = set("abcd") print(a) b = set("aqwe") print(a | b) #求并集 print(a & b) #求交集 #集合的CRUD my_set = set(("Tony","Jack","Robbin")) #set只能给它一个参数 print(my_set) my_se...
d2f23af05aa0909a63062646853d780dd46fa859
jack-davies/leetcode
/36.py
781
3.5
4
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: def isValid(segment: List[str]): # Checks a segment of nine elements for duplicates numbers = [n for n in segment if n != "."] return len(numbers) == len(set(numbers)) for row in range(9): ...
5d6b71efebb6a271a66b3250e0e7046636ba5f4d
alexlwn123/kattis
/Python/bitbybit.py
891
3.609375
4
def main(): n = int(input()) while n: bits = [-1 for i in range(32)] for i in range(n): line = input().split() if line[0] == 'SET': bits[int(line[1])] = 1 elif line[0] == 'CLEAR': bits[int(line[1])] = 0 elif line[0] == 'AND': i, j = int(line[1]), int(line[2])...
d47a09913cc22b85c290c87dc14c17b6a8960de9
Amankhalsa/pythonHero
/venv/Py_hero/Tic_Tac_game/board.py
4,194
3.921875
4
import random print("Tic-Tac-Toe game...!") game_input=["Null","x","0","x","0","x","0","x","0","x"] # board def board(game_input): print(game_input[7]+"|"+game_input[8]+"|"+game_input[9]) print(game_input[4]+"|"+game_input[5]+"|"+game_input[6]) print(game_input[1]+"|"+game_input[2]+"|"+game_input[3]) # bo...
7550190b284bf53f881a892fccb13a032568e8b2
wilsonleeee/Python
/scanner.py
1,030
3.515625
4
#/usr/bin/env python # _*_ coding:utf-8 _*_ #By:wilsonleee #date:2016-09-30 #主要完成信息的爬取,通常我们需要对爬虫捕捉的数据进行分析,处理,再次利用或者格式化, #显然我们不能只是把爬虫捕捉到的数据在内存中处理,然后打印在屏幕上,我将介绍几种主流 #的数据存储方法。爬虫处理数据的能力往往是决定爬虫价值的决定性因素,同时一个稳定的存 #储数据的方法也绝对是一个爬虫的价值体现,采用多线程爬虫创造多个并行线程协调工作也是 #绝对提高爬虫效率,降低失败率的好方法 #Python多线程使用 import time import ...
23fe1c8673dc2d598ebc61e3c33afc0a1390a093
PGuajardo/python-exercises
/control_structures_exercises.py
11,651
4.3125
4
# 1. Conditional Basics # a. prompt the user for a day of the week, print out whether the day is Monday or not print("What is the day of the week?\n") user_day = input("Enter day of the week: ") day_of_the_week = "Monday" while day_of_the_week != user_day: print("Thats Not the day of the week try again!\n") ...
faea2c20b87adb5cba6352c36397c10a585201fe
Abdulrauf-alhariri/Intermidate_level
/timer_version2.py
1,365
3.890625
4
from tkinter import * from tkinter import messagebox import time root = Tk() root.title("My timer") hours = StringVar() minutes = StringVar() seconds = StringVar() hours.set("00") minutes.set("00") seconds.set("00") hours_entry = Entry(root, textvariable=hours, font=("Arial", 18, ""), width=7) minut...
8e8cd9e5265942ee5a7535311d694a29738ff4ad
nbrahman/HackerRank
/03 10 Days of Statistics/Day05-03-Normal-Distribution-I.py
1,762
4.125
4
''' Objective In this challenge, we learn about normal distributions. Check out the Tutorial tab for learning materials! Task In a certain plant, the time taken to assemble a car is a random variable, X, having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours. What is the probability t...
f1c0ddf63936b051602c8d0cf94c2d7177d4479a
willcampbel/String-Jumble
/stringjumble.py
1,306
4.0625
4
""" stringjumble.py Author: will campbell Credit: david, mr dennison, ethan, stackoverflow Assignment: The purpose of this challenge is to gain proficiency with manipulating lists. Write and submit a Python program that accepts a string from the user and prints it back in three different ways: * With all letters ...
977fa6401d3c0d48237387bc8fb7c4325c6def0d
TITHI007/Python
/funct.py
490
4.1875
4
class Parent: def __init__(self,name): print("Parent __init__",name) class Child(Parent): def __init__(self): print("Child __init__") # method 1 to call parent class __init__ Parent.__init__(self,"Tithi") # method 2 to call parent class __init__ # here when you use super we don'...
2bd6d7ec5961289c58ecd11166f220504ea6761f
alanjia163/tensor
/204_activation.py
519
3.875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Jia ShiLin import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # fake data x = np.linspace(-5, 5, 200) # shape(100,1) # following are popular activation functions y_relu = tf.nn.relu(x) # y_softmax = tf.nn.sotfmax(x),sess sess = tf.Sess...
9038e3d6db2dd238fa21028b7d4b79101048f301
hrz123/algorithm010
/Week05期中考试题目/20. 有效的括号.py
3,037
3.84375
4
# 20. 有效的括号.py # 遍历 # 因为满足后进先出的特性,所以用stack做缓存 # 用一个hashmap存储对应关系 class Solution: def isValid(self, s: str) -> bool: hashmap = {")": "(", "]": "[", "}": "{"} stack = [] for ch in s: if ch not in hashmap: stack.append(ch) else: if not ...
4fc02ecfea2281391240907417905fb1026240c7
Rajiv-Nayan/HackerRank-Regex
/Introduction/Matching Word & Non-Word Character.py
118
3.921875
4
Regex_Pattern = r"\w{3}\W\w{10}\W\w{3}" import re print(str(bool(re.search(Regex_Pattern, input()))).lower())
bafc2078dc8d4ad1439a9e70fe14313d4b807810
zseen/hackerrank-challenges
/Python/GraphTheory/BFS/BFS_Hackerrank.py
8,250
3.65625
4
#!/bin/python3 import math import os import random import re import sys from collections import deque import unittest LOCAL_INPUT = "ON" class NodeWithDistance: def __init__(self, nodeId, distance): self.nodeId = nodeId self.distance = distance class Graph: def __init__(self): sel...
8448f34e278f582884fd4f8c54aaf85a2fa71241
TheXJT/python_study
/Chapter14/sentence_gen.py
498
3.515625
4
import re import reprlib from collections import abc RE_WORD=re.compile('\w+') class Sentence: def __init__(self,text): self.text=text self.words=RE_WORD.findall(text) def __repr__(self): return 'Sentence(%s)' % reprlib.repr(self.text) def __iter__(self): for word in self.words: yield word return ...
1dfb3869cf22676af3f2fd22d4df15af6d42d6aa
phoenixSP/Leetcode-Problems
/python/is_balanced_bst.py
806
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 07:04:24 2019 @author: shrey """ class Node: def __init__(self, data): self.val = data self.left = None self.right = None def isBalanced(root, height): if root is None: return True l_height=[0] r_height=[0] ...
8606612da1e7f3555890e2d54de37da869336940
Aasthaengg/IBMdataset
/Python_codes/p03001/s397622123.py
135
3.53125
4
W, H, x, y = [int(a) for a in input().split()] print(W * H / 2, end=' ') if 2 * x == W and 2 * y == H: print(1) else: print(0)
07fdbc12372fa99070802d4144644289b5a448d8
evanmags/hexipawn
/modules/computer.py
2,138
3.921875
4
from typing import List from random import choice class Computer: def __init__(self): self.pieces = [0, 1, 2] def move(self, state, connection): # generate all possible combinations all_moves = [] for piece in self.pieces: moves = self.piece_moves(state, piece) for move in moves: ...
0b20f1436379668cdd9f9fa9ca6ea631ed21569d
EduardoAlbert/python-exercises
/Mundo 2 - Estruturas de controle/066-071 Interrompendo repetições while/ex069.py
839
3.765625
4
pos = mais18 = totalHomens = totalMulheresMenosDe20 = 0 while True: pos += 1 print('-' * 30) print(f' CADASTRE A {pos}ª PESSOA') print('-' * 30) idade = int(input('Idade: ')) if idade > 18: mais18 += 1 sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [...
85f4ee2df3c7378a48a5b5d3ac608102436b43b1
Gustavokmp/URI
/1198.py
272
3.65625
4
while True: try: numeros = input() numeros = numeros.split() n1 = int(numeros[0]) n2 = int(numeros[1]) diferenca = n1 - n2 if diferenca < 0: diferenca *= -1 print(diferenca) except: break
4b8d96b17056b3f52dbe67ba457ce409efcb1a38
KotaCanchela/PythonCrashCourse
/6 Dictionaries/6-5 Rivers.py
796
4.875
5
# “Make a dictionary containing three major rivers and the country each river runs through. # One key-value pair might be 'nile': 'egypt'. river_loc = {'nile': 'egypt', 'seine': 'france', 'yangtze': 'china'} # Use a loop to print a sentence about each river, such as The Nile runs through Egypt. for key, value in river...
1b21cf5a1d489b552a004e09e844be8f09c9d810
jamiesonpower/Year9Design01PythonJP
/CylinderCalculatorGUI.py
900
3.671875
4
import tkinter as tk import math def calculate(): print("Calculate pressed") r = float(entr.get()) h = float(enth.get()) v = math.pi*r*r*h v = round(v,3) output.config(state="normal") outputValue = "Given\nradius:"+str(r)+" cm\nheight:"+str(h)+" cm\nThe volume is:"+str(v)+" cm cubed\n\n" output.delete(1.0...
31e53f19a054db69dc0eabe52c49aad7d821fb2f
xuecheng27/WWW21-Structural-Information
/utils/graphIO.py
666
3.5
4
import pandas as pd from igraph import Graph import numpy as np def read_edgelist(filepath, heads=['from', 'to', 'weight']): """Read a graph from its edgelist. Arguments: filepath (str): filepath of the edgelist heads (List[str]): titles of each column in the edgelist Returns: g...
67942a406d75335fb22f31206eac633e84ecf380
hackonion/algorithmics
/Palindrome_number.py
638
4.15625
4
#https://leetcode.com/problems/palindrome-number/ """ Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not. Example 1: Input: x = 121 Output: true Example 2: Input: x = -121 Output: false Ex...
6fc2e9a6da82708c5a0e37b4677f46f0ffbc5338
GabrielaZarzozaPerez/TAREA
/programa7.py
187
4.09375
4
print("Introduce una palabra") word = str(input()) alrevez_word = reversed(word) if list(word) == list(alrevez_word): print("Es un palindromo") else: print("No es un palindromo")
bad3944d0af0ccf0b80b03b1c0df1d5bae447a7c
rpassas/python_projects
/MBTA/subway.py
9,992
3.5625
4
''' Robert Passas CS5001 hw5 - subway provides directions for getting around via the Boston subway ''' LINE_NAMES = ['Red', 'Orange', 'Blue', 'Green'] LINES = [['Alewife', 'Davis', 'Porter', 'Harvard', 'Central', 'Kendall/MIT', 'Charles/MGH', 'Downtown Crossing', 'South Station', 'Broadway'...
60de43aed036f39c4c3beb970bffc221588e4519
u-chu/159
/159.py
702
3.8125
4
#!/usr/bin/env python ///numbers of days between dates # -*- coding: utf-8 -*- import datetime, sys d=sys.argv #~ print datetime.date.today() #~ [datetime.date.today() if x=='-now' or x=='-today' else x for x in d] for n, x in enumerate(d): if x=='-now' or x=='-today': e=datetime.date.today() #~ print e d[n]=...
e87babcc003b5bfb5716f1bbe4a54053d14779aa
OPENSOURCE-CORPORATION/OPEN-CALCULATOR.github.io
/Pthon_Logic/MATRIX/1_Form_a_matrix.py
309
4.03125
4
# A(i,j) = f(i,j) # Input # 1> Order # 2> Equation then substitute value of i,j wrt the Element and Store and Print (Equation may changte wrt relation among i and j) # Ex if i>j -> F(x) , i<=j -> G(x) print("Enter the Order of Matrix (i,j)") i = int(input("Enter i :")) j = int(input("Enter j :"))
4a509ced8a8371d22676ed9916b2c6281c81013e
HITLB17/basic_RL
/Q-learning maze/Q_Learning.py
2,154
3.625
4
"""" most of this code copied from morvan this part is a Q-learning algorithm for finding a optimal path in a maze Q(s,a) = Q(s,a) + learning_rate * [reward + gamma* max_a'{Q'(s',a')} - Q(s,a)] """ import numpy as np import pandas as pd class QLearningTable: def __init__(self, actions, learning_rate = 0.01, rewar...
937bce28f0381448fafea4e601455fce3f0ff8f7
jiangyihong/PythonTutorials
/chapter8/exercise8_10.py
409
3.609375
4
def make_great(magician_names): i = 0 while i < len(magician_names): magician_names[i] = 'the' + ' ' + magician_names[i] i += 1 def show_magicians(magician_names): for name in magician_names: print(name.title()) magician_names = ['Eisenheim', 'Sophie', 'Inspector Uhl', ...
4fac2c14a49b47449fc69dc9a007050e73c005c6
htg30599/SS1
/HW/w3/bubble_sort.py
331
3.59375
4
def bubbleSort(nlist): for passnum in range(len(nlist) - 1, 0, -1): for i in range(passnum): if nlist[i] > nlist[i + 1]: temp = nlist[i] nlist[i] = nlist[i + 1] nlist[i + 1] = temp nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70] bubbleSort(nlist) pr...
75c928133354f6526d37ae56fc7e4652dd9e6772
kfrancischen/leetcode
/2019_round/211_add_and_search_word_data_structure_design/solution.py
1,691
4.15625
4
class TrieNode(object): def __init__(self, char): self.char = char self.children_map = {} self.has_word = False class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode('') def add...
db9f20f65fab886d74f0b43402d23af8d96aff6b
rafaelperazzo/programacao-web
/moodledata/vpl_data/46/usersdata/99/18814/submittedfiles/funcoes1.py
493
3.875
4
# -*- coding: utf-8 -*- from __future__ import division #escreva o código da função crescente aqui #escreva as demais funções #escreva o programa principal n=input('Digite a quantidade de elementos das listas:') a=[] b=[] c=[] for i in range(0,n,1): a.append(input('Digite os valores de a:')) for i...
33c02705a95e4aa4b439691cfdca929e31bf27af
adamgleizer/pyta-server
/pyta_server/static/test/testsource2.py
3,219
3.8125
4
pair_combinations = ['AT', 'TA', 'GC', 'CG'] def is_base_pair(base1, base2): """(str, str) -> bool Returns True if the two chemical bases form a base pair >>>is_base_pair('A', 'T') True >>>is_base_pair('G', 'A') False """ return base1 + base2 in pair_combinations def is_dna(strand1...
3b635c222130900bf16749000f826c7e21f1c1a2
Vladimir-A2021/Geeckbrains
/Python/lesson03/exercize04.py
514
4.125
4
# Вариант №1 def my_func(x, y): return x ** y print(my_func(10, -2)) # Вариант №2 def power(a, n): if a == 0: return 0 elif n == 0: return 1 elif n == 1: return a elif n < 0: return 1 / (a * power(a, -n - 1)) else: return a * power(a, n - ...
184a058d7bdc0d23a6da7384133f59683b0086f1
kennyqqr/pythonHW
/basic/loop.py
185
3.921875
4
# while i = 0 while i < 6: i += 1 if i == 3: continue if i == 5: break # print(i) # for for x in range(3,40,3): print(x) else: print("end test")
cb1e9367fd0f701f514371c14883cb0906c8b7bb
goldenamir/python_Coding_with_Mosh
/Functions/04.KeywordArguments.py
219
3.75
4
def increment(number, by): return number + by result = increment(2, 9) print(result) # or we can write the above two lines with one line print(increment(2,by = 9)) # using by called keyword argument utilization
d0e5d8d615b28264870ca4e059db3ef04c38a907
MoraesCaio/Python-Graph-Algorithms
/kruskal.py
2,207
3.90625
4
"""Python Kruskal's algorithm implementation. Constructs a minimum spanning tree from a source vertex (node). The sum of the MST edges values are the minimum possible. Dev: Caio Moraes GitHub: MoraesCaio Email: caiomoraes.cesar@gmail.com """ from utils import parse_file def minimum_spanning_tree(input='', starting...
2cd35ba1491599bdc8a990301613227dd3484040
sunnyhyo/Problem-Solving-and-SW-programming
/lab3-8.py
222
3.59375
4
#lab3-8 name=input('이름: ') kor=int(input('국어점수: ')) eng=int(input('영어점수: ')) math=int(input('수학점수: ')) tot= kor+eng+math mean= float(tot/3) print('총점: %d'%tot) print('평균: %0.2f'%mean)
328db55556c99db0397b257b2b8409cbd026e942
MMyungji/algorithm2
/코테전문제풀이/11725_트리의부모찾기.py
856
3.515625
4
# 트리를 그래프로 구현 -> 부모노드 찾기(dfs,bfs) # 그래프처럼 순회하지 않고 한방향으로만 내려가므로 visited 리스트 필요없음 import sys input = sys.stdin.readline N = int(input()) graph_tree = [[] for _ in range(N+1)] parents = [[] for _ in range(N+1)] for _ in range(N-1): a,b = map(int,input().split()) graph_tree[a].append(b) graph_tree[b].append(a...
19ab9a5824747d97ebfca9a7a81d6217033f5cee
jalondono/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
649
3.90625
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) numaux = abs(number) % 10 if numaux > 5 and number > 0: print("Last digit of {:d} is {:d}".format(number, numaux), "and is greater than 5") elif numaux == 0: print("Last digit of {:d} is {:d}".format(number, (numaux)),...
04cd284978ab3e0a1d8e271c4a208075c4ad7430
ricardopeloi/analise_covid
/src/app.py
2,646
3.5
4
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np #from time import sleep @st.cache def carregaDados(caminho): dados = pd.read_csv(caminho) #sleep(3) simulando uma base que demora return dados def graficoComparativo(dadosUm, dadosDo...
73fc05db00fd46f34a05a977c3e7de2559ee8f06
WinDaLex/jacks-or-better-calculator
/Game.py
988
3.578125
4
# -*- coding: utf-8 -*- import time from random import Random from Card import * from Judge import * class Game(): desk = [] def init(self): self.desk = [] for suit in Card.suits: for rank in Card.ranks: self.desk.append(Card(suit, rank)) Random().shuffl...
8633c10595be7fd783e91a79d28549d91cd9d774
ibaydan/Work-Management
/main.py
2,044
3.671875
4
#!/bin/python3 from sys import stdin import pickle from datetime import date #DEFAULT VALUES database_name="db" projects=[] f=open(database_name,"r+") projects=pickle.load(f) f.close() def database_load(): pass #a=[["gcc","linux,programming"],[["12-07-2014",3],["12-06-2014",2]]] #b=[["vlan","network"],[[...
9526d123ae0572436181528704dd248c2e2958d4
gbrown022/automate
/ch3/third.py
3,117
3.90625
4
# GCB 3/31/2020 # # Questions # 1. Why are functions advantageous to have in your programs? # A. Functions are advantageous to reuse code, making it easier to # debug and trace # # 2. When does the code in a function execute: when the function is # defined or when the function is called? # A. Fun...
143902817f73474246cf75d67d873718b3dedeff
naitax/LeetCode---Python
/DataStructure/53_maximum_subarray.py
1,972
3.609375
4
#### best solution class Solution: def maxSubArray(self, nums: List[int]) -> int: final_max_sum = nums[0] current_max_sum = nums[0] for i in range(1, len(nums)): current_max_sum = max(nums[i], current_max_sum + nums[i]) final_max_sum = max(final_max_sum, cur...
64f0c1cb900f0684d46445aa57e049b5b63c8640
daniela2001-png/DATA_SCIENCE
/SEABORN/style_plot.py
1,581
3.515625
4
''' Cambio de estilo y paleta Volvamos a nuestro conjunto de datos que contiene los resultados de una encuesta realizada a los jóvenes sobre sus hábitos y preferencias. Hemos proporcionado el código para crear un diagrama de conteo de sus respuestas a la pregunta "¿Con qué frecuencia escuchas los consejos de tus padres...
e50aa81d3922e506a9dc2d43068c46ae96a37e40
samkeet/Python
/pyds-linkedlist.py
1,088
3.890625
4
class Node(object): def __init__(self, data): self.data = data self.next = None def setNext(self, node): self.next = node def setData(self, data): self.data = data def getNext(self): return self.next def getData(self): return self.data class LinkedList(object): def __init__(self, head = None): ...
f54a28e7a1e29ca43f04639f9295dd48d564372b
IgaIgs/PythonKataChallenges
/Kata8BurrowsWheelerTransformation.py
2,926
3.921875
4
import numpy as np from operator import itemgetter # Burrows-Wheeler-Transformation # The forward transformation works as follows: Let's say we have a sequence with length n, # first write every shift of that string into a n x n matrix: # # Input: "bananabar" # # b a n a n a b a r # r b a n a n a b a # a r ...
bad69d735a4536d8c4f556e326d36caba2429941
Msksgm/atcoder_msksgm_practice
/abc/054/C1.py
627
3.671875
4
def bfs(n, node, prev, visited, graph): visited.append(node) if len(visited) == n: return 1 res = 0 for edge in graph[node]: if edge == prev: continue if edge in visited: continue res += bfs(n, edge, node, visited, graph) # print(visited) ...
74c418d7f1d8b80f755babd389ebadf1578be7ca
Lexo80/Advent_2016
/Day2/AoC_Day2_1.py
1,370
3.5
4
""" Advent of code 2016 Day 2 part 1 """ from collections import namedtuple class Index(): """manage keypad index for Advent of code day 2 part 1""" def __init__(self): self.iH = 1 self.iV = 1 def update(self, s): if str(s).upper() == 'U': self.iV -= 1 if ...
3ef48d8bd94ca4d95a8a6fe3e21ec9948d4cbdd2
megha081298/Booking-movie-tickets
/main.py
4,549
4.21875
4
print("WELCOME TO THE EDYODA MOVIE BOOKING!!") print("WE BELIEVE YOU ENJOY THIS BOOKING PROCESS") class Theatre: def options(self): print("Please make the below choices:") ##CHOICES WHICH HELPS IN CALLING FUNCTION REPECTIVE OF CHOICES self.choice=int(input("\n1.Show seats:\n2.Buy a ticket:...
00baff55c2d538d0d5e539b0d8601067054341e6
yangzl2014/Study-Python
/flags/Sweden.py
694
3.609375
4
import uturtle turtle = uturtle.Turtle() def rect(x, y, color, x2, y2): width = abs(x2 - x) height = abs(y2 - y) turtle.pencolor(color) turtle.penup() turtle.goto(x,y) turtle.pendown() turtle.setheading(0) turtle.fillcolor(color) # turtle.color(color, color) turtle.begin_fill()...
9bcfde727e3514355e379bed47d58a61ea892487
jennyChing/leetCode
/189_rotate.py
512
3.71875
4
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. (cannot copy large portion of the array) """ if k != 0: new_start = len(nums) - k print...
47f8e467af7c4ab65edee2fb0d0ae18f295e72d8
gaoisbest/Basic-Algorithms
/Sorting_algorithms/Insert_sort.py
524
4.125
4
def insertion_sort(a): """left sequence of key element is already sorted""" n = len(a) # iterate over 1 to n-1 for j in range(1, n): # current element key = a[j] i = j - 1 # find approximate index of key while (i >= 0) and (a[i] > key): a[i+1] = a[i]...
8eee7579a090bbee85bfcacbe72bb67065200cc1
matthewsaporito/programmingproj1
/project2/Old_proj_2/methods_old/displayGrades.py
1,118
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 24 13:11:15 2020 @author: Matt Saporito """ import os import numpy as np import math as m import pandas as pd from pandas import isnull from pandas import NA from methods.utils import * #merge calculated finale grade with the rest of grade data to...
fae83cef353b782b09a66cfc6d9ad58b1a97ffaf
mbagrel1/isn
/td_cours/td_4_fonctions/td_4_ex_1.py
141
3.5625
4
def fonction(i): resultat=i*i-3*i+5 return resultat for i in range (-5,6,1): fonction(i) print "f(",i,")", "=", fonction(i)
5e1ded56a84f4781b4215c7e2adf53fdb734b165
varunsmurthy/python
/tutorials/1_google/6_dicts_files/count_words.py
856
3.921875
4
import sys def count_words_in_string(sentence, word_count_dict): for word in sentence.split(): word = word.lower() if word in word_count_dict.keys(): word_count_dict[word] += 1 else: word_count_dict[word] = 1 def count_words_in_file(filename): master_word_coun...
bd6d6f42c646307901efc158aaff852324257d6a
jianminchen/leetcode-8
/word_pattern_ii.py
2,117
3.546875
4
import re class Solution(object): def wordPatternMatch(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ self.dict1 = {} self.dict2 = {} return self.match(pattern, str) def match(self, pattern, str): tol =...
05ee82fb9e80d4d421339b70858250ce6b59c5fe
guyao/leetcode
/paint-fence.py
511
3.640625
4
# https://leetcode.com/problems/paint-fence # There is a fence with n posts, each post can be painted with one of the k colors. # You have to paint all the posts such that no more than two adjacent fence posts have the same color. # Return the total number of ways you can paint the fence. def solution(n, k): if n...
dd1845fc887d0bb88a94a3966607fb4fbbeb5a02
dickersonsteam/CircuitPython_Blink_with_switch
/main.py
487
3.609375
4
# main.py # CircuitPython Blink with Switch import time from digitalio import DigitalInOut, Direction, Pull import board led = DigitalInOut(board.D6) led.direction = Direction.OUTPUT switch = DigitalInOut(board.D9) # use pin D9 switch.direction = Direction.INPUT switch.pull = Pull.DOWN while True: if switch.val...
243744ae2e61da48b0a59953e4d6756164659831
TStalnaker44/interface_creator
/polybius/graphics/basics/mask.py
847
3.53125
4
""" Author: Trevor Stalnaker File: mask.py Models and manages a rectangle of varying transparency """ import pygame from .drawable import Drawable class Mask(Drawable): def __init__(self, position, dimensions, color, alpha, worldBound=False): """Initializes a mask object""" super().__init__("",...
726b72e702f7b1a329c12d2c716c0d0e99a43ec3
cyzhang9999/leet_code
/3numbs.py
6,160
3.515625
4
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: Chunyu Zhang @license: @file: 3numbs.py @time: 18/5/28 下午9:45 """ ''' 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2...
62dc5bf96b39e5cc7461f637e3bb76613cd1d5d9
arkajit/puzzles
/misc/palindromes.py
654
3.953125
4
class ListNode(object): def __init__(self, x): self.value = x self.next = None def printList(l): while l is not None: print l.value l = l.next def toArr(l): nums = [] while l is not None: nums.append(l.value) l = l.next return nums def fromArr(arr): nodes = [ListNode(n) for n in a...
183f01a0039700dd3f1c5923ad04abdd6d5afde0
michaeldavitt/COMP10280_Practicals
/Week 5/Sheet 15/p15p3.py
1,279
4.0625
4
""" Pseudo Code: Define a recursive function with one formal parameter n: if n is equal to 0: return 13 else if n is equal to 1: return 8 else: return f(n - 2) plus 13 multiplied by f(n - 1) Prompt the user for an integer while the user integer is greater than or equal to 0: ...
b03e2a09ccd152bedba9fcc6906c376b54b84b8d
DavidBetteridge/AdventOfCode2020
/Day12/day12.py
2,234
3.640625
4
moves = open('Day12/day12.txt').read().splitlines() def part_one(): x = 0 y = 0 direction = 90 for move in moves: action = move[0] amount = int(move[1:]) if action == 'N': y += amount elif action == 'S': y -= amount elif action ==...
5d0859b4c66fcd285d449aedf67c772061ed426e
Hyper10n/LearningPython
/letter_grade.py
465
3.859375
4
def letter_grade(score): try: score = float(score) if score > 1 or score < 0: raise Exception except: print("Enter a decimal number between 0 and 1 inclusive") if score >= 0.9: letter_grade = 'A' elif score >= 0.8: letter_grade = 'B' elif score >=...
f203663237f1031af349e19450beb8ec175968d1
muhit04/python_simple_tree_traversal
/tree_traversal.py
683
3.984375
4
class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def printInorder( node): if node: printInorder(node.left) print(node.val) printInorder(node.right) def printPreOrder(node): if node: print(node.val) printPreOrder(node.left) printPreOrder(node.right) d...
9189043265149955b30fabceba4f2dde8175a4fd
zizu1985/100daysOfCoding_Python
/day4/practice_32.py
137
4.03125
4
answer=str(input("Enter yes or no : ")) for a in answer: if a.isupper(): print("Next time please use all lower case letters")
0449fd9b5c8a7d5fe7cbe68a4a7488206a777eae
truexenom/First
/ClassWork_4.py
1,173
4.09375
4
#!/usr/bin/python #----------1----------- def random_number(): import random number =random.randint(1,100) print(number) #----------2------ def number_game(): while True: user_number=input("Please enter your number \n") if user_number == number: print("You ROCK! Correct nu...
fd9773cef9ab29e05a9901dd77d606773c533a27
artemburlaka/PythonPuzzles
/python-02.py
1,635
3.9375
4
import os.path def path_to_file(): path = input("Please enter a path to a file:\n\t") if os.path.isfile(path): statistic_from_file(path) else: print("The path is uncorrected!") path_to_file() if one_more(): path_to_file() return True def one_more(): answer_one...