blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d8497837a494480703e1d99bcb0351bd3875885e
pepgonzalez/jsStudyCases
/python/1/movies/inheritance.py
452
3.921875
4
class Parent(): def __init__(self, last_name, eye_color): print("parent constructor") self.last_name = last_name self.eye_color = eye_color class Child(Parent): def __init__(self, last_name, eye_color, toys): print("child constructor") Parent.__init__(self, last_name, ey...
8bd041f82eafa1017f2bd1254b9c9759afb97569
CostaDouglas/testes
/elevador2.py
1,027
3.96875
4
from time import sleep print('bem vindo ao elevador ') p = int(input('quantos andares o prédio tem?: ')) a = 0 b = 1 while b != 0: b = int(input('\ndigite o numero do andar desejado ou digite o andar atual para consultar as informações: ')) if b >= 0 or b <= p: if b > a: for c in range(a,...
87cf627d5732a8692e7be41dab9e62643b66045c
danrasband/coding-experiment-reviews
/responses/HH4HT2-UZB/2_reverse_digits.py
343
3.796875
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(X): new_text = '' pos = -1 X = str(X) while pos * -1 <= len(X): if X[pos] != '-': new_text = new_text + X[pos] else: new_text = '-' + new_text pos -=1 ...
f24005d3ad8d64a4708270a55befae1dcff67db0
selvaganesh-M/Algorithms-implementation-python-
/Tower_of_hanoi.py
405
4
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 26 22:31:44 2019 @author: selva """ def move( start, end): print("Move from {0} to {1}".format(start, end)) def tower(height,start, end, spare): if height == 1: move(start, end) else: tower(height-1,start, spare, end) tower(1, start, ...
31cb789c14819b774d03e0ba8c0ba5b5e255ded7
sngvahmed/Algorithm-Coursera
/DataStructure_And_Algorithm/week3/greedy_algorithms_starter_files/largest_number/largest_number.py
1,782
3.734375
4
#Uses python3 import sys from random import randint def isBigger(left, right): lf, rt = str(left), str(right) for i in range(min(len(lf), len(rt))): if lf[i] > rt[i]: return True elif rt[i] > lf[i]: return False if len(lf) > len(rt): return True return ...
8e4d8752474d83b116b7ca10a4faff9ac895e0c7
Christian-Gennari/JPGtoPNG-Converter
/main.py
673
3.5625
4
import sys import os from PIL import Image # Grab first and second argument from command line input imageFolder = sys.argv[1] outputFolder = sys.argv[2] print(imageFolder, outputFolder) # Check if /new exists, if not create if not os.path.exists(outputFolder): os.makedirs(outputFolder) # Loop through imageFolder...
754c21f0b6561c89c250d43ad2ba6316815e9e83
ritumehra/trainings
/flask_python/session_flask.py
1,540
3.921875
4
# https://overiq.com/flask/0.12/sessions-in-flask/ # https://www.tutorialspoint.com/flask/flask_sessions.htm from flask import Flask, session, redirect, url_for, request import requests app = Flask(__name__) app.secret_key = 'ritu' @app.route('/') def index(): if 'username' in session: username = session...
c766f4e1f543777a6e68a71dc02c16c4704c6a15
akobabkov/auto_with_pyautogui
/test 2.py
848
3.6875
4
""" 1. Идем по списку вниз 2. Открываем форму нажатием enter 3. Ставим мышь в определенную координату экрана 4. Кликаем левой кнопкой 5. Ставим мышь в определенную координату экрана 6. Кликаем левой кнопкой 7. Ставим мышь в определенную координату экрана 8. Кликаем левой кнопкой """ import pyautogui as pg import time a...
24b22d54c30fc2b31a95e262aa66669f5a3f5f0c
AhmedSimeda/CodeForces
/Problem 30 Calculating Function/Code.py
384
4.15625
4
def f(n): # sum of even_numbers ## first of all we need to determine n_even, a_1, a_n n_even, a_1, a_n = n//2, 2, n if n%2==0 else n-1 even_sum = n_even*((a_1+a_n)//2) # similarly let's get the sum of odd numbers n_odd, a_1, a_n = n-n//2, 1, n if n%2!=0 else n-1 odd_sum = n_odd*((a_1+...
e572728a8cab4e96b98e77c38d779bf9791030e8
workingjubilee/Algorithms
/eating_cookies/eating_cookies.py
1,434
3.6875
4
#!/usr/bin/python import sys # The cache parameter is here for if you want to implement # a solution that is more efficient than the naive # recursive solution def eating_cookies(n, cache=[]): ways = [0] * (n + 1) start = [1, 1, 2] for i in range(len(ways)): if i <= 2: ways[i] = star...
f206e59d7378db1995cba7f042aabf20d4c8a3bd
amukiza/Palindrome-kata
/test/test_palindrome.py
1,389
3.546875
4
from unittest import TestCase from lib.word import Word from lib.palindrome import Palindrome from hamcrest import assert_that, is_ class TestPalindrome(TestCase): def test_get_letter_at(self): word = Word("noon") palindrome = Palindrome(word) assert_that(palindrome.get_letter_at(0), is_...
2b6a25ee3d2d1c3c7bf25819aef77d8ee947944d
Igor-Polatajko/python-labs
/lab_7_12.py
245
3.921875
4
#!/usr/bin/env python import re def remove_redundant_spaces(line): return re.sub(r'\s+', ' ', line) if __name__ == '__main__': line = input("Enter line: ") print(f"Line without redundant spaces: {remove_redundant_spaces(line)}")
2ca93098cf02f0989b854b534b53a956e028368f
hupei1991/Algorithm-DataStructure
/Algorithm/quick-select.py
2,546
4.03125
4
def quick_select(unsorted_list, start, end, k): """ quick select utilizing partition at space O(1), time O(nlogn) (best O(n), worst O(n^2)) :param unsorted_list: the unsorted list :param start: start index :param end: end index :param k: the kth :return: the kth smallest number of the unsort...
fece9e027b6f2153d138a55662bc88a344cbce16
Daniil7575/Python_practice
/Practice_3/19.5.py
356
3.75
4
def prime(number): if 1 < number < 4: return "Простое" if number == 1: return "Ни простое ни составное" for i in range(2, number // 2 + 1): if number % i == 0: return "Составное" else: pass return "Простое" # print(prime(int(input())))
bf4308c601a85edc169aace44c9ead00057592b8
AlexBlasi/battleships
/ShipPlacement.py
6,468
3.625
4
from tkinter import * import random import math #this version lets users set small ships locations global p2Board p2Board = [["*","*","*","*","*"],["*","*","*","*","*"],["*","*","*","*","*"],["*","*","*","*","*"],["*","*","*","*","*"]] global p1Board p1Board = [["*","*","*","*","*"],["*","*","*","*","*"],...
2e6e0790c585215025cbcf9a5b78f71bf5e850f5
dvenkatr/python-exercises
/sieve/sieve.py
643
3.625
4
from itertools import filterfalse def primes(limit): if limit <= 0: raise ValueError("Limit should be >=1") if limit == 1: return [] prime_factors = range(2, limit + 1) i = 0 while(prime_factors[i] != prime_factors[-1]): prime_factors = drop_multiples(prime_factors[i], prim...
a605cb5f07bca7159f57795a34daf2a99abe0bc5
lindo-zy/leetcode
/字节/226.py
544
3.921875
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def...
d4ecf8cd3004678c33e55ece798f86c122874831
vino160898/LIST
/revr.py
251
3.859375
4
#input="one owt three ruof" #output="one two three four" input="one owt three ruof" words=input.split() i=0 l=[] for word in words: if i%2==0: l.append(word) else: l.append(word[::-1]) else: print(l) output=" ".join(l) print(output)
a9abb7355d89da25023b108e075fc1952f972f22
KrushikReddyNallamilli/Python-100days-Challenge
/swastik pattern.py
1,379
3.703125
4
# n=5 # for i in range(1,2*n): #(1,2,3,4,5) # for j in range(1,2*n): #(1,2,3,4,5) # if i==n or j==n: # print('*', end='') # elif i< n and j==1: # print('*', end='') # elif i==1 and j >n: # print('*', end='') # elif i>n and j==2*n-1: # ...
0f3368a0300c98c87db3453ea196609c4aa74df7
nmante/cracking
/chap-1/python/1-1.py
2,167
4.125
4
""" Implement an algorithm to determine if a string has all unique characters - Have to examine each character no matter what solution [ O(n) ] - Purely alphabetical, or can they be numerical as well? Consider character sets (ASCII) Solution 1: - store occurrences of existing characters ...
bff7234ec305f434879f54830233fed9ec9b9558
PacorrOz/ProyectoPythonBD
/CapturaDatos.py
2,024
3.890625
4
import datetime class CapturaDatos: @staticmethod def leeCalificacion(message): calificacion = 0 while True: try: calificacion = int(input(message)) if calificacion < 0: print('Error :: El número ingresado no debe ser negativo.') ...
f4bac7d72ae70ce4494128cedccb1652d791a55b
RakaChoudhury/Cerner_2-5-Coding-Competition
/TriangleValidity.py
486
4.09375
4
#cerner_2^5_2019 #Check if a triangle of positive area is possible with the given angles def isTriangleExists(a, b, c): if(a != 0 and b != 0 and c != 0 and (a + b + c)== 180): if((a + b)>= c or (b + c)>= a or (a + c)>= b): return "YES" else: return "NO" else: ...
775fe9b2010e6ac83676ee1cdd63d8a35aae99fc
the-brainiac/twoc-problems
/day4/program_2.py
227
3.90625
4
l=[] for _ in range(int(input('enter number of elements in a list:'))): l.append(tuple(input('Enter tuple elements').split())) n=int(input('Enter index value to sort the list:')) print(l) print(sorted(l[n-1:])+sorted(l[:n-1]))
cc20e0ea03fdaa5fdbe17e425fe42bfd6fe1e1e7
Daniel-Pinheiro/jogo-sinuca
/buraco.py
771
3.9375
4
# -*- coding: utf8 -*- from FGAme import * # Esta classe serve para implementar melhor os buracos, pois quando são # apenas circulos, eles acabam colidindo com as bolas. # # Um buraco é composto de três circulos,com um dentro do outro, onde o # maior não possui colisão e tem o tamanho do buraco, o médio, ao colid...
3f067170783ed6511dc8693b7d939bf8af3148cf
TStand90/code-eval
/swap_elements/swap_elements.py
878
3.78125
4
import sys def main(file_arg): with open(file_arg) as f: for line in f: elements, swap_positions = line.strip().split(' : ') elements = [int(element) for element in elements.split(' ')] swap_positions = swap_positions.split(', ') swap_positions = [position.s...
96e1aa4ef48967603367b1ed4d08dc4a87108d29
trungtv4597/Python_Exercises
/chapter1.py
1,613
3.53125
4
# 1: Viêt một câu với đúng ngữ nghĩa nhưng sai cú pháp. # Viết một câu khác đùng cú pháp nhưng lại sai ngữ nghĩa. # 2: Dùng Interpreter, nhập các biểu thức (expression) với các dấu +, *, ** và cho chạy. # Python tính toán các biểu thức này và biểu thị kết quả ngay ở dòng phía dưới. # 3: Nhập 1 2 và cho chạy. # Báo ...
691f65169424d164df015b10a68368f78396ac14
lily2138/pre-education
/quiz/pre_python_02.py
598
3.890625
4
""""2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오 예시 <입력> 첫 번째 수를 입력하세요 : 10 두 번째 수를 입력하세요 : 15 어떤 연산을 하실 건가요? : * <출력> 150 """ num1 = int(input("첫번째 수를 입력하세요")) num2 = int(input("두번째 수를 입력하세요")) cal = input("어떤 연산을 하실건가요?") if cal=="+": print(num1+num2) elif cal=="-": print(num1-num2) elif cal=="*...
16a9632aee3481d3c48ce125fa2d5ee6fb507d0a
malini-kamalambal/gcp_demo
/run/main.py
804
3.640625
4
from flask import Flask import os import random app = Flask(__name__) # Create a Flask object. PORT = os.environ.get("PORT") # Get PORT setting from environment. # The app.route decorator routes any GET requests sent to the root path # to this function, which responds with a "Hello world!" HTML document. # If somet...
7475a6d7875f74cbf13e26a1ae02565035e4f1d3
yunzhe99/UCSD_Python
/python_class2/generator_functions.py
616
3.90625
4
"""Some weird examples of making generator functions for REPL""" def all_together(*iterables): for iterable in iterables: for item in iterable: yield item def all_together(*iterables): for iterable in iterables: yield from iterable def strange_number_generator(): for i in rang...
60c9c94e58439139087cc070efdc1ae495a2d103
Gabriel300p/Curso_em_Video_Python
/Exercicios/Aula07/005.py
280
4.25
4
''' Faça um programa que leia um número inteiro e mostra na tela o seu sucessor e seu antecessor ''' numero = int(input("Digite um número: ")) numero1 = numero + 1 numero2 = numero - 1 print("O antecessor de {} é {}, e o sucessor é {}." .format(numero, numero2, numero1))
2e8f88123a8a49d171ebe86ff5614e96a617c0df
shindesharad71/Data-Structures
/08.Hashing/16_count_substrings_with_equal.py
741
3.875
4
# Count Substrings with equal number of 0s, 1s and 2s # https://www.geeksforgeeks.org/substring-equal-number-0-1-2/ def get_equal_number(string: str): n = len(string) map = dict() map[(0, 0)] = 1 zc, oc, tc = 0, 0, 0 res = 0 for i in range(n): if string[i] == "0": zc +...
9a343d0fdd981bc24422850fe911c7d6284e99f7
daniel-reich/ubiquitous-fiesta
/6o5wkfmSaFXCJYqDx_5.py
83
3.640625
4
def abcmath(a, b, c): return a % c == 0 if b > 0 else abcmath(a + a, b - 1, c)
0b8054f4964fea7a76a1934d559865119b38a336
froontown/learn_python
/functions/exercise2.py
865
3.8125
4
# def city_country(city, country): # location = f"{city.title()}, {country.title()}" # print(location) # city_country('santiago', 'chile') # print('=====') # def make_album(artist, album, tracks=''): # info = { # 'artist': artist, # 'album': album, # } # if tracks: # info['tracks'] = tracks # return in...
a23277c6ef69f28b3a9e07a54f0bd519f7153586
SteveJSmith1/leetcode-solutions
/Solutions/7_Reverse_Integer.py
1,359
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 7 12:08:52 2017 @author: SteveJSmith1 """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ # Process negative number if x < 0: rev = str(x)[:0:-1] ...
4f3055cd48effc9ca594cbb6a6cca41a43115335
Silentsoul04/FTSP_2020
/Durga OOPs/Method_Overloading_OOPs.py
6,431
4.375
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 13:57:41 2020 @author: Rajesh """ Method Overloading :- ------------------ class Test: def m1(self): print('No-arg method') def m1(self,x): print('One-arg method') t = Test() t.m1() # TypeError: m1() missing 1 required ...
63e4e62c59840367e6b5f8da6f6e97a9fe345af0
hjayyang94/Python_Practice
/Tetris/tetris_board.py
1,416
3.65625
4
import pygame class Board(object): def __init__(self, width, height): self.width = width self.height = height self.board = { (x,y): '0' for x in range(self.width) for y in range(self.height) } self.piece_active = False def print_board(self): result = '' for row in range(self.height): result += str(r...
f30f0e0a19151a994a8d2997b808c35fab4b03ce
PolyatomicBrian/Recent-Reddit-Comment
/recentRedditComment.py
2,670
3.75
4
#This program uses Reddit's JSON storage to find a user's most recent comment. #Honestly, this could have been done easier using PRAW, or some similar library, but I was looking for something new and different. import json import urllib2 from Tkinter import * root = Tk() screenW = root.winfo_screenwidth() screenH =...
12ad08124cb03c798197999bb275714f31f78e72
java-final-project-ml/nba
/build_model.py
3,886
3.734375
4
'''Import the pandas library for data manipulation''' import pandas as pd import joblib def build_model(): #Read in the cleaned dataset df = pd.read_csv("cleandata.csv") #We don't have the statistics of players five years in the future df = df[df["season"]<2014].reset_index() '''Some players did no...
5df10018970a564ec78391a6a46aed8271420c8b
vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3
/Algorithms/2 Sorting/SwapSubArray.py
1,080
4.09375
4
""" Given an array of integers, find if reversing a sub-array makes the array sorted. In this algorithm start and stop are the boundry of reversed sub-array whose revarsal makes the whole array sorted. """ def checkReverse(arr): size = len(arr) start = -1 stop = -1 for i in range(size-1): if ...
32e2d9271957d18bcdd0470787d1940587b53631
Ramptl/GraphAlgorithms
/DynamicConnectivity.py
1,825
4.09375
4
# Python3 implementation of # incremental connectivity # Finding the root of node i def root(arr, i): while (arr[i] != i): arr[i] = arr[arr[i]] i = arr[i] return i # union of two nodes a and b def weighted_union(arr, rank, a, b): root_a = root (arr, a) root_b = root (arr, b) # union based on ran...
0298b3fcc8c5e3769c269452329c9ad35af353e7
sforrester23/SlitherIntoPython
/chapter8/Question2.py
134
3.78125
4
words = input().split() suffix = input() i = 0 while i < len(words): if suffix in words[i]: print(words[i]) i += 1
a408a7f6a8db6ff57f81f8c0c8ef88c936284963
akorotenro1967/lesson_2_dz
/dz_2.py
2,730
3.984375
4
''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' # for i in range(1,6): # input = ('0000000000000000000000000') # print(i, input) ''' # Задача 2 # Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр 5. # ''' # sum = 0 ...
c5106a502538de84b5fc4ae99849e33470a48602
aulasau/BSU.Magistracy
/ScriptLanguages/Seminar 3/linked_list.py
585
3.890625
4
class Node: def __init__(self, value, next=None): self._value = value self._next = next assert type(next) == Node or "NoneType", "Wrong type of next node" def __str__(self): return "Value {}, Next: {}".format(self._value, self._next) def __iter__(self): self = self....
62d536a4e632562bf95173b44388a2201e54881a
bitsein/marubatsu
/monte.py
2,327
3.625
4
#〇×ゲームで互いにランダムに埋めていった場合 import numpy as np import random import matplotlib.pyplot as plt def check_occupy(F, P, x): #マスxが空なら1、埋まってたら0、全てのマスが埋まってたら2 if len(F) + len(P) == 9: return 2 elif x in F or x in P: return 0 else: return 1 def check_game(F): #勝敗が決まってたら1、まだなら0 if 1 in F...
2a2ca773cb44e1f00a3d66acd5adc6a6621f61a3
tdnzr/project-euler
/Euler058.py
1,576
3.671875
4
# Solution to Project Euler problem 58 by tdnzr. # This problem is related to problem 28. # Instead of going through the pain of generating the spiral again, # here I use the insight that beginning with the center (spiral side length 1), # the corner numbers in the next spiral (side length 3) can be reached by adding ...
d6f7b090f1a11ec5c5d6e8946bbbe2a3f554406b
kulraween/PY4E
/Exercise/Exercise 9.4.py
456
3.703125
4
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) email = dict() for line in handle: line = line.rstrip() if line.startswith("From "): word = line.split() address = word[1] email.setdefault(address, 0) email[address] += 1 else: ...
b5238294015f833e578046a09b75a71190988204
OmegafacE/Curso-De-Rafa
/both_games.py
5,058
3.984375
4
import random print("Welcome!") continue_program = True while continue_program: print ("Choose a game:") print ("a) Rock Paper Scissors Lizard Spock!") print ("b) Guess the number!") print ('Write "quit" to quit the program') game = input () if game == "quit": print("Shuting down...\...
d63b9f491152c26780d086707d30a2803dc021a9
tjguk/active_directory
/misc/t.py
989
3.75
4
import unittest class DisjointError(Exception): pass class ShorterError(Exception): pass def relative_to(l1, l2): if len (l2) < len (l1): raise ShorterError("%s is shorter than %s" % (o, l2)) for i1, i2 in zip(reversed(l1), reversed(l2)): if i1 != i2: raise DisjointError("%...
0fa761d9b93876aaec9877b899459cfaa2a7879e
rannrunn/py35
/sample/time/_time.py
452
3.59375
4
import datetime now = datetime.datetime.now() print (now) print (now + datetime.timedelta(hours=1, minutes=23, seconds=10)) s1 = '10:33:26' s2 = '11:15:49' # for example FMT = '%H:%M:%S' tdelta = datetime.datetime.strptime(s2, FMT) - datetime.datetime.strptime(s1, FMT) s1 = '2017-06-20' s2 = '2017-06-19' s3 = '0...
a6ce3fb1f8f7f73d7625b1dce69b40c830af05ea
SharmaAjay19/DataStructuresPython
/Dijkstra.py
2,048
3.609375
4
from Graph import Graph def dijkstra(graph, source): shortestPathSet = [] overallSet = [i for i in range(graph.size)] mindistances = [float("inf") for i in range(graph.size)] mindistances[source] = 0 while len(shortestPathSet)<graph.size: minind = overallSet[0] minval = mindistances[overallSet[0]] for x in o...
a104e137fed0e697f54c487dde92ea2e29f3f78a
KyousukeAsakura/Math
/Fibonacci_number/main.py
114
3.5
4
N = int(input()) F = 1 bk = 0 for i in range(N): temp = bk print(F) bk = F F = temp + F
3a5b0dfc5f43135ae1a6afa7844f1d1747d071b8
JackHumphreys/Lists
/linear_search.py
810
3.96875
4
def linear_search_input(): searchlist = [] finished = False while not finished: item = input("Please enter item in list (stop to finish list): ") if item == "stop": finished = True else: searchlist.append(item) find = input("Please enter search te...
9efc9a3275fee647957f1edd0e2101ea4bcd4f71
Robinrrr10/python
/src/whileLoop.py
147
3.84375
4
x = input("Enter any name:") y = int(input("How many times the name should print:")) i = 1 while i <= y: print(x) i = i + 1 print("Done")
8cb1445d570c432bfc72b59fcd4d41c58bf53687
DD0s-JCN13/Python_science
/python_myproject/Program_File/2019_iTalthon/NstepTimes.py
322
3.96875
4
def NstepMode(read_in): if type(read_in) is not int: print("格式錯誤,請重新執行程式!") if read_in < 0: print("N階乘最小值為 0! = 1,小於0之階乘不存在") elif read_in == 0: return 1 else: return read_in * NstepMode(read_in-1) print(NstepMode(5))
43e87e4f799cdbb3ecc035bcc7cd9c11c84ca85c
psggs/pylearning
/第一次作业.py
1,330
3.671875
4
dic={"张三":{"年龄":18,"联系方式":111},"李四":{"年龄":29,"联系方式":222}} while True : InputMes=input("输入信息").strip() if InputMes == "delete": DelMEs=input("输入需要删除的用户名").strip() if DelMEs in dic: del dic[DelMEs] print ("修改后的数据库为",dic) else: print ("用户不存在") elif I...
786bbe03feb2abcdee8a2a7e157901d802d25116
MiessiGomes/PythonStudies
/Farenheit-to-Celsius.py
165
3.859375
4
TemperaturaF = input ("Digite a temperatura em Fahrenheit: ") TemperaturaC = (float(TemperaturaF) - 32) * 5 / 9 print("A temperatura em celsius é", TemperaturaC)
2c2c3fc72ff44f34605ef4c8d587f56cc77d1bcd
Rakshith123-123/PESU-IO-SUMMER
/bin.py
799
4.125
4
string = input("enter numbers by space") a = input("enter number to be searched") x = int(a) list = string.split(" ") arr = [] for i in list : arr.append(int(i)) def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l)//2; # Check if x is present at mid if ar...
da68098113faac0d2c0c355799e8fee8fc863638
ian-qian-ting/python_learning
/task1/task1.py
7,121
3.65625
4
#!/bin/python #transform an sorted array into binary tree #from builtins import input as raw_input import random import time class TreeNode: def __init__(self,key,value,parent=None,left=None,right=None): self.key = key self.value = value self.parent = parent self.leftChild = left ...
832bd6e9568184e54381070e76b37924694e04b7
dzhamaldzhamiev/pythonintask
/IVTp/2014/Dzhamiev/task_07_6.py
1,688
4.1875
4
# Задача 6. Вариант 6. # Создайте игру, в которой компьютер загадывает название одного из семи городов России, имеющих действующий метрополитен, а игрок должен его угадать. # Dzhamiev D. R. # 11.04.2016 from random import choice print('Угадайте один из семи городов России, имеющий действующий метрополитен!...
0f23c0c89d1dfadbf5f27313f41e3e7262ebae4e
yangjici/GalvanizeDSI
/week7/GraphTheory/graphs-files/src/shortest_path.py
1,408
3.9375
4
from collections import deque from load_imdb_data import load_imdb_data from sys import argv, exit def shortest_path(actors, movies, actor1, actor2): ''' INPUT: actors: dictionary of adjacency list of actors movies: dictionary of adjacency list of movies actor1: actor to start at ...
bfaec97f8b51d196429ad5fb14edf1e8b57b23d3
aadityadabli97/Python-Practice
/7.py
713
3.875
4
# concept of buttons(packing buttons in tkinter) from tkinter import * main=Tk() main.geometry('400x500') def lelo(): print("lega kya ") def dedo(): print('deo na') frame= Frame(main ,bd=15, bg='grey',relief=SUNKEN) frame.pack(side=LEFT,anchor='ne') b1=Button(frame,fg='red',bg='white',text="lo",comman...
21060130b122055b47d8982a938143da7af62cbb
geekcomputers/Python
/Strings.py
579
4.125
4
String1 = "Welcome to Malya's World" print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a TechGeek" print("\nString with the use of Double Quotes: ") print(String1) # Creating a String # with triple Quotes String1 = '''I'm Malya and I live in a world...
1d0a32e46452eb73dc9244678aa9e41da847bdf4
pythongus/metabob
/hackerrank/two_d_arrays.py
647
3.90625
4
""" 2D arrays module. For Hackerrank tests. """ def create_2d_array(source: str): arr = zip(*[[int(cell) for cell in row.split(' ')] for row in source.split('\n') if row]) return list(arr) def hourglassSum(arr): """Complete the hourglassSum function below.""" hg_arr = [make_hour_glass(i, j, arr) fo...
e1977f7b18b19c0ec20fd80d84aa7020121cfd41
YaccConstructor/pyformlang
/pyformlang/regular_expression/regex.py
10,099
3.984375
4
""" Representation of a regular expression """ from typing import Iterable from pyformlang import finite_automaton import pyformlang.regular_expression.regex_objects from pyformlang.finite_automaton import State from pyformlang.regular_expression.regex_reader import RegexReader from pyformlang import regular_expressio...
7426c6c38eedd5219519eb7a6ed78f8ad8923ecd
MaoYuwei/leetcode
/73.py
820
3.609375
4
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ rows = [] cols = [] m = len(matrix) n = len(matrix[0]) for i in range(m): ...
743706fcd59b0cdf5d768914b40de3d32d095944
PdxCodeGuild/20170626-FullStack
/lab19-blackjack.py
1,248
4.15625
4
# lab 19: blackjack advice # First, ask the user for three playing cards. Save the user's inputs as a string: A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, or K. # Then, figure out the point value of each card individually. Number cards are worth their number, all face cards are worth 10. At this point, assume aces are worth ...
ff27fad98d2bbacefaa30dd428fe9c21972cab4b
kierenmihaly/worldwebproject
/11032020.py
1,091
3.53125
4
# 대부분 프로그램은 사용자의 선택을 요구 # 편집기에서 파일을 저장 한다고하면 저장, 취소 버튼을 # 눌렀는지 판단해서 서로 다른 동작을 해야한다 people = 3 apple = 20 if people < apple / 5: print('신나는 사과 파티! 배 터지게 먹자!') if apple % people > 0: print('사과 수가 맞지 않아! 몇 개는 쪼개 먹자!') if people > apple: print('사람이 너무 많아! 몇 명은... ') # if 조건문은 4 부분으로 이루어짐 # 첫 번째 if 조건의 ...
0baecc58b778dccf9940a8b5991ce49ceb4e2970
hanbee1123/algo
/DataStructures/Graph/clone_graph.py
1,459
3.921875
4
# Given a reference of a node in a connected undirected graph. # Return a deep copy (clone) of the graph. # Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. # class Node { # public int val; # public List<Node> neighbors; # } # Test case format: # For simplicity, ea...
38f32394f593536bd660b8a769a47c39a343131e
NikhilT27/fossnitrrcp31
/02may2020/2DArray.py
860
3.640625
4
# Nikhil Thakare # Link: https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays # fossnitrrcp31 # Code: #!/bin/python3 import math import os import random import re import sys # Complete the hourglassSum function below. def hour...
4c6557576e9b9e68806c296d05fc8085beabe2a7
pannchat/1day1commit
/python/pythonojbect1.py
2,758
3.640625
4
print('EX1-1 : ') print(dir()) x = {'name':'kim', 'age':33, 'city':'Seoul'} y = x y['name'] = 'park' print(x,y, sep="\n") print('EX2-1 : ', id(x), id(y)) print('EX2-2 : ', x == y) # 같은 value(값)을 가지고 있는지 print('EX2-3 : ', x is y) # 같은 object(객체)를 가리키고 있는지? x['class'] = 10 print(x,y, sep="\n") z = {'name':'park', 'age...
b1aab2fb9f4b74a2566c75211555305fceecc4a1
cn5036518/xq_py
/python16/day1-21/day014 内置函数02/04 filter.py
5,006
3.765625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- #@time: 2019/11/2 9:32 #@author:wangtongpei #1筛选出列表中大于3的元素 li1 = [1,2,3,4,5] def func(x): if x>3: #x>3是判断条件 return x def func1(x): #和上面的函数等效 return x>3 #x>3是返回值 li2 = filter(func,li1) #参数1是自定义函数名 参数2是iterable print(li2) #<filter object at 0x000000E2FB4...
87852062576d93b390169fc38c51a01775c49e68
Alkali-1234/Pongtable
/Pongtable Release 1.1/mainp.py
3,688
3.609375
4
import pygame from paddle import Paddle from ball import Ball from button import button import datetime pygame.init() # paddle color color = 255, 255, 255 # datetime d = datetime.datetime.utcnow() # screen setup screen = pygame.display.set_mode([500, 800]) # title and icon pygame.display.set_caption("Pong ...
c7e3e5c27e0a6f63992f35a9a9a6e890fffff47e
tim-burke/voting-capstone
/src/data/query_census.py
2,933
3.71875
4
# This file downloads specific data from the US census, then writes it to .tsv import pandas as pd import click from census import Census def query_census(census, col_id, col_name=None, fips='37'): ''' Calls the census API to get a given column, output it to a pandas Dataframe :census: Initialized Census ...
3f7f8ca45b64d8b1c7d8b9a010ec72eff178f7dc
badluckmath/AGA0503
/EP2/Ex1_Gauss/EP2_Ex1_Gauss.py
9,388
3.890625
4
# AGA 0503 - Métodos Numéricos para Astronomia # Professor Dr. Alex Carciofi # Segundo Exercício de Programação (EP2) # 1) Método de Gauss (3 pontos) # Comentários importantes: #No Método de Eliminação de Gauss, o pivô é o primeiro elemento da linha que #está sendo usada para eliminar termos das demais. ...
e2a8294e758cc126a03d1f441deeb45890f7627c
jakubfolta/Censor
/censor_solidifying.py
704
3.6875
4
def censor(text, censored): return text.replace(censored, len(censored) * '*') print(censor('sadsad kala abhdhd ufhdjw kala fdsf kala', 'kala')) def censor(text, censor_word): censor = len(censor_word) * '*' text = text.split() for index, x in enumerate(text): if x == censor_word: ...
c19b8d9e2ff92a98ecd90a42df23f5ce4c366153
2428036768/leetcode
/222.py
291
3.65625
4
""" 完全二叉树的节点个数 DFS 中等 python 中没有null;用None来代替 """ def countNodes(self, root: TreeNode) -> int: if root == None: return 0 left=self.countNodes(root.left) right=self.countNodes(root.right) return left+right+1
d226211939e52f0275e030a3623b6c9f99158db4
lass7965/Games
/Card games/blackjack.py
5,056
3.765625
4
import random class card: def __init__(self,suit,number): self.suit = suit self.number = number def score(self): if self.number == "A": return [11,1] elif self.number == "J" or self.number == "Q" or self.number == "K": return 10 else: ...
0a3b2dd08eb62bdbbfb9135313b4fcf1b6284b28
mafzaldev/CS261F21PID43
/SearchFilters.py
2,197
3.625
4
from typing import List from abc import ABC, abstractmethod class Filter(ABC): @abstractmethod def perform_search(self, array: List, column, query): pass class startsWith(Filter): def perform_search(self, array: List, column, query): temp = [] for idx in range(0, len(array)): ...
fc27beab996692e8fbf8939c8606021a254b344c
elenaborisova/Python-Advanced
/18. Exam Prep/paint_colors.py
1,333
3.96875
4
from collections import deque def check_secondary_colors(all_colors, combinations): for i in range(len(all_colors) - 1, -1, -1): color = all_colors[i] if color in combinations and not all([main_color in all_colors for main_color in combinations[color]]): all_colors.remove(color) re...
dfc961091b00906fc69355cc0f2a4f314bd34de7
jakefeldy1/Python-Challenge
/Pybank/main.py
2,039
3.703125
4
import os import csv csvpath = os.path.join("..", "PyBank", "budget_data.csv") counter = 0 dates = [] averagechange = [] changeoverperiod = [] x = 0 with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter =',') header = next(csvreader) for row in csvreader: cou...
bd7894e69fe84122cc82c4bf77d3720f912f2e88
bhavanasinguru/PythonGames
/pong.py
2,282
3.9375
4
import pygame BLACK=(0,0,0) WHITE=(255,255,255) RED=(255,0,0) GREEN=(0,255,0) BLUE=(0,0,255) pygame.init() size=(800,600) screen=pygame.display.set_mode(size) pygame.display.set_caption("pong pong") rect_x=400 rect_y=580 #initial position of the paddle rect_change_x=0 rect_change_y=0 #initial speed of th...
33add5b5269389ddb165a37cf427045d804a8df1
riturajkush/Geeks-for-geeks-DSA-in-python
/strings/Check if string is rotated by two places.py
956
4.09375
4
#User function Template for python3 ''' Your task is to check if the given string can be obtained by rotating other string 'p' by two places. Function Arguments: s (given string), p(string to be rotated) Return Type: boolean ''' def isRotated(s,p): q=s[2:]+s[:2] r=s[len(s)-2:]+s[:len(s)...
4f51b174d46501d8b09e2e03a6f8afbfa04224a2
kemingy/techie-delight
/src/ternary.py
331
4.0625
4
# In this post, we will see how to implement ternary-like operator without using # conditional expression like ternary operator, if-else expression or # switch-case statements. def ternary(condition, option_x, option_y): # return option_x if condition is True ans = [option_y, option_x] return ans[c...
4c67009f523be18a04054df60bb0e95ff3dadaec
2020gupta/class103
/bar.py
201
3.8125
4
import pandas as pd import plotly.express as px df=pd.read_csv("data1.csv") graph=px.scatter(df,x="Population",y="Per capita",color="Country",title="Scatter Graph",size="Percentage") graph.show()
e77c297f6ab8d02db150b2f5d8c32a002b8370f1
caleberi/Python-dsa
/bubbleSort.py
232
3.9375
4
def bubbleSort(arr): for i in range(0,len(arr)-1): for j in range(0,len(arr)-1-i): if arr[j] > arr[j+1]: arr[j], arr[j+1]= arr[j+1],arr[j] return arr print(bubbleSort([1,4,3,5,0,67,3,8]))
cb5e8a6533aa1337631030837b8d4ec5fa46bdee
qhuydtvt/C4E3
/Assignment_Submission/haidv/13032106/Bai3.py
108
3.59375
4
def distance(x1,y1,x2,y2): dist=((x1-x2)**2+(y1-y2)**2)**(1/2) return dist print(distance(2,3,4,6))
65d55852750cc5585ea7251accf88c72c68fc3ff
Acedalus/assignment3
/act3.py
1,735
4.03125
4
print("ISQA 3900 Lumber Price Calculator") answer = "y" while answer == "y": print("Please input how much feet of board and of what board type you want (common or rare)") #print("Enter number of board feet: ") #while True: quantity = int(input("Enter amount of board feet desired: ")) if quantity > 0: ...
073e3780d316cfccae727b6c2ed4ca109b0006ad
dhyani21/Hackerrank-30-days-of-code
/Day 24: More Linked Lists.py
1,897
4
4
''' Task A Node class is provided for you in the editor. A Node object has an integer data field, data, and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list). A removeDuplicates function is declared in your editor, which takes a pointer to the head node of a linked list as a para...
e9623179cc0c388aac70deee554622785f96103b
ConorODonovan/other-stuff
/Python/Number Sequences/CollatzConjecture.py
415
4.1875
4
# Collatz Conjecture import time def collatz(num, steps): if num > 1: if num % 2 == 0: num = num/2 else: num = (3 * num) + 1 # time.sleep(0.25) print("{}".format(int(num))) collatz(num, steps + 1) else: print("Steps: {}".format(steps)) if __name__ == "__main__": start = input(...
d25ccb73ab4783014836c4e5e39c9cdcc84b0848
fataik1/Intro-Python-I
/src/rps.py
1,084
4.25
4
#write a program to play rock paper scissors with a user #lets flesh out the rules and think about how this will work #Rules: Rock ---> Scissors # Scissors -> Paper # Paper -> Rock import random # Flow: # Start up program # User will specify their choice users_choice = input("Choose rock, paper, or sci...
b206bb80e10b02a367706b099ea5a63354861185
harshi922/nokia-snake-game
/scoreboard.py
669
3.703125
4
from turtle import Turtle ALIGN = "center" FONT = ("Century Gothic", 13, "bold") class Score(Turtle): def __init__(self): super().__init__() self.color("white") self.penup() self.hideturtle() self.goto(10, 280) self.current_score = 0 self.write(f"Score: {se...
3a0f7dba2f457a742c7d631c4ea1fe9a724edacc
Happyxianyueveryday/leetcode-notebook
/Linked List/445. Add Two Numbers II/445. Add Two Numbers II.py
1,440
3.734375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ...
7c1f187b79bf6e2f661977337d40d084d2bc4489
Redmouse-Python-group4/Azamat
/Task2.py
607
4
4
print("Общество в начале XXI века") a = int(input("Введите пожалуйста ваш возраст:")) if 0<=a<7: print("Вам в детский сад") elif 7<=a<18: print('Вам в школу') elif 18<=a<25: print("Вам в профессиональное учебное заведение") elif 25<=a<60: print('Вам на работу') elif 60<=a<120: print("Вам предоставл...
7fea606364a0d464a9aca22075813f49014d96a3
raindewGH/test
/20200508面试题57.和为s的两个数字.py
2,641
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-05-08 12:15:53 # @Author : raind (848299610@qq.com) # @Link : http://raind.cc # @Version : $Id$ # 输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。 #   # 示例 1: # 输入:nums = [2,7,11,15], target = 9 # 输出:[2,7] 或者 [7,2] # 示例 2: # 输入:nums ...
c1b12bad308dc07aa90d40afeb3a871a4dd8469f
Yejin6911/Algorithm
/프로그래머스/PR_프린터.py
517
3.5
4
#프린터 from collections import deque def solution(priorities, location): priorities = deque(priorities) count = 0 while location != -1: temp = priorities.popleft() location-=1 now = True for i in priorities: if i > temp: now = False ...
58fbd41101fb1067638c898c0f5a0402d3443e63
mleue/project_euler
/problem_0001/python/test.py
691
3.53125
4
import unittest from e0001 import multiples_of_x_below_y, solution class Test0001(unittest.TestCase): def test_multiples_of_x_below_y_examples(self): """it should get the example correct""" test_cases = [([3, 6, 9], (3, 10)), ([5], (5, 10))] for test_case in test_cases: multiples ...
7201785d68fbe66156e22a34d879ee934652bcbc
Sukhrobjon/leetcode
/medium/103_binary_tree_zigzag_level_order_traversal.py
3,259
4.15625
4
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [...
a60a2e8db2289a22ecaea3b3681298a7b0ec3ee0
skysamer/first_python
/코딩오답/4-1(5).py
134
3.890625
4
numbers=[1, 2, 3, 4, 5, 6, 7, 8, 9] output=[[], [], []] for number in numbers: output[(number+2)%3].append(number) print(output)
b24c4319dba5d3f43ae5e34e727acb5c37935f20
amr-raazi/MathsPy
/utilities.py
655
3.6875
4
import math import sys def is_prime(number): try: prime = True if number < 0: return False elif number in (2, 3): return True elif number in (0, 1, 4): return False else: for potential_factor in range(2, math.ceil(math.sqrt(nu...
af2fa2dc12f1a793efb1dc881e421802f934dfbd
akaptur/game
/rooms.py
6,756
3.640625
4
from random import choice, randint from quiz import sortingquiz from riddles import riddles from things import objectlist import json quips = ["""You are knocked out. When you come to, you are a silvery misty version of yourself looking down at your own limp body. You are a ghost.""", """Too bad you're not a cat. G...