blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
6c2d4da2736e0cf2ace5aaaffb5466351082443f
WiktorPieklik/Llama
/src/geometry/vector.py
1,036
3.5
4
import math import numpy as np def unit_vector(vector): """ Returns the unit vector of the vector. """ return vector / np.linalg.norm(vector) def calc_angle_inner(v1: np.ndarray, v2: np.ndarray): """ Returns angle between vector 1 and vector 2, expressed in degrees. Parameters ---------- ...
cffc218248dedc4217dec125c31e5217b06bf3d2
krishnodey/Python-Tutoral
/mirrored_rhombus.py
485
4.09375
4
''' lets print a mirrored rhombus like below ****** ****** ****** ****** ****** ''' n = int(input("Enter the number of rows: ")) #traverse the rows for i in range(1,n+1): for j in range(1, n-i+1): #print space fron 1 to n-i column print(" ", sep=" ", end=" ") ...
f63515370b557ce233bb1f9848014c168d3bfa6c
40741107/frunch
/python/亂數1.py
393
3.765625
4
import random fruit=['apple','蘋果','orange','橘子','papaya','木瓜','grape','葡萄','kiwi','奇異果'] #print(fruit[1],fruit[3],fruit[5],fruit[7],fruit[9]) r=random.randrange(1,10,2) question="請問"+fruit[r]+"的英文單字是甚麼?" ans=input(question) if ans==fruit[r-1]: print("恭喜你,答對了") else: print("很抱歉,您答錯了,答案應為",fruit[r-1])
c4379d37faba54caea1fceda2190eee9f80418f9
ikeshou/Kyoupuro_library_python
/src/mypkg/others/flatten.py
1,637
3.703125
4
from typing import Any, Sequence, List def flatten_with_depth(L: Sequence[Any], depth: int=1) -> List[Any]: """ ネストしたリストである L を depth だけ展開したリストを返す。 depth = 1 の場合 sum(data, []) と同様の挙動となる。この関数はその多次元版である。 depth が実際のネストより深い場合は限界まで展開を行う。 Args: L (list) depth (int) Returns: ...
517ed6851fbaecb086d5c6f50e5c52ec9fe9522c
allenphilip93/leetcode
/python/380_Insert_Delete_GetRandom.py
795
3.578125
4
import random class RandomizedSet(object): def __init__(self): self.num_to_idx = {} self.num_list = [] def insert(self, val): if val in self.num_to_idx: return False else: self.num_list.append(val) self.num_to_idx[val] = len(self.num_list) -...
5020e51045c23ed9f25cd64793c86ef77e31cabc
warleyken42/estrutura-de-dados
/lista-de-exercicio-2/Questão1.py
146
4.125
4
num1 = int(input("Informe um numero: ")) num2 = int(input("Informe um numero: ")) print("O maior numero digitado foi {}".format(max(num1, num2)))
b1e5a84d95e2fa3b3f6175880068b2e21de5d871
OS-Dev/PythonDevCourseWork
/CSC_242_PythonWork/Assignments/Asg5.py
1,687
4.21875
4
# # Assignment 5 # # Osmel Savon # def printTriangle(n,m): 'This function is recursive and prints a upside down triangle starting from n. Also using m for indentation of the triangle' star = '*' space = ' ' if n <= 0: return 0 else: print ((space * m)+(star * n)) ...
a0070c1dadac23c3fed7af6a669b84b6edba69d8
YashCK/Python_Basics
/Polymorphism.py
5,125
4.46875
4
# Polymorphism # - Sometimes an object comes in many types or forms. # - If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they share the same logic: onClick(). # - We access them using the same method . This idea is called Polymorphism....
56aba1b6039bcfd1b93869595285d4fe85578bfc
keizerkjj/Machine_Learning
/s07_线性回归.py
1,119
3.625
4
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import ai_utils DATA_FILE = '/Users/likaizhe/Desktop/Python/Machine_learning/data_ai/house_data.csv' # 使用的特征列 FEAT_COLS = ['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'sqft_above', 'sqft...
f6fb38a86f0be062f9a5aafe4f7881eeae4de40e
lucasdutraf/competitive-programming
/codeforces/PPC/Training-5/L.py
181
3.515625
4
a = input().strip() yes = 0 if "1111111" in a: yes += 1 else: yes += 0 if "0000000" in a: yes += 1 else: yes += 0 if yes > 0: print("YES") else: print("NO")
b519fbcb0a93d78bbd50c139162c0831d7c31602
Licho59/Licho-repository
/inne_projekty/problem_solving_with_algorithms/fraction_class_improved.py
2,484
3.640625
4
def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, top, bottom): common = gcd(top, bottom) try: bottom > 0 # it allows negative denominators except: pass assert is...
b9c8400f983b3f0f5c84ca036e751f18d6698341
shreephadke/CS50x
/dna.py
2,033
3.984375
4
import csv from sys import argv # if there aren't 3 command-line arguments, exit the program if not len(argv) == 3: print("INVALID") exit(1) # open the database file and save it as a list named key with open(argv[1], newline='') as keyf: reader = csv.reader(keyf) key = list(reader) # open the sequenc...
5911771893c272d62d09fb635e7a2fd93449afeb
thiagocosta-dev/Atividades-Python-CursoEmVideo
/ex017.py
425
3.921875
4
''' DESAFIO 017 Faça um programa que leia o comprimento do cateto oposto e do adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. ''' from math import hypot catetoOp = float(input('Cateto oposto: ')) catetoAj = float(input('Cateto adjacente: ')) hi = hypot(catetoOp, catetoAj) print(f...
0428b75b1644ae22d50fc071845c973faab2243d
suvarov/pyhton3
/week_02.py
8,300
4.625
5
import matplotlib.pyplot as plt plt.plot([i**2 for i in range(10)]) plt.show() ### Homework 2 ### # Exercise 1 ''' Tic-tac-toe (or noughts and crosses) is a simple strategy game in which two players take turns placing a mark on a 3x3 board, attempting to make a row, column, or diagonal of three with their mark. In th...
9234ef4b90c95c6f68f6cda05e3c146e3a8873b1
Lucky4/coding-interview
/33.py
792
3.5625
4
# -*- coding: utf-8 -*- class Solution(object): ''' 八皇后问题,使用元组保存状态,state[0]==3,表示第1行的皇后是在第四列。 ''' def queens(self, num=8, state=()): if len(state) == num - 1: for pos in range(num): if not self.conflict(state, pos): yield (pos,) else: ...
00a819e51aa850b03d6d6aa25ec1616272a6a74d
omar-osario/TechnicalProfile
/EulerProject/Euler014.py
1,540
3.578125
4
from os import * from shutil import * from math import * import time starttime,sol = time.time(), 0 def nextCollatz(n): if (n%2 == 0): return n/2 else : return (3*n + 1) # Setting dictionary # Collatz = {number:length of Collatz chain} Collatz = {1:0} # Adding elements given from question Collatz[2] = 1 Colla...
f8b434bbc30d095fd8698e91d9f7082d48c7c51a
Prokofyev-Evg/yap-algo
/sprint12/taskf.py
267
3.984375
4
string = input() only_alpha = "" for char in string: if ord(char) >= 65 and ord(char) <= 90: only_alpha += char.lower() elif ord(char) >= 97 and ord(char) <= 122: only_alpha += char sentence = only_alpha[::-1] print(sentence == only_alpha)
0b28bae0679f034d0e4f84ab551e0c738eb69931
niveshmavuduru123/MyPythonPractice
/char.py
641
4.15625
4
import datetime print("Getting input from the user") print("---------------------------") Name = input("Please enter your name : ") Age = int(input("Please enter your age : ")) cur_year1 = datetime.datetime.now() #to access the current date year month hour minute second cur_year = cur_year1.year turn_old = 100 - Age fi...
8ff1c1a4a2c37f981fe041be209f60fc5f7e98bc
xys234/coding-problems
/algo/dp/best_time_to_buy_and_sell_stock_II.py
2,144
4.375
4
""" 122. Best Time to Buy and Sell Stock II (Easy) Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may n...
ea577eda8185993ef009035afdce16dbef71019d
tashakim/puzzles_python
/array_diff.py
407
3.75
4
def array_diff(a, b): """ Purpose: Deletes array diff. """ for i, x in enumerate(a): if x in b: a[i] = None res = [] for x in a: if x is not None: res.append(x) return res def array_diff2(a, b): for ele in b: while ele in a: a.r...
f400f878a702247db1c35767789dbd3c40b28f59
Kcpf/MITx-6.00.1x
/Week 6-Algorithmic Complexity/bogo_sort.py
361
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 14:16:51 2020 @author: Fernando """ import random def bogo_sort(L): """ Input: Unsorted List Output: Sorted List best case: O(n) where n is len(L) to check if sorted worst case: it is unbounded if really unlucky """ while L != sorted(L...
37c00d0119ad97b2d0b83009ff05b6d92d746547
qiuosier/Aries
/excel.py
11,326
3.984375
4
"""Contains ExcelFile class for handling MS Excel file. """ import re import logging import string from tempfile import TemporaryFile from openpyxl import load_workbook, Workbook from openpyxl.utils import get_column_letter logger = logging.getLogger(__name__) def int2letters(n): """Converts an integer to a stri...
d222b44e2c9b9d1d883b57aa607538bb9457e879
darsovit/pyRayTracerChallenge
/renderer/bolts.py
4,320
3.6875
4
#! python # from math import isclose, sqrt EPSILON = 0.00001 def equality(float1, float2): return EPSILON > abs(float1 - float2) class Tuple: def __init__(self, x, y, z, w): self.val = (x, y, z, w) def isPoint(self): return equality( self.val[3], 1.0 ) def isVector(self): re...
6074d36f07080bf23665be618147e4d95d8168c7
dhagesharayu/python_assignments
/day_1/Program1.py
459
4.0625
4
''' 1. a. Given a number count the total number of digits in a number For example: The number is 75869, so the output should be ''' n=int(input("Enter the number to count digits")) n1=n c=0 while n>0: c+=1 n=n//10 print("the total number of digits in ",n1,"are",c) ''' b. Reverse the following list using for l...
034679142b4e5df02dd176ef4706f08dbdb46f1c
cstelios/lpthw
/ex48/skeleton/ex48/lexicon.py
841
3.875
4
mapping = { 'direction' : ["north", "south", "east", "west", "down", "up", "left", "right", "back"], 'verb' : ["go", "stop", "kill", "eat", "run"], 'stop' : ["the", "in", "of", "from", "at", "it"], 'noun' : ["door", "bear", "princess", "cabinet", "honey"] } mapping_categories = mapping.keys() ...
f6a3ededc1a4b210c709b8eaf8389dde144cfa19
CamilliCerutti/Python-exercicios
/Curso em Video/ex025.py
242
3.90625
4
# PROCURANDO UMA STRING DENTRO DE OUTRA # Crie um programa que leia o nome de uma pessoa e diga se ela tem “SILVA” no nome. nome = str(input('Tem "silva", no seu nome? Digite seu nome completo: ')).strip() print('silva' in nome.lower())
22cd5290e83d2a35724b6ad25acfd1d213d59f07
skafev/Python_OOP
/999Exams_advanced/02-2Darts[to_check].py
2,612
3.59375
4
player_one, player_two = input().strip().split(", ") def make_matrix(): matrix = [] for s in range(7): rows = input().strip().split() rows_to_append = [] for r in rows: rows_to_append.append(r) matrix.append(rows_to_append) return matrix def is_valid(row, col...
64a542cf45ac7094916eb2e67175895e0bfa5be7
bryanchun/handwritten-digit-classifier
/model.py
6,116
3.53125
4
import numpy as np import random class Network(object): def __init__(self, layers): """random initialisation of biases and weights :param list layers: umber of neurons in each layer as a vector """ self.layers = layers self.num_layers = len(layers) self.biases = [np...
023b2fab3783bee62887b40471d12b20eafacb1d
davidev886/gauss_elimination
/gauss_elimination.py
3,191
3.65625
4
import numpy as np def Gauss(A, mod=0): """Compute the Gaussian elimination of the matrix A modulo mod Parameters ---------- A : numpy array The matrix that will be row-reduced mod : int, optional integer representing the modulus Returns ------- numpy array th...
7c2621fc70dc5cdfb3ca28f606d4ab2ffe3791dd
GavinPHR/code
/phase1/344.py
375
3.859375
4
# Reverse String from typing import List class Solution: def reverseString(self, s: List[str]) -> None: if s == []: return for i in range(len(s) // 2): tmp = s[i] s[i] = s[~i] s[~i] = tmp return if __name__ == '__main__': a = ["h","e","l","l","o"] ...
0bae6871850f91ff3339d497615bd2e012460d49
areeta/cssi
/cssi-labs/python/labs/make-a-short-story/mystory.py
1,072
4.0625
4
# The Story # Once a upon time, there was a classroom where # a bunch of students went to ***Google*** and learned # Computer Science with Googlers. These students # ate a bunch of ***food*** everyday and learned things # like ***HTML***, ***CSS***, and ***JavaScript***. They had # a lot of ***fun*** and hope to work b...
c50cad76996b0876cc399266e492bfc3c631aef9
m4mayank/ComplexAlgos
/word_search.py
1,542
3.984375
4
# Given an m x n board and a word, find if the word exists in the grid. # The word can be constructed from letters of sequentially adjacent cells, where "adjacent" cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. # Example 1: # Input: board = [["A","B","C","E"],["...
a3fce49da29ef17508e974c50e4a74e4970bd632
aa-ahmed-aa/Python_Projects
/introduction/third.py
101
3.9375
4
for x in range(2 , 10 , 2 ): print(x) but = 5 while but< 10: print("hello !!!") but+=1
fa8df87dfa3564b197ea1f06cb734301f6733af7
juechen-zzz/LeetCode
/python/0201.Bitwise AND of Numbers Range.py
595
3.6875
4
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. Example 1: Input: [5,7] Output: 4 Example 2: Input: [0,1] Output: 0 性质:n个连续数字求与的时候,前m位都是1. 举题目给的例子:[5,7] 共 5, 6,7三个数字, 用二进制表示 101, 110,111, 这三个数字特点是第一位都是1,后面几位求与一定是0 """ class Solution: de...
60d11ea9967dc92d3c3785e05b832b0e0f70f325
xmatheus/Faculdade
/Programação 1/PYTHON-Testes/miguelsoma.py
328
3.609375
4
def main(): entrada = raw_input() x,y = entrada.split() x = int(x) y = int(y) while x>0 and y>0: soma = 0 if(x>y): aux =x x = y y = aux for i in range(x,y+1): soma = i+soma print str(i) + "", print("Sum=" + str(soma)) entrada = raw_input() x,y = entrada.split() x = int(x) y = int(y)...
92f420055aa2e7e4a83bfcdd0462b168241a5581
lynnchae/python-starter
/org/lynn/python/first.py
1,228
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 第一行告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释 a = '123' print(a) A = 'COW BOY' B = A A = 'CRAZY BOY' print(B) print(10 / 3) # 地板除 print(10 // 3) print('中文') # 如果不知道类型,可以永远使用%s做格式化占位符 # name = input() # print("hello, %s!" % name) print('Hello, {0}, 成绩提升了 {1:.1f}...
4c1327e0dc488e680b193063a4958c61259b4d70
subhamaharjan13/IW-pythonassignment
/Datatypes/Q20.py
373
4
4
# Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. data = ['bc','abc','bac','aba','1211'] word_list = [] for i in data: if len(i)>2: word_list.append(i) count = 0 for i in word_list: if i...
0a64affd296855776f326541d3a921fe79f51710
joaogomes95/Blue
/Módulo 1/15-06-for/Aula_Dicionário/funcoes.py
1,920
4.3125
4
# Funções # Como boas práticas fazer as funções antes de iniciar a escrever o código # Escopo: espaço(dentro) da nossa função # def '' seria definr uma função # 1. ( ) # 2. (**) # 3. (*) (/) (//) (%) # 4. (+) (-) # def soma(): # soma = 2 + 3 # print(soma) # soma() # Faça um programa que tenha uma função c...
5eb4a038a2bdc7ee92c0285511e20784be6ec501
Taohid0/LeetCodeProblemSolutions
/python/Symmetric tree (iterative).py
916
3.9375
4
import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self,root): q = queue.Queue() q.put(root) q.put(root) while not q.empty(): n1 = q.get() n2 = q....
bb0e7ea8393c200dc09fe991aca1f0e6a1fe4862
lloydw/platform-take-home
/server/maps/distance.py
1,027
4.25
4
""" This module implements methods for calculating distances """ import math def haversine(lat1, lng1, lat2, lng2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) using the haversine formula - https://en.wikipedia.org/wiki/Haversine_formula :...
43876e397393727b34c3edc5bba3479ac805c83e
mxrold/python-exercises
/aprende-con-alf/simple-data-types/exercise_8.py
125
3.953125
4
num = abs(int(input('Enter a number: '))) formula = (num *(num + 1)) / 2 print('The sum of the numbers is ' + str(formula))
b5cc9628d1e0ae5525304eec6106a85f15c73c4e
brycehorman/INFO303
/Week3/DictionariesDemo.py
5,476
3.671875
4
my_dict_items = {} my_dict_items = {1: 'orange', 2: 'banana', 3: 'kiwi'} my_dict_items = {'first name': 'Joe', 1: [8,12,33]} print(type(my_dict_items)) print(dir(my_dict_items)) my_dict_items = dict({1: 'orange', 2: 'banana', 3: 'kiwi'}) my_dict_items = dict([(1, 'orange'), (2, 'banana'), (3, 'kiwki')]) print(...
8c95d217a4d54afb6a6d8562dbe01321888d2ef5
FikretPythonLesson/Lecture2_StartCoding
/SimpleLoop3.py
92
3.6875
4
total = 0 for i in [1,3,7,8]: print(i) total = total + i print "Total is :", total
0eee92a935bb5a52413cc708950fdd6e4090a7d5
HoweChen/PythonNote-CYH
/Python Basic/PYTest/Survey/language_survey.py
391
3.875
4
from survey import AnonymousSurvey question = 'What language did you first learn to speak?' survey = AnonymousSurvey(question) survey.show_question() while True: answer = input('Input your answer: \n') if answer == 'q': break else: survey.store_response(answer) print('Thank you for your a...
96baba6546c7a9db521204e86f29af8a00877ef5
zhrcosta/testando_codigos_python
/sort_list_1.py
714
4
4
def sort_list(lista): count = 0 loop = 0 while not count == len(lista)-1: # Verifica se todos os valores estão em ordem crescente. for index in range(len(lista) - 1): if lista[index] <= lista[index + 1]: count += 1 if count == len(lista) - 1: ...
985aa19dee05db8f692c64b165be2f82a607b72d
TBudden/Year9DesignCS4-PythonTB
/CastingExample.py
69
3.84375
4
x = input("Give me a number: ") x = int(x) x = x * 100 print(x)
5bf81924d77e71092d0eca2e1184434b966e49d1
bilginyuksel/AlgorithmSolutions
/hackerrank/chief-hopper.py
291
3.90625
4
def findMinEnergy(heights): shouldProduceEnergy = 0 for height in reversed(heights): shouldProduceEnergy = (shouldProduceEnergy + height + 1) // 2 return shouldProduceEnergy input() # not necessary heights = list(map(int, input().split())) print(findMinEnergy(heights))
fb25de3c4e3a5b5fb0417bff46165ad5278816d4
suekwon/FEProgramming1
/scipy examples/linear_regression.py
544
3.625
4
from scipy.stats import linregress import numpy as np def f(x): return 2*x x = np.random.randn(200) y = f(x) + 0.3*np.random.randn(200) gradient, intercept, r_value, p_value, std_err = linregress(x,y) print("intercept = %g"%intercept) print("slope = %g"%gradient) print("r^2 = %g"%r_value**2) print("p_value = %g...
727c3e8dcf04b722fd1aaaf46a78580fc34039f3
xulei33/python
/hello.py
1,320
3.859375
4
print("hello word") a=[1,2,3] for x in a: print(x) def hello(): print("hello words") hello() def hello(name): print("hello %s"%name) return "xulei" a=hello("xulei") print(a) def person(name,*pars): print(name) for x in pars: print(x) person('xulei','man',26,'guangzhou') def defultpars(name,age=21,sex='...
4a662fa8760fbc1f24ba01e8cbef71736018e345
pamu5248/wind_tools
/wind_tools/geometry.py
1,268
3.78125
4
"""geometry module """ import numpy as np def wrap_180(x): """ Wrap an angle to between -180 and 180 """ x = np.where(x<=-180.,x+360.,x) x = np.where(x>180.,x-360.,x) return(x) def wrap_360(x): """ Wrap an angle to between 0 and 360 """ x = np.where(x<0.,x+360.,x...
01a647cab6ba2541d2219e5501a7c0c23b5eead2
johncornflake/dailyinterview
/imported-from-gmail/2020-02-27-anagrams-in-a-string.py
332
3.84375
4
Hi, here's your problem today. This problem was recently asked by Twitter: Given 2 strings s and t , find and return all indexes in string s where t is an anagram. Here's an example and some starter code: def find_anagrams ( s , t ): # Fill this in. print ( find_anagrams ( 'acdbacdacb' , 'abc' )) ...
c29e449cd65c1340e6386decb9df7979b60ac3e5
wxl789/python
/Day17/代码/正则表达式/9-贪婪与非贪婪.py
463
3.734375
4
''' . : 匹配除换行符以外的所有字符 贪婪 * :任意多个 贪婪 ? : 0个或1个 非贪婪 .*? : 将贪婪匹配变为非贪婪匹配 ''' import re re1 = "ni .* hao" str1 = "ni jintian hao ni mingtian hao ni houtian hao" resu1 = re.findall(re1, str1) print(resu1) re2 = "ni .*? hao" str2 = "ni jintian hao ni mingtian hao ni houtian hao ni hao" resu2 = re.findall(re2, str2)...
ddd3ad457dd57ccd95a6da967f947a3703228184
joelgarzatx/portfolio
/python/Python3_Homework07/src/furnishings.py
1,395
3.765625
4
class Furnishing(object): def __init__(self, room): self.room = room class Sofa(Furnishing): def __init__(self, room): super().__init__(room) self.name = "Sofa" class Bookshelf(Furnishing): def __init__(self, room): super().__init__(room) ...
4c7b3597f1a30170506edff6740d15fae8f20161
18s005073/Leet
/2.py
768
3.6875
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): p = dummy = ListNode(-1) carry = 0 while l1 or l2 or carry: val = (l1 and l1.val or 0) + (l2 and l2.val or 0) + carry carry = val...
79a5e1c181375d05b90daa2b226b78765d37d064
arbwasisi/CSC120
/tree_funcs.py
2,311
3.671875
4
from tree_node import* def count(root): if root == None: return 0 else: num = count(root.get_left()) + 1 num2 = num + count(root.get_right()) return num2 def is_bst(root): tree_val = in_order_traversal(root) return (tree_val == sorted(tree_val)) def search(...
6ff8c85c5c8fa9521fd76ac2cc0d76ab42afe83d
leinian85/note
/练习/汉诺塔/HanoiStack.py
1,243
3.71875
4
class HanoiMove: def __init__(self, stack_num, stack_from, stack_to): if stack_num <= 0 or stack_from == stack_to or stack_from < 0 or stack_to < 0: raise RuntimeError("Invalid parameters") self.stack_from = stack_from self.stack_to = stack_to self.hanoimove = [] ...
ab79f4b0b67bfd2d79533e34899d4db1d2d81fd2
bfillmer/Project-Euler-Problems
/euler problem 09.py
1,182
4.03125
4
#!/usr/bin/env python # encoding: utf-8 """ euler problem 9.py Copyright (c) 2013 . All rights reserved. A Pythagorean triplet is a set of three natural numbers, a b c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. F...
001eb57d3ace44d2827adf4ea8d9b86d66867db5
remotephone/lpthw
/01thru10/ex04-01.py
1,122
4.4375
4
# We are assigning variables! # Each one of these values is assigned a number. This is stored in memory as # the program runs. cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 # You can do math on its own or you can do math on the variables. Python will # interpret the variables as you use them so there's...
ed6f307d762dd7ae52673159e5944786cd85bb6a
Orocker/learning-python
/Process_Thread/multi_thread/thread_lock.py
1,429
3.609375
4
# -*- coding: utf-8 -*- import time,threading # 针对thread_no_lock.py的问题,要确保balance计算正确,就要给change_it()上一把锁,当某个线程开始执行change_it()时,可以说,该线程因为获得了锁, # 因此其他线程不能同时执行change_it(),只能等待,直到锁被释放后,获得该锁以后才能改。由于锁只有一个, # 无论多少线程,同一时刻最多只有一个线程持有该锁,所以,不会造成修改的冲突。创建一个锁就是通过threading.Lock()来实现: balance = 0 lock = threading.Lock() def change_...
f979dced92ba616a774dec9e43f5925e7dbf2cb2
effedib/the-python-workbook-2
/Chap_06/Ex_138.py
630
3.953125
4
# Text Messaging # Display the key presses needed for a message entered by the user, using the cell phone numeric keypad. keypad = { '.': '1', ',': '1'*2, '?': '1'*3, '!': '1'*4, ':': '1'*5, 'A': '2', 'B': '2'*2, 'C': '2'*3, 'D': '3', 'E': '3'*2, 'F': '3'*3, 'G': '4', 'H': '4'*2, 'I': '4'*3, 'J': ...
feb97886dd935202be450533cb21fd4abe5bb729
subotai54/square_spiral
/square.py
3,642
3.78125
4
import argparse parser = argparse.ArgumentParser() class Square(): def __init__(self,num=3): self.diameter=int(num) self.Sq= [[0 for a in range(self.diameter)] for b in range(self.diameter)] #creates an emptyPosition square with the diameter as sides self.xPosition=0 self.yPosition...
4427cf01813940dd15d273593c7cc15c0f1dfd90
IvanJeremiahAng/cp1404practicals
/prac_03/lecture ex2.py
316
3.78125
4
def main(): temp1 = celcius_to_fahrenheit(10) # 10 & 1.8 + 32.0 = 50 -> temp1 = 50 temp2 = celcius_to_fahrenheit(50) # 50* 1.8 + 32.0 = 122 -> temp2 = 122 print(temp1) print(temp2) def celcius_to_fahrenheit(celcius): return celcius * 1.8 + 32.0 if __name__ == '__main__': main()
3abab7bed2043b7fe189f1735a52617bb7fb9632
DiksonSantos/Curso_Intensivo_Python
/Página_231_Faça_Você_Mesmo.py
1,588
3.8125
4
''' #8.12 Sanduiches: def Fazer_Sanduiche(Pão_Tipo,**Extras): Sanduba = {} Sanduba["Tipo de Pão"] = Pão_Tipo #Organizar, Quem é Chave, Quem é Valor. for Paes, X_Tras in Extras.items(): Sanduba[Paes] = X_Tras #Acredito que Nesta Linha se Define a Forma\Sequencia Como as Informações Serão Org...
e342081665f5df4a22bb9ea0aaf0a8377f7753c2
Seba-vp/PrograAvanzada2019-2
/Tareas/T00/DestaparBaldosaRanking.py
4,252
3.515625
4
import MenuJuego import MenuInicio import parametros def segundo_elemento(lista): return int(lista[1]) def print_ranking(): archivo = open("ranking.txt", 'r') linea = archivo.readlines() linea2=linea[0].split(';') linea2 = linea2[:-1] print("-------------------------------------") print("...
93fc054203c0c0ee211a242c97cdb706727b8feb
yeswhos/LeetCode
/Recursion/344_Easy.py
414
3.875
4
""" 2021.06.03 mengfanhui """ def string_reverse(s, left, right): # 相当于指针和递归相结合,当指针相遇或者错过的时候停止 if left >= right: return s # 两个两个交换,首先是第0个和最后一个,然后是第一个和倒数第二个 s[left], s[right] = s[right], s[left] # 递归,开始下两个指针 return string_reverse(s, left+1, right-1)
1b2bff4687864f21d375d0a85a3b09a751e5d451
harayou12/Python_Yoichi
/Kmeans
866
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import random import matplotlib.pyplot as plt import math import numpy as np n = input() num = [] crs = [] com = [] [[0] * 3] * (int(n)) for i in range(int(n)): num.append([random.random(),random.random()]) # x = num[i][0] # y = num[i][1] # plt.plot(x, y, "o",...
61f9cbdbcc47f72b8ffffcbf9ebce9d6f2b176ed
SumMuk/data-struct-algo
/stacks.py
2,287
4.0625
4
#Evaluate postfix expression in a stack def postfix_expr(strs): stack_ = [] math_operators = "+-/*" for i in strs: if i.isdigit(): stack_.append(i) if i in math_operators: b = stack_.pop() a = stack_.pop() if i == "+": stack_.a...
eb83a8ed7bd6b55b9b3a8738ad73166ea2fc8333
underbais/CSHL_python2017
/python6_problemset/1.py
294
3.59375
4
#!/usr/bin/env python3 import re with open("Python_06_nobody.txt", "r") as nobody: for line_num,line in enumerate(nobody): line = line.rstrip() for match in re.finditer(r"Nobody", line): print("Number of matching line:",line_num+1,match,'Start:',match.start(), 'End',match.end())
aaa73225dda148c35213beedb5266da3b5208d37
roastbeeef/100daysofcode
/days_13_15/program.py
1,825
3.671875
4
from days_13_15.actors import Creature, Wizard, Dragon import random def main(): print_header() game_loop() def print_header(): print('--------------------') print('----WIZARD_GAME-----') print('--------------------') print() def game_loop(): creatures = [ # TODO: add some creatur...
d8a20d375b8f4f2164669326c0818f7839bd41be
PeravitK/PSIT
/WEEK1/Train.py
186
3.6875
4
"""Train""" def main(): """Train""" word1 = input() word2 = input() num1 = int(input()) word3 = word1+word2 print(word3) print(word3*num1) main()
6b8c41ac4aaf06048993ac35359b477b40e089f2
VachaganGrigoryan/aca-python
/Resources/2021.02.22/linked_lists.py
2,904
3.9375
4
from abc import ABC, abstractmethod class Node: def __init__(self, value): super().__init__() self.value = value self.next = None def __repr__(self) -> str: return f'Node({self.value})' class LinkedList(ABC): @abstractmethod def add(self, item): pass @...
da1e141c336313b575f75b4508e38d6b0b93c28f
SinCatGit/leetcode
/00099/recover_binary_search_tree.py
2,944
3.875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def recoverTree(self, root: TreeNode) -> None: """ #### [99. Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) Two elemen...
7e533700986c0db4f2eeac39ceab366964466def
AJM432/Simple-Python-Projects
/mini_projects/tk_simpleApp.py
798
3.890625
4
import tkinter as tk import random # *---Main Window---* win = tk.Tk() win.title("Login System") win.geometry("400x400") # window size # *---Label---* user = tk.Label(text="Enter your Username: ") # this is LABEL and can be used in any way user.grid(column=0, row=0) # aranges elements into grid structure (column, ro...
6cf0c717e6c96aeefdfe3acd1ea9e78e683e0ba1
WastPow/Basic_keyworder
/keyworder_with_file.py
1,045
3.625
4
def keyworder(file): f = open(file, "r") tags = { "#kost": [ "kost", "mat", "matvana", "läsk", "socker", "kalorier", "saft", "onyttig", "fett", "kolhydrater", "cola", ...
064777db0ae7f7f6ac6f0f7cb8065ac991bf7f87
tpratap/Mathematical-Problems
/k strings.py
288
3.53125
4
# Printing all possible combinations of k strings for n digits def K(n,k): if n < 1: print(A) else: for i in range(k): A[n-1] = i K(n-1,k) k = int(input("Numbers upto (K):")) n = int(input("No. of digit(n):")) A = [0]*n K(n,k)
c7e642c640c6ed5cd5ee946ad8c5ac5f3438be89
vinitdedhiya/project
/Useful/Rijul - Useful/transpose.py
228
4.03125
4
''' This function returns the transpose of the 1D row matrix entered.''' import numpy as np def transpose(A): n = len(A) A_T = np.ones([n,1]); for i in range(n): A_T[[i],[0]] = A[i]; return A_T
5ebe0854031152a98467c710987f884a113ab8cb
SubbuDevasani/Programs
/1.Functional/Leap year.py
1,133
4.1875
4
""""" ---------------------------------------------------------------------------------- Leap Year a. I/P -> Year, ensure it is a 4 digit number. b. Logic -> Determine if it is a Leap Year. c. O/P -> Print the year is a Leap Year or not. ----------------------------------------------------------------------...
8eebaf070f022f5ec82ecad2b7267287a46e467b
covrebo/contacts_db
/classes.py
1,224
4.1875
4
class Contact: """ A contact object Attributes: first_name(string) last_name(string) address1(string) address2(string) city(string) state(string) zip(int) phone(string) email(string) """ def __init__(self, first_name, last_name...
5e41ae2358b0e5badefd6282d563ffd6a1fa1505
peeyush20/python-mini-programs
/Hangman.py
1,497
4.03125
4
import random word_list= ['time', 'love', 'inspire', 'hello', 'sound', 'air'] r = random.seed() # print(r) num = random.randrange(0, 6, 1) #print(num) #print(word_list[num]) word_length = word_list[num].__len__() guess_word = ['_ ']*word_length print("Guess the word. Hint: It is {} letter word".format(word_l...
39e164348e87a4433c42f44d3e55a5d2df068e9f
DaryaRomannova/Python-HomeWork
/HomeWork1.1.py
387
4.40625
4
#По номеру месяца напечатать пору года n=int(input("Введите номер месяца:\n")) if 3<=n<=5: print("Весна") elif 6<=n<=8: print("Лето") elif 9<=n<=11: print("Осень") elif n==12 or 1<=n<=2: print("Зима") else: print("Ошибка введите номер мясяца от 1 до 12")
0bb8361502554be30b90a28fa751dc8b88c09baa
yuwinzer/GB_Python_basics
/hw_to_lesson_08/02_exception.py
880
3.625
4
# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, # вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать # эту ситуацию и не завершиться с ошибкой. class ZeroDivision(Exception): def __init__(...
f553ad191dbf193e85ae7445f0de6b26821c27d4
gazon1/nn
/perceptron/perceptron.py
1,415
3.546875
4
import unittest import sklearn from perceptron_class import Perceptron import numpy as np class TestPerceptron(unittest.TestCase): def setUp(self): self.num_inputs_nodes = 10 self.num_neurons = 10 self.pnn = Perceptron(self.num_inputs_nodes, self.num_neurons) def test__init__(self): ...
d968a34ca669e8bf422c7a01641455e463cb853d
BoMarconiHenriksen/movie_dataset
/library/popular_danish_movie.py
756
4.125
4
import pandas as pd def find_most_popular_danish_movie(data): ''' This method find the most popular danish movie of all time. ''' # Gør at vi kan printe all kolonner. pd.set_option('display.max_columns', None) # Find all the danish movies. danish_movies = data[data['original_language'] ==...
742deadc7f47acb67bdccfa1e118e1aa8df30c8b
Jeremiaszmacura/Star-Wars-game
/player.py
2,557
4.15625
4
"""The module contains the Player class.""" import pygame from const import Consts class Player: """The player's class contains the methods needed to draw a player's object, change its coordinates, movement restriction, keyboard controls (controls).""" def __init__(self): self.position_x = Consts...
7e820d7d1fd407f1cf7ca7c87520d027a5d30480
culvin2/Calculator
/kalkulator.py
673
4.03125
4
print("-----Kalkulator-----") print("********************") def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print('''Pilihan Operasi 1. Penjumlahan 2. Pengurangan 3. Perkalian 4. Pembagian''') pilihan = input("Masukkan piliha...
a2a3679200716be7727d385701034e0f8d0a783f
nahaza/pythonTraining
/ua/univer/HW04/ch06AlgTrain08.py
1,055
4.25
4
# 8. A file exists on the disk named students.txt. The file contains several records, and # each record contains two fields: (1) the student’s name, and (2) the student’s score for # the final exam. Write code that changes Julie Milan’s score to 100. import os def main(): found = False nameForGradeChange = '...
cefec2d9673d06d1001c558534965d9cccf0ae68
idobleicher/pythonexamples
/examples/functions-and-modules/function_arguments.py
919
4.40625
4
# Technically, parameters are the variables in a function definition, # and arguments are the values put into parameters when functions are called. # Function arguments can be used as variables inside the function definition. # However, they cannot be referenced outside of the function's definition. # This also appl...
65a8e291d301605c6b4481b9024fbea1015b08c5
bibongbong/pythonCookBook
/learningStuff/Dijkstra.py
6,859
3.609375
4
infinity = float('inf') # 数组processed,用来记录已经处理过的节点 processed = [] class Node(object): # sons = {} # key=SonNodeObject, value=costFromSelfToSon # parents = {} # key=parentNodeObject, value=costFromParentToSelf name = "" # bool processed = False #这个属性不应该是Node的属性,而是算法的属性 def __i...
c873a5d69053ea60053b2a12d52e8e00c635c7a3
raytwelve/LeetCode
/Easy/Palindrome Number.py
543
4.09375
4
''' https://leetcode.com/problems/palindrome-number/ Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Coud you solve it without converting the integer to a string? ''' class Solution: def isPalindrome(self, x: int) -> bool: if x == 0: r...
490c5189e6e1d54511b7f864232e40f29c142ca3
marc22alain/G-code-repositories
/drawn_entities/Circle_class.py
2,217
3.6875
4
from Tkinter import * from GeometricEntity_class import GeometricEntity class Circle(GeometricEntity): """Draws circles in the Tkinter canvas.""" def __init__(self, view_space): self.x1 = None self.y1 = None self.x2 = None self.y2 = None self.center_x = None sel...
dcedc0683fe683f747748389f0cac80a17fdec03
cynthfol/Metro-Data
/Data/Class 3 python.py
3,114
4.0625
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 25 08:35:51 2017 @author: Owner """ #%% from math import sqrt value=-100 #condition if value >= 0: # what to do if condition is true: rootValue=sqrt(value) print (rootValue) else: # what to do if condition is false: print('Sorry, I do not compute squ...
d67407d7e37dc099dc45f70da98b23bbcc2bdf65
Tomnr100/instagrambot
/test.py
131
3.640625
4
from datetime import datetime now = str(datetime.now()) now = now.replace(':', '-').replace(' ', '-').replace('.', '-') print(now)
94adf106ad5a39bcc004cf482c20fb5c09046e72
sraywall/GitTutorial
/quiz.py
1,646
3.828125
4
#!/usr/bin/python3 import argparse from os import system import random # :set noexpandtab def ask(q,a): response = input(q) if response == a: print("correct") else: print("incorrect,",a) input() system("clear") def main(): parser = argparse.ArgumentParser() parser.add_argume...
d7b9a93a52bc7734f99f488d8708492898a61b22
parvathimandava/Geeksforgeeks
/Mathematical_geeksforgeeks/largest prime factor.py
799
4.40625
4
''' Given a number N, the task is to find the largest prime factor of that number. Input: The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains an integer N. Output: For each test case, in a new line, print the largest prime factor o...
20c8560e9a95193b1f5f3b46b6a08dee06e87cc3
PSReyat/Python-Practice
/guessing_game.py
353
3.859375
4
target = 9 guess_count = 1 guess_limit = 5 while guess_count < guess_limit: guess = int(input("Guess: ")) guess_count += 1 if guess_count == guess_limit: print("You lost...") break if guess < target: print("A bit higher") elif guess > target: print("A bit lower") ...
86b224268891eea935c5fa55f44d50ca597a5d8b
sidv/Assignments
/Ramya_R/Ass24Augd21/plot_aids.py
695
3.765625
4
import pandas as pd #Importing pandas import numpy as np #Importing numpy import matplotlib.pyplot as pl #Importing matplolib to draw graph df=pd.read_csv("aids.csv") #Reading csv file. Pass the path to csv file new_df = pd.DataFrame(df.loc[:,["Year","Data.AIDS-Related Deaths.All Ages"]]) new_df.plot( kind="scatter",...
2d70cd4f45a4dfc638e9d908415f22b81361f38b
karthik9319/Projects
/small_codes/num_guess.py
480
3.890625
4
from random import SystemRandom def guess_num_check(num: int): if num % 2 == 0: print("Its a even number") elif num % 2 != 0: print("Its a odd number") # score = 10 def score_keep(score: int): score -= 1 print(score) if __name__ == "__main__": random_gen = SystemRandom() X...
a2b18ff536fc3eb5fe83abaef8b6e498796135ad
hustfc/OJ
/PYTHON/三数之和O(N^2)版.py
755
3.578125
4
class Solution: def isNotSame(self, lists, list): # 判断是否重复函数 for i in range(len(lists)): if list == lists[i]: return False return True def threeSum(self, nums): lists = [] for i, num1 in enumerate(nums): for j, num2 in enumerate(nums[i + 1...
2164a8201734c2b1353136c785a99855c516559a
gagan-s-kumar/pythonRevisit
/datatypes/userInput.py
141
3.96875
4
print("Enter the following details: ") name = input("Name: ") age = input("Age: ") print("Hello " + name+". You are " + age + " years old.")
db5d7bcb0055a80b239ddb40e1fd9f3bd6ed215f
YifZhou/Pythonlibrary3
/fit/linearFit.py
745
3.5625
4
#! /usr/bin/env python from lmfit.models import LinearModel import numpy as np def linearFit(x, y, dy=None, p0=None): """ convenient function for linear fit using lmfit module :param x: x parameter :param y: y parameter :param dy: uncertainties of y, default is None :param p0: initial guess for t...