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
82c207d672d9350f12803f90dd06740e44cad123
shinotora/py.test000
/new.py
177
3.578125
4
def new(num_buckets=256): """Initializes a Map with the given number of buckets.""" aMap = [] for i in range(0, num_buckets): aMap.append([]) return aMap
94c125c556674ca5a7753979e92e370dd3fff03a
colin-chang/pythonstructure
/binarytree.py
2,333
3.890625
4
class Node(object): """二叉树节点""" def __init__(self, elem=-1, lchild=None, rchild=None): self.elem = elem self.lchild = lchild self.rchild = rchild class CompleteBinaryTree(object): """完全二叉树""" def __init__(self, root=None): self.root = root def add(self, elem): ...
49dea2a0a7e6507795d00dc61962bc2e823a1c3d
jacksheeran/LTassignments
/combine-dictionaries.py
667
3.9375
4
"""dictionaries for tesing""" engnums = {1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 6 : 'six', 0 : 'nul'} ukrnums = {1 : 'odyn', 2 : 'dva', 5 : 'piat', 7 : 'sim', 8 : 'visim', 0 : 'nul'} def combine_dicts(d1, d2): """returns a combined dictionary from two input dictionaries""" combined = dict() ...
7d78dc3a28d6b60077ff1254bc9fe3b5f9c747f7
sara-tmonteiro/aulasdassara
/exercicios/somando-dois-numeros.py
257
3.859375
4
Numero01 = input('Priemiro Numero') Numero02 = input('Segundo Numero') print (int(Numero01) + int(Numero02)) n1 = int(input('Digite um valor')) n2 = int(input('Digite o segundo Valor')) s = n1 + n2 print('A some {} e {} é igual a {}'.format(n1,n2, s ))
660004a8f7251ae0a76aa35a099532f967cd19f8
bedlex/python-day-4-
/methodsShoppingCart.py
2,241
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 20 07:45:54 2019 @author: bedlex """ class shopingCart(): def __init__(self,items): self.items = items def add_to_cart(self): while True: item = input("Enter an item wich you wanna add: ") sel...
567fde1ff57110452acd505bccb01add6e04ecaf
WillHTam/reference
/heapsort.py
1,150
4.0625
4
""" https://books.google.com.hk/books?id=NLngYyWFl_YC&pg=PA127&dq=introduction+to+algorithm+heap+sort&hl=zh-CN&sa=X&ei=HnnTULG2Ga6QiAfhyoEQ#v=onepage&q=introduction%20to%20algorithm%20heap%20sort&f=false """ import heapq def swap(i, j): """ Swap two values helper function """ sqc[i...
9c25291e7cce6ec2d3665e678c7162fbc52c94d0
WillHTam/reference
/f_string.py
770
4.0625
4
name = 'Wombat' age = 69 print(f'Hello, {name}. You are of {age} years.', '\n') # evaluated properly print(f'{2 * 37}', '\n') # call functions def to_lower(input): return input.lower() print(f'He is a {to_lower(name)}', '\n') #direct call print(f'I am a {name.lower()}', '\n') # Can even be used with strings p...
250013f9d8f1cb624ca63725487ec54ad7985317
WillHTam/reference
/bubble_sort.py
1,239
4.1875
4
# Bubble Sort # compare consecutive pairs of elements # swap elements in pairs such that smaller is first # at end of list, do so again. stop when no more swaps have been made def bubble_sort(L): """ inner for loop does the comparisons outer while loop is doing multiple passes until no more swaps """ ...
121b2f2cce2ba327d64a5406490e32386eb447bb
MartyVos/V2ALDS_Week1
/1-mymax.py
709
4.03125
4
# mymax(a) # This function returns the maximum value of a list. # Parameters: # a: list # A list of ints or floats # Return: # m: int # The maximum value of the list def mymax(a): assert len(a) != 0 m = a[0] for x in a: assert (isinstance(x, int) or isinstance(x, ...
9e389be51ab324db021ce7cc0444f54b976adfc8
sam351/TIL
/flask_lecture_191211/python_basics/python_warmup/q1.py
246
3.546875
4
''' 문제 1. 문자열을 입력받아 문자열의 첫 글자와 마지막 글자를 출력하는 프로그램을 작성하시오. ''' str1 = input('input a string : ') # 아래에 코드를 작성해 주세요. print(str1[0]) print(str1[-1])
715d76fb74cc882d1e33f9babde665ea6bd0f0a3
ryanwilsonperkin/calvinball
/calvinball/action.py
655
4.0625
4
"""Action in a Calvinball game.""" class Action(object): """Action in a Calvinball game.""" def __init__(self, verb, preposition, obj): self.verb = verb self.preposition = preposition self.object = obj def __repr__(self): return '{0}({1})'.format(self.__class__, self.__dic...
17e18aa47f32d8c7e1aab585445042dac50b73f1
Stedi65/Calculator
/calculator/app.py
1,550
3.640625
4
import sys from functions import arithmetics from functions import geo # negativ Beispiele: könnte Konflikt mit anderen Funtkionen geben: # from functions import summe # from functions.arithmetics import * # Konstanten in Python werden groß geschreiben. Konvention! OPERATIONS = { '+': arithmetics.summe, '*': ...
f5d16bb396a347c20b9ee354e931b45952382bc1
JonasTrindadeAntunes/Phyton-ClubeDesportivo
/ClubeDesportivo/Amador.py
1,416
3.75
4
from AtletaNaoProfissional import AtletaNaoProfissional #from ficheiro.py import Class class Amador(AtletaNaoProfissional): salariominimo = 5 # O valor desta percentagem pode ser atualizado, e é igual para todos os atletas # percentagem aplicada aos premios do atleta no mes percentagem_variav...
87da2774a88509c32515dd5a784b104d4cf4899c
danecollins/mpy
/basepy/dict.py
488
3.828125
4
d1 = dict(a=1, b=2, c=3) print(len(d1)) # use len to get count del d1['a'] # to delete # get name value pair print(d1.pop('b')) # return value of b and removes it while d1: print(d1.popitem()) # returns k,v tuples d2 = {} d2.setdefault('a', 3) # get value of a or set to 3 and return def x(): assert T...
0a32d6916320b59f96217d2c3f3fd826ab97c779
BiggBaddBluee/mock_atm_V2
/mock_atm_v2.py
3,870
3.84375
4
database = {} from random import randrange bal = 5000 #landing page, an entry point into the system def landingPage(): print('Welcome to Bankblue, Do you have an account with us?') options = int(input('Yes (1) No (2)\n')) if (options == 1): login() elif (options == 2): ...
154fa273fd39d4e222b4516c6bd6a45da94427bf
felipecdo/dicom_explorer
/file_helper.py
297
3.75
4
import os; def list_all_files(directory_path): print "----" paths = [] for (dir, _, files) in os.walk(directory_path): for f in files: path = os.path.join(dir, f) if os.path.exists(path) and os.path.isfile(path): print path paths.append(path) return paths
912f71e7813de37a3e70d91f41c6b8c57353d45b
Nihiru/Python
/Leetcode/maximum_subarray.py
522
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 4 17:34:37 2020 @author: nick """ def maximum_subarray(array): # setting the maximum sub array similar to max_sum = array[0] current_sum = max_sum for ele in array[1:]: current_sum = max(ele + current_sum, ele) # adding el...
85fc61504048d840fd116d191f9a2196429a1182
Nihiru/Python
/AlgoExpert/ClosestValueInBST.py
2,290
4.09375
4
""" :Checking the closest value in BST :Logic :Set the closest value to -infinity :Compare the current node value with the target value :If current node value is lesser than target value then traverse the right subtree for further comparison :Else traverse left subtree for comparison :Complexi...
c66034b359d7cde0275795f476674c75a2af201c
Nihiru/Python
/Leetcode/ContinuousSubarray.py
373
3.59375
4
def findMaxLength(nums): counts = {0:-1} max_len = 0 count = 0 for i in range(len(nums)): if nums[i] == 0: count += -1 else: count += 1 if count in counts: max_len = max(max_len, i- counts.get(count)) else: counts[count] ...
1aa4e8017ba7143e8ba8447485ec3755dc25136a
jgbaldwinbrown/geneview
/geneview/karyotype/_karyotype.py
3,407
3.53125
4
""" Plotting functions for create karyotype plots. Copyright (c) Shujia Huang Date: 2016-02-19 """ from __future__ import division, print_function import numpy as np from pandas import DataFrame import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from ..util import chr_id_cm...
3d1715aaa82e42fc60cd5a672272f9f65577fb89
hearecho/pycommon
/datetime_test.py
1,092
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/21 17:33 # @Author : hearecho # @Site : # @File : datetime_test.py # @Software: PyCharm from datetime import datetime,timedelta import time #-----------*返回当前时间*------------ now = datetime.now() print(now) #-----------*指定时间日期*------------ dt = ...
04b6bb1fb2c080c5800b7a5aab1fc8ef9d924425
hejibo/Python-for-Psychologist
/Lecture 11. Excel File Processing/ReadXls.py
305
4.03125
4
''' __author__ = 'hejibo' demostrate how to read excel using python ''' import xlrd from xlrd import open_workbook wb = open_workbook('simple.xls') for s in wb.sheets(): print 'Sheet:',s.name for row in range(s.nrows): for col in range(s.ncols): print s.cell(row,col).value
cfcd031e3eaffb141d04b815a4f0a24adf5f4cea
vatsalmehta-3009/MLZS-CLASS-11-PRACTICALS
/Bhakti/lists.py
385
3.953125
4
ls = ['2' , 4, [7]] print(ls) ls = [1,2,3,4,5,6] ls[0] = 9 print(ls[0]) ls = [1,2,3] ls += 'abc' print (ls) ls = [2,5,6] ls[0:3] = [9] print (ls) ls =[3,5,6] ls1 = 2 print (ls * ls1) ls[0:3] = 0,3/3 print (ls) ls = [0, 1.0] print (type(ls[1])) ls = [1,[1,2,['a']]] print (type(ls[1][2][0])) names =[] name = ...
294d834e6e5c498d24e195336416c9047ad1693a
vatsalmehta-3009/MLZS-CLASS-11-PRACTICALS
/gracy/string2.py
150
4.21875
4
string = 'alphabet' i = input('enter an alphabet:') if(i in string): print(i,'is in alphabet') else: print(i, 'is not in alphabet')
1c64ebd3b822ce08309fb5557d477639e4013cc5
rizalwildan/computer-science
/computation numeric/Bisection/Python/bisection.py
528
3.796875
4
def func(x): return x**3 + x**2 - 3*x - 3 def bisec(a, b): c = a while ((b-a) >= 0.01): #cari nilai tengah c = (a+b)/2 #check apakah nilai tengah mendekati nol if (func(c) == 0.0): break if (func(c)*func(a) < 0): ...
f5d1d374f4b3ffe9fc1ec04f069b6f52f7838fd3
yh08037/ExercisePygame
/사각형 그리기.py
1,265
3.5
4
import pygame #게임 엔진 초기화 pygame.init() #RGB포맷으로 색 정의 BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) #화면의 크기과 폰트, 제목을 설정 size = [400, 300] screen = pygame.display.set_mode(size) pygame.display.set_caption("Draw Rectangle") #닫기 버튼을 누를 때까지 반복 do...
2e373317f171f9a6ba91dc713cb32d2c4797c835
BobGanti/luhn-algorithm
/authentication.py
1,976
3.609375
4
import random class Authentication: def __init__(self): self.sum = 0 def verify_card(self, card_num): total_even_i = 0 total_odd_i = 0 str_list = str(card_num) for i in range((len(str_list) - 1), -1, -1): if i % 2 == 0: num_even...
b0dd906b06cafa81f2c03ce7237cb4a7a970de9c
saa-lem/Password-Locker
/user_test.py
1,143
3.75
4
import unittest from user import User class TestUser(unittest.TestCase): ''' Test clas that defines test cases foe the User class ''' def setUp(self): ''' Method to run before test cases ''' self.new_user = User('Salem', 'Owino', 'Salemitho', 'steph1') def ...
1472c349b5660d46f6c7f7560ad6fcfc9f253bd1
srujana2105/CSCE636_DeepLearning
/HW1_LinearModels_DigitClassification/code/LRM.py
4,842
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 6 12:00:48 2019 @author: """ import numpy as np import sys """This script implements a two-class logistic regression model. """ class logistic_regression_multiclass(object): def __init__(self, learning_rate, max_iter, k): self.learn...
12876ae07371f7911c32a878edf13cd1e723f691
stevalang/Data-Science-Lessons
/statistics/blackjack.py
1,240
3.84375
4
from random import random class Card(): def __init__(self, suit, rank): self.suit = suit self.rank = rank self.length = 0 if rank >= 10: self.points = 10 elif rank == 1: self.points = 11 else: self.points = rank def __repr__(s...
a13938ce25ca826cf3a21e4b63ca8afc446918e6
stevalang/Data-Science-Lessons
/Pandas/series_challenge.py
1,476
3.5625
4
import pandas as pd prices = pd.Series([1,1,2,3,5], index=['apple', 'pear', 'banana', 'mango', 'jackfruit']) inventory = pd.Series([10, 50, 41, 22], index=['pear', 'banana', 'mango', 'apple']) discount_prices = prices.apply(lambda x: .9 * x if x > 3 else x) produce = pd.DataFrame({'price...
dfe0e90a0cd120c46632f6c09ba4259e94e58f22
stevalang/Data-Science-Lessons
/statistics/binomial_cdf.py
3,511
4.125
4
''' CDF is Cumulative Distribution Function - cumulative implies accumulator - cumulative provavility between 0 and some value of k (inclusive) ''' def factorial(n): prod = 1 for num in range(2, n+1): prod *= num return prod def combinations(n, k): return factorial(n) / (factorial(n-k) * ...
a46330c49e5fff962ce01c4609b78696e173dbc2
stevalang/Data-Science-Lessons
/statistics/daily_challenge.py
753
3.671875
4
''' A family has two pets. We know all of the pets are either a dog or cat. If the family doesn't have a preference of one type of animal over the other (equal probability of each pet being a dog/cat), and we know that the family has one at least one cat; what is the probability that both pets are cats? ''' # Event ...
6e4fd7b62f7a94f069eab77bc17f5d7d6506a95f
stevalang/Data-Science-Lessons
/statistics/07_remove_outliers.py
232
3.578125
4
from detect_outliers.py import detect_outliers def remove_outliers (lst): outliers = detect_outliers(lst) output = [] for num in lst: if num not in outliers: output.append(num) return output
00c305f72eb4ca256dd67b8596097b834fb7c910
sandesh-chhetry/basic-python-
/Python Assignment 4/session3_functional.py
2,584
4.25
4
""" ---------------------------------------------------------------------------------------------------------------------------------------------------- """ """ 1. Write a program to display all prime numbers from 1 to """ ##function to find prime number in a range def findPrimeNumber(initial,final): for i i...
c29246c37d513184514a1319aec0688b4e3db1f2
sandesh-chhetry/basic-python-
/Python Assignment 1/listGetExample.py
421
4.15625
4
##Exercise 4. Consider a list of any arbitrary elements. Your code should print the length of the list ##and first and fourth element of the list. ##list which contain some element elements = ["1st position", "2nd position", "3rd position", "4th position", "5th position", "6th position"] print("Length of the give...
413b46189ab8c8bfd51273c4d4c44914509296eb
ARTFL-Project/libphilo
/python/philologic/utils/OutputHandler.py
766
3.53125
4
#!/usr/bin/env python import sys class OutputHandler(object): """Modifies the default sys.stdout in several ways: - unbuffers sys.stdout - adds ability to print to file and console with one print statement - adds ability to disable logging or printing to console""" def __init__(self, console...
16447713cea05103fdf1acc81a54dd3178aa39a8
beemnipon56/CP3-Nipon-Kamfoy
/Exercise5_2_Nipon_K.py
122
3.578125
4
s = float(input("Please enter your distant (m) :")) t = float(input("Please enter your times (s) : ")) print(f"{s/t} m/s")
aa6c3ad5f25fc007228b573fafdd7817d83bfc61
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Tarea4/Problema05S.py
330
3.703125
4
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- ''' Josue Artemio Hernandez Rodriguez, 316060064 Este programa realiza la suma de los primero n naturales, donde esa n la da el usuario. ''' print "***SUMA DE LOS N PRIMEROS TERMINOS****" from Problema05 import suma_n n = input("Dime hasta que número 'n' quieres sumar: ") ...
4319632df4120a2a1fc16e08ed5666b455b0f4a7
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Practica/Problema3.py
715
4
4
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- ''' Josue Artemio Hernandez Rodriguez, 316060064 Similar al problema anterior. solo cambia el numero al que se eleva la función. Usando la recursividad se resuelve, dado un numero n, se calculo la suma de los cubos anteriores a esa n ''' n = input ("Dame el número a calcula...
d2a8e97cec6a7e28affd4e0209eae2bb618bcfd5
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Tarea8/Problema2.py
1,510
4.25
4
'''filas = int(input ("Introduzca el numero de filas de sus matrices: ")) columnas = int(input ("Introduzca el numero de columnas de sus matrices: ")) matriz1 = [] matriz2 = [] matriz3 = [] for i in range (filas): matriz1.append( [0] * columnas) matriz2.append( [0] * columnas) matriz3.append( [0] * columnas) print...
cab1953a37171d8cccf35d9894a65d3fe5e7d03c
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Practica/Problema6.py
294
3.6875
4
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- ''' Josue Artemio Hernandez Rodriguez, 316060064 Lo que hice fue usar while, y poner como condicion que mientras n sea mayor a 1 se repita el pro- ceso hasta que no sea 1 ''' def fac(n): f = 1 while n > 0: f *= n n -= 1 return f
9c5f23b817fd6536afd0912229e37a80fc3dfbac
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Tarea5/Problema09S.py
367
3.71875
4
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- ''' Josue Artemio Hernandez Rodriguez, 316060064 Este programa le pide al usuario una cadena, y la invierte, es decir invierte el orden de las letras empezando desde la última hasta la primera ''' from Problema09 import inversa cadena = input("Dame una palabra cualquiera en...
cc65da3f90e0425dba6d247f77056ccb8981306a
316060064/Taller-de-herramientas-computacionales
/Clases/Programas/Ulam.py
588
3.5
4
# -*- coding: utf-8 -*- def ulam(x): #if (x/2)*2-x == 0: if x%2 == 0: # Estuve atorado usando solo con una funcion, e intentando # con las formulas de impar y par, es decir 2*x y 2*x-1. Y ademas pense que # podría realizarlo con un while dentro de un if return...
5d94d8c05c421c3646c269da07e37799cccfd6d7
semg101/13-IBM-Deep-Learning-using-GPUs-to-scale-and-speed-up-deep-learning-
/6_Lab_CNN_with_GPUs/GPU.py
15,831
4.25
4
#Digit Classification using Convolution Neural Networks on GPUs (with IBM PowerAI) (External resource) #Import the MNIST dataset using TensorFlow built-in feature--------------------------------- ''' It's very important to notice that MNIST is a high optimized data-set and it does not contain images. You will need to...
d9763b0129034dd6a347acb2c8aa6e8ae3b8c869
tsullivan/pyexercises
/09-pythagorean-triplet.py
576
4.03125
4
# Problem 9 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a**2 + b**2 = c*2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. goal = 1000 def run(pm, pn): a = b = c = 0 m = pm ...
83e25601ede1e7cf37dacaa1a8a854a0cfb42b7c
tsullivan/pyexercises
/13-problem.py
259
3.5
4
# Work out the first ten digits of the sum of the following one-hundred # 50-digit numbers. numFile = open("13-input.txt", "r") numLines = numFile.readlines() number = 0 for i in xrange(len(numLines)): number += long(numLines[i]) print(str(number)[:10])
563232ddfba664d3554bb592dc5866465c682144
cardstdani/military-alphabet-python
/MainClass.py
459
3.609375
4
wordsList = ["Alfa", "Bravo", "Charli", "Delta", "Eco", "Foxtrot", "Golf", "Hotel", "India", "Julia", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-Ray", "Yankee", "Zulu"] inputString = input() outputString = "" for c in inputString: ...
d17f426892c5a23e6d6525b8038003e453f13528
sugataach/play
/2sum.py
590
3.71875
4
def twosum(arr, k): seen = set() for num in arr: target = k - num if target not in seen: seen.add(num) else: print((num, target)) def twosum2(arr, k): # sort the array O(n*logn) arr.sort() # left, right pointer left_pointer = 0 right_pointer = len(arr)-1 # walk the list from left to right while le...
56426b780ce919d9681262576fdfafdcd4b1ce02
sugataach/play
/2sum_almost.py
733
3.765625
4
def twosum_almost(arr, k): arr.sort() left_pointer, right_pointer = 0, len(arr)-1 has_match = False almost_pair = None almost_sum = float('inf') while left_pointer < right_pointer: _sum = arr[left_pointer] + arr[right_pointer] if abs(k-_sum) < almost_sum: almost_sum =...
199223c05f1178b8c1aadd3b6d7a3acf5b4b216a
ooici-eoi/fenics-ptypes
/test_vector.py
3,082
3.609375
4
__author__ = 'SChatterjee' from dolfin import * import numpy #-------------------------------------------------------------------------------------------- # One can create a vector.... and also a matrix and a general tensor #-------------------------------------------------------------------------------------------- ...
aa2cd8447b492cb7ca8a2b94c830a444c76904f8
SkyeWoo/zhihu_spider
/InvertedIndex.py
688
3.578125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- #Filename: InvertedIndex.py #Author: Wu Xin #Email: dango.xin@gmail.com #Date: 2017.6.1 import re import string import pandas as pd def create_inverted_index(filename): src_data = open(filename, errors = 'ignore').read() list_data = src_data.split(' ') set_data = set(...
4d7fe1d13c8b98f35c49b8789b5468020e455a07
mspgeek/Client_Portal
/Scripts/ict/ict/test.py
183
3.515625
4
from datetime import datetime start = datetime.utcnow() date = start.date() time = start.time() print(datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")) print(date) print(time)
bf66495bef57ff50d0e0112c3d2ad6f3778f4015
anastasia0418/py_advanced
/урок_01/1 урок.py
2,190
3.5625
4
# Приведение строк к типу bytes, проверить тип и содержание соответствующих переменных. word1 = 'разработка' word2 = 'сокет' word3 = 'декоратор' print('\n', word1, type(word1), '\n', word2, type(word2), '\n', word3, type(word3)) b = bytes(word1, 'utf-8') b2 = bytes(word2, 'utf-8') b3 = bytes(word3, 'utf-8') print('\nП...
4b5553268669ed7df911c1c48260746818c19594
oosantia/Othello
/othello_class.py
7,744
4.21875
4
class InvalidOthelloMoveError(Exception): '''Raised whenever an invalid move is made''' pass class OthelloGameOver(Exception): ''' Raised whenever there is no moves left for both players ''' pass class Othello: def __init__(self,num_rows:int,num_columns:int,initial_player:str,top_positio...
302e14a0a325f6763f28b5f2c5d567859717fecf
joescalona/Programacion-Astronomica
/Tarea 1/ejercicio3.py
2,125
4.40625
4
#NUMEROS DE MENOR A MAYOR #PROGRAMA MAS LARGO YA QUE CONSIDERE DIVERSAS OPCIONES INGRESADAS POR EL USUARIO #DISCULPAR POR LA ABUNDANCIA DE CODIGO print('------ NUMEROS DE MENOR A MAYOR (DISTINTOS) ------'+'\n') #SOLICITAR NUMERO Y VERIFICAR QUE SEA ENTERO a=input('Ingresa un numero = ') #SI UN FLOTANTE, TAL COMO ...
ff73a2f847225274005d382e389a397c61b0acac
joescalona/Programacion-Astronomica
/Tarea 4/tiare.py
807
3.984375
4
# coding: utf-8 # In[6]: def encrip(string,desplazamiento): #crear abecedario para ver si el caracter pertenece al abc o no abc ='abcdefghijklmnopqrstuvwxyz' cod = '' for car in string: #si el caracter pertenece a los caracteres del diccionario, hacer el código que ya tenás if car in a...
aafe0e3ec5d4229aee900d54e7a8086b095126ed
joescalona/Programacion-Astronomica
/Tarea 5/Graficas/juntos.py
2,837
4
4
# -*-coding:utf-8-*- import time import matplotlib.pyplot as plt import numpy as np #Fibonacci while loops def Fib_while(n): time.clock() #comienza el tiempo a correr cont = 0 #se inicializa el contador x1 = [] ##se inicializa eje x y1 = [] #eje y r = [1,1] while len(r) <= n: #la cantidad de elementos en la li...
181b5324ba8239fc341d0304edc0007e2e73fde9
wiselyc/python-hw
/swap.py
352
4.34375
4
def swap_last_item(input_list): """takes in a list and returns a new list that swapped the first and the last element""" input_list[0], input_list[-1] = input_list[-1], input_list[0] # gets the first and last element and makes the first element = the last and the last element = the first return input_l...
7ccc30224ff1bf81d7142c4ffaec5525b11a81f6
linfengzhou/LeetCode
/archive/python/Python/unsorted/682.baseball-game.py
664
3.5
4
class Solution(object): def calPoints(self, ops): """ :type ops: List[str] :rtype: int """ new_ops = [] for point in ops: if point == 'C': new_ops.pop() elif point == 'D': new_ops.append(new_ops[-1] * 2) ...
58526088e3fb0f233400ca6bb5eefe05cf3affce
linfengzhou/LeetCode
/archive/python/Python/binary_tree/236.lowest-common-ancestor-of-a-binary-tree.0.py
1,095
3.859375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # what if p or q not in the tree class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode ...
4d5dc66583e39f4b3d0b5b0b73b1c89c1a746c92
linfengzhou/LeetCode
/archive/python/Python/depth_first_search/131.palindrome-partitioning.py
1,756
3.578125
4
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ def get_is_valid(s): n = len(s) # 2D array whether start, end index substring is palindrome or # not is_palindrome = [ ...
1c68c60dc66efd7401e73672e1fe18262100963f
linfengzhou/LeetCode
/archive/facebook/28.implement-strstr.py
476
3.53125
4
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if (not haystack and not needle) or needle == haystack: return 0 sub_len = len(needle) for i in range(len(haystack)): ...
db316ef0d396ee7972731f1cd754b5d77105c371
linfengzhou/LeetCode
/leetcode_115/33.search-in-rotated-sorted-array.0.py
1,060
3.625
4
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # [1, 2, 3, 4, 5, 6] # [4, 5, 6, 1, 2, 3] if not nums or len(nums) == 1: return -1 start, end = 0, len(nums) - 1 ...
4c41c14269844538b6468fa4858bcdcd856d33e8
linfengzhou/LeetCode
/archive/python2/349_intersection_of_two_array.py
540
3.640625
4
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ res = [] nums1_dict = dict() if len(nums1) * len(nums2) == 0: return [] else: for num...
bd1fd10205be58a062aa6e5f03eb2c05b5ae7556
linfengzhou/LeetCode
/archive/python/Python/unsorted/160.intersection-of-two-linked-lists.py
1,071
3.78125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ # find t...
2c192538c9f523ce6635753904cae93b5178e163
linfengzhou/LeetCode
/archive/python/Python/binary_tree/98.validate-binary-search-tree.0.py
713
3.796875
4
# 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 isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ res = [] ...
3836b971c2ef0a35ab3ec9d00749e980853bb03b
linfengzhou/LeetCode
/archive/python2/110_balanced_binary_tree.py
1,993
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # my version: based on maximumn depth class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rt...
73fef8e3607227648967ecd7ca49b6cc034e7a1f
linfengzhou/LeetCode
/archive/python2/500_keyboard_row.py
699
3.6875
4
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ row_dict = {1: 'qwertyuiop', 2: 'asdfghjkl', 3: 'zxcvbnm'} res = [] for word in words: word_row = 0 ...
40cd6b0cb30f5b49af51b92691b203094b27da23
linfengzhou/LeetCode
/archive/python/217_contains_duplicate.py
762
3.59375
4
# My solution class Solution(object): def containsDuplicate(self, nums): nums_count = {} for item in nums: if not(str(item) in nums_count): nums_count[str(item)] = 1 else: nums_count[str(item)] += 1 for count in nums_count.values(): ...
128771062011bd1ff7b71a415deae22769522002
sjlee2016/Cracking-the-Code_Interview
/CH2-Linked_Lists/2.2_Remove_Nth_node.py
906
3.765625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode "...
ce22a97e5a0a1d07e02855da30bc3083cafdabba
abmurli/my_codes
/python_code/Self-test/sorting/find_the_captain_room.py
207
3.734375
4
group = 5 input = "1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2" rooms = map(int, input.split()) room_list = list(rooms) for i in room_list: if room_list.count(i) == 1: print(i)
ef7471e8ae579997b4d451f909899757cad7d019
abmurli/my_codes
/python_code/Self-test/diagonal_diff.py
501
3.578125
4
def diagonal_diff(arr): ld = 0 rd = 0 for _ in range(0, len(arr)): ld = ld + arr[_][_] count = 0 for i in range(len(arr)-1, -1, -1): rd = rd + arr[i][count] count = count + 1 total = ld - rd print(abs(total)) if __name__ == '__main__': # n = int(input().strip())...
9b7d21e47bf0b921f3d10fef4bc16988de5a054e
abmurli/my_codes
/python_code/Self-test/regex_test.py
1,691
3.671875
4
import re # line1 = "Today is 10th May, 2021, Just anaother day in the year 2021" # regex_pattern_date = "[0-9]{2}th" # regex_patter_year = "[0-9]{4}" # regex_patter_month = "[A-Za-z]{3}{Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec}" # # line1_list = str(line1).split(" ") # # for i in line1_list: # if re.match(r...
62482eb26b465185c7301587a6667e2b8fa18603
phttrang/MITx-6.00.1x
/Problem_Sets_3/Problem_2.py
1,834
4.25
4
# Problem 2 - Printing Out the User's Guess # (10/10 points) # Next, implement the function getGuessedWord that takes in two parameters - a string, secretWord, and a list of letters, # lettersGuessed. This function returns a string that is comprised of letters and underscores, based on what letters in # lettersGuessed...
097d03377de001d8e51d3cc9719ff237f8126571
R-Rudolf/scramble
/scramble.py
4,197
4.03125
4
__author__ = 'Rudolf Horvath' import doctest class TextBlock: """ This class represents a text sequence. It can have a given type like *word*, *special*, and it can be scrambled. """ textTypes = {"word":0, "special":1} def scramble(self): """ This function leaves the first an...
9b5ca67e0d4a071843f4bf7b4584e3973bb9300b
srobo/sr-turtle
/test.py
2,195
3.546875
4
from __future__ import print_function import time from sr.robot import * SEARCHING = "SEARCHING" DRIVING = "DRIVING" R = Robot() def drive(speed, seconds): R.motors[0].m0.power = speed R.motors[0].m1.power = speed time.sleep(seconds) R.motors[0].m0.power = 0 R.motors[0].m1.power = 0 def turn(s...
f68f226507d7421b941dfb374137d8701024970a
hackjsw/pythonStudy
/studyFromBook/vampire.py
283
3.984375
4
name = input() age = input() if name == 'Alice': print('Hi Alice.') elif int(age) < 12: print('you are not Alice, kiddo.') elif int(age) > 2000: print('Unlike you, Alice is not an undead, immortal vampire.') elif int(age) > 100: print('you are not Alice , grannie.')
5338682a088acde9120d654a28dabcf197c4c2c5
AleksandrSarkisov/BinarySearchTree
/TreeNode.py
3,148
3.921875
4
class Node(object): def __init__(self, data, left, right): self.data = data self.left = left self.right = right class TreeNode(object): """docstring for TreeNode.""" def __init__(self): self.root = None self.count = 0 self.height = 0 def isLeaf(self, n...
769a8926078e67d5894abbd6422c8c9e3827c96f
denver/learn_python
/lessons/ex13_a.py
573
4.09375
4
# ex 13 #2 # learn python : author : denver peterson from sys import argv script, first, second = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second #print "Your third variable is:", third #print "Your fourth variable is", fourth age = raw_inp...
bb536d9a769dcc2122a8b5ee72e233440cce8655
StaicuBogdan/UniStuff
/Anul I/LFA Problema1/Problema.py
1,650
3.59375
4
cuvant = input("Dati un cuvant:") fisier = open("fisier", 'r') alfabet = fisier.readline() noduri = fisier.readline().split() nr_muchii = int(fisier.readline()) nod_initial = fisier.readline() lista_stari_finale = fisier.readline().split() dictionar = {} def accepta_cuvant(cuvant, nod, listastarifinale): sem = ...
445660c19149c7e08747e67c86a6a4cc608d3801
StaicuBogdan/UniStuff
/Anul II/Algoritmi_Avansati/Lab7/Ex1.py
1,129
3.640625
4
import math class Plane: def __init__(self): abc = input() a, b, c = [float(value) for value in abc.split()] if abs(a) <= 0: self.vertical = True self.a = b else: self.vertical = False self.a = a self.b = c t = int...
75d02d733a8f7121cc694a890b034c85e6bb93dd
TreesClouds/PiE2020
/challenges.py
4,777
3.796875
4
# Team 35 Coding Challenges # Problem 1 def convert_time(num): hour = num // 100 minute = num % 100 if hour > 12: hour -= 12 return [hour, minute] # Testing problem 1 print("Testing Convert Time") print(convert_time(1738)) # [5, 38] print(convert_time(0)) # [0, 0] print(convert_time(2359...
feb10b2dccd5bb2e8569be3d1408c0860a61f1e2
IrinKalkatina/All-the-Same-Elementary-
/Program1.py
829
4.0625
4
def appendElementsToList(listForNumbers): listLength = int(input("How many elements do you want to append? ")) for i in range(listLength): elementInp = int(input("What element do you want to append? ")) listForNumbers.append(elementInp) return listForNumbers def chekIfElementsAreEqual(listF...
e99cb327206c0f68bea9e5a116878d3b0ea49f97
shaipld/Practie-Python
/test python1.py
3,665
3.9375
4
def user_choice(): print("what size game board you want to draw? ") game_size = input() return game_size def print_game_board(size): size = int(size) width = "-"*3 + " " length = "|"*1 + " " + "|" + " " print(width * size) for i in range(size): print(length*size) print(w...
2945e387eb1a73bd8610e69bf79b7d0ff0b9462b
qrzhang/Udacity_Data_Structure_Algorithms
/3.Search_Sorting/recursion.py
1,221
4.1875
4
"""Implement a function recursively to get the desired Fibonacci sequence value. Your code should have the same input/output as the iterative code in the instructions.""" def get_fib_seq(position): first = 0 second = 1 third = first + second seq = [first, second, third] if position < 1: r...
72ae6ace6818a8f10c24cf3a9bf1a8a22fd897e9
songx2-xy/HW3
/HW3_b.py
514
3.9375
4
year=input("Please input a year: ") if year.isdigit(): if (len(year)<=4): y=int(year) if (y%4==0): if(y%100==0): if(y%400==0): print(y," is a leap year") else: print(y," is not a leap year") else: ...
e9127e8c3166ecb744e16fc8c33d34c20a4f4cf7
asmaier/haddock
/haddock/haddock.py
467
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import random from io import open def curse(lang="en"): if lang not in curses: try: filename = os.path.join(os.path.dirname(__file__), 'curses_%s.txt' % lang) with open(filename, encoding='utf-8') as f: curses[...
4b7532749ae827c6832a08669a1923536af361b0
feizc/Machine-Learning-Algorithm
/linear_regression/lasso.py
1,581
3.609375
4
""" Lasso 回归 费政聪 """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model,cross_validation def load_data(): ''' 加载用于回归问题的数据集 ''' diabetes = datasets.load_diabetes() return cross_validation.train_test_split(datasets.data,diabetes.target, test_size=0...
c4e828c0f515e5f7b03bdb84814ffa6b2e1ed5d2
vikas08-cmd/ProjectCMS
/venv/cmsproject.py
2,778
3.8125
4
idlist=[] namelist=[] agelist=[] moblist=[] addrlist=[] def addcustomer(id,name,age,mob,addr): idlist.append(id) namelist.append(name) agelist.append(age) moblist.append(mob) addrlist.append(addr) def searchcustomer(id): i=idlist.index(id) return i def deletecustomer(id): i = idlist.i...
d514f7069b332fe3a81a51ec038a6bb9f7e61bf2
vinihsouza/BasicoPython
/Básico Python II.py
15,805
4.1875
4
""" #Exercicio 1 val1 = float(input('Digite o valor 1: ')) val2 = float(input('Digite o valor 2: ')) if val1 > val2: print('Valor 1 maior') elif val1 == val2: print('Valor 1 e 2 são iguais') else: print('Valor 2 maior') #Exercicio 2 val1 = float(input('Digite um valor: ')) if val1 < 0: pr...
aa00145cfff0c3d87d1ebc57537143777a49c728
opeoje91/Election_Analysis
/CLASS/PyPoll_Console.py
1,634
4.4375
4
#The data we need to retrieve # Assign a variable for the file to load and the path. #file_to_load = 'Resources/election_results.csv' # Open the election results and read the file #with open(file_to_load) as election_data: # To do: perform analysis. #print(election_data) import csv import os # Assign a varia...
dee97b21b9e2b31df218ebf2f75f51155de51650
opeoje91/Election_Analysis
/CLASS/lists.py
1,247
4.625
5
counties = ["Arapahoe","Denver","Jefferson"] #print(counties) #print(counties[0]) #print(counties[2]) ##-to know the second to last item in list, -1 to know the last item #print(counties[-2]) #print(len(counties)) ##slicing to get the first 2 items in counties #print(counties[0 : 2]) ##slice to get the first item in co...
742c811058b998cadf18494959b9935a308961bb
wojciechowskimarcin/piatkaCMI
/zajecia02/00-Podstawy.py
2,566
3.859375
4
import array x = array.array('b') x.append(5) x.extend([6,7,8]) print("To jest element tablicy:", x[0], ",", x[1]) ### Listy tekst = "To jest lekcja Pythona" print("Trzecia litera ze zmiennej tekst to:"+tekst[2]) lista = [1,2,3,4,5,6,7,8] print("ilość elementów w lista:", len(lista)) print (lista*3) lista.append(9)...
571d49aef7ec2a227a22cbc15eac8be14697fadc
alfaijmansuri/poems-of-your-favorite-words-in-python
/poem.py
4,713
4.25
4
import sys ''' This programme will take keywords as input from user and will display poem relaed to their input keywords ''' print("POEMS OF YOUR FAVOURITE KEYWORDS\n") name = input("enter your name\n") print("dear" , name , "you have to choose from following keywords") print("\n") print('''keywords :\n\nalone\ncraz...
811d94f95e7888628b0e10519c0354f0578ae74f
damaainan/MyLang
/Python/Algorithm/sort/shell.py
942
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Python 3.5 # 希尔排序 class SQList: def __init__(self, lis=None): self.r = lis def shell_sort(self): """希尔排序""" lis = self.r length = len(lis) increment = len(lis) while increment > 1: increment = int(incre...
522aca1690422deddbd80edbd5ece5bbd1f48c45
frangki17/pgame
/pgame-15078/code52.py
506
3.71875
4
#latihan code 5.2 : Tuple #buat variabel buah=("Durian", "Mangga", "Rambutan") print(buah) print(type(buah)) print("Jumlah Element :", len(buah)) #tambah elemen yang sama # buah.append("Mangga") # print("Jumlah Buah Mangga :", buah.count("Mangga")) #buah tuple dalam tuple buah=('Durian', 'Mangga', 'Rambutan', 'Ma...
b44e845258c9b9ff765956baa8d7141a6d74e3b3
frangki17/pgame
/pgame-15078/code101.py
536
3.5
4
#Simpan dengan nama : code101.py #Pemrograman Game Praktikum 10 #Latihan code 10.1 : PyGame import pygame running = 1 width , height = 600, 500 x,y = 0,0 screen = pygame.display.set_mode((width, height)) img = pygame.image.load('bola.png') bg = pygame.image.load("bg.png").convert() while running: event = pygame.event...
11b2b57c08a6b7ef3cc5e84be229524a814b218c
laqieer/se2m4a
/tool/generate_quantized_matrix.py
1,067
3.53125
4
#!/usr/bin/env python3 """ Generate quantized matrix from quantized table. Author: laqieer Email: laqieer@126.com """ quantized_table = [0, 1, 4, 9, 16, 25, 36, 49, -64, -49, -36, -25, -16, -9, -4, -1] quantized_matrix = [] for d in range(-255, 256): quantized_value = 0 if d == 0: quantized_matrix.ap...
42bf9404f1be460c7bdc358392b816a55b689e96
janenguyenvn/learning-python
/homework3.py
621
3.703125
4
class Account(): def __init__(self,name, balance): self.name = name self.balance = balance def the_object(self): print('Account owner: ' + name) print('Account balance: ' + balance) def deposit(self,number): print('Deposit Accepted') self.balance += number ...