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
919a3cd74aa220e6f25a708c95e3cbe0304b537e
jsdiuf/leetcode
/src/Binary Subarrays With Sum.py
1,755
3.640625
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-10-29 9:36 In an array A of 0s and 1s, how many non-empty subarrays have sum S? Example 1: Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] Not...
80c0e24423aa62f932ec85bb6c172dfac5c9244b
jsdiuf/leetcode
/src/Valid Parentheses.py
2,026
4.125
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-3 9:47 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets mus...
13fe4eb8b65055174cbe72726fa0b6996f1f6a29
jsdiuf/leetcode
/src/BSTIterator.py
1,378
3.984375
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-8 15:06 """ # Definition for a binary tree node class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BSTIterator(object): def __init__(self, root): ...
71901787aca536456c28b9a10bfbba70b8d816c6
jsdiuf/leetcode
/src/levelOrder.py
1,169
3.90625
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-5 23:46 """ # Definition for a binary tree node. import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root): ...
a1541f7548215a0d4f83164fa21404ebac3f1e9d
jsdiuf/leetcode
/src/Surface Area of 3D Shapes.py
1,832
3.96875
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-26 15:20 On a N * N grid, we place some 1 * 1 * 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j). Return the total surface area of the resulting shapes. Example 1: Input: [[2]] ...
6e0cb9e12e8a986bd2c28c3be40f706668d2a254
jsdiuf/leetcode
/src/Add Strings.py
1,050
4
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-11-1 10:01 Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does n...
40d26a6f9730deb24c97e2793f492213daac4437
jsdiuf/leetcode
/src/Sort Array By Parity II.py
1,137
4.1875
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-10-14 9:32 Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. You may return a...
50f390563d6a72bd23e3dd9bc98a195e26f64e84
jsdiuf/leetcode
/src/Reverse Nodes in k-Group.py
1,157
3.828125
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-4 21:01 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self, head, k): """ :type head: ListN...
f7891ddc60b4a4735bf95c336b47d3132d00288b
jsdiuf/leetcode
/src/hasCycle.py
770
3.84375
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-8-14 20:10 """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): """ :type hea...
f52e07423108de88b37dc1f3339c659b57c63d8d
juishah14/Accessing-Web-Data
/extraction_from_JSON.py
914
3.90625
4
# Assignment from University of Michigan's Coursera Course Using Python to Access Web Data # For this assignment, we must read JSON data from the URL using urllib, parse and extract comment counts from JSON data, # and compute the sum of the numbers in the file. # Test with http://py4e-data.dr-chuck.net/comments_564...
b276137b24d5cb17c66f09826e4cea9e3287ef2a
kriegaex/projects
/Python/projectEuler/59 XOR Decryption.py
1,027
3.59375
4
import re import collections f = open('p059_cipher.txt') cipher = f.read().strip().split(',') cipher = [int(x) for x in cipher] # the key has three digits, so we slice the list with interval of 3 c1 = cipher[::3] print(collections.Counter(c1)) c2 = cipher[1::3] print(collections.Counter(c2)) c3 = cipher[2::3] print(...
ebf01172e909a56151808d913ac0134040e29c52
kriegaex/projects
/Python/projectEuler/TriangularPentagonalAndHexagonal.py
716
3.625
4
import time start = time.time() def istriangular(number): x = 0.5 * ((8 * number + 1) ** 0.5 - 1) if x % 1 == 0: return True def ispentagonal(number): x = ((24 * number + 1) ** 0.5 + 1) / 6 if x % 1 == 0: return True def ishexagonal(number): x = 0.25 * ((8 * number + 1) ** 0.5 + 1...
e85c29d6ce48d148d5d4ea669b6ed113270e4cbb
kriegaex/projects
/Python/maze/DFS_maze.py
4,748
4.25
4
import turtle from random import randint from time import sleep from stack import Stack from queue import Queue '''Create a search list for positions yet to explore, add the entrance to this stack While the stack is not empty Remove the next position from the search list If it is the exit position, [n-1, n-1...
d0310e7d2731257d2fec4ec481675bef97b4833b
WL-Richards/Advent_of_Code_2020
/day_1/day1ExpenseReport.py
925
4.0625
4
def two_entry_2020_sum(lines): """Add up two entries to equal 2020""" for line in lines: line = line.strip() for line_1 in lines: line_1 = line_1.strip() if int(line) + int(line_1) == 2020: print("Two Entry Answer: " + str(int(line) * int(line_1))) ...
15def978d14ace9dc60ae954f9c18cb1184acff7
sauerseb/Week-Two-Assignment
/program3.py
439
4.34375
4
# __author__ = Evan Sauers (sauerseb) # CIS-125-82A # program3.py # # This program prompts the user for a distance measured in kilometers, converts it to miles, and prints out the results. # K= kilometers # M= miles # Ask user for a distance in kilometers # Convert to miles # (K * .62) K = eval(input("Please enter...
c4127600ef11e1237275d661cabc2ff833f505e2
pabloBrizzi/TAD_Sintaxis_2021
/TP1_p2/Prueba.py
685
3.703125
4
import os '''marcas = { 1: "ford", 2: "chevrolet", 3: "fiat", } print("Seleccione la Marca: \n\r") for i, j in marcas.items(): print(i, "-", j) t = int(input()) t=marcas[t] print(t) nroC = int(input("Ingrese el Num. de Cliente: \n\r")) dniC = int(input("Ingrese el Dni: \n\r")) dia = int(input("Ingre...
874d4c1c79838b35a49dc5676f286a2a0da5212a
pabloBrizzi/TAD_Sintaxis_2021
/TP_Integral/pruebaDatetime.py
1,459
4
4
import datetime '''x = [0,1,2,3] def imprime(x, i): return x[i] if(imprime(x,3) > imprime(x, 0)): print(imprime(x,3)) else: print(imprime(x,0)) ''' #Obtener el dia actual '''today = date.today() print(f"El dia de la fecha es {today}")''' #Obtener hora ''' hour = datetime.datetime.now() print(f"Hora: ...
1a703ea1833994726eb0782a8c6488d448e9ec49
trymtv/ProgProsjekt
/Prosjekt2 RPS/RPS.py
7,199
4.09375
4
""" Module for the game rock, paper, scissors. """ from random import randint from matplotlib import pyplot class Action(): """ Class representing an action. """ winning = {'R': 'S', 'P': 'R', 'S': 'P'} losing = {'R': 'P', 'P': 'S', 'S': 'R'} def __init__(self, action): self.action =...
12216ffb06cb8a9b906b95e4c1e671fe15c09aeb
dhivya2nandha/hunter
/11.py
87
3.59375
4
s=input() a=s.split(" ") for i in range(len(a)): t=a[i] print(t[::-1],end=' ')
5cadb775e37a1b12e7a6ac3145bf6a3b5194d7e7
Casyfill/Square_cities
/tools/csvDiff.py
1,112
3.640625
4
#!/usr/bin/env python #-*- coding: utf-8 -*- import pandas as pd import sys def diff(path1, path2): '''show difference between two csv''' name1 = path1.split('/')[-1] name2 = path2.split('/')[-1] df1 = pd.read_csv(path1) df2 = pd.read_csv(path2) print '%s : %d rows' % (name1, len(df1)) print '%s : %d row...
175ffaedb9ab219498d94b28ab1415f63cb28b5b
mauleypeach/pythonthehardway
/learnpythonthehardwayorg/ex.py/ex33c.py
172
3.921875
4
def max_of_two(x,y): if x > y: return x return y def max_of_three(x, y, z ): return max_of_two(x, max_of_two(y, z )) print (max_of_three(3, 6, -5))
0427392f6891d84022d259c5664c2da62601ca38
mauleypeach/pythonthehardway
/learnpythonthehardwayorg/ex.py/ex18.py
541
4.03125
4
# this is like you scripts with argv. def print_two(*args): arg1, arg2, = args print "args1: %r, arg2: %r" %(arg1, arg2) # ok, that *args is actually pointless, we can actually just do this. def print_two_again(arg1, arg2): print "args1: %r, args2: %r" %(arg1, arg2) # this one takes one argument. def pri...
c96d3f41d200efc0cc4b25e98659131a020e2934
mauleypeach/pythonthehardway
/learnpythonthehardwayorg/ex.py/ex32_b.py
163
3.890625
4
elements = [] for i in range(0,6): print "Adding %r to elements list." % i elements.append(i) for i in elements: print "Element list %r." % i
6654dab9c8608f749f3b9d537aac73242777f0b4
mauleypeach/pythonthehardway
/learnpythonthehardwayorg/ex.py/ex33.py
830
4.09375
4
i = 0 numbers = [] x = int(raw_input("What is the max number to count too? \n>")) y = int(raw_input("What is the increment to use? \n>")) while i < x: print "At the top i is %d" % i numbers.append(i) i = i + y print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The Numbers: ...
3381cbb4e997978ffa139b47868fdb282a00a7db
langestefan/pyluhn
/luhn/luhn.py
1,094
4.25
4
"""Calculate checksum digit from any given number using Luhn algorithm.""" def create_luhn_checksum(number): """ Generates luhn checksum from any given integer number. :param number: Number input. Any integer number. :return: Calculated checksum digit """ str_number = str(number) n_digits ...
c0c74fe14d6ff278ee0bc0396d298cf903aa505f
kingsleyndiewo/codex-pythonium
/simple_caesar_cipher.py
806
4.40625
4
# A simple Caesar cipher # Author: Kingsley Robertovich # Caesar cipher is a type of substitution cipher in which each letter in the plaintext is # 'shifted' a certain number of places down the alphabet. In this example we use the ASCII # character set as our alphabet def encipher(clearText, offset = 5): cipherTex...
78cbbd44e7510f39fedfc702c4493611d13ec6dd
blue-view/blue-view.github.io
/python/prime.py
263
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 07 14:00:08 2018 @author: Administrator """ x = 2 count = 0 while count < 50: for i in range(2, x): if x % i == 0: break else: print x, 'is a prime' count += 1 x += 1
a939e7b5a4052c58e4bd88c45ab9cd4dcf7305e0
JongeManMetBaard/van-input-naar-output
/pizzaCalculator.py
708
3.890625
4
#Ali, Goutsal #Pizza calculator SmallPizza = (input("Hoeveel small pizza wilt u? ")) MediumPizza = (input("Hoeveel medium pizza wilt u? ")) largePizza = (input("Hoeveel large pizza wilt u? ")) small = 8.99 medium = 10.49 large = 12.99 TotaleKostenSmall = small * float(SmallPizza) TotaleKostenMedium = medium * float(...
3a42842e16a4d505918b27079a8368e380352cac
danielmohansahu/ENPM673
/project3/Code/test.py
849
3.6875
4
"""Test our ExpectationMaximization algorithm. """ import random import numpy as np from matplotlib import pyplot as plt from custom.maximize import ExpectationMaximization as EM NUM_GAUSSIANS=3 NUM_POINTS=100 if __name__=="__main__": K = NUM_GAUSSIANS N = NUM_POINTS # generate a random distribution ...
11808f8c4804412597967cca94428c2889e93ced
sahilchauhan1/Image-Editor
/colflower.py
4,930
3.609375
4
# name: File path of the pgm image file # Output is a 2D list of integers def readpgm(name): image = [] with open(name) as f: lines = list(f.readlines()) if len(lines) < 3: print("Wrong Image Format\n") exit(0) count = 0 width = 0 height = 0 for line in lines: if line[0] == '#': ...
10e2411aa4b0fbda41ccf72f5851562f4799306e
KDamsgaard/DataStructures
/Archived/old_avl_tree.py
2,349
3.859375
4
# #Kristian Knudsen Damsgaard, 2019 # #An AVL implementation for the binary search tree. # # from binary_search_tree import BinarySearchTree as BST from node import Node class AVLTree(BST): def __init__(self): #Since no database exists the incrementing key is set to 0. self.__incrementingKey = 0 ...
cc0eeabdb74aa2e0cef6d7ae2dbbffe315a5a53f
ElDanilova/AT_School
/task_3.3.py
565
4
4
def season (n): n = int(n) if n == 1 or n == 2 or n == 12: return ("зима") elif n == 3 or n == 4 or n == 5: return ("весна") elif n == 6 or n == 7 or n == 8: return ("лето") elif n == 9 or n == 10 or n == 11: return ("осень") # Программа print("Добро пожаловать! Пере...
3e23a8b4d289649dbd81fb4fba74a9d66c08fbd1
vinayakakote9632724944/vinayaka-kote
/8python.py
238
4.0625
4
print("welcome to python lab") a=(input("enter value for a:") b=(input("enter value for b:") #add a and b if(a>b): print(a,"is greater than",b) elif(a==b): print(a,"is equal to",b) elif(b>a): print(b,"is greater than",a)
d3aaa5e389de735ed6c011afe7e3bf30325aee40
firdevsmersin/Trie
/Trie.py
9,673
3.53125
4
import sys import os import re import glob class Trie(object): def __init__(self): self.root = TrieNode(None,0) def add_word(self, word): """add word to trie""" self.root.add_word(word) self.root._add() def all_words_in_trie(self): """print all keys from tree in asc...
6e178d82ba9280a6752c5fbff8d5856cfe0db2cf
adam-barnett/LeetCode
/word-break.py
1,691
3.984375
4
""" Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code". Problem found here: http://oj.leetcode.com/pr...
8d3db6b8f2e9c64fa6ab630286f8c7cf8a96f21a
adam-barnett/LeetCode
/populating-next-right-pointers-in-each-node.py
3,837
4.46875
4
""" Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may onl...
d4cabe574a786147dba2fbb9cee912e24a4a120d
adam-barnett/LeetCode
/unique-paths-ii.py
1,689
4.125
4
""" Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, There is one obstacle in the middle of a 3x3 grid as illustrated below. [[0,0,0], [0,1,0], [0,0,0]] The...
4d17824042c17b5b2ab6abdfb9a9bd9fb97cf707
adam-barnett/LeetCode
/minimum-path-sum.py
1,356
3.828125
4
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Problem found here: http://oj.leetcode.com/problems/minimum-path-sum/ """ """ Here my solution as...
93e057cd3712801682e4a8314524ad8b932fb534
adam-barnett/LeetCode
/word-search.py
2,452
3.796875
4
""" Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [["ABCE"],["SFCS"],["ADEE...
4498d0ffde03918f755b2aa7df565030062cc86b
adam-barnett/LeetCode
/minimum-depth-of-binary-tree.py
1,294
4
4
""" Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Problem found here: http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/ """ # Definition for a binary tree node class TreeNode: def __i...
260f858cc142488d0ae7a0777656ada14fca0c55
ronfletcher1/python-intro
/text_rpg/goblin_fight.py
2,980
3.84375
4
# This is a procedural approach to a text based rpg # The hero is fighting the goblin. # The hero has the option to: # 1. Fight # 2. Dance # 3. Flee : # Go get the os module from pythom import os # os.system(os) #will take any linux command # and if python can run it, it will print """ Luv Dragons _) ...
d5234edd6db2c6e312017f22a6fb07a0c0b3e887
swordwielder/codementor
/oop/customer.py
436
3.640625
4
class Customer: def __init__(self, _name, _contact): self._name = _name self._contact = _contact def name(self): return self._name def contact(self): return self._contact def set_contact(self, contact): self._contact = contact def __str__(sel...
ee15deb7b4cf947b117310c5203b5af7cb4879ee
KonradMarzec1991/books_examples
/Chapter 14 - Iterables, Iterators and Generators/9 - Yield from.py
869
3.765625
4
import random def chain(*iterables): for it in iterables: for i in it: yield i s = 'ABC' t = tuple(range(3)) print(list(chain(s, t))) def chain2(*iterables): for it in iterables: yield from it # syntactic sugar s = 'ABC' t = tuple(range(3)) print(list(chain2(s, t))) def d6...
ac97296d4597700516f8bbc160fc8cd7d993e5e2
abnerwang/algorithm008-class02
/Week_01/283.移动零.py
883
3.53125
4
# # @lc app=leetcode.cn id=283 lang=python3 # # [283] 移动零 # # https://leetcode-cn.com/problems/move-zeroes/description/ # # algorithms # Easy (60.23%) # Likes: 552 # Dislikes: 0 # Total Accepted: 129.8K # Total Submissions: 215.2K # Testcase Example: '[0,1,0,3,12]' # # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相...
71a1e30327e58b46a8851048359e520621d8f088
miaoranren/calculator-2-exercise
/calculator.py
1,411
4.375
4
"""A prefix-notation calculator. Using the arithmetic.py file from Calculator Part 1, create the calculator program yourself in this file. """ from arithmetic import * while True: response = input("> ") tokens = response.split(' ') if tokens[0] == 'q': print("You will exit!") break ...
a7a978643dd23bede4c14e15db0e05ea74c27b9e
paabes/AudioSignal-Deep-Learning
/3 - backpropagation from scratch /mlp_from_scratch.py
2,596
4.03125
4
import math import numpy as np class MultiLayerPerception: def __init__(self, num_inputs=3, hidden_layers=[3, 3], num_outputs=2): """Constructor for the MLP. Takes the number of inputs, a variable number of hidden layers, and number of outputs Args: num_inputs (int): Number...
d81bf1b7d55ebe30e388365e7b0fdcb912fc49fd
pwithnall/namesworth
/strategies/markov_bigrams.py
2,537
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 import random """ Name generation strategy building a Markov chain of the bigrams in the corpus. """ class MarkovBigramsStrategy: def __init__(self, corpus): self.corpus = corpus self.chain = MarkovChain() """ Train th...
c032b879a16324b62abddf04c8e1ba33d9910b99
jothivarshini/A-Z_Pythonpractice
/Python Workbook/Dictionaries/scrabble.py
353
3.984375
4
points = {"A": 1, "B":2, "C" : 3, "D": 4, "E":5, "F":6, "G":7, "H":8,"I":9,"J":10,"K":11,"L":12,"M":13,"N":14,"O":15,"P":16,"Q":17,"R":18,"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26} word = input("Enter a word: ") uppercase = word.upper score = 0 for ch in uppercase: score = score + points[ch] print(wor...
cc49f9839fd7b515915be34b2f02e5d86af2dc74
jothivarshini/A-Z_Pythonpractice
/Dictionaries/test10.py
125
3.6875
4
my_dict={'a' : 100, 'b' : 200, 'c' : 300} result = 1 for keys in my_dict: result = result * my_dict[keys] print (result)
0ea923b52dc18d777d9f8b05fcc0f5e7498ecc6b
jothivarshini/A-Z_Pythonpractice
/Dictionaries/test.3.py
156
3.828125
4
d={1:10,2:2-0,3:30,4:40} print (d) x=int(input()) def key_dict(x): if x in d: print ("key present") else: print ("key absent")
ce098f0395d6a77a640644c9f19b2954f9957cfd
jothivarshini/A-Z_Pythonpractice
/Dictionaries/test7.py
83
3.5625
4
dict1={'a':10,'b':20} dict2={'h':4,'j':6} d=dict1.copy() d.update(dict2) print(d)
d212df181e5777ca7eb0386fd9293ce6b0617a79
jothivarshini/A-Z_Pythonpractice
/Hackerrank & Extras/sum.py
97
4.15625
4
print ('Enter radius') r=int(input()) pi= 3.142 Area=pi*r*r print ('Area of the circle is',Area)
5229eab3b9429ee9e2091472a70f830ddf3591b3
jorge-jah/jokenpo
/jokenpo.py
3,590
3.796875
4
def jogo_jokempo(): #função onde tem o código do jogo. print('Olá!') player1 = input("Digite o nome do Jogador 1: ") player2 = input('Agora digite o nome do Jogador 2: ') print() print('Ok', player1.title(),'e', player2.title(),'vamos jogar...') print() print(" *** PEDRA-PAPEL-TESOURA ***") print() p...
9162b97070d6ca218d36b7fb44401d7ae6ea6ca2
happysmile27/Conprehencions_day26
/exa3.py
286
3.59375
4
with open("file1.txt", "r") as file1: # file1_data = file1.readlines() list1 = [int(num) for num in file1] print(list1) with open("file2.txt", "r") as file2: list2 = [int(num) for num in file2] print(list2) result1 = [n for n in list1 if n in list2] print(result1)
822cb131b8300f05ac734bdb23c26b739cc72f8b
vnb/Leet-Code-Problems
/Dynamic Programming/1025 Divisor Game.py
1,184
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < N and N % x == 0. Replacing the number N on the chalkboa...
189c89c19fb490f76971eb96992591b7c56905a2
vnb/Leet-Code-Problems
/Tree/983 Range Sum of BST.py
1,209
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' link: https://leetcode.com/problems/range-sum-of-bst/ Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. ''' # Definition for a binary t...
d09c85f2a1045ba910cc619b3c5415c08453fe4b
dwbarne/PYLOTDB
/PylotDB/Modules/checkbutton_2.py
2,307
3.78125
4
# checkbutton frame using python & Tkinter # date: 070808 # This file sets a variable to true or false, depending on whether the box is checked or not, respectively from Tkinter import * import tkFont import string win=Tk() #root.title=("Send email to me?") class CheckButton_2(Frame): def __init__(self,window...
1bf3cb8fbd4e2f0e76933b4a40fbed5f0bc290e1
IXIXIXIXIXIXIXIXIX/hangman
/tests/player_test.py
2,590
3.6875
4
import unittest from src.player import Player from src.game import Game class TestPlayer(unittest.TestCase): def setUp(self): self.player = Player() self.game = Game("primary") def test_state_is_zero(self): self.assertEqual(0, self.player.state) def test_guess_letter(self): ...
1a1fb73b1656a05f8a4bbfa17205361d96fc95c3
alexvmk/algorithms
/py/Seattle/pythonProj/Easy/PascalTriangle.py
703
3.5
4
class Solution: # https://leetcode.com/problems/pascals-triangle def calc_triangle(self, n: int) -> [[int]]: result = [[1]] if n <= 1: return result result.append([1, 1]) for i in range(2, n): result.append([]) for j in range(0, i + ...
552ea78d26b1ee7fbe6de3808a4ecb31798171f4
alexvmk/algorithms
/py/Seattle/pythonProj/Sort/MergeSort.py
984
3.640625
4
from typing import List class Solution: def sort(self, nums: List[int]) -> List[int]: # if length 1 the return if len(nums) == 1: return nums # split array into two subareas mid = len(nums) // 2 left = nums[:mid] right = nums[mid:] ...
d1c49a71cc2440deb72d20b9ff3280310c430f54
jason-beh/CS50
/pset6/sentiments/analyzer.py
1,236
3.640625
4
# analyzes twitter comments import nltk positive_words = [] negative_words = [] class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer.""" self.positives = positives self.negatives = negatives with open(positi...
f6cf306ac35e52d716f1070c32e70f0f1b7381a9
freshskates/Encryption
/cipher.py
1,317
3.8125
4
# Robert Cacho Ruiz class Encryption: @staticmethod def getIndex(character): return 26 - (122 - ord(character)) - 1 @staticmethod def getChar(index): return chr(97 + index) @staticmethod def caesar(phrase: str, mode=1) -> str: # mode: 1 cipher # mode: -1 decip...
896c5d1adeafa4ca6833465080583d18dc10dea3
gyuruza921/p139
/main2.py
1,489
4.15625
4
# coding : utf-8 # 文字コードの宣言 #買い物プログラム # 残金 money = 0 # 商品毎の単価 # りんご apple = {"name": "りんご", "price": 500} # = {"name": "", "price": } # バナナ banana = {"name": "バナナ", "price": 400} # ぶどう grape = {"name": "ぶどう", "price": 300} # 果物のリスト fruits = {"apple":apple, "banana":banana, "grape":grape} print(fruits) # 個数 cou...
643a787819b8aebe4b9db6a6e5b4a03dfa2c7bb2
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W9_Help Session_Q2.py
1,281
3.734375
4
import math class QuadraticEquation(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def get_roots(self): if self.b ** 2 - (4 * self.a * self.c) >= 0: delta = math.sqrt(self.b ** 2 - (4 * self.a * self.c)) return (-self.b - delta) ...
9b8801646badd5aeb6de9c19820e6b6b4b8bfeb2
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W9_Quiz.py
467
3.828125
4
class Triangle(object): def __init__(self, color='green', filled=True, side1=1.0, side2=1.0, side3=1.0): self.color = color self.filled = filled self.side1 = side1 self.side2 = side2 self.side3 = side3 def perimeter(self): return self.side1 + self.side2 + self.si...
ca9ff4e3ddc26bc6918fd857204f7025096527c5
jelsaoverlandfrost/frozen-digital-world-code
/Answers for Midterm/MidTerm - Q6 - c.py
290
3.765625
4
#### This problem will be graded manually. #### Please ignore the points given out by Tutor. def get_friends(G,node): final_list = G[node].keys() return final_list print get_friends({0: {1: 1, 2: 1, 3: 1}, 1: {0: 1, 48: 1, 53: 1}, 2: {0: 1}, 3: {0: 1}, 48: {1: 1}, 53: {1: 1}}, 2)
a2a7d4c949ebbc7728e2c47297e81d07c7a9601e
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W4_HW3.py
291
3.84375
4
def multiplication_table(N): if N <= 0: return None else: output = [] for i in range(0, N): output.append([]) for j in range(0, N): output[i].append((i+ 1)* (j+ 1)) return output print multiplication_table(-1)
f8cf363c1a6371da098ee3ab3bbcaf44b0311f13
jelsaoverlandfrost/frozen-digital-world-code
/Answers for Midterm/MidTerm - Q3.py
215
3.515625
4
#### This problem will be graded manually. #### Please ignore the points given out by Tutor. import math def area_r_polygon(n, s): area = n * (s ** 2) / (4.0 * math.tan(math.pi / n)) return round(area, 3)
352aa32fe5ea4780c9261c1a9a1898bfc75c7e37
jelsaoverlandfrost/frozen-digital-world-code
/Answers for Last Year Finals/Final_2013_Q2.py
786
3.8125
4
# Another choice is to declare an Global Variable here # count = 0 # Visitor class class Visitor(object): # A variable to count the number of calls for a visitor callCount = 0 # Piazza! This is a property of the Class Visitor count = 0 # Initialization def __init__(self, name='Visitor'): ...
c6f355b8d077304dfc323ce7cacec33e68dc7fab
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W3_HW2.py
1,070
4.09375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Feb 7 13:02:53 2017 @author: frozen """ def temp_convert(type, temp): if type == "F": return celsius_to_farenheit(temp) elif type == "C": return farenheit_to_celsius(temp) else: return None ######### Ignore cod...
8ebf36c9826b755ab281145e7bb8bcd0ed188cb1
jelsaoverlandfrost/frozen-digital-world-code
/1D Project/Try_test.py
846
3.609375
4
import better_exceptions alphabet = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25} inverse = {v: k for k, v in alphab...
84845dd6779200e57d814dfc8ce5905b8f04f501
jelsaoverlandfrost/frozen-digital-world-code
/Answers for Midterm/MidTerm - Q6 - a.py
316
3.546875
4
#### This problem will be graded manually. #### Please ignore the points given out by Tutor. def get_nodes(fid): list_nodes = fid.readlines() final_list = [] for i in list_nodes: string_list = i.split() final_list.append((int(string_list[0]), int(string_list[1]))) return final_list
91e955337ac2dd11d330644654abdce9c729abf2
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W4_Q3.py
872
4.09375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Feb 16 15:27:54 2017 @author: frozen """ ####### Your function should return a tuple containing a list of average ##### ####### and the overall average, e.g., ([3.5,6.0,1.4], 3.625) ################ def find_average(listOfLists): listOfAvg = [] ...
43ac3d9bd73d36764571f21addefa170f4b31843
jelsaoverlandfrost/frozen-digital-world-code
/Exercises/W4_HW4.py
509
3.734375
4
def most_frequent(numList): countList = [] numberList = [] finalList = [] for i in range(len(numList)): count = 0 for j in range(i, len(numList)): if numList[j] == numList[i]: count += 1 countList.append(count) numberList.append(numList[i]) ...
63c103f06bd1b37c37fc6bccac541e8cd6e4fe08
Mustafalw02/MustafaPythonAssignment
/exercise_ii_a/add_one..py
379
3.625
4
# -*- coding: utf-8 -*- #Taking Input x = input('Enter a five digit number: ') sum = 0 #Calculating Reverse d = int(x[0]) d = d+1 if d<9 else 0 sum += d * 10**4 d = int(x[1]) d = d+1 if d<9 else 0 sum += d * 10**3 d = int(x[2]) d = d+1 if d<9 else 0 sum += d * 10**2 d = int(x[3]) d = d+1 if d<9 else 0 sum += d * 10...
c2f3e0c669695c7b1680ee9af96e835df1344c7b
Mustafalw02/MustafaPythonAssignment
/exercise_ii_b/total_marks.py
562
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 14 18:59:13 2019 @author: mustafa """ #Taking Input marks = input("Please enter the marks of 5 subjects and 3 practicals: ") marks = marks.split(',') th_marks = int(marks[0]) + int(marks[1]) + int(marks[2]) + int(marks[3]) + int(marks[4]) pr_marks = int(marks[5]) + int(...
96e58f05ae73d97005efcddd72d84b36bd3cac25
jagins/code-challenges
/leetCode/lengthofLastWord.py
173
3.578125
4
def lengthofLastWord(s: str) -> int: array = s.split() if len(array) > 0: last_index = len(array) - 1 return len(array[last_index]) return 0
ed99bf87029a09f750a3adc06636c9e82a37ecff
SBenkhelfaSparta/eng89_python_oop
/snake.py
485
3.609375
4
# ### Snake class # #### Create a Snake class from reptile import Reptile class Snake(Reptile): def __init__(self): super().__init__() self.forked_tongue = True self.cold_blooded = True def use_tongue_to_smell(self): # Adding some specific methods/behaviours return " *Hiss* ...
0343fb212950495fc52349a8bbc2067c18f586c0
l181241khuramraza/Python-Practice-Work
/Guess_a_Number_game_using_functions.py
1,077
4
4
###### Game: 'Guess a Number' using Function ####### import random secretNumber = random.randint(1,100) ## randit return random number btwn 1 and 100 including them ### function definition def guessANumberGame(): global numberOfGuesses ## global variable statement for numberOfGuesses in range(1,7): gu...
0d5918c1c7bfcb45e76cf6ce8e43296e9ceaf801
hearsid/hackerrank
/__python/py-strings/swap-case.py
190
3.78125
4
def swap_case(s): newString = ""; for i in s: if(i.istitle()): i = i.lower() else: i = i.upper() newString+=i; return newString
c42c698a2d072fab5ea5f38cc07c8a81d5c55382
dodo4910/Zerojudge.tw
/a010.py
1,149
3.734375
4
# 本題解的太冗長,程式碼應該有精簡空間 import sys for num in sys.stdin: num1 = int(num) num2 = 0 save = [] #使用List while(num2==0): for i in range(2,num1+1): if num1 == i: save.append(str(i)) num2 =1 break elif num1 % i == 0 and num1 != i: ...
f91c04c007aaaaba64710105a973cb14a8b369ad
dodo4910/Zerojudge.tw
/a015.py
684
3.765625
4
#矩陣的翻轉 import sys NumList = [] for num in sys.stdin: NumList += num.split() isover = True while(isover): row = int(NumList[0]) col = int(NumList[1]) ori = [[0]*col for i in range(row)] plus = 0 for j in range(row): for i in range(col): ori[j][i] = NumList[2+plus] ...
e9036007b03382735d1522f0d219438076cc99ed
Parthu8108/Mangrove-loss-mapping-using-Remote-sensing-and-GIS
/Gui/Demo.py
268
3.5625
4
from tkinter import * top = tkinter.Tk() var = StringVar() label = Label( top, textvariable=var, relief=RAISED ) var.set("Layout") C = tkinter.Canvas(top, bg="White", height=1000, width=1000) label.pack() C.pack() # Code to add widgets will go here... top.mainloop()
befaf447b804416f94809a4ea5aeefd135451f25
buzycoderscamp/ML-Workshop-Samlpes-Day2-
/Visualization/Plot.py
467
3.546875
4
from matplotlib import pyplot import math def sine(xvals) : y = [] for i in xvals : y.append(math.sin(i * math.pi / 180)) pyplot.plot(xvals, y) pyplot.show() def plotLine(x, m, c) : y = [(i*m) + c for i in x] pyplot.xlabel("X axis") pyplot.ylabel("Y axis, y = mx+c") pyplot.xlim([...
0787e0898397506356f6680439ace557d315d8db
kporwit/python-hangman
/functions.py
3,555
4.03125
4
def word_check(given_word): if( not given_word): print "Word must conatin only letters. Try again." return 1 elif( len(given_word) < 4): print "Please try harder! At least four signs." return 1 elif( len(given_word) > 40): print "Hold on cowboy, that is a really long ...
6f13d7ddf71e1139bbdd95565507b3fba35f37b4
cesarcoboscv/prof-python
/closure_division.py
461
3.84375
4
def make_divisionby(n: int): def division(integer) -> float: assert type(integer) == int, "Solo puedes ingresar números enteros" return integer / n return division def run(): division_by3 = make_divisionby(3) print(division_by3(18)) division_by5 = make_divisionby(5) pr...
24f47ff892079e3272f9dc1aefd3e110f2d84272
strikingraghu/Python_Labs
/02_Namespaces_Scope.py
1,065
4.03125
4
""" A namespace is a system to have a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go through an example, a directory-file system structure in computers. """ # Variables in Global &...
e8860d7c2095fa654b7e6ed28f9a60ce73931491
ptg251294/DailyCodingProblems
/ParanthesesImbalance.py
801
4.3125
4
# This problem was asked by Google. # # Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make # the string valid (i.e. each open parenthesis is eventually closed). # # For example, given the string "()())()", you should return 1. Given the string ")(", you sh...
c56e83834fe1e889bd985dd43b7d9d62976554d2
ptg251294/DailyCodingProblems
/One2OneCharMapping.py
770
4.125
4
# This problem was asked by Bloomberg. # # Determine whether there exists a one-to-one character mapping from one string s1 to another s2. # # For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d. # # Given s1 = foo and s2 = bar, return false since the o cannot map to two ch...
260dca4fe4ddf37786b9c3e72ae50b59525a33c6
kuzmin-sa/mnog_test
/4 lingual leo+.py
874
3.78125
4
#Задание 4 "Словарь с рандомной выдачей" import random amount_of_words = input("Как много слов вы хотите занести в словарь \n:") aow = int(amount_of_words) slovar = {} for i in range(aow): key = input("Введите слово на английском \n:") value = input("Введите слово на русском \n:") slovar[key] = value ke...
487c24805b8ac4e7025373ca00f9c5bcc5ece4d9
kbarta8/CPSfinalproject
/user.py
1,969
3.59375
4
import re import sys def askUserFirst(): print("Welcome to your IoT device! Please enter your login info: \n") username = raw_input("Enter your username: ") password = raw_input("Enter your password: ") checkDefPass(username, password) def checkDefPass(user, pwd): if user == "admin...
fdf23badd63de15ca49deeeb23f7af38f7f8d888
591751889/python_example
/15正则表达式提取数字.py
832
3.625
4
## 总结 ## ^ 匹配字符串的开始。 ## $ 匹配字符串的结尾。 ## \b 匹配一个单词的边界。 ## \d 匹配任意数字。 ## \D 匹配任意非数字字符。 ## x? 匹配一个可选的 x 字符 (换言之,它匹配 1 次或者 0 次 x 字符)。 ## x* 匹配0次或者多次 x 字符。 ## x+ 匹配1次或者多次 x 字符。 ## x{n,m} 匹配 x 字符,至少 n 次,至多 m 次。 ## (a|b|c) 要么匹配 a,要么匹配 b,要么匹配 c。 ## (x) 一般情况下表示一个记忆组 (remembered group)。你可以利用 re.search 函数返回对象的 groups() 函数获取它的值。 ##...
1fb4185313748ab87afc76aa7ae63a426d8456f6
paren8esis/Style_Transfer
/utils.py
1,405
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Various utility functions for style transfer. """ import numpy as np import keras.backend as K def mean_subtraction(x): ''' Subtracts the ImageNet mean value from given image. Parameters: ----------- x : ndarray The image to subt...
ec344518f6e2c833c51242439b4885fdb9a8178c
luckysona/luckysandy
/check the points lie in the same line.py
211
3.90625
4
s1=input().split() s2=input().split() s3=input().split() if(s1[0]==s2[0]==s3[0] or s1[1]==s2[1]==s3[1] or (s1[0]==s1[1] and s2[0]==s2[1] and s3[0]==s3[1])): print("yes") else: print("no")
f1ca329d6d5861a4b507d1f8e26449e526437546
bkim82/FreshPyCharm
/Labs/Lab6/6_1/Tell_Story.py
4,123
3.671875
4
from tkinter import * class Application(Frame): def __init__(self,master): super(Application,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Enter the following:" ).grid(row = 0, column = 0, colu...
6dc239be87fbb05f7eb325608f7101e30a3aff97
bkim82/FreshPyCharm
/Warm Up/Character Frequency.py
383
3.6875
4
def readFile(filename): dist = {} file = open (filename,"r") for line in file: line = line.upper() for c in line: if c.isalpha(): dist[c] = dist.get(c,0) + 1 return dist def main(): d = readFile("story.txt") chars = list(d.keys()) chars.sort()...
5d39939eab49950e22200eadaa474702c44a11f7
bkim82/FreshPyCharm
/Labs/Lab 5/Lab: Battle/characters.py
2,257
3.625
4
import random class Character (object): MAX_DEXTERITY = 100 def __init__ (self, name, hit_points, strength, dexterity): self.name = name self.hit_points = int(hit_points) self.strength = strength self.dexterity = dexterity def attack (self, enemy...
62586385f2a4f2d0d26b0c869ebdc2df5e7cbc70
Ming-H/leetcode
/230.kth-smallest-element-in-a-bst.py
1,498
3.515625
4
# # @lc app=leetcode id=230 lang=python3 # # [230] Kth Smallest Element in a BST # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: ...
fe6c445f4a36f2063375baae71ad848ba16e82d3
Ming-H/leetcode
/451.sort-characters-by-frequency.py
405
3.6875
4
# # @lc app=leetcode id=451 lang=python3 # # [451] Sort Characters By Frequency # # @lc code=start class Solution: def frequencySort(self, s: str) -> str: from collections import Counter counter = Counter(s) sorted_chars = sorted( counter.items(), key=lambda x: x[1], reverse=Tru...
1dd71885569f48acc170fe7e997d9ec036974ab3
Ming-H/leetcode
/318.maximum-product-of-word-lengths.py
704
3.5
4
# # @lc app=leetcode id=318 lang=python3 # # [318] Maximum Product of Word Lengths # # @lc code=start class Solution: def maxProduct(self, words: List[str]) -> int: def check(chars1, chars2): for a, b in zip(chars1, chars2): if a and b: return True ...