blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
b5e3c7d35cda605a4b4004dee7be3da1979f0c7e
valdinei-mello/python
/definindo funções.py
2,546
4.40625
4
""" Definindo funções - funções são pequenos trechos de codico que realizam tarefas especificas; - pode ou não receber entradas de dados e retornar uma saida de dados; - muito uteis para executar procedimentos similares por repetidas vezes; OBS: se voce escrever uma função que realiza varias tarefas dentre dela ...
b29980d26d92e69517eb618b9c897ace10cde422
micheaszmaciag/organizer
/przedmiot.py
1,577
3.53125
4
from abc import ABC, abstractmethod class przedmiot(ABC): def __init__(self, typ, priorytet): self.typ = typ self.priorytet = priorytet @abstractmethod def __str__(self): pass class notatka(przedmiot): def __init__(self, priorytet, tytul, tresc, id): super().__init...
30d3b01b6c3d4a44d4cb84412478d8e62eca6285
beingp/Python-Beginner-To-Advance
/python basic/python list 1.py
216
3.515625
4
var = [1,2,3,4,5,"ashik"] # print(var[-6]) # print(111 in var) # var[0] = "Rafi" # var[2] = 33 # print(var) # del var # print(var) # del var[0] # print(var[0]) l1 = [1,2,3,4] l2 = [5,6,7,8] l1 = l1+l2 print(l1)
2bb869108f110856da18de58016b947acb5f3ac3
zadraleks/Stepik.Python_3.First_steps
/Lesson 1-4/1-4-2.py
174
4.03125
4
#Напишите программу, которая считает квадрат введённого вещественного числа. a = float(input()) print(a**2)
9b4c1af08c692c76d842037238abcb60a2b8d63a
helectron/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,234
4.03125
4
#!/usr/bin/python3 ''' module square Class Square ''' from models.rectangle import Rectangle class Square(Rectangle): ''' Creates a Square object Properties: size (int): represent width and height from Rectangle class x (int): x coordenate y (int): y coordenate ...
eaa7ba3bba44d4e5babbf559fae992fa419fbecf
D40124880/Python-Django-Flask
/Fundamentals/type_list.py
838
4.03125
4
# listing = [1, 5, 2, 7, 4] # listing = ['magical','unicorns'] listing = ['magical unicorns',19,'hello',98.98,'world'] sum_all = 0 count_num = 0 count_str = 0 string = '' for x in range(0, len(listing)): if isinstance(listing[x], int) or isinstance(listing[x], float): sum_all += listing[x] elif isinsta...
f31d51bc75bf36df3791d6a5861d11262720397e
ramvibhakar/hacker_rank
/Algorithms/Warmup/utopian_tree.py
219
3.828125
4
__author__ = 'ramvibhakar' T = input() while T > 0: height = 1 N = input() for i in range(0,N): if i%2 == 0: height *= 2 else: height += 1 print height T -= 1
12d74a39ec871d3e55c883a1dfaefc7d12cd2647
ryderaka/pykivy
/pycrpt/imagecrypt/crypt_text.py
664
3.578125
4
# -*- coding: utf-8 -*- from Crypto.Cipher import AES import hashlib def encryption(password, input_text): password = hashlib.sha256(password.encode('utf-8')).digest() encryption_suite = AES.new(password, AES.MODE_CBC, 'This is an IV456') while len(input_text) % 16 != 0: input_text += ' ' ci...
fa0890f25a4314b054341e36e367220e8640dc0b
lettier/bbautotune
/experiments/1/scripts/dist_to_standard.py
8,158
3.53125
4
''' David Lettier (C) 2013. http://www.lettier.com/ This script calculates the Lettier Distance, the Frechet Distance, and the Hausdorff Distance between the standard ball's trajectory (P) and any tweaked parameter ball's trajectory (Q). ''' import os; import sys; from os import listdir; from os.path import isfile...
b34a8e2afb2d70f1d2558540e55994bdb14a9189
tA-bot-git/python-logisticReg
/cost_func.py
1,573
4.0625
4
from sigmoid import sigmoid import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from sklearn.model_selection import train_test_split def cost_function(theta, X, y): """ Computes the cost of using theta as the parameter for logistic regression Args: theta: Parameters of...
cedfd8534d6a2ba214cccc59bd948b30fd5862a0
blaoke/leetcode_answer
/周赛/5213.py
398
3.5625
4
# !/usr/bin/env/ python # -*- coding:utf-8 -*- class Solution: def minCostToMoveChips(self, chips: [int]) -> int: chips=sorted(chips) b = [0] * 3 for i in range(len(chips)): if chips[i]%2==0: b[2] += 1 else: b[1]+=1 ...
dbe8d8e8701291da575972eb199a5e541ca8ce84
sabarna/codefights
/2sigma/Round1.py
2,324
3.75
4
#Two Sigma engineers process large amounts of data every day, much more than any single # server could possibly handle. Their solution is to use collections of servers, or server farms, to handle the massive # computational load. Maintaining the server farms can get quite expensive, and because each server farm is sim...
44ed72747887af5a03c35c16e3119fd5745b4ef3
AlfredoSG97/Prueba4_ProgramacionAlgoritmos_DuocUC
/Funciones_Pasajes.py
6,865
3.546875
4
import sys from itertools import cycle DatosCliente=[[],[],[]] rutClientes=[] validarut=0 validanombre=0 #Tarifas tarifanormal=78900 validatelefono=0 tarifavip=240000 contadorN=0 contadorV=0 pagonormal=0 pagovip=0 totales=[] #Pagos descuento=0 def menu_asientos (): print ("------MENU------") ...
2453912649ddbc3c55209b8cbb5db17a3a81c1f7
maoyalu/leetcode
/Python/200-299/242_Valid_Anagram.py
1,003
3.65625
4
import unittest from collections import Counter def solution(s, t): # ********** Attempt 1 - 2019/09/24 ********** count_s = Counter(s) count_t = Counter(t) return count_s == count_t # ********** Attempt 1 - 2019/09/24 ********** # word_dict = {} # for c in s: # if c not in...
b3fac82ade6509bca1b457eb41ae3638caf4ddfb
qiurenping/tiger
/python/study100/4.py
384
4.0625
4
# -*- coding:UTF-8 -*- year = int(input('year:\n')) month = int(input('month:\n')) day = int(input('day:\n')) days = [0,31,59,90,120,151,181,212,243,274,304,334] all_days = 0 if 0 < month <=12: all_days = days[month-1] all_days += day else: all_days = day if ((year % 4 == 0 and year % 100 ==0) or (year ...
07eeb92c77fcc63530182b9850828f531b59daa4
jasonfilippou/Python-ML
/Python-ML/PP01/pa01/code/wdknn.py
3,344
3.96875
4
''' Created on Sep 23, 2012 @author: Jason ''' from knn import KNN import numpy as np '' class WDKNN(KNN): ''' WDKNN, which stands for "Weighted Distance K-Nearest Neighbors", is a subclass of KNN, which simply stands for "K-Nearest Neighbors". The only method of the superclass t...
8c5e1d769125c0c1787dd04b69d59e99aef03d8e
wellszhao/intro_ds_wy_course
/ch02_python/code/basic_function.py
649
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 20 18:05:12 2018 @author: tgbaggio """ # 定义函数f def f(a, b): return a + b f(1, 2) # lambda表达式定义与f一摸一样的函数 g = lambda a, b: a + b g(1, 2) l = [1, 2, 3] def h(a): return a + 1 # 使用map和函数h对l里面的每一个元素加1 list(map(h, l)) # map加上lambda表达式可以...
534bc5edd8ba7d03b2feebeb5226e3b14f71fb20
lincappu/pycharmlearningproject
/日常练习/2022/2022-00/变量.py
3,666
4
4
# !/usr/bin/env python3 # _*_coding:utf-8_*_ # __author__:FLS # !!!全局变量: a = 3 def Fuc(): print (a) a = a + 1 Fuc() 这个就会出现未定义而使用的情况,因为Fuc里面的a会变成局部变量,如果要引用的是全局的那个a a = 3 def Fuc(): global a print (a) a = a + 1 Fuc() 要首先申明称全局变量,才可以。但是main函数除外 a = 3 def Fuc(): global a print (a) # 1 a = ...
c4ba156edf9ec98ec9769159a31c8ba3421b6854
jastiso/statLearningTasks
/mTurk_graph_learn_blocks/mTurk-10-node-breaks/experiment/utilities/visualize.py
805
3.796875
4
import networkx as nx import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation def animate_walk(G, walk): """ Takes a graph and walk and creates an animation that can be saved to a movie e.g. anim.save(filename.mp4, writer='ffmpeg', fps=15, dpi=dpi) ""...
a14619b0caace6ad496edae4bb997c776c631391
alexchou094/Python200805
/Day3-6.py
1,400
3.78125
4
print("歡迎進入系統") d = {} while True: print("1. 新增詞彙") print("2. 列出所有單字") print("3. 英翻中") print("4. 中翻英") print("5. 測驗學習成果") print("6. 離開") x = input("選擇功能 : ") if x == '1': while True: addv = input("請輸入要新增的單字(按0跳出) : ") if addv == '0...
11a1b7877877624c654c9ae2f86383f92580ef50
Tulasi59/python
/Python_prac/programs/examples.py
7,004
4.25
4
"""factorial of a number For example factorial of 6 is 6*5*4*3*2*1 which is 720. """ from functools import reduce # with recursion def factorial(n): if n==1 or n==0: return 1 else: return n*factorial(n-1) # print(factorial(6))#720 #without recursion def factorial_without_recursi...
171833217a85a6eac7b4103d8e390371c7617f16
Krugger1982/Algoritmes_SD
/Less_2_10.py
5,762
3.5625
4
class Vertex: def __init__(self, val): self.Value = val self.Hit = False class Stack: def __init__(self): self.stack = [] def size(self): return len(self.stack) def pop(self): if len(self.stack) > 0: return self.stack.pop() return ...
a8e294a911745e8ae91f84e29b189632e8d78fa6
lakshyarawal/pythonPractice
/Bitwise Operators/basic_operators.py
1,278
4.46875
4
""" Bitwise Operators """ """ AND Operator: 1 when both bits are 1 """ def and_operator(a, b) -> int: return a & b """ OR Operator: 1 when any one of the bits is 1 """ def or_operator(a, b) -> int: return a | b """ XOR Operator" 1 when both bits are different """ def xor_operator(a, b) -> int: re...
75d5209d0b72233136af8b88c12b4e989f6aee0a
vishalpmittal/practice-fun
/funNLearn/src/main/java/dsAlgo/leetcode/P12xx/P1268_SearchSuggestionsSystem.py
3,959
3.953125
4
""" tag: trie, recursion Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more...
afc02dbc54281ccbb197b72f334eee6f9f78165c
GLAU-TND/python-lab-chiragsr
/q2.py
292
3.921875
4
while True: try: x = int(input("Hey, enter a no.")) break except (AttributeError): print("Its, not a valid attribute.") except (TypeError): print("Its, not a valid type.") except (ValueError): print("Its, not a valid value.")
472f0cb42c1fce6033b169989cabb6a45ac353c5
Mark1002/ds_algo_pratice
/leetcode/106.py
1,439
3.875
4
"""106. Construct Binary Tree from Inorder and Postorder Traversal url: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ """ from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left se...
972de7c7132745f38bd8f9fbafc38be24923fbc0
Christian12c/Pathfinding-Algorithm-Visualisation-Tool
/recursiveDivisionVisualised.py
5,623
3.71875
4
#Importing modules, procedures and constants that are referenced in this file from random import choices from random import randint from random import randrange from math import floor import pygame import sys from pygame_Setup import SCREEN, BLACK, WHITE, PURPLE, BLOCK_SIZE, GRID_HEIGHT, GRID_WIDTH from time im...
556e44bc1fbfc4357f21caea828af854702da5a2
HaliteChallenge/Halite-II
/bot-bosses/tscommander/hlt/entity.py
14,889
3.8125
4
import math from . import constants import abc from enum import Enum class Entity: """ Then entity abstract base-class represents all game entities possible. As a base all entities possess a position, radius, health, an owner and an id. Note that ease of interoperability, Position inherits from Entit...
256318081ce2ae6b6dfdaaa922a449f15a8ebb0a
Ankit-Developer143/Programming-Python
/edabit/Check Array One Is Similar To Other.py
137
3.59375
4
def check_equals(lst1, lst2): if (lst1[::] == lst2[::]): return True else: return False print(check_equals([1, 2], [1, 3]) ) #False
3768f849a4129191f322b6d20b3becdd7101bc89
ApexTone/Learn-Python
/PythonBasic/23TryExcept.py
340
3.9375
4
# Like try/catch error handling try: cursed_value = 10/0 # Produce ZeroDivisionError number = int(input("Enter a number: ")) # User might try input string here print(number) except ZeroDivisionError as err: print(err) except ValueError: print("Invalid input") except: # Generic exception prin...
17ee04365dd398ece2b5b6bf3dfa0bdc4b6e1383
amansouri3476/ML-Course-HW
/HW1/Plotter.py
4,050
3.515625
4
# Import Pandas import pandas as pd # importing libraries for the plots. # import matplotlib import matplotlib.pyplot as plt import numpy as np # Load data file_name = "iris.csv" name = ["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm", "Species"] iris = pd.read_csv(file_name, sep=",", names=...
8116adb47a51dc01d5520a17a8539182c90dded5
mmarget/project-euler-python
/problem003.py
562
3.84375
4
#Project Euler Problem #003: Largest prime factor #What is the largest prime factor of the number 600851475143 cunt = 600851475143 i = 1 largestPrime = 0 def isPrime ( i ): c = 2 ret = True while c < (i**0.5) + 1: if i % c == 0: ret = False break c = c + 1 return...
000ffcb23548df284ba54de3b0a04587105fa3a9
kleberfsobrinho/python
/Desafio031 - Custo da Viagem.py
201
3.734375
4
distancia = float(input('Entre com a distancia da viagem: ')) if distancia <= 200: preco = distancia*0.5 else: preco = distancia*0.45 print('O preço da viagem ficou por: {} R$'.format(preco))
d776ba38813bfd3d9567b74bdbb06b85ddb89d46
yjiakang/Bioinfo-Practice
/extract_fa.py
658
3.703125
4
# -*- coding: utf-8 -*- ''' #This is a script for extracting sequence from a fasta file ''' import sys def usage(): print('Usage: python3 script.py [fasta_file] [idlist_file] [outfile_name]') def main(): fo = open(sys.argv[3],"w") dic = {} with open(sys.argv[1],"r") as fi: for line in fi: if line.startswith(">...
7084a1772eda50c6326361314aa6b43c01d67716
emmacallahan/tic-tac-toe
/tictactoe.py
1,808
4
4
print("Let's play Tic-Tac-Toe!") board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] player_1 = 'X' player_2 = 'O' current_player = player_1 def print_board(): for row in board: print(row) def is_input_valid(row, column): if 0 > row or row > 2 or 0 > column or column > 2: return False ret...
f95b776ee7418c016e15d87795717892503bf7be
kasrasadeghi/cs373
/notes/07-05.py
1,998
3.734375
4
# ----------- # Wed, 5 Jul # ----------- """ mimic relational algebra in Python select project joins cross join theta join natural join """ """ movie title, year, director, genre "shane", 1953, "george stevens", "western" "star wars", 1977, "george lucas", "western" ... """ """ d...
60b73a744e6ba191e4d4f2a9262173306d6b2346
OksKV/python
/Lesson1.py
2,213
4.15625
4
# Task 1 variable1 = 10 variable2 = 4.5 print("This is an example of integer number: " + str(variable1) + "\nAnd this is an example of float number: " + str( variable2)) name = input("What is your name?") age = input("How old are you?") print(f"Hey, {name}! You don\'t look like you\'re {age} years old!") # Task 2...
2ee57917b0c36c3aaa7f967801eb591a739b11f3
MEAJIN/Baekjoon
/L5/2577. 숫자의 개수.py
478
3.921875
4
#1 A = int(input()) B = int(input()) C = int(input()) all_multiplication_str = str(A*B*C) for i in range(10): all_multiplication_count = all_multiplication_str.count(str(i)) print(all_multiplication_count) #2 total = 1 for _ in range(3): i = int(input()) total *= i # 3개의 정수를 곱함 total_str = str(tota...
17904f27eb1046d423431234493967e54dc44b9e
lucsikora/exercise
/201710_ex06.py
430
4.40625
4
# practicepython.py # # Solution by: Lukasz Sikora # Date: 25th October, 2017 # # Ask the user for a string and print out whether this string is a palindrome or not. # (A palindrome is a string that reads the same forwards and backwards.) a = input("Hi, Please give me random word: ") b = a[::-1] if a == b: print(...
0dbfb8c2812fbf50a17b7a5458711aa625cd6a95
GoodieBag/chat-server-iot
/bot.py
1,498
3.96875
4
from motor_driver import Motor import time class Bot: """ A class used to represent a bot with two DC motors Attributes ---------- NA Methods ------- move_forward() moves the Bot in forward direction move_backward() moves the Bot in backward direction turn_l...
1ee290978482cfdd70864c26c3e7636baa152f8f
Harshil78/Python
/str.py
340
4
4
str = 'hello world' print(str) print(str[0:9]) print(str[-7:-3]) print(str[:5]) print(str[6]) str1 = input("Enter any String:") print(str1.isalnum()) print(str1.isalpha()) print(str1.isdigit()) print(str1.islower()) print(str1.isupper()) print(str1.isspace()) print(str1.find('co', 10)) print(str1.find('co', 10, 15)) ...
32807790b88b45c2461d30ec38eae6c63079124a
DSHaworth/MurachPython
/Assignment/Assign4a.py
607
3.890625
4
def main(): size = int(input("Hello, please enter an integer value the size of your list: ")) star_list = [] for i in range(size): val = int(input("Please enter a value between 1 and 10 (inclusive): ")) if val > 10: val = 10 elif val <= 0: val ...
a283a9a03926914ce04668593630a31ab8b08725
zVelto/Python-Basico
/aula12/aula12.py
447
3.9375
4
""" Operadores Lógicos and, or, not in e not in a = '' b = 0 if not a: print('Ta errado') nome = 'Welton Carvalho' if 'n' in nome: print('ta aqui') if 'w' not in nome: print('Aqui tbm') """ usuario = input('Nome de usuário: ') senha = input('Senha do usuário: ') usuario_db = 'Welton' senha_db = '123...
50da1687240712828ddb5e8404f73bedafe3ec3a
ofentsekgomotso94/higher-lower-game
/main.py
2,381
3.71875
4
from art import logo, vs from game_data import data import random import os print(logo) end_of_game = False score = 0 # print(len(data)) def generate_list_dictionary_A(): dictionary_A = random.choice(data) # print(dictionary_A) return dictionary_A def generate_list_dictionary_B(): ...
596aedcf32f114a5b035e699a18db81f4c2e05e1
likeweilikewei/Python-study-demo
/pandas_test/pandas_to_dict.py
935
3.5625
4
#! /user/bin/env python # -*- coding=utf-8 -*- import pandas as pd pd_dict = {'code': ['000001', '000002'], 'inc': [1, 1.1], 'name': ['平安银行', '万科A'], 'price': [3, 3.1], 'rate0': [4, 4.1], 'rate1': [5, 5.1], 'rate2': [6, 6.1]} pdData = pd.DataFrame(pd_dict) print(pdData) print(pdData.to_dict()) # T会让索引为键,默认...
f6da547ef7d818a505e3618e7c8c9eecfdbfff91
indranarayan12/Logs-analysis
/logs_analysis.py
1,977
3.671875
4
#!/usr/bin/env python3 # using Postgresql import psycopg2 # query_1 stores most popular three articles of all time query_1 = """select articles.title, count(*) as num from logs, articles where log.status='200 OK' and articles.slug = subdtr(log.path,10) group by articles.title order by num desc limit 3;""" # query_2...
d79927fd530f49188c71e7ae1b08b9d7caf66b46
datakortet/dklint
/dklint/pfind.py
834
3.65625
4
#!/usr/bin/python """`pfind path filename` find the closest ancestor directory conataining filename (used for finding syncspec.txt and config files). """ import os import sys def pfind(path, fname): """Find fname in the closest ancestor directory. For the purposes of this function, we are our own closes...
7c3c888e16db2362ae804b29402d0d67930d2711
NataliyaPavlova/WordSearch
/word_search.py
4,428
3.875
4
import codecs import sys import re import argparse class Dict: def __init__(self, filepath): self.filepath = filepath def make_dict(self): #make a dictionary of words; group words by their lengths with codecs.open(self.filepath, encoding = "utf8") as f: ...
d8a6583ccf82efcee73aa8b62d21c1b7810159a0
Vince249/Projet_Python_COVID
/Projet_Python/Projet_Python/methode_JSON/methodes_JSON.py
4,184
3.578125
4
#Mettre ici les méthodes de lecture/écriture JSON # Python program to update # JSON from datetime import datetime import json from datetime import date,timedelta # function to add to JSON def write_json(data, filename): with open(filename,'w') as f: json.dump(data, f, indent=4) return def EnregistrerClient...
b33cd202f48ae05efcfa8fe1d93f7ae7d41ef690
OliverIgnetik/tkinter_practice
/python_namespaces.py
528
3.765625
4
# illustration why importing everything from tkinter is a bad idea # the namespace is absolutely cluttered ################################################ num1 = 5 num2 = 3.142 s = 'hello' def add_two(num1, num2): print('function/local namespace') print(dir()) return num1+num2 sum_of_numbers = add_two...
70ad62d28607d8ecfc46ef97b522cc86090629b6
mayaragualberto/Introducao-CC-com-Python
/Parte1/Semana4/Cartões.py
435
3.921875
4
meuCartão=int(input("Digite o número do seu cartão de crédito: ")) cartãoLido=1 encontreiMeuCartãoNaLista=False while cartãoLido!=0 and not encontreiMeuCartãoNaLista: cartãoLido=int(input("Digite o número do próximo cartão de crédito: ")) if cartãoLido==meuCartão: encontreiMeuCartãoNaLista=True if encontreiMeuCar...
c2b43f193dca6df62b9a5488ebd8d91c963d201d
cedenoparedes/Python-course
/calc/calc.py
1,275
3.9375
4
def main(): def sumar(a,b): return a+b def restar(a,b): return a-b def multiplicacion(a,b): return a*b def division(a,b): return a/b print "Calculadora" print "Bienvenido" print "Introdusca el primer numero" a = int(raw_input()) ...
d68c21bb62a72eb51827fb84a3febb1edaf2450f
hoangdat1807/pycharm_test-
/ex11.py
502
3.828125
4
from datetime import datetime, date # a= datetime(2017, 11, 28, 23, 55, 59, 34280) # print("year =", a.year) # print("month =", a.month) t1= date(year = 2018, month = 7, day= 12) t2= date(year = 2017, month = 12, day=23) t3= t1 - t2 print("t3 =", t3) t4 = datetime(year = 2018, month=7, day =12, hour =7, minute =9, sec...
a506101ac9977d230b7633e80fb59aa2d597aa63
frankieliu/problems
/leetcode/python/116/sol.py
736
3.921875
4
7 lines, iterative, real O(1) space https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37484 * Lang: python3 * Author: StefanPochmann * Votes: 84 Simply do it level by level, using the `next`-pointers of the current level to go through the current level and set the `next`-pointe...
9ff50b16965da22dd76ebba422753a10d7ef8f09
jmkd0/ProjetGestionDeStock
/main.py
663
3.578125
4
import re #Ouverture du fichier en lecture file = open('file2.txt',"r") lines = file.readlines() #initialisation d'une liste vide liste = [] for line in lines: #Enlever l'espace et le \n de ma cdc line = re.split(' |\n',line) #Supprimer les '' de la liste if '' in line: line.remove('') #C...
0cf7d21514bdcf1cb6ed07e1dceade7fff4d8e8e
idosilverwater/ai-project
/BackTrackHeuristics/Degree.py
1,266
3.90625
4
from BackTrackHeuristics.VariableHeuristic import * class Degree(VariableHeuristic): """ This class represents Degree Heuristic. """ def __init__(self, variables): """ Creates a new degree heuristic object. :param variables: A list of variable objects. """ Vari...
82852b31b7d5a7c41e9ec077779d77b80197490f
abhimanyupandey10/python
/while_loop.py
176
4.09375
4
# This program prints even numbers till the limit entered. limit = int(input('Enter limit: ')) i = 1 while i <= limit: if i % 2 == 0: print(i) i = i + 1
eff7c25fe670111dd807f52eb19c1c816f3586f0
eduardhogea/Algorithms-and-Datastructures
/montecarlo.py
2,059
3.890625
4
from random import random class MonteCarlo: def __init__(self, length, width, rectangles): """constructor :param length - length of the enclosing rectangle :param width - width of the enclosing rectangle :param rectangles - array that contains the embedded rectangles :...
3c28abdd0b44d4d03a65b34e4d5cb661e8e7cb5e
mouryay/python
/factorial.py
455
4.34375
4
""" Get user input to find the factorial of the number, given by the user. The output should be on a single line. """ user_num = int(input("Enter a number: ")) if user_num < 0: print("Factorial of a negative number is not defined.") elif user_num == 0: print("Factorial of 0 is 1.") else: factoria...
e7b39f326cd9db257c45d81bf05393d7d622da83
brianweber2/project2_battleship
/ship.py
1,221
3.734375
4
from constants import VERTICAL_SHIP, HORIZONTAL_SHIP, SUNK, HIT, MISS class Ship(object): """ Ship with name, size, coordinates, and hits. Args: name (str): Name of the ship size (int): ship size in board spaces coords (list[str]): list of ship board coords direction (str)...
d3ecd2b94eb361f1fe2c6d235b019c4c10849843
WangZhengZhi/GoFile
/python/hello.py
98
3.671875
4
import turtle bob=turtle.Turtle print(bob) turtle.mainloop() for i in range(4): print("hello")
84ff97cf3df389ee8521da8e41bb542e7edd6fe4
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/anagram/f34e7f6d9be84c8cbf674e37cf512a8b.py
617
4.09375
4
#!/usr/bin/env python """ Anagram Write a program that, given a word and a list of possible anagrams, selects the correct sublist. Given `"listen"` and a list of candidates like `"enlists" "google" "inlets" "banana"` the program should return a list containing `"inlets"`. """ class Anagram(object): def __init...
ebcb89be32b6d81d7659452b6ced7adc3f067ff2
Carlisle345748/leetcode
/283.移动零.py
1,652
3.515625
4
class Solution1: def moveZeroes(self, nums: List[int]) -> None: """ 把遇到的非零数依次放到数组的前面,遍历完一次数组后,所有的非零数组都按原有顺序排列在前面了,最后再把后面的数字都设为0就好 """ nonzero = 0 for i in range(len(nums)): if nums[i] != 0: nums[nonzero] = nums[i] nonzero += 1 ...
709d40ce816b16fc9b764fff094c3c9cf7289e47
domdew23/Machine-Learning-Algorithms
/supervised_learning/forge.py
2,524
4.03125
4
# Two types of supervised learning: # Classification - the goal is to predict a class label, which is a choice from a predifined list of possibilites # Regression - the goal is to predict a continous number, predicted value is an amount import mglearn import matplotlib.pyplot as plt from sklearn.model_selection import...
fa5e284c746230c7aa93de3bc2ec5ca0c1fe4aab
gdh756462786/Leetcode_by_python
/Tree/Construct Binary Tree from Preorder and Inorder Traversal.py
1,371
3.96875
4
# coding: utf-8 ''' Given preorder and inorder traversal of a tree, construct the binary tree. ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, preorder,...
7272d0efc6ce49b4a779fb71a066a76b0262cd5e
vamsitallapudi/Coderefer-Python-Projects
/programming/dsame/trees/PreOrderTraversal.py
324
3.546875
4
class BinaryTreeNode: def __init__(self, data, left, right): self.data = data self.left = left self.right = right class Tree: def preOrder(self, root: BinaryTreeNode): if root: print(root.data) self.preOrder(root.left) self.preOrder(root.rig...
911674ffd7230a16bfdabfc28806f80b013026dc
groversid/holbertonschool-python-camp2
/0x02-python_if_else_loops_functions/1-odd_or_even.py~
122
4.125
4
#!/usr/bin/python3 number = 12 if number % 2 ==0: print (number + 'is even') else: print (number + 'is odd')
62fc9ae8322e0fdfc394240eade0e2a2e70da54a
arched1/Hangman
/hangman.py
4,101
4.15625
4
import random from words import word_list # Get a random word from the words.py file. def get_word(): selected_word = (random.choice(word_list)) return selected_word.upper() # Based on the stage of the game, the correct hangman illustration will be shown. def display_hangman(tries): stages = {0: "\ |---...
2a6085a5ccaca023de72b93ca2ae6f1a184b3e4b
PurnaKoteswaraRaoMallepaddi/Design-1
/HashMap.py
1,954
3.84375
4
""" Time complexity: Put: O(1) Get: O(m) where m is the hashmap size we difined Remove: O(m) Space complexity: O(1) for every thing. """ class Node: def __init__(self,tup = [-1,-1],next = None): self.next = next self.tup = tup class MyHashMap: def __init__(self): """ ...
c9d723798eae1de520aa751d82e474fe26109531
mkodekar/PythonPractice
/Loops.py
254
3.921875
4
condition = 1 while condition <= 20: print(condition) condition += 1 while True: print('doing stuff') break exampleList = [1, 2, 3, 4, 5, 6, ] for eachNumber in exampleList: print(eachNumber) for x in range(1, 3): print(x)
5e086b9d944b4c3a54da5ff168dadfb709c7816e
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/88-合并两个有序数组.py
1,582
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6] 来源:力扣(LeetCode) 链接:https://l...
bdea67f523c17d67fe9d9f889e06cb1c783e2d33
sugia/leetcode
/search-insert-position.py
642
3.890625
4
class Solution: #given a list of integers and an integer #return an integer def searchInsert(self, A, target): if len(A) == 0: return 0 if target <= A[0]: return 0 if target > A[-1]: return len(A) left = 0 right = len(A) - 1 ...
dba42242972435d05cfe70beadb2004aaaada03a
RalapIT/Python-
/Python基础源码/day02/homework/05.猜数字游戏.py
252
3.84375
4
import random num2 = random.randint(1,999) for i in range(10,0,-1): num = int(input("请输入一个数字:")) if(num < num2): print("小了") elif(num > num2): print("大了") else: print("正确") break
a1f8ad2ff76084762e464981944419ef9777a68f
anuj-padmawar/Hackerrank_Python_codes
/itertools.product().py
237
3.84375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import product A = raw_input().split() A = list(map(int, A)) B = raw_input().split() B = list(map(int, B)) for i in product(A, B): print (i),
5ba9a5ba3be4b78e0c0073205aa13ad7aa0ed946
qizongjun/Algorithms-1
/Leetcode/Binary Search/#222-Count Complete Tree Nodes/main.py
1,512
3.9375
4
# coding=utf-8 ''' Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclus...
62babbf6532c5a5fcb41b58b26221c127034c2a9
rlankin/advent-of-code
/2015/day1.py
652
3.515625
4
def part_1(): floor = 0 with open('input/day1_input.txt', 'r') as f: while True: direction = f.read(1) if not direction: break floor += 1 if direction == "(" else -1 print("Part 1: " + str(floor)) def part_2(): floor = 0 count = 0 ...
807aee2b956adf7427a93928566a3614406a7bf1
welchsoft/assignment-5.4.2018
/bonus/descriptive.py
1,017
4
4
#set up the dictionary number_names = { 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', 17 : 'seventeen', 18 :...
1502c118ab8e83c65f2a0fb257adad98ba79dfd0
FrankieZhen/Lookoop
/python/设计模式/适配器模式/adapter.py
990
3.640625
4
# coding:utf-8 # 2019-2-4 """适配器让两个或多个不兼容的接口兼容""" class Human(object): def __init__(self, name): self.name = name def speak(self): print('{} say hello.'.format(self.name)) class Mp3(object): def __init__(self, name): self.name = name def play(self): print("play song: {}".format(self.name)) class Com...
696dc7a0a52d9e11019a636f7cb45ef88d4332ff
rafaelperazzo/programacao-web
/moodledata/vpl_data/390/usersdata/313/77354/submittedfiles/ex1.py
193
3.796875
4
a = int(input( ' digite o valor de a ' )) print( '%d' % a ) b = int(input(' digite o valor de b ' )) print( '%d' % b ) c = int(input(' digite o valor de c ' )) print( '%d' % c ):
7653991b2510b90937d12076b42daefa935d4b1c
mwilso17/python_work
/OOP and classes/users.py
2,142
4.3125
4
# Mike Wilson 20 June 2021 # this program simulates the creation of a user profile. class User: """create a user profile""" def __init__(self, first, last, user_name): """initialize self and attributes""" self.first = first self.last = last self.user_name = user_name self.login_attempts = 0 ...
62724d4cae2bc9a43f7bf497cd52300c09bcce53
Web-Control/PythonCourse
/Kurs Pirple/Homeworks/importing/importing_csv.py
2,061
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 3 17:43:35 2021 @author: psnma """ import csv #Open and read csv file #Open and reading csv file as a list with open('username.csv', 'r') as csvfile: csvReader = csv.reader(csvfile,dialect='excel', delimiter=';') # ============================================...
8c2368dd1e03fa781c9f8fed1becb26ea7679d7b
MollyKate-G/file_managment_MG
/bank.py
1,284
4.09375
4
def bank_assign(): print("Welcome to MollyKate's Bank ATM") balance = 0 choice = '' def user_balance(): global balance print(f'Available funds: $ {balance:,.2f}') def user_deposit(): global balance deposit_amount = (int(input("Enter deposit amount: "))) ...
4680b40d7469b3dbe4b0c02d8d421500220213d6
Shiuay/Flower-Simlator
/Programme/bin/Meteo.py
6,027
3.546875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 31 20:01:52 2016 @author: Roméo """ from random import * def test_degage(duree): tirage = random() if tirage < 0.1 * (1 + (1 / -duree)): return ["Nuageux3", 1] if tirage < 0.3 * (1 + (1 / -duree)): return ["Nuageux2", 1] if tirage < 1...
3c3f1c5542c94fdcc8467a916bf625af3e826648
Agoming/python-note
/3.高级语法/多线程和多进程/多线程案例1-18/15.py
840
3.546875
4
# encoding:utf-8 # 可重入锁,当同一个线程在未释放同一把锁的情况下,可再次申请的操作 import threading import time class MyThread(threading.Thread):# 继承多线程写法 def run(self): global num time.sleep(1) if mutex.acquire(1):# 申请超时超过一秒则不申请 num = num+1 msg = self.name +"set num to"+str(num) prin...
9f64a972565f160af0b5af30acaff4a8d5a03e6b
harrisonmk/ListaPython
/src/Lista.py
4,762
3.625
4
from No import No class Lista: def __init__(self): self.primeiroNo = None self.ultimoNo = None def isEmpty(self): return self.primeiroNo is None def tamanho(self): atual = self.primeiroNo cont = 0 while atual is not None: cont = cont + 1 ...
bb79d4598bd0d766341f0386fcb15bacd98f555f
famaf/Modelos_Simulacion_2016
/Practico_06/ejercicio04.py
2,594
3.71875
4
# -*- coding: utf-8 -*- import random import math from distribuciones import * def generarM(): """ Genera M tq' M = {n : U1 <= U2 <= ... <= Un-1 > Un} """ n = 2 U = random.random() # Un-1 Un = random.random() # Un while U <= Un: n += 1 U = Un # U pasa a ser Un (nuevo Un-1...
2225823a13a994841afcc2491fef853f637eb591
Shihab-Munna/Learning-Python3-
/namota.py
108
3.71875
4
n = int (input("Please enter a number :")) c = 1 while (c <= 10): print( n,'X' ,c ,'=', n*c) c+=1
e889b83948245996339bef194c3a89b2cbe97431
quockhanhtn/artificial_intelligence_exercise
/ex4_n_queens_with_and_or_search/ex4_main.py
7,069
4.03125
4
#nguồn: code thầy phần class NQueensProblem: # Solve N-queens problems using AND-OR search algorithm ''' YOUR TASKS: 1. Read the given code to understand 2. Implement the and_or_graph_search() function 3. (Optinal) Add GUI, animation... ''' import tkinter as tk from PIL import ImageTk, Image import time as t class ...
d3b3f1a947ca07038d4244ee054da6bade648fae
ghanshyamdhiman/gsdss
/c1.py
401
3.71875
4
import calendar import datetime yy = 2020 mm = 12 the_cal = calendar.TextCalendar(calendar.SUNDAY) cal_display = the_cal.formatmonth(2020,11) # display the calendar print(calendar.month(yy, mm)) print(cal_display) #print(the_cal.today()) week_days = the_cal.iterweekdays() def print_time(r_time): retur...
bcc21417bb7b70eb6c177ee3fe4c1f23dba0f353
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sieve/4e221cf14bc743ca9ba7a63e749fcad0.py
269
3.703125
4
def sieve(n): ints = range(2, n) count = 0 while count < len(ints): currentprime = ints[count] multiple = currentprime while multiple < n: multiple = multiple + currentprime if multiple in ints: ints.remove(multiple) count = count + 1 return ints
c8f2e4044bdb4db9edcad0e5a4b63a187be724a8
caiosainvallio/estudos_programacao
/USP_coursera/primalidade.py
173
3.78125
4
num = int(input('Digite um número inteiro: ')) i = 1 div = 0 while i <= num: if num % i == 0: div += 1 i += 1 if div == 2: print('primo') else: print('não primo')
c0e736f6de3766abfe94b01431e9d34046e53c06
RyanPretzel/Ch.01_Version_Control
/1.2_turtorial.py
1,998
4.1875
4
''' Modify the starter code below to create your own cool drawing and then Pull Request it to your instructor. Make sure you keep the last two lines of code. Your first and last name must be written on your art. The last line keeps the window open until you click to close. Turtle Documentation: https://docs.python.org...
c295dda94ef5b4fbbb4a35fba9653cb986bf9d65
Vick1165/downloadMp3Files
/mp3.py
1,622
3.53125
4
import requests,re from bs4 import BeautifulSoup ''' URL of the archive web-page which provides link to all mp3 files. It would have been tiring to download each video manually. In this example, we first crawl the webpage to extract all the links and then download mp3 files. ''' # specify the URL of the archiv...
8e03ab8d3b2e2c63aa8782aa26b5940be1ab21c9
veera2508/AI-Lab
/S-1/191-S1.py
2,274
3.515625
4
''' Decantation Problem States - Represented as (a,b,c) where a is water in bucket 1, b is water in bucket 2, c is water in bucket 3 Actions - Transfer water completely from one bucket to another bucket given it has sufficient capacity [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)] Initial State - (8,0,0) Goal State - 4 i...
517cff5cb7ad0680de6d860b7dec80f7428c33ed
Varobinson/Projects
/python 102/even-numbers.py
112
3.6875
4
numbers = [2, 5, 9, 4, 1] even_numbers =[] for number in numbers: if number % 2 == 0: print(number)
8950a81dc01c7eb0345fcb15d5bc355c3b75aee4
iStealerSn/codingbat-python-solutions
/List-2.py
2,648
4.3125
4
# List-2 solutions """ Medium python list problems -- 1 loop.. Use a[0], a[1], ... to access elements in a list, len(a) is the length. """ # count_evens """ Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. For example - count_evens([2, 1, 2, 3, 4])...
bb37632b765c09abc8dc6eb142db3384451d83a0
Burseylj/ProjectEuler
/P14.py
650
3.703125
4
#attempt at project euler problem 14 #for some reason the dynamic programming parts aren't helping import time start = time.time() def collatzLength(x): initialValue = x length = 0 while x != 1: x = collatzSequence(x) length+= 1 return length +1 def collatzSequence(x): if...
55d84f25ae764f5aeb9fa18ec4e91ea761b8c053
omarsinan/hackerrank
/submissions/time_conversion.py
649
3.984375
4
# author: Omar Sinan # date: 26/08/2017 # description: HackerRank's "Time Conversion" Coding Challenge #!/bin/python import sys def timeConversion(s): t = 0 arr = s.split(':') if "PM" in arr[len(arr) - 1]: t = 1 arr[len(arr) - 1] = arr[len(arr) - 1].replace('PM', '') else: arr...
1f278a96e70d21c27f09aea018dba6de1f74c311
Adasumizox/ProgrammingChallenges
/codewars/Python/7 kyu/SquareEveryDigit/square_digits.py
109
3.75
4
def square_digits(num): ret = "" for x in str(num): ret += str(int(x)**2) return int(ret)
f6002044c2b165fa4cc774811767f97d1c38606d
raveena17/workout_problems
/basic_python/primeSieve.py
365
3.5
4
def primeSieve(numberList): if numberList == []: return [] else: prime = numberList[0] return [prime] + primeSieve(sift(prime, numberList[1:])) #call------- primeSieve(range(2, 100)) # output:------[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,...