blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b4738087d00e2b650dc222c2c9f4aa25243064be
SanJin1213/Python
/Numpy/code/attribute_numpy.py
319
3.984375
4
import numpy as np # 将列表转化成数组 array = np.array([[1, 2, 3], [2, 3, 4]]) print(array) # ndim 代表是几维数组 print("number of dim:", array.ndim) # shape 代表数组的行数和列数 print("array shape:", array.shape) # size 是代表元素的个数 print("size:", array.size)
72c5cb8ac57eb705c656c0476538563bed9701d5
mihaelacr/ProjectEuler
/Problem38.py
1,619
3.90625
4
import itertools # Define "concatenated product" * between # an integer and a sequential tuple of digits as # y = x * (1,2,...n) = x | 2x | ... | nx # where | is digit concatenation # and we want to find the largest y # that is 1-to-9 pandigital (assume n>1) def tuple2int(t): return int("".join(map(str, t))) de...
70ffa35edddf738a2b4b213203cb97ad8a70437e
mihaelacr/ProjectEuler
/Problem17.py
880
3.640625
4
#!/usr/bin/env python2 units = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tweens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "nine...
18c4da8961e17726c585e2ad241a2dcaf180e97c
mihaelacr/ProjectEuler
/Problem20.py
1,215
3.765625
4
#!/usr/bin/env python2 # Functions for doing arithmetic based on ASCII values # so we do not have to rely on Python's arbitrary precision def add(v1, v2): v1 = str(v1) v2 = str(v2) # Pad with 0s so strings same length maxw = max(len(v1),len(v2)) v1 = v1.rjust(maxw,'0') v2 = v2.rjust(maxw,'0') ...
1326d9a3a01a350c157bda784c657eabb4c25638
mihaelacr/ProjectEuler
/Problem66.py
3,140
3.65625
4
import math from fractions import Fraction from itertools import islice import numpy as np # We want to find integer solutions x,y to # x**2 - D*y**2 = 1 # for minimal x and # for non-square integer D, 2 <= D <= 1000 # # and then find the D which gives maxium x # # this is Pell's equation # https://en.wikipedia.org/wi...
6097bd526959bb3f4d52d80c2411c3491d51ddb3
Blake-Latchford/nine_men_morris
/move_test.py
8,881
3.734375
4
import unittest from board import Board from move import Move class TestEquality(unittest.TestCase): def test_equal(self): board = Board() first = Move(board, (0, 0)) second = Move(board, (0, 0)) third = Move(board, (0, 1)) self.assertEqual(first, second) self.ass...
246230d338d105ac5c2b85f151a63818d8b890a7
1gn1z/Python_Ejercicios
/ex005_cadena_inversa.py
824
4.40625
4
# Ejercicio 5. Obtener la representacion inversa de una cadena de caracteres #cadena = input('Ingresa la cadena: ') #print(cadena[::-1]) # Lo logré sin ver el tutorial :3 <3 # De aquí pa' abajo el codigo del tutorial. # Con un ciclo for iteraremos la cadena cadena = 'Python' # Con RANGE definimos que empiece desde...
6ed63eafc7c885e0a192285467174b3c53fa8cec
LihameA/GWC-stuff-
/DataVisualizationproject/data_vis_project_pt1.py
3,501
3.84375
4
''' In this project, you will visualize the feelings and language used in a set of Tweets. This starter code loads the appropriate libraries and the Twitter data you'll need! ''' import json from textblob import TextBlob import matplotlib.pyplot as plt from wordcloud import WordCloud #Get the JSON data tweetFile = op...
edb64895bedb65d7507d25946b1b1916475c2018
sachuverma/Software-Testing
/Eqv Partitioning/houses/houses.py
2,913
3.828125
4
# import math # error classes from errors import OutOfRangeError from errors import TypeError # checks if variables are in range # if variables not in range then OutOfRangeError is raised def checkCodeRange(code): if code < 11111 or code > 99999: raise OutOfRangeError('Code is out of the given range') def checkA...
2c3de822da3d30e84eaa9cfc87c17ee6ac69fa0d
rockypta/simplePendulumn
/MergeSort.py
2,869
3.65625
4
# Merges two subarrays of arr[]. # First subarray is arr[l..m] # Second subarray is arr[m+1..r] def merge(arr, leftArrStart, lefArrEnd, rightArrEnd): leftArrSize = lefArrEnd - leftArrStart + 1 rightArrSize = rightArrEnd- lefArrEnd # create temp arrays # Copy data to temp arrays tempLeftArr[] an...
089fa9e1c0ee670d2802a0bf2637201b5dca1198
316141952/Practica02
/Codigos/Ejercicio03F.py
1,188
3.984375
4
# -*- coding: utf-8 -*- #Funciones del ejercicio 3 def ubicacion (letrita, palabrita): '''Verifica si una letra se encuentra dentro de una cadena''' P = list(palabrita) for i in range(len(P)): for P[i] in P: if letrita == P[i]: return True def posicion (letrita, pala...
bb9a588598b54932d51fff87de0b79a4c6a74432
aviidlee/AutomateBoringStuff
/Regex/phone_email_extractor.py
1,685
3.5625
4
#! python3 # # Code partly taken from: https://automatetheboringstuff.com/chapter7/ # # Find all phone numbers and emails addresses in clipboard contents, then paste # extracted content back into clipboard. import pyperclip, re, string phoneReg = re.compile(r'''( (\+\d{1,3})? # Optional country code (\s|-|\.)...
36947f18d2dec9a62b54fd5a6e9266f150edfb1f
ndrbrt/pymine-engine
/pymine/game.py
5,922
3.5625
4
from typing import Union, Optional, List import time from .board import Board, Cell, Status from enum import Enum class Outcome(Enum): WIN = 1 LOST = 2 class Game(): def __init__(self, rows: int, cols: int, number_of_bombs: int) -> None: self.rows = rows self.cols = cols self.num...
3323fad56341d79a0c4ed2b141ca0d96a82955dd
nirajkumar27297/Spark-Scala
/stockprediction/pythonFiles/StockPricePrediction.py
1,439
3.9375
4
""" The objective is to take input from a standard Input,create a dataframe from that Load the LinearRegressionModel which we have dumped earlier and predict the Close Price and return it using Standard Output Library Used - 1> pandas [For Creating DataFrames] Version - 1.1.2 2> pickle [For Dumping Model] Version -...
66f5c2a7c49fa36d5d8650f6dc29cbce47e4b1cc
CodecoolBP20172/pbwp-3rd-si-game-statistics-DanielKnoll
/part2/reader.py
5,429
4.03125
4
import sys import datetime def read_file(file_name, simple_string_is_enough): """Reader with input error handling. It can return two different type from the file because for some questions a simple string is enough to work with.""" try: with open(file_name) as file: preferences_str...
eca549a0d86e1b696c2f01b3b8a0149beaaf3321
mehdishirazi/restfulpy
/restfulpy/utils.py
2,803
3.5625
4
import importlib.util import re import sys import warnings from hashlib import md5 from os.path import dirname, abspath def import_python_module_by_filename(name, module_filename): """ Import's a file as a python module, with specified name. Don't ask about the `name` argument, it's required. :param...
9aed27fb3e36b56c47ec06f8b5e7bc084d7459b7
KumarHalder/BattleSink
/player.py
2,496
3.734375
4
class player: #init def __init__(self,name, health=3): self.name = name self.opponentBoard = [[0 for i in range(8)] for j in range(8)] self.opponentShipCoordinates = [] self.opponentHealth = health #Place ship for opponent player def placeShip(self,x:int,y:int,isHorizon...
eab2366f4e02d32f72e65168d4e0ecc82a959ebc
ospluscode/Sort
/quickSort.py
1,046
3.984375
4
# Quick Sort takes a random pivot and then places it as # all the smaller elements are on left and greater elements are on the right # then the choosing pivot and moving elements continues recursively # Unlike Merge Sort Quick doesnt require extra space # TC: O(NlogN) - division by half # SC: O(N) # Helper method # ...
f48e5ea192d223895808417ebf97fb3131e58b35
etscrivner/dse
/lib/display_table.py
3,258
3.828125
4
# -*- coding: utf-8 -*- """ lib.display_table ~~~~~~~~~~~~~~~~~ Reusable module that will display a nicely formatted table. DisplayTable: Interface for display data in a nicely formatted table. """ import sys class DisplayTable(object): """Displays a nicely formatted table to standard output ...
ebf8caaa3359bad44f356431f14e91040efd4ef5
etscrivner/dse
/bin/2B.py
5,967
4.28125
4
# -*- coding: utf-8 -*- """ 2B ~~ The PSP Exercise 2B Program. Modify program 1B to allow for addition and modification of values from a file. prompt_for_output_file(): Prompt a user for an optional new file name. read_file(): Read and display the contents of the given file. write_file(): ...
da13dea256a7589f7b9e2e176b218fe8852943b8
etscrivner/dse
/bin/9A.py
1,678
3.96875
4
# -*- coding: utf-8 -*- """ 9A ~~ PSP Exercise 9A, perform the chi-squared test on given data. Application: The application entry point """ from lib import chi_squared from lib import io class Application(object): """Request a CSV file from the user containing data to be tested. Then perform ...
e661be38d8e3736c64f0762eca0325b67fbe6a78
AhmadChaiban/Data-Science-Engineering-Capstone
/AWS_Tools/Archived/s3_zip.py
1,133
3.875
4
from zipfile import ZipFile import os from os.path import basename from misc import user_feedback def create_zip_file(path, zip_name): """ Creating a zip file for each category :param path: the path of the folder to be compressed :param zip_name: the name of the output zip file :return: None ""...
9721712b31f55d2e1e1ac92d445f899bd42db112
azizsm6/python
/Example-Login.py
408
3.515625
4
from datetime import * def login(): today = datetime.today() print (today) print ("hello admin your info : ") print ("root") print ("12345") def loginx(): print ("n1ce try :)") def xxx(): user = input("username : ") password = input("password : ") if user == 'admin' and p...
88f8fc96f2020d1429f084abac627b5751375ce5
wenses/ASC
/main.py
756
3.609375
4
import tkinter from tkinter import * from tkinter import messagebox win=Tk() win.geometry('700x500') win.title('KIDESHENIS STOCK CARE SOFTWARE') #win.resizable(FALSE,FALSE) #win.config(bg='dark grey') font_text=('Cambria',25,'bold') title_text="KIDESHENI'S STOCK CARE" title_label=Label(win,text=title_te...
4b14ec9b5335858a8c5ecbfcfffe178459be550e
srread12/MasterMind
/MasterMind.py
7,987
4.21875
4
import csv from random import randrange from datetime import datetime def user_comp_num(comp_num2): comp_num2.clear() while True: print("What is the number you want the ai to solve.") num = input() if num.isdigit() and len(num) == 3: break elif len(num...
6b86c196cacfc4867d92349b2084713cc1ce7aea
reialfrl/Basic_exercises
/centigrados_fahrenheit.py
632
3.890625
4
if __name__ == "__main__": #Función para convertir los grados centigrados ingresados por el usuario a grados fahrenheit def grados_fahrenheit(): try: centigrados = float(input('Ingrese la cantidad de grados centigrados que desea convertir: ')) if centigrados <= 0: ...
e08066d033f52b374a856cde616ccb7e0bc098f4
reialfrl/Basic_exercises
/10.volumen_esfera.py
231
3.921875
4
from math import pi def volumen_esfera(): r = float(input('Ingrese el radio de la esfera: ') ) volumen = 4/3 * pi * r **3 return print('El volumen de la esfera es {:.2f} unidades cúbicas'.format(volumen))
dd2e06f08c3d7548945a4778440c26d1f67bf9cf
reialfrl/Basic_exercises
/fibonacci.py
200
3.765625
4
def fibonacci(max_number): start, next = 0, 1 serie = [] for _ in range(max_number): serie.append( start + next ) start, next = next, serie[-1] return serie
2000c62cf1d61e4e41b5b6a9d9a5f2e71595d494
kykel/ForbiddenQuest
/bosses.py
3,090
3.578125
4
#Bosses import random, sys class monster(): def __init__(self,name,hp,dmg): self.name = name self.hp = hp self.dmg = dmg class Helga(monster): name = "Grand Witch Helga" hp = 45 dmg = random.randrange(5,15) def __init__(self): pass ...
e295e28c719ea0310c2f1448dbafa63f950c528c
edtjguillamon/SMXISM2016
/M03/Ejercicio-edades-3.py
197
3.515625
4
#Ejercicio-edad-3: #coding utf-8- edad =input("Introduce tu edad: ") if (edad >=18 and edad<=23) or edad==17: print "Adelante, controla tu cubata!!" else : print "No cumples la edad, fuera :/"
c906e331ee55f5cdec7ccf65c8fb160454a518c2
a10aquafina/dat-c4e28-fundamentals
/selection1/turtle_intro.py
202
3.75
4
from turtle import * speed(0) shape('turtle') # for i in range (2): # for j in range(4): # forward(100) # left(90) # right (23) circle (200) mainloop()
7d4794e3d6bc6217d755363fa19bfcda28f87b57
a10aquafina/dat-c4e28-fundamentals
/4-3-2019/ship.py
641
3.515625
4
x=[5,7,300,90,24,50,75,100] print(*x,sep=",") c=list(x) b=max(list(x)) print("the biggest ship",b) month=0 y=int(input("enter the number of month ")) month=month+y x[0]=x[0]+50*y x[1]=x[1]+50*y x[2]=x[2]+50*y x[3]=x[3]+50*y x[4]=x[4]+50*y x[5]=x[5]+50*y x[6]=x[6]+50*y x[7]=x[7]+50*y if x[0]>300: ...
78bd813bcbe5a7ea2c2052da8139cf8774971012
dcsheive/Python-OOP
/Store.py
1,121
3.515625
4
class Store: def __init__(self, location, owner): self.location = location self.owner = owner self.products = [] def addProduct(self,price,name,weight,brand): self.products.append([price,name,weight,brand]) return self def removeProduct(self, name): for i in r...
813f6d3082c287192ea83b0a327958cf4c57f9e6
gilberto233/Show-me-the-code-project-used
/Illegal_word_crawler/Source/main.py
2,271
3.953125
4
""" Script being used to check out if the input stream has specify words from filter file. When these words are found, relative message will show in the screen. After these procedure the input stream will be hand in to __examinate_and_substitute__() function. The illegal words will be substituted with '*' characters wh...
77cee1eae648b4d90ce87bfd203332c8f49fd0c8
Mb01/Code-Samples
/algorithms/sorting/heapsort.py
1,886
4.25
4
#!/usr/bin/env python import random LENGTH = 100 data = [random.randint(0,100) for _ in range(LENGTH)] def heapsort(lst): def swap(lst, a, b): """given a list, swap elements at 'a' and 'b'""" temp = lst[a] lst[a] = lst[b] lst[b] = temp def siftdown(lst, start, en...
7a77ec4dc432b6f9375f977bd6d6b354ee59ca3a
asdarov77/ozonacademy
/task5.2.polindrom.py
480
4.0625
4
# -*- coding: utf-8 -*- """ В данном примере будем под палиндромом понимать так называемый зеркальный вариант # -*- coding: utf-8 -*- """ def is_palindrome(string): if string == string[::-1]: return True string=input('Введи строку для провери: ') if is_palindrome(string)==True: print('Строка', stri...
e02e83c6c26a6e38a6451a1f2fff180be829c9d2
krei/scripts
/dectobin.py
255
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- decimals = int(input("Введите натуральное число: ")) binars = "" while decimals > 0: y = str(decimals % 2) binars = y + binars decimals = int(decimals / 2) print(binars)
e463fcffad1f2af8a5b41fd3697ef343bf8ce903
krei/scripts
/fac.py
214
3.796875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- n = input("Факториал числа ") n = int(n) factorial = 1 i = 0 while i < n: i = i + 1 factorial = factorial * i print("равен ", factorial)
4afd9878f63f0754215bbebf37fcc9b6b0ea0bf3
karlmoller/challenges
/freshplum/palindrome_number.py
348
3.640625
4
# resources: # python documentations http://docs.python.org/2/library/itertools.html#itertools.permutations from itertools import permutations def next_palindrome_num(num): ret = num while True: ret = ret + 1 if tuple(str(ret)) in permutations(str(num)): return ret # test print ...
352415a82f8a1e96f9b073ded163ed3f04047d3c
nobbynobbs/devman-async-python-4
/minechat_client/observer.py
1,133
3.734375
4
import abc """ Я видел в описании к заданиям, что не надо делать сложно и изобретать абстракции, но без этой штуки "логировать" в файлик несвязанные процессы установления соединения и чтения из сокета было очень неудобно и некрасиво. """ class Observable(abc.ABC): def __init__(self, subscribers=None): if...
e000a8ffedc49d85e04512b56e8e2e9c757f0593
amanda-ciampa/Piano-Virtuoso
/PianoInput.py
3,204
4.1875
4
""" Created by Amanda Ciampa, 2017 - Senior Thesis Project, Endicott College Piano Virtuoso - Educational video game to teach piano lessons. PianoInput.py - Used to read in input from MIDI controller > Initializes pygame.midi - MIDI controller device # is 1 if plugged in. Otherwise 0. - Controls th...
2a5d9f27f41c54d5cb71c3ef3e15ed7fc024f046
brucewlee/pushingonreadability_traditional_ML
/calculate.py
445
3.796875
4
import pandas as pd number_list=[10,20,30,40,50,60,70,80,90,110,120,130,140,150] def calculate(number): df = pd.read_csv("Research_Data/weebit"+str(number)+".0.test.csv") total_correct = sum(df['Grade'] == df['bert.2.pred']) total_passage = len(df['Grade']) print(total_correct) print(total_passage...
01c6b81665be2b66f442b12c9af6ba63b4a40fe3
oldblackwang/DataAnalysis
/生成数据/绘制简单的折线图.py
673
3.671875
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 19 14:40:10 2018 使用plot()绘制简单的折线图 @author: lenovo """ import matplotlib.pyplot as plt # 模块pyplot包含了很多用于生成图标的函数 input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.plot(input_values, squares, linewidth = 5) # linewidth决定绘制线条的粗细 # 设置图标主题,并给坐标轴加上标签 plt.title...
1a878b8075e88fe478cc709c9d4dce7123298a58
JacobPimental/TA505
/unpack_sample.py
5,883
3.6875
4
import r2pipe import struct # Global variables used in the check function var_1 = 0 var_2 = 0 rol = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) def tohex(x): return (x + (1 << 32)) % (1 << 32) def check(data, i): ...
a66fb357650a8ed9e9e2e6ab206e7ddf6c1c4ecc
Sirrie/112work
/homework10/# connect4.py
4,066
3.6875
4
# connect4.py # This code was developed in recitation on Fri 7-Oct-2011. # As such, it may not contain perfect style, and may # even contain a small bug here or there (usual disclaimer). # A simple game of connect4 with a text interface # based on the wordSearch code written in class. def playConnect4(): rows = 6...
9a0f95fb95259af5228bcb0df7dacc39dce3b4e9
Sirrie/112work
/homework4/#hw4solution.py
967
3.59375
4
#hw4 solution def findZeroWithBisection(f,x0,x1,epsilon): if(f(x0)==0):return x0 if(f(x1)==0):return x1 if(f(x0)*f(x1)>=0):return middle = (x0+x1)/2.0 fMiddle= f(middle) while(abs(x0-x1)>epsilon): if (f(x0)*fMiddle<0): x1=middle else:# zero between middle and x1 x0 = middle middle = float(x0+x1)/2 ...
a8bf11ed5c064622a0f20c46030ed509e9647f48
Sirrie/112work
/homework6/otherisola.py
5,360
3.890625
4
def make2dList(rows,cols): a =[] for row in xrange(rows): a+=[[0]*cols] return a # make a 2dList with all inital value of 0 def getMove(board,player): #print the board first print "\n*******************" printBoard(board) while True: prompt = "Enter mover for player"+ getPlayerL...
9675aac0fd4ab0fe8a73a63f5dce8e5750c1b80c
Sirrie/112work
/termProject_backup_copy/gamePart/faceDemoWithStruct.py
2,369
3.71875
4
# faceDemoWithStruct.py # face module used by modulesDemo2.py # adapted to use a Struct rather than a dictionary # Creates a face and displays it # The face can either smile or frown from Tkinter import * ################################ # declare the Struct class first ################################ class Struc...
905f5eded12f932615a3c3a4b096da1d0a67359f
Sirrie/112work
/homework1/test1.py
879
3.515625
4
# Enter these expressions and statements into the interpreter. # Predict the results of each line before advancing to the next line. # Be precise. print 3*3/4, 3/4*3, 3**3/4 x = 1000*1000*1000*1000 # one trillion x print x type(x) x /= 1000*1000*1000 # divide by one billion x x/1000 x x = 123 x.bit_length() import...
5d6c1a0fddce4304784f333e96e685069a49ad69
hollandm/cs441-majestic-eagle
/CEEBData/ceebScraper.py
2,318
3.9375
4
# # Description: This python file scrapes CEEB code data from the # website "sat.collegeboard.org # # Input: None. # # Output: A .csv file containing every high school's name and CEEB # number as reported by the SAT Collegeboard. # # Based on the data scraping tutorial provided in the book "Visualize # This" by Nathan ...
804555ea0283cefb31c88b5ba64fc0aa4bf9b541
Degermandal/Introduction_to_Algorithm_and_Design
/Hw4/Solutions/Q1_b.py
1,019
3.796875
4
def findSpecial(arr): print("################") #print the elements of array for i in range(len(arr)): for j in range(len(arr[i])): print(arr[i][j]," ", end='') print() print("################") for i in range(len(arr)-1): for j in range(len(arr[i])-1): #...
42cc31424e8565f3ecb807d6bb750d01415e1460
Degermandal/Introduction_to_Algorithm_and_Design
/Hw4/Solutions/Q5.py
752
3.828125
4
def findBest (arr1, arr2, low, high, lst): if low == high: return 1 middle = (low + high) // 2 findBest(arr1, arr2, low, middle, lst) #Left findBest(arr1, arr2, middle + 1, high, lst) #Right for i in range(len(arr1) -1):#I used difeerence between the two array lst.append(arr2[i+1] -...
1c676ba9bb43be453458060ce539fa12e31e645b
brianaguirre/CS3240
/lab3/lab3_part1.py
1,642
4.28125
4
__author__ = 'BrianAguirre' #USER CREATION user_name = "" password = "" data = {} print("This program takes in usernames and password.") print("If at any point you wish to quit, enter an empty string.") user_name = input("Please enter the first user name:") password = input("Enter a password for " + user_name + ":")...
787a685d3c84da9f46bb9ae4586dcb0ccef3ffc3
Krdshvsk/python_less
/3.collections.py
4,793
4.125
4
# *** коллекции (контейнеры) *** # список (list) # создание пустого спска my_list = [] my__list = list() # добавление объекта (элемента) а список my_list.append(100) my_list.append(3.14) my_list.append('hello') my_list.append([10, 20, 30]) #print(my_list) # чтение значений элемента # в квадратную кобочку указывае...
64f11cb8d0df24171334ef129e1a255332fe242e
rafaly007/poec-python
/variable.py
383
4.0625
4
age= "je suis vieux" print(age) age="je suis jeune" print(age) text="je suis du texte" print(type(text)) nombre=42 print(type(nombre)) texte="je suis du texte" print(text*3) #concatenation text=text+" en plus" print(text) txt="Hello world !!!" print(len(txt)) print(txt[1]) print(txt[0:5]) print("bonjour je m'appelle ...
58d8e5da962370d21564be1b4e891a64abfb26da
underwaterlongs/codestorage
/Project_Euler/P3_LargestPrimeFactor.py
1,362
4.15625
4
""" The prime factors of 13,195 are 5,7,13,29. What is the largest prime factor of a given number ? We can utilize Sieve of Eratosthenes to find the prime factors for N up to ~10mil or so efficiently. General pseudocode for sieve: initialize an array of Boolean values indexed by 2 to N, set to True i = 2 for i to ...
6a91ab16d4cd8765899f03ab0071b9f33a442ca6
iwatobu/algorithm_for_DNAsequencing_coursera
/week3.py
5,038
3.671875
4
def readGenome(filename): """ a function that parses a DNA reference genome from a file in the FASTA format""" genome = '' with open(filename,'r') as f: for line in f: if not line[0] == '>': genome += line.rstrip() return genome def editDistance(x, y): # Create...
ce91aa87e045fc7e36c25ff23de47176f67128c6
pacocp/Cracking-the-Coding-Interview
/ArraysandStrings/question1-4.py
640
4.03125
4
'''Question 1.4 @author: Francisco Carrillo-Perez ''' string = 'never odd or even' def palin_per(string): hash_table = {} string_ = string.replace(' ', '') # create hash table for ch in string_: if ch not in hash_table.keys(): hash_table[ch] = 1 else: hash_tabl...
1ff3cedd6744d62e09f034859cd12bae5a7b65b8
pacocp/Cracking-the-Coding-Interview
/ArraysandStrings/question1-3.py
480
3.9375
4
'''Question 1.3 @author: Francisco Carrillo-Perez ''' def replace(string): new_string = '' for i in range(0, len(string)): if string[i] == ' ': if new_string[-3:] == '%20' and i != 0: return new_string[:-3] elif i == len(string)-1: return new_str...
05f7b9c287e7acf3a1534243c4cb7b96cdf5d916
felipem0ta/furry-potato
/Python/Cousera_Google Automation/Crash Course/coursera.py
791
4.1875
4
""" função que conta quantas vezes uma letra aparece em um texto. """ def count_letters(text): result = {} #incializando um dicionario vazio for letter in text: #percorre o texto passado if letter not in result: result[letter] = 0 #inicializa a contagem da letra com 0 se não estiver no dic...
7754077712bcf3e0428578a5a732c77f2b968b59
felipem0ta/furry-potato
/Python/Exercicios/basicos.py
1,060
4.0625
4
""" print ("hello") print ("world") def escrever(): print("hello, world") escrever() """ #builtins #print(type (15)) #print(dir()) """ lista_numero = [10, 20 ,30] nova_lista = filter(lambda n: n>=20, lista_numero) print(list(nova_lista)) """ """ catalogo = [ {'produto': 'Controle', 'preco': 300 }, {'pr...
9058960da2e622ec2c1beea28763f5573bdc2c1e
jdscorpio/Python
/sort_words.py
81
3.609375
4
txt = input("Wprowadz tekst: ") words = txt.split() words.sort() print(words)
6ba8496163ab7641886bf8c549074a14c182c588
yadifuentes/Mision_03
/Trapecio.py
816
3.671875
4
# Autor: YadiraFuentesCalderón, A01745235 # Descripcion: Calcular el are y perimetro de un trapecio def calcularArea(baseMayor, baseMenor, altura): area= ((baseMayor+baseMenor)/2)*altura return area def calcularPerimetro(baseMayor, baseMenor, altura): hipotenusa= ((((baseMayor-baseMenor)/2)**2)+(a...
d891d030f322c049ff7ae01f7ba6e67ef2b248ff
maancham/Data-Structures
/CA3/houmaan-chamani-q1.py
2,019
3.609375
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if(len(self.items) == 0): return 0 ...
b02f149b5f9f070bc619c7c3712fc21c81e1120c
mnpatil17/dna-linker
/dna_sequence.py
6,375
3.953125
4
class DNASequence: """ An abstraction of a DNA sequence. """ def __init__(self, seq_str, prev_seq=None, next_seq=None, prev_overlap=0, next_overlap=0): self._seq_str = seq_str self.prev_seq = prev_seq self.prev_overlap = prev_overlap self.next_seq = next_seq s...
d60e1887ffc53b4cab070e48c2d9b93700a23f3c
xshen1122/Python-practice-1
/dingzhi_p1.py
537
3.609375
4
# dingzhi_p1.py # coding: utf-8 ''' 1. 除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类 2. such as __str__: 打印出一堆<__main__.Student object at 0x109afb190>,不好看。 怎么才能打印得好看呢?只需要定义好__str__()方法, 返回一个好看的字符串就可以了: ''' class Student(object): def __init__(self,name): self.name = name def __str__(self): return 'Student object (na...
c7fd6ebe137f4f3cfa8500f72f6aa725aae3f9a2
valletidinesh/HackerRank
/ViralAdvertising.py
515
3.6875
4
#!/bin/python3 import math import os import random import re import sys # Complete the viralAdvertising function below. def viralAdvertising(n): days = [2] liked = [2] for i in range(1,n + 1): like = ((liked[i-1])*3)//2 days.append( like + days[i-1]) liked.append(like) return d...
cc7a053d4d67ec7c763bbce39a51c9e686366e31
ashumway2019/Moreprojects
/Random_AS.py
1,366
3.953125
4
import random words = ["Gossip Girl","One Tree Hill","Glee","Friends","Gilmore Girls"] hint1 = ["Ed Westick stars in it","Sophia Bush stars in it","Chris Colfer stars in it","Lisa Kudrow stars in it","Lauren Graham stars in it"] hint2 = ["They live in the Upper East Side", "They live in North Carolina", "They live...
159e94853a19d4303739a8e67c90fc0a25c793aa
Roy-Chandan/Roy-world
/Emp_of_month.py
272
3.71875
4
work_hours = [('Sona',100),('Roy',900),('Riya',200)] def emp_of_month(work_hours): max = 0 emp = '' for name,hours in work_hours: if hours > max: emp = name max = hours else: pass return (emp,max) result = emp_of_month(work_hours) print result
c514183018509ca710e85497281d2f21b0e8a23f
Roy-Chandan/Roy-world
/magic_method.py
458
3.546875
4
#magic/special methods class Book(): def __init__(self,sub,auth,pages): self.sub=sub self.auth=auth self.pages=pages #String representaion of the function.. always return def __str__(self): return 'This is the book of {} written by {} and contain {} pages'.format(self.sub,self.auth,self.pages) ...
1044ae5fa1dcff182100ef9f352d2985e2ee924a
Roy-Chandan/Roy-world
/Range1.py
685
4.15625
4
def user_choice(): choice = 'Wrong' accept_range = range(0,10) within_range = False while choice.isdigit() == False or within_range == False: choice = input ("Enter a number between 1-10: ") if choice.isdigit() == False: print ("Please enter a numb...
2cd2cee48549e357234920cd03528ecad6b1c5ba
kvega/potentialsim
/src/potentialsim.py
1,020
4.28125
4
#!/usr/bin/python3 import pylab import random """ Generates a text file of values representing the coordinates of n particles in a potential. """ # Create the Particle Class class Particle(object): """ Representation of a simple, non-interacting, massive particle (assumes point-like, does not model charg...
19d45b6f1b3caeadc4455a35ce2aa21b1145b0bb
josegalvezfernandez/cesarlpb.github.io
/Python/Py/python.py
2,034
3.640625
4
#python # Clase 11-05-2020 # Script básico para conectar a una web con python import requests url = 'https://www.idealista.com/alquiler-habitacion/madrid/centro/mapa' response = requests.get(url) response # error 403 = Forbidden / Prohibido url = 'http://web.mta.info/developers/turnstyle.html' response = requests.get(u...
37f4ff089cb55ae18b691d41c060df7d0515ce77
bbaejisoo/TIL
/2023/python/jump-to-python/03.py
686
3.6875
4
# 3의 배수의 합 구하기(1~1000까지의 자연수) result = 0 i = 1 while i <= 1000: if i % 3 == 0: result += i i += 1 print(result) # 별 표시하기 i = 0 while True: i += 1 if i > 5 : break print('*' * i) # 1 부터 100까지 출력하기 for i in range(1, 101): print(i) # 평균 점수 구하기 A = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100...
d5aaf1ecedf85a10c46cb91734597559e8706e89
shadowgamefly/python-scraping
/scrapetest.py
4,007
3.546875
4
import csv import requests from urllib.request import urlopen from urllib.error import * import re from bs4 import BeautifulSoup #异常处理 def getTitle(url): try: html = urlopen(url) except URLError as e: print(e) return None except HTTPError as f: print(f) return None ...
70185e860bac302c826445fcb345a6ee3b90bb17
dandrea1/CoffeeMachine
/main.py
3,150
4.15625
4
# Import Resources from data import resources from data import MENU EARNINGS = 0.00 is_on = True # Function to check if resources are sufficient for the order def resource_check(order_ingredients): """Determines if enough resources for the order and returns true or prints inadequate resources""" ...
3b01fadaffd3ef805696f3d8bbf49440fa8f2990
Enokisan/AtCoder-History
/AtCoder/第二回アルゴリズム実技検定/C/yamakuzushi.py
532
3.609375
4
N = int(input()) S = [] for i in range(0, N): si = input() #str object doesn't support item assignment si = list(si) S.append(si) for i in range(N-2, -1, -1): for j in range(1, 2*N-1): if S[i][j] == '#': if S[i+1][j-1] == 'X': S[i][j] = 'X' if S[i+1][j]...
5cfedd1cf572f54af42b3cdcbf009b62fadcc662
Enokisan/AtCoder-History
/AtCoder/ABC198/C/compass.py
179
3.71875
4
import math R, X, Y = map(int, input().split()) d = math.sqrt(X**2 + Y**2) if R == d: print("1") elif d <= 2*R: print("2") else: a = math.ceil(d/R) print(str(a))
43fcb55e8e52a5ff3ee9ec7d42d945f35ca93e76
Enokisan/AtCoder-History
/AtCoder/ABC201/A/A.py
184
3.5
4
A = list(map(int,input().split())) if 2*A[0] == A[1]+A[2]: print("Yes") elif 2*A[1] == A[0]+A[2]: print("Yes") elif 2*A[2] == A[0]+A[1]: print("Yes") else: print("No")
606922caeb0bee083030023a72fda2b611b5a005
Enokisan/AtCoder-History
/AtCoder/ABC179/A/plural.py
101
3.78125
4
S = list(input()) if S[len(S)-1]=="s": S.append("es") else: S.append("s") print("".join(S))
967df6099d9ce6d26f92168650dcb681d907cfa6
Enokisan/AtCoder-History
/AtCoder/AtCoder Regular Contest 046/A/zorome.py
173
3.5
4
import math N = int(input()) x = math.ceil(N/9) #x桁の数 y = N % 9 #ゾロ目の数 if y == 0: y = 9 res = "" for i in range(0, x): res += str(y) print(res)
f551d1d4d2de3f643cd17321c0b5e1bab9f249ed
Enokisan/AtCoder-History
/AtCoder/ABC198/B/palindrome.py
233
3.984375
4
import re # 回文判定 def ispalindrome(str): return 1 if str == str[::-1] else 0 N = input() N = re.sub("0+$", "", N) # 末尾に0が1回以上続くのを消す r = ispalindrome(N) if r: print("Yes") else: print("No")
26eb5e2e53d709c3ecc27383c775d12c8aff2a2f
bbarreto1987/ProjectEuler100
/python/p002.py
275
3.765625
4
def p002(x): def fibonacci(a0, a1): return a0 + a1 a0 = 1 a1 = 2 r = 2 a2 = fibonacci(a0, a1) while a2 < x: r += a2 if (a2 % 2 == 0) else 0 a0 = a1 a1 = a2 a2 = fibonacci(a0, a1) return r
6fbc622e20843f478f0eb96f8ed9a06acae4ad0c
ghyeon1946/backjoon
/11279(1).py
305
3.53125
4
import heapq import sys n = int(input()) Max_heap = [] for i in range(n): item = int(sys.stdin.readline()) if item != 0: heapq.heappush(Max_heap, (-item, item)) else: if not Max_heap: print(0) else: print(heapq.heappop(Max_heap)[1])
a608c2cc6ee265434e431ddd117077d2304694ca
DumbwaysDotId/python-basic
/array_n_dict.py
443
3.671875
4
# Dict fruits = [ {'id': 1, 'name': "Apple",}, #0 {'id': 2, 'name': "Grape"}, #1 ] x = [] y = [] # 1. start looping fruits for f in fruits: x.append(f['id']) y.append(f['name']) # eof 1 print(x) print(y) # Looping standard bingits # # javascript # for(i=0;i<10;i++){ # # } #python for i in range(1,...
46d5ce71865a07caeebe2e600ec26f991d6d4ab3
ridwan-salau/Datafain
/capstone_project_1.py
3,551
3.859375
4
def grader(score): if score >= 70: return "A" if score >= 60: return "B" if score >= 50: return "C" if score >= 40: return "D" if score < 40: return "F" def total(test_scores, exam_scores): ''' The output will be a list of lists of subject scores of each student e.g., [[64, 70], [...
3b63ecb9e9d85067b051904ac8207edd6735ec89
GabrielSouzadaSilva/Algoritmo-de-Euclides-estendido
/euclides.py
364
3.5625
4
def euclides (A, B): #variáveis para efetuar trocas a, b = A,B x,x1 = 1,0 y,y1 = 0,1 while True: #quotient quociente = int((a/b) - (a/b)%1) # math.floor(a/b) a, b = b, a % b x, x1 = x1, x - (quociente * x1) y, y1 = y1, y - (quociente * y1) if b == 0 : return(a,x,y) # tais qu...
e668cb2cc942500474bc1e27564796da624445cd
rdbishop19/py-cashToCoins
/cashToCoins.py
726
3.78125
4
import math dollarAmount = 8.69 piggyBank = { "pennies": 0, "nickels": 0, "dimes": 0, "quarters": 0 } # Your magic Python code here def make_change(dollar_amount): piggy_bank = { "pennies": 0, "nickels": 0, "dimes": 0, "quarters": 0 } piggy_bank["quarters"]...
30249fa1ffaca3e38fec51b4ccf5a3d7e2f8676f
amir78729/algorithm-design-course
/3/code/Q3(auick).py
1,439
3.5
4
import random comp = 0 def compare(A, B): global comp if len(A) == len(B): n = len(A) for i in range(n): if A[n-i-1] == B[n-i-1]: comp+=1 pass else: comp+=1 return (A[n-i-1] > B[n-i-1]) else: comp+=1 if (len(A) > len(B)): return True else: return False def partition_rand(...
f7eff52ecae24c01bc1b981f8eb418d7421488d9
minisparrow/acm
/step1/leetcode/python/linklist_lc21_linklist_merge2linklist.py
1,477
4
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l3 = ListNod...
dec154057a4b4b31f3d4a9e63717740aa6f4768c
lazylearner-007/leetcode
/1008leet.py
814
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right #time complexity O(nlogn) #space complexity O(n) class Solution(object): def bstFromPreorder(self, preorder): ...
25141f77f2db3317017b23218fa76d7aa6a16f96
itwebMJ/pythonStudy
/6day/7. return_func.py
1,179
3.859375
4
''' 재귀함수 자신을 호출하는 함수 반복동작을 짧게 구현할 수있는 장점이 있지만 스택 사용량이 확 늘어나서 스택 오버플로우 문제 발생가능. 대부분 재귀는 루프로 대체 가능하기 때문에 루프로 대체하는 것이 좋다 ''' #5! = 5*4*3*2*1 def fact(num): if num==1: return 1 else: return num * fact(num-1) def fact2(num): res = 1 for i in range(1, num+1): res *= i return res ...
f9edd305f2cab166694e406a937421312a63df9a
itwebMJ/pythonStudy
/7day/5. file2.py
945
3.703125
4
''' 파일의 읽고 쓰기 위치 제어 tell() : 현재 위치 반환 seek(off, whence) :whence를 기준으로 off만큼 떨어진 위치로 이동, whence는 0(앞), 1(현재위치), 2(맨뒤) ex> abasdfad ab 련재 : 2 seek(5, 0) seek(-1, 1) seek(-10, 2) ''' def writeFile(): f = open('./file/f.txt', 'w') s = 'abcdefghijklmnopqrstuvwxyz' f.write(s) f.close() def readFile(...
84ed36eedcbf88072fe7bfe33380d225038f0756
itwebMJ/pythonStudy
/9day/8. static_method2.py
548
3.671875
4
#정적 메서드 활용 및 정적 변수 활용 예 => 객체 생성없이 클래스에서 제공하는 메서드(기능)를 사용하는 클래스 #API 제공 class Math: __pi = 3.14 # 변수 앞에 __를 붙이면 private멤버변수(클래스 밖에서 안보임) PI = __pi def circle(r): return r*r*Math.PI def rect(w, h): return w * h def main(): print('pi : ', Math.PI) w= Math.circle(5) prin...
861a99afac2f93a6163847d6a9bdc57b21136b19
jflow415/mycode
/dict01/marvelchar01.py
1,290
4.21875
4
#!/usrbin/env python3 marvelchars = { "Starlord": {"real name": "peter quill", "powers": "dance moves", "archenemy": "Thanos"}, "Mystique": {"real name": "raven darkholme", "powers": "shape shifter", "archenemy": "Professor X"}, "She-Hulk":{ "real name": "jennifer walters", "powers": "super...
8baf4c25db531f9d28671c82be3b8c89ab0e997b
Mycroft0121/checkio
/Scientific_Expedition/Caps_Lock.py
592
4.0625
4
def caps_lock(text: str) -> str: text = text.split("a") for i in range(1,len(text),2): text[i] = text[i].upper() # your code here return "".join(text) if __name__ == '__main__': print("Example:") print(caps_lock("Why are you asking me that?")) # These "asserts" are used for self-...
a152457d8b30b154b3664cb7db1286a206859bca
VaikunthSeshadri/FE595Assignment3
/Assignment3 - 1.py
1,517
3.765625
4
# the libraries needed to solve this right now import csv import pandas as pd #creating lists to keep track of the various titles name = [] purpose = [] # opening and reading Aniruddh's csv file with open('Assignment_2.csv') as ani: ani_data = csv.reader(ani) for row in ani_data: if row[...
20c326bf3b6d3774b942596331ebf424d2dea65c
Swapnil2095/ds-cheatsheets
/Interview_Problem/sum_of_subarray.py
992
3.953125
4
# User function Template for python3 # Function to find a continuous sub-array which adds up to a given number. import math class Solution: def subArraySum(self, arr, n, s): # Write your code here summDict = {} curSumm = 0 for index in range(0, n): curSumm += arr[inde...
870f3755dfe267dcb8edbc1bd109bb4689b31890
17Orlok17/EconometricCode
/regOLS.py
821
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 30 13:07:19 2014 @author: Evan Goal: Take in a vector Y and a matrix X, calculate the regression coefficients. Assume there is an intercept calculated as well. Note: For My_Test_01-My_Test_05, I created the vector of ones for the intercept in this program. Now I assum...
9eba57c0586d9a6e8fe03db61e977ec3c60cbd9c
red23495/random_util
/Python/Algebra/binary_exponentiation.py
671
3.90625
4
def mod_pow(base, power, mod=None): """ Implements divide and conquere binary exponetiation algorithm Complexity: O(log power) source: https://cp-algorithms.com/algebra/binary-exp.html Params: @base: base number which needs to be multiplied @power: power to which base should be raised @...