blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
be0b86721d4ad58b52d6bf23c81a13b07231d359
nkhuyu/python
/projectEuler/ProjectEuler1.py
261
3.828125
4
def mutliplesof3and5(n): if(n%3==0 or n%5==0): return 1 else: return 0 def sum(n): temp=0 for i in range(3,n):# 3:n-1 if(mutliplesof3and5(i)): temp=temp+i return temp ## n=5 sum(n)
44b110dcaf1902cc607db2b51cf9dbad11b484d0
gnayuy/taocp
/python/linkedlists.py
5,885
4.09375
4
"""Implementation of the linked list and circular lists algorithms (chapter 2.2.3 and 2.2.4). """ import itertools def topological_sort(relations): """Implement algorithm T of chapter 2.2.3. In this implementation the linked lists are actually replaced by lists. This does not depart significantly from ...
9e160c2e16ffbaeff98c0d4b96f7f0094af5e86e
ivanshukaushik/OpenCV_Projects
/drawing_functions_in_python.py
685
3.609375
4
import numpy as np import cv2 img = cv2.imread('lena.jpg', 1) # img = np.zeros([512, 512, 3], np.uint8) # To make the entire image black img = cv2.line(img, (0, 0), (255, 255), (255, 0, 0), 5) # BGR img = cv2.arrowedLine(img, (255, 255), (400, 400), (255, 0, 0), 5) # Arrowed Line img = cv2.rectangle(img, ...
0321662cfde748244a93de8a0b14f1763b7bf261
XaserAcheron/damnums
/damfont.py
1,070
3.796875
4
import sys MAX_DIGITS = 5 # [TODO] document this silly thing: def genfonts(prefix, width, height): yoffset = height - 2 for charindex in range(10): char = chr(65 + charindex); for numdigits in range(2, MAX_DIGITS+1): spritewidth = width * numdigits xoffset = int(spritewidth / 2) for digit in range(...
30a67482cc0693be0074d22cc8672e1b2debf5dc
stasvf2278/Rename_Files
/Renames_Files.py
783
3.609375
4
import os, shutil def main(): print('Enter input directory path') ## Enter first folder file path here folder1 = input() print('Enter New File Prefix') prefix = input() print('Enter output directory path') ## Enter second folder file path here folder2 = inpu...
c579b12922eb92b1e4cc4f1b28c6c183923b6150
uuind/Average_Atomic_Mass-Calculator
/Calculator.py
359
4.03125
4
def Average_Atomic_Mass(): isotopes = input("How many isotopes?") average = 0 for x in range(1,int(isotopes) + 1): mass = input("What is the isotope %s's mass in amu?" % x) percent = input("How abundant is it in %?") average += (float(mass)*(float(percent)/100)) print("%s ...
98b9c79b89cca09f9159031ed04c1a19e71eecea
andy12290/Python-Essential-Training--1
/Exercise Files/11 Functions/generator.py
452
3.53125
4
#!/usr/bin/python3 # generator.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC def main(): print("This is the functions.py file.") for i in inclusive_range(0,25,1): print(i, end = ' ') def inclusiv...
93640b1d7b6e00f7a02321e8868723ba2315fb55
Tim810306/junyi_test
/1.py
254
3.890625
4
#第一題a用python: def reverse(s): return s[::-1] #第一題b用python: def reverse5(s): s1 = '' length = len(s) - 1 while length >= 0: s1 = s1 + s[length] length = length - 1 #還沒完成順序調整 return s1
4f619614442506f1567eb9ecc0de6c989f0c2c21
ashburnere/data-science-with-python
/python-for-data-science/1-2-Strings.py
2,344
4.28125
4
'''Table of Contents What are Strings? Indexing Negative Indexing Slicing Stride Concatenate Strings Escape Sequences String Operations ''' # Use quotation marks for defining string "Michael Jackson" # Use single quotation marks for defining string 'Michael Jackson' # Digitals and spaces in string '1 2...
d86edccc25b0e5e6aebddb9f876afd3219c58a65
ashburnere/data-science-with-python
/python-for-data-science/4-3-Loading_Data_and_Viewing_Data_with_Pandas.py
2,038
4.25
4
'''Table of Contents About the Dataset Viewing Data and Accessing Data with pandas ''' '''About the Dataset The table has one row for each album and several columns artist - Name of the artist album - Name of the album released_year - Year the album was released length_min_sec - Length of the album (hours,...
7e13a68d223d69c45253189c3de073873d14ae04
zlzlzl002/Python
/Hello/test/2월20일DataType.py
723
3.796875
4
#-*- coding:utf-8 -*- # Dict type mem1={"num":1,"name":"gura","addr":"hong"} # 삭제하기 del mem1["num"] # 수정하기 mem1["num"]=2 # tuple type 수정/삭제 불가 list type 속도 빠름 a=(1,2,3,4) # 여러값 넣기 a,b=10,20 # 1개 생성할때는 , 를 붙여 줘야한다 a=(1,) # 두변수 상호 교환 isMan="guzn" isGirl="sang" isMan, isGirl=isGirl,...
fff0dfba6e768aff3d24c520512ea80566372ff4
anucoder/Python-Codes
/01_numbers.py
203
4.09375
4
#using paranthesis to prioritise print((2*9)+(10*5)) #reassignment #dynamic assignment---> no need to declare the type. a = 5 print(a) a = a*5 print(a) #snake casing two_dogs = 2 #2_dogs is invalid
29383e08c12d57b53c61ae628026cb065957f9b7
anucoder/Python-Codes
/04_dictionaries.py
513
4.34375
4
my_stuff = {"key1" : "value1", "key2" : "value2"} print(my_stuff["key2"]) print(my_stuff) #maintains no order #multiple datatype with nested dictionaries and lists my_dict = {"key1" : 123, "key2" : "value2", "key3" : {'123' : [1,2,"grabme"]}} print(my_dict["key3"]['123'][2]) #accessing grabme print((my_dict["key3"]...
fee9d9373e1e0f209244e0a6913555313c8bd7ef
chiranjibKonwar/intron_dataset
/CORRECT_tetra_frequency_calculator_v2.py
1,979
3.640625
4
from optparse import OptionParser import sys, re from itertools import product usage= sys.argv[0] + """ -f FASTA_intron_sequence_file""" parser = None def createParser(): global parser epilog = """ This code takes input a FASTA intron sequence and computes overall tetranucleotide frequency for the input intron ...
a33d60ed9f9f9b024cf5304550812e7df316d230
BurntSushi/qcsv
/qcsv.py
15,785
3.609375
4
""" A small API to read and analyze CSV files by inferring types for each column of data. Currently, only int, float and string types are supported. from collections import namedtuple """ from __future__ import absolute_import, division, print_function from collections import namedtuple import csv import numpy as np ...
733046f20c403d8ad93489e1a29f4faf89939851
swest06/Hangman
/hang.py
2,246
3.953125
4
import random import time from os import system, name def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux else: _ = system('clear') def game(): words = ["banana", "grape", "orange", "mango", "cherry", "apple", "pear", "peach"] strikes = int(7) ...
2c2f3c5f98ddf31330b03ae761ba95ec1f391778
uuind/2018-cc
/GCC3.py
1,136
3.59375
4
def beg(): b = int(input('how many integers?\n')) if b == 0: print("sorry not allowed") quit() a = [int(x) for x in input('Please enter the values now\n').split(' ')] if len(a) == b: return a else: print('incorrect amount of values within sequence') def gr...
f39a2be4092c5f94f3195f0abffa5b11adb45b33
kbenedetti9/Mision-TIC-Python
/Retos diarios/Reto día 8/reto_dia8.py
890
3.546875
4
def reto1(palabra): cantidad = len(palabra) i = 0 correcto = 0 num = cantidad while i<cantidad: num-=1 if palabra[num] == palabra[i]: correcto+=1 i+=1 if correcto == cantidad: result = True else: result = False print(result) # Modifica el codigo para imprimir cada valor ...
eff50cbd0f7ee774a1d90db6832560189dbdd1fb
amaurirg/Tarefas-Macantes
/testes/fizzbuzz.py
1,127
3.765625
4
from sys import _getframe import unittest multiple_of = lambda base, num: num % base == 0 def robot(pos): say = str(pos) # mude essa linha de and para or para gerar um erro e ver a saída if multiple_of(3, pos) and multiple_of(5, pos): say = 'fizzbuzz' elif multiple_of(3, pos): say = ...
e027f52eed46b3390499dabf1c19386dcd1101af
amaurirg/Tarefas-Macantes
/Graficos/scatter_squares.py
1,133
3.59375
4
import matplotlib.pyplot as plt #plt.scatter(2, 4, s=200) # define um ponto específico x=2, y=4 e s=200 (tamanho do ponto) # x_values = [1, 2, 3, 4, 5] # y_values = [1, 4, 9, 16, 25] x_values = list(range(1, 1001)) y_values = [x**2 for x in x_values] # plt.scatter(x_values, y_values, c='red', edgecolor='none', s=4...
f340ae17dd37811fc51fb2405c68c71d4fb8acec
amaurirg/Tarefas-Macantes
/excel(openpyxl)/teste_atualiza.py
796
3.640625
4
PRICE_UPDATES = {} resp = '' while resp != 'n': resp = input('\nAtualizar produto? (s para sim ou n para sair): ') try: if resp == 's': produto = input('Digite o produto: ') preco = input('Digite o valor: ') # if ',' or '.' not in preco: # preco = input('Digite um valor válido (ex.: 2,00):...
6345660779fa7e35d49ca37642ed793d0a40de4c
amaurirg/Tarefas-Macantes
/manipulando_arquivos/arquivos_HD/utilizando_pprint.py
1,307
3.953125
4
#! python3 #Utilizando o módulo pprint para salvar em um arquivo.py, gerando assim um módulo próprio chamado "myCats. #Esse trecho comentado cria o módulo que não será necessário ser criado novamente. ''' import pprint #importa o módulo para salvar de forma mais elegante. cats = [{'name': ...
3fcc4107b7bc8d14674675813d66c6ced891fdb3
amaurirg/Tarefas-Macantes
/tempo/stopwatch.py
718
3.859375
4
#! python3 #Simples cronômetro. import time #Exibe as instruções do programa. print('Pressione ENTER para começar. Depois, pressione ENTER para registrar o tempo no cronômetro. Pressione CTRL+C para sair.') input() print('Início da contagem de tempo.') startTime = time.time() lastTime = startTime lapNum = ...
7b87c1451cf718b0094d101c26c5d1c82f41efe3
amaurirg/Tarefas-Macantes
/web_scraping/lucky.py
1,736
3.703125
4
#! python 3 #Abre vários resultados de pesquisa no Google. import requests, sys, webbrowser, bs4 #importa o módulo requests para download da página. #importa o módulo sys para ler a linha de comando. #importa o módulo webbrowser para abrir o navegador. #importa o módulo ...
069e6443b63d7b1885a59bd2eaad877127b5cef9
amaurirg/Tarefas-Macantes
/Graficos/Matplotlib/colormap.py
696
3.828125
4
import matplotlib.pyplot as plt # Valores de x e y x_values = list(range(1, 1001)) y_values = [x**2 for x in x_values] # Plota uma linha gradiente azul, sem contorno, e expessura s=40 plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor='none', s=40) # Define o título do gráfico e no...
6bf4f21da8abe83fb9749888a2a488a231cdf9a4
AlveinTeng/CSC311FinalProject
/starter_code/part_a/knn.py
4,736
3.78125
4
from sklearn.impute import KNNImputer from utils import * import matplotlib.pyplot as plt def knn_impute_by_user(matrix, valid_data, k): """ Fill in the missing values using k-Nearest Neighbors based on student similarity. Return the accuracy on valid_data. See https://scikit-learn.org/stable/modules/gen...
9f67be3ea93dcb4ab9f1d84391cecbb293f408e8
Mkath1423/Projects
/Projects/Mini Adventure/databaseTools.py
4,245
4.0625
4
import sqlite_manager as db def createNewDB(database, rooms): ''' This function initializes a new database. A new gameSave database will be created with the required tables. rooms number of stock rooms then get inserted into the database. The database name also gets added to the gameFilePaths.txt file. ...
a016c597b8fc5f70e2ab5d861b756d347282289d
jourdy345/2016spring
/dataStructure/2016_03_08/fibonacci.py
686
4.125
4
def fib(n): if n <= 2: return 1 else: return fib(n - 1) + fib(n - 2) # In python, the start of a statement is marked by a colon along with an indentation in the next line. def fastFib(n): a, b = 0, 1 for k in range(n): a, b = b, a+b # the 'a' in the RHS is not the one in the RHS. Python distinguis...
5b4440484b062a79c73b005f2016ad3cd7c49ebf
YDrall/laboratory
/python/lpthw/loops_and_list.py
398
3.84375
4
the_count = [1,2,3,4,5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1,'pennis',2,'dimes',3,'quarters'] def sperator(): print '-'*20 for number in the_count: print number sperator() for fruit in fruits: print fruit sperator() for i in change: print i elements = [] for i in rang...
951eb2846feac19190916771176ad0621ddf4987
YDrall/laboratory
/python/lpthw/matrices_testdoc.py
454
3.609375
4
def make_matrix(rows, column): """ >>> make_matrix(3,5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> make_matrix(4,2) [[0, 0], [0, 0], [0, 0], [0, 0]] >>> m = make_matrix(4,2) >>> m[1][1] = 7 >>> m [[0, 0], [0, 7], [0, 0], [0, 0]] """ matrix = [] for i in rang...
be9b1b682cc8b1f6190fead9c3441ce72f512cf4
Nathan-Dunne/Twitter-Data-Sentiment-Analysis
/DataFrameDisplayFormat.py
2,605
4.34375
4
""" Author: Nathan Dunne Date last modified: 16/11/2018 Purpose: Create a data frame from a data set, format and sort said data frame and display data frame as a table. """ import pandas # The pandas library is used to create, format and sort a data frame. # ...
0d3797cc77e5934de5fae55da24a79d27154ec0f
cjp0116/ML
/multiple_linear.py
4,000
3.640625
4
# Importing the Libaries import numpy as np import matplotlib.pyplot as plt import pandas as pd """Out of the R&D Spends and Marketing spends, which yields better profit? With the assumption that the location of the startup hold now significance. A Caveat to Linear Regressions: 1. Linearity 2. Homosced...
5fec285125210654cdc334d9d16bebf72c4be2c7
benjvdb9/RandNumGenerator
/test.py
267
3.515625
4
from time import time times = [] for i in range(10): times += [time()] delta = [] old = "" for elem in times: print("Time:", elem) if old == "": res = "No delta" else: res = elem - old print("Delta:", res) old = elem
8eba1f38d3e13306076467af0694dc65f7d6ed7f
englernicolas/ADS
/python/aula3-extra.py
1,934
4.1875
4
def pesquisar(nome) : if(nome in listaNome) : posicao = listaNome.index(nome) print("------------------------------") print("Nome: ", listaNome[posicao], listaSobrenome[posicao]) print("Teefone: ",listaFone[posicao]) print("-------------------------") else: print(...
796e17d9375a3eb2b6fb36232d6beb7cf73adda3
lgdelacruz92/LeetCode-Challenges
/path-in-grid/path-in-grid.py
1,334
3.5
4
def optimal_path(grid): n = len(grid) record = [] for i in range(n): row = [] for j in range(n): row.append(-1) record.append(row) record[0][0] = grid[0][0] def sum_path(i,j): if record[i][j] != -1: return record[i][j] if i < 0 or i...
3ed7723170138098f9cd9f5032ec00d851b2f7f1
lgdelacruz92/LeetCode-Challenges
/accounts-merge/disjoint-sets.py
1,675
3.5
4
from pprint import PrettyPrinter pp = PrettyPrinter() class DisjointSet: def __init__(self): self.universe = ['a','b','c','d','e'] self.PARENT = {} for item in self.universe: self.PARENT[item] = item self.PARENT[self.universe[3]] = self.universe[1] self.GRAPH = ...
9a52ad177df52e01fa357cfc3f620df7e91f46d7
lgdelacruz92/LeetCode-Challenges
/create-sorted-array-through-instructions/create-sorted-array-through-instructions.py
1,088
3.875
4
def b_search(nums, search_item, start, end): if end < start: return -1 k = int((end-start)/2) + start y = search_item if nums[k] < y and k == end: return k elif nums[k] < y and y <= nums[k+1]: return k elif y < nums[k]: return b_search(nums, search_item, start, k-...
c89ada8107f353998c9e5c569dbe7e51b5e9889f
lgdelacruz92/LeetCode-Challenges
/continous_max_subarray/sol1.py
905
3.828125
4
from queue import PriorityQueue def count_subarrays(arr): n = len(arr) result = [1] * n stack = [] for i, v in enumerate(arr): if not stack: result[i] += i else: while stack and stack[-1][0] < v: stack.pop() if stack: ...
a79bbf5a8c8ed5992fe82f9d5409c6d7ad11648f
LionStudent/practice
/bfs.py
808
3.90625
4
class Graph: def __init__(self): self.nodes = {} def __repr__(self): return str(self.nodes) def addEdge(self, src, tgt): self.nodes.setdefault(src,[]).append(tgt) self.nodes.setdefault(tgt,[]) # add other node but not reverse edge def bfs(self, roo...
86422c92b3f66365832ee47decc1370b789393be
ReblochonMasque/spiralofsquares
/rectangle.py
1,057
3.828125
4
""" a Rectangle """ from anchor import Anchor class Rectangle: def __init__(self, width, height): self.width = width self.height = height self.bbox = None self.norm_bbox = None self.calc_bbox(Anchor()) self.normalize_bbox() def calc_bbox(self, anchor): ...
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...
c6751016634ed6ef77a3be91342ddfd60af0fdae
natashahussain/webLnatasha
/CO1 Pg12.py
118
4.03125
4
#accept a file and print extension fn=input("enter filename") f=fn.split(".") print("extension of file is;"+ f[-1])
317bafca9aa622828b3cb835b10d02301372f4ca
DeetoMok/CS50
/(Pre-July) 3. Flask/sandbox.py
1,385
3.875
4
#Taking in an input #name = input() from pyclbr import Class name = "Daryl" #f is to print in format String. I this case, the variable "name" print(f"Hello, {name}!") # initiating a variable does not require u to specify the data type i = 28 f = 2.8 b = False n = None # Conditional statements x = 28 if x > 0: p...
2f42cd1195a17baddb6f223e470659906aa702cd
abdul-malik360/Python_Proj_Week_Prep
/numbers.py
770
3.6875
4
from tkinter import * import random from tkinter import messagebox root = Tk() root.geometry("500x500") root.title("Generate Your Numbers") numb_ans = StringVar() numb_ent = StringVar() mylist = [] mynewlist = [numb_ent] ent_numb = Entry(root, textvariable=numb_ent) ent_numb.place(x=50, y=25) Label(root, textvariabl...
bb2c90429b029e33059fa667a3864eb1fdc60808
NatanBB/BSI-2_Classes
/classes_exec/bola.py
1,053
3.921875
4
# Classe Bola: Crie uma classe que modele uma bola: # Atributos: Cor, circunferência, material # Métodos: trocaCor e mostraCor class Ball: def __init__(self, color="unknown", circunf=0, material="unknown"): self.color = color self.circunf = circunf self.material = material ...
996998a8d1b2e956b635d0bae93cd0fe49cb454e
ambrishrawat/burrows-wheeler
/BurrowsWheelerTransform.py
1,228
4
4
class BurrowsWheelerTransform: """Transforming a string using Burrows-Wheeler Transform""" def __init__(self): pass def bwt(self,f): """Applies Burrows-Wheeler transform to input string. Args: f (File): The file object where each line is a '0' or '1'. Return...
f5dc8fd74e6bad8bb10b81b98e3ec711dfb9613a
lemonad/advent-of-code
/2015 (Python)/december03.py
2,167
3.5625
4
""" December 3, Advent of Code 2015 (Jonas Nockert / @lemonad) """ from common.puzzlesolver import PuzzleSolver class Solver(PuzzleSolver): @classmethod def make_move(cls, move, pos): if move == '^': pos = (pos[0], pos[1] + 1) elif move == 'v': pos = (pos[0], pos[1] -...
a46c37325d7a3efdcf1a50a43dd943b69163a690
520Coder/Python-Programming-for-Beginners-Hands-on-Online-Lab-
/Section 14/Student Resources/Assignment Solution Scripts/01_file_io_phone_book.py
3,368
3.96875
4
# File IO - Append # File my_file = "my_phone_book.txt" # Add def add_entry(first_name, last_name, phone_number): entry = first_name + "," + last_name + "," + phone_number + "\n" with open(my_file, "a") as file_handler: file_handler.write(entry) # Get list def get_list_from_file(file_name): pho...
aa5511e07cc866babfcd2ee3c7f7d6149ba1b740
520Coder/Python-Programming-for-Beginners-Hands-on-Online-Lab-
/Section 6/Student Resources/Assignment Solution Scripts/assignment_lists_02_solution_min_max.py
308
4.21875
4
# Lists # Assignment 2 numbers = [10, 8, 4, 5, 6, 9, 2, 3, 0, 7, 2, 6, 6] min_item = numbers[0] max_item = numbers[0] for num in numbers: if min_item > num: min_item = num if max_item < num: max_item = num print("Minimum Number : ", min_item) print("Maximum Number : ", max_item)
e581134dca95d8b5b36dace6546333c01f61b8a7
eman19-meet/y2s18-python_review
/exercises/functions.py
165
3.671875
4
# Write your solution for 1.4 here! def is_prime(x): i=1 while i<x: if x%i==0: if i!=x and i!=1: return False i=i+1 return True print(is_prime(5191))
4de3b01cdf53acec3acf826e69f054234e5d022c
Abhinavjha07/Cloud-Computing
/Lab1/lab12.py
1,598
3.65625
4
import split import operator def readFile(fileIn): content="" for line in fileIn : content+=line return content def wordCount(contents): wordcount={} for word in split.tsplit(contents,(' ','.','!',',','"','\n','?')): if word != '': if word not in wordcount: ...
d0ef890c1a36d3daf597b6649dfc11c1ddf4891e
BerryRB/Leetcode
/leetcode-day3.py
999
3.78125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 14:57:21 2019 @author: 刘瑞 """ """ 题目描述: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次数。 思路:只要把数组中所有的非零元素,按顺序给数组的前段元素位赋值,剩下的全部直接赋值 0 """ class Solution: def moveZeroes(self, nums): "...
7e16b4a55a95d817df09ae851dba7b797ce9a330
BerryRB/Leetcode
/leetcode-day13.py
1,178
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 26 16:19:46 2019 @author: 刘瑞 """ """ 题目描述:快乐数 编写一个算法来判断一个数是不是“快乐数”。 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。 示例: 输入: 19 输出: true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 思路:重点是如何判断无限循环,若某一...
325829efc0923bb02e79c044b190855d65baa16e
ggradias/real-python-test
/fibo.py
226
3.65625
4
#Leonardo de Pisa import sys def fib(n): #return the nth fibonacci number n = int(n) if n <= 1: return 1 return fib(n-1)+ fib(n-2) if __name__ == '__main__': import pdb; pdb.set_trace() print(fib(sys.argv[-1]))
bfd6a6a1ce1a215bd6e698e732194b26fd0ec7b4
tjnelson5/Learn-Python-The-Hard-Way
/ex15.py
666
4.1875
4
from sys import argv # Take input from command line and create two string variables script, filename = argv # Open the file and create a file object txt = open(filename) print "Here's your file %r:" % filename # read out the contents of the file to stdout. This will read the whole # file, because the command ends a...
ec8ba8655f455632af649f889421ab136b30bf1d
xy008areshsu/Leetcode_complete
/python_version/dp_word_break.py
1,080
4.0625
4
""" Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code". """ # idea: # function: f[i] if it can be b...
a3c1730239862bd1d138a800e38288af6e482c67
xy008areshsu/Leetcode_complete
/python_version/2_sum_3.py
991
3.96875
4
""" Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equal to the value. For example, add(1); add(3); add(5); find(4) -> true find(7) -> false """ class TwoSu...
95f95fdcee0ef4b94db756b9528c11a567e5f031
xy008areshsu/Leetcode_complete
/python_version/single_number.py
776
3.875
4
""" Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, ...
6b9281109f10fd0d69dfc54ce0aa807f9592109a
xy008areshsu/Leetcode_complete
/python_version/intervals_insert.py
1,267
4.125
4
""" Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,...
a200196530d1911796efd53079b094260a0576e5
xy008areshsu/Leetcode_complete
/python_version/min_stack.py
719
3.6875
4
class stack: def __init__(self): self.s = [] def push(self, val): self.s.append(val) def pop(self): return self.s.pop() def top(self): return self.s[-1] class MinStack: def __init__(self): self.s = stack() self.min_s = stack() def push(self...
8c4ef949fb0a7b32cd0556da41121ad5b3595054
xy008areshsu/Leetcode_complete
/python_version/graph_clone.py
853
3.671875
4
# Definition for a undirected graph node class UndirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if node is None: return ...
cccd42643b9b7088915328edb06738e2270345e2
xy008areshsu/Leetcode_complete
/python_version/DFS_factors_of_number.py
688
3.796875
4
""" e.g. 12 : return [ [1, 12], [2, 2, 3], [2, 6], [3, 4] ] """ def factors_of_num(num): res = [] list_aux = [] helper(num, res, list_aux) return res def helper(num, res, list_aux): if num == 1: if len(list_aux) < 2: list_aux.append(num) res.append(list_aux[:]) ...
466622f128194101691bb1a3d11623356560025c
xy008areshsu/Leetcode_complete
/python_version/longest_substring_with_at_most_two_distinct_chars.py
2,663
3.78125
4
""" Given a string, find the length of the longest substring T that contains at most 2 distinct characters. T is "ece" which its length is 3. """ #idea : maintain a h_map, keys are each char, and vals are lists of indices of each char, each val is a sorted list, since the index goes from 0 to len(s) - 1 # scan the s...
7e3a1b29b321ff31e6e635d825ddcfb1668aeb5c
xy008areshsu/Leetcode_complete
/python_version/dp_unique_path.py
1,531
4.15625
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? A...
cfbf373d21232629f021e68cee613b716deb32d8
xy008areshsu/Leetcode_complete
/python_version/dp_distinct_subsequence.py
1,225
3.796875
4
""" Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequenc...
5337ae5f30015e142b6b6916ca2b088bcd8d8e72
xy008areshsu/Leetcode_complete
/python_version/2_sum_2.py
906
3.90625
4
""" Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (...
13741847dbcaee5b10bdf8d23774f8af86a9418b
xy008areshsu/Leetcode_complete
/python_version/graph_topological_sort.py
1,385
3.5625
4
class Graph: def __init__(self, vertices = [], Adj = {}): self.vertices = vertices self.Adj = Adj def itervertices(self): return self.vertices def neighbors(self, v): return self.Adj[v] class DFSResult: # More practice def __init__(self): self.parent = {} ...
9af95f8a72a43fb5ff1b9cf8ca24e33abcb83ec3
xy008areshsu/Leetcode_complete
/python_version/dp_stock_3.py
2,009
3.84375
4
""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). """ # idea: # t...
e48702cf9debf012096411f0f631ca753990fb46
xy008areshsu/Leetcode_complete
/python_version/binary_search_find_peak_element.py
1,043
4.03125
4
""" A peak element is an element that is greater than its neighbors. For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. """ class Solution: # @param num, a list of integer # @return an integer def findPeakElement(self, num): if len(num) ==...
1c54bfc00aac0e3123c800d0e6dcfaad5a83790d
xy008areshsu/Leetcode_complete
/python_version/linkedlist_copy_with_random_pointers.py
1,038
3.921875
4
""" A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. """ # Definition for singly-linked list with a random pointer. class RandomListNode: def __init__(self, x): self.label = x self.ne...
d54e443f757c74f225b32e46e24c7a403cf48cc3
volkovandr/Snakeee
/py/snake.py
8,911
3.71875
4
#!/usr/bin/python3 ''' Implementation of the Snake class responsible for movement of the Snake ''' from time import time from food import Food from random import randint from copy import deepcopy from exceptions import GameOver class Snake: dead = 0 default_speed = 3 default_length = 10 UP, DOWN, L...
acf62110c3914a749821a025854092c3971a3e70
Cvtq/GridSearch
/main.py
1,482
3.734375
4
# Вариант 2 cuts = [[-5, 5], [-5, 5], [-5, 5]] f = "x**2 - 2*x + y**2 + 4*y + z**2 - 8*z + 21" def findExtr(f, c): cuts = c k = len(cuts) m = 5 d = cuts[0][1] - cuts[0][0] h = d / m min = None e = 0.0001 # Пока шаг сетки больше eps while (h > e): # Найдем координаты все...
5b577e98faf5fa8f139b2010122678df321f6436
giorgioGunawan/jenga-vs
/catkin_ws/src/baldor/src/baldor/transform.py
10,909
3.515625
4
#!/usr/bin/env python """ Homogeneous Transformation Matrices """ import math import numpy as np # Local modules import baldor as br def are_equal(T1, T2, rtol=1e-5, atol=1e-8): """ Returns True if two homogeneous transformation are equal within a tolerance. Parameters ---------- T1: array_like ...
cc99f3cfb363936e9902969471bda245627e8a46
Isetnt2/dice-ploter
/main-dice.py
976
3.5625
4
import matplotlib.pyplot as plt from random import randint as rnd amountOfDice = int(input('Hur många tärningar vill du kasta?')) amount = int(input('Hur många gånger vill du kasta?')) amountOfSides = int(input('Hur många sidor ska tärningarna ha?')) sum = [] frequency = [] plt.plot(sum, frequency[amountOfDice...
23b9542d92eb82c369b68d10ff4550af25d33b6b
kwaper/iti0201-2018
/L2/robot.py
1,413
3.921875
4
"""Terminator.""" import rospy from PiBot import PiBot robot = PiBot() count = int() robot.get_leftmost_line_sensor() robot.get_rightmost_line_sensor() def counting(count): """Counting.""" if count == 3: print("Turning Right") robot.set_right_wheel_speed(-30) robot.set_left_wheel_spee...
d9bfdddb7cdc8dc6ad7a1585f125edfd09ed871d
SpamAndEgg/jump_and_run_madness
/visualize_convolution.py
1,560
3.546875
4
# Here the convoluted frame is produced as output for further use by the neural network or for visualization. import threading import numpy as np import global_var from math import floor # This thread visualizes the convolution of the game screen. class VisualConvolutionThread(threading.Thread): def run(self): ...
91b56df18751d0c24e4622b5556e95123eb6c68d
skimbrel/project-euler
/python/p9.py
363
3.9375
4
"""Find the 3-tuple (a, b, c) such that a < b < c, a**2 + b**2 == c**2, and sum(a,b,c) = 1000.""" def find_tuple(): for c in xrange(0, 1000): for b in xrange(0, c): for a in xrange(0, b): if a ** 2 + b ** 2 == c ** 2 and sum([a, b, c]) == 1000: print a * b * ...
c20802ed076df2adc4c4b430f6761742487d37a7
samluyk/Python
/GHP17.py
900
4.46875
4
# Step 1: Ask for weight in pounds # Step 2: Record user’s response weight = input('Enter your weight in pounds: ') # Step 3: Ask for height in inches # Step 4: Record user’s input height = input('Enter your height in inches: ') # Step 5: Change “string” inputs into a data type float weight_float = float(weight) height...
4b02aaeaf5193eb6df74c199eb4fc563a01441dc
HarivigneshN/Harivignesh-N
/Converting uppercase to lowercase.py
104
3.859375
4
s=input() a='' for x in s: if x.islower(): a=a+x.upper() elif x.isupper(): a=a+x.lower() print(a)
b26697a86d2fc1058c709d53cb0abbace118653a
HarivigneshN/Harivignesh-N
/alphabets finder.py
196
4.1875
4
a=input() if((a>='a' and a<='z') or (a>='A' and a<='Z')): print ("Alphabet") else: print("No") #####Another method##### #if a.isalpha() == True: # print("Alphabets") #else: # print("No")
c4d747c1283007bfd70d81bf8686e448038d7c68
HarivigneshN/Harivignesh-N
/Encode string by adding 3 in char.py
61
3.609375
4
s=input() a='' for x in s: a = a + chr(ord(x) + 3) print(a)
020ba9167844284ef2608e37e6bcb10292330368
HarivigneshN/Harivignesh-N
/Armstrong number.py
111
3.625
4
a=int(input()) b=0 c=a while (a>0): d=a%10 b=b+(d**3) a=a//10 if (b==c): print ("yes") else: print ("no")
7c2b8b11f351400e56ea11ee016adadd9cbef2cf
HarivigneshN/Harivignesh-N
/duplicate remover.py
209
3.734375
4
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist) --------------------------------------------------------------------------- use set() ie., a=set(a) but cant sort again.
fcec737c20d89968234256445be103b61601a119
hed-standard/hed-python
/hed/tools/util/io_util.py
11,590
3.703125
4
"""Utilities for generating and handling file names.""" import os import re from datetime import datetime from hed.errors.exceptions import HedFileError TIME_FORMAT = '%Y_%m_%d_T_%H_%M_%S_%f' def check_filename(test_file, name_prefix=None, name_suffix=None, extensions=None): """ Return True if correc...
fe4e6bf449c1fe5dc2ba80f6102ab13fe10fbeaf
hed-standard/hed-python
/hed/tools/remodeling/operations/remove_rows_op.py
1,988
3.640625
4
""" Remove rows from a tabular file. """ from hed.tools.remodeling.operations.base_op import BaseOp class RemoveRowsOp(BaseOp): """ Remove rows from a tabular file. Required remodeling parameters: - **column_name** (*str*): The name of column to be tested. - **remove_values**...
0d28d6b5f6a31a6201a1d728d6a54e40ee339635
caderache2014/data_structures
/queue.py
953
3.890625
4
class queue_item(): def __init__(self): self.data = None self.next = None class queue(): def __init__(self): self.head= None def enqueue(self, data): new_item = queue_item() new_item.data = data new_item.next = self.head self.head = new_...
2743bd4df557ccc89ab0f3961fa0ca8e2b31697b
LstChanceMadrid/digital-crafts-18
/tip_calculator.py
331
3.984375
4
total_amount = float(input("Enter the total amount: ")) tip_percentage_amount = float(input("Enter the tip percentage amount: ")) def tip_amount(total_amount, tip_percentage_amount): tip = total_amount * tip_percentage_amount / 100 print("$" + str(tip)) return tip tip_amount(total_amount, tip_percent...
0d8fbaba74f8471905facad5aa730ae95ba3fb57
Robin970822/Ada-IRL
/maze_env.py
5,705
3.5
4
""" Created on Tue April 24 21:07 2018 @author: hanxy """ import numpy as np import tkinter as tk import time UNIT = 40 # pixels SQUAR = UNIT * 3 / 8 # create points on canvas def create_points(point, canvas, fill): rect_center = UNIT / 2 + point * UNIT shape = np.shape(rect_center) assert shape[-1] =...
b43f3dc11cc4b367dc7148973fc7f5096d01704c
dlapochkin/project.6
/main.py
6,431
3.875
4
from string import * from random import * def main(): """ Main function :return: None """ board, stats = cleaner(preparation()) table(board, stats) turn(board, stats) def preparation(): """ Creates board pattern and dictionary, containing board values :return: Shuffled board ...
dd4e4883ebadb8a6623e09f1da4eaafefb75d15c
mariomendonca/Solving-problems-python
/fibRecursivo.py
158
3.59375
4
def fib(n): print(f'calculando fib de {n}') if n <= 1: return n else: return fib(n - 2) + fib(n - 1) print(fib(7)) # fib(10) # print(fib(100))
7d7df2aa2534244e01bc30880c5304bd0e98935a
mariomendonca/Solving-problems-python
/orientação_a_objetos/aula4.py
856
3.890625
4
class Mamifero(object): def __init__(self, cor_de_pelo, genero, andar): self.cor_de_pelo = cor_de_pelo self.genero = genero self.num_de_patas = andar def falar(self): print(f'ola sou um {self.genero} mamifero e sei falar') def andar(self): print(f'estou andando sobre {self.num_de_patas}') ...
a68815a2b384a6cc5eff0b8879ce4688a48afd89
mariomendonca/Solving-problems-python
/expressoes_oo.py
1,748
3.6875
4
class No(object): def __init__(self, dado=None): self.dado = dado self._proximo = None self._anterior = None def __str__(self): return str(self.dado) class Pilha(object): def __init__(self): self._inicio = None self._fim = None def isVazia(self): if self._inicio == None: ret...
d5e0ba6271759bb746c8bef131ba5c8d8c006f17
mariomendonca/Solving-problems-python
/fatorialRecursivo.py
162
3.671875
4
def fatorial(n): print(f'calculando fatorial de {n}') if n <= 1: return 1 else: return n * fatorial(n - 1) print(fatorial(1)) print(fatorial(7))
4a74596fba5738a6fc1ea4651c8b9b31527a7d99
mariomendonca/Solving-problems-python
/orientação_a_objetos/aula_professor.py
2,140
3.546875
4
class No(object): def __init__(self, dado=None): self.dado = dado self._proximo = None self._anterior = None def __str__(self): # return f'{self.dado}' return str(self.dado) class Lista(object): def __init__(self): self._inicio = None self._fim = None def isVazia(self): if ...
5bdcb416f92937e245bd6860d09c119d2eaa1ca1
wxhheian/hpip
/ch9/ex9_1.py
641
3.953125
4
class Dog(): #一般来说类的首字母大写 """一次模拟小狗的简单测试""" def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗被命令蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗...
e40b364e777e48fcd98e4bb30cfdeb4aa55c8641
wxhheian/hpip
/ch3/ex3_2.py
755
3.703125
4
# motorcycles = ['honda','yamaha','suzuki'] # print(motorcycles) # motorcycles[0] = 'ducati' # print(motorcycles) # motorcycles.append('ducati') # print(motorcycles) # motorcycles.insert(0,'ducati') #在索引0处插入元素‘ducati’ # print(motorcycles) # motorcycles.insert(1,'ducati') # print(motorcycles) # del motorcycles[0] ...
0448e9274de805b9dec8ae7689071327677a6abb
wxhheian/hpip
/ch7/ex7_1.py
641
4.25
4
# message = input("Tell me something, and I will repeat it back to you: ") # print(message) # # name = input("Please enter your name: ") # print("Hello, " + name + "!") # prompt = "If you tell us who you are,we can personalize the messages you see." # prompt += "\nWhat is your first name? " # # name = input(prompt) # ...
c017be82d19c5be167dc7d9dd51251756c3076bc
JapoDeveloper/think-python
/exercises/chapter7/exercise_7_3.py
1,405
3.9375
4
""" Think Python, 2nd Edition Chapter 7 Exercise 7.3 Description: The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/π: https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2Fa1%2Ff5%2F81%2Fa1f581c7dc6c3c581...
856461a845a16813718ace33b8d2d5782b0d7914
JapoDeveloper/think-python
/exercises/chapter6/exercise_6_3.py
1,891
4.40625
4
""" Think Python, 2nd Edition Chapter 6 Exercise 6.3 Description: A palindrome is a word that is spelled the same backward and forward, like “noon” and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and the middle is a palindrome. The following are functions that take a...
12af2132a90d11fbe573827f34f16bfa675402b8
JapoDeveloper/think-python
/exercises/chapter1/exercise1_2.py
986
3.96875
4
""" Think Python, 2nd Edition Chapter 1 Exercise 1.2 Description: try math operations and answer the questions """ # 1) How many seconds are there in 42 minutes 42 seconds? print(42 * 60 + 42) # 2,562 seconds # 2) How many miles are there in 10 kilometers? # Hint: there are 1.61 kilometers in a mile. print(10 / 1....