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
e498ed4283c63dc47c0772e06389a9e189b5b2d7
betoxedon/CursoPython
/Funções/callable_packing.py
732
3.71875
4
#!/usr/bin/python3 """calcular o preço do produto com o imposto""" def calc_preco_final(preco_bruto, calc_imposto, *params): """calcula o preço final do produtos a partir de parâmetros posicionais. que são indicados através do '*' antes do argumento""" return preco_bruto * (1 + calc_imposto(*params)) de...
069f7da88df8724e108c799d46a57686c2e3e703
betoxedon/CursoPython
/Programação_Funcional/funcoes_imutabilidade_v2.py
471
3.765625
4
#!/usr/bin/python3 from functools import reduce from operator import add # utilizando tuplas onde os valores não podem ser mudados # pode ser uma solução para a imutabilidade valores = (30, 10, 25, 70, 100, 94) # por ser uma tupla, ela não será mutável print(sorted(valores)) print(valores) print(min(valores)) print(...
d91b9125f37b549b39a412173d4d4e096ce89875
WinstonR96/Fraccionario
/Metodos/metodos.py
2,104
3.890625
4
#Declaro la clase y sus Atributos class Fraccionario: numerador=0 denominador=0 #Constructor def __init__(self, num, den): self.numerador = num self.denominador = den #Metodo ToString def __str__(self): cadena = self.numerador," / ",self.denominador return caden...
1d04d4da9740f90573981a7815b36ee143e8806d
itapogna/s21_class_library
/smallest_number.py
123
3.640625
4
def smallest_number(*, the_list, the_item): new_list = [item for item in the_list if item < the_item] return new_list
3e3091032f2b7054215ea279c504e3f8994681bf
binarybin/exp-machines
/src/objectives/logistic.py
2,008
3.625
4
""" Utils related to the logistic regression. """ import numpy as np from sklearn.linear_model import LogisticRegression def log1pexp(x): """log(1 + exp(x))""" return np.logaddexp(0, x) def sigmoid(x): return 1.0 / log1pexp(-x) def binary_logistic_loss(linear_o, y): """Returns a vector of logistic l...
c4f82abb7cdff252ae48297cadb217ff9fab3209
ByrMucahit/Machine-Learning-Algorithms
/Algorithms/MeanRemoval.py
3,076
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 9 17:25:54 2020 @author: mücahit """ import numpy as np from sklearn import preprocessing # STANDARDİZED #We need to convert values into data to between one and zero to get more succesfully result # We prepared data to operate. i...
63f58cab84527dd6512a584757d47da90e6185f8
DMvers/Physarum-VRP-Solver
/Branch and Bound Solver/code/greedyfirst.py
2,247
3.828125
4
from code import baseobjects class GreedyFirst(object): """ A very simple greedy algorithm, used for initializing more complex algo's. Nodes are sorted by their demand, and then selected i that order to be attended by first vehicle that has availible capacity. After that every route is sorted...
23db66c9a3c05e471c4a36c652eb8522ab65c5a6
OnerBerk/b-f-Python-flask
/3_user-input/code.py
263
3.75
4
name=input("enter your name : ") gretting=f"Salut {name} " print(gretting) size_input=input("combien de pied de long fait votre maison :") pied=int(size_input) metre=pied/10.8 print(f"{pied} Pied font {metre:.2f} metre") # :.2f permet de n'affher que 2 decimal
1528f381b6b211aed9fe9a48dbb380e03dbafe7d
OnerBerk/b-f-Python-flask
/17_lambdaFonction/code.py
545
4.0625
4
add=lambda x,y:x+y print(add(5,7)) #comme les fonctions lambda n'ont pas de nom on les lie a une variable print((lambda x,y: x+y)(6,8)) #ou ont definis l'action et les les argument sur la meme ligne def double(x): return x * 2 sequence =[1,3,5,7] doubler = [double(x) for x in sequence] #code classic doubled= l...
d35a45f9e59186c3a45a4519b6fe71ab2fcf199b
OnerBerk/b-f-Python-flask
/15_defaultParametreFunction/code.py
208
3.828125
4
def add(x, y=8): print(x+y) add(5) add(4, y=5) defaultY=5 def add2(x, defaultY): print(x+y) add(5) defaultY=8 #en une variable avec une valeur dans la fonction on ne peut plus la modifier add(5)
1605bc14384fc7d8f74a0af5f3eb1b03f23b1cd5
Oussema3/Python-Programming
/encryp1.py
343
4.28125
4
line=input("enter the string to be encrypted : ") num=int(input("how many letters you want to shift : ")) while num > 26: num = num -26 empty="" for char in line: if char.isalpha() is True: empty=chr(ord(char)+num) print(empty, end = "") else: empty=char print(...
cd4f74089c51889a00492c3918c3134dde50c83c
Oussema3/Python-Programming
/looping.py
101
3.578125
4
print("the odds number are above") for i in range(21): if i%2 != 0: print("i = ",i)
aa3efd739891956cf40b7d50c8e4b8211039eccd
Oussema3/Python-Programming
/conditions2.py
417
4.1875
4
#if elif age = input("please enter your age :") age = int(age) if age > 100: print("no such age haha") exit else: if age <= 13: print("you are a kid") elif age >13 and age < 18: print("You are a teenager") elif age >= 18 and age < 27: print("You are young enough") eli...
7c9f4808e2bf8155c4de96ce16e07f7a869ac4a5
Oussema3/Python-Programming
/lists1.py
151
3.578125
4
import math import random numList = [] for i in range(5): numList.append(random.randrange(0,9)) for i in numList: print(i) print(numList)
0302c283eeb9b921ba8c95120e62f49aac51a095
margonjo/Records
/1.1.py
451
3.890625
4
#Marc Gonzalez #29/01/15 #1.1 class StudentMarks: def __init__(self): self.studentName = "" self.testMark = int() new_student = StudentMarks() new_student.studentName = input("please enetr student name: ") new_student.testMark = int(input("please eneter the test score for this...
162acf35104d849e124d88a07e13fbdbc58e261b
stevewyl/chunk_segmentor
/chunk_segmentor/trie.py
2,508
4.15625
4
"""Trie树结构""" class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.data = {} self.is_word = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a...
ea5a406e74744a3861301187014ade89a9f4fcbd
hozzjss/veneer
/listing.py
312
3.53125
4
from art import Art class Listing: def __init__(self, art: Art, price, seller): self.art = art self.price = price self.seller = seller def __repr__(self): return "{art_name}, {price}.".format( art_name=self.art.title, price=self.price )
ee044d2d9b52f6e834aef6f1e7bcca7231e49018
LeilaBagaco/DataCamp_Courses
/Unsupervised Learning in Python/Chapter3-Decorrelating your data and dimension reduction/Exercises_chapter_3.py
11,955
4.15625
4
# ********** Correlated data in nature ********* #You are given an array grains giving the width and length of samples of grain. You suspect that width and length will be correlated. # To confirm this, make a scatter plot of width vs length and measure their Pearson correlation. # ********** Exercise Instructio...
eb1ba8ee65ab19dad296f9793e0a0f6ba6230100
LeilaBagaco/DataCamp_Courses
/Supervised Machine Learning with scikit-learn/Chapter_1/1-k-nearest-neighbors-fit.py
2,163
4.28125
4
# ********** k-Nearest Neighbors: Fit ********** # Having explored the Congressional voting records dataset, it is time now to build your first classifier. # In this exercise, you will fit a k-Nearest Neighbors classifier to the voting dataset, which has once again been pre-loaded for you into a DataFrame df. # I...
05be799f79b19ca74ce7c50b425da9ac5f0a3ca3
oszikr/PyHEX
/processing1.py
1,685
3.78125
4
from board import board from datetime import datetime """ The program read games and write game outcome to the output file. The output file name is generated based on input file name. The input raw_games.dat contains a list of moves corresponding to a 13x13 hex game on each line. A game represented by space separate...
160fdeed8bd2c5b06b68270bad80a238962bcb67
Arthyom/PythonX-s
/metodos.py
867
4.25
4
#### revizando los metodos de las structuras principales # diccionarios D = {1:"alfredo", 2:"aldo", 3:"alberto",4:"angel"} print D.has_key(9) print D.items() print D.keys() ##print D.pop(1) #lista = [1,2] #print D.pop(1[0,1]) print D.values() print D # cadenas cadena = "esta es una cadena de prueba esta ...
29e640f6d86c598486c8b74a57c4e088e2e75dd9
Omar-zoubi/data-structures-and-algorithms
/python/Data_Structures/linked_list/linked_list.py
3,304
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None def insert(self,data): new_node = Node(data) if self.head is None: self.head = new_node return last_node =sel...
5b516c9ac4e3e023cbdd121e938aa6d1eacecf4e
FMNN025KDC/Project-2
/differentiation.py
3,079
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 24 13:24:45 2016 @author: David Olsson, Kristoffer Svendsen, Claes Svensson """ from scipy import * from pylab import * def getGradient(function): """Returns the gradient of a funciton as a function object. Uses finite differences approximation. ...
1ee6ca7236d718e25bf2e974632c538fb061a175
Slidem/coding-problems
/string-multiply/string-multiply.py
3,500
3.515625
4
from collections import deque import copy def multiply(num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" multiplication_rows_container = MultiplicationRowsContainer() for d in reversed(num1): row = DigitAndStringMultiplicationHolder(int(d), num2) multiplicati...
9aab1afcb9f59c2c65e1856933e1ce699c9796d1
Slidem/coding-problems
/swap-nodes-in-pairs/swap-nodes-in-pairs.py
1,153
3.875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head prev = None new_head = head.next nod...
4f5024060129ad988a3b766cbd9221a20973a5b9
Slidem/coding-problems
/permutations-II/permutations-II.py
778
3.859375
4
def permuteUnique(nums): return permute(nums, set(), "") def permute(nums, permuted_keys, key): if not nums: return None if key in permuted_keys: return -1 permutations = [] initial_key = key for x in nums: remaining = nums.copy() remaining.remove(x) ...
07a1a5e20f9f03a0e72f3bcc6c9e471170640c27
KushagraChauhan/HackerRank
/array/array2.py
322
3.65625
4
#this is the left rotation question n, k = map(int, input().strip().split(' ')) c = a = [int(i) for i in input().split()] def array_left_rotation(a, n, k): for i in range(k, n + k): if i < n: print(a[i], end=' ') else: print(a[i - n], end=' ') array_left_rotation(a, n, k...
18344819e0bfa8316b45878a197559e320d041f7
Bruck1701/CodingInterview
/stringManipulation/makingAnagrams.py
730
3.796875
4
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the makeAnagram function below. def makeAnagram(a, b): hash_a = dict(Counter(a)) hash_b = dict(Counter(b)) union_hash = {**hash_a,**hash_b} count = 0 for key, value in union_h...
412de080bbbae3728b6ecb6fe3750198b0379a48
Bruck1701/CodingInterview
/Arrays/LeetCode/TwoSum.py
1,293
3.703125
4
''' Two Sum problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target. This problem is similar to the Ice cream problem from Hackerrank. What you store in the hashmap is the difference from a specific target but you check the current number of the array it is in ...
ea364a5baa704ff55a0366b04dceec86d2a0b9e8
Bruck1701/CodingInterview
/Arrays/LeetCode/defangIP.py
387
3.59375
4
""" Defang IP address """ class Solution: def defangIPaddr(self, address: str) -> str: hashmap = {} for el in address: if el not in hashmap: hashmap[el] = el hashmap["."] = "[.]" output = "" for el in address: output += hashmap[el] ...
ebcb4f204e3f8b1572da47fde4a102180bfd926b
Bruck1701/CodingInterview
/Arrays/Codility/stacksAndQueues/manhattanSkyline.py
935
3.75
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(H): # write your code in Python 3.6 if len(H) == 1: return 1 stack = [] # stack.append(H[0]) counter = 0 for el in H: if not stack: stack.append(el) els...
932afb5064029e16f6343d1247f584e0de4a2a55
melissaehong/online-python-aug-2016
/GideonLee/Assignments/oop/mathDojo/mathDojo.py
2,076
3.78125
4
# Part 1 # Create a python class that allows for add and subtract that accepts at least 1 parameter class MathDojo1(object): def __init__(self): self.total = 0 def add(self, *x): for i in x: self.total += i return self def subtract(self, *x): for i in x: self.total -= i return self def result(self)...
9fe168224f546a49bf60aa6c4f75d2f9eb904edd
rozifa/mystuff2
/ex401.py
472
3.703125
4
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def make_song(self): for line in self.lyrics: print line puff = Song(['puff the magic dragon', 'lived by the sea', 'what a cool fucking dragon']) immigrant = Song(['come from the land of the ice and snow', ...
4ee49b9f3daca7e8504953005094db95487e6152
HouseJaay/LCPractice
/657_Judge_Route_Circle.py
573
3.625
4
class Solution(object): def judgeCircle(self,moves): def move(posi,dirc): if dirc == 'U': posi[0] += 1 elif dirc == 'D': posi[0] -= 1 elif dirc == 'L': posi[1] -= 1 elif dirc == 'R': posi[1] += 1 ...
46d2c55724c2751a0f4ddeb93c60027a87ac38af
quesadap/CursoPython
/autos.py
5,536
3.78125
4
# class Autos: # def __init__(self, marca, modelo, patente, color, velocidad_maxima): # self.marca = marca # self.modelo = modelo # self.patente = patente # self.color = color # self.velocidad_maxima = velocidad_maxima # self.velocidad_actual = 0 # self.encend...
fb2e9096ebf2ab6c48b1b44cca65376601acc7c0
utukJ/zuri
/budget_oop/oop_task.py
909
3.75
4
class Budget: def __init__(self, amount=0, category="any"): self.amount = amount self.category = category def deposit(self, amount): self.amount += amount def withdraw(self, amount): self.amount -= amount def transfer(self, other, amount): self.withdraw(amount)...
3ff5a72bea73d61a9d8196c839219594b504597d
gilvpaola/Ciclos_Python
/Suma_1_hasta_n_for.py
614
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 12 09:41:18 2021 @author: USUARIO """ n = int(input("Ingrese un número entero: ")) suma = 0 # Forma correcta for i in range(1, n+1, 1): suma = suma + i print("La suma de los números enteros de 1 hasta n con parámetros 1, n+1, 1 es:", suma) # Forma incorrecta suma ...
560d6ca00a4036c921050036f3d791c9c8ed2fd2
gilvpaola/Ciclos_Python
/For_Anidados.py
644
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 12 11:25:11 2021 @author: USUARIO """ # Programa para generar secuencias con ciclo anidados n = int(input("Ingrese un número entero: ")) for i in range(1, n+1): for j in range (1, i+1): print(i, end="") print("") print("") for i in range(1, n+1): f...
b5ce09abe340df57a8a61a770f2b18916215308b
KKIverson/python_ds_alg
/parChecker.py
674
3.53125
4
# -*-coding: utf-8 -*- # 括号匹配算法(stack实现) from pythonds.basic.stack import Stack def parChecker(parstring): s = Stack() match = True pos = 0 while pos < len(parstring) and match: par = parstring[pos] if par in '([{<': s.push(par) else: if s.isEmpty(): ...
8f219f0722a5b971dab8e1f3904038197cc7ab74
KKIverson/python_ds_alg
/anagramSolution3.py
698
3.5625
4
# using Counter: O(n) solution # space in exchange of time # from collections import Counter # 空间换时间,形成字典,比对字典中key对应的value是否相等 # 时间复杂度为O(n) def anagramSolution3(s1, s2): if len(s1) != len(s2): return False # c1 = Counter(s1) # c2 = Counter(s2) c1 = [0] * 26 c2 = [0] * 26 for i in range(...
f3d8e79c234d1feebef8a9646bd850963482a298
nageshnemo/python-tkinter-media-player-practice
/messagebox.py
1,290
3.546875
4
from tkinter import * from tkinter import messagebox def finish(): root.destroy() def clear(): e1.delete(0,END) e2.delete(0, END) e3.delete(0, END) e1.focus() def divide(): try: e3.delete(0,END) a = int(e1.get()) b = int(e2.get()) c = a/b e3.insert(0,str(c...
4bd672db671a61754d0c7686669d1dca7ed95580
nageshnemo/python-tkinter-media-player-practice
/revision21(choice control).py
550
3.84375
4
# choice controls allow user to select an option from the available list of choices """ == Checkbutton """ from tkinter import * def changecolor(): if x.get() == 1: root.configure(bg = "red") else: root.configure(bg = old_color) root = Tk() root.geometry("200x200") old_color = root["bg"] x = I...
fab350d499b8157596923bfaef8a639f83dec1a3
pashamur/euler-golf
/017/p17.py
1,036
3.890625
4
#!/usr/bin/python import sys small_num = { 0 : "zero", 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five", 6 : "six", 7 : "seven", 8 : "eight", 9 : "nine", 10 : "ten", 11 : "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 1...
a8d673cf846640945cff93ea07ae11f416512f78
nirmalshah88/pygame-sudoku
/sudoku_section.py
2,534
4.09375
4
# -*- coding: utf-8 -*- import pygame from pygame.sprite import Sprite from sudoku_settings import Settings from sudoku_block import Block class Section(Sprite): def __init__(self, num, game): """Initialize Sudoku section (9 x 9 blocks)""" super().__init__() ## Initialize var...
61e5de5e94d03dd6a54066d413214363a26d5958
SABAT-dev/PROJETOS-EM-PYTHON
/TP3/Simon_Assagra_DR1_TP3 (QUESTÃO3).py
459
3.90625
4
#QUESTÃO 3: for voto in range(5): nome = str(input(f"Informe o nome do {voto + 1}º participante: ")).strip() nota = float(input(f"Informe a nota do {voto + 1}º participante: ")) #CONDIÇÃO: if nota >= 0 and nota <= 10: print() if voto == 0 or nota > nota_vencedor: vencedo...
25f91e5a79b7006e9e52ba87767661d8eec1a84a
kickccat/sample
/PandasStaudy/Study_folder/src/testInherit.py
1,111
3.546875
4
import math import numpy class Animal(object): def __init__(self, name): self.name = name def getInfo(self): print "This is animal's name: %s" %self.name def sound(self): print "The sound of this animal goes?" class Dog(Animal): def __init_...
2e98af33d4218cbf5c05240826e5916e19fb931e
Rainlv/LearnCodeRepo
/Pycode/Crawler_L/threadingLib/demo1.py
949
4.15625
4
# 多线程使用 import time import threading def coding(): for x in range(3): print('正在写代码{}'.format(threading.current_thread())) # 当前线程名字 time.sleep(1) def drawing(n): for x in range(n): print('正在画画{}'.format(threading.current_thread())) time.sleep(1) if __name__ == "__main__": ...
0a96a9e56fac1e05146792e1df951f043daed5bb
cs-fullstack-2019-spring/python-arraycollections-cw-rsalcido-1
/Grade WorkW3.py
2,415
4.0625
4
# Problem 1: # # # # # # Create a function with the variable below. After you create the variable do the instructions below that. # # # # # # arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"] # # # a) Print the 3rd element of the numberList. # # # # # # b) Print the size of the array # # # # # # c) Delete the se...
8d7f17c196cd73489492db794c2ea8db9858bfbd
Anas-Tomazieh/Python_Stack-
/inter2.py
1,591
4.09375
4
# x = [ [5,2,3], [10,8,9] ] # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'} # ] # sports_directory = { # 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], # 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] # } # z = [ {'x': 10, 'y':...
39d5510129b23fc19a86740a018f61f19638570c
duchamvi/lfsrPredictor
/utils.py
599
4.28125
4
def bitToInt(bits): """Converts a list of bits into an integer""" n = 0 for i in range (len(bits)): n+= bits[i]*(2**i) return n def intToBits(n, length): """Converts an integer into a list of bits""" bits = [] for i in range(length): bits.append(n%2) n = n//2 re...
5009218a95311bb93c7a31fcab001aa22bdc2626
mike42/pyTodo
/todolist/ListBackend.py
837
3.546875
4
class ListBackend(object): """ Class to help manage the todo-list data structure in an array """ def __init__(self): self.lst = [] self.fname = None def load(self, fname): self.fname = fname with open(fname, 'r') as f: for line in f: self....
b0401052dab558b2f3a893008e4d9261eae108e3
bhagi162/python2017fall
/4Task1.py
264
3.90625
4
def nested_sum(nested_list): total=0 for x in nested_list: if isinstance(x, int): total=total+x else: for n in x: total=total+n return total s=[4,5,6,[1,2,3],5] print (nested_sum(s))
9f594e1b409daa6b188336f1860b42ab2ff2ecd7
deyuwang/pisio
/test/comprehension.py
111
3.765625
4
''' @author: wdy ''' #comprehension print {x: x * x for x in range(3, 6)} print [x * 2 for x in range(3, 6)]
caa267957d591edadf7b2336e4cab3a4e294c4c5
kulkarpo/sparkfiles
/basic/exercise3/my-min-temperatures.py
1,449
3.625
4
from pyspark import SparkContext, SparkConf import collections def parse_line(line): """ parse the line and return required fields for performing analytics every entry has ITE00100554,18000101,TMAX,-75,,,E, [0], [1], [2], [3],[4],[5], [6] To analyse the minimum temperature by l...
3891b107447bab9fb392ffe1604ef54e772e1f5c
KostadinKrushkov/DesignPatterns
/adapter_pattern/implementation.py
1,356
3.5
4
class MetricSystem: # Target def derive_distance(self, minutes, velocity): return minutes * velocity / 60 class ImperialSystem: # Adaptee def derive_time(self, distance, velocity): return distance / velocity def derive_veloctiy(self, distance, time): return distance / time cla...
04320d7cad5a0aff770a50170feb284ac231117d
Lukasz-MI/Knowledge
/Basics/02 Operators/math operators.py
718
4.25
4
# math operators a = 12 b = 7 result = a + b; print(result) result = a - b; print(result) result = a * b; print(result) result = a / b; print(result) result = a % b; print(result) result = a % 6; print(result) result = a ** 3; print(result) # 12*12*12 result = a // b; print(result) #assignment operators a = 12 ...
77868cdb39ef46ad241e51ef21ad88e1ed1897cc
Lukasz-MI/Knowledge
/Basics/03 if and loops/nested loops.py
217
3.84375
4
from typing import List severalLists = [ ["Kate" , "John" , "Adam"], [23, 80, 122], ["banjo" , 1 , "guitar" , 2 , "vocals " , 3] ] print(severalLists) for list in severalLists: for v in list: print (v)
239372e51dabbe5107846b0926983a6e5012894b
Lukasz-MI/Knowledge
/Basics/01 Data types/13 immutable vs mutable.py
464
3.671875
4
# immutable: int, float, bool, str, tuple, frozenset a = 1 addr1 = id(a) a += 1 addr2 = id(a) print (addr1) #2243938707760 print (addr2) #2243938707792 print (addr1 == addr2) # False - diferent ids in immutable types # mutable types: list, set, dict data = [1, "Anne" , 30, "Henry"] addr1 = id(data) print(addr1)...
8e0148c31c798685c627b54d2d3fe90df4553443
Lukasz-MI/Knowledge
/Basics/01 Data types/06 type - tuple.py
907
4.28125
4
data = tuple(("engine", "breaks", "clutch", "radiator" )) print (data) # data [1] = "steering wheel" # cannot be executed as tuple does not support item assignment story = ("a man in love", "truth revealed", "choice") scene = ("new apartment", "medium-sized city", "autumn") book = story + scene + ("length",) # Tuple ...
42b0da6daa9978f806a2d4541637307753a61909
johnrichardrinehart/CodingProblems
/random/all_permutations/main.py
2,259
3.59375
4
def main(): wobt_tests() worp_tests() def wobt_tests(): tests = [ ([1,2,], [[1,2],[2,1],]), ([1,1,],[[1,1,],[1,1],]), ([1,2,3,], [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2],]) ] for i in range(len(tests)): test = tests[i] results = [] result = w...
52239420343b5adf7889dfc971f6417223b13c38
hoangnguyen1312/code-practice
/DivideAndConquer.py
3,576
4.09375
4
# Binary Search # Compare it to the middle element of array # if it is equal return result # else if it is lower , recursion first haft array # else if it is greater, recursion second half array def binarySearch (arr, element): if arr == []: return False middle = arr.index(arr[(len(arr) - 1)//2]) i...
164fcb27549ae14c058c7eaf3b6c47b58d198e6d
Dan-krm/interesting-problems
/gamblersRuin.py
2,478
4.34375
4
# The Gambler's Ruin # A gambler, starting with a given stake (some amount of money), and a goal # (a greater amount of money), repeatedly bets on a game that has a win probability # The game pays 1 unit for a win, and costs 1 unit for a loss. # The gambler will either reach the goal, or run out of money. # W...
8babc659615885331c025a366d21e21dd701ee2c
Ckk3/functional-programming
/imperative.py
1,583
4.46875
4
def get_names(peoples_list): ''' Function to get all names in a list with dictionaries :param peoples_list: list with peoples data :return: list with all names ''' for people in peoples_list: names_list.append(people['name']) return names_list def search_obese(peoples_list): ''...
d1526a3746a7e3956170475451d81f2bc9d3c1e1
codingwithchad/journal
/topscore/topscore.py
2,196
3.984375
4
import unittest def sort_scores(unsorted_scores, highest_possible_score): # if the length is 0 or 1, we can return. There is nothing to sort. if len(unsorted_scores) <= 1: return unsorted_scores # Create a list to hold all possible scores in O(m) space where m is the size of highest_possible_sco...
8edd94d0b1eaf9b1c62ae0cd63bc03385d8c5fc7
breurlucas/computer-theory
/TM-simulator/main.py
3,493
3.609375
4
# import libraries # ----------------------------------------------------------------------------- # # Lucas Breur # 29-09-2020 # Senac Computer Theory - Turing Machine Simulator # # ----------------------------------------------------------------------------- # FILE READING file = open("tm-example.txt", "r") # Ope...
b58bb5e5e2b3095373c43ef9a50bb8b3354dd96f
jccramos/My-first-repository
/threads_concurrent/05-loop.py
1,335
4.03125
4
#Muito bem, para termos uma ideia mais consolidada sobre o assunto #criaremos um loop, executanto a função 10 vezes import time import threading def any_foo(): ''' any_foo é uma função cuja tarefa leva 1 segundo para ser realizada ''' print('sleeping 1 second') time.sleep(1) print...
24fbaecc8188a65661c110fccd4437c830441f9a
deepakpesumalnai/Project
/Sample Programs/Function/Function.py
412
4.0625
4
def square(num): ''' This funtion is get square of passed number in parameter num :param num: int :return: int ''' out = num ** 2 print('in function') print(out) return out def main(): print('In main function') # square(number) if __name__ == '__main__': number = 8 ...
0b07b95409bc0997f454bc6d70cb4d358e0e8646
quentin-burthier/MT_UGC
/tools/lid_filter.py
908
3.53125
4
"""Script to filter sentences in the wrong languages.""" def main(src_path: str, tgt_path: str, src_lid_path: str, tgt_lid_path: str, src_filtered: str, tgt_filtered: str, src_lang: str, tgt_lang: str): with open(src_path, "r") as src_raw, open(src_lid_path) as src_lid, open(tgt_path, "r...
61d4723114beae66a55474d38fee9a5b90a9db56
imdeepmind/AgeGenderNetwork
/model/utils.py
892
3.703125
4
import datetime as date from dateutil.relativedelta import relativedelta # This method compares two dates and return the difference in years def compare_date(start, end): try: d1 = date.datetime.strptime(start[0:10], '%Y-%m-%d') d2 = date.datetime.strptime(str(end), '%Y') rdelta = relatived...
9d0a8bf89bb87595953b5344bd78529ae8f8b9a6
LeedsCodeDojo/Refuctoring
/Gordon_Phil_Python/versions/fizzbuzz.py.11.animal_abuse
631
3.640625
4
#!/usr/bin/python3 # Stringify the number # Over-indentation # Semi-colons # Not abuse # Magic numbers # ASCIIfication # Snooze # Cats and horses # linebreaks # Animal abuse def fizzbuzz(number): horse = 'cat'; cat = 'horse'; number = '.' * number; zzzz = chr(122) * 2 if not len(number) % len('a {1} and {0}'.fo...
8d6dae8f899541ae5683d26b8a8e8a0c87f5046a
MatthewBieda/Tenure-Track-2030
/Tenure Track.py
7,327
3.9375
4
""" Python Tkinter Splash Screen This script holds the class SplashScreen, which is simply a window without the top bar/borders of a normal window. The window width/height can be a factor based on the total screen dimensions or it can be actual dimensions in pixels. (Just edit the useFactor property) Very s...
c1fb0eb8ce344825c695e5dfcc408ff2c9f93a7e
befreeman/advent-of-code-2016
/day2/test_puzzle_two.py
4,497
4.03125
4
""" Let's test the Keypad Class! """ import unittest from puzzle_two import Keypad class TestKeypad(unittest.TestCase): """ make sure keypad works as expected! """ def setUp(self): """ set up an instance of keypad for the test cases """ self.keypad = Keypad() def test_can_make_keypad(s...
4f9b344063339fec622fae3a4ac18ceff57d10be
AlexandreCassilhas/W3schoolsExamples
/Dictionaries.py
1,370
4.3125
4
thisdict = { "brand": "Ford", "model": "Mustang", "year": "1964" } print (thisdict) x = thisdict["model"] print(x) # Acessando o valor de um elemento do dicionário z = thisdict.get("brand") print(z) # Alterando o valor de um elemento do dicionário thisdict["year"] = 2018 print (thisdict) # Varrendo as c...
5d96e91292e6591de9b42b40c5a5224e34179152
jesusapb/ADA_6-AED
/division.py
2,193
3.515625
4
''' Cambiar nombre a Castear''' class division: def __init__(self,cadena): self.cadena = cadena.pop() self.lista_cadena = [] self.nueva_lista = [] def proceso(self): self.lista_cadena = self.cadena.split() def hacer_ajuste(self): i = 0 ...
38f1ff52dd1686fe177bd44ced6a722be2ad677a
rajeshsrinivasa1981/Demo
/Unit Testing/Unittestfile1.py
738
3.546875
4
import unittest from SampleProjects.Examples import Example class MyTestCase1(unittest.TestCase): @classmethod def setUpClass(cls) -> None: print("This will run once before all the methods") @classmethod def tearDownClass(cls) -> None: print("This will run once after all the methods") ...
2988f907df24214c55e01e78ef2245a77b333a73
Roger-Yao8126/cmpe273_20spring
/cmpe273-lab1/submit/async_ext_merge_sort.py
4,269
3.75
4
#CMPE 273 lab 1 #Use any kind of External Sorting algorithm to # sort all numbers from input/unsorted_*.txt files # and save the sorted result into output/sorted.txt # file amd async_sorted.txt file. import sys import asyncio def read_file(filename): fp=open(filename,'r') contents=fp.readlines() fp.close() return ...
2e2821bc842d2b6c16a6e9a5f5252b64c4f2d097
ngenter/lnorth
/guessreverse.py
631
4.125
4
# Nate Genter # 1-9-16 # Guess my number reversed # In this program the computer will try and guess your number import random print("\nWelcome to Liberty North.") print("Lets play a game.") print("\nPlease select a number, from 1-100 and I will guess it.") number = int(input("Please enter your number: ")) if num...
5c0ea9f314a48d35fb26c039191122714f908ba1
stillsw/playzone
/interesting algorithms/python/assignments from algorithms courses/heapUtils.py
15,886
3.53125
4
import math, utils """ Home grown heap implementation, supports extractMin/Max, delete, key/priority update and fast lookup of an item (also by added optional lookup key) When calling pop() pass a function if need to do tie breaking... see pop() Note on structure: internally each entry is an array[3] comprisi...
9ec968141f9eb927247483e0f50d3ae94db70e1a
rdeaton/spyral
/rect.py
7,680
4.3125
4
class Rect(object): """ Rect represents a rectangle and provides some useful features. Rects can be specified 3 ways in the constructor * Another rect, which is copied * Two tuples, `(x, y)` and `(width, height)` * Four numbers, `x`, `y`, `width`, `height` Rects support all th...
0a2d5097d521d659c7bae0dd6ae4e0e03dfbb497
rdeaton/spyral
/color.py
1,475
3.546875
4
_scheme = {} sample = """ color,r,g,b color1,r,g,b,a """ def install_color_scheme(filename): """ Loads a colorscheme from a file, and installs the colors there for use with any spyral function which accepts a color by passing a string as the color name. You can install more than one scheme, b...
49aa5ca2f32071f9973f46886266469daab4c134
Mushinako/Advent-of-Code-2020
/Day_21/utils/read_input.py
475
3.5
4
""" Module: Read and parse input file Public Functions: read_input: Read and parse input file """ from pathlib import Path from .sentence import Sentence def read_input(path: Path) -> list[Sentence]: """ Read and parse input file Args: path (Path): Input file path Returns: (li...
f52f96dbdfd7ed61d164be91ae57dadf0f9e24c9
Mushinako/Advent-of-Code-2020
/Day_22/utils/read_input.py
604
3.671875
4
""" Module: Read and parse input file Public Functions: read_input: Read and parse input file """ from pathlib import Path from collections import deque def read_input(path: Path) -> tuple[deque[int], deque[int]]: """ Read and parse the input file Args: path (Path): Input file path Ret...
20ee733c07c2f5403b3b52004a6ec64e039f3f4f
sevgibayansalduzz/NLP-WORKS
/Corrector/driver1.py
1,041
3.546875
4
import pickle from src.convert_turkish import highest_possible_sentence, convert_to_english_letter, convert_to_turkish_letter from src.ngram import Ngram from src.hecele import text_to_syllable with open("input/tr_wiki_30.txt",encoding="utf8",errors='replace') as myfile: train_data=myfile.read() train_d...
ecab82333f58ead4bbcce3d45f8c22f93490f78a
AvTe/Python-Complex-Coding-Question
/Solution_01.py
254
3.859375
4
# Answer 1: #program which will find all such numbers which are divisible by 7 # # but are not a multiple of 5, between 2000 and 320 nl=[] for x in range(1500, 2701): if (x%7==0) and (x%5==0): nl.append(str(x)) print (','.join(nl))
b60beee10433a71d8222f45985014f0e8d206cff
AlexseySukhanov/HomeWork14
/rectangle.py
2,073
3.671875
4
class Rectangle: def __init__(self, width, heigth): self.w = width self.h = heigth def __str__(self): return str(self.w * self.h) def __gt__(self, other): if not isinstance(self, Rectangle): raise TypeError(f'{type(self).__name__} Object is not valid') i...
33291e16ed1a09f2fede35fa1471a4f07b7cd043
ruthubc/ruthubc
/PythonDispersal/src/TestsDrafts/PlayingWithFunctions.py
132
3.71875
4
''' Created on 2013-01-12 @author: Ruth ''' def add_number(number): number += 15 return number print(add_number(10))
8b47b8d751892f46f1ff397a3c1de0ca7ffde08e
olga2288/lpthw
/ex16_1.py
509
3.75
4
from sys import argv script, filename = argv print "\nWe're going to read %r" % filename print "If you don't want that, hit CTRL-C (^C)" print "If you do want that, hit RETURN" raw_input("?") print "Opening the file..." target = open(filename, 'r') print target.read() print "Now I'm going to ask you for three lines ...
f14076dac6b148114cfec193d02b35a7c16608a2
olga2288/lpthw
/ex44_my.py
659
3.828125
4
class Parent(object): def hello(self): print "\nHello all!!!" # implicite def bzz(self): print "\nI'm sleeping now!!!" print "Bz-z-z-z-z" class Child(Parent): # override def hello(self, name): self.name = name.title() print "\n\tHello %s" % self.name class Child_...
5385c94ba5e1b5fba240b6298d4858a7c4490e68
olga2288/lpthw
/ex48/ex48/lexicon.py
721
3.84375
4
words = {'verb' : ['go', 'kill','eat', 'eats'], 'direction' : ['north', 'south', 'east'], 'stop' : ['the', 'in', 'of'], 'noun' : ["bear", "princess"]} def scan(sentence): phrase_words = sentence.split() result = [] for phrase_word in phrase_words: try: number = int(phrase_w...
342d4b53dc20b586b697bc002c78c2539722fb70
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-035.py
486
4.21875
4
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. print('--=--' * 7) print('Analisador de triângulo') print('--=--' * 7) a = float(input('Primeiro segmento:')) b = float(input('Segundo segmento: ')) c = float(input('Terceiro segmento: ')) if a < b ...
de09ab5c8218bcd1993a2c5ebe5ee3143f5044a3
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-019.py
441
4.0625
4
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escrevendo o nome do escolhido. import random a1 = input('Nome do primeiro aluno: ') a2 = input('Nome do segundo aluno: ') a3 = input('Nome do terceiro aluno: ') a4 = input('Nome do quarto al...
10fd00b55bc1d02b636e346dd5b4df069349b337
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-016.py
227
3.890625
4
# Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira. import math n = float(input('Diga-me um número: ')) i = int(n) print('O número absoluto de {} é {} .'. format(n, i))
75ad294709b9191d882e38c6cb3036b545c3dbe6
LeandrorFaria/Phyton---Curso-em-Video-1
/Script-Python/Desafio/Desafio-031.py
411
3.953125
4
# Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem cobrando R$ 0,50 por Km para viagens de até 200Km e R$ 0,45 para viagens mais longas. distancia = int(input('Qual a distância em KM da viagem? ')) if distancia <= 200: preco = distancia*0.50 else: preco = distanci...
f5fdc3620c1497c1d6356752ec7129ccffe09da7
zacwentzell/BIA660D_Group_1_Project
/prediction/features.py
9,732
3.71875
4
""" More EDA and feature selection BIA660D - Group 1: Alec Kulakowski """ import pandas as pd import numpy as np data = pd.read_csv('../BIA660D_Group_1_Project/eda/hoboken_step1.csv') data.head(2) # Lets see what correlations we can draw and what new features we can create ### Feature Evaluation """ For missing restaur...
3ef9c9c658eddbd7c5eca93c0a75dc17b3c1df4d
zenghuihuang/exercise-in-c-and-python
/pset6/mario/more/mario.py
398
4.03125
4
from cs50 import get_int def main(): while True: # height is the height of the pyramid height = get_int("Height: ") if height > 0 and height < 9: break get_pyramid(height) def get_pyramid(n): for i in range(n): j = n - i - 1 print(" "...
0ff7c83cc7e96dcce7ffea36fe68941a6098cfe0
SaumyaSingh034/Python---Learning
/While1.py
849
4
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> num = 1 >>> while(num<10): print("Hi! I am ",num) num = num+1 Hi! I am 1 Hi! I am 2 Hi! I am 3 Hi! I am 4 Hi! I am 5 Hi! I am 6 Hi! I am 7 Hi! I am ...
c424471d6428f0fd07164ebc0c92a4ba33447677
SaumyaSingh034/Python---Learning
/Break2.py
145
3.875
4
while True: print("Enter a digit") num = input() var = str(num) if(ord(var) in range(48,58)): break print("You are in")
c442febe8991e40811e2b59fc65e67cde2504e47
SaumyaSingh034/Python---Learning
/AdvancePython/Argparse1.py
653
3.984375
4
import argparse def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a def Main(): parser = argparse.ArgumentParser() parser.add_argument("num", help = "The Fibonnaci number "+ \ "You wish to calculate", type = int) parser.add_argument("-...
dd37f5c73e67f7d545c3551881051a7850405211
SaumyaSingh034/Python---Learning
/FileInput/Copying.py
841
3.96875
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ufn = input("Enter your filename: ") Enter your filename: TestFile.txt >>> file1 = open(ufn,"r") Traceback (most recent call last): File "<pyshell#1>", line 1,...
7109531b80f9a2152074b258f67fd5432e909b27
SaumyaSingh034/Python---Learning
/Module/Time Module/Sleep.py
250
3.71875
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import time >>> for i in range(0,10): print(i) time.sleep(1) 0 1 2 3 4 5 6 7 8 9 >>>