blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4eec9778324cfb4e768592529b45517836ff017d
HuaTsai/ML-homework
/hw2/hw2_3.py
795
3.734375
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np def hw2_3_1(): global X, T, N, D, X_test, T_test, N_test W = np.zeros((N,D)) Softmax = np.zeros((N,1)) for i in range(N): np.mat(W).T * Ew = - T * Y #def hw2_3_2(): #def hw2_3_3(): #def hw2_3_4(): #def hw2_3_5(): #def...
dafe81b0a7e56000da290cc618327205975a6aa5
15930599706/Flight_delay_data_analysis
/analysisUseSpark/dataAnalysisByPYSpark.py
12,371
3.65625
4
from pyspark import SparkContext from pyspark.sql import SQLContext sc = SparkContext() sqlContext = SQLContext(sc) airportsData = sqlContext.read.format("com.databricks.spark.csv").\ options(header="true",inferschema="true").\ load("hdfs://localhost:9000/airports/airports-csv.csv") # airportsData.show() airp...
d7b590d0a3b60623f2476c955d8556a837285c18
daveboat/interview_prep
/coding_practice/general/random_point_in_non_overlapping_rectangles.py
2,926
3.546875
4
""" LC497 - Random point in non-overlapping rectangles Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles. Note: An integer point is a point that has integer coordinates. A point on t...
d64458e6fa2def7d8b10bf892be94c42a745aa20
bradleycarouthers/day-11_text_based_blackjack
/main.py
2,435
4.0625
4
import random from replit import clear from art import logo def deal_card(): """Returns a random card from the deck""" cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] card = random.choice(cards) return card def calculate_score(cards): """Take a list of cards and return the score calculated ...
385021313edef5f4cfd3dc97d99d67512cb295bc
rayt579/leetcode
/graph/alien_dictionary.py
3,192
3.5625
4
from collections import defaultdict, deque class Solution: def __init__(self): self.cycle_detected = None def alienOrder(self, words): return self.alien_order_dfs(words) def alien_order_dfs(self, words): if not words or len(words) == 0: return '' # create adj ...
0a5d13159230e8dac395be933b85d275cd261764
hewanshrestha/Sorting-Algorithms-in-Python
/quick_sort.py
729
3.765625
4
def quick_sort(nums): def partition(nums, low, high): pivot = nums[(low + high) //2] i = low - 1 j = high + 1 while True: i += 1 while nums[i] < pivot: i += 1 j -= 1 while nums[j] > pivot: j -= 1 if i >= j: return j nums[i], nums[j] = nums[j]...
7e05f0130fde449b5be314c2bed29f7494890de5
Pigoman/Lehman_College
/Learning_Python/cw/05_15_17_cw3.py
858
4.1875
4
#!/usr/bin/env python3 class Chocolate: def __init__(self, n, ppp, w, coo): self.name = n self.pricePerPound = ppp self.weight = w self.countryOfOrigin = coo def cost(self): return self.pricePerPound * self.weight def getWeight(self): return self.weight def getName(self): return self.name de...
30bba6092f5caef38626b4634cdb7f617b2cdadd
smswajan/mis-210
/Chapter-6/6.7-Compute-the-future-investment-value.py
558
3.765625
4
def futureInvestmentValue(investmentAmount, monthlyInterestRate, years): months = years * 12 futureInvestmentValue = investmentAmount * pow((1+monthlyInterestRate), months) return futureInvestmentValue investmentAmount = eval(input("The amount invested: ")) annualInterestRate = eval(input("Annual int...
e10b706737245850ea7bceb5a5cb3b1ef391beab
GeorgeDanicico/Fundamentals-of-Programming-Year1
/Fundamental Of Programming/Lab1/p3.py
1,483
4.125
4
# # Implement the program to solve the problem statement from the third set here # # Implement problem 15 from the Set 3 def Read_given_number(): # we read the given number number = int(input("Please insert your number: ")) return number def Is_perfect(number): # we check if the current number is perfect ...
de74044c1e7962b15de86827e4699f627d61a139
laithadi/School-Work---Data-Structures-Python-
/Adix5190_a04/src/functions.py
2,119
3.984375
4
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-02-10 ................................................... ''' from Priority_Queue_array import Priority_Queue def queue_is_identical(source1, source2):...
86e31460f1afee5cb65f1977bdd4ae1c8a384ade
Nishi216/PYTHON-CODES
/STRINGS/string1.py
523
4.59375
5
# DIFFERENT FORMAT SPECIFIERS FOR STRINGS string1="{} {} {}".format('python','is','fun'); print(string1) string2="{2} {1} {0}".format('python','is','fun'); print(string2) string3="{b} {c} {a}".format(b='python',c='is',a='fun'); print(string3) name="|{:<10} |{:^10} |{:>10}|".format('python','is','good') pr...
ed4fc0df22a3d3dd9b8ca02f60970085b535a7e3
yerassyldanay/leetcode
/pyland/algirthms/buildTree.py
752
3.609375
4
from pyland.algirthms.depth_first_search import BinaryTree class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class Solution: def build(self, pre: list, inr: list): def help(pre: list, inr: list): if not inr: ...
ddf8c98dae95aeb316309b7a6e6b49374da021de
jhand2/ml-classifiers
/models/bagging.py
1,620
3.703125
4
""" Jordan Hand, Josh Malters, and Kevin Fong CSE 415 Spring 2016 Professor: S. Tanimoto Final Project Bagging classifier. Uses multiple classifiers and votes on each classification. """ import comparison as comp class bagging(object): """ A machine learning classifier which uses bagging to combine multiple ...
ec243648e2f570befd2e4758c0bdcfdb0fe56d3b
antonyaraujo/ClassPyExercises
/Lista03/Questao17.py
463
4.1875
4
# Escreva um programa que leia dois números inteiros e faça a multiplicação de um número pelo outro # sem utilizar o operador de multiplicação (*). Imprimir na tela o valor encontrado. # Obs: Lembrar que uma multiplicação pode ser definida por uma sucessão de somas A = int(input("Informe o termo A do produto: ")) B = ...
e7544e6ff619f1118804a13782d9ed45199936b0
redrei/Ovingerogdiverse
/Pythonovinger/øving3.py
4,740
3.734375
4
# -*- coding: ISO8859-10 -*- #gjort uten Jupyter p grunn av at jeg ikke fikk tilgang til ving 3 p jupyter def tekstbasertspill(): #jeg lagde et tekstbasert spill i ving to s jeg baserer meg p den print("ving - tekstbasert spill 2") game = True lstDr = True irritasjon = 0 while(game): ...
d106abd512150000896b2346220838bb7938bb63
pBogey/hello-world
/09. Tuples/02. SwapVariables.py
365
4.21875
4
""" 16.12.2018 14:58 Value Swap Bogdan Prădatu """ def swap(x, y): print("before swap statement: x:", x, "y:", y) (x, y) = (y, x) print("after swap statement: x:", x, "y:", y) return x, y a = 5 b = 10 print("before swap function call: a:", a, "b:", b) a, b = swap(a, b) print("after swap function cal...
ffcb1db52c450bfe3f35a1a90c097e7c9d366409
KhaledAchech/Car-Evaluation
/Car_Classification.py
1,691
4.21875
4
""" this programme has for purpose to use the KNN algorithme to classify cars """ import sklearn from sklearn.utils import shuffle from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np from sklearn import linear_model, preprocessing #reading our data data = pd.read_csv("Data/car.da...
79cc74ccd6a7c9ea397196432d965b6d201720ac
jiangshen95/UbuntuLeetCode
/VerifyPreorderSerializationofaBinaryTree2.py
788
3.78125
4
class Solution: def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ nodes = preorder.split(',') stack = [] for node in nodes: if node == '#': if not stack and len(nodes) == 1: retur...
f3510c9103b4e53c41226110450e624de72be98b
Sanvit-Katrekar/Air-Hockey
/sprites.py
6,125
3.671875
4
''' This module defines game sprites. Includes: 1. Player 2. Ball ''' import math import random import pygame class Player(pygame.sprite.Sprite): ''' Class that defines the game mallets ''' def __init__(self, x, y, r, colour, xLimits=None, yLimits=None, **kwargs): super().__init__(...
5ffa0cc5f4c464354e0ac2a22d459db2eead4e2a
capric8416/leetcode
/algorithms/python3/knight_probability_in_chessboard.py
1,531
4.0625
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). A chess knight has 8 possible moves it can ma...
f48f6e507861a772c7aa2dd86a8e539dd6dc1e42
acaciooneto/cursoemvideo
/aula-23-pratica.py
710
4.03125
4
try: a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b #except: -> dá para criar vários 'except', definindo seus erros, e criando um bloco pra cada um # print('Infelizmente tivemos um problema :(') #except Exception as erro: # print(f'Problema encontrado foi: {erro.__class__}'...
7b78daa7971ca3af555c121e99b2a28a66f98d58
zuigehulu/AID1811
/pbase/day15/code/text3.py
1,029
4.0625
4
# 3.分解质因数,输入一个正整数,分解质因数 # 输入90 # 打印 90 = 2*3*3*5 # 注:质因数是指最小能被原数整数的素数(不包括1) zhenshu = int(input("输入一个正整数:")) def zhishu(zhenshu): L = [] for z in range(2,zhenshu): a = sushu(z) if a ==None: continue L.append(a) return L def sushu(z): for x in range(2,z): if z...
9a0890786351fbf78a4d04eb76aded5c6cb0d763
dmitriyVasilievich1986/home-work
/interview preparation/Lesson 03/lesson_3-3.py
985
3.6875
4
# region Текст задания """ Создать два списка с различным количеством элементов. В первом должны быть записаны ключи, во втором — значения. Необходимо написать функцию, создающую из данных ключей и значений словарь. Если ключу не хватает значения, в словаре для него должно сохраняться значение None. Значения, которым ...
93d1196dba3f7745718d64da935ad2b3e96b631e
grkheart/Python-class-homework
/homework_3_task_1.py
734
3.875
4
# Реализовать функцию, принимающую два числа (позиционные аргументы) и # выполняющую их деление. Числа запрашивать у # пользователя, предусмотреть обработку ситуации деления на ноль. def my_div(*args): try: arg_1 = int(input("Введите первое число: ")) arg_2 = int(input("Введите второе число: ")) ...
b3324c1d211dff3b4291f6dfe123e97562b247be
Follisage/ersten
/furst/index.py
132
3.875
4
def plus(a, b): return a + b def minus(a, b): return a - b if __name__ == '__main__': print(2, 2) print(2, 2)
72bea8ad8663ab5c8edd515db46de7876a3e5758
luongnhuyen/luongnhuyen-fundamental-C4E17
/Session03/example.py
914
3.890625
4
# name1="canh" # name2="hieu" # name3="duc anh" # name4="nguyen" # name5="don" # names = [] # print(names) # print(type(names)) # names = ["Canh"] # print(names) names = ["Canh", "Hieu", "Duc Anh", "Don"] # # print(names) # # # names.append("Nguyen") # print(names) # # new_name = "Don" # names.append(new_name) # pri...
f67fd93bf40ca3f02c0e9b227f8a5db46b7c006d
arjupoudel/Bitwise-Binary-Addition
/BinaryAddition.py
950
3.90625
4
def XOR_function(X,Y): if (X =='0' and Y == '1') or (X == '1' and Y =='0'): ans ='1' else: ans ='0' return ans def AND_function(X,Y): '''returns or value''' if X =='1' and Y == '1' : ans= '1' else : ans = '0' return ans def OR_function(X,Y): if ...
8251d18fbaaa77ef885e5416e99a7efd25439213
sumitkrm/lang-1
/python/ds-algo/ds/graph/ugraph-cycle-union-find.py
1,335
3.84375
4
class Graph: def __init__(self): self.vertex_list = {} def addEdge(self, u, v): if u not in self.vertex_list: self.vertex_list[u] = set() if v not in self.vertex_list: self.vertex_list[v] = set() self.vertex_list[u].add(v) def find_parent(self, paren...
b8a0e4c7a94557708a48f5acba917ea4fb585e1e
luispauloportelacoelho/solveProblems
/exercises/climbingTheLeaderboard/climbing_the_leaderboard_test.py
471
3.53125
4
from unittest import TestCase, main from climbing_the_leaderboard import climbingLeaderboard class Test(TestCase): """Test for climbingLeaderboard problem.""" def test_climbing_leader_board(self): """Test the climbing_leader_board with the given example.""" self.assertEqual(climbingLeaderboard...
530eb2a9de81a37808cfab5a1819f6cc3f15425b
itsparth20/Data-structure-and-Algorithms
/LeetCode/RemoveDuplicatesfromSortedListII.py
1,518
3.859375
4
''' Remove Duplicates from Sorted List II Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well. Input: head = [1,2,3,3,4,4,5] Output: [1,2,5] Input: head = [1,1,1,2,3] Output: [2,3] Constra...
a4428f5b0084351e5bbbe58bd6880fee65fca951
Jeniffervp/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/12-fizzbuzz.py
337
3.90625
4
#!/usr/bin/python3 def fizzbuzz(): for ran in range(1, 101): if ran % 3 == 0 and ran % 5 == 0: print(("FizzBuzz "), end="") elif ran % 3 == 0: print(("Fizz "), end="") elif ran % 5 == 0: print(("Buzz "), end="") else: print("{:d}".forma...
653aff180dbec9398935f5ca52a788d497061e07
JunDang/PythonStudy
/queue.py
603
3.875
4
class Queue(object): def __init__(self): """Create an empty set """ self.el = [] def insert(self, e): self.el.append(e) def remove(self): #result = [] try: result = self.el[0] for i in range(len(self.el) - 1): self.el[i] = s...
4b5e632b2187aacd1c4f6408c44562c69c12168f
carlinhoshk/python
/coursera/IntroduçãoÀCiênciaDaComputaçãoComPythonParte2/semana05/ex_classe_ordenador_ordenacao_bolha_bubblesort.py
2,888
3.625
4
import time from ex_classe_lista_aleatoria import ListaAleatoria class Ordenador: def selecao_direta(self,lista): fim = len(lista) for i in range(fim - 1): #Inicialmente o menor elementa já visto é o i-ésimo posicao_do_minimo = i for j in range(i + 1, fim): ...
7c44850160d6d10573ac522aa7e03627513c0907
Daneidy1807/CreditosIII
/07/ejercicio7.py
444
3.921875
4
""" Ejercicio 7. Hacer un programa que muestre todos los numeros impares entre dos numeros que decida el usuario. """ numero1 = int(input("Introduce un numero: ")) numero2 = int(input("Introduce el siguiente numero: ")) if numero1 < numero2: for x in range(numero1, (numero2 + 1)): if x%2 == 0: ...
4c30e9da68318f5cfe9b59e1b08d33ee8d5a0b68
hackrmann/learn_python
/CodeChefPractice/x1.py
269
3.578125
4
t = int(input()) for i in range(0,t): p1,p2,k = input().split() sum = int(p1) + int(p2) k = int(k) if (sum)/k==0: print("CHEF") else: if (2*(sum//(2*k))==(sum//(k))): print("CHEF") else: print("COOK")
1e555b0171bcf1428733aa077cef3499661f4dab
ebam23/crazy-rhythms
/VisualRhythms/2016/standings2016.py
1,105
3.546875
4
from urllib2 import urlopen from bs4 import BeautifulSoup from pandas import Series, DataFrame import csv def standScrape(): #Strip unique team ID out of each team URL def getID(row): cols = row.findAll('td') link = cols[0].find('a').get('href') id = link.split('&', 2)[1] return id #Get team record def g...
e9a2444936556f650b179449dadea0faed4d1b90
enlilodisho/visionalert
/TCPServer.py
2,520
3.640625
4
import socket from threading import Thread class TCPServer: # TCP Server Constructor def __init__(self, port): print("TCPServer Constructor"); self.port = port # Server Status self.running = False # Set up socket self.socket = socket.socket(socket.AF_INET, soc...
0a3939ebf759ce4acc920fac67f0c658c4b8189c
Leonardo-KF/Python3
/ex022.py
355
3.71875
4
n1 = str(input('Digite seu nome completo: ')).strip() print('Analisando...') n2 = n1.split() n3 = n1.upper() n4 = n1.lower() n5 = len(n1) - n1.count(' ') n6 = len(n2[0]) print(f'Seu nome em maiusculas é: {n3}') print(f'Seu nome em minusculas é: {n4}') print(f'Seu nome tem ao todo {n5} letras') print(f'O seu p...
209cab5aa556f37389676ccd0e601a0147a1c056
AnnissaK/BrewApp
/Source/time_function/week_selection.py
1,356
3.671875
4
from Source.data_bases.round_list import round_variables from Source.time_function.week_day import week_day from Source.data_bases.saving_databases import insert_round_data def week_day_selection(): input_owner =input('can you reconfirm whos buying the round \n') input_name = input('can you please re-confirm ...
bc2800f704d9de4ae31690e8e3c9ed0dcc3ce920
cmhuang0328/hackerrank-python
/introduction/7-print-function.py
494
4.46875
4
#! /usr/bin/env python3 ''' Read an integer N. Without using any string methods, try to print the following: 123...N Note that "..." represents the values in between. Input Format The first line contains an integer N. Output Format Output the answer as explained in the task. ''' if __name__ == '__main__': n...
0a6a16193ac833ecf4865481d019ebfe93688037
Andres-Hernandez-Mata/Scripts-Python
/src/edad.py
903
4.09375
4
""" Uso: Fecha de nacimiento Creador: Andrés Hernández Mata Version: 1.0.0 Python: 3.9.1 Fecha: 01 Julio 2021 """ edad = 0 dia = 0 mes = 0 age = 0 day = 0 month = 0 age = int(input("Hola, Ingresa tu edad: ")) while age < 0 or age > 100: print("Por favor, Ingresa un valor numerico o mayor que cero") age = int...
2f0581270302bf1e591dde9377820a7ddf09a316
valursp/Tri-Peaks
/TriPeaks GUI/test_kapall.py
3,201
3.578125
4
import unittest from Card import * from Deck import * from TriPeaks import* from kapall import* class Test(unittest.TestCase): def setUp(self): self.testCard1a = Card('H',10, 0, 0, None) self.testCard1b = Card('H',10, 0, 0, None) self.testCard2a = Card('S',5, 0, 0, None) self.testC...
834bf644903227457e47b3d876e49b6ac09df78b
CNwangbin/shenshang1
/shenshang/simulate.py
6,043
3.5625
4
import numpy as np from scipy.stats import rankdata def permute_table(m, inplace=False, seed=None): '''Randomly permute each feature in a sample-by-feature table. This creates a table for null model. The advantage of this is that it doesn't change distribution for any feature in the original table, t...
d293cebedeace1173d8cae600d678b963a6ecafb
kedarpujara/LeetCode
/PythonLeet/Graphs/CycleUndirectedGraph/try2_cycle.py
1,968
3.734375
4
from collections import defaultdict class CycleGraph: def __init__(self, f): #self.graph = defaultdict(list) self.graph, self.visited, self.recursion_stack = self.make_adj_list(f) """ """ def graph_variable(self): return defaultdict(list) """ Making an adjacency l...
6c058a2d01d53e949ac24b3942d6518817ca35fe
hillarymonge/class-samples
/drawTriPattern.py
1,135
4.03125
4
import turtle def make.triangle(myTurtle): myTurtle.penup() myTurtle.pendown() myTurtle.goto(0,0) sidecount = 0 while sidecount < 3: myTurtle.forward(100) myTurtle.right(120) sidecount = sidecount + 1 def drawMoreTriangles(m...
c8e6b22f77edb12ff8d30d5d038afb8f67704ffc
crawfordl1/ArtIntel
/5-PID/3-Racetrack/3-3.py
7,206
3.71875
4
''' Created on Mar 4, 2015 @author: Wastedyu6 TOPIC: In a 2D world, apply Proportional Controller (PID) to Robot to CONVERGE to specified Trajectory (RACETRACK) *Note: Robot converges to appropriate Goal Location (SMOOTHED PATH) --No Steering Angle Set; no need to correct for it (PID Integral) ''' # --------...
cbd2afb14f4451e7fc1dd25761fbf9558196604c
manu863018/AT06_API_Testing
/ManuelValdez/Python/Session5/Practice2/Person.py
298
3.59375
4
class Person: def __init__(self, name, lastName, age, ci): self.name = name self.lastName = lastName self.age = age self.ci = ci def printAttributes(self): print("Name:", self.name, ",Last Name:", self.lastName, ",Age:", self.age, ",CI:", self.ci)
9e2054772509ed3758eb66a2cca6b5210558e8fa
sanyamcodes26/Efforts
/DerekBanas_UDEMY/Section_27.py
1,647
3.9375
4
import random def is_prime(num): for i in range(2, num): if num % i == 0: return False return True def generator_prime(max_num): for num in range(2, max_num): if is_prime(num): yield num return double = (x * 2 for x in range(10)) def initial(): ...
ba030fa648cbbb9ec62e722599acccd1e6ee803d
sorsini4/PythonBaseball
/playerClass.py
819
3.75
4
class Player: """ __init__ is the constructor class, its called at object Any code you want to run directly after instantiation should obvi be added here """ def __init__(self, name, pos, hits, at_bats, slg, obp): self.name = name self.pos = pos self.hits = hits self...
7dfc1e8f0fc11ba16e3d6f80c7f231d8d0d23454
RLewis11769/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
412
4.25
4
#!/usr/bin/python3 """ append_write - appends string to file and returns number of characters written @filename: text file to append/write to @text: string to append to end of file Return: number of characters in text string """ def append_write(filename="", text=""): """ Appends text to end of filename """ ...
8a7d5a74873904f3b2edf659c0be3b7e6a764bb2
devops-coop/ansible-haproxy
/filter_plugins/flatten.py
766
3.640625
4
# -*- coding: utf-8 -*- def flatten(d, separator='.'): """ Flatten a dictionary `d` by joining nested keys with `separator`. Slightly modified from <http://codereview.stackexchange.com/a/21035>. >>> flatten({'eggs': 'spam', 'sausage': {'eggs': 'bacon'}, 'spam': {'bacon': {'sausage': 'spam'}}}) {'...
f273c2946b504a7aa290bd962c9dcf712b9a7b33
petesndrs/progspeed
/python/xor_shift_gen/xor.py
462
3.5625
4
def main(): SEED = 1; val = SEED; period = 0; keepgoing = True while (keepgoing): val ^= (val << 13) & 0xffffffff; val ^= val >> 17; val ^= (val << 5) & 0xffffffff; if ( (val & 0xffffff00) == 0): print('period {}, val {:x}'.format(period, val)); ...
203d29477757c14c4e3df1790e7a3a80ca658669
isakruas/lista-de-exercicios-python
/estrutura-de-decisao/25.py
1,392
4.4375
4
""" 25. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: "Telefonou para a vítima?" "Esteve no local do crime?" "Mora perto da vítima?" "Devia para a vítima?" "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participa...
53a94308a1861273ecb48de578deb61eabcc03b7
jiapingzeng/summer2020
/math151b/hw1/hw1.py
1,166
3.671875
4
from math import pow, exp def main(): q3c() def q2b(): h_vals = [0.5, 0.2, 0.1, 0.01] # step sizes t_0, t_f, y_0 = 1, 2, 2 # initial/final values for h in h_vals: t, y, steps = t_0, y_0, int((t_f-t_0)/h) for _ in range(steps): y_prev = y y = y_prev + h*(1+t...
9eb2c595ae9d2f4d3a9425a4fc9a243292f7d380
adjielogin/Bebas
/latihan6.py
184
3.71875
4
# assigment operator # += # -= # *= # /= # %= # **= var1 = 3 perulangan = [] for i in range(1,5): perulangan.append(i) # var1 += 1 print(i**var1) print(perulangan)
09a87cb60c91a4ab9f6ea244ceaeff2c3806071a
abderrahmanesaad/python-climb-learning-tutorial
/python-tips-and-tricks/Reversing-Lists/main.py
140
3.546875
4
values = [1,2,3,4,5,6,7,8] revlist = [] for index in range(len(values)): revlist.append(values[len(values) - index - 1]) print(revlist)
ddb40d141a64b97bba9a292db624aaf68084c9f6
harrys66/Bezique
/beziquePack.py
14,967
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 28 23:18:40 2019 Notes: White space/style guide? Classes: Player Score If they are dealing Hand @author: Harry """ import random import time class Card: def __init__(self, suit, value): self.suit = suit self.value = va...
cebdcec910bb050bb8e7f7c0fd4b41bed2d3bd68
captainhcg/leetcode-in-py-and-go
/bwu/linked_list/234-palindrome-linked-list.py
1,384
3.84375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: ...
47151c888d7c9cc8a0b2f8dabcda0e7d96f6edae
AlenaMcLucas/algorithmic-toolbox
/week-2/challenge-1.py3
214
3.9375
4
def calc_fib(n): fibonacci = [0,1] counter = 2 while counter <= n: fibonacci.append(fibonacci[counter - 1] + fibonacci[counter - 2]) counter += 1 return fibonacci[n] n = int(input()) print(calc_fib(n))
ef79d5f2e0c8395947dbd6bf942035710593f596
mrworksome/algorithm_python
/greedy_alg_continuous_knapsack.py
3,877
3.796875
4
#! Python3 """ Задача: непрерывный рюкзак Первая строка содержит количество предметов 1 ≤ n ≤ 10^3 и вместимость рюкзака 0 ≤ W ≤ 2 * 10^6. Каждая из следующих n строк задаёт стоимость 0 ≤ ci ≤ 2 * 10^6 и объём 0 < wi ≤ 2 * 10^6 предмета (n, W, ci, wi — целые числа). Выведите максимальную стоимость частей предметов (от...
e65b02b7fed76f99408973e01f6eb86a70fc0d8d
lomayka/PythonProjects
/NAlab2/Running.py
1,113
3.5
4
import copy class Running: arr = [[]] def __init__(self, array): self.arr = array def solve(self, arguments): b = copy.deepcopy(arguments) array = copy.deepcopy(self.arr) length = len(array[0]) l = [0] * length delta = [0] * length x = [0] * lengt...
7f8b14e239997bf36be687249ea10a5b1ce183c9
haleekyung/python-coding-pratice
/hgp_book/06_exception/book_06_1_exercise.py
944
3.765625
4
numbers = [52, 273, 32, 103, 90, 10, 275] print("# (1) 요소 내부에 있는 값 찾기") print("- {}는 {} 위치에 있습니다.".format(52, numbers.index(52))) print() print("# (2) 요소 내부에 없는 값 찾기") number = 10000 if number in numbers: print("- {}는 {} 위치에 있습니다.".format(numbers, numbers.index(number))) else: print("- 리스트 내부에 없는 값입니다.") pr...
587cd44bc09900b16127a227d0ffbc5d34af61f2
adityaapi444/python_class
/nameandphcorrect.py
259
4.03125
4
name=input("enter your name") ph=(input("enter phone no.(w/o country code)")) if(len(name)>2 and name.isalpha() and len(name)<=25 and len(ph)==10 and ph.isdigit()): print("name={}\nphone no={}".format(name,ph)) else: print("Incorrect Details")
1eb717eb00b2680a2b605ea558ffd2ca2085713a
iremkilinc99/Bil103-dev3
/Odev3_171101036.py
1,761
3.84375
4
# coding=utf-8 import crypt import string import itertools def testPass(cryptPass): salt = cryptPass[0:2] dictFile = open('dictionary.txt', 'r') for word in dictFile.readlines(): word = word.strip('\n') cryptWord = crypt.crypt(word,salt) if cryptWord == cryptPass: ...
45ef1f14cc7fed58699e2294a500f2c822ad41a5
zhongyn/coding-pratice
/wellOrdered.py
935
3.796875
4
def wellOrderedLower(n,l): if n<=0 or n>26: print 'please input an integer between 1 and 26' if n == 1: # return a list of a to z return [chr(i) for i in range(ord('a'),ord('z')-l+n+1)] result = [] # for each item in wellOrdered(n-1), # if its last character is before 'z', # we concatenate a possible char...
61d47386c8aa1aee83265d8390b32836d5c74b5d
rehmanhamza/Python_Learning_Workspace
/panda.py
721
3.671875
4
import numpy as np import pandas as pd #data = np.array([['','Col1','Col2'],['Row1',1,2],['Row3',3,4]]) #print (pd.DataFrame(data=data[1:,1:],index=data[1:,0],columns=data[0,1:])) stats = pd.read_csv('C:\\Users\\Humxa\\Desktop\\Atom\\Python\\DemographicData.csv') #print stats stats.columns = ['CountryName', 'CountryCo...
99870a56bcd0cb477277691e449ff019ce5348c0
vsamanvita/APS-2020
/Swap_without_temp.py
330
4.1875
4
#Given 2 numbers a,b,the codelet swaps the 2 numbers. #Method1:bitwise(XOR) def swap_num(a,b): a=a^b b=a^b a=a^b print("After swap") print("a:",a,"b:",b) #Method2 def swap_num1(a,b): a=a+b b=a-b a=a-b print("After swap") print("a:",a,"b:",b) print("a:",10,"b:",15) swap_num(10,15) swap_n...
f039db8ab57dc9e2686edbc711fc2dfe66bac0ac
Wanjau-Keith/Python-Lab-Practicals
/Casting.py
328
4.1875
4
#If you want to specify the data type of a variable, this can be done with casting. # Syntax x=int(value) #Casting is when you convert a variable value from one data type to another data type x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 print(x,y,z) x= int(4j) print(x)...
10a169017d0afcea745e94da6dc25bc6ca7a1c76
gtafuro/Pierin-oh
/src/main/python/rot6u.py
6,749
3.734375
4
from tkinter import * import math, os width = 800 height = 512 xc = width/2 yc = height/2 baseHeight = 135 angle = 90 shoulderLength = 105 shoulderX = 0 shoulderY = 0 angle1 = 90 elbowLength = 100 elbowX = 0 elbowY = 0 angle2 = -90 clampLength = 155 wristX = 0 wristY = 0 sec = 0 readKey = True def down(e): ...
3e8dfe16423fcf2b7eaca86dd39d03fa8a57dd0a
JulianDomingo/interviews
/333.largest-bst-subtree.py
1,725
3.875
4
# # [333] Largest BST Subtree # # https://leetcode.com/problems/largest-bst-subtree/description/ # # algorithms # Medium (31.95%) # Total Accepted: 25.8K # Total Submissions: 80.9K # Testcase Example: '[10,5,15,1,8,null,7]' # # Given a binary tree, find the largest subtree which is a Binary Search Tree # (BST), where...
76bba8f648257c5a57f5f8a3092dce6ed0e51df0
mossbanay/Codeeval-solutions
/unique-elements.py
247
3.59375
4
import sys def remove_duplicates(line): return dict.fromkeys(line.strip().split(',')).keys() with open(sys.argv[1]) as input_file: for line in input_file.readlines(): print(','.join(sorted(remove_duplicates(line))))
b4a1f36acb444dbbcda8c2f5784bde920f391748
yvallet/exo_042021
/main.py
6,572
3.53125
4
""" EXO 2021 sequence de commentaires avec triple quote 12H00 type(var) ==> type de la variable str, int, float, boolean var_alpha = str(var_num) var_num = int(var_alpha) ###### local et global ################## var=1 def my_fonction() global var var += 1 ## pas besoin de return my_fonction() ## ==> v...
c45daed2ec3e54743554a8002b74331e66b88b50
farhanswitch/cryptography-caesarcipher
/encrypt.py
705
3.609375
4
huruf = 'abcdefghijklmnopqrstuvwxyz' def Encrypt(pesan, kunci): pesanHurufKecil = pesan.lower() ciphertext = '' indeksKapital = [] for kapital in pesan: if kapital in pesan.upper(): indeksKapital.append(pesan.find(kapital)) for simbol in pesanHurufKecil: if simbol in h...
e765c273764c286e112c557ccc9c9501325425e7
potato179/pythonProjectwlswodnd
/cox pro 2급/1차시/문제2.py
579
3.828125
4
# Cox Pro 2급_1차시 # 문제2 def solution(price,grade) : answer = 0 if grade == "S" : answer = price * 0.95 # 1 : 100% 0.5 : 50% 0.25 : 25% 0.1 : 1% if grade == "G" : answer = price * 0.90 if grade == "V" : answer = price * 0.85 return int(answer) # 계산된 가격을 리턴 price1 =...
be36da505f40c34ef6e0ecfaa90aff80aa974ac1
dliberat/quince
/quince/ui/how_to_play.py
8,688
4
4
"""Generates a window that shows the basics of how the game is played.""" import tkinter as tk FRAME_WIDTH = 500 class HowToPlay(tk.Toplevel): """Window element that teaches players how to play the game.""" def __init__(self, root): tk.Toplevel.__init__(self, root) self.winfo_toplevel().tit...
297e42dd2aec7a4392498be24e0269a3298fb7e2
Darrenrodricks/EdabitPythonPractice
/EdabitPractice/printThis.py
106
3.953125
4
# Sample value : x =30 # Expected output : Value of x is "30" x = 30 print('Value of x is "{}"'.format(x))
38b57786224e217a4a895539254464ccea18fa86
sherutoppr/coding-python
/002_add_two_number.py
1,119
3.8125
4
''' you are given two linked list representing two non-negative number. the digit are sorted in reverse order and each node contain a single digit. add two number and return it as a linked list time - o(max(m,n)) where m and n are length of input of l1 and l2 respectively space - o(max(m,n)) ''' class ListNode: ...
058dfcfb707a8544dcefaf256f62ffcf3a953648
AbhiProjects/Language-Translator
/AllLanguageCodesCreator.py
450
3.796875
4
import goslate FileName='AvaliableLanguages.txt' """ FileName : Name Of The File Where All Languages Will Be Stored Stores All The Avaliable Languages In The File """ def AvaliableLanguages(FileName): gs=goslate.Goslate() language=gs.get_languages() f = open(FileName,'w') for language_key in language.keys(): ...
f67c76b3a7776737845512418b63ba3cb0269f56
hungnt2604/LearnPython
/FirstPythonProject/NumberGuess.py
456
3.890625
4
import random number = random.randint(1,20) guess = int(input("Bạn hãy đoán một con số từ 1 đến 20. Con số bạn chọn là: ")) while guess != number: if guess < number: print("Bạn đã chọn con số nhỏ hơn đáp án rồi.") else: print("Bạn đã chọn con số lớn hơn đáp án rồi.") guess = int(input("Bạn h...
50524a9b345682f3fd1e6ad3a27d85e8d7f1644c
joeySeal/mxAudit
/main.py
6,082
3.625
4
#!/usr/bin/env python3 import csv import ssl from urllib import request from html.parser import HTMLParser from html import unescape import argparse parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", type=str, help="specify name of input file, default: 'input.csv'", default='in...
bd89bb6a914be223cb4a99353e385444d1fac875
jrw5/ATBSQP
/CH6/TablePrinter.py
605
3.5625
4
#Table Printer #Joel Wheatley #1/21/20 tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(table): widthArray = [] k=0 for i in range(len(table)): if k < len(table[i]): k = len(table[i]) f...
201ed9d46a3392d4bbe71c0a7fb7cd72635c01aa
sim-num/2DpoolGameSimulation
/main.py
3,518
3.640625
4
import Tkinter as tk from Tkinter import * from pool2D import * import time # main window window = tk.Tk() window.title("2D Pool simulation") L = 505 # window size W = 473 window.geometry(str(L) + "x" + str(W)) yy = 5 # pozycjonowanie elementow GUI # labelki var = tk.StringVar() labelN = tk.Label(window, textvariab...
af0402c5a086a18f91c68c6d5a9e239eec849ea9
akankshakmr174/Py-Django
/sonali/question2.py
369
3.78125
4
def count(n): f=0 sum2=0 while f<len(n): if n[f]==" " or n[f]=="-": f+=1 else: sum2+=1 f+=1 return sum2 a=True sum1=0 while(a): c=raw_input("enter ur number in words: ") sum1+=count(c) k=raw_input("enter do u want to continue(1/0): ") i...
10bd13bddcb3243dc9193e0bbf26d76e6b45e73a
Gabarcell/Alg3
/ex03.py
1,000
4.21875
4
""" 3. Faça um programa em Python que receba (leitura do teclado) 3 notas e seus respectivos pesos, calcule e mostre a média ponderada dessas notas. Média Ponderada = (Nota 1 ∗ Peso da Nota 1)+ (Nota 2 ∗ Peso da Nota 2) ----------------------------------------------------- Soma dos Pesos das Notas ...
4ecc86fd7810aa781e2e01010494015cc5766455
SangilShim/Study-for-Coding-TEST
/Day1/Greedy/3-3_숫자카드게임.py
1,441
3.765625
4
# 숫자카드게임 행렬 형식으로 입력되면 각 행에서 가장 작은 수를 뽑고 다른 열과 비교하여 가장 큰 수를 뽑아내는 게임이다. # 첫번째 풀이 (오답) # 첫번째 입력예시를 봤을 때 (3,3)의 경우만 생각하여 풀이하였기 때문에 다른 (2,4)와 같은 다른 입력에는 오류가 생겼다. n, m = map(int, input().split()) data_1 = list(map(int, input().split())) data_1.sort() data_2 = list(map(int, input().split())) data_2.sort() data_3 = list(map(...
ab5851484ecb809eb109ea2de649b3f61d347562
lindsaymarkward/CP1404-InClassDemos-2017-2
/files.py
329
3.6875
4
in_file = open("data.txt") # text = in_file.read() # print(repr(text)) # print(text.split()) # print(in_file.readline()) # input() # print(in_file.readline()) for line in in_file: # print(line) parts = line.split(',') # print(parts) name = parts[0] age = int(parts[1]) print(name, age) in_file...
ec9557a68174a81127c06795dd8cb7bf31c7e3cc
Remyaaadwik171017/myproject2
/advancedpython/exam.py
165
4.0625
4
import re n=input("Enter a word to validate:") x="[A-Z]+[a-z]+$" match=re.fullmatch(x,n) if match is not None: print("valid:",n) else: print("Not valid:",n)
e04305a42f77289ef3d3160677ab0c424f0c8336
khasherr/SummerOfPython
/RecursionMultiplication.py
754
4.125
4
#Sher #This program does multuplication recursivelu def muliplication(m,n): if m == 0 or n == 0: #either m or n = 0 returns 0 bc 0 * anything == 0 return 0 else: # IH - give me the multiplication of m * (n-1) meaning that if i want to find multiplication of # 3 *2 --> (m ==3, n ==2) so ...
3f678de9c60c9a83f6369c7c93833b16c4ac2268
PRodenasLechuga/HackerRank
/Problem-Solving/Time-conversion.py
749
3.703125
4
#!/bin/python3 import os import sys import datetime # # Complete the timeConversion function below. # AMPM = "" hour = "" def timeConversion(s): AMPM = ''.join(x for x in s if x.isalpha()) hour = ''.join(x for x in s if not x.isalpha()) date_time = datetime.datetime.strptime(hour, '%H:%M:%S') retur...
d3992bb2e644b0f2b97a35bc0d744bf7fcb9be42
GayatriParanjothi/PythonCode
/SimpleCalculator.py
1,505
4.28125
4
# Simple calculator program while True: print("Enter 'add' to add two numbers") print("Enter 'sub' to subtract two numbers") print("Enter 'mul' to multiply two numbers") print("Enter 'div' to divide two numbers") print("Enter 'quit' to end the program") user_input = input("Entered options:\t") ...
8a11d268d5a2989d37cc0c2decd11d94439f109c
gabcruzm/Basis-Python-Projects
/project_guess_the_number/guess_the_number.py
683
3.765625
4
# Python module: code package written by Python. Available to run. They are functions already written. import random #Package of code that has functions to work with randomness in the language def run(): random_number = random.randint(1, 100) #randint is to generate an integer and the range. chosen_number = in...
e66c948d9d8311b630aeaf798695928b12101f89
Kamisi24/dottv
/python dottv/test.py
1,201
3.859375
4
import csv def compare(user, movie): comp1 = abs(user[0]-int(movie[1])) comp2 = abs(user[1]-int(movie[2])) comp3 = abs(user[2]-int(movie[3])) comp4 = abs(user[3]-int(movie[4])) comp5 = abs(user[4]-int(movie[5])) return comp1+comp2+comp3+comp4+comp5 Act_q1= "how much graffic do you like your ...
89876e7dc6048a9e9995d580dc93b6a36a7c60aa
908jyw/pythonAlgorithm
/string/findPrimeNumber.py
499
3.65625
4
# [String] 소수 찾기 - 프로그래머스 1단계 N = 100 def solution(n): answer = 0 primeNum = [2] for i in range(3,n+1): for j in primeNum: if ((i // 2) < j): primeNum.append(i) break if(i % j == 0): break if(j == primeNum[len(pri...
2b123dc647d1d17675c6011a0bc1024b94566785
Nefari0uss/grokking-algorithms
/binary_search.py
525
4.15625
4
#!/usr/bin/python3 def binary_search(list, item): low = 0 high = len(list) - 1 while low <= high: index = (low + high) // 2 num = list[index] if num < item: low = index + 1 elif num > item: high = index - 1 elif num == item: ret...
9a17b143186ba745a367a2f57213134afea2fba5
martinwr57/Tic-Tac-Toe
/BoardGame.py
21,181
4.21875
4
#!/usr/bin/env python import random import itertools import os, sys class TicTacToeGame(): """Base class for Tic Tac Toe game. """ def __init__(self): """Initializes class attributes for Tic Tac Toe game. @type moves: List @param moves: List of X a...
af6d9a06e4098fbcdcc67418aee5fffb220c0ba6
Paulacamposro/Coursera
/verificaCrescente.py
365
3.875
4
tamanho = int(input("Digite o tamanho da sequencia: ")) anterior = int(input("Digite o numero: ")) i = 1 crescente = True while i < tamanho: atual = int(input("Digite o proximo valor: ")) if atual < anterior: crescente = False anterior = atual i = i + 1 if crescente: print("cr...
c13703281726b4535965a89c8e9308a1e154f072
danganhvu1998/myINIAD
/code/PythonINIAD/turtle_keybroad.py
655
3.765625
4
import turtle import re def run(kame, cmd): if("forward" in cmd): cmdStr = 'F' elif("backward" in cmd): cmdStr = 'B' elif("left" in cmd): cmdStr = 'L' elif("right" in cmd): cmdStr = 'R' elif("circle" in cmd): cmdStr = 'C' else: print("Invalid format cmd!") return 0 cmdNum = int(re.findall('[0-9]+'...
b28ac175fdd5019bf9221dc3a82353604e01a3ad
IssacAX123/Matrices-Calculator
/home.py
2,145
3.5
4
from tkinter import * import main_classes class HomeLayout(main_classes.App): def __init__(self, windows): super().__init__(windows) self._window = windows self.__button_option_matrices_arithmetic = Button(self._windows, text='Matri...
cf0e2cac8be65918d37ef88d1271832504b25c37
malvina-s/Daily-Python-Challenges
/Day 19
634
4.09375
4
#!/python3 # Remove outliers def values(int_list, n=2): if len(int_list) >= 4: return True else: return False def remove_outliers(int_list, n=2): print('The original list you entered is: ',int_list) for i in range(0,n): int_list.pop() int_list.pop(0) print('...
df1f20cb1c68413791aa56794fb815349f8bb396
wartyz/KidsCanCode-Game-Development-
/Game Development 1-1/pygame_template.py
898
3.703125
4
# Pygame template - esqueleto para un nuevo proyecto de pygame import pygame import random WIDTH = 360 HEIGHT = 480 FPS = 30 # define colores WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # inicializa pygame y crea ventana pygame.init() pygame.mix...