blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
14bd5d73a5c6cd21cd423671a842b44cddb2ed8b
ShaktiGit/ShaktiPython
/csvViewerGui.py
687
3.53125
4
import tkinter import csv from tkinter import * from tkinter import messagebox root=tkinter.Tk() def onclose(): if messagebox.askokcancel("Quit Window","Do You Want To Quit?"): root.destroy() lbl1=Label(root,text="Enter Loc:") lbl1.pack(side="left") txt1=Entry(root) txt1.pack() def display(): str1=txt1....
c12dea23f8414434694c402fe32bb4b9d7986bb3
mattwhitesides/CS5200
/Exam/2/Zip/Prob8c.py
5,365
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import random import time # In[2]: class BinaryTreeNode: def __init__(self, v): self.key = v self.left = None self.right = None def tree_insert(T, z): y = None x = T while x: y = x if z.key...
141726cc245fe3ee6c92e9804571cd2034b49253
sahanaparasuram/leet_code
/can be overwritten.py
95
3.6875
4
sum=0 l=[1,2,3,4,5,6,7,8,9,10] for i in l: if i%3==0: sum+=i print('result =',sum)
2374a5ecb69f8118d3d5a8674df2c4bf5db98356
JourneyBoiye/discovery
/scripts/transform_un_census_data.py
2,459
3.734375
4
#!/usr/bin/env python # # This script takes in UN data for all cities and performs a transformation on # it. Note that each row is assumed to represent both sexes with no split. This # transformation consists of a few steps. First, the result only contains the # city population, the country name and the city name. The...
d69db4baca4fc1abd3e803d63573714a193eee2e
manokhina/leetcode-common-questions
/python/11_longest_substring_distinct.py
776
3.859375
4
""" Question: Given a string S, find the length of the longest substring T that contains at most two distinct characters. For example, Given S = “eceba”, T is "ece" which its length is 3. """ class Solution: def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int ...
52a1c1517c089b64710faff404ba9e341a9c56e5
StAndrewsMedTech/wsipipe
/wsipipe/utils/filters.py
1,364
3.546875
4
import numpy as np from numpy.lib.stride_tricks import as_strided from scipy import stats def pool2d(A, kernel_size, stride, padding, pool_mode="max"): """ 2D Pooling Taken from https://stackoverflow.com/questions/54962004/implement-max-mean-poolingwith-stride-with-numpy Parameters: A: input 2...
6b6a2249a3eb138a551ecff6f72f409242bb6bec
kevinliangsgithub/usePy
/src/com/basic/basic.py
7,238
3.734375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:basic.py # if you want to print chinese,mast set coding (before 3.x) # print("中文") # Python 标识符 # 在 Python 里,标识符由字母、数字、下划线组成。 # 在 Python 中,所有标识符可以包括英文、数字以及下划线(_),但不能以数字开头。 # Python 中的标识符是区分大小写的。 # 以下划线开头的标识符是有特殊意义的。以单下划线开头 _foo 的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx...
2dc43ad912f28e8dc076f81c34a7fb951dbd5ef0
Arctem/nmt_python_labs
/labs/attic/poke_project/tk_helloworld.py
703
3.984375
4
import tkinter window = tkinter.Tk() window.title("Title!") # Notice dat title! window.config(background = "white") left_frame = tkinter.Frame(window, width = 200, height = 400) left_frame.grid(row = 0, column = 0, padx = 10, pady = 3) right_frame = tkinter.Frame(window, width = 200, height = 400) right_frame.grid(r...
8e3efca828aab25f84ffb36283c4bd8409bbab6f
nptit/python-snippets
/squareRoot.py
1,011
3.90625
4
class squareRoot(): def __init__(self, value=0, accuracy=1e-10): if value < 0: raise ValueError("don't know how to calculate root of a negative number") self.value = value self.root = 0 self.accuracy = accuracy def binarySearch(self): low = 0 high = s...
40f55646df6728021d0ca363914c008829da10c3
lilywang20119/shiyanlou
/Code/calculator-2.py
1,289
3.921875
4
#!/usr/bin/env python3 import sys salary_dict = {} for arg in sys.argv[1:]: try: salary_dict[arg.split(':')[0]] = int(arg.split(':')[1]) # print(salary_dict) except: print("Parameter Error") def f1(salary): total_tax = salary*(1-0.165)-3500 if 0<total_tax <=1500: rate = 0...
b9f7ac9c690d722dc993de04d94423d60e901aeb
sambhav228/Data_Structure_Algorithm
/Python-Hackerrank/Validating phone numbers.py
279
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import re n = int(input()) pattern = re.compile(r'^[7-9]\d{9}$') numbers = [input() for _ in range(n)] for number in numbers: if pattern.match(number): print('YES') else: print('NO')
b43eb67091d85c9f91029aaca58952581ae5a6bf
glauterlima/jogos
/faixa_etaria/faixa_etaria_variaveis.py
133
3.5625
4
idade_str = input("Digite sua idade:") idade = int(idade_str) maior_idade = idade > 18 criaca = idade < 12 adolescente = idade > 12
d350b2840dc288f5dd8f0578ece737327c0a4ddd
vincentntang/LY-Python3-Essential
/12 Classes/classes-polymorphism-1.py
1,169
4.28125
4
#!/usr/bin/python3 # classes.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC class Duck: def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck.') def bark(self)...
75c72d44cb8978abca192d1e10c74610d4e7c547
jgalaz84/eman2
/examples/ctf_first_zero.py
588
3.53125
4
#!/usr/bin/env python # this simple program will find the approximate resolution of the first zero as a function of defocus # computationally. While you could compute a functional form as well, this demonstrates some useful # EMAN2 programming techniques from EMAN2 import * from numpy import * c=EMAN2Ctf() c.voltage=...
7c12e2c7a88a02658fcaa26e094ade06f3665547
Shuailong/Leetcode
/solutions/closest-binary-search-tree-value.py
1,648
3.875
4
#!/usr/bin/env python # encoding: utf-8 """ closest-binary-search-tree-value.py Created by Shuailong on 2016-02-18. https://leetcode.com/problems/closest-binary-search-tree-value/. """ '''Not solved yet''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = ...
af21017966de78fe00a29d0bdfd44b2501bcab75
11BigBang/sandbox
/betting.py
1,766
3.625
4
import matplotlib.pyplot as plt import numpy as np from random import random from statistics import mean, median #test def get_br(n, rounds, perc_bet, win_perc): """Generates a list of the median bankroll. Arguments: n - number of sequential bets rounds - number of times to perform simulation ...
4fb65f9085bc8911b863316e1ffc78b11907e1c9
ScrawnySquirrel/FeistelCipher
/cryptography.py
6,735
3.59375
4
import multiprocessing from itertools import repeat import random import math import baseconversion as bc def split_half(str): """ Split a string in half and return tuple. str - the string to split """ split_pairs = str[:len(str)//2], str[len(str)//2:] return split_pairs def left_shift(key,s...
ba32b929f96ff73117e8e5fac8ae48644eb14b5d
kv-95/pyStreak
/Basic Programs/Day08.py
395
4.34375
4
# Python program to check whether a number is Prime or not def isPrime(num): for i in range(2, int(num/2)+1): if num%i == 0: print("{} is a NOT a Prime Number!".format(num)) return print("{} is a Prime Number!".format(num)) if __name__== '__main__': num =int(input("Enter th...
611834ccb6ff3b0626f74725cedbd25fd7e7aace
Warriors33/cti110
/M7T2_FeetToInches_QuincettaDaniels.py
401
4.25
4
# You will Convert Feet To Inches #14 Dec 2017 #CTI 110 M7T2_FeetToInches #Quincetta Daniels # def feetToInches( userFeet ): inches = ( userFeet / 1 ) * 12 return inches def main(): userFeet = float( input( "Please enter the number of feet: " )) inches = feetToInches( userFeet ) print...
373546c39c0d66d4963bd0f7bea7d49de50e9800
xentropy-git/nnLinearFit
/linear_fit.py
2,493
3.9375
4
import matplotlib.pyplot as plt import numpy as np import time # line fit experiment # use a single neuron to fit a line # line definition format y = mx+b m = 2 b = 15 # plot line for reference x0 = np.linspace(-15, 15, 1000) y0 = m*x0 + b print ("Defined line in y=%sx+%s"% (m, b)) plt.plot(x0, y0); plt.show() time.s...
9de58a8a30436517cb53cdf235caf34bd03258a3
HenriqueDomiciano/projetosEulereOutros
/Euler 51-60/euler55.py
345
3.5625
4
def sum_of_inverse(n): x=str(n) m=x[::-1] return int(x)+int(m) def is_tyrrel(n): val=0 r=0 while r<51 : n=sum_of_inverse(n) if str(n)==str(n)[::-1]: return False r+=1 else: return True val=0 for r in range(1,10001): if is_tyrrel(r): ...
c2889b7ad7989dadb13fea2076e52007a476f120
jacky881011/12-Hours-Python-Class
/#8 Nested Loop.py
315
4.15625
4
# nested loop = The 'inner loop' will finish all of it's iterations before # fifishing one iteration of the "outer loop" rows = 5 cols = 10 for i in range(rows): for j in range(cols): print('$', end ="") # 平遞增顯示 print() # 結束一整列後換行
c29aac71e8c9191aed087895ced805bfb9287991
ChenLaiHong/pythonBase
/test/homework/5.1.2-求绝对值最小者.py
602
3.765625
4
""" 【问题描述】编写程序实现:计算并输出标准输入的三个数中绝对值最小的数。 【输入形式】标准输入的每一行表示参与计算的一个数。 【输出形式】标准输出的一行表示输入的三个数中绝对值最小的数,如果有多个,以一个空格作为间隔. 【样例输入】 -1 3 1 【样例输出】 -1.0 1.0 """ number = [] temp = [] for i in range(3): number.append(float(input())) temp.append(abs(number[i])) minNum = min(temp) for j in range(temp.__len__()): if minNum =...
04cf72a64440956f5a13bc177e60fd7736b146e3
electrachong/holbertonschool-higher_level_programming
/divide_and_rule/h_str_length.py
504
3.734375
4
import threading class StrLengthThread(threading.Thread): total_str_length = 0 ''' constructor for class ''' def __init__(self, word): threading.Thread.__init__(self) if type(word) is not str: raise Exception("word is not a string") self.word = word ''' add the le...
65cd4237603a37d034ff0e68bc6fc378176b3c16
berkcan98/Python_ogrenme
/format_kullanimi.py
1,446
3.578125
4
dilekçe = """ tarih: {} T.C. {} ÜNİVERSİTESİ {} Fakültesi Dekanlığına Fakülteniz {} Bölümü {} numaralı öğrencisiyim. Ekte sunduğum belgede belirtilen mazeretim gereğince {} Eğitim-Öğretim Yılı {}. yarıyılında öğrenime ara izni (kayıt dondurma) istiyorum. Bil...
f80157c1eabc9e5c6b862ac6d36cc7241be68467
iCodeIN/competitive-programming-5
/leetcode/Bit-Manipulation/convert-a-number-to-hexadecimal.py
1,373
3.5
4
class Solution(object): def toHex(self, num): """ https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/ :type num: int :rtype: str """ st = "" base16 = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] if num > 0: ...
fd73e760abaccc6beb1889b6b5aa4a5f9c451f07
Talha215/SideScrollingGame
/Goal.py
675
3.53125
4
import pygame import Game from Animation import * class Goal(pygame.sprite.Sprite): """ Platform the user can jump on """ def __init__(self, width, height): """ Platform constructor. Assumes constructed with user passing in an array of 5 numbers like what's defined at the top of this ...
dd84e39a7b3f1e453c5af9566b2d4f2c6f155249
KingKerr/Interview-Prep
/Stacks_And_Queues/maxOfSubarrays.py
666
4.03125
4
""" Given an array of integers and a number k, where 1 <= k <= array length, compute the maximum values of each subarray of length k An example is: [10, 5, 2, 7, 8, 7] and k = 3 This will return [10, 7, 8, 8] """ from collections import deque def max_of_subarrays(lst, k): q = deque() for i in range(k): ...
fea11f166857be327b4a9919c671bf2d42c70d80
leeseoyoung98/javavara-assignment
/2nd week/python_if_elif.py
473
4.15625
4
my_name="이서영" print(f"my name is {my_name}.") #{}안에서 연산도 가능. ex) my_name.upper() #리스트 안에 리스트 list_in_list=[1, 2, [3, 4, 5], 6] print(len(list_in_list)) list_in_list[2][0] #index=2에서의 0번째 (chained index) #조건문 name = "이서영" if name == "이서영": print("백현을 JONNA 사랑한다.") else: print("오늘부로 입덕한다.") #ternary operator n...
0a01197eb3e8b0c7bd36a440c0be6dfdbc55b98c
brofistercoop/python-basics
/add.py
89
3.53125
4
i = int(input("haey enter any no : ")) j = int(input("haey enter any no : ")) print(i+j)
b41b085bfb167c3f6f17fe691907cbad9e367369
esdomar/my_common_functions
/open_find_write.py
1,619
3.734375
4
def open_csv(path, delimiter = '\t', skip = 1, columns = []): import csv ''' * Requires module numpy as np to work Open only float data the column variable is list containing the number of columns that want to be imported for importing all the columns, no argument required '...
b85cb2cc1dbea4f496e3ceeed02383f2fcc5c8d2
xastrobyte/FellowHashbrown-API
/api_methods/logic/variable.py
2,710
4.5625
5
class Variable: """A Logic Variable contains information that pertains to the letter of a value and whether or not there is a NOT operator attached to it. :param variable: The letter or word for this Variable :param has_not: Whether or not this Variable has a NOT operator attached to it ...
0e8f955d84ba5f0bfd61738c5daf484618e84167
kotsky/programming-exercises
/Dynamic Programming/Longest String Chain.py
2,753
4.09375
4
''' Define the longest chain from the given strings in descending order, where each next string is made by removing one letter from the string before this chain. strings = ["abde", "abc", "abd", "abcde", "ade", "ae", "1abde", "abcdef"] print(longestStringChain(strings)) => ['abcdef', 'abcde', 'abde', 'ade', 'ae'] 1....
857828fb95eec5b4fff59ddaa5cabd4f20f1a279
rreed33/choamodel
/cluster_viz.py
1,310
3.5
4
#this file will reduce the dataset into 2 dimensions and represent a visual import dataprocessing import argparse from sklearn.manifold import TSNE import matplotlib.pyplot as plt def main(args): df = dataprocessing.main() reduce_data = TSNE(n_components = 2).fit_transform(df) plt.plot(reduce_data) plt.savefig('...
a1bcffdcd18bdf3dfae238d9086ee242a771f01e
IrvingQuirozV/Ing.Conocimiento
/Exercises_pyhton/ejericicio_39.py
413
4.21875
4
""" ----------------Ejercicio 39-------------- Dados diez enteros, imprimir solo el mayor. No supones que los numeros estan enlistados en los datos en un orden especial. Puede suponerse que no hay dos numero iguales. """ print ("----Numero mayor--------") print ("") print ("Lista: ") num = (1,2,3,4,5,6,7,8,9,10) print(...
34a63df3fe2496abc4dfa1588d53810df78918ee
mube1/Cryptool
/Railfence Encryption Better.py
1,142
4
4
Plaintext="abcdefghijkl" # the data used can be programmed to be from the user keye=4 # the key offset=1 # the offset offset=offset%(2*keye-1) # offset at most can be twice the key minus 1 ch='*' for i in range(33,47): if Plaintext.find(ch): break ch=chr(i) Plaintext=ch*offset+Plaintext # populatin...
e57e128fb5599eff250d59b8f66f9fd56d3540a8
heavylgf/liugf.python
/spark-study-python/python-people-intelligent/lesson1/demo3_input_print.py
1,753
4.1875
4
''' input print 知识点: 1.通过input获取用户输入内容 2.print直接输出字符串内容 ''' # card_id = input("请输入卡号:") # pwd = input("请输入密码:") # print(card_id) # print(type(card_id)) # print(pwd) #1.print打印字符串 # print("hello python") #2.print打印变量值 # name = "zhangsan" # print(name) #3.print格式化输出 #使用格式化占位符格式化输出 # print("您输入的卡号是:%s"%card_...
104d2c6989e503438ed1215b1857758706eafef4
hieugomeister/ASU
/CST100/Week6/rectangle.py
4,620
4.6875
5
""" Author: Hieu Pham ID: 0953-827 Section: 82909 Date: 11/28/2014 Create a class named 'Rectangle' with the following attributes and methods sample run for each method included): 1) Each instance should have an x, y, width, and height attributes. 2) You should be able to pass the attributes when creating the rectangl...
b2205c70f870a7cb84280051ae9a56f292766f3a
IrvingArielEscamilla/PythonExercises
/AnalisisE2.py
134
3.578125
4
def esPar(numero): return (numero % 2 == 0) def run (): numero = int(input('Dame numero :')) print(esPar(numero)) run()
3375e04540f87a7593bedebccd9e6635e74e6bab
ahmedyoko/python-course-Elzero
/templates/numpy_arithmetic6.py
1,405
3.703125
4
#................................................ # numpy => Arithmetic operation : #................................................ # Addition # Substraction # Multiplication # Dividation #....................... # min # max # sum # ravel => return flattened array 1 dimension with the same type #........................
77fdcf1dbfc3a529545552210737968c88bf404b
dunitian/BaseCode
/python/1.POP/1.base/01.helloworld.py
970
4.0625
4
'''三个单引号多行注释: print("Hello World!") print("Hello World!") print("Hello World!")''' """三个双引号多行注释: print("Hello World!") print("Hello World!") print("Hello World!")""" # 单行注释 输出 print("Hello World!") # 定义一个变量并输出 name = "小明" print(name) print("x" * 10) print("dnt.dkill.net/now", end='') print("带你走进中医经络") print("dnt.d...
33fb2a9d79da7df4ba1f83b4c99221157dc7d247
gauripatil20/loop
/AMSTRONG_ NUMBER.PY
247
4
4
# num=int(input("enter the number")) # sum=0 # b=num # while num>0: # sum=sum+(num%10)*(num%10)*(num%10) # print(sum) # num=num//10 # if sum==b: # print(b,"it is amstrong number") # else: # print(b,"it is not amstrong number")
9a8851e038e1eedbe41d2206ead0cf06bf87fbb2
wxyBUPT/leetCode.py
/math/Solution_423.py
1,152
3.609375
4
#coding=utf-8 __author__ = 'xiyuanbupt' # e-mail : xywbupt@gmail.com import collections ''' 423. Reconstruct Original Digits from English Add to List QuestionEditorial Solution My Submissions Total Accepted: 4945 Total Submissions: 11867 Difficulty: Medium Contributors: Admin Given a non-empty string containing an ...
44562237f71f80ec2ae1bae5fde215d98316581e
apdaza/universidad-ejercicios
/python/cartas.py
502
3.625
4
# -*- coding: utf-8 -*- from random import * def baraja(): return sample([(x, y) for x in [str(n) for n in range(2, 11)] + ['J', 'Q', 'K', 'A'] for y in ["picas", "corazones", "treboles", "picas"]],52) def jugar(mazo,jugador,casa): print "-------------------------------------" print mazo #print casa ...
fb9638094acc2a877d6b074f868f7c008f2ef347
moshtab/Python_Assignments
/pythonProject/JunitTesting_Programs/4MonthlyPayment.py
468
3.96875
4
''' @Author: Mohsin @Date: 2021-10-19 18:00:30 @Last Modified by: Mohsin @Last Modified time: 2021-10-19 18:00:30 @Title : Monthly Payment” ''' import math def monthlyPayment(P,Y,R): n = 12 * Y r = R / 1200 payment = (P * r) / (1 - math.pow((1 + r), -n)) print("Monthly Payment is :",payment) P=int(input...
a9039fe94658944f5d89ec4ae8f5057ea843ee25
Aravind-sk3/sde2
/uniquematrix.py
298
3.703125
4
"""Given a binary matrix, print all unique rows of the given matrix""" l=[] a=int(input()) for i in range(a): r=list(map(str,input().split())) l.extend([r]) d=[] s=" " for i in range(len(l)): m=l[i] k=s.join(l[i]) if k not in d: print(l[i]) d.append(k)
0782c9ac6094db7adb767e1f5a6ce1ab57d152e7
dewanshrawat15/Algorithmic-Toolbox
/week3_greedy_algorithms/5_collecting_signatures/covering_segments.py
729
4
4
# Uses python3 from collections import namedtuple Segment = namedtuple('Segment', 'start end') def optimal_points(segments): points = [] segments = sorted(segments, key=lambda segment: segment.end) current = segments[0].end points.append(current) for s in segments: if ((current < s.start) ...
3fde5a8d9a98c5c938bce08d8f9e682b5b495c9d
JoyiS/Leetcode
/crackfun/214. Shortest Palindrome.py
942
4.25
4
''' Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa". Given "abcd", return "dcbabcd". ''' class Solution: def shortestPalin...
4e2b25597aa836dc62bdc501c82e37fa5d4ce0f9
Gusta-froes/Agent-based-modelling-UNICAMP
/Functions.py
8,221
3.625
4
from Classes import * import numpy as np import matplotlib.pyplot as plt import random import matplotlib.animation as animation def create_classes(num_class, unicamp_dict): classes = {} for i in num_class: classes[i] = [] for j in range(num_class[i]): # day = -1 # hour = -1 aux = 0 op...
798ca8f00ae30d76fc8162a0a546c6af58607441
jackjyq/COMP9021_Python
/quiz05/remove_zero_value.py
509
4.34375
4
def remove_zero_value(dict_with_zero_value): """remove_zero_value Remove keys from dictionary which value is zero in order to fit output format. """ dict_without_zero_value = dict(dict_with_zero_value) for key in dict_with_zero_value: if dict_without_zero_value[key] == 0: del dict_wi...
c02b702ea7fdacd56e3217c2127403caebb58175
srinivasskc/Python-Programming-Learning
/Python150Challenges/ForLoops/35-44 Challenges/Challenge36.py
248
4.34375
4
#036 Alter program 035 so that it will ask the user to enter their name and a number and then display their name that number of times. name = input("Enter the name: ") num = int(input("Enter the number: ")) for i in range(num): print(name)
a047f5f0d96ac05208d0c34df7f2c8e39fe35463
stevenbaur/My_Py_Cookbook
/Raspberry/GPIO/LED Blink.py
984
3.890625
4
import RPi.GPIO as GPIO #import the RPi.GPIO import time.sleep #import sleep-function to wait x seconds GPIO.setmode(GPIO.BCM) #configure GPIO as BCM GPIO.setup(4, GPIO.OUT) #Set BCM Pin 4 as Output-Pin (3.3V) limit = int(input("How often blink the LED? ")) seconds = int(input("H...
b214f9c09be0e2bf6a3dd5d71e763b7b148c648c
cx1964/cx1964ReposPGPpublic
/check_os_py3.py
439
3.59375
4
# file: check_os_pr3.py # functie: check OS waarop het python3 script draait import platform system = platform.system().lower() # Bepaal OS is_windows = system == 'windows' is_linux = system == 'linux' is_mac = system == 'darwin' # Doe iets afhankelijk van het OS if is_linux: print("Het draait op Linux") elif is...
a978e72b2bfad3a9b1f78cedf189bc415474857e
pete-watters/real-python
/handleExceptions.py
147
3.875
4
while True: userInput = input("Please enter an integer:") try: integerValue = int(userInput) break except ValueError: print("Error ahoy")
d821aac253bdb901ce158241fd795b770e5af0c7
iannolon/Projects
/ticTacToeGraphics.py
19,319
3.5
4
#IanNolon #4/4/18 #ticTacToeGraphics.py #import graphics and random integer, needed for the program from ggame import * from random import randint #cell size constant, easily changeable for different sized games CELL_SIZE = 175 #works best with 200 or 175 #checks to see if a square is empty and returns True or False...
6d65ace96e7bb0dd569718aa2c0887bf9891bf2c
Jai-karthik/Python
/minesweeper/placingMines.py
2,264
3.53125
4
import random x_mine = [] y_mine = [] for _ in range(10): x_mine.append(random.randint(0,9)) y_mine.append(random.randint(0,9)) #Random placing mines in the cell mines_matrix = [[0]*10 for y in range(10)] mines_index = [] for i in range(10): mines_matrix[x_mine[i]][y_mine[i]] = 1 mines_index.append([...
90f73b08a64b0c1cd8ddccf6c64a7ba2efe60866
cyj407/Machine-Learning-labs
/HW2/ML_HW2_2_309553009.py
1,173
3.625
4
from math import factorial def C(m, n): return float(factorial(m) / (factorial(m-n) * factorial(n))) ## input file file_n = str((input("file path: ") or 'testfile.txt')) cases = [] with open(file_n) as f: for l in f: c = l.strip() cases.append(c) f.close() ## input beta prior prior_a = int((i...
784da96870f31865623b2d156ec46c86566bc89e
JiahangGu/leetcode
/DFS+BFS/src/20-9-13-79-word-search.py
1,175
3.625
4
#!/usr/bin/env python # encoding: utf-8 # @Time:2020/9/14 9:21 # @Author:JiahangGu from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: """ dfs搜索即可,设定一个flag数组标记是否使用过。 :param board: :param word: :return: """ def ...
8b476d042846964a135f6d10bc9ca80e0f601347
sachinrohaj-29/geeksforgeekspython
/mustdocodingquestions/array/SubArrayWithGivenSum.py
1,135
3.6875
4
class SubArrayWithGivenSum: def work(self): total_test = int(input()) while total_test > 0 : size_sum = [int(entry) for entry in input().strip().split()] array_size = size_sum[0] expected_sum = size_sum[1] given_array = [int(entry) for entry in inpu...
2c201c18638d73f86051a9937ebbcb72d6fd70fd
limapedro2002/PEOO_Python
/Lista_01/Clara Lima/LIST_1_QUESTAO_2.py
557
3.5625
4
print('\n') print('='*50) print(" LISTA 1 QUESTÃO 2" ) print('='*50) #Receber 10 numeros #Calcular a soma dos numeros #imprimir a soma dos numeros pares #imprimir a soma dos numeros impares (SERIAM OS PRIMOS) primos = [] impares = [] a = 0 for i in range(1,11): num = int(input("Digite %iº número: "...
5ce5534c7e87be4f4a7e9ef2f6172f2ace438356
vsamanvita/APS-2020
/Sum_and_XOR.py
295
3.5
4
# Given a number n this codelet retuns the count where n+x=n^x where xE[0,n] def sumXor(n): if n==0: return 1 count=0 l=int((math.log(n) / math.log(2)) + 1) n=n^((1<<l)-1) # print(n,l) while n: n=n&(n-1) count+=1 return 2**count
cd86ba691ddbe7aca951e2d98763c649f91ae9f7
daydaychallenge/leetcode-python
/01451/test_rearrange_words_in_a_sentence.py
397
3.53125
4
import unittest from rearrange_words_in_a_sentence import Solution class TestSolution(unittest.TestCase): def test_Calculate_Solution(self): sol = Solution() self.assertEqual("Is cool leetcode", sol.arrangeWords("Leetcode is cool")) self.assertEqual("On and keep calm code", sol.arrangeWord...
fa021df86d0004ef4bfa718508c1d1c7096d6e9f
rescenic/Softuni-Python-v2
/python-advanced/ZZ - Exam - Prep/19 August 2020/03.py
855
3.9375
4
def numbers_searching(*args): min_num = min(args) max_num = max(args) unique_nums = set() duplicates = set() missing_num = None for num in range(min_num, max_num): if num not in args: missing_num = num for num in args: if num in unique_nums: duplicat...
e6207eabb92e31d5a0f23d0870a49710f4ed7d0c
mystm/stmpython
/pa.py
667
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- goods = [{"name":"芯片","price":200},{"name":"耳机","price":40},{"name":"充电器","price":120},{"name":"手机","price":200}] i = 0 while i< len(goods): print(i,goods[i]["name"]) i += 1 yourBlanceS = input("请输入您的余额:") yourBlance = int(yourBlanceS) while yourBlance >0: p...
73db0ffeea547cb81e56824a2c590fcfe75cf331
kargulke/Kattis
/Python/Finished Problems/simon.py
163
3.859375
4
loop = int(raw_input()) for x in range(loop): string = raw_input() if(len(string) > 11): if(string[:11] == "simon says"): print string[11:]
518a92c93798619ba57b49ac1d5019c5af8e9ca4
uschwell/DI_Bootcamp
/Week4 (18.7-22.7)/Day4 (21.7)/Daily Challenge/Daily_Challenge.py
1,146
3.5
4
from typing import final # def decode_clean(to_clean): # to_clean.replace(" ", "") # return to_clean def decode_matrix(encoded): rows=len(encoded) row_sentence='' final='' #iterate through for cols in range(len(encoded[0])): for r in range(rows): if(str(encoded[r]...
af3485098b6635ce728c0008d137d4c063f4c52f
anthony-correia/HEA
/HEA/tools/df_into_hist.py
8,307
3.65625
4
""" Functions to turn a dataframe into a histogram """ from pandas import DataFrame, Series from HEA.tools.da import el_to_list from HEA.tools.assertion import is_list_tuple from HEA.tools.dist import ( get_count_err, get_bin_width ) import numpy as np def _redefine_low_high(low, high, data): """ if low...
ced2659b111daaa5a87f51a5e344986aebbb4655
rahkeemg/neural-network-from-scratch
/run.py
601
3.703125
4
import numpy as np import neural_network as nn import plotly.express as px np.random.seed(42) # Set the inputs and weights using numpy random function inputs = np.random.uniform(low=-10, high=10, size=4) weights = np.random.uniform(low=-10, high=10, size=(3,4)) biases = np.random.randint( 0, 5, size=3) print(f'Input...
a6bfcb13b36f72b49c9b2cd5ee93cba79dec6d9c
pfan8/LeetCode
/字符串/[LeetCode 97] Interleaving String/bp.py
714
3.5625
4
class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: l1 = len(s1) l2 = len(s2) if l1 + l2 != len(s3): return False dp = [ False for _ in range(l2+1)] for i in range(l1+1): for j in range(l2+1): if i == 0 and j == 0...
7e3292748e693a6503f0b546bafff78840a7202a
boonchu/python3lab
/coursera.org/python2/memory.py
11,562
4.1875
4
# implementation of card game - Memory # Coursera # An Introduction to Interactive Programming in Python (Part 2) # Boonchu Ngampairoijpibul - 07/18/2015 2:38 PM PDT # change log: # * moves all tracking metric/counts to mouse operation # * clean states after reset import simplegui import random # Panel size HEIGHT ...
ff65e8246b316e8186f61d7bd07bcf200fa1fb81
bobhelander/code-challenge
/python/hamming/iteration.py
421
3.8125
4
def compute(value1, value2): # Validation if len(value1) != len(value2): if len(value1) > len(value2): raise ValueError("Value1 is longer") raise ValueError("value2 is longer") # Use built-ins to build an array of zero and ones. Sum() that array return sum(map(compute_ele...
9d5778d81ef1cdd799e0cb78ce6e975540f8a100
zeeshanhanif/ssuet-python
/16April2017/DemoDictionary/DemoDictionary1.py
193
3.59375
4
myDictionary = {"name":"Adnan", "age":45,"email":"adnan@gmail.com"} print(myDictionary["age"]) print(myDictionary["email"]) myDictionary["age"] = 50; print(myDictionary); print(myDictionary["age"]);
d1327f9c8f08dfe5bd2fbcdb0769d73effdcf896
olcayCansu/AirBNBPricePrediction
/Source/Functions/Utilities.py
722
3.53125
4
from sklearn.datasets import make_classification from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.model_selection import train_test_split def TestAnova(trainData): #generate dataset #define feature selection print(trainData) fs = SelectKBest(...
dcf790bbbe1083cef2821c50b0ff86c35d76c4b4
Chetchita641/QT_Tutorials
/advancedpyqt5/examples/graphics/hittest.py
2,246
3.640625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' ZetCode Advanced PyQt5 tutorial In this example, we we work with a thread. We click on the area of the rectangle and the rectangle starts to fade away. Author: Jan Bodnar Website: zetcode.com Last edited: August 2017 ''' from PyQt5.QtWidgets import QWidget, QApplic...
2d2c11dcf319f29917077f122407976049893661
oms1994/Artificial-Intellegence
/priority_queue.py
794
3.625
4
class PriorityQueue: pivot_value = {} value_key = {} keys=[] #priority Queue Code def get(self): key = self.keys[0] value = self.pivot_value[key] del self.pivot_value[key] del self.value_key[value] self.keys = self.keys[1:] return value...
981cd59d5b6c1bcc2d63ea14e1532b7e5cb79dd8
neozl24/leecode
/TwoSum.py
1,949
3.75
4
#Given an array of integers, find two numbers such that they add up to a specific target number. #The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based...
57307eb0112c989051f9ff4b0e21ddce3978d4b2
rguerreroayon/EmSys_Python
/Asignacion9/bisiestos2.py
676
3.640625
4
def esBisiesto(ano): return ano%4 == 0 and ano%100 != 0 or ano%400 == 0 def leeAnhos(listaBisiestos): anoInicial = listaBisiestos[0] anoFinal = listaBisiestos[len(listaBisiestos) - 1] anos = [anoInicial,anoFinal] return tuple(anos) def listaBisiestos(ano1,ano2): anos = [ano1] while(ano1 ...
6d9637b1f0d4bd474efe051a5deb20b7aab9271e
MarkHofstetter/pythonkurs201709
/002-add.py
309
3.671875
4
''' + das programm soll 2 usereingaben (zahlen) entgegennehmen + und die beiden Zahlen sollen addiert werde ''' ''' + ausgabe des Resultats ''' summand1 = int(input('bitte eine Zahl eingeben: ')) summand2 = int(input('bitte noch eine Zahl eingeben: ')) summe = summand1 + summand2 print(summe)
45efffa34eacbe7d76cfd4d6292eee3d988238f6
RijuDasgupta9116/LintCode
/Container With Most Water.py
725
3.765625
4
""" Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Example Given...
21d9ecdff050c3da1d017445d314a4c14041917e
michaelswitzer/projecteuler
/problem001.py
463
4.09375
4
#If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. from common_funcs import answer def multiples_below(below, m1, m2): total = 0 for x in range(0,below): if(x % m...
01f0ba4fc0c45ca825a6e57835a52f365c956ce9
TrTai/ClassProjectsPython
/python/StateTax1.py
973
4.0625
4
#Tax Calculation #Treye Chaney #9/30/2016 release #calculating total payment after adding set tax for state and county #Ask for input from user for amount of purchase purchase = float(input('Input amount of purchase')) #multiplying purchase amount by State Tax to find amount paid in State Taxes and assigning to variabl...
7038e65fabcab0e2054ff2e84cda0110046417f8
michaelzh17/think_python
/return_f.py
227
4.0625
4
#!/usr/bin/env python3 # test if in a condition the function goes to end without a return statement def test(x): if x > 0: return x if x < 0: return -x print(test(9)) print(test(-6)) print(test(0))
d0b3abdff986d82d80a3b92b9abe1cb298040fbe
Cmajor98/Algorithm
/BTH004/laboratory_assignments/bubblesort.py
771
4.15625
4
import random import time start =time.clock() def bubbleSort(bubbleList): n=len(bubbleList) while n>0: for i in range(n-1): if bubbleList[i] > bubbleList[i+1]: temp=bubbleList[i+1] bubbleList[i+1]=bubbleList[i] bubbleList[i]=temp n -= 1...
2961ba999bb9f0d4d42e1053211ef4f456338aef
lihaofei/Learn_Python
/day2/string_demo.py
1,903
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author:Bill Li name = "my \t name is {name} and i am {year} old" print(name.capitalize()) print(name.count('a')) #计算a的个数 print(name.center(50,"-")) # 一共打印50个字符,不够的话则通过-补全 print(name.endswith("ld")) #判断字符以ld结尾 print(name.expandtabs(tabsize=30)) #tab按键转换成30个空格 \t print(nam...
051741f3f03b089367ad671a46c068d1fc82ca49
mycho2003/TIY
/5/5-7.py
374
3.984375
4
favorite_fruits = ["tomato", "mango", "pineapple"] if "banana" in favorite_fruits: print("You like bananas.") if "apple" in favorite_fruits: print("You like apples.") if "pineapple" in favorite_fruits: print("You like pineapples.") if "watermelon" in favorite_fruits: print("You like watermelon.") if "m...
76b1a60f5ca602178db1cadf9f9d1627b881a6c6
nisha25choudhary/FSDP_2019
/uni.py
1,172
4
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 13 10:18:09 2019 @author: Lenovo """ import sqlite3 from pandas import DataFrame conn = sqlite3.connect ( 'university.db' ) c = conn.cursor() c.execute ("""CREATE TABLE students( name TEXT, age INTEGER, rollno INTEGER, branch TE...
acf0b00faaba8d61c61db250e9928a829fbb4c43
Dmitry-Igoshin/SkillFactory
/Unit_0/set.py
315
3.921875
4
a = input("Введите первую строку: ") b = input("Введите вторую строку: ") a_set, b_set = set(a), set(b) # используем множественное присваивание a_and_b = a_set.symmetric_difference(b_set) print(a_and_b) print(len(a_set)) print(len(b_set))
662019ef2e91f88c53afd4587929c3084ace0898
zittoooo/Algorithm
/programmers/level1/수박수박수박.py
248
3.75
4
def solution(n): answer = '' for i in range(n): if i % 2 == 0: answer += '수' else: answer += '박' return answer ##두번째 풀이 # def solution(n): # return '수박'*(n//2) + '수'*(n%2)
6503286344b5dd3717bfb8bf730ced64b1bbc42d
dfrc-korea/carpe
/modules/android_basic_apps/android_contacts.py
1,880
3.59375
4
# -*- coding: utf-8 -*- """This file contains a parser for the Android contacts2 database. Android accounts are stored in SQLite database files named contacts2.db. """ import os import datetime import sqlite3 from modules.android_basic_apps import logger query = \ ''' SELECT c.display_name as name, ...
0dad00b70c3999cacbe0992a652ad380aaf564d1
Mvianna10/Sheep-sim
/sheep.py
3,843
3.671875
4
from colors import WHITE, YELLOW from random import randrange, random, uniform, randint from math import ceil import copy class Sheep: def __init__(self, x, y, sheep_color = WHITE, speed = 4, energy = 20, reproduction_energy = 40): self.x = x self.y = y self.size = 8 self.speed = speed self.energy = energ...
340e1b26b7e5e646bb430aa4ee412501159fc1bd
JorgeAc25/Python--SQL--TKInter--POO--OpenCV
/Python/Ejemplo 01 encapsulamiento.py
965
3.796875
4
class Pelicula: # Constructor de la clase def __init__(self, titulo, duracion, lanzamiento): self.titulo = titulo # Creacion de atributos desde el metodo self.duracion = duracion self.lanzamiento = lanzamiento print("Se creo la pelicula:", self.titulo) def __str__(self): ...
25bbd733b2ceff108f85a01d8aaf1f99800a409b
jjzhang166/Python-OOP-High
/HIGH/进程线程/线程/5.线程间通信.py
619
3.671875
4
''' 线程间的通信采用事件,event,只要控制了事件对象就能控制线程什么时候执行 ''' import threading,os,time def func(): event = threading.Event() #这个地方一般都一定要加括号,实例化对象,类需要加括号 def run(): for i in range(1000): event.wait() event.clear() print('you need python') threading.Thread(target=run,).start() ...
3109b5a192714a4e6b2e08bd179cb6a701bf7b10
asymmetry/leetcode
/0060_permutation_sequence/solution_1.py
730
3.703125
4
#!/usr/bin/env python3 class Solution: def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ if n == 1: return '1' if k == 1 else None facts = [1] for i in range(2, n): facts.append(facts[-1] * i) ...
8e0ae036d95f3970cced1df859e6ec3e234728fb
svinyard/algoreithms
/RandomSearch.py
683
3.578125
4
#!/usr/bin/python import random def objectiveFn ( vec ): return sum( [x*x for x in vec] ) def randomVec( minmax ): return [(kv[0] + ((kv[1] - kv[0]) * random.random())) for i,kv in enumerate( minmax )]; def search( searchSpace, maxIter ): best = None for i in range( maxIter ): candidate = {} candida...
536933229e4cdfdf59a30d880c4fcbc17a3b38bb
Muneerah1612/WebScraper
/analyse.py
387
3.578125
4
from validator_collection import checkers class CheckUrl: @classmethod def ValidUrl(cls): ''' This method checks if the user input is a valid url ''' web_valid = input('Enter a website to analyse: ') checkers.is_url(web_valid) if checkers.is_url(web_valid): ret...
d66320d0f52fcb90b88a30576d49c0284dba6e7d
leezzx/Baekjun-Study-Python
/이코테3(DFS & BFS).py
7,917
4
4
# 스텍 자료구조 : 먼저 들어온 데이터가 나중에 나가는 형식의 자료구조, 입구와 출구가 동일한 형태로 스텍을 시각화(프링글스 통) stack = [] stack.append(5) # [5] stack.append(2) # [5 2] stack.append(3) # [5 2 3] stack.append(7) # [5 2 3 7] stack.pop() # [5 2 3] stack.append(1) # [5 2 3 1] stack.append(4) # [5 2 3 1 4] stack.pop() # [5 2 3 1] print(stack[::-1]...
29465e6865c436bc1d2323ae2ff50a2f6b00ee51
abhilesh/Rosalind_codes
/DNA_motifs.py
403
4.09375
4
# Given: A DNA sequence and a smaller DNA motif # Return: All locations of the motif as a subsequence of the DNA sequence seq = raw_input("Enter the DNA sequence: ") motif = raw_input("Enter the DNA motif: ") index = 0 while index < len(seq): index = seq.find(motif, index) if index == -1: ...
f600105ef61f53dc50707144a32d25a78c1032b3
spaceturnip/potpourri
/python/checksum.py
1,517
3.9375
4
import sys def calculateTotal(num): total = 0 num = [int(i) for i in list(num)] #split out each digit and make sure its an int num.reverse() # sorting places are always the same if you start from the end for index, val in enumerate(num): if index % 2 == 0: # we want to double every odd d...
45bd63db49335a4e250a65fa1eb498d048ac0ed2
jgarciakw/virtualizacion
/ejemplos/ejemplos/class.py
424
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #____________developed by paco andres____________________ class Circle(object): PI = 3.14 def __init__(self, radius): self.radius = radius def perimeter(self): return 2 * self.PI * self.radius def f1(a,b=5,*args,**kargs): print a print (k...
5488812b055675cf33139aa67cb6a1314c76bd60
heverthon/IFPA-LP2-PYTHON
/atv1.py
553
3.96875
4
destino = input('Onde você deseja ir?') dias= input("Quantos dias") money = int( input("Quanto você tem?")) interior= "Itupiranga" capital ="Brasilia" top="Paris" if money < 100: print("Vixe! com esse dinheiro não dá pra chegar em/na {}, no máximo você chega em {} e talvez nem dê pra voltar ".format(dest...