blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
50736978b3dfddfec0882186d7829f341e1c71a6
almiranda86/PythonLab
/PythonLab/PythonLab/mostCommonLetter.py
1,148
3.78125
4
def checkio(text: str) -> str: t = text.lower().replace(" ","") myDict = {} count = 0 for x in t : if x.isalpha(): if x in myDict: myDict[x] += count+1 else: myDict[x] = count+1 if all(value == 1 for value in myDict.values()): ...
5494ffcfe34a12e7fbb148a7fada72ecedf8ff92
Mostafa-At-GitHub/Data-Structures-and-Algorithms-codes
/CS_LAB_MA252/Dynamic Programming/longest.py
823
3.703125
4
def printlcs(b,X,i,j): if i==0 or j==0: return if b[i][j]=="proceed": printlcs(b,X,i-1,j-1) print(X[i-1]) elif b[i][j]=="^": printlcs(b,X,i-1,j) else: printlcs(b,X,i,j-1) def lcs(A,B): la=len(A) lb=len(B) w, h = la, lb; c = [[0 for x in range(h+1)] for y in range(w+1)] #c is length of lcs b = [[0...
6be6d862ae3bd299bc4af5f3f71166a11660b336
crh2302/capstone
/delete/convert_to_full_hash.py
2,004
3.609375
4
import pandas """ The purpose of this file was to convert small commit hashes into full commit hashes. This module does not take part in the collection of metrics """ def read_data(file_name, column_names): data = pandas.read_csv(file_name) df = pandas.DataFrame(data) df.columns = column_names retur...
a3c5134b05e18ec48a2634d8d36f7204acea3018
mlipshultz/Asymmetrik-programming-challenge
/Business_card_parser.py
5,343
3.953125
4
import re import sys #The business card parser class will be doing all of the heavy lifting in figuring out #the different pieces of contact information class BusinessCardParser: #We will define a series of private helper functions for parsing out the pieces of contact information. def __parseName(self, docum...
5600d557d505b2fb6283996edfc9c3f097174717
banjocat/codeeval_solutions
/31/main.py
345
3.515625
4
import sys def main(): with open(sys.argv[1]) as f: for line in f: solve(line) def solve(line): (word, end) = line.split(',') letter = end.strip() pos = -1 for x in range(0, len(word)): if word[x] == letter: pos = x print(pos) if __name__ == '...
4166493515218391c7706e54d1012e547d530a57
mattgarrett/hits
/crawl.py
3,551
3.84375
4
#!/usr/bin/python #matt garrett #cse 417 #crawl is a python implementation of a simple wikipedia crawler to explore #the wikipedia graph. It is built on top of BeautifulSoup. import sys import urllib2 from bs4 import BeautifulSoup import re #the regex to match an internal wikipedia link wikiLink = re.compile("^/wik...
4471b582aa890ff026efad9fdc5ebf86f1bb30b9
salonikalsekar/Python
/programs/binarySearch.py
452
3.65625
4
pos = -1 def search(list, n ): l = 0 u = len(list) - 1 while l <= u: mid = (l + u) // 2 if list[mid] == n: globals()['pos'] = mid return True else: if n > list[mid]: l = mid + 1 ; else: u = mid - 1; ...
ab18d6fceb444644ddf2931fd6ee12d796784d5f
SandraAlcaraz/FundamentosProgramacion
/quiz2-1.py
110
3.671875
4
hora=9 minutos=23 segundos=45 print(hora,minutos,segundos,sep=":") print("%i:%i:%i"%(hora,minutos,segundos))
bdd36183aca316ce0e936d155d7501edc7d1069e
nptit/python-snippets
/class.py
1,624
4.125
4
class A(object): def __init__(self): self.a = 1 def x(self): print "A.x" def y(self): print "A.y" def z(self): print "A.z" class B(A): def __init__(self): A.__init__(self) self.a = 2 self.b = 3 def y(self): print "B.y" def z(se...
fa37af86ad4edc02d7c1faeaee0dc866d26acff7
trvsed/100-exercicios
/ex049.py
247
3.8125
4
while True: t=int(input('Digite um número para saber a sua tabuada: ')) for c in range(1, 11): print('{} x {} = {}'.format(t, c, t*c)) cont=str(input('Deseja continuar? (s/n): ')).lower() if cont !='s': break
f959211a86d8f499a9f3d84cc9ecf4a6306994f6
Bundaberg-Joey/Pybanez
/pybanez/utilities.py
500
3.578125
4
def shared_notes(*args): """Identify notes belonging to all multiple passed lists of notes. Parameters ---------- *args : list, shape(num_notes, ) 1D List of notes. Returns ------- unique_notes : list shape(num_unique_notes, ) Alphabetically sorted list of notes which are ...
cea660e35fae2810739d45f79832cce69e9db939
RyosukeNAKATA/leetcode
/March_LeetCoding_Challenge_2021/day6.py
877
3.859375
4
""" Question: Short Encoding of Words A valid encoding of an array of words is any reference string s and array of indices indices such that: - words.length == indices.length - The reference string s ends with the '#' character. - For each index indices[i], the substring of s starting from indices[i] and up to (but not...
181bdd31606f9b8ec46f7634f95964bc4debd25d
henry1034/Challenge-Project-of-CodeCademy
/python/Hypothesis_Testing_with_Python/Testing_a_Sample_Statistic/Simulating_a_Binomial_Test/binomial_testing_with_scipy.py
785
3.5625
4
import numpy as np import pandas as pd from scipy.stats import binom_test # calculate p_value_2sided here: p_value_2sided = binom_test( 41, # the number of observed successes n = 500, # the number of total trials p = 0.1 # the expected probability of success ) print(p_value_2sided) print(f"IF the true proba...
f5ab7d33cb9346bed3eb3004525952e3535cf89c
templeorz/test001
/第七章 输入和while循环 课后练习.py
5,499
4.21875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 7-1 汽车租赁 : 编写一个程序, 询问用户要租赁什么样的汽车, 并打印一条消息, 如“Let me see ifI can find you a Subaru”。 # 7-2 餐馆订位 : 编写一个程序, 询问用户有多少人用餐。 如果超过8人, 就打印一条消息, 指出没有空桌; 否则指出有空桌。 # 7-3 10的整数倍 : 让用户输入一个数字, 并指出这个数字是否是10的整数倍。 car_rental = 'What kind of car would like rent?' car = input(car_rental) prin...
054083474f6d5c63ff72e77387d3b33c5730bd63
Rohithmarktricks/20186097_CSPP-1
/cspp1-assignments/m11/p3/assignment3.py
1,031
3.828125
4
''' Assignment-3 @author : Rohithmarktricks ''' def is_valid_word(word, hand, word_list): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> ...
e25091fe0d7d6054bc5b655b7b87b70548eff05a
PeterL64/UCDDataAnalytics
/8_Introduction_To_Data_Visualization_With_Seaborn/3_Visualizing_A_Categorical_And_A_Quantitative_Variable/3_Customizing_Bar_Plots.py
794
3.921875
4
# Customizing bar plots import matplotlib.pyplot as plt import seaborn as sns # Use sns.catplot() to create a bar plot with "study_time" on the x-axis and final grade ("G3") on the y-axis, # using the student_data DataFrame. sns.catplot(x='study_time', y='G3', data=student_data, kind='bar') # Using the order paramet...
b6d6c14801205ff9781e2c5cdeb4749375dd52d9
Eboru77/see-segment
/see/JupyterGUI.py
5,889
3.625
4
"""This produces a GUI that allows users to switch between segmentation algorithms and alter the parameters manually using a slider. It shows two images, one with the original image with the resulting mask and one with the original image with the negative of the resulting mask.""" import matplotlib.pylab as plt i...
bb5056cafde9b0023ff190de4418caf1507b52fc
Yona-Dav/DI_Bootcamp
/Week_4/Day5/challenges_1.py
5,940
4.15625
4
#Exercise 1 #Write a script that inserts an item at a defined index in a list. list = [1,2,3,4] list.insert(2,62) # in index2 print(list) #Exercise 2 # Write a script that counts the number of spaces in a string sentence = "This is a Beautiful Day" print(sentence.count(' ')) # Exercise 3 # Write a script that calcu...
69eb8dcacd87ed1f1b872fda555db813d534e02d
softechie/ProjectEagle_L6_AI_ML_NLP
/PythonNLTK/nltk_02_sent_work_tokenize.py
422
3.8125
4
from nltk.tokenize import sent_tokenize, word_tokenize example_text = "Hello Mr. Pythonpro, how are you doing today? welcome to the python programming" print ("word list","\n","~~~~~~~~~~") print (word_tokenize(example_text)) print ("sentence list","\n","~~~~~~~~~~~~~") print (sent_tokenize(example_text)) print ("\n...
c7d38122c0004b4220dfcde49a5e68e3c5b5c2de
962245899/t07-maira-sandoval
/bucle04.py
629
4.0625
4
#validar el nombre de un mes nombre_de_un_mes="" no_es_el_nombre_de_un_mes=True while(no_es_el_nombre_de_un_mes): nombre_de_un_mes=input("Nombre de un mes:") no_es_el_nombre_de_un_mes=(nombre_de_un_mes != "enero" and nombre_de_un_mes != "febrero" and nombre_de_un_mes != "marzo" and nombre_de_un_mes != "a...
18c2b521d6ea5c2d9052c868a76c8b84c422d68c
VZakharuk/sofrserve_pythonc
/ClassWork/cw13/mile_to_km.py
303
3.734375
4
# variant with map # def miles_to_km(numb_miles): # return numb_miles*1.6 # list_miles = [1.0, 2.0, 1.4, 2.5] # list_km = list(map(miles_to_km, list_miles)) # print(list_km) # variant with lambda list_miles = [1.0, 2.0, 1.4, 2.5] list_km = list(map(lambda x: x*1.6, list_miles)) print(list_km)
ad08dfdd705b0ac724e798474e4730f43bba9b67
jordanjj8/exercising_with_python
/slice.py
965
4.28125
4
# Jordan Leung # 2/13/2019 # printing out what is given print("Given: ") cubes = [num**3 for num in range(1,11)] print(cubes) # printing out the first three items print("The first three items in the list are: ") print(cubes[:3]) # printing out the middle of the list print("Three items from the middle of...
237b020210e0a9c7cb59528ad6852e646f1f83f8
Rebecca-Simms/Python-Challenges
/FizzBuzz Challenge/FizzBuzz.py
382
3.734375
4
def fizzbuzz_compute(maxnumb): fizzbuzz = [] for i in range(0, maxnumb + 1): word = '' if i % 3 == 0: word += "Fizz" if i % 5 == 0: word += "Buzz" if i % 7 == 0: word += "Pop" if word == '': word += str(i) fizzbuzz.a...
ccf96f9711d950dba0b8ea01ea711151c4daf6bd
lucabianco78/QCBsciprolab2020
/exercises/readFile_gz.py
505
3.78125
4
import argparse import gzip parser = argparse.ArgumentParser(description="""Reads and prints a text file""") parser.add_argument("filename", type=str, help="The file name") parser.add_argument("-z", "--gzipped", action="store_true", help="If set, input file is assumed gzipped") args = parser.parse_args() inputFile = ...
45bcb952e6936d45717ab49fa8a910edaeedaa3e
dydwnsekd/coding_test
/programmers/python/소수_찾기.py
611
3.640625
4
# https://programmers.co.kr/learn/courses/30/lessons/12921 def solution(n): sieve = [True] * (n+1) m = int(n ** 0.5) for i in range(2, m + 1): if sieve[i] == True: for j in range(i+i, n+1, i): sieve[j] = False return sieve[2:].count(True) """ def isdecimal(n):...
be3d010d24ec82183280cc2e011a1db5b2001c38
BreenIsALie/-Python-Hello-World
/ex13.py
497
3.734375
4
__author__ = 'BreenIsALie' # Exercise 13, Exercises taken from http://learnpythonthehardway.org/book/ # Parameters, unpacking and Variables # import the argument variable (argv) for use. This is a MODULE (IMPORTANT TO REMEMBER) from sys import argv # Take input from argv and assign it to variables script, first, sec...
b4f4d967bc3e22c44d6e57d88219da46908984cb
rcarino/Project-Euler-Solutions
/problem36.py
474
3.5625
4
__author__ = 'rcarino' def is_5and2_palindromic(n): binary = bin(n)[2:] return is_palindrome(str(n)) and is_palindrome(binary) def is_palindrome(s): end = len(s) for i in range(end/2 + 1): if s[i] != s[end - 1 - i]: return False return True def palindromes_base_5and2(n): r...
56fac970d8344fc0c446d41d82830a4f4c10dc95
PGYangel/python_test
/dataType/numbers.py
3,977
4.125
4
# Number(数字) # 数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。 num = 1 print(num) ''' del语句的语法是 del var1[,var2[,var3[....,varN]]]] 您可以通过使用del语句删除单个或多个对象的引用。例如: del var del var_a, var_b ''' ''' Python 支持四种不同的数值类型: 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。 长整型(long integers) - 无限大小的整数,整数最后是一个大写或小写的L。 浮点型(floating point real va...
f6902f120114efd5e328f0e478138f207dc72f3f
Upasna4/Training
/primeornot.py
161
4
4
n=int(input("enter a number")) f=0 for i in range(2,n): if (n%i==0): print("composite number") f=1 break if(f==0): print("prime")
787445b8cb127df7996a1c4c0577ae68c3a4e8c5
egbeyongtanjong/MIT_Data_Analysis_2020
/Lecture_notes/Lecture5.py
3,518
4.21875
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 10 08:36:06 2020 @author: Egbeyong """ """ There are three data structures used in python to collect items: Tuples, lists, and dictionaries tuples and lists are ordered sequence of objects. It makes sense to talk about the first object, the second object, the last objec...
0b4d756c4f917a2f9071b65fa6c52b968211a9ec
jdb45/Guess-Number-Game
/tests/test_guess_the_number.py
854
3.765625
4
import unittest from guess_the_number import Guess_The_Number class TestGuessTheNumber(unittest.TestCase): # testing to make sure the check guess function is correctly displaying the right message def test_check_guess(self): self.assertEqual('guess is too low!', Guess_The_Number.check_guess(2, 4)) ...
9c31580ca962d7d179baefb5bad77186b9a4019f
kozlakowski/Fibonacci-w-explanation
/fibonacci.py
285
3.859375
4
iloscLiczb = int(input("Ile liczb fibonacciego chcesz uzyskac: ")) lista = [] num1 = 0 num2 = 1 for i in range(iloscLiczb): num1 = num2 - num1 print("Aktualne num1:", num1) num2 = num1 + num2 print("Aktualne num2:", num2) lista.append(num1) print(lista)
d4aec054a464f776924dd42b12874bd9fc3226c9
saattrupdan/stay_awake
/stay_awake.py
1,101
3.921875
4
def stay_awake(interval: int = 3, failsafe: bool = False): ''' Keeps the computer awake. INPUT interval: int = 3 How often the movement should occur, in minutes failsafe: bool = False Enable PyAutoGUI's failsafe, which disables the GUI if the mouse is moved t...
2659a4c21942136e6b37a1f3ed2eae77c9fbcef2
coolwonny/Jupyter_Workspace
/pracitice.py
3,338
3.828125
4
# grocery = ["Water", "Butter", "Eggs", "Apples", "Cinnamon", "Sugar", "Milk"] # print(f"The first two items: {grocery[:2]}") # print(f"The last five items: {grocery[-5:]}") # print(f"Every other items: {grocery[1::2]}") # grocery.append("flour") # grocery[3] = "Gala Apples" # print(f"The total number of items: {len(...
14eb2a56190d242154d8344c8feaafb164ee10be
melamri/Python_Applications
/04 Functions/Taking_a_Vaca.py
1,362
4.5
4
"""Define a function called rental_car_cost with an argument called days. Calculate the cost of renting the car: Every day you rent the car costs $40. if you rent the car for 7 or more days, you get $50 off your total. Alternatively (elif), if you rent the car for 3 or more days, you get $20 off your total. You c...
a90349514cac600cbbcebd9fb49821a21c887de8
AlexseyPivovarov/python_scripts
/lesson4_1523633686/player us player.py
1,815
3.75
4
from os import system, name cls = "cls" if name == "nt" else "clear" board = [ [" ", " ", " "], [" ", " ", " "], [" ", " ", " "] ] chip = ["X", "O"] i = 0 win = 0 while True: gamer = i % 2 # interface system(cls) print(" 1 2 3") print("1 {0[0][0]}|{0[0][1]}|{0[0][2]} Игрок: {1}".form...
ca0d85198b9379043d9d0a8c88caa05a766eb0d4
Chrisboris/python-work
/power.py
206
4.21875
4
base = int(input("Enter base : ")) power = int(input("Enter power: ")) def pow(base,power): result = 1 for x in range(power): result = result*base return result print(pow(base,power))
8fa617ef14fe216fe00e1dda399942104fa505e4
teerapat-ch/DataScienceProjects
/Machine Learning A-Z Code/Chapter 4 Clustering/Hierarchical_Clustering/hc.py
1,235
3.796875
4
# Hierarchical Clustering # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3, 4]].values # y = dataset.iloc[:, 3].values # Using the dendrogram to find the optimal number of cluste...
25571a454111d39ee5518385e37fe23364808eea
subho2107/Hacker-Rank
/Data Structures/Stack/Poisonous Plants.py
1,389
3.9375
4
""" PROBLEM LINK:https://www.hackerrank.com/challenges/poisonous-plants/problem """ #!/bin/python3 import math import os import random import re import sys # Complete the poisonousPlants function below. def poisonousPlants(p): day = 0 stackArr = [] pos = 0 stackArr.append([]) stackArr[0].append(p[...
455be873dfb644c24725a0e8daf179a13396f0f0
dlin94/leetcode
/array/414_third_max_number.py
536
3.53125
4
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 3: return max(nums) s = set(nums) if len(s) < 3: return max(s) m1 = None m2 = None m3 = None fo...
e2a9f26dc5c6c56582daa002a4c3c616fa7834a7
Akagi201/learning-python
/lpthw/ex42.py
1,432
4.28125
4
#!/usr/bin/env python # Exercise 42: Is-A, Has-A, Objects, and Classes ## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a animal cla...
d7af183a88284380542a46559f490bdbefdcd9f3
dwayneglevene/myfirstflask
/model.py
135
3.5
4
def foodAte(food): if food.lower() == "waffles": return "thats a nice breakfast" else: return "Ok sounds good"
c2d2b2e04cf5f85fffd1c9126dd3f30b36348dd9
metchel/poker
/test_hand.py
2,597
3.5
4
import unittest from hand import Hand, HandRanker, Rank from card import Card, Suit, Value class TestHand(unittest.TestCase): def test_royal_flush(self): ranker = HandRanker() cards = [ Card('S', 14), Card('S', 13), Card('S', 12), Card('S', 11), Card('S', 10) ] hand = Hand(cards) s...
a8d136117927b83dcc10cdb3b3470f1b9b46959b
Roshanbhuvad/Peewee--Python-MySQLite
/Insert_table/count_instances.py
600
3.546875
4
#To calculate the number of model instances in the table, we can use the count() method. import peewee import datetime db = peewee.SqliteDatabase('test2.db') class Note(peewee.Model): text = peewee.CharField() created = peewee.DateField(default=datetime.date.today) class Meta: database = db db_table = 'notes'...
70f41797d4b40cbebbf422a28f41083c2b98e60d
andrehmiguel/treinamento
/exercicioLista_EstruturaDecisao/ex27.py
1,121
4.0625
4
# 27. Uma fruteira está vendendo frutas com a seguinte tabela de preços: # ======================================================== # |Até 5 Kg |Acima de 5 Kg # Morango |R$ 2,50 por Kg |R$ 2,20 por Kg # Maçã |R$ 1,80 por Kg |R$ 1,50 por Kg # ===============================...
033102ee055525bc49f07beb1db77ea3eeb25cf8
Francois-Aubet/UCL_MSc_ML_code
/algorithms/Algorithm.py
567
3.59375
4
from abc import ABCMeta, abstractmethod import numpy as np class Algorithm(): """ The abstract parent class for all the algorithms. """ # we define the class as an abstract class: __metaclass__ = ABCMeta def __init__(self, dataset, meta_data): """ Constructor """ self._da...
8fe49f33d844a8da056321e24aeb2adeba87f5b3
erikac613/PythonCrashCourse
/3-9.py
151
3.65625
4
guests = ['geddy lee', 'john cleese', 'st. vincent', 'john lennon', 'kate bush', 'patrick stewart'] print("There will be a total of " + str(len(guests))) + " guests at dinner."
222ba51b9e8284415e506727cf070f626835d26c
KrushikReddyNallamilli/Python-100days-Challenge
/semoprime.py
495
3.9375
4
import math def checkSemiprime(num): cnt = 0 for i in range(2, int(math.sqrt(num)) + 1): while num % i == 0: num /= i cnt += 1 if cnt >= 2: break if(num > 1): cnt += 1 return cnt == 2 def semiprime(n): if checkSemipr...
70426b8a776ba3da815beedb3986acc356716d80
pbehnke/algorithmx-python
/algorithmx/graphics/types.py
1,892
3.609375
4
from typing import Dict, Union, Iterable, Callable, TypeVar, Any T = TypeVar('T') ElementFn = Union[Callable[[Any], T], Callable[[Any, int], T]] """ A function taking a selected element's data as input. This is typically provided as an argument in a selection method, allowing attributes to be configured differently f...
220090199640617a2c02e51d297ab72785429848
JakubKazimierski/PythonPortfolio
/AlgoExpert_algorithms/Medium/FindSucessor/FindSuccessor.py
1,971
4.1875
4
''' Find Sucessor from AlgoExpert.io January 2021 Jakub Kazimierski ''' class BinaryTree: ''' Write a function that takes in a Binary Tree (where nodes have an additional pointer to their parent node) as well as a node contained in that tree and returns the given node's successor. ...
7589c18be5f69b8bb6586946106740aa45a003b0
bagusdewantoro/datascience
/algebra_vector.py
3,452
3.5
4
vector = [ [0, 0], [2, 5], [1, 3], [3, 6], [5, 7] ] def jarak(v, w): return [vi + wi for vi, wi in zip(v,w)] Notes = """ 1. Perlu fungsi untuk bikin list vector: [0, 0], [2, 5], [3, 8], [6, 14], [11, 21] Caranya: - initial = vector[0] --> sama dengan vector[-1...
32007a58e18c39c534ab8fc46ddb6bf1388b079c
Kaciras/leetcode
/easy/Q26_RemoveDuplicatesFromSotredArray.py
447
3.6875
4
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: last, length = None, 0 for n in nums: if last != n: nums[length] = n last = n length += 1 return length if __name__ == '__main__': input_0 = [1, 1, 2] print(str(Solution().removeDuplicates(input_0)) ...
a1b9d0dd64a41d70b26953b83001fb798884b6fb
jmsevillam/Herramientas-Computacionales-UniAndes
/Homework/Hw5/Solution/problem1.py
1,132
3.921875
4
class Dog: def __init__(self,name,posx,posy): self.name=name self.posx=posx self.posy=posy self.awaken=False self.hungry=False self.counter=0 def awake(self): if self.awaken: print(self.name+' is already awaken') else: self....
4d1ba5f2ebe79eaabcf62c1f1f9c217ae5f57c46
marianac99/Mision-04
/ventaSoftware.py
1,274
3.953125
4
#Mariana Caballero Cabrera A01376544 # Programa que calcule el precio de software aplicando un descuento dependiendo de las unidades que se compren #Calcula el descuento dependiendo de las unidades compradas def calcularDescuento(unidades): descuento = 0 if unidades < 10: descuento = 0 ...
883b552320415f059fbd93a74ebd887ebac8d4ba
SEOULVING-C1UB/Daily-Algorithm
/Daily-Algo/2020-09-01 Stack2/Forth/권기현_forth.py
1,047
3.609375
4
import sys sys.stdin = open('forthinput.txt') def postfix_calculator(postfix): operand_stack=[] try : for i in postfix: if i == '.': result = operand_stack.pop() if operand_stack: return 'error' else: r...
5d448a9c7e65ed382ebe5a2079e84205c5c72a1a
jain-sasuke/guess-the-number
/guess.py
1,699
3.9375
4
from random import randint a = randint(1,100) i = 0 b = 0 #print(a) print ("WELCOME TO GUESS THE NUMBER!") print("I'm thinking of a number between 1 and 100") print("If your guess is more than 10 away from my number, I'll tell you you're in COLD zone") print("If your guess is within 10 of my number, I'll tell you you'r...
7397236e0699ab3080f3bbe78ddbe2230cb7644c
chrisxue815/leetcode_python
/problems/test_0605.py
648
3.59375
4
import unittest from typing import List import utils # O(n) time. O(1) space. Array. class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if n <= 0: return True prev = -2 for i, planted in enumerate(flowerbed): if planted: ...
9b707d4eea3a5b3c734f2303cbcc6d464468a58f
LivInTheLookingGlass/python-go
/Go/stone.py
12,092
3.75
4
class stone(): def __init__(self, color, left=None, right=None, up=None, down=None, board=None, coord=(None, None)): self.color = color if color == 'white': self.opposite_color = 'black' elif color == 'black': self.opposite_color = 'white' self.left = left ...
f2328184b234a87a3fd33a15ed7fc1ea96cc4eea
sangeethadetne/python
/List.py
818
4.0625
4
lucky_numbers = [4,64,7,76,35,55,] friends = ["John","Shawn","Shandy","Toby","Shandy","Shandy"] friends.extend(lucky_numbers)# add the list to another list friends.append("Sangeetha")# add the elements to the list friends.insert(3,"Geetha")# Inserts the elemenst at specified position friends.remove("Shandy") lu...
c66decef915c66471943540e932f8b792cc58f8c
AntonBrazouski/thinkcspy
/12_Dictionaries/12_03c.py
308
4.0625
4
# dictionary methods inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(list(inventory.values())) print(list(inventory.items())) for (k, v) in inventory.items(): print("Got", k, "that maps to", v) for k in inventory: print("Got", k, "taht maps to", inventory[k])
aea008976cc88f6440a638929cfe7b1b67b2f0c4
acpark22/daily_challenges
/louis/1/i.py
2,075
4.59375
5
""" [intermediate] challenge #1 create a program that will allow you to enter events organizable by hour. There must be menu options of some form, and you must be able to easily edit, add, and delete events without directly changing the source code. (note that by menu i dont necessarily mean gui. as long as you...
00dfaf61555b394cab271f7a13188071d7b5cdcd
ssarangi/algorithms
/epi/primitive_types/5_3_convert_base.py
1,570
3.609375
4
""" The MIT License (MIT) Copyright (c) <2015> <sarangis> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,...
b32fd9516002b2a6de870b756c21c73a7040cc66
mahimadubey/leetcode-python
/add_binary/solution3.py
968
3.625
4
""" Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". """ class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ a = a[::-1] b = b[::-1] m = len(a)...
58604ef760280489bdcaf8d87899bf171545d5d5
DeborahPerez/CrackingTheCodingInterviewPython37
/unique.py
2,313
4.0625
4
############################################################################### # USAGE: # python3.7 isUnique.py # DESCRIPTION: # 1.1 Is Unique # Implement an algorithm to determine if a string has all unique # characters. # Input:...
639e743d95636e20520455551f36aea7f8aa682e
ricwtk/misc
/202003-ai-labtest-results/Submissions/17003906.py
2,659
4.03125
4
""" Lab Test (AI CSC3206 Semester March 2020) Name: Leong Wen Hao Student ID: 17003906 """ import pandas as pd from sklearn import datasets import matplotlib.pyplot as pt # import glass.csv as DataFrame data = pd.read_csv("glass.csv", names=["Id", "RI", "Na", "Mg", "Al", "Si", "K", "Ca", "Ba", "Fe", "G...
e368ddf25aeb3e4b9be7e164159beab2e46c07b9
KindleHsieh/OOP_book_practice
/test.py
683
3.828125
4
class ContactList(list): def search(self, name): matching_contacts = [] for contact in self: if name in contact.name: matching_contacts.append(contact) return matching_contacts class Contact: all_contacts = [] def __init__(self, name, email): sel...
65615746f0d749f4f973b74a3dae8db2fbb3c003
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3999/codes/1635_1053.py
310
3.828125
4
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. nome=input() if(nome=="cervo"): mensagem="cervo eh patrono do Harry Potter" else: mensagem= nome + " nao eh patrono do Harry Potter" print(mensagem)
6ee5d13936c0f734d8a865143abf75516278cd6e
sudhi76/data-analysis
/linearregg.py
1,232
3.671875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 4 22:29:22 2019 @author: DELL """ #importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataset df = pd.read_csv('Salary_Data.csv') x = df.iloc[:,:-1].values y = df.iloc[:,:1].values #spliting the dat...
0d270bc70a7f87849cd883666ebf2783b7cfb6a6
YoungXueya/LeetcodeSolution
/src/113. Path Sum II.py
819
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: return [] res=[] path=[r...
51ab9add6264d68996a00d8c3f5545f40377ca4b
PramodShenoy/Competitive-Coding
/Hackerrank/Code-Heat/card.py
642
3.5625
4
def subset_sum(numbers, target, partial=[], partial_sum=0): if partial_sum == target: yield partial if partial_sum >= target: return for i, n in enumerate(numbers): remaining = numbers[i + 1:] yield from subset_sum(remaining, target, partial + [n], partial_sum + n) cards = l...
23d644e8e6fc486ad64b254266b5dca0a452b8c2
vrrp/Workshop2018Python
/Modulo1/proyectos/fibo.py
330
3.890625
4
# Módulo de números Fibonacci def fib(n): a,b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print("se ejecuto fib") def fib2(n): a,b = 0, 1 resultado = [] while b < n: resultado.append(b) a, b = b, a+b print(resultado) return resultado if __name__ == "__main__": import sys fib2(int(sys.ar...
17187d5cb148361d83e1e5957f9c886d54ee1c7e
ammar-assaf/Assignment2
/Logic-1/date_fashion.py
134
3.796875
4
def date_fashion(you, date): if date<=2 or you<=2: return 0 elif date >=8 or you >=8: return 2 else: return 1
bf0fa5169c55b45d38fde41c8f26f750187e4e50
YQ-7/code-interview-guide
/c5_string/trie.py
2,327
3.953125
4
import unittest class TreeNode(object): """ 搜索树节点,存储a~z """ def __init__(self): self.path = 0 # 记录元素 self.end = 0 self.map = [None] * 26 class Trie(object): """ 搜索树 """ def __init__(self): self.root = TreeNode() def insert(self, word): ...
5b9e36ef2de411d02b83cc8c4c597aad4e26d71c
Jigar710/Python_Programs
/Matplotlib/with_pandas/p2.py
377
3.875
4
''' with dataframe bar plots group the values in each row together in a group in bars, side by side, for each value''' from matplotlib import pyplot as plt import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(6,4), index = ['one','two','three','four','fifth','sixth'], columns = pd.Index(['A','B','C'...
b40c682fd49d588029b81d5df9a70a5a5f876138
Ashoksugu7/DSA
/Leetcode/Thousand_Separator.py
704
3.734375
4
""" Thousand Separator User Accepted:0 User Tried:0 Total Accepted:0 Total Submissions:0 Difficulty:Easy Given an integer n, add a dot (".") as the thousands separator and return it in string format. Example 1: Input: n = 987 Output: "987" Example 2: Input: n = 1234 Output: "1.234" Example 3: Input: n = 12345678...
1963fae6757386a237aa54ecca1edb4640b0c206
Victor-GuilhermeCN/LibrarySystem
/db.py
2,178
3.71875
4
import pymysql class Databank: def __init__(self): """This function starts the Databank class""" self.con = pymysql.connect(user='root', passwd='') self.cursor = self.con.cursor() def database(self): """This method creates the database, and selects it.""" try: ...
cb132d73d5ef2e32f2eea86bf2ded2641137a9d3
subashinie/my_captain_assignment2
/dictionary.py
589
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Aug 20 12:48:38 2021 @author: suba """ car={"brand":"ferrari", "horsepower":"812", "torque":"718Nm", "year":"2021"} a=car.copy() print(a) x=('Ford','BMW','RR') y='5' cars=dict.fromkeys(x,y) print(cars) X=car.get("torque") print(X) ...
3987695eb8fb31dff3ec8f128f40909cb5b144a8
tekiegirl/SafariPython
/main.py
1,027
4.03125
4
print("Hello Python World!") print('"Hello" Python World!', 99, "is the count", sep="**", end="") print("next") x = "123" print(x) print(type(x)) print(x + str(99)) print(int(x) + 99) x = 99 print(x) print(type(x)) x = 12.34 print(x) print(type(x)) # IEEE 754, 64bit E+-308 x = 1000000000 print(x) x = x * x * x * ...
0c963837e0b9bca82b325edc2ebbb3c36b192f67
BuiltinCoders/PythonTutorial
/oops concept practice/operator overloading & dunder methods.py
1,318
4.46875
4
# Defining a method for an operator and that process is called operator overloading. # Operator overloading refers to setting up the functionality of perticular operator for perticular situation. # Operator in python can be overloaded using dunder method. # These methods are called when a given operator is used on the ...
bf704913638de1851f89c56d5703458e8c240540
sanket17/python_basic
/conditionalStat.py
161
3.953125
4
lang = 'Python' print(lang) if lang == 'C': print('C Language') elif lang == "Python": print('Python Language') else: print('Programming is great')
7a4bf2bc945c0a0a57c9fb2df372d394c6f2589a
informramiz/Route-Planner
/astar/student_code.py
2,681
3.5625
4
import math import math from queue import PriorityQueue from helpers import Map def shortest_path(M: Map, start, goal): if start == goal: return [start] intersections_count = len(M.intersections) is_frontier = [False for _ in range(intersections_count)] is_explored = [False for _ in range(inte...
05f734d4d17962e6ff9ff4ca11b4b6e3794c47e6
connorKeir/cp1404practicals
/prac_05/hex_colours.py
714
4.25
4
HEX_COLOURS = { "aliceblue": "#f0f8ff", "aquamarine1": "#7fffd4", "black": "#000000", "blue2": "#0000ee", "chartreuse1": "7fff00", "coral": "#ff7f50", "cornsilk3": "#cdc8b1", "cyan1": "#00ffff", "darkgoldenrod": "#b8860b", "darkviolet": "#9400d3" } def main(): """search for...
334d3ff75a8e3c9a7cf76a429309cd7ecf37fdbb
ruidge/TestPython
/Test/tips.py
382
3.734375
4
#格式化 print('Age: %s. Gender: %s' % (25, True)) r = 2.5 s = 3.14 * r ** 2 print(f'The area of a circle with radius {r} is {s:.2f}') #if的判断 x = 0 # x = "" # x = None # x = 'None' # x = -1 if x: print('True') else: print('False') #for的判断 sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x print(...
19bec2ede7abe5a1498f327d6549f6d149a53e84
TomasBalbinder/Projekty
/natural_numbers.py
841
4.15625
4
''' Create a program who writte how many units, tens, hundreds and thousands make up the nubmer on the input input: natural number output: numbers of units, tens, hundreds, thousands 1. read input value 2. calculation 3. output ''' natural_numbers = int(input("Enter the number: ")) output = natur...
59c5c9c8385bde699eb12b9506176e6065fdbb4f
ankit-rane/Travel-Hack
/ticket-booking.py
2,349
4.09375
4
global f f = 0 # this t_movie function is used to select movie name def t_movie(): global f f = f + 1 print("which country do you want to visit?") print("1. India ") print("2 The United States of America ") print("3. The United Kingdom") print("4 Back") movie = int(input("...
c1fdfbed8315f7d91fbd700a4180eaedabf56713
leigh93/100daysofPython
/day25/theory.py
1,560
3.953125
4
import csv # with open('weather_data.csv') as file: # data = file.readlines() # print(data) # with open('weather_data.csv') as data_file: # data = csv.reader(data_file) # print(data) # temperatures = [] # new_list = [] # for row in data: # if row[1] != 'temp': # temperat...
8963f474badec9e241792169c167d28123ea0495
joshf26/CU-Boulder-Computer-Graphics-Club-Image-Compression-Talk
/image_helper.py
4,432
3.640625
4
import PIL.Image import PIL.ImageDraw import PIL.ImageFont # Note: This was only tested on Ubuntu 18.04. You may have to modify this to # point to an existing font file. FONT_PATH = '/usr/share/gazebo-9/media/fonts/arial.ttf' FONT = PIL.ImageFont.truetype(FONT_PATH, 32) def convert_to_image(path): """ Give...
1a4f848078b71002fc49023e03238a120ada1e30
ilee38/practice-python
/coding_problems/CTCI_sorting_searching/group_anagrams.py
551
3.9375
4
#!/usr/bin/env python3 """ Problem 10.2 from CtCI book """ def group_anagrams(A): if len(A) == 0 or A is None: return None word_map = {} key = '' for word in A: key = ''.join(sorted(word)) #the sorted() built-in function returns a list, so if key not in word_map: #it needs to be converted ...
735a43a3a66b7c4ca13f225f080a8618fb8d8604
maxbergmark/old-work
/Egna projekt/Bella/read_word.py
249
3.90625
4
f=open("ordlista.txt","r") s=f.read() l=s.split("\n") avg=(len(s))/(len(l)) print(len(l),avg) total_letters=0 for word in l: total_letters+=len(word) avg2=total_letters/(len(l)) print(avg2) print(sum([len(word) for word in l])/len(l))
c3464cb644fef6d9e179afe13c8e13e9145d91a7
jbbarrau/problems
/balls/balls.py
1,504
4.0625
4
# http://www.careercup.com/question?id=5145121580384256 # n is the number of balls (n = 3^d) # Time: O(log n) - Space: O(n) class BallSet: def __init__(self,ballset): #ballset is list of 81 weights #the index is the identifier of the ball # 81 = 3 * 3 * 3 * 3 self....
d440e2fec4521eef14d6129a17a0f3659ebcd0ca
britannica/euler-club
/Week5/euler5_sbosco.py
707
3.640625
4
# euler 5 from functools import reduce def primes(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) n //= d d += 1 if n > 1: primfac.append(n) return primfac def insertprimes(allfacs, primfacs): for j in allfacs: ...
784cefab02bc27c36acf866e2b1466c2839290c1
gaurav613/Pygames
/CarRacing/main.py
7,093
3.53125
4
import pygame import time, random pygame.init() #basic window creation - width and height for dynamic reference display_width =800 display_height = 600 #rgb color codes BLACK = (0,0,0) WHITE = (255,255,255) GREEN = (0,200,0) RED = (200,0,0) LIGHT_RED = (255,0,0) LIGHT_GREEN = (0,255,0) GREY = (119,136,153) PURPLE = (...
3d28564441795c156583bb04ecefb5f2db846daa
duckworthd/configurati
/configurati/loaders/utils.py
698
3.671875
4
import code import re def substitute(s): """Contents of `...` evaluated in Python""" if isinstance(s, basestring) and s.count("`") == 2: match = re.search("""^`([^`]+)`$""", s) contents, rest = match.group(1), s[match.end():] return evaluate(contents) else: return s def evaluate(line): """Ev...
cac00dcb55e873a0dfa413924a1cd97ae96f51b6
AlliotTech/python-scripts
/Learnpy/network/tcpWeb/objWeb.py
3,674
3.578125
4
# -*- coding:utf-8 -*- # 第6个. # 使用面向对象思想进行封装. # 目标: 能够使用面向对象思想,对web服务器进行封装. """ 1. 功能分析 - 使用面向对象思想进行封装. - 通过对象方法start(),启动web服务器. 2. 实现思路 - 创建HttpServer类. - 创建HttpServer类的构造方法,并在构造方法中对tcp_server_socket创建初始化. - 创建start()方法,用来web服务器启动。 """ import socket import os class WebServer(object): # 初始化方法 de...
cce8918ab3d3a05a1750a8e02f8cfeb0e3742386
GrishaAdamyan/All_Exercises
/To read and sort the table.py
969
3.59375
4
#row = int(input()) #col = int(input()) #table = [[input() for j in range(col)] for i in range(row)] #for i in range(len(table)): #if i == 0 or i == len(table)-1: #print('\t'.join(table[i])) #else: #for k in range(len(table[i]) - 1): #for j in range(len(table[i]) - 1 - k): ...
e1aa8c198dead18462c19d2bb94fd498198e8b9f
michalwojewoda/python
/Exercises/Coding Bat/Warmup-1.py
3,132
3.890625
4
# Given an int n, return True if it is within 10 of 100 or 200. # Note: abs(num) computes the absolute value of a number. def near_hundred(n): return ((abs(100-n) <=10) or (abs(200 - n) <=10)) #The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in i...
0214e7527bab7f7725454ad0ab6e3bf90893ffae
LucaMarconato/deutsch
/dienstprogramme.py
536
3.5
4
# von https://stackoverflow.com/questions/2460177/edit-distance-in-python def levenshtein_distanz(s1, s2): if len(s1) > len(s2): s1, s2 = s2, s1 distanzen = range(len(s1) + 1) for i2, c2 in enumerate(s2): distanzen_ = [i2 + 1] for i1, c1 in enumerate(s1): if c1 == c2: ...
710c1cd0280831e99f04600793bdbe1b1ba736aa
sunnytake/CodeAndDecode
/左神/初级班/第二课/二叉堆.py
1,694
3.90625
4
# coding=utf-8 ''' 小顶堆 ''' def upAdjust(array): ''' 上浮调整 ''' child_index = len(array) - 1 parent_index = (len(array) - 1) // 2 # temp保存插入的叶子节点值,用于最后的赋值 temp = array[child_index] while parent_index >= 0 and temp < array[parent_index]: # 无需真正交换,单向赋值即可 array[child_index] = ...
00c157ee0b3b97bc0477c3752339dc695302b725
Nubstein/Python-exercises
/Strings/Ex6_strings.py
832
4.21875
4
#Data por extenso. Faça um programa que solicite a data de nascimento # (dd/mm/aaaa) do usuário e imprima a data com o nome do mês por extenso. meses_ext= ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"] data=input(" Insira uma data em fo...
d70e58a2040642b2875e75a520b9ca35d890c9d6
mippzon/python-mini-projects
/practice-python/08-rock-paper-scissor.py
218
3.65625
4
print('Welcome to the Rock Paper Scissor game!') player_points = 0 computer_points = 0 possible_actions = ['rock', 'paper', 'scissor'] player_action = int(input('Enter 1 for Rock, 2 for Paper or 3 for Scissor: '))