blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9e7434c45d27864384e1a42c58ed2d9b34d9fba5
zenmeder/leetcode
/16.py
1,339
3.609375
4
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" import math class Solution(object): def threeSumClosest(self, nums, target): nums.sort() previous_sum = [] for i in range(len(nums) - 2): j = i + 1 k = len(nums) - 1 while j < k: sums = nums[i] + nums[j] + nums[k] - target ...
56422f66bc8fe11a1bfc8c489086a10c422dec91
jonascarnby/programmering_1
/uppgift4.py
1,267
3.640625
4
# -*- coding: UTF-8 -*- """ Jonas Carnby Python Ver.3.4.1 OSX 10.9.5 """ import celsiusconvert as omvandlare import sys from tkinter import * def convert(): try: x = int(ment.get()) c = omvandlare.convert(x) uinput = Label(mGui,text = "Din inmatning är i grader celsius:") ...
5603798fec63d07e66b2f57f8651cecd8a17e3c3
ebehlmann/algebra-library
/vector.py
3,291
3.671875
4
import math class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates ...
772f0a6493c60975f1e14dc50d61df25c8f8e350
greysou1/pycourse
/Mod1/sec4/task1.py
187
3.5625
4
random_tip = 'wear a hat when it rains' mid_point = len(random_tip)//2 print('The mid point is at ' + str(mid_point)) print(random_tip[:mid_point]) print(random_tip[mid_point:])
fbbe4805980a418919a0629ac54df33ea74c4197
moong3871/Algorithm
/SWEA/05.Stack2/4874.Forth.py
955
3.578125
4
import sys sys.stdin = open("input.txt", "r") operator = ['+', '-', '*', '/'] def cal(oper): if len(stack) < 2: return False try: tmp2, tmp1 = int(stack.pop()), int(stack.pop()) except: return sys.float_repr_style if oper == '+': return tmp1 + tmp2 elif oper == '-'...
4ecf166e88f5ecb281c3357fade16b1a00c15db6
mariachacko93/luminarDjano
/luminarproject/zzzmyprograms/functionalprogramming/mapfilterreduce.py
319
3.640625
4
numbers=[1,2,3,4,5,6] data=list(map(lambda num:num*num,numbers)) print(data) data=list(filter(lambda num:num%2==0,numbers)) print(data) from functools import* data=list(reduce(lambda num:max(num),numbers)) print(data) names=["kkc","rrc","mmc"] data=list(map(lambda names:names.upper(),names)) print(data)
f86c427ad7810bd13914481c48a8fdae68fd3d11
sarahwalters/python-lexer-generator
/postfix_utils.py
1,451
3.515625
4
def regex_to_postfix(regex): infix = concat_expand(regex) postfix = infix_to_postfix(infix) return postfix def concat_expand(regex): # https://github.com/burner/dex/blob/master/concatexpand.cpp # Mark concatenation locations with chr(8) (backspace char) res = '' for i in range(len(regex)-1): char_l...
d0d5a53122a062aa5121f4b2e207f431c9659758
rupakdasatos/python_practice
/powerpuff_girls_np.py
1,230
3.84375
4
''' Read input from STDIN. Print your output to STDOUT ''' #Use input() to read input from STDIN and use print to write your output to STDOUT import numpy as np class Error(Exception): """Base class for other exceptions""" pass class QRErr(Error): """Raised when the quantity required number list...
5dc8b68102112bd1d6ba55f5b5ade9dbec946443
neetiv/SelfTaughtPythonPrograms
/combining conditions test.py
403
4.03125
4
age = 12 if age == 10 or age == 11 or age == 12 or age == 21: print("Hiya!") else: print("blech!") print(''' ''') age = 2 if age == 10 or age == 11 or age == 12 or age == 21: print("Hiya!") else: print("blech!") age = 12 if age >= 10: print(' OLDY MOLDY!!! ') else: print('YOUNGY PUNGY!') a...
6bb733b24e35df04dfb70a7f5341e8ef30fb6d3d
mangodayup/month01-resource
/day07/exercise09.py
396
4.21875
4
# 练习1: 定义函数,在终端中打印一维列表. # list01 = [5, 546, 6, 56, 76, ] # for item in list01: # print(item) # list02 = [7,6,879,9,909,] # for item in list02: # print(item) def print_list(list_target): for item in list_target: print(f"元素是:{item}") list01 = [5, 546, 6, 56, 76, ] list02 = [7, 6, 879, 9, 909, ] pr...
6a4d9b0bd7d82b0f6594209dcd72739fac964aea
Panic-Point/Euler
/Easy/Largest_Palindrome_Prod.py
255
3.734375
4
ans = 0 def is_palindrome(n): s = str(n) r = s[::-1] if r == s: return True return False for x in range(999, 901, -1): for y in range(999, 901, -1): if is_palindrome(x*y): print(x*y) exit()
87748bfbcbe981d16a24c52fbec0e0669a2c5bc1
mshagena89/Reddit-Comment-Analytics
/Reddit Web Scraper/csvhelpers.py
707
3.703125
4
import csv #CSV Read and write Helper functions #returns list of comments from csv source file #sourceFile: .csv with one column of comment def csvreader(sourceFile): commentList = [] with open(sourceFile, 'rb') as readFile: commentReader = csv.reader(readFile) for row in commentReader: ...
184844e37dfef90c738323f1a6f5d2a538b6b0ec
k200x/leetcode
/Q20.py
372
3.609375
4
#coding:utf-8 def func(ss): tmp_num = 0 isPositive = 1 if ss[0] == "+": pass elif ss[0] == "-": isPositive = -1 total_str = ss[1:] level = 1 for index in range(len(total_str) - 1, -1, -1): tmp_num += int(total_str[index]) * level level *= 10 return tm...
45c252ea8d9db2c694b0c0d845075077fd264761
fifa007/Leetcode
/test/test_pascal_triangle.py
775
3.828125
4
#!/usr/bin/env python2.7 ''' unit test of pascal's triangle ''' import unittest import src.pascal_triangle class pascal_triangle_test(unittest.TestCase): sol = src.pascal_triangle.Solution() def test_with_row_number_equals_zero(self): self.failUnless(self.sol.generate_pascal_triangle(0) == []) ...
5d091d2bdc99af3f6db7ea494cbffa001f1cfda6
phuycke/Project-Euler
/Code/problem_22.py
1,965
4.1875
4
#!/usr/bin/env python3 # Problem setting """ Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the...
6a2de1a4bc6124bf8f6bf39ef261206591e28d50
gabriellaec/desoft-analise-exercicios
/backup/user_208/ch169_2020_06_22_16_29_22_215962.py
553
3.8125
4
def login_disponivel (login,lista): if login not in lista: return login else: for login1 in range(len(lista)): i = 1 while login in lista: login = login + str(i) if login in lista: login = login [:-1] i+=...
f8f03d8bd1033b2638ee1042379b2db012c85a33
pjbautista/algorithms-python
/max_spacing_clustering.py
1,359
3.71875
4
""" Computes the max-spacing k-clustering of a graph """ import sys from heapq import heappop, heapify def main(): """ Main function """ # initialization nr_clusters = int(sys.argv[1]) nodes, graph = build_graph() spacing = 0 clusters = [set([x]) for x in nodes] # orders the edges by...
62a243a1cc4c491b32c464443b1655707329bdc6
nazfisa/python-code
/Basic Python Code/function2.py
188
3.984375
4
def tuple(mytuple): print("Tuple before add") print(mytuple) print("length of tuple is: ") ln=len(mytuple) return ln mytuple=(1,'asif',2,'nazim') print(tuple(mytuple))
11a9a1b69f4253f0a58ebf4b0f8d5e5179cff73e
RafaelGPaz/dotfiles
/bin/misc/obsolete/lauraAge.py
1,443
4.28125
4
#! /usr/bin/env python def CalculateAge(self,Date): '''Calculates the age and days until next birthday from the given birth date''' try: Date = Date.split('.') BirthDate = datetime.date(int(Date[0]), int(Date[1]), int(Date[2])) Today = datetime.date.today() if (Today.month > B...
cf1fec19e512483db1e3625030f32404655b472c
chrishuan9/oreilly
/python/python1/space_finder.py
811
3.96875
4
__author__ = 'chris' #Python 1: Lesson 4: Iteration: For and While Loops """Program to locate the first space in the input string.""" s = input("Enter any string: ") pos = 0 for c in s: if c == " ": print("First space occurred at position ", pos) break pos += 1 else: #Python loops come with ...
c1d148602b89833b44112ab14f5a5746a2a50709
S-W-Williams/CS-Topic-Notes
/Solutions and Writeups/Unique Binary Search Trees.py
219
3.640625
4
from math import factorial class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ return factorial(2*n) / (factorial(n + 1) * factorial(n))
57c0a59efd2fd1f4d0106c654cadba6dd86158e0
tikhomirovd/1sem_Python3
/zachitaintegralov/main.py
361
3.859375
4
# Тихомиров Дмитрий # ИУ7-15Б def f(x): # return 3 * x ** 3 + 2 * x ** 2 + 1 return x*x*x*x*x*x*x def Newton(f,a,b,n): s = 0 h = (b-a)/n for i in range(n): s += f(a+i*h)+3*f(a+i*h+h/3)+3*f(a+i*h+2*h/3)+f(a+i*h+h) s *= h/8 return s a = 0 b = 1 n = 1 I = Newton(f,a...
28f32f3a955f303dd874e8be0f61b06b8fd29664
cyc1am3n/Problem_Solving
/DP/1463.py
491
3.515625
4
# https://www.acmicpc.net/problem/1463 # Name: 1로 만들기 # Topic: Dynamic Programming def solution(N): dic = {} for i in range(1, N + 1): if i == 1: dic[i] = 0 else: dic[i] = dic[i - 1] + 1 if i % 3 == 0: dic[i] = min(dic[i/3] + 1, dic[i]) ...
f78ca3921cbc1ae955f6e41409706644032462a9
mranta-ai/Data_analytics_in_accounting
/_build/jupyter_execute/7.3_ML_for_structured_data-xgboost_example.py
8,515
3.59375
4
## Example - Xgboost, state-of-the-art ensemble method for structured data Xgboost is one of the latest implementations of gradient boosting algorithms, with many optimisations compared to other gradient boosting algorithms. https://xgboost.readthedocs.io/en/latest/ In this example, we are predicting abnormal Tobin...
f92cedc968f5e3ccf46f6be5dbae0bb2dcf5e45f
Merna-Atef/Algorithmic-Toolbox-Coursera-MOOC
/week2_algorithmic_warmup/4_least_common_multiple/lcm.py
436
3.640625
4
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd_eucl(a, b): if b == 0: return a else: return gcd_eucl(b, a%b) def lcm_fast(a,b): const = a*b gcd = gcd_eucl(a, b) retur...
d213016753567a29c1bf7e9538a0beb56e9eb6cb
Lossme8/Python_Fundamentals
/Pandas_library/pandas_library.py
323
3.65625
4
import pandas as pd df = pd.DataFrame({'Date':['7/10/19', '8/10/19', '9/10/19', '10/10/19', '11/10/19'], 'Hours Worked': [7, 7, 7, 7, 7], ' Knowledge acquired on date in percentage': [20, 23, 17, 33 , 7]}) print(df) print("-"*50) print(df.tail()) print("-"*30) print(df.head...
8cb008ebf57280a46ba1c393b380aa539bffa427
branning/euler
/problems/euler026.py
1,019
3.65625
4
#!/usr/bin/env python from euler007 import eratosthenes ''' http://mathworld.wolfram.com/RepeatingDecimal.html http://mathworld.wolfram.com/MultiplicativeOrder.html ''' def MultiplicativeOrder10(n): ''' returns multiplicative order of 10 mod n this is equal to the length of the period of the decimal expansio...
77d1df7caf24550feb313d9ca1cfc676b1943e3f
Shilpi1307/ShapeAI_Python_Cyber_Security
/Shilpi.py
1,253
3.546875
4
import requests #import os from datetime import datetime import sys #to write or push output in a text file api_key = 'd541c87d8c16d4d904419f17a11c4d53' place = input("Enter the name of the place: ") complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+place+"&appid="+api_key api_link = r...
7857961bfc7a477352a6627ef9b38e9f28dd4cb9
jaghadish281098/leap-or-not
/leap or not (jagh).py
165
3.828125
4
year=int(raw_input()) if year%4==0: if year%100==0: if year%400==0: print "leap" else: print"not" else: print "leap"
126ae4c1df4cdfefb37d09583d39604209a1164d
bbperdomo/Competitive-Programming
/hw/hw5/11586_traintracks.py
922
3.890625
4
# Input # Input begins with the number of test cases. Each following line contains one test case. Each test case # consists of a list of between 1 and 50 (inclusive) train track pieces. A piece is described by two code # letters: ‘M’ for male or ‘F’ for female connector. Pieces are separated by space characters. # Outp...
362ec70a8e60e01a9cc07e6c7a6635b250cd5094
Chig00/Python
/Dodge.py
7,973
3.9375
4
#!/usr/bin/env python3 """ Dodge - 'One-tap' dodger. This a 'one-tap' game where the player controls a ball and must avoid the walls approaching by pressing the space bar. Each wall successfully dodged gives the player a point. Over time, the game will become harder by increasing the speed of the walls. """ impor...
09e92d83107e9f1d831cfcac3ad6dc47a636a7a7
jonathanpyle35/free-shavacado
/guess_a_number_ai_pyle.py
2,452
3.8125
4
#Guess-A-Number AI # #Jonathan Pyle #September 13, 2016 import random import math print("**********************************************************************") print(" ") print(" __ ___ __ __ __...
443f332d0a8307d8fd14f487c85e553fdc7121ff
INOS-soft/Python-LS-LOCKING-Retunning-access
/4.3 TSP Problem (Nearest Neighbor heuristic).py
3,123
4.15625
4
""" 1.Question 1 In this assignment we will revisit an old friend, the traveling salesman problem (TSP). This week you will implement a heuristic for the TSP, rather than an exact algorithm, and as a result will be able to handle much larger problem sizes. Here is a data file describing a TSP instance (original sourc...
da1c9659cadc6890efb0a302ed4bea1db0157d49
joingram/cs1200_jingram
/lab_3_0/3_0.py
5,426
4.6875
5
""" CSCI 1200 Lab Exercise 3.0 INTRODUCING LISTS Your task in this lab exercise is to learn to declare lists and to perform basic operations on lists. Do all work in Geany IDE and follow instructions provided in this code file. Learning Outcomes ================= In this lab you will learn: - How to declare lists ...
174b295147f6dbee67c9fe662f554cda76a6f58c
Tranqui11ion/Concurrency
/processes.py
1,104
3.640625
4
import time # from multiprocessing import Process from concurrent.futures import ProcessPoolExecutor def ask_user(): start = time.time() user_input = input("Enter your name: ") greet = f"Good morning, {user_input}!" print(greet) print(f'ask_user {time.time() - start}') def complex_calculation():...
116b577ed3e12997a273675c2add7d9cc4fd46cf
JeffersonDing/CompetitiveProgramming
/CCC/CCC_2021/PREP/j1.py
244
3.65625
4
digits = [] for i in range(4): digits.append(int(input())) if(digits[0] == 8 or digits[0] == 9): if(digits[-1] == 8 or digits[-1] == 9): if(digits[1] == digits[2]): print("ignore") exit() print("answer")
49b3b1c4ae89d2ba66ac4139d9bc74b8a9ee9f28
quhuohuo/python
/lvlist/teacherPython/try2.py
348
3.640625
4
#!/usr/bin/python import traceback def div(a,b): try: return a / b except (ZeroDivisionError,TypeError) as e: # print "zero can not be divsion" print e traceback.print_exc() else: print "else......" finally: print "finally...." result = div(3,'c') pri...
6b782189945c44d89ed7cb01de6afa0f10edfa9c
rashid-mamadolimov/Collection
/digits of decimal number.py
203
3.59375
4
x_dec = 90 x_dec_str = str(x_dec) print("String form: ", x_dec_str) x_dec_list = [] for i in range(len(x_dec_str)): x_dec_list.append(int(x_dec_str[i])) print("List form: ", x_dec_list)
690729694f41376be889f8c2d2482bdc248ec12a
AshJo233/Python_fullstack
/day13/lambda.py
608
3.703125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Filename :lambda.py @Description : @Datatime :2020/08/30 11:33:42 @Author :AshJo @Version :v1.0 ''' # 匿名函数:一句话函数,比较简单的函数 def func(a,b): return a + b # 构建匿名函数 func1 = lambda a,b: a + b print(func1(1,2)) # 接收一个可切片的数据,返回索引为0和2的对应元素(元组形式...
db53f29968b97d275c93c09e365b565f916fc242
shadiqurrahaman/python_DS
/stack/make_queue_with_stack.py
699
4
4
class Queue: def __init__(self): self.s1 = [] self.s2 = [] def enQueue(self,data): if len(self.s1) != 0 : for i in range(len(self.s1)): self.s2.append(self.s1.pop()) self.s1.append(data) for i in range(len(self.s2)): se...
a76cce0c65ca939d4852ca299033351137c26953
seakun/automated_python_projects
/comma_code.py
301
3.625
4
def commaCode(listInput): newOutput = '' for x in listInput: if(isinstance(x, int)): newOutput += str(x) + ', ' else: newOutput += x + ', ' return newOutput[:-2] #spam = ['apples', 'bananas', 'tofu', 'cats'] spam = [1, 2, 3] print(commaCode(spam))
77b32ed2eb4512b97296c33191453d388fdd01ed
CookieVulture/Kattis
/Chapter-3/froshweek2.py
420
3.5625
4
if __name__ == "__main__": n, m = map(int, input().split()) task = 0 tasks = list(map(int, input().split())) intervals = list(map(int, input().split())) tasks.sort() intervals.sort() i = 0 j = 0 while i < len(tasks) and j < len(intervals): while tasks[i] > intervals[j] and j ...
c3b36ea94545a04147390712fdb7fa949b3b2516
J0/Kattis
/python/farming/fizzbuzz.py
267
3.609375
4
test_case = input().split() for i in range(1, int(test_case[2]) + 1): x = int(test_case[0]) y = int(test_case[1]) if i % x == 0 and i % y ==0: print("FizzBuzz") elif i % x == 0: print("Fizz") elif i % y == 0: print("Buzz") else: print(i)
d8581660bf4b4cc8511c665fa2404da2f504e0b7
swetha-1994/affosoft-test
/test.py
121
3.8125
4
n=input("Enter the string:") x=len(n) for i in range(x): for j in range(i+1): print(n[j],end="") print()
06f72f8798182d93dbde6c4eaa26ba9acb04af85
AliAbdilahi/Assignment-week-6
/Assignment 2.py
394
4.03125
4
prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = {"banana": 10,"apple": 0,"orange": 7,"pear": 9,} for x in prices: print (x) print ("price: %s" % prices[x]) print ("stock: %s" % stock[x]) total = 0 print("Prices * Stockes=") for x in prices: print (prices[x] * stock[x...
6da4527e728ed28b0d582b81d142fe4623033100
bluelemon1969/Training
/Python/20171123_VariableAndCalculate.py
197
3.5
4
test = 123456 test2 = 123456 print (test + test2) 卵 = 123 砂糖 = 123 print (卵 + 砂糖) ishinabe = "石鍋の" saori = "馬鹿野郎" print (ishinabe + saori) test += test print (test)
cc0fdb3a4058277b29e1c778529bb80fe5dab6e1
ManuelSerna/uark-snlp
/wsd/wsd.py
8,397
3.703125
4
#************************************************ # SNLP Homework 2 # Manuel Serna-Aguilera # # Disambiguate word sense given a pseudoword (two different words with two different meanings concatenated together) #************************************************ import sys import string import json #===================...
f43663276821cac4c9c415ebe7c9077deb9620b8
tanglan2009/mit6.00
/LecturePractice/classPerson.py
2,088
4.21875
4
import datetime class Person(object): def __init__(self, name): """Create a person called name""" self.name = name self.birthday = None self.lastName = name.split(' ')[-1] def getLastName(self): """return self's last name""" return self.lastName def setBirt...
65072cd5daabda89acb20f8d738605979b261a26
purushothamanpoovai/notifybirthday
/notifybirthday.py
1,777
3.5625
4
#!/usr/bin/env python #Author: Purushothaman K #To print the birthday list everyday #Birthday list: data={ "0101":["karthickraja"], "1701":["Thulasi"], "2101":["Padmanagarajan"], "2201":["Purushothaman"], "0102":["Muthukumar"], "1802":["Vinothini"], "2703":["Sathiya"], "0204":["Neelaveni","Maharajan"], "06...
46b03fa65c49f41fe39bf23ad636ad503f8a87b6
ganastassiou/poly2d
/poly2d/poly2dfit.py
10,817
3.6875
4
""" 2D Polynomials with fitting capability. """ from functools import reduce, wraps import numpy as np from numpy.polynomial.polynomial import polyval2d def calculate_powers(x, n): """ Calculate the powers of x up to order n, Parameters: ----------- x: scalar or array like 1-D array conta...
31df7ceea67fa770d5a4401f46aa8858e583d3d5
datatalking/test_monkey
/mystuff/ex15.py
894
3.796875
4
# PATH ~/sbox/lpthw/mystuff/ex15.py # imports sys module from argv from sys import argv # creates a script at position 0 and 1 as argument variables # the script becomes the filename of the python script in this case ex15.py script, filename = argv # sets the txt as variable to open the filename as an object txt = o...
567014d31abdfa7b45e762b8b8b1712a86d68472
riehseun/NutritionDetector
/FoodCalorieWriter.py
360
3.578125
4
import json def writeToFile(foodName, Calorie): """ """ with open("FoodToCalorie.json") as f: data = json.load(f) data.update({foodName: Calorie}) with open("FoodToCalorie.json", "w") as file: json.dump(data, file) file.close() food = input("input food: ") cal = input("inpu...
e8173f2baa4e3080b5c33ae1bd6ffd7134413589
l-schultz3/python-tictactoe
/prototypes/testing.py
478
3.953125
4
print("running...") def swap(arr, x, y): arr[x], arr[y] = arr[y], arr[x] def runPermute(arr): permute(arr, 0, len(arr)) def permute(arr, i, n): global numberOfPermutes if (i == n): numberOfPermutes += 1 else: for j in range(n): swap(arr, i, j) permute(arr, ...
6a01a734f89c28e05bcabf94e449fd687b525f74
vineetkumarsharma17/MyPythonCodes
/List/List_input_output.py
263
3.875
4
n=int(input("Enter the number of element:")) lis=[] for i in range(n): val=int(input("Enter value:")) lis.append(val) print(lis) # method 2 with tyr and except method try: lis=[] while True: lis.append(int(input())) except: print(lis)
4e0d7d7a8971e9fc1f9a0cce06665d084b519803
sam79733/LeetCode
/MayMonthChallenge/Valid Perfect Square.py
712
3.875
4
""" Valid Perfect Square Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false Solution: """ class Solution: def isPerfectSqua...
ca6502f3667f9f72d3cb1e18ac6e3e905018db0a
L-xbin2020/PythonStudy
/PythonStudy/06格式化字符串.py
216
3.671875
4
# 格式化字符串后面的()本质上是元组 print("%s 年龄是 %d 身高是%.2f" %("小明",18,1.75)) info_tuple = ("小明",18,1.75) info_str = "%s 年龄是 %d 身高是%.2f"%info_tuple print(info_str)
73a1995dbad6025929091f998d54821417dc8360
sagar124987/Showing_calendar
/Showing_calendar_Using_Tkinter.py
632
4.375
4
# as simple monthly calendar with Tkinter # give calendar and Tkinter abbreviated namespaces import calendar as cd import tkinter as tk # supply year and month year = eval(input('Enter a year:')) month = eval(input('Enter a month:')) # jan=1 # assign the month's calendar to a multiline string str1 = cd.month(year, m...
8d2fd98ffc6857cde991335e1d5bc875314a7fd6
vvaquero/MIT_Python_6.0001
/ps2/hangman.py
13,691
4.125
4
# Problem Set 2, hangman.py # Name: # Collaborators: # Time spent: # Hangman Game # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string WORDLIST_FILENA...
dc147eded14edba14347bcf4b016a6d55cfee01e
marri88/python-base
/Hakaton/Hakaton1.py
5,680
3.640625
4
# # Задание №1: # Если взять ВСЕ числа от 0 до 10, которые деляться на 3 или 5 БЕЗ ОСТАТКА, то получим 3, 5, 6 и 9. # Сумма этих чисел равна 23 (3+5+6+9) = 23. # Найдите сумму всех чисел меньше 1000, кратных 3 или 5. a=[x for x in range(1,1000) if x%3==0 or x%5==0] print(sum(a)) # --------------------------------...
f7c4d601e49760017a47290587a7011924045685
AruzhanBazarbai/pp2
/tasks/task1/E.py
148
3.703125
4
#done import re def f(s): x=re.match("^[a-z]+@[a-z]+\.[a-z]+$",s) if x: print("Yes") else: print("No") s=input() f(s)
231fcb91f9140656478c73b35601a70d08d373b2
xiaozurong/xzr
/ex6-4.py
431
3.734375
4
str=input("请输入要分析的字符串,回车表示结束:") while str !='': counts={} for ch in str: counts[ch]=counts.get(ch.o)+1 items = list(counts.items()) items = sort(key = lambda x : x[1],reverse=True) for i in range(len(items)): word,count = items[i] print("{0:<10}{1:5}".format(word,cou...
7f10195ed90c80092455aa8c63e38e7a53c1f369
Ciaran-McGarvie/helloworld
/Exc9.py
356
3.953125
4
# This is your main function # This is where you declare your variables and use your functions def main(): distance = 20 speed = 1 distance_covered = 0 while(distance_covered < distance): print(distance_covered) distance_covered= distance_covered + speed print("you are finished") # Call your main function ...
e94e2cb3f8f7848ff6a1a0d6e9fa381d79b5af0f
magnoazneto/IFPI_Algoritmos
/URI/uri_1042_ordem_crescente.py
257
3.796875
4
def main(): lista = input().split() original = [] for c in range(0, 3): original.append(int(lista[c])) crescente = original[:] crescente.sort() for c in range(0, 3): print(crescente[c]) print() for c in range(0, 3): print(original[c]) main()
1597a760024c56179e83002a33477cd9b9de16b2
KyleC14/SwordToOfferPractice
/code/Question19/Solution1.py
828
3.53125
4
''' 递归做法 参考https://leetcode-cn.com/problems/regular-expression-matching/solution/zheng-ze-biao-da-shi-pi-pei-dong-tai-gui-hua-by-jy/ ''' class Solution: def isMatch(self, s: str, p: str) -> bool: #p到结尾时,如果s也到结尾则为true if not p: return not s if len(p) > 1 and p[1] == '*': ...
250f40fc7a0a44cc1a630a0e49ccb73e78c5020c
gcnit/Competitive-Programming
/left shift.py
58
3.59375
4
t=int(input()) x=1 while t>0: x=x<<1 t=t-1 print(x)
98ef87e8cd1db024cb0808e0dd7df7c907caf346
bluestreakxmu/PythonExercises
/FlashCardChallenge/quizzer.py
1,352
3.65625
4
import random from sys import argv import os def read_flashcard_file(filename): """Get the questions from a fixed flash card file""" filepath = "cardrepository/" + filename if not os.path.isfile(filepath): print("Not a valid file name!!") exit() flash_card_dict = {} with open(file...
728fd4d81dcf6c82795df7c8defed433e614cd08
cgisala/Capstone-Intro
/My_Turn2.py
252
3.515625
4
numList = [0, 3, 4, 0, 22, 1] noZero = [zero for zero in numList if zero > 0] print(f'No zero in list: {noZero}') classList = ['ITEC 2560', 'BTEC 1010', 'ITEC 2905'] itec = [itec for itec in classList if 'ITEC' in itec] print(f'ITEC classes: {itec}')
e32415e8110a0793b594e02d7ad9b9c1331398ce
mcode36/Code_Examples
/Python/Python_CodingBat/make_bricks.py
1,000
3.90625
4
''' # method 1 def make_bricks(small, big, goal): possible = False i = 0 for i in range(0,big+1): for j in range(0,small+1): # print(i,j,i*5+j) if i*5 + j == goal: possible = True break if possible: break return possible # method 2 def make_bricks(small, big, goal): ...
4211b1fa093def536158860e2735e6301f133337
Omkar-M/Coffee-Machine
/Problems/Piggy bank/task.py
562
3.625
4
class PiggyBank: # create __init__ and add_money methods def __init__(self, dollars, cents): self.dollars = dollars self.cents = cents def add_money(self, deposit_dollars, deposit_cents): self.dollars += deposit_dollars self.cents += deposit_cents if self.cents > 99:...
0957a8d13c972f72bdd567661d74aa389d8e63f0
pineman/code
/old_proj/BOSK/Real Code/oldClasses.py
20,207
3.65625
4
import cmd class Player(object): def __init__(self,name,sex,hp=0,strength=0,defense=0,agility=0,intelect=0 ,luck=0,swag=0,money=0,inventory=[]): def check_stat(stat): '''check if the passed argument is an integer''' return not(type(stat) == in...
f1450f788546dc87cc2a973ba7ec88c7a0bbacf1
kennybix/MATH_5470
/interpolation_models/core/preprocessing.py
2,391
3.828125
4
import numpy as np def normalize(x): y = (x-min(x))/(max(x)-min(x)) return y # def denormalize(x,ymin,ymax): # if(x.shape[1]==1): # n = len(x) # y = np.ones(n) # for i in range(n): # y[i] = (x[i]*(ymax-ymin))+ymin # else: # k = x.shape[1] # ...
3101af3a2763eae48140635bdfc3927920050dc5
JuliaWozniak/computor2
/second.py
1,971
3.703125
4
from abc import ABC, abstractmethod import re class Operand(ABC): @abstractmethod def describe(self): pass @abstractmethod def __add__(self, other): pass # @abstractmethod # def __sub__(self, other): # pass # @abstractmethod # def __mul__(self, other): # pass # @abstractmethod # def __truediv__(self...
509a39ccb542e8510d8ddf510afcf133288e0bbc
ongsuwannoo/PSIT
/circularprime V.Chotipat.py
867
4.15625
4
""" CircularPrime """ def sum_circular_prime(num): """Return sum of circular prime from 1 to num""" total = 0 for i in range(1, num+1): if is_circular_prime(i): total = total + i return total def is_circular_prime(num): """Return True if num is circular prime else otherwise"""...
f731979f5dfba2240dfc71ba89f8f7eddffee59a
rocheio/advent-of-code
/day3.py
3,121
4.34375
4
""" https://adventofcode.com/2019/day/3 """ def path_to_trail(path): """Walk a path starting at (0,0) and return a list of each coordinate hit along the way.""" trail = [] current = (0, 0) trail += [current] for step in path: coords = coords_between(current, step) trail += coords ...
6336ecbfca48c0e59d293b2bf4f953a8732e545d
Erniess/pythontutor
/Занятие 6 - Цикл while/Практика/Стандартное отклонение.py
982
3.5
4
# Задача «Стандартное отклонение» # Условие # # Дана последовательность натуральных чисел x1 # , x2, ..., xn. Стандартным отклонением называется величина # σ=(x1−s)2+(x2−s)2+…+(xn−s)2n−1‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾√ # где s=x1+x2+…+xnn # # — среднее арифметическое последовательности. # # Определите стандартное ...
444648bebfd0a6111683801b5b111ba11fd8fcb0
FloHab/Project-Euler
/Problem 22.py
1,544
3.90625
4
#Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, #begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, #multiply this value by its alphabetical position in the list to obtain a name score. #For example...
454cf3443785db17b1a08644ddce592c5252a071
Aasthaengg/IBMdataset
/Python_codes/p02900/s650383711.py
1,045
3.65625
4
import math def primelist(n): is_prime = [True] * (n + 1) is_prime[0] = False is_prime[1] = False for i in range(2, int(n**0.5) + 1): if not is_prime[i]: continue for j in range(i * 2, n + 1, i): is_prime[j] = False return [i for i in range(n + 1) if is_prime...
508a972f076ff199669c13d6dc949bcc22e2743c
ajayajdeveloper/my-python-code-
/Zigzag1.py
1,605
3.90625
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import deque class Zigzag1: def zigzagLevelOrder(self, root): if not root: return [] re...
3b2c7974e4abcc4218c1731fbdf49a1877d5bec8
isaacrivas10/arbol-proyecto-aed
/pruebas/temp.py
2,161
3.84375
4
# NO MODIFICAR! # SE EFECTUAN PRUEBAS class ListaEnlazada: def __init__(self): self.first= None # Es un nodo def add(self, addV): c = self.first if c is None: self.first = addV else: exist= True while exist: # Mientras exista el nodo if c.getNext() is None: # Si despues de c no hay un nodo ...
1d7ffc9486cdd3ff09cae01930f7a7fb2161d140
longgb246/MLlearn
/leetcode/base/11_max_area.py
1,507
3.734375
4
# -*- coding:utf-8 -*- # @Author : 'longguangbin' # @Contact : lgb453476610@163.com # @Date : 2019/1/11 """ Usage Of '11_max_area.py' : """ class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ # 较长线段的指针向内侧移动,矩形区域的面积将受限于较短的线段而...
3f1678e0040f67bf47a3d019b30342628c640984
danielrobin2011/ML-Practice
/Linear Regression/Salary-Experience/Salary-Regression.py
688
3.8125
4
import numpy as np; import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv("Salary_Data.csv"); #Divide the dataset into X and Y alpha = 1 X = dataset.iloc[:,0].values Y = dataset.iloc[:,1].values m = dataset.iloc[:,0].values.length(); print(m) theta=[ 1.0, -1.0 ] def cost(X, Y, m, theta): squa...
e30acd77c493919f03b9082225fa0730667e7436
Prasad-Medisetti/STT
/My Python Scripts/NearlyEq.py
285
3.71875
4
def nearly_equal(s1, s2): l = len(s1) if len(s1) < len(s2) else len(s2) i = 0 cnt = 0 for i in range(l): if s1[i] == s2[i]: continue else: cnt += 1 print("Nearly Equal") if cnt == 1 or cnt == 0 else print("Not Nearly Equal")
7f1a217753ba8a67f3fc0a9fe4516c2cd9f5f19f
matheuspiana/Trabalho-CG
/compgraf.py
1,559
3.640625
4
from random import choice import string usuarios = [] def cadastro(): listuser = open("user.txt","w") listsenha = open("senha.txt", "w") user = input("Escolha seu ID: ") senha = input("Digite a sua senha: ") #cadastro = ["\n", user,"\n", senha, "\n", "_"*50] listuser.wr...
490b8aaf0ab4e2adb3440355fbf271a1b9b9f650
codecakes/random_games
/remove_html_tags.py
1,625
3.890625
4
#Remove HTML Tags from plaintext # When we add our words to the index, we don't really want to include # html tags such as <body>, <head>, <table>, <a href="..."> and so on. # Write a procedure, remove_tags, that takes as input a string and returns # a list of words, in order, with the tags removed. Tags are defined ...
7583dda8c8a6b8fa9e7b9ae66b7a41f79e0d284a
gmclapp/Personal_library
/chess/chess.py
13,652
3.65625
4
import pygame from pygame.locals import * def quit_nicely(): pygame.display.quit() pygame.quit() class board(): def __init__(self): self.dark_color = (50, 50, 50) self.light_color = (255, 255, 255) self.square_size = 60 self.light_square = pygame.Surfa...
95988b112ba8773b5e51910b1d583675b448182a
Sorany-Potato/nlp100nock
/nock6.py
1,231
3.6875
4
import ngram import list_subtraction a="paraparaparadise" b="paragraph" x=sorted(set(ngram.ngram(a,2))) y=sorted(set(ngram.ngram(b,2))) print("x:",x) print("y:",y) w=x+y """ 関数ngramの内容 def ngram(text,n): #n字数ごとずらす x=[] for y in range(len(text)): if y==len(text)-n+1:...
203c49a5c17d7c8cc22b89b47e00dabf1c3b4fa1
aleexnl/aws-python
/UF1/Nieto_Alejandro_Gomez_Alejandro_PT12/Ej8.py
623
3.9375
4
letrasdni = ["T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E"] # Iniciamos lista con valores pred. dni = int(input("Introduce los numeros del DNI:")) # Pedimos un DNI while len(str(dni)) != 8: # Comprobamos que tenga esta longitud bucle ...
896af2ba19237f1a96fa17f7b7a3758b91acdb81
daniel-reich/turbo-robot
/J67xWvM4jFhn9nEpJ_9.py
4,490
4.46875
4
""" Make a function that takes a integer, `size`, returns 2D list that is a Magic Square with side lengths of `size` A Magic Square is an arrangement of numbers in a square in such a way that the sum of each row, column, and diagonal is one constant number, the "magic constant." For this challenge I will be testing...
95b53da71bb60b32345dfc290ac8cf3d2f6f3310
RayArthur/PythonLession
/pro0605/py08.py
1,078
3.8125
4
def f1(a, b): return a + b def f3(): print('Python') def f5(a=1, b=2, c=3): return a + b + c def f7(x, y): if x > y: return x else: return y print(f1, type(f1)) print(f1(1, 3)) print('-' * 30) f2 = lambda a, b : a + b #匿名函式 print(f2, type(f2)) print(f2...
315533accdcaa4bd590de5b0e511287c6482ba21
ghadd/tictacdrop
/ai.py
7,147
4
4
from config import * from random import shuffle from copy import deepcopy def is_column_valid(board, col): return board[0][col] == 0 # check the search range for rows and columns def is_range_valid(row, col): return row in range(ROWS) and col in range(COLS) # return all valid moves (empty columns) from th...
45c66b48391616d3da159e6a1750eb1a871aff37
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/9210076ca09b4f089924c9b45732cea7.py
203
3.6875
4
def distance(dna1, dna2): longest = None if len(dna1) >= len(dna2): longest = dna1 else: longest = dna2 dist = 0 for i in range(len(longest)): if dna1[i] != dna2[i]: dist += 1 return dist
16c9f40d3688422c4139d53748f653a62cb1f8a3
ashleynkomo/selection
/Revision exercise 3.py
247
4
4
#Ashley Nkomo #30-09-2014 #Selection Revision Exercises 3 number = int(input("Please enter a number: ")) if 21 <= number <=29: print("The number entered is within range") else: print("The number entered is out of range")
f908862645806a014e3e75777b5b03b857d40567
kevingtzz/DistData
/p1/client.py
1,878
3.71875
4
#Client code """ August 1, 2021 Created by: Sebastian Loaiza Correa """ #Import socket library import socket import constants import os #Variables for connection host = constants.SERVER_ADDRESS port = constants.PORT def runClientSocket(): #Create client socket clientSocket = socket.socket() #Connection w...
27c1cabf5662fd4bed2f3d4c400e644cd87ee34d
zombiyamo/nlp100
/1/08.py
473
3.875
4
# -*- coding: utf-8 -*- import sys def cipher(text): rText = '' for letter in text: if 97 <= ord(letter) <= 122: rText += chr(219 - ord(letter)) else: rText += letter return rText # return "".join(chr(219-ord(c)) if c.islower() else c for in text) args = sys.a...
f577d321d59b4267ccc87a08bf95f9d678a3cf97
rirwin/sandbox
/scratch/python-dp/longest_common_subsequence.py
355
3.5
4
import numpy def lcs_1(s1,s2): if len(s1) == 0 or len(s2) == 0: return 0 elif s1[0] == s2[0]: return lcs_1(s1[1:], s2[1:]) + 1 else: return max(lcs_1(s1,s2[1:]), lcs_1(s1[1:],s2)) def lcs_2(s1,s2): n = len(s1) m = len(s2) mat = numpy.zeros(n,m) s1 = "theryan" s2 =...
328a1870ed5ca480a3123b643812d6f21536924c
PragayanParamitaMohapatra/Basic_python
/DataStructure/convert_integer_to_binary.py
345
4.03125
4
""" use stack data structure to convert the integer values to binary values """ from DataStructure.stack import StackDs def div_by_2(dec_num): s=StackDs() while dec_num>0: rem=dec_num%2 s.push(rem) dec_num=dec_num//2 bin_num="" while not s.is_empty(): bin_num += str(s.p...
1fa1383f2a5ad583e70a8162001eae75ed5c2e9d
BetterRules/example-rules-as-code
/python/test.py
1,715
4.03125
4
#!/usr/bin/env python import csv from run import Person def make_bool(value): if value == 'Yes': return True if value == 'No': return False return None if __name__ == "__main__": # open up the csv file containing the tests with open('../shared/example_beards.csv') as csv_file: ...
94a6b47a8468ddc40a758b8c22d0c1894af05fa3
igorfelipes/Estrutura_de_dados_UNIESP
/Exercicios_estrutura_de_dados/exercicioH.py
263
3.9375
4
def main(): ages = [] for i in range(5): ages.append(int(input('Digite o ano de nascimento: '))) ages.sort() print('Crescente: ', ages) ages.sort(reverse=True) print('Decrescente: ', ages) if __name__ == "__main__": main()
9789613a8beff9f27a8429d0a82410de59f78fe7
reiniscirpons/freebandlib
/freebandlib/digraph.py
3,776
4.125
4
"""Graph utility functions.""" from typing import List, Optional DigraphVertex = int DigraphAdjacencyList = List[List[DigraphVertex]] def digraph_reverse(digraph: DigraphAdjacencyList) -> DigraphAdjacencyList: """Create the reverse digraph of the input. Does not modify the input digraph. Parameters ...
18ffaf2f32689e739646cf04914568cfda69233c
ssrajputtheboss/DSI
/python/item/item.py
953
3.546875
4
from datetime import datetime class item(): def __init__(this ,id : int , name : str , mntime : datetime): this._id = id this._name = name this._mntime = mntime def __repr__(this) -> str: return repr(( this._id , this._name , this._mntime )) def __str__(this) -> str: ...