blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
91d0e99762217d718ba256b5883c3d01d27c34a8
domspad/hackerrank
/apple_disambiguation/which_apple.py
1,613
4.3125
4
#!/usr/bin/env python """ (Basic explanation) """ def whichApple(text) : """ Predicts whether text refers to apple - the fruit or Apple - the company. Right now only based on last appearance of word "apple" in the text Requires: 'apple' to appear in text (with or without capitals) Returns: 'fruit' or 'computer-c...
478dbb17f67b70442813c40e7029b333c83c9bdb
Ichigo-lab/PythonBegins
/Classes/inheritence.py
553
4.09375
4
class Animal: def __init__(self): self.age = 1 def eat(self): print("Eat") # Animal: Parent, Base # Mammal: Child, SubClass class Mammal(Animal): def walk(self): print("Walk") class Fish: def swim(self): print("Swim") tiger = Mammal() tiger.eat() print(tiger.age) ...
bf4e165084aa33a6a0881493eab85e5d5829017f
ajmalbinnizam/python-code
/crossroadspython/ex.py
145
3.921875
4
print('It\'s a bad string!') a=int(input("your number")) b=input() c=10 sum1=a+int(b) print("result is" , sum1) print("result is "+str(sum1))
76bbec46522bf4cddbb36e602043ca493f11f4e3
FiodorGrecu/Exercises
/data_structures/stacks_and_queues/1_stack_bool/solution/solution.py
604
3.75
4
class ListNode: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.head_node = None def push(self, value): new_head = ListNode(value) new_head.next = self.head_node self.head_node = new_head def pop(self): ...
0966ce04a2dd6863bbbab5fea947e1aa420f3b0b
shimamchan/NLP100knock
/answer_10-19/answer_19.py
353
3.5
4
from itertools import groupby file = 'hightemp.txt' lines = open(file).readlines() prefs = [line.split('\t')[0] for line in lines] prefs.sort() result = [(pref, len(list(group))) for pref, group in groupby(prefs)] result.sort(key=lambda pref: pref[1], reverse=True) for pref in result: print('{pref}:{count}'.for...
6d229950faa0315d5cebf77c46985c907a443cf0
ricardollopis9/module3
/uniqueNumbers.py
147
4.03125
4
mylist = [10,2,3,4,4,4,3,3,3,56,7] newlist = [] for i in mylist: if i not in newlist: newlist.append(i) print(mylist) print(newlist)
68077611e48173cf76a8152b4bb9d8a221ff6e84
marianfx/python-labs
/python-samples/11_threading.py
2,550
3.765625
4
# use thread / _thread for old, low-lvl methods # use threading for class-based import _thread, time # LOCKS lock1 = _thread.allocate_lock() def MyThreadedFunction(sleeptime, name, nr): global lock1 with lock1: # calls lock.acquire and lock.finish print(name, " - ", str(nr)) time.sleep(sleeptime) ...
a18248f74410d1a1556751866a7caf5053427295
PauloVilarinho/algoritmos
/atividades_aleatorias/ProblemaVacina.py
751
4.03125
4
idade = int(input("qual é a idade do seu filho? ")) sexo = input("qual o sexo do seu filho? (M ou H)") if idade>15 : print("seu filho nao tomará nenhuma vacina.") elif sexo == "H" : if idade<11 : print("seu filho tomará somente a vacina da gripe") elif idade<=12 : print("seu filho tomará a vacina da gripe e do ...
978e7da2032bf46981944e09eeeb67b3b1416d93
algrs/polliwog
/polliwog/polyline/inflection_points.py
1,910
3.796875
4
import numpy as np import vg def inflection_points(points, axis, span): """ Find the list of vertices that preceed inflection points in a curve. The curve is differentiated with respect to the coordinate system defined by axis and span. Interestingly, `lambda x: 2*x + 1` should have no inflection poi...
36c659996a255afb0dad2af0923e59104d89fe90
MohitMehndiratta/Python-Assignments
/Assignment-1.py
3,063
3.84375
4
import tkinter as tk from tkinter import messagebox window = tk.Tk() window.title('Python Assignment-1 Solution') # question-1 def assignment_ques_1(): number_div_by7_not_div_by5 = [int(i) for i in range(2000, 3201) if int(i) % 7 == 0 and i % 5 != 0] sub_window = tk.Toplevel(window) sub_window.title('Q-1...
21a01047572d5cc5fdb91899ad8810484acfdde3
Charamba/Cross-Ratio-Arrays-Shape-Descriptor
/src/circles2.py
816
3.5
4
""" ============================ Circles, Wedges and Polygons ============================ """ import numpy as np import matplotlib from matplotlib.patches import Circle, Wedge, Polygon from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt fig, ax = plt.subplots() resolution = 50 # the...
bc960fd77abe3476cd9553adde41f0e88866ca1a
Just1bridou/BachelorDIM-Lectures-Algorithms-2020
/assignements/S1_algotools.py
3,422
3.703125
4
import numpy as np import random tab = [1,9,3,4,5,6,7,8,2] np_tab = np.zeros((200,200)) np_tab[70:90,45:55] = np.ones((20,10)) def average_above_zero(tab:int): """ This function calculate the average of list tab Parameters : tab: the list Returns : return the average of list """ ...
75ff28301fb23957fde062d31c2e169eb5ce4151
eldr4d/project773
/src/util/tweet_cleaner.py
2,151
3.875
4
""" Removes special words from tweets and converts to lower case """ import re class TweetCleaner: EXCLUDE = "schiz" #regex to exclude tweets URL = "__url__" USER = "__user__" HASHTAG = "__tag__" NUMBER = "__num__" SPECIAL = [URL, USER, HASHTAG, NUMBER] @staticmethod def clean_whitespa...
0f07f58b1fce64ab70e42e9304bcf4f40c0a82e2
malmgren80/python-experiments
/timeconvert.py
233
3.765625
4
#!/usr/bin/python import sys def TimeConvert(num): hours = num / 60 print hours minutes = num - (hours * 60) print minutes output = str(hours) + ':' + str(minutes) print output return output TimeConvert(int(sys.argv[1]))
5526e88f85604e1e38c7b0dad238410aaf848210
zhousiyuan12138/compuational_physics_N2015301020051
/Exercise 07/代码_1.py
6,128
3.90625
4
```python from numpy import * import matplotlib.pyplot as plt #class:LORENZ solves for Lorenz model #where: # r : driving dt: time step # time :total time # sigma, b : other parameter class LORENZ(object): def __init__(self,_r=25,_dt=0.001,_time=50,_sigma=10,_b=10/3): self.t...
37af56c42e681c153be4caff599662c6bd78afe4
rajatthosar/leetcode
/1385_dist_between_two_arrays.py
544
3.671875
4
from typing import List class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: if len(arr1) > len(arr2): arr1, arr2 = arr2, arr1 if d == 0 and arr1 != arr2[:len(arr1)]: return 0 count = 0 for val1 in arr1: ...
8b836e051cbafa0d21bace68c45197d1153ea4e0
garoegonzalez/MOOC_Coursera_Edx
/Coursera_Dat_Sci/assignment1/top_ten.py
1,499
3.640625
4
import sys import json def extract_tweets(tweet_file): '''Function which return a list of tweets given a raw tweet txt file. ''' tweets = [] for line in tweet_file.readlines(): try: tweet =json.loads(line) tweet_text=tweet[u'text'] tweets.ap...
9f71cd9c33bec00e562d66b02e764c7e67193e5a
dineshpazani/coding
/linkedlist.py
1,457
4.0625
4
#single linkedlist class Node: def __init__(self, data): self.data = data self.nextnode = None class LinkedList: def __init__(self): self.head = None def insert(self, data): if self.head is None: self.head = Node(data) else: node = self.head ...
8d52c6057548120c41217793d5bbc6123ff76ade
Sledis/Elementary-Finance
/HolidayLogic.py
970
3.859375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #This is a collection of functions that deal with determining if banks are open. import datetime #Collection of bankholidays UK2019=["01/01/2019","17/03/2019","19/04/2019","22/04/2019","06/05/2019","27/05/2019","12/07/2019","26/08/2019","25/12/2019","26/12/2019"] #The ...
333f7c9194145c96135603db50de31c45c023619
JiaquanYe/LeetCodeSolution
/LinkList/sword_deleteDuplication.py
799
3.734375
4
""" 删除链表中重复的结点 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5 """ class Node(): def __init__(self, data, next): self.data = data self.next = next def deleteDuplication(pHead): if pHead is None or pHead.next is None: return pHead first = Node...
5ed98bb3b1055904988ad36be22facf60fe3f501
rajeevj0909/FunFiles
/Subroutine(1).py
296
3.953125
4
#Subroutine that prints out this sentence 3 times def myFirstFunction(): for i in range(1,3): print('This is a subroutine') #Main Program, shows the start, end and the middle which is coded ontop/\ print('Start of main program') myFirstFunction() print('End of program')
e82338f0e63aa4d2213fa1ced0edc3843d4f4103
VictorRSantos/Python
/Python_Impacta_Treinamentos/Aula 13 - Banco de Dados/banco_dados.py
2,195
3.71875
4
#Banco de Dados import sqlite3 #Vamos criar uma variavel para armazenar a conexão com o banco de dados conn = sqlite3.connect("galeria.db") #Vamos criar um cursor, são interadores aonde permite navegar e maipular os registro do banco de dados cursor = conn.cursor() #Sempre vamos cada script dentro de uma f...
2b0cfe58561606d1a0cbff03164c0c1ac6f452de
AGiantSquid/advent_of_code
/python/2020/day_2/day_2.py
1,301
3.875
4
#!/usr/bin/env python3 ''' Solves Advent of Code problem for day 2. ''' from collections import Counter from typing import List from aoc_utils import get_aoc_data_for_challenge def password_checker_range(passwords: List[str]) -> int: '''Check if password contains a valid number of letters''' valid = 0 fo...
c5c66f2969c93fe22b3833f48eec1eba8c9b23df
jinseoo/DataSciPy
/src/파이썬코드(py)/Ch12/code_12_5_1.py
392
3.859375
4
# # 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) # 12.5 CSV에서 원하는 데이터를 뽑아 보자, 310쪽 # import csv f = open('d:/data/weather.csv') # CSV 파일을 열어서 f에 저장한다. data = csv.reader(f) # reader() 함수를 이용하여 읽는다. header = next(data) for row in data: print(row[3], end=',') f.close()
827e712e62f63635085a047c927ae6edacc20006
setr/cs429
/a2/score.py
5,030
3.828125
4
""" Assignment 2 """ import abc from collections import defaultdict import math import index def idf(term, index): """ Compute the inverse document frequency of a term according to the index. IDF(T) = log10(N / df_t), where N is the total number of documents in the index and df_t is the total number of d...
89628ba3c23ef7f07bc88d0af924dfc25459739d
crazypanda123/python_projects
/dailyCodingProblem/#2.py
572
4.15625
4
""" Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected ...
0f0b85328288accec998cbc84ec0db1b9335274a
ken0105/competitive-programming
/procon-archive/atcoder.jp/abc187/abc187_c/Main.py
447
3.546875
4
from itertools import combinations import re if __name__ == '__main__': n = int(input()) li = [] for i in range(n): li.append(input()) notmatch = [s.replace("!", "") for s in li if re.match('^\![a-z]+$',s)] notmatch = set(notmatch) match = [s for s in li if re.match('^[a-z]+$', s)] a...
40e2b013869c01fbc58b5bbe25bda3a93d61b731
junseok-0505/Algorithm
/이코테/구현/이코테 실습 2-8(답안지와 다름).py
219
3.53125
4
s = input() text = [] num = [] for i in s: try: a = int(i) num.append(a) except: text.append(i) result = sorted(text)+sorted(num) for j in result: print(j,end='')
e079698b7f1eef36098703786818199ced4f96e2
Igor122/uri
/figuras.py
269
3.515625
4
def mdc(dividendo, divisor): if (divisor == 0): return dividendo else: return mdc(divisor, dividendo % divisor) x = int(input()) for i in range(1, x + 1): f1 = input().split() a = int(f1[0]) b = int(f1[1]) print(mdc(a,b))
880ccf627cd3bda530732383a61575a02bc295c0
Jhanviparmar/Python-with-Django---Jhanvi-Parmar
/Day-02.py
2,651
4.21875
4
#Day-02 print("Day-02") #PYTHON COMMENTS print("Hello") print("------------------------------------------------") #print("World") '''This is multiline comment''' #VARIABLES IN PYTHON print("VARIABLES IN PYTHON") a = 10 b = 10.5 c = "aa" print("a = ",a,"type of a=",type(a)) print("b = ",b,"type of a="...
9bd5b4b6e8995fab00d21a4cec5283a2a8372643
JANMAY007/python_practice
/Python language practice/python sorting option/selection_sort.py
362
3.875
4
def selectionsort(nlist): for j in range(len(nlist)-1,0,-1): k=0 for i in range(1,j+1): if(nlist[i]>nlist[k]): k=i temp=nlist[j] nlist[j]=nlist[k] nlist[k]=temp return nlist nlist=input("enter elements: ").split() print("...
6d245e71e882566acb0646816421087c3c425db4
ryoman81/Leetcode-challenge
/LeetCode Pattern/3. Backtracking/79_med_word_search.py
4,165
4.125
4
''' Given an m x n gird of characters board and a string word, return true if 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. Note: There will be some...
ed073172feaed99868ed56cd291099d00ac37694
JensMunkHansen/cs231n
/assignment1/cs231n/classifiers/broadcast.py
4,603
3.703125
4
import numpy as np a = np.array([[1,1,1,1],[2,2,2,2]]) b = np.array([[1,2,3,4],[1,1,1,1],[1,2,1,9]]) np.linalg.norm(a[:, np.newaxis] - b, axis = 2) Here are the original input variables: A = np.array([[1,1,1,1],[2,2,2,2]]) B = np.array([[1,2,3,4],[1,1,1,1],[1,2,1,9]]) A # array([[1, 1, 1, 1], # [2, 2, 2, 2]...
16418da38feb86b4150f2b1ea45ab0bffb91843c
abdullahmamunv2/four-in-a-row
/py2.7/Game.py
11,240
3.515625
4
import random from Agent import * from MinimaxFIARAgent import CellValueTuple ############## author charlie ########### ################## animation ####################### import random, copy, sys, pygame from pygame.locals import * BOARDWIDTH = 7 # how many spaces wide the board is BOARDHEIGHT = 7 # ho...
42503ef88e539a8238c1532576b1c832feac7194
chakrapanianisetti/Lab2-1
/swap.py
163
3.96875
4
# swapping of two numbers #input a=int(input("Enter 1st number ")) b=int(input("Enter 2nd number ")) #logic temp=a a=b b=temp #output print(a,b)
b095bf02b8e52c276bfc7d11c01bb5c3eee7e72c
SriYUTHA/PSIT
/Re examination/HelloWorldComeBack.py
267
3.765625
4
"""HelloWorldComeBack""" def language(): """This code print Thai or English""" eng = 'abcdefghijklmnopqrstuvwxyz' txt = input() if txt[0].lower() in eng: print("Hello", txt + ".") else: print("สวัสดี", txt) language()
867402e8bb3ad76d026b7c69835fa09290a796b3
SaulyS01/Examen_01_FP
/EJ3/Python 03.py
1,125
3.921875
4
#definir datos de entrada edad = int(input("Ingrese su edad: \n")) sexo = str(input("Ingrese su sexo M/F: \n")) #proceso_datos de empresa if edad >= 70 and sexo == "M": # proceso_datos de salida print(f"A usted se le aplica el tipo C por tener {edad} años de edad") elif edad >= 70 and sexo == "F": # proceso...
6ecd58cb8dda42709e1560e1094d7fca1b4df72b
IamLam163/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_base.py
13,830
3.515625
4
#!/usr/bin/python3 """Unittest for Square class """ import unittest import sys import io import json from models.base import Base from models.rectangle import Rectangle from models.square import Square class TestBase(unittest.TestCase): """Testing Base""" def test_base_repeated_id(self): """Base repe...
309bf503bd40a7d70322ebbd111d68a64f71ca14
YMikita/exadel-python-course-2021
/tasks/task08/shape2d/rectangle.py
899
3.765625
4
from tasks.task08.shape2d.shape import * class Rectangle(Shape): bottom_left = Point(0, 0) width = 0 length = 0 def __init__(self, bottom_left: Point, width: float, length: float): self.bottom_left = bottom_left self.width = width self.length = length def __contains_by_x(...
595d0a9bbb079a0bfe729b1044e3c9b8096715aa
m9rehman/Machine-Learning
/Machine Learning in Action/01_Intro/01_ml.py
351
3.5
4
from numpy import * def randomArrayGenerator(n): myrandom = random.rand(n,n) print(myrandom) return myrandom def arrayToMat(array): myMat = mat(array) print(myMat) return myMat def inverseMat(mat): myInv = mat.I print(myInv) return myInv myArray = randomArrayGenerator(5) myMatrix = arrayToMat(myArray) my...
8b41b3a3961b8399146511abe957817d26af0f00
fidansamet/code-for-fun
/is_power.py
223
4.03125
4
"""Returns True if a is power of b.""" def is_power(a, b): if a/b == 1.0: return True elif a % b == 0: return is_power(a / b, b) else: return False if is_power(64,8): print('Yup')
9c510ccbf02e2b06c6004e3b66d75e355b56217d
huginngri/Skilaverkefni
/Skilaverkefni8/document_retrieval.py
2,441
4.0625
4
import string def filereader(): filename = input("Document collection: ") filetext ='' try: with open(filename, 'r') as f: for lines in f: filetext += lines return filetext, 1 except: print("Documents not found.") return filetext, 3 def s...
c44988a5f346a55c2e0ae032991f74ca4bfd35d8
coremedy/Python-Algorithms-DataStructure
/Python-Algorithms-DataStructure/src/leet/147_InsertionSortList.py
1,906
3.53125
4
''' Created on 2015-08-23 ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode ""...
b0b303366bbe1a8ed8b9fa6d7d8516f1b815317f
fqjdmppc/leetcode
/20.Valid.Parentheses.py
339
3.78125
4
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ d = {'}': '{', ']': '[', ')': '('} q = list() for _ in s: if not q or _ not in d or q[-1] != d[_]: q.append(_) else: q.pop() ...
4f0c26dac04e59c23728adddbdcd3a44dc6a3e0b
mahdi-jewel/URI-solve-in-Python
/URI1040.py
564
3.75
4
N=input().split(" ") n1 = float(N[0]) n2 = float(N[1]) n3 = float(N[2]) n4 = float(N[3]) avg = ((n1*2)+(n2*3)+(n3*4)+(n4*1))/10 print('Media: %0.1f' %avg) if avg >=7.0: print("Aluno aprovado.") if avg<5.0: print("Aluno reprovado.") if avg >=5.0 and avg <= 6.9: print("Aluno em exame.") score...
b9ecaffb09e270bde31ec89cdb64d6165c245a15
ParvathyGS/My-learnings
/Python/ex1.py
193
3.890625
4
name = input("Enter your name") age = int(input("Enter your age")) calc_age = 2020 + (100 - age) print("Welcome " + name) txt = "You will turn 100 years old in {}" print(txt.format(calc_age))
8b0c406594ae673135ecb9480db287e46aeff1e5
venkateshmoganti/Python-Programes
/Task25.py
2,138
3.828125
4
# Caesar Cipher def ccd(): original_text = input("Enter the text: ") text = original_text.replace(" ", "") key = input("Enter the key: ") a = int(input("Press 1 for Encryption, 2 for Decryption : ")) z = [] result = "" for i in range(0, len(text), len(key)): temp = text[i:i + len(key...
14b0f80ae488d5b18a26630c77eba350bdd81260
rafaelperazzo/programacao-web
/moodledata/vpl_data/5/usersdata/120/2702/submittedfiles/atm.py
372
3.84375
4
# -*- coding: utf-8 -*- from __future__ import division import math #ENTRADA v=int(input('informe o valor a ser sacado:') #PROCESSAMENTO nota20=(v//20) a=(v-(nota20*20)) nota10=(a//10) b=(a-(nota10*10)) nota5=(b//5) c=(b-(nota5*5)) nota2=(c//2) d=(c-(nota2*2)) nota1=d #SAIDA print('%d'%nota20) print('%d'%nota10) print...
b5c5a8461930b6749be43030bfdf11a6355f2b5a
fantasylsc/LeetCode
/Approach/Classification/Recover_Rotated_Sorted_Array.py
1,413
3.8125
4
''' Description Given a rotated sorted array, recover it to sorted array in-place.(Ascending) Clarification What is rotated array? For example, the orginal array is [1,2,3,4], The rotated array of it can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3] Example Example1: [4, 5, 1, 2, 3] -> [1, 2, 3,...
8e144fc5cf94c45453c33a2f86cd14d143e234c3
sanu11/Codes
/Leetcode/1030.MatrixCellsInDistanceOrder.py
658
3.515625
4
class Solution(object): def allCellsDistOrder(self, R, C, r0, c0): """ :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] """ #2 ways - 1st using BFS 2nd - calculate all the dist, store, sort by dist. #2nd wa...
b39e8625db478786ba6fd848ec1471673291c533
francisannemmanuel-arcamo/student_info_system
/DeleteStudent.py
4,723
3.515625
4
from tkinter import * from tkinter import messagebox from Student import Student class DeleteStudentFrame: def __init__(self, frame, table): self.delete_frame = frame self.display_table = table self.stud_class = Student() self.data = self.stud_class.data self.id_no = Str...
e4887057cd6f9c3dbfb6ca9e4d49bec78c39bbae
herlanin/codility
/7_stacks_queues/nesting.py
533
3.734375
4
def solution(S): parentheses = 0 for element in S: if element == "(": parentheses += 1 else: parentheses -= 1 if parentheses < 0: return 0 if parentheses == 0: return 1 else: return 0 def solution(S): stack = [] ...
626e3f72fff9060cc59bb774497bb2e52c7234ce
valkata1220/Programming-Basics-Python
/07.While-Loop-Lab/06.account_balance.py
313
3.859375
4
payments_count = int(input()) total = 0 while payments_count > 0: money_value = float(input()) if money_value < 0: print(f'Invalid operation!') break else: print(f'Increase: {money_value:.2f}') total += money_value payments_count -= 1 print(f'Total: {total:.2f}')
4472f0bb96ff7762038b7ab5cb4d15e88cb16b72
AccLoo0311/mit6.0001-notes-pset
/my_pset_code/ps4/ps4b.py
12,172
3.953125
4
# Problem Set 4B # Name: <your name here> # Collaborators: # Time Spent: x:xx import string #导入string这个模块 #print string.letters #包含所有字母(大写或小写)的字符串 #print string.lowercase #包含所有小写字母的字符串 #print string.uppercase #包含所有大写字母的字符串 #print string.punctuation #包含所有标点的字符串 #print string.ascii_letters #与string.letters一样 de...
8d56176aaf93b7430ba4f0f7067d580ba4d7ca30
andrei-radu/ECCPR-Python
/imagine mediana/imagine mediana.py
1,264
3.65625
4
#citire lin=int(input()) col=int(input()) i=1 linie=[] A=[] while i<=lin*col: element=int(input()) linie.append(element) if i%lin==0: A.append(linie) linie=[] i+=1 #prelucrare Azero=[] # o construim noi i=0 while i<lin+2: #+2 pentru bordare: margine sus si margine jos ...
563116d7510b865685ac964752d3d44a634be516
LingB94/Target-Offer
/33二叉搜索树的后序遍历序列.py
823
3.5
4
class TreeNode(object): def __init__(self, n): self.val = n self.lchild = None self.rchild = None def verify(L): if(not L): return False p = L[-1] step1 = 0 while(L[step1] < p and step1 < len(L)): step1 += 1 for step2 in range(step1, len(L)):...
ccf7e1f07ed1cc173a55bd874f7bb4e65685c2cf
chengke07/MyPython
/tk2.py
337
3.515625
4
from tkinter import * class App(Tk): def __init__(self): super().__init__() self.hi_there = Button(self,text='打招呼',bg='black',fg='red',command=self.say_hi,) self.hi_there.pack() def say_hi(self): print('小甲鱼你好,') def close(self): self.destroy()
22781dc867c7ac5421e7f48251c3d4e284c047fd
EdwardBetts/Thinkful-python
/tip_calculator.py
2,439
3.796875
4
''' meal = 100.00 tax = 0.20 tip = 0.10 tax_value = tax * meal meal_with_tax = meal + tax_value tip_value = meal * tip total = meal_with_tax + tip_value print "${0:.2f}".format(meal) print "${0:.2f}".format(tax_value) print "${0:.2f}".format(tip_value) print "${0:.2f}".format(total) ''' ''' from optparse import Op...
882020c3b1a4f9f8fe893b6c826bf74ce189812b
brianchiang-tw/HackerRank
/Python/Regex and Parsing/Validating and Parsing Email Address/validating_and_parsing_email_address_regex.py
625
4.03125
4
import re def validate_address( email ): regex = r'^<([A-Za-z0-9]+[A-Za-z0-9-\.\-_]*@[A-Za-z]+\.[A-Za-z]{1,3})>$' pattern = re.compile(regex) result = re.match( pattern, email ) if result is None: return "Invalid" else: return "<" + result.group(1) + ">" if __name__ == '__main...
ae98dfc6038cd0686063e70c375bc4204ca0a3da
asxzhy/Leetcode
/leetcode/question_1370/solution_1.py
1,353
4
4
""" The way that this code works is that first sort the string alphabetically and convert the string to a list. Each element contains a group of same characters. Add the characters from index 0 to len(list) and from len(list) to 0 again. """ class Solution: def sortString(self, s: str) -> str: s...
e290a623e21ce58b56e89c333254bc90e7d525a4
tvollstaedt/aoc2020
/_1.py
412
3.625
4
from typing import List def part1(input: List[str]): for i in input: for j in input: if int(i) + int(j) == 2020: return int(i) * int(j) return 0 def part2(input: List[str]): for i in input: for j in input: for k in input: if int(i) ...
58dca5dd8be8c4bee0f1025016f909e058018ab8
ktikeda/dicts-restaurant-ratings
/ratings.py
3,592
4.09375
4
import sys import random import os def create_restaurant_ratings(filename): """Restaurant rating lister.""" restaurant_ratings = {} # initialize restaurant_ratings dictionary with open(filename) as restaurant_file: # import the file for line in restaurant_file: # for each line: li...
08e81ba922df3a4714993ca5a59c5257f7bcf059
havenshi/leetcode
/285. Inorder Successor in BST.py
1,367
3.875
4
# -*- coding: utf-8 -*- # Given a binary search tree and a node in it, find the in-order successor of that node in the BST. # # Note: If the given node has no in-order successor in the tree, return null. # Inorder Successor is the leftmost element in the right subtree of 'a' # Time: O(h) # Space: O(1) # Definition...
5345a7d8d3c798a0aeb57b3b49c3a405b19d1991
barbaraolivieri/uri
/1079.py
185
3.734375
4
n = int(input()) for x in range(n): linha = input().split(" ") a,b,c = linha a = float(a) b = float(b) c = float(c) media = float(((2*a)+(3*b)+(5*c))/10.0) print("%.1f" %media)
df499856035e3b1a44d1529824f60ec3ef1c2307
ConradBohm/monster_uni_program
/functions.py
2,820
3.953125
4
from data import * # stud_list = [j_black, j_mcintyre, b_jameson, t_foolery] def students(): while True: print('\nStudents menu:\n' '1 -- View Student Details\n' '2 -- View Student List\n' '3 -- Add Skill to Student\n' '4 -- Add Student\n' ...
73407b391cc8ddd91eada840b5e129ee8a3620cd
muhlik20033/muhlik20033
/TSIS 6/11.py
270
3.578125
4
def perfect(x): l = [] for i in range(1, x): if x%i==0: l.append(i) if sum(l) == x and (sum(l)+x)/2==x: print(x, 'is perfect number') else: print(x, 'is not perfect number') perfect(int(input()))
8457811a03f3bd3945e335ac0581bf1756dedeb9
tuank60/pdf_project
/PdfFileReader.py
2,245
3.765625
4
# Python program to create # a pdf file from fpdf import FPDF from fpdf import * class PDF(FPDF): def header(self): # Logo self.image('logo.png', 10, 8, 33) # Arial bold 15 self.set_font('Arial', 'B', 15) # Move to the right self.cell(80) # Title ...
621b6c6cbbdb35907fa1004b386915afe5054dbb
gabrielnoguerales/Practica_python
/Dia1.py
1,222
3.8125
4
''' Tenemos un conjunto de numeros en un array. Dado un numero cualquiera devolver un booleano cuyo valor dependa de si el numero se puede obtener como combinacion de dos numeros de nuestro array Por ejemplo [1,2,5,6] (3) Devolveria true porque 2+1 = 3; [1,5,6] (3) Devolver...
12d80c942255ac6b50627484bd4fb8a493fd1bd4
yywecanwin/PythonProjectAdvance
/day01/13.死锁.py
903
3.71875
4
# -*- coding: utf-8 -*- # author:yaoyao time:2020/2/26 import threading # 创建互斥锁 lock = threading.Lock() # 保证同一时刻只有一个线程根据下标去取值 def get_value(index): # 取值之前先上锁 lock.acquire() my_list = [1, 4, 8] # 判断下标是否越界 if index >= len(my_list): print("下标越界:", index) # 下标越界不能取值,也需要把锁释放,保证后面的线...
896e742b538c2ac7152108cfe9546be0ebe87d4f
yingweima2022/speedbot_cali
/testmyw.py
78
3.609375
4
str = '1 ,2 , 4 , 4' for value in str.split(','): print(float(value))
75f44c415ffa22a208c42f370594ee48150f1b96
vishsanghishetty/LC-Python
/easy/Roman to Integer/solution.py
761
3.84375
4
# Time complexity: O(len(s)) # Approach: Traverse the roman string from left to right and keep adding the values from mapping. class Solution: def romanToInt(self, s: str) -> int: db = { "M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, ...
eb0ccce9cd075f4dcda7fe38bcfd4fe94f5205c9
guodonghe/python-vs-rust
/guest.py
571
4.0625
4
#!/usr/bin/python import random print ("Guess the number!") secret_number = random.randint(1,101) #print ('The secret number is: {}' .format(secret_number)); while True: print ("pleaee input your guess."); # guess = input() try: guess = input() print ("You guessed: {}".format(guess)...
2c7d0939e16034bd7e8d9e7c0082ba31a4502042
natashahussain/webLnatasha
/CO1 pg7(a).py
362
4
4
#Enter 2 lists of integers.Check #(a) Whether list are of same length list1 = [2, 5, 4, 1, 6] list2 = [1, 6, 2, 3, 5] print ("The first list is : "+ str(list1)) print ("The second list is : "+ str(list2)) if len(list1) == len(list2): print ("Length of the lists are same") else : prin...
04be25580f9f5637d536d2ce39d190c9a66590cd
rboling/data_analysis_work
/exercise.py
1,409
4.375
4
# This is your first exercise in Python! Use it as # a warmup exercise. # The built-in aString.split() in Python only uses # whitespace to split the string. This is annoying because # if you had a sentence with punctuation marks, # the procedure won't be able to recognize it. # Define a procedure, split_string, that...
a516128d0ecaacf5f9d265bff3e535a0993cc29b
NateDreier/Learn_Python
/independent_learning/decorators/decorator.py
1,778
3.890625
4
#!/usr/bin/env python3 """ Playing with Decorators 1. Timing decorator to test the speed of a function. 2. Decorating decorator to decorate the output. 3. Number checking decorator to check the validity of the number. """ import time import concurrent.futures class Dec: def __init__ (self, n): self.n =...
5530bb6c92d75bbecb0bef10728ff0d62bcdc02c
xiasiliang-hit/leetcode
/pathSum2.py
1,133
3.5625
4
# test case is wrong I think # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: i...
701162b44b77eedfb817aed45db7a689ff484713
PdxCodeGuild/20170724-FullStack-Night
/Code/matthew/python/lab26-bogosort.py
1,378
3.984375
4
# lab 23: bogosort, not using built-in functions import random import time # generate a random list of n values each between 1 and 99 def random_list(n): nums = [] for i in range(n): nums.append(random.randint(1, 99)) return nums # re-arrange a list by swapping pairs of elements def shuffle(num...
b796683aca359293a02336884ebc7935e6e46adf
dtran2108/door-to-door
/Algorithms/NearestNeighbor.py
1,200
3.8125
4
from graph import Graph from Parsers import total_length from node import Node from time import time class Nearest_neighbor(Graph): """ Find the closest city base on the distance between them """ def nearest_neighbor(self): """ find the closest city by calculating the distances between the start Node...
c67bccd1ccbca2c46763e66f1416376ec5249d31
Rodagui/Programas_Teor-aComputacional
/programa9.py
446
3.96875
4
#Programa 9: Elimina los caracteres que tienen valores de indice impar de una cadena. def eliminarImpares(cadena): nva = "" for i in range(1, len(cadena), 2): nva += cadena[i] return nva #------------------ Main ------------------# print("\nPrograma 9: Elimina los caracteres que tienen valores de in...
e8c7a45abef8f443f747e32e79d4a202531732e6
KarolJanik-IS/pp1
/02-ControlStructures/zadanie15.py
145
3.5
4
#02-15 liczba = int(input("Podaj liczbę: ")) for i in range(1,11): #print(liczba,"x",i, "=", liczba*i) print(f"{liczba}*{i}={liczba*i}")
f9402328a2aac7bb315496b9f59bb5fbc5d903fb
duybui2905/C4T-13
/session7/squaring_numb.py
107
3.9375
4
numb = float(input("enter a number: ")) numb_square = numb**2 print("the squared number is", numb_square)
91420e0cb780848921adbeeba89ea398c9215ce6
tigervanilla/Daily_Coding_Problem
/38.py
2,431
3.65625
4
# This problem was asked by Microsoft. # You have an N by N board. # Write a function that, given N, returns the number of possible arrangements of the board # where N queens can be placed on the board without threatening each other, # i.e. no two queens share the same row, column, or diagonal. def isSafe(board, n, ...
5c0ba18424978a9bffb7191ac78c649a89039649
Spafey/Combining-shaping-Data
/Aggregates&Groupby.py
1,052
3.671875
4
import pandas as pd df = pd.read_csv('Modified.csv') print("\nGroupby can look at the 'Type 1' column, grouping similar (identical?) objects & returning the mean:\n") print(df.groupby(['Type 1']).mean()) print("\nSort_values() can be used here - e.g., type organized by mean defense:\n") print(df.groupby(...
88d6d52120fdeff0551067ccc0b5e72521b35137
neilsjlee/AlarmSystem
/ControlHub/priority_queue.py
1,600
3.875
4
# Implementing Priority Queue using List data type import threading class MyPriorityQueue: def __init__(self): self.queue_list = [] self.queue_size = 0 self.lock = threading.Lock() def put(self, task_type, priority, timestamp, address, data): self.p() i = 0 fo...
d8b024a04feae870b04713aea593a5d3dd00a5a7
Alien-Intelligence/Coderbyte
/Coderbyte_Easy_3_KA.py
779
3.625
4
def LongestWord(sen): a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] A = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'...
e859097596e0595e8fd1882b00bd14ae9fbf9534
charliechocho/py-crash-course
/name_cases.py
387
4.0625
4
# Printa variabeln name och name_2 med olika stripping och formatering name = "Nina" print(f"Hello, {name}! Would you like to learn some python?") name_2 = "nina pentti" print(name_2) print(name_2.upper()) print(name_2.title()) quote = '"A person who never made a mistake, never tried anything new"' fam_person = " Alber...
d4af8b9642210cdd7b7402276072865e62610e7a
learnerofmuses/slotMachine
/march10p1.py
1,094
4.03125
4
#test2 max function, average student function def main(): #function make_list row = int(input("number of students ")) col = int(input("number of courses ")) grades = make_list(row, col) print(grades) #to print in matrix form for i in range(row): print(grades[i]) #function max_value maxV, i_max, j_max =...
c6cddd883828209dce1c40799ceff7fc07e9af44
ymxin/ymx_task
/python_practice/test_os.py
373
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import os # os.mkdir("testdir") # print(os.listdir("./")) # os.removedirs("testdir") # print(os.getcwd()) # 判断b文件夹是否存在 # print(os.path.exists("b")) if not os.path.exists("b"): os.mkdir("b") if not os.path.exists("b/test.txt"): f = open("b/test.txt", "w") ...
1c29bd59178691fb6f0941b1bfb8052f3d654f77
Illugi317/forritun
/Unsorted/Tile2.py
2,266
3.84375
4
def get_row(indexY, rows): return rows[indexY] def check_lever(directions): return "L" in directions def print_directions(directions): string = "" for direction in directions: if direction == "N": string += f"({direction})orth" elif direction == "S": string +...
e590b3077113564f1cbbb1b2c232166c129fd5e9
Lee-3-8/CodingTest-Study
/level2/점프와_순간_이동/신필.py
207
3.625
4
def solution(n): battery = 0 while n!=0: print(n,battery) if n%2 == 0: n/=2 else: n-= 1 battery+=1 return battery print(solution(5000))
2e451c8029f83fef961c30b6c072950d84ac905f
piotriwn/oop_gui_sample
/figures.py
3,426
3.65625
4
import math class Triangle: def __init__(self): pass @property def a(self): return self._a @property def b(self): return self._b @property def c(self): return self._c @a.setter def a(self, aIn): try: aTemp = float (aIn) ...
581ae9c22678732a858bea7f8b509cd16c78b162
kazadi/learnpythonthehardway
/ex15.py
859
3.984375
4
#Ex 15: Reading Files #imports the argv module from the system from sys import argv # # assigns new arguments from the command line # # argv[0] is the script 'ex15.py' pathname, # # argv[1] is the 'ex15_sample.txt' input file # script, filename = argv filename = raw_input("Enter filename: ") #assigns the argv[1] obj...
424bbf4af1e6b54be1e0c879bef87358dd423d08
w320alm/Piston-in-Mousai
/TestDummy.py
3,613
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 29 20:00:59 2018 @author: austinmcdonnell """ import matplotlib.pyplot as plt import os import numpy from pathlib import Path home = str(Path.home()) def pressure(V,n,R,T): return n*R*T/V def Force(P,A): return P * A def acceleration(F,m...
b28d30914bdaa3c16637fef11046fef897e91a52
archieparedes/Python-Programs
/STRING MIRROR.py
911
4.125
4
""" CSC 243 Python for Programmers Created on Oct 22 Sun 10:57:23 2017 @author: Archie Paredes Problem 6.22 pg 196 """ # type main() in shell or press f5 to run def main(): word = str(input("Enter a word: ")) if(mirror(word) == False): print("INVALID") def mirror(word): validChar = {'U':'U', ...
c49220b29baefd4bf85f94d34dbf3d251399cb39
timmy61109/Introduction-to-Programming-Using-Python
/examples/FibonacciNumberGenerator.py
337
4.03125
4
def fib(): fn1 = 0 # Current two consecutive fibonacci numbers fn2 = 1 while True: current = fn1 fn1, fn2 = fn2, fn1 + fn2 yield current def main(): iterator = fib() # Display all Fibonacci numbers <= 10000 for i in iterator: print(i, end = ' ') if i > 10...
7655b6d87d371e4fd4ee9ac62c65bafe128618e1
snpushpi/P_solving
/279.py
662
4
4
''' Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. ''' import math def main(n): c = math.sqrt(n) sqr_...
690f7e344424461fc505f4bc3a4df5305e4d9f18
Pau1Robinson/term2_challenges
/22-8/22-8_part3.py
826
4.03125
4
''' Answer for the third section of the morning challenge for the 22-8 term 2 ''' #Asks the user for a string of two digit numbers separated by comma's user_input = input('input a string of two digit numbers separated by comma\'s\n') #test_input = '34,67,55,33,12,98' #Delares the new list and tuple new_list ...
04d0fef054c3529143d333e96404aba370158448
zhuwenzhang/Python-base
/堆栈头文件.py
553
3.703125
4
class Stack: def __init__(self): self.__elements = [] def isEmpty(self): return len(self.__elements) == 0 def peek(self): if self.isEmpty(): return None else: return self.__elements[len(self.__elements)-1] def push(self,value): ...
446702114641337983e5197deff42e28e1f27449
alexarirok/list-in-python
/project.py
1,120
3.828125
4
from random import randint biglistnum = int(input("length of bigger list? ")) smallerlistnum = int(input("length of smaller list? ")) numtoadd = int(input("value to be added to initial bigger list? ")) #print(biglistnum, smallerlistnum, numtoadd) biggerlist = [] smallerlist = [] while len(smallerlist) < smallerlistnu...
cdade0d5c78fff4366b8cfe40e24e5baa6108781
Prakash1154/Bus-Ticket-Booking-System
/BusTicket_Booking/bustable.py
1,845
3.71875
4
import sqlite3 def Create_Table(): conn = sqlite3.connect('test.db') print("Opened database successfully") conn.execute('''CREATE TABLE BUS_SERVICE (BUSID INT PRIMARY KEY NOT NULL, BUSNAME TEXT NOT NULL, ORIGIN INT NOT NULL, DEST...