blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2630c75c6e5d9176399d32d1ebfe6fc32f0f766d
lordstone/shua_python
/2016/varifyPreorder.py
784
3.625
4
class Solution(object): def verifyPreorder(self, preorder): """ :type preorder: List[int] :rtype: bool """ if len(preorder) < 3: return True stack = [preorder[0]] minimum = - 0x7fffffff for i in range(1, len(preorder)): if preorder[i] < min...
0ae83bda990a76cf70d0c8e84caa5b809768b971
lordstone/shua_python
/2016/numOfIslandUnion.py
3,037
3.609375
4
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] class StupidSolution(object): def numIslands2(self, m, n, positions): """ :type m: int :type n: int :type positions: List[List[int]] :rtype: List[int] """ res = [] if m == 0 or n == 0 or len(positions) ...
fc297b1efcc4935db3f207da4c32f8c7ee9a5b66
lordstone/shua_python
/2016/ds_Trie.py
547
3.8125
4
class TrieNode(object): def __init__(self): self.children = [None] * 26 self.isEnd = False self.endWord = None # optional def look_up(self, letter): return self.children[ord(letter) - ord('a')] @staticmethod def build_trie(root, word): for c in word: ...
5ca6fde922d76d8a16f2f604f870b9ecb88f0d6b
lordstone/shua_python
/2016/cloneGraph.py
1,296
3.625
4
# Definition for a undirected graph node class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if node is None: return ...
e8f98e1a9db3ed16c8c3c6a2cdd6a4439049aca8
tomkf/text-analyzer
/text_parse.py
2,121
3.578125
4
import requests response = requests.get(input("Provide the url for the .txt file you would like to analyze from the Project Gutenberg website (or elsewhere): ")) working_responce = response.content.decode("utf-8") punctuation = ['!', '.', '-', ':', ',', '_', "'"] text_dict = { 'character_count': 0, 'character_coun...
8ab04dd64c88c048f273302ba21ee4f0e9d87fe8
jcrosskey/design_patterns
/src/patterns/factory.py
9,000
4.5625
5
""" Factory Pattern (twofer!) The Factory Method Pattern defines an interface for creating an object, but let subclasses "decide" which class to instantiate. Factory Method lets a class defer instantiation to subclasses. The Abstract Factory Pattern provides an interface for creating families of related or dependent ...
490cb93dd459fecd10ca99e6f8c4b912249cd16b
priyankvex/FindNearByCustomers
/tests/test_great_circle_distance.py
698
3.59375
4
from jsonschema import ValidationError from unittest2 import TestCase from src.great_circle_distance import GreatCircleDistance class GreatCircleDistanceTestCase(TestCase): def test_with_invalid_input(self): with self.assertRaises(ValidationError): GreatCircleDistance.calculate({}, {}, 100)...
6c9a5609b9a758f564a7475f8c3c118669e040c0
zephir73/Day02
/ex02/bonjourV2.py
143
3.65625
4
def bonjour(): prenom = input("Bonjour ! Quel est votre prénom ?\n") print(prenom + ", enchanté moi c\'est James, James Bond.\n") bonjour()
abaf5bbd958292e73aa25bb30a6e710dd239625c
zhane98/studying
/Code Wars/codewars02nov.py
2,207
3.625
4
#https://www.codewars.com/kata/56dae9dc54c0acd29d00109a/train/python # def main(verb, noun): # return verb + noun #https://www.codewars.com/kata/5625618b1fe21ab49f00001f/train/python # def say_hello(name): # return f"Hello, {name}" #https://www.codewars.com/kata/595970246c9b8fa0a8000086/train/python #def cap...
01c24301675d01827175591a0591249ed0bc6282
zhane98/studying
/Day2.py
424
4.03125
4
height = 166 tall = height > 180 if (height > 170): print("you are too tall") elif (height == 166): print("you are a crappy height") else: print("you are not too tall") if not (tall): print("you are not tall") for i in range(3, 12): print(i) for char in "calvin": print(char) else: print("...
4d09c457de3bc7c821777ec337dfd33dce987a37
zhane98/studying
/codewars19oct.py
1,590
4.03125
4
def flip(direction, sequence): if direction == 'R': sequence.sort() else: sequence.sort() sequence.reverse() #sequence = sequence[::-1] called slicing. return sequence # flip('R', [3, 2, 1, 2]) => [1, 2, 2, 3] # flip('L', [1, 4, 5, 3, 5]) => [5, 5, ...
0aebd5e746566621c431fde39fcc258e5b9a1494
zhane98/studying
/Dictionaries.py
860
4
4
zhane = { "height": 166, "weight": 130, "age": 29, "city": "Liverpool", "country": "England" } print(zhane) print(zhane["city"]) zhane["gender"] = "female" # if did gender again it will just update it to the new pair (as gender already exists) print(zhane) for i in zhane: value = zhane[i] #...
e1f4b62df6e361512ed713fc09c929c11a9e2a03
zhane98/studying
/Code Wars/codewars12nov.py
1,617
3.65625
4
#https://www.codewars.com/kata/5769b3802ae6f8e4890009d2/train/python # def remove_every_other(my_list): # empty = [] # for x in range(len(my_list)): # if x % 2 == 0: #Odd # empty.append(my_list[x]) # return empty # return my_list[::2] # print(remove_ev...
839cd9fc960bfbe7decf17b8d2185361a1ddc7e5
papan36125/python_exercises
/concepts/Exercises/oop/inheritance_example_1.py
680
3.78125
4
from oop import BankAccount class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): super().__init__() self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print ('Sorry, minimum ...
6ddb26678162ab9d15ab26a2d11c06abaf7221dc
papan36125/python_exercises
/concepts/Exercises/counting_in_loop.py
133
3.734375
4
count = 0 print('Before', count) for thing in [9,41,12,3,74,15]: count += 1 print( count, thing) print('After', count)
f6b9bf4f096484a7ba02ad160de19b229514a7a7
papan36125/python_exercises
/concepts/Exercises/files.py
490
3.8125
4
with open("test.txt",'w',encoding = 'utf-8') as f: f.write("This is my first file\n") f.write("This file\n") f.write("contains three lines\n") f = open("test.txt",'r',encoding = 'utf-8') print(f.read(4)) print(f.read(4)) print(f.read()) print(f.read()) print(f.tell()) f.seek(0) print(f.read()) f....
e3fe1734f9c19a9dc5ea92f9340e501c8b8a8e03
papan36125/python_exercises
/concepts/Exercises/list_functions.py
651
3.875
4
lucky_numbers = [4,8,15,16,23,42] friends = ['Kevin', 'Karen', 'Jim', 'Oscar','Toby'] print(lucky_numbers) print(friends) friends.extend(lucky_numbers) print(friends) friends.append('Creed') print(friends) friends.insert(1,'Kelly') print(friends) friends.remove('Jim') print(friends) friends.clear() print(f...
f31e287adcba5c2e9ed5dbddc8e64ddd94334df2
papan36125/python_exercises
/concepts/Exercises/string_examples.py
872
4
4
str = 'programiz' print('str = ', str) #first character print('str[0] = ', str[0]) #last character print('str[-1] = ', str[-1]) #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) #slicing 6th to 2nd last character print('str[5:-2] = ', str[5:-2]) my_string = 'programiz' # can't do below because strings a...
25ef358d1faa212ee4e9ecc4f3e51e437f4f72d7
papan36125/python_exercises
/concepts/Exercises/bitwise_operators.py
567
3.890625
4
x = 10 # 0000 1010 in binary y = 4 # 0000 0100 in binary # Bitwise AND, Output: x& y = 0, 0000 0000 in binary print('x & y is',x & y) # Bitwise OR, Output: x | y = 14, 0000 1110 in binary print('x | y is',x | y) # Bitwise NOT, Output: ~x = -11, 1111 0101 in binary print('~x = ',~x) # Bitwise XOR, Output...
acca8e9285a8ac9dc0f330640dcd666bd97cda80
jtessensohn/python-functions
/is_odd.py
146
4.15625
4
number = int(input("Which number would you like to check? ")) def is_even(num): return (num % 2) != 0 result = is_even(number) print(result)
984620607ab6fd698672eca20bc99c4ae7081fbe
ShivaPrasadhegde101/TIC_TAC_TOE_GAME
/tic_tac_toe_game.py
2,766
3.96875
4
board=[' ',' ',' ',' ',' ',' ',' ',' ',' ',' '] check=1 win=1 tie=-1 running=0 game=running chance='X' #function to draw the board def Draw(): print("%c | %c |%c"%(board[1],board[2],board[3])) print("___|___|___") print("%c | %c |%c"%(board[4],board[5],board[6])) print("___|___|___") ...
c510b69d9a39d928afe70b5f1e450dfc12428cda
yuna-liu/python-programming-Yuna-Liu
/Labs/Lab3.geometry-OOP/rectangle.py
4,921
4
4
from geometry_shape import Shape import matplotlib.pyplot as plt import matplotlib.lines as mlines import matplotlib class Rectangle(Shape): def __init__(self, x: float, y: float, side1: float, side2: float) -> None: """A subclass to represent rectangle with (x, y) of the midpoint, length and width""" ...
3a9c787eedce45d584ba808c4d6d783e5c9459f4
nayan-pradhan/python
/linkedList.py
771
3.859375
4
# Nayan Man Singh Pradhan # Still working on this file # Node class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # LinkedList class LinkedList: def __init__(self, numberOfElem): self.numOfElem = numberOfElem self.head = None ...
480b45cef79545131d3a5ce1e56a9fb3e020a8a1
snehass135/Python-Programs
/spiral traverse of matrix.py
874
3.78125
4
matrix = [ [1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7] ] def spiral_traverse(arr): row_start, row_end = 0, len(arr) col_start, col_end = 0, len(arr[0]) res = [] if row_end - row_start <= 1: return arr[row_start] if col_end - col_start <= 1: return [row[0] for row in arr] while r...
4039712c28a9e2208b17b9f8a55ce18b00c34645
snehass135/Python-Programs
/fibanocciseries.py
205
4
4
def fib(n): if (n<=1): return n else: return fib((n)-1)+fib((n)-2) n = int(input("enter number:")) if n<=0: print("enter positive integer") for i in range(n): print(fib(i))
88895b47acc76332cb3bb090e76478a0def5cfc2
snehass135/Python-Programs
/Sieve_of_Eratosthenes.py
799
3.8125
4
#https://m.facebook.com/story.php?story_fbid=2848722018739963&id=100008065788593 #subscribed by Sam Parker import math n = 200 # n is any arbitrary integer List = [] for x in xrange(2, n): # add numbers from 2 to n - 1 to List List.append(x) # note the above statement is equivalent to List = range(2, n) p = 2 #...
c38b508d9e0830e8112bd830cce3f0db66cd3786
thinksource/practicecode
/happynumber.py
507
3.5625
4
class Solution: # @param {int} n an integer # @return {boolean} true if this is a happy number or false def isHappy(self, n): # Write your code here numset=set() while True: sum = 0 while (n != 0): k = n % 10 sum += k ** 2 ...
0b99ceeb55cbab0fd864a1cff98e81fa5f56202c
chuck-y-lee/my_leetcode
/Tree/[easy]404-sum-of-left-leaves.py
1,529
3.96875
4
# ========================= Problem Description ============================================ # #Find the sum of all left leaves in a given binary tree. # #Example: # # 3 # / \ # 9 20 # / \ # 15 7 # #There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. # --------...
8e88c7b3b3b7f05535f0f3974312d639edd7730e
mzuniga94/cpsc305
/Mini Project 3/red_star.py
241
3.515625
4
import turtle turtle.setup(800, 800) wn = turtle.Screen() thomas = turtle.Turtle() thomas.color((1,0,0)) for x in range(0, 72): thomas.forward(200) thomas.left(180) thomas.forward(200) thomas.left(185) wn.exitonclick()
ddecfecde54cf6fdfcefd3004e6274b9e3c53e15
hithxh/CS190B-Web-and-Text-Mining
/Web Analytics /Yelp/yelp.py
1,175
3.671875
4
# coding: utf-8 # BeautifulSoup Demo #import packages from bs4 import BeautifulSoup import urllib2 #the url you want crawl url = 'https://www.yelp.com/biz/milk-and-cream-cereal-bar-new-york?osq=Ice+Cream' #use urllib2 module to open the url ourUrl=urllib2.urlopen(url) soup=BeautifulSoup(ourUrl,'html.parser') #cre...
f3b88dbedfc8e2a4cc7a07e2b38a9117780b394d
BryantLuu/daily-coding-problems
/4 - Find first missing integer.py
1,439
3.8125
4
""" Good morning. Here's your coding interview problem for today. This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates...
490f73453430f0297a5d0d0d5eabeaefa0489b6c
BryantLuu/daily-coding-problems
/1 - Given a list of numbers, return whether any two sums to k.py
729
3.890625
4
""" Good morning. Here's your coding interview problem for today. Given a list of numbers, return whether any two sums to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? Upgrade to premium and get in-depth solutions to every problem. If you like...
a5052f19e9916da138617a40bf93de55b87fdd02
vishnuster/python
/for-with-list.py
192
3.671875
4
b=0 a=input("Enter your name") for i in a: if (i in ['A','E','I','O','U','a','e','i','o','u']): b=b+1 print ("You have",b,"vowels in your name") input("Hit enter to exit")
0765925f76a5696f49b383e4d476cee9dbeb90df
vishnuster/python
/awesometest2.py
339
3.59375
4
import os import re userinp=input("enter file name to be searched: ") walk=os.walk("C:\\Users\\VPrakas\\Desktop") print("Patterns that match", userinp,"are given below\n") for path, folder, files in walk: for i in files: if(re.search('%s' %userinp, i,re.IGNORECASE)): print(path,folder,i) input("h...
00db019e551f9fbe46c317e22009e4c8624bcfd0
Ujwal2910/AI_Lab_Assignments
/Lab_Assignmnet_7/neural_net.py
2,845
3.75
4
import numpy as np import matplotlib.pyplot as plt X = np.array(([-20], [-19], [-18],[-17],[20],[-10],[30]), dtype=float) y = np.array(([10], [5], [-1],[5],[20],[-10],[30]), dtype=float) # scale units #X = X/np.amax(X, axis=0) # maximum of X array #y = y/100 class Neural_Network(object): def __init__(self): #p...
e952273c0de68b297a264f5e73de1d966e1253d8
os-data/gb-country-regional-analysis
/scripts/aggregate.py
2,862
3.703125
4
import csv def make_castrow(rowtypes=None): '''This function takes e.g. a CSV row of data and casts the data to relevant types. Imagine this being part of data package utilities ''' if rowtypes is None: rowtypes = { 'amount': 'number' } def castrow(row): ...
1a54d3268a65f2ba7b0bafc42337d38814df9930
k-shar/pygame
/platformer/main.py
11,563
3.515625
4
import pygame import math import random FPS = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) pygame.display.init() class Player(pygame.sprite.Sprite): ''' This class represents the player and their carrot shooting carrot launcher ...
d0e324ad75f63aa8c07c750b9b500d6f4232e27d
wangpeihu/algorithm017
/Week_08/LRUCache.py
2,381
3.890625
4
''' #第一种方法:python collections.OrderedDict from collections import OrderedDict class LRUCache(collections.OrderedDict): def __init__(self, capacity: int): super().__init__() self.capacity = capacity def get(self, key: int) -> int: if key not in self: return -1 self....
736a529339834a5731eb6b370c645aa96905f544
AP-MI-2021/lab-2-alicebugnariu1o
/main.py
2,932
3.734375
4
import math def get_leap_years(start: int, end: int): list = [] for i in range(start, end + 1): if i % 4 == 0 and i % 100 != 0: list.append(i) elif i % 400 == 0: list.append(i) return list def test_get_leap_years(): assert get_leap_years(2000, 20...
14c1622390343be7bdf3e608c80b5dc944767fb6
whh881114/common_scripts
/小脚本/list_2_recursive_dict.py
662
3.84375
4
# -*- coding: UTF-8 -*- """ 函数功能: ['default', 'master', 'redis'] ---> {"defalut":{"master":{"redis":{}}}} """ def list_2_dict(list): ret = {} dict_tail = {} dict_tail[list[0]] = '' for i in list[1:]: head = {} head[i] = dict_tail dict_tail = head ret = head print('...
091516d87b3ecd6f7070bc6d7fb6eba0349e5510
whh881114/common_scripts
/numpy学习/017_sample_统计函数.py
801
3.53125
4
# -*- coding: UTF-8 -*- from __future__ import print_function import numpy as np # numpy.amin()用于计算数组中元素沿指定轴的最小值。 # numpy.amax()用于计算数组中元素沿指定轴的最大值。 a = np.array([[3, 7, 5], [8, 4, 3], [2, 4, 9]]) print('我们的数组是:') print(a, end='\n\n') print('调用amin()函数:') print(np.amin(a, 1), end='\n\n') print('再次调用amin()函数:') print(...
0adc1fe1f0b134fdbad5c999593ff8942d8af6a9
whh881114/common_scripts
/nginx日志分割/1.py
1,087
3.796875
4
# -*- coding: UTF-8 -*- from __future__ import print_function a = [1, 2, 4, 5, 7, 9, 11, 14] b = [1, 2, 4, 5, 7, 9, 11, 14] # [1, 2, 4] [5, 7] [9, 11], [14] # for index,value in enumerate(a): # print(index, value) print(a) base_num = a[0] new_nums = [] # new_nums.append(base_num) # for e in a[1:]: for e in a...
5ca0efb4b1e65c9c1ac662b6ed7c41d6ceab562b
KrasiF/sudoku-solver
/sudoku_solver.py
14,194
3.609375
4
import itertools import copy class SudokuSolver: ALL_NUMBERS = {1,2,3,4,5,6,7,8,9} def __init__(self, field): self._field = copy.deepcopy(field) self._row_sets = [set() for i in range(9)] self._col_sets = [set() for i in range(9)] self._square_sets = [[set() for j in range(3)]...
a536aa53ab430246f63cb1f1f424ab9f1790966d
seowshuen/dw-1d
/internetofthings_thymio_pyrebase/wk4_raspberrypi.py
2,094
3.5
4
import RPi.GPIO as GPIO from time import sleep from libdw import pyrebase projectid = "dw-1d-fa276" dburl = "https://" + projectid + ".firebaseio.com" authdomain = projectid + ".firebaseapp.com" apikey = " AIzaSyBwPUajf42FDcK_TwPja34tr0Jy760y3QQ " email = "yew.seowshuen@gmail.com" password = "123456" config = { ...
3b42edf933488a2162dcebd1aa4316738f7338bb
rajalap/coolstuff
/rotateMatrix.py
497
4.15625
4
def print2D(array): for i in array: for j in i: print(j, end=" ") print() def rotateArray(array): newArray = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]] n = array.sizeof() for i, row in array: for j, column in i: newArray[n - j][i] = array[i][j] return...
dd1d81b77b0b8a22155d2393fa8020125e72cbbe
rajalap/coolstuff
/isUnique.py
344
3.875
4
import os def main(): # string = os.getcwd() # permute = True # for i, string.length(): # if string[i].isalpha(): # if(nstring[i] != string[string.length()-1]): # permute = False # if permute == True: # print("String is a palindrome") print("Is Unique") if __na...
b812ffb47ef9a851ffcd60c2ebd265a1b1feb6fa
rajalap/coolstuff
/palindromeLL.py
1,770
3.59375
4
from node import Node def printLL(node): print(node.data) if node.next is not None: printLL(node.next) def check4Pals(node, LL): LL.append(node.data) if node.next is not None: check4Pals(node.next, LL) print(len(LL)) if len(LL) == 1: print("Linked List of size 1") ...
96d42f4298d97b13436ab6ccc7a5d79fa30a448d
naviat/learnpythonthehardway
/Ex04.py
835
3.96875
4
import os import sys from sys import * cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print("There are", cars , "cars available.") print("There ar...
3d9b047d7803b2ffd5cc869cd89a49081aa1f86c
DeadZombie14/chillMagicCarPygame
/utilidades/treed/core3d.py
24,333
3.890625
4
import pygame, math import numpy as np """ LIBRERIA DE OBJETOS 3D BÁSICOS ========================================== Esta librería proviene de un tutorial para renderizar formas simples usando matemática y pygame. Este archivo esta designado para dibujar en pantalla la forma especificada. """ # Radian rotated by ...
4bbf541d05fb68ed3cdf88c29dd40d5186393eff
DeadZombie14/chillMagicCarPygame
/pantallas/asd.py
1,643
4.03125
4
##################### Funcion principal ##################### def miprograma(): empresas = [] productos = [] usuarios = [ { 'ID': "1", 'Nombre': "Pablo" } ] # Llamar a mi menu empresas.append(registrarEmpresa()) # Esto registra un...
f5fc469ff4a22f0a0a3f7c8f21b5243d98182a4a
mitchazj/mandelbrot
/main.py
909
3.96875
4
# Generate the Mandelbrot set import time from PIL import Image def mandelbrot_iter(c): """Get the mandelbrot value for a complex number c""" z = 0 for i in range(0, 255): z = z * z + c if abs(z) > 2: return i return 255 def mandelbrot(x, y): """Compute the Mandelbro...
35669e16749eaa4b4e3d5164398d71922414ce8b
renweiXu/PyDemo
/com/xu/oop/OopDemo.py
2,108
3.953125
4
''' 面向对象 封装 封装属性和方法 减少耦合 继承 提高开发效率 多态 类 用来描述具有相同的属性和方法的对象集合 变量 类变量/成员变量/实例变量 方法 类中定义的函数 定义类 class ExampleClass(): #类变量 val1 = 100 #构造函数 def _init_(self): #成员变量 self.val2 = 200 ...
beb17386052dbc5d0816349af7380734102fa7c1
abhinavramkumar/basic-python-programs
/divisibleBySeven.py
432
3.921875
4
# Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, # between 2000 and 3200 (both included). # The numbers obtained should be printed in a comma-separated sequence on a single line. def divisibleBySeven(m,n): arr = "" for i in range(m,n + 1): if (i %...
47956dbcb3de235cd35dcd5753e2ddd543c6ab08
Rohan-Potter/Command-Line-Programs
/winning.py
410
3.90625
4
from random import randint a= randint(1,10) def winning(n,z): if n==a: return ("Yeah you won!! NO. of chances you have taken :"+ str(z)) elif n>a: return ("You'r no is greater than the winning no") else: return ("You'r no. is less than the winning no ") for i in range(1,20):...
a945dd252124623571fc32e1198f4a951fd6b91d
miguel76/python-play
/treecake.py
547
3.71875
4
def half_fib(n): if n == 1 or n == 2: return 1 else: sum = (half_fib(n - 1) + half_fib(n - 2)) % 1000000007 if n % 3 == 0: return sum - 1 else: return sum FIVE_SQUARED = 5 ** 0.5 FI = (1 + FIVE_SQUARED) / 2 PSI = (1 - FIVE_SQUARED) / 2 def half_fib2(n): ...
f77e2860b10abb078cfacd8aa6caa399e332d08d
Tymotheus/Ensimag-Python
/2_Iterations/3_PGM_images/pgm.py
2,092
3.5
4
#to finish - getting dimensions from a user #!/usr/bin/env python3 """ Images PGM - circles """ #importing used modules import math import random class Circle: #circle full of grey dots def __init__(self): self.center = [0,0] def create_in_window(self, width, height): #picking coordinat...
dd3a83feb2c9010d12197795e4b3411298aeefcd
Tymotheus/Ensimag-Python
/2_Iterations/1_Reconstiution/filtre.py
680
3.515625
4
#!/usr/bin/env python3 """ pointy """ class Point: def __init__(self, x,y): self.coordonnees = [int(x), int(y)] def svg(self): print("<circle cx=\"{}\" cy=\"{}\" r=\"3\" fill=\"red\"/>".format( self.coordonnees[0], self.coordonnees[1] )) def __str__(self): ...
fd9c443b013904f8be048484ea38fc66ece14f65
sol83/python-simple_programs_5
/Parameters & Return/sentence_generator.py
1,940
4.8125
5
""" Sentence generator Implement the helper function make_sentence(word, part_of_speech) which will take a string word and an integer part_of_speech as parameters and, depending on the part of speech, place the word into one of three sentence templates (or one from your imagination!): If part_of_speech is 0, we will ...
8396762a922c0b9150699346697862f92bd5c042
ppli2015/leetcode
/237 Delete Node in a Linked List.py
654
4.03125
4
#-*-coding:cp936-*- __author__ = 'lpp' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, mod...
21eac37112673a452cb78edb41158dc6cd082b11
ppli2015/leetcode
/7 Reverse Integer.py
661
3.59375
4
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ flag = 0 if x < 0: flag = 1 x = -x elif x == 0: return 0 l = [] while x != 0: l.append(x % 10) x /= 10 ...
156687a6264ccd8310ddcd46e8b3ac0604b1eec9
ppli2015/leetcode
/235 Lowest Common Ancestor of a Binary Search Tree.py
923
3.953125
4
# -*-coding:cp936-*- __author__ = 'lpp' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode ...
feea6d739fde2c03cb5d61002dcc56e9d117a62a
dhaval-khatri1996/sentiment-analysis-using-python
/treeGenerator.py
2,981
3.625
4
import word def sign(p): if p>=0: return 1 return -1 def nonzero(lst): nonzeros=0 for value in lst: if value !=0: nonzeros+=1 return nonzeros def calculate(data, lst): polarity,count=0,0 for i in lst: if i!=0: polarity+=data[i].polarity...
e457ff09ba3c20d480eb7429a2c2fe504f440a93
gf355/math-tool
/aime II p3.py
437
3.59375
4
ans = 0 for a in range(1, 6): for b in range(1, 6): for c in range(1, 6): for d in range(1, 6): for e in range(1, 6): if (a != b and a != c and a != d and a != e and b != c and b != d and b != e and c != d and c != e and d != e): if ((a...
a3de899d0b1d34ff53c4b51549b2e9bd301bc857
ashishvista/geeks
/geekforgeeks/Triplet Sum in Array.py
855
3.703125
4
def triplet_sum(arr, n, x): for i in range(n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): if arr[i] + arr[j] + arr[k] == x: print(1) return print(0) def triplet_sum2(arr, n, x): arr.sort() s = x for i in r...
e4676a9b760819f976165853acda31204b79f732
ashishvista/geeks
/geekforgeeks/Print Diagonally.py
638
3.78125
4
def diagonal(arr, n): for i in range(n): pd(arr, n, 0, i) for i in range(1, n): pd(arr, n, i, n - 1) def pd(arr, n, x, y): while x < n and y >= 0: print(arr[x][y], end=" ") x += 1 y -= 1 if __name__ == "__main__": tcases = int(input()) for t in range(tcas...
44cfad167630e5e62215a3458a5370161aa910e7
ashishvista/geeks
/leetcode/Queue Reconstruction by Height.py
1,475
3.609375
4
from typing import List class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reconstructQueue1(self, people: List[List[int]]) -> List[List[int]]: def compare(a): return a[0] people = sorted(people, key=lambda x...
1582c45ccb70cd76c882ccadeb3595471c19d524
ashishvista/geeks
/geekforgeeks/test.py
1,399
3.765625
4
def merge(arr1, arr2, m, n): i = m - 1 j = n - 1 while j >= 0: if arr1[i] > arr2[j]: arr1[i], arr2[j] = arr2[j], arr1[i] customSort(arr1, m) j -= 1 # shell sort custom for one element def customSort(arr, n): i = n interval = i // 2 while interval >= 1: ...
68d9c00603fd8067f007f145de84bed0fa99e30a
ashishvista/geeks
/leetcode/Rotate Image.py
1,050
3.75
4
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ r = c = len(matrix) m = 0 n = r - 1 while m < n: i = m for j in range(m, n): ...
f4cb136ae1efefd45d070168e88382be601743cf
ashishvista/geeks
/leetcode/Counting Bits.py
506
3.671875
4
from typing import List class Solution: def countBits(self, num: int) -> List[int]: res = [0] if num == 0: return res i = 0 while True: ln = len(res) j = 0 while j < ln: res.append(1 + res[j]) j += 1 ...
d10ace56e15dfeacf43b84244db92c3419335916
ashishvista/geeks
/leetcode/Maximal Rectangle.py
1,824
3.515625
4
from typing import List class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: rows = len(matrix) if rows == 0: return 0 cols = len(matrix[0]) dp = [0 for i in range(cols)] area = 0 for i in range(rows): for j in range(co...
8fe5cea62f93658a935d8625a85faefc027c0e7d
ashishvista/geeks
/leetcode/Find First and Last Position of Element in Sorted Array.py
1,466
3.65625
4
from typing import List class Solution: def searchRangeHelper(self, nums, target, start, end): flag = False hash = {} while start <= end: mid = (start + end) // 2 if nums[mid] == target: flag = True break elif target < num...
8fe432398ebe63928ec3154931bf0ebf8ca295fa
ashishvista/geeks
/geekforgeeks/Circle of strings.py
1,224
3.609375
4
from collections import defaultdict class Node: def __init__(self, s, i): self.s = s self.i = i def isCircle(n, arr): node_arr = [] h = defaultdict(list) for i, s in enumerate(arr): node = Node(s, i) h[s[0]].append(node) node_arr.append(node) visited = {n...
1c0991d93b5d1d1426287c60b026bc334b402a18
SWKineo/COS-125
/Homework 1/hw1-7.py
141
3.609375
4
x = 2.2 - 2.0 print '2.2 - 2 = ',x if x == 0.2: print "Python is a math whiz." else: print "Huh, what?? x is NOT equal to 0.2"
b8e798acbb6aa09ce63249a800900fe638fcdd56
SWKineo/COS-125
/Homework 2/Hwk2-2.py
2,697
4.125
4
def bottle_verse_special(verse_number): if verse_number == 2: print "Two bottles of beer on the wall, two bottles of beer." print "Take one down and pass it around, one bottle of beer on the wall." elif verse_number == 1: print "One bottle of beer on the wall, one bottle of beer." ...
ffb1779817b02f32987071f105a9a006e4426d27
SWKineo/COS-125
/Lab 5/Ward_Spencer_Dice_Roll.py
1,523
3.671875
4
""" Created by Spencer Ward COS 125 Fal 2016 Lab #5 """ import Tkinter from random import randint class Die: def __init__(self, frame): self.value = randint(1, 6) self.display = Tkinter.Label(frame, text=str(self.value), ...
a20367617199475b65bfc65d1b253be485a2b7a0
14Praveen08/Singly-Linked-List
/Creation of node.py
326
3.65625
4
class node: def __init__(self,dataval=None): self.dataval = dataval self.nextval = None class linkedlist: def __init__(self): self.headval = None node1 = linkedlist() node1.headval = node("first") e2 = node("second") e3 = node("third") node1.headval.nextval = e2 e2.nextval ...
7ca773d11384cb733390beeb39b8fced31c32b09
Yehuda1977/DI_Bootcamp
/Week8PythonOOP/Day1Feb21/Day4Feb24/exercises.py
2,090
4.34375
4
# Consider this code class Pets(): animals = [] def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__(self, name, age): self.name = name self.age = ...
f292bf0b89997f719a1c1adc230b16abd04d97e0
Yehuda1977/DI_Bootcamp
/Week9/Day2/DailyChallengeCircle.py
1,234
4.4375
4
# Instructions : # The goal is to create a class that represents a simple circle. # A Circle can be defined by either specifying the radius or the diameter. # The user can query the circle for either its radius or diameter. # Other abilities of a Circle instance: # * Compute the circle’s area # * Print the circle and...
75c2a8e6523ceb93e0764c13476671a9bb278d90
Yehuda1977/DI_Bootcamp
/Week9/Day2/DailyChallengeInput.py
724
4.28125
4
# Instruction: Information From The User # Notice : solve this using a lambda function, even if you can think of another way # Hint: Look at the lesson on Week4Day4 # Take the following inputs 5 times from the user: # Name (string) # Age (int) # Score (int) # Build a list of tuples using these inputs, each tuple will ...
5812c529d281e79c14c28fc9102e6efe1eff1a41
huming0618/quant-book
/itertools/main.py
860
3.78125
4
import itertools def test_permutations(items): for item in itertools.permutations(items): print(item) def test_combinations(items, qty): for item in itertools.combinations(items, qty): print(item) def test_combinations_replace(items, qty): for item in itertools.combinations_with_replaceme...
1540bd5cf250b0c88902356839ff9cfbbb6a607e
cdt-data-science/cdt-tea-slides
/2015/theo/optimisation/cost_functions/Squared_Loss.py
2,489
3.78125
4
__author__ = 's1463104' from Cost_Function import Cost_Function from auxiliary.common_functions.Mean_Squared_Error import Mean_Squared_Error import numpy as np rng = np.random class Squared_Loss(Cost_Function): """ A concrete class (i.e. a class from which an object can be created). This class implements...
284510d86f43f784cc20dd90288d49145be31e2c
JoshYuJump/v2python
/Questions/delete_duplicate_elements_from_list.py
222
3.953125
4
# -*- coding: utf-8 -*- # Python面试题:请写出一段Python代码实现删除一个list里面的重复元素 l = [1, 3, 2, 'a', 'z', 'd', 3, 'd', 'z'] # set print list(set(l)) # dict print {}.fromkeys(l).keys()
b51ea3787a566724227fd52bb341c82e2ae3061f
yli11/cs340-registrars-problem
/code/components.py
1,727
3.953125
4
class Student: """A student is a class containing unique identity and a list of preference classes Args: idx : A unique label of a student classes: classes this student wants to take taken: list of times this student is unavailable """ def __init...
fad504c7282b0afafb07f80b94e03832a3a46b14
eishnar/CS35lab8
/textree.py
14,461
3.96875
4
#!/usr/bin/python # This program takes as its sole argument the name of a text file containing # visual representations of trees. It produces a TeX file containing code # which will generate diagrams of those trees. # # The input file is expected to be a text document. Each line of the text # document is one of the ...
fdbda095821cc429b1e59365eb0c886378425002
linfel/Not_Soo_Smart_Doge
/GuessNumberGame.py
1,151
3.828125
4
a = 1 b = 1000 print(f'Загадай число от {a} до {b}...') # Даем время на подумать import time time.sleep(1) print('Загадал?') time.sleep(1) print('Тогда поехали!') print() time.sleep(1) rules = '''Если я угадаю, напиши "=", если твое число меньше, то введи "<", а если больше, то ">". И нажми на Enter. ''' print(rules) ...
e8daf665a9d9916da309dfb4b4c89432ccfa8df5
thinking-ASI/artficial_potential_field_for_ur5
/self_defined_modules/robot_class.py
1,685
3.96875
4
from typing import List import numpy as np class Point(): """ Represent a point in Cartesian space """ def __init__(self, p:List[float]) -> None: """ p : The coordinate of the point in Cartesian space """ ...
79fbd9919936fd7931160ea083210c30e40a9002
fatna-sys/datascience
/date scripts .py
1,045
3.765625
4
# -*- coding: utf-8 -*- #Converting timestamps of “yyyy-MM-dd'T'HH:mm:ss.SSSZ” format in Python from datetime import timedelta,datetime str_time = "2021-05-27T05:49:24.257+02:00" #replace the last ':' with an empty string, as python UTC offset format is +HHMM str_time = str_time[::-1].replace(':','',1)[...
5f02bf12b62e163e4081969b013b23f6f9cc2b8d
ClintonIgwegbu/Song-matches
/tests/test_song.py
1,995
3.703125
4
import unittest from song import Song class TestSong(unittest.TestCase): def setUp(self): """Initialise six songs before each test.""" self.song_a = Song('a', 1) self.song_b = Song('b', 2) self.song_c = Song('c', 3) self.song_d = Song('d', 4) self.song_e = Song('...
313c148a8f83166781315c92e5a831a3757ad73b
guipleite/code-interview
/ent4a.py
849
3.5625
4
class TreeNode: def __init__(self, value=None, left=None, right=None, parent=None): self.value = value self.left = left self.right = right self.parent = parent def in_order_succ(node: TreeNode) -> TreeNode: if node is not None: if node.right is not None: buf...
b9d4314ff66ea19869e186a9153aeee536196a49
dzy2020/data_structure
/venv/Data_Structure/Graph/Bfs.py
1,399
4.09375
4
# -*- coding: utf-8 -*- # @Time : 2020/4/18 0018 14:37 # @Author : DZY # @File : Bfs.py # @Software: PyCharm #github #bfs,首先一个结点入队列,然后让它出队,当它出队时,与之相连接的结点一股脑全进入 #队列,然后先进的就先出,先出的结点再把与之相连接的结点全部入队,重复上面的 #过程,直接所有的点都出队 #bfs通过队列来保证层的顺序 def bfs(graph,s): #queue中间介质,所有数据都是先通过这个队列然后出来 queue = [] #visited放入已经走...
6ca75fcb315f6a567d5b839c408b4c6d18090292
El-Bando/Python_Sheet
/Python_Sheet-master/code/Fstrings.py
99
3.875
4
# F-String example fruit = 'apple' color = 'red' print(f'The fruit {fruit} has the color {color}')
b0893edb265b30d041296b2a30839b157d5e143d
El-Bando/Python_Sheet
/Python_Sheet-master/code/Listen/Listen_sort.py
250
3.546875
4
def myfunc(e): return len(e) mylist = [4, 3, 5, 7, 3, 2] strlist = ['BMW', 'Tesla', 'GM'] mylist.sort() print('#1', mylist) mylist.sort(reverse=True) print('#2', mylist) print('#3', mylist.count(2)) strlist.sort(key=myfunc) print('#4', strlist)
2f8dfaba08956a94c675fe2ce8e7d62399d15b2c
fahimkhan/python
/basic-python/find.py
456
4.1875
4
#!/usr/bin/python import re str1 = "this is string example....wow!!!"; str2 = "exam"; str3="Hello" print str1.find(str2); print str1.find(str2, 10); print str1.find(str2, 40); if str1.find(str3,10): print "Found" else: print "Not found" str4="Hello World" str5="world" if str5 in str4: print "Find",str5 e...
96b81274582439a14cc3d207a1250b1459f14604
fahimkhan/python
/pyqt-Example/input-dialog.pyw
987
3.53125
4
#!/usr/bin/python """ The QtGui.QInputDialog provides a simple convenience dialog to get a single value from the user. The input value can be a string, a number or an item from a list. """ from PyQt4 import QtGui,QtCore import sys class Example(QtGui.QWidget): def __init__(self): super(Example,self).__in...
ca844d525221896af4f12eeabbdde247ba125433
fahimkhan/python
/tkinter_gui/plot-in-canvas.py
1,254
3.5
4
#!/usr/bin/python # plot of log line from Tkinter import * import math def particleCount(decay, p0, time): p = (p0*math.e)**(-(decay*time)) return (p) # define root window root = Tk() root.title("Radioactive Decay Graph") # create frame to put control buttons onto frame = Frame(root, bg='grey', width=400, hei...
fc354be514e525f65b6c1e791cc2e606ec8fee35
fahimkhan/python
/Coursera-Example-Python/condition_2.py
442
4.375
4
# Conditionals Examples # Return True if year is a leap year, false otherwise def is_leap_year(year): if (year % 400) == 0: return True elif (year % 100) == 0: return False elif (year % 4) == 0: return True else: return False year = 2012 leap_year = is_l...
86f9fe67ff9d05e18355e6ae459a68f7f3f1d266
fahimkhan/python
/basic-python/problem1.py
591
3.921875
4
#! /usr/bin/python balance = 4213 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 total_paid=0.0 monthlyInterestRate = annualInterestRate/12 for month in range(1, 13): minimum_monthly_payment=round(monthlyPaymentRate*balance,2) balance=round((balance-minimum_monthly_payment)*(1+monthlyInterestRate),2) total_pa...
56cfd9484bdbfaff1242be08f615ad03fc44a26a
fahimkhan/python
/basic-python/polymorphism.py
1,604
4.75
5
#!/usr/bin/python """ Poly means many, and morph means change. Through polymorphism, you can have a method with the same name in different classes to perform different tasks. You can handle objects of different types in the same way. To implement polymorphism, you define a number of classes or subclasses that have me...
dd41efb20a27dead974061a5fcffb0c74126ad16
kishore1215/other
/PythonPractice_Office_200319.py
4,893
4
4
print("Radha Soami") print('I will prefer using visual studio code as preferred ide for my data science learning') print('radhasoami') import pandas as pd print('importing pandas completed') """ before this date, I tried to practice python in jupyter notbook. have a feeling now that practicing in vs code will be more ...
3f5c3784832d441be4251ffe3871b7ea1e6e240f
wardzj08/CaeserCipher
/cipher.py
2,874
4.625
5
#Ceaser cipher script. When given a string, it encodes and/or decodes the message with a given key(number 1-26). The cipher is, #each given letter is shifted down by the key number and non alpha characters remain the same. For example, abc with a key of 1, #becomes bcd and xyz123 with key of 5 becomes cde123 #tak...