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
1ce1a82e5295e4bbe129a95b7ec3c6b252b87f45
guilhermebap/Data-science-personal-study
/Udacity/Foundation AWS/5 - Software Engineering Practices Part 2/Exercise 01 - Unit test/compute_launch.py
378
4.25
4
def days_until_launch(current_day, launch_day): """"Returns the days left before launch. current_day (int) - current day in integer launch_day (int) - launch day in integer """ #if launch_day > current_day: # result = launch_day - current_day #else: # result = 0 return la...
ffb9898fac43592cc29642c5652a2f4913130dc9
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/mtttaf002/question2.py
292
4.28125
4
#creating a triangle with height n #created by tafara mtutu #23 march 2013 def isosceles(n): s = "*" for i in range(1,n+1,1): print(" "*(n-i), s, sep = "") s+="**" height = eval(input("Enter the height of the triangle:\n")) isosceles(height)
e764cc9e3a5ecbba5720d730f9b8a13421f64b56
17764591637/jianzhi_offer
/剑指offer/62_KthNode.py
1,637
3.765625
4
''' 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 ''' # -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 方法一: # class Solution: # # 返回对应节点TreeNode # def KthNode(self, pRoot, k): # # ...
d04ed393c87ee05b9f33da5b941da47a1bb4eb02
tyanbz/Algo-courses
/ps/2. simple paint/paint.py
944
3.765625
4
from turtle import * v = 100 #скорость черепашки step = 15 #шаг t = Turtle() t.color('blue') t.width(5) t.shape('circle') t.pendown() t.speed(v) def draw(x, y): t.goto(x, y) def move(x, y): t.penup() t.goto(x, y) t.pendown() def setRed(): t.color('red') def setGreen(): t.color('green') def setBlue():...
27b22e7cd140f72febe4364107e2fed57d4927b0
justin-crabtree/Practice-Python
/Repfields.py
557
4.28125
4
age = 28 print("My age is {0} years".format(age)) # The {0} is replaced with the first format value in the list (age) print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}" .format(31, "Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec")) print("Jan: {2}, Feb: {0}, Mar: {2}, Apr: {1}, May: {2}, June: {1...
78cb8cf7efeb151a58d882cd018d2ad3d5850349
kfrankc/code
/python/coin_change.py
547
3.84375
4
# Coin Change - Dynamic Programming class Solution: # vals: array containing value of the coins # total: total to give back # returns: minimal number of coins to make a total of t def coinChange(self, vals, t): tmparr = [0 for i in range(0, t+1)] n = len(vals) for i in range(1, t+1): minimum = float("inf"...
4a310c9cf89d17dcce1ce0f57d39ada19f367797
rsquir/learning-ai-python
/old_projects/not_ai/music_tree.py
666
4
4
class Node(object): def __init__(self, data): self.data = data self.children = [] def add_child(self, obj): self.children.append(obj) m_i = Node('c') m_i_i = Node('c') m_i.add_child(m_i_i) m_i_i_i = Node('c') m_i_i.add_child(m_i_i_i) m_i_i_ii = Node('d') m_i_i.add_child(m_i_i_ii) m_i...
176f8a3571be6c9be27b34a6b1d91cf4d79846a2
irshadkhan248/JavaPythonAndroidMysqlCode
/irshad dir/kamal/demo_python/python/L3/patteren2.py
313
3.703125
4
# wapp to generae: # A # B B # C C C # D D D D num=int(input("enter number of line ")) c=65 for i in range(num): for j in range(i+1): print(chr(c),end="\t") print() c+=1 num1=int(input("enter number of line ")) for k in range(num): for l in range(k+1): print("+",end ="\t") print()
15099296ed6f58b0390c6678d2498df44d305a68
GZHOUW/Algorithm
/LeetCode Problems/DFS/Flood Fill.py
1,714
4.125
4
''' An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a "flood fill", consider the st...
eb39189cfa24c993d684331eb6d10720bb04b850
soeirosantos/python-basico
/00-cadastro_funcionarios.py
2,051
3.59375
4
# -*- coding: utf-8 -*- def aplicacao(): ''' Programa que controla o cadastro de funcionários com as funcionalidades de -- Inclusão -- Alteração -- Exclusão -- Listagem de todos os Funcionários -- Exibição dos dados de um Funcionário ''' print...
98a9a10a622cb9513ec55ab0ea2263e46966a61c
mishra-ankit-dev/raspberrypi-backup
/code/test/parent.py
437
3.921875
4
class parent(): global parent1,parent2 parent1 = 'father' #parent2 = 'mother' def print_parent(self): global parent2 parent2 = 'mother' print("your parents are {} and {}".format(parent1,parent2)) class mother(parent): def print_mother(self): print("your mother's nam...
dc9cb123fc583362bdfbe8a629ca062d90a2ad20
gabriellaec/desoft-analise-exercicios
/backup/user_310/ch32_2019_03_12_18_57_47_179091.py
116
3.828125
4
duvida=input("Tem duvidas? ") while duvidas!= "não": print("Pratique mais") duvidas=input("Tem duvidas? ")
6a48f4ecf5cd6062e9ac5000d683a347bcea9aff
charlie1kimo/leetcode_judge
/126_word_ladder_2.py
2,977
3.765625
4
""" Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example, Given: start = "hit" end = "cog" dict = ["hot","dot","dog","lot","log"] ...
dff2ec9b4ea4d19ba8d6ef400526a6c91e25d74c
yadelab/API_challenge
/step3.py
1,238
3.765625
4
# step3.py # ------- # Challenge: Locate the needle in the haystack array. You are going to send # back the position, or index, of the needle string. The API expects indexes # to start counting at 0. # Implementation import requests import json __author__ = "Yadel Abraham" # Fire initial HTTP POST request to API url...
188d9bb0ce9e94064337061d10485754284a03d0
AnthonySimmons/EulerProject
/ProjectEuler/ProjectEuler/Problems/Problem2.py
739
4.03125
4
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. de...
16d4050c6a2721ed96f1dc8ecf6b1d9a411e4a6e
RoscoBoscovich/cp1404practicals
/prac_06/guitars.py
830
3.53125
4
"""Guitar collection program""" from prac_06.guitar_class import Guitars def main(): guitar_list = [] print("My Guitars!") name = " " while name != "": name = input("Name: ") if name == "": break year = int(input("Year: ")) cost = int(input("Cost: ")) ...
78faf3426912d68396bd3825547bdeb1661c69cc
Clem-Jos/CellScanner
/CellScanner_1.1.0/db_script.py
19,151
3.515625
4
from sqlite3 import * from shutil import copyfile import os """This file contains all functions linking the program and the database """ def execute(phrase): """This function create a connection to the database and execute a command. :param phrase: str SQL sentence to execute :return: list of...
3521cd212a88ebb7eac8e34f68cb6928d850d907
aaaaaaason/codeforces
/BusToUdayland.py
466
3.75
4
n = int(input()) rows = [input() for _ in range(n)] def check(rows: list, r: int, c: int) -> bool: if rows[r][c] == rows[r][c+1] and rows[r][c] == 'O': rows[r] = rows[r][:c] + '++' + rows[r][c+2:] return True return False found = False for i, row in enumerate(rows): if check(rows, i, 0) o...
6a00f0ca9fa632aab7f9c362b3f647c6682c5507
swadhikar/python_and_selenium
/python_practise/Interview/threads/images/thread_locker.py
1,269
3.765625
4
from contextlib import contextmanager from threading import Lock, Thread, current_thread from time import sleep # Run a function # The function must be protected by thread lock # After the function gets executed, the lock should be released sum_of_values = 0 @contextmanager def acquire_thread_lock(): lock = Loc...
d1eab49e66cd7578e0dc835d8cee113a94e661b7
zeelp741/Data-Strucutures
/PriorityQueue_linked.py
5,647
3.5
4
# Imports from copy import deepcopy class PQNode: def __init__(self, element): """ ------------------------------------------------------- Initializes a priority queue node that contains a copy of the given element and a link pointing to None. Use: node = PQNode(...
adffbd365423fb9421921d4ca7c0f5765fe0ac60
denvinnpaolo/AlgoExpert-Road-to-Cerification-Questions
/Arrays/ThreeNumSum.py
1,745
4.34375
4
# ThreeNumSum # Difficulty: Easy # Instruction: # Write a function that takes in a non-empty array of distinct integers and an # integer representing a target sum. The function should find all triplets in # the array that sum up to the target sum and return a two-dimensional array of # all these triplets. The...
4393bf305299eea380c630b0486e73aed1c29102
RegisSchulze/challenge-card-game-becode
/utils/game.py
3,941
3.78125
4
from utils.card import Deck from math import floor class Board: """ Class Board, that represents the status of the game containing four attributes -attribute players that is a list of Player containing all the players -attribute turn_count that is an int and keeps record of how many rounds have be...
1d58d17040b4e94522bbd9256cacc9b2a9c39680
lvyu-imech/PyVT
/pyvt/myio/binarytecplot/binary2asciifile.py
2,479
3.9375
4
import struct class Binary2AsciiFile(object): """ Binary2AsciiFile: this class is a helpfull class to read a binary file characters. Mainly, converts bytes to char, long integers, float, double, text Binary2AsciiFile( filename ) """ def __init__(self, filename): ...
bbcd56895dff583787c16e847b17c5f462da48e1
cyclony/pythonTrainingProject
/dataModel.py
729
3.609375
4
import random class Factor: def __init__(self, n): self.i = 1 self.total = 1 self.n = n def __iter__(self):#python解释器一旦碰到的类有这个方法,则该类对象是iterable的 return self def __next__(self): #for循环执行的时候会内部调用该方法来实现迭代。 if self.i == self.n: raise StopIteration se...
e28449c4c08c2aa8a3dd63a4e8f83a9ac2701083
EdwardLijunyu/first-room
/数据结构/16链表中环的入口节点.py
1,253
3.84375
4
# 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 ''' 思路: 1.先确定链表是否含有环,通过快慢两个指针一次移动,如果没有快指针能追上慢指针就说明有环 2.确定有环之后,当快慢指针重合的时候,再让一个指针成从头指针开始,两个同时移动,直到两个指针重合时就是环的入口节点 ''' # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def EntryNodeOfLoop(self, ...
d4ec950993dd2edf31ab707dceef429c71fbf118
mtpatil10/MechITgr8
/Lecture 3 and 4-Variables in python.py
443
3.8125
4
print('navin\'s "laptop"') # \ directs to ignore ' print('navin'+ ' navin') print(r'docs\navin') # r which is a row string directs to ignore special meaning of \n print() # for empty line name='youtube' # y o u t u b e # 0 1 2 3 4 5 6 #-7 -6 -5 -4 -3 -2 -1 ...
6580df6e197ac3be075cd2aeb5f3c48a1b4cb37f
Dqvvidq/Nauka
/Operacje na plikach/main.py
809
3.640625
4
import os import csv # tworzenie ścieżki dostępu do pliku os.path.join("czesc.txt") # tworzenie pliku i zapisywanie coś na nim st = open("czesc.txt", "w") st.write("czesc") st.close() # otwieranie pliku i jego zawartości with open("czesc.txt", "r") as f: print(f.read()) # umieszanie zmian...
dac9f9ce7a485fa8fb7787e227ce88422b7b4060
JHPolarBear/TensorFlow_Practice
/03.Classification/04-1_Logistic_Classification_Logit_zoo.py
2,780
3.546875
4
## 소스 출처 : https://hunkim.github.io/ml/ ## 아래 코드는 위 링크에서 학습한 머신 러닝 코드를 실습한 내용을 정리해 놓은 것으로, ## 관련된 모든 내용은 원 링크를 참고해주시가 바랍니다 ## Source Originated from : https://hunkim.github.io/ml/ ## The following code is a summary of the machine learning code learned from the link above. ## Please refer to the original link for al...
7b45382df7bdf9351d1237b42375a5a90a25abf2
palmeida7/dayfive-python
/func_exercises.py
4,287
4.59375
5
""" #1. Madlib function Write a function that accepts two arguments: a name and a subject. The function should return a String with the name and subject interpolated in. For example: madlib("Jenn", "science") # "Jenn's favorite subject is science." madlib("Jeff", "history") """ # "Jeff's favorite subject is history...
abb5302ab8fca5d1cb9e91b85630b47ffb4aca26
YiddishKop/python_simple_study
/MultiThread2_asyncWriter.py
1,696
4.4375
4
# MultiThreading - 2 # Asynchronous Tasks # Some tasks can take a long time. Input and output for example can take a long time. # Some programs are required to be real time. So we can setup Threads to run in the background to write a file or search for items while the user can still interact with the interface or comma...
66268e7b91c1312a0b5ee11d3352ec38f6f8eb80
RotcehOdraude/horario-fi
/Python Scrapping/HorarioFIScrapping.py
553
3.640625
4
##Hola paco rodri :D, por si querias scrapear la pagina de horarias de la facultad :o import pandas as pd listaDeMaterias = ['1645','1644','1562','1686','1413'] Materias = pd.DataFrame() for materia in listaDeMaterias: website = "http://ssa.ingenieria.unam.mx/hrsHtml/{}.html?".format(materia) datalist = pd.re...
0df8b4c11794dfa7efc67ac9d88951da88a1facc
anshu3769/KeplerProject
/Backend/data/database.py
3,055
3.578125
4
""" This module creates SQLAlchemy engine and contains a method to initialize the database which will be called upon running the application. """ from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool im...
fffe6c2a0ea5678450a1e8304755b358c1ef9d9e
prabhupant/python-ds
/algorithms/dynamic_programming/longest_subarray_with_no_pairsum_divisible_by_k.py
1,466
3.953125
4
""" Find the longest subarray in the input array such that the pairwise sum of the elements of this subarray is not divisible by K The idea is - How can we tell that two numbers x and y will make a pairsum that will be divisible by K just by looking at their remainders? There can be two conditions 1. It will be only...
803fa874360ac82951c3f7949b55178c3746169f
StampedPassp0rt/courses
/lphw/ex8.py
572
3.75
4
#Exercise 8 #variable that force prints four inputs with %r, kind of a debugger too. formatter = "%r %r %r %r" #printing out 1 through 4 print formatter % (1,2,3,4) #printing out one through four as strings. print formatter % ("one", "two", "three", "four") #forcing the print of Boolean values print formatter % (True...
c6c142a9e6525d7307b9ccaf27f636e0d65da2ae
Ibunao/pythontest
/test1/yanglao.py
1,181
3.515625
4
import math # 每月计划投入多少钱 plan = 5000 # 现在几岁 now_age = 27 # 多少岁可以取 plan_age = 40 # 目标活到多少岁 target_age = 80 # 周期,按月则是12,按周52,按天356 cycle = 12 # 分红,分红先不计算利率 profit = 129060 # 到期后每月返还多少 get_plan = 1029.5 # 预期利率 plan_rate = 0.10 def getWorthy(): ''' 计算利息 :return: ''' global plan, plan_age, now_age...
20e4664b280eaa2a93738524400c58ed384a34cb
petercheng00/adventOfCode
/2022/python/day12.py
2,918
3.625
4
import sys from typing import Dict, List, Tuple def load_heightmap() -> Tuple[List[str], Tuple[int, int], Tuple[int, int]]: with open(sys.argv[1]) as f: heightmap = f.read().splitlines() start_pos = (-1, -1) end_pos = (-1, -1) for i in range(len(heightmap)): if (start_j:=heightmap[i].f...
9f97b14927e5e15a283922a106c4614d72133f4f
hector81/Aprendiendo_Python
/CursoPython/Unidad8/Soluciones/moulo_II_.py
1,333
4.125
4
"""paquete del moulo principal del descuento""" import random def sorteo(valor): x = random.choice([0,10,20,25,50]) bolas = {0:"BOLA BLANCA", 10:"BOLA ROJA", 20:"BOLA AZUL", 25:"BOLA VERDE", 50:"BOLA AMARILLA"} if x == 0: print("Lo siento no tienes descuento, te salió la bola blanca") ...
af4080f51de0369622e20069a6a1310ce8eadc7a
JackelyneTriana/EVIDENCIA-3
/EVIDENCIA3.py
7,665
3.71875
4
separador = ("*" * 40) import sys import sqlite3 from sqlite3 import Error with sqlite3.connect("CURSO.db") as conn: c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS materias (idmateria INTEGER PRIMARY KEY, nombre TEXT NOT NULL);") c.execute("CREATE TABLE IF NOT EXISTS alumnos (idalumno INTE...
87ab05696a47a263f53a4d5db264c0e844a62a1c
dipro007/Python-all-in-one
/area.py
253
3.96875
4
b = float(input("Enter the value of base: ")) h = float(input("Enter the value of height: ")) r = float(input("Enter the value of radius: ")) at= 0.5 * b * h ac = 3.1416 * r * r print("Area of Triangle = ",at) print("Area of Circle = ",ac)
0758c7bdd7f377f4aed1159cbcce20398de79693
emkramer/homework_python
/13.09/15.09.py
124
3.875
4
def generator_(): number = 0 while number<1000000: yield number number += 3 for i in generator_(): print(i, end=" ")
581eb4f8342ca1603abb22b42b2b710f4ff33951
aleshkoa/python_exercise
/question2.py
156
3.734375
4
celsius = float(raw_input('Enter Temperature in Celsius ')) fahrenheit = 9.0/5.0 * celsius + 32 print 'Temperature in Fahrehnheit is: ' + str(fahrenheit)
d2eeb7908498328e2e25037d713d53fad9464f20
dyedefRa/python_bastan_sona_sadik_turan
/13_Python_Generators/01_generators.py
568
4.0625
4
# def cube(): # result = [] # for i in range(5): # result.append(i**3) # return result # print(cube()) def cube(): for i in range(5): yield i ** 3 # generator = cube() # iterator = iter(generator) # print(next(generator)) # print(next(generator)) # print(next(generator)) # print(n...
24522bbc843ddf43e6505c3196c572b3be06d614
manixaist/pyclimber
/src/particle_generator.py
3,772
3.765625
4
"""Particle generator for Py-Climber""" from src.particle import Particle import random class ParticleGenerator(): """The ParticleGenerator class is responsible for creating and tracking Particle objects which are just 2D rects of a given color. A calling object may specify a callback to customize the par...
42a3528872a1f3cde35e0f8cbd16cce415395fa4
palhiman/Lab-Practices
/ml/dfm1.py
852
4.1875
4
#!/usr/bin/python # Implementation of Diffie-Hellman-Merkel key exchange algorithm # Author: Himanshu Shekhar import math def power(a, b , P): if b == 1: return a else: return (math.pow(a, b) % P) if __name__ == "__main__": p = int(input("Enter the comman prime number:")) g = int(inp...
8e189741b544ba01abf8a99179ffbd1128bdbc22
Pharaoh00/My-Experiments
/Pygame/test_maps/test_map_v5.py
6,945
3.625
4
#-*- coding:utf-8 -*- #test_map_v5.py import pygame from pygame.locals import * from pygame.math import Vector2 pygame.init() #pygame.key.set_repeat(250, 25) s_width = 600 s_height = 600 clock = pygame.time.Clock() fps = 30 running = True game_screen = pygame.display.set_mode((s_width, s_height), py...
e485bec3fab28d61253218a3a00387fa16915781
kiranani/playground
/Python3/0124_Binary_Tree_Max_Path_Sum.py
618
3.515625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxPathSum(self, root: TreeNode) -> int: def helper(root): if not root: return 0 nonl...
283290e663ae6e345e9f03357f22a0549ec1fc30
Jp9910/Projeto-e-Analise-de-Algoritmos
/nQueens.py
1,712
3.6875
4
def posicaoValida(X,r,col) -> bool: #checa se a coluna col já foi utilizada por uma rainha de índice anterior a r #e também se a rainha k não ataca em diagonal a rainha r for k in range(1,r): if (X[k] == col) or (abs(X[k]-col) == abs(k-r)): return False return True def NQ(i,n,X): ...
d0362c81ac4651f60c95b1ae9a6e769335a978c9
Fuseken/code
/python/if.py
99
3.859375
4
door = input("> ") if door == "a": print("you have typed ",door, "right?") else: print("okay")
f9fb49141c26304f264b8eb7c7d8425668c6cc50
Dython-sky/AID1908
/study/1905/month01/code/Stage1/day07/exercise08.py
637
4.09375
4
""" list01 = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] 练习1:打印第二行第三个元素 练习2:打印第三行第每个元素 练习3:打印第一列每个元素 """ list01 = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] # 练习1:打印第二行第三个元素 print(list01[...
10a000bafbc19d46e623dac5cbb1f76eacfae7ed
michlee1337/practice
/CTCI/c4_treesAndGraphs/firstCommonAncestor.py
2,124
3.796875
4
from queue import * # O(n) time: finding the nodes takes O(n) time, # and the rest takes O(h) time where h is height of the tree # O(lgn) space: search queue will be O(lgn) (at least the root will be on a diff level) # and the rest are constant space pointers def firstCommonAncestor(root, node1, node2): # find t...
ed952f6a95f21f5d549e209705fcaabc6bc64271
PierreKimbanziR/belgium_housing_price_predictor
/app.py
4,433
3.5
4
import streamlit as st import pickle import pandas as pd import numpy as np import os import webbrowser from bokeh.models.widgets import Div cwd = os.getcwd() # Get the current working directory (cwd) model = pickle.load(open(cwd + "/estimator.pkl", "rb")) data = pd.read_csv( "https://raw.githubusercontent.com/S...
2336fdef1f7c65c453ce50f31bc57cdd659ce96a
pawelptak/FaceRecognizer
/classes/screen_stack.py
597
3.6875
4
class ScreenStack: def __init__(self): self.stack = [] def add_screen(self, screen_name): if len(self.stack) > 0: if self.stack[-1] != screen_name: self.stack.append(screen_name) else: self.stack.append(screen_name) def previous_screen(self):...
eca678dc8091cdc00b987c2733c163a32996e0dc
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-5.py
510
4.09375
4
''' Exercise 10.5. Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. ''' def is_sorted(L): for i in range(1, len(L)): if L[i] < L[i - 1]: return False return True t1 = [] t2 = [1]...
2fb3cf465ce2c1fa829e5805ed6799196c2811fd
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/51375a5af58746209b9db60b7d392b3c.py
285
3.796875
4
from collections import Counter def word_count(phrase): cleaned_phrase = "" # Remove anything not alphanumeric or a space for c in phrase: if (c.isalnum() or c == " "): cleaned_phrase += c.lower() return Counter(cleaned_phrase.split())
a68b92849ffb44f9cc611e2a7399248a6c525f33
relsqui/joculators
/bot/cryptograms.py
3,272
4.21875
4
#!/usr/bin/python3 """ Cryptogram finder. (c) 2017 Finn Ellis. A "cryptogram" for the purpose of this module is a string which can be transformed into a target string by consistently replacing each letter 1:1 with another letter (or with itself). """ import logging import random logger = logging.getLogger(__name__)...
0af70927a3788c82e9dad253df2b05d35eb1b1e7
Python-x/Python-x
/面向对象/单例.py
1,101
3.71875
4
class Person(object): def __init__(self, name): self.name = name def read(self): print(self.name +"正在读书") def watch_TV(self): print(self.name+"在看电视") class Woman(Person): def maoyi(self): print(self.name+"在逛街") mama = Woman("妈妈") mama.maoyi() mama.watch_TV() class Man(Person): def football(self): ...
5e12a1a8358669ec2b3f7569986fd1457a95e091
melottii/notas
/MergeSort.py
2,715
3.96875
4
import pickle def student(notas, alunos): #Função para somar a nota de cada aluno e chamar as ordenações das notas. overall_grade, term = [], 0 for i in notas: sum_of_assessments = notas[term][1] + notas[term][2] + notas[term][3] + notas[term][4] overall_grade.append((term+1, sum_of_as...
68cfe6a531368bda768d91b4c4885d3943a134e6
gauthampaimk/Hangman
/Hangman.py
6,196
4.21875
4
import random import string WORDLIST_FILENAME = "words.txt" # Extracts the contents of 'words.txt' and stores it in the variable 'WORDLIST_FILENAME'. # 'words.txt' contains a big number of words that are to be guessed in the game. def loadWords(): """ Function significance : Returns a list of valid wor...
88d90ac4e1efc3df9d71d3a333bf634918f67f32
ayushgarg2702/Intern-Management-API
/common/common_filters.py
152
3.515625
4
import re def CheckMobileNumber(param: str) -> bool: if re.search(r"^[6-9]\d{9}$", str(param)): return True else: return False
aea9f514df21bf317438340e645f2a8d09438f2b
liviaasantos/curso-em-video-python3
/mundo-1/ex024.py
210
3.984375
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 3 20:01:18 2021 @author: Livia Alves """ city = input('Em que cidade você nasceu: ') city = city.upper().strip() corte = city.split(' ') print(corte[0] == 'SANTO')
b7e85a91199225c2ac3c1a41a3aa6648cfa6f28c
Oumar96/travelingstrategy-1
/server/data/helper_class/wiki_weather_parser.py
2,033
3.609375
4
from bs4 import BeautifulSoup class wiki_weather_parser: def __init__(self, url, driver): self.url = url self.driver = driver #This is the parser for the main tables which include def visa_parser_table(self): info ={} self.driver.get(self.url) #Selenium hands the ...
3f63dc60b0fd95bcc0b7ee34e28cc5983fd2ec8a
BenRauzi/159.172
/Tutorial 8/text_therapist.py
2,912
3.875
4
import random hedges = ( "Please, tell me a little more.", "Many of my patients tell me the same thing.", "Please, carry on talking." , "What is your point?") qualifiers = ("Why do you say that ", "You seem to think that ", "Can you explain why ") #I have ...
fbd4ee6e35f6905e3c4dbeea7ef8ec5a9dfd8c43
shahbagdadi/py-algo-n-ds
/sortSearch/searchSuggestionSystem/Solution.py
551
3.53125
4
from bisect import bisect_left from typing import List class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: products.sort() i , prefix , res = 0 , '' , [] for c in searchWord: prefix += c i = bisect_left(products,prefi...
86b703d029d254e88c938b08d413f0a844143779
ragulkesavan/python-75-hackathon
/WRITE FILE/line_by_line.py
469
3.546875
4
#WRITING INTO FILE LINE BY LINE #opening file in w mode f=open("lyrics.txt","w") ''' USING write() FUNCTION WE CAN WRITE LINE BY LINE INTO FILES ,EACH ATTRIBUTE OF write() IS A LINE STRING AND SHOULD END WITH "\n" OR EOL ''' f.write("Spent 24 hours\n") f.write("I need more hours with you\n") f.write("You spend the week...
f5bb794391c32a84d05a80a2fd595437b3eabb92
vmred/Coursera
/coursera/python-basic-programming/week1/hw18.py
733
4.03125
4
# Электронные часы показывают время в формате h:mm:ss, # то есть сначала записывается количество часов (число от 0 до 23), # потом обязательно двузначное количество минут, затем обязательно двузначное количество секунд. # Количество минут и секунд при необходимости дополняются до двузначного числа нулями. value = int(...
e61883b63f0ff3c5308dea1a7f6522cf7219866a
statho7/PythonExamples
/export_csv_from_multiple_csv_files.py
2,184
3.71875
4
import sys import pandas as pd import os def Run(action, *args): if action == 'merge': Merge(args) elif action == 'concatenate': Create_the_combined_csv_file(args) def Create_the_combined_csv_file(export_filename, *args): # CSV to Pandas DataFrame the first 2 CSV files csv_1 = pd.read...
881afdd855296901476e045d44b15d8a6730a82e
acunaMatata22/Jump-Chess
/utils.py
632
3.734375
4
# generally helpful functions used throughout the application def squarePos(num): # returns the XY coordinates of the squares for initialization render # NOTE: for drawing only, not for indexing return (num % 8 - 3.5, (num % 64) // 8, (num // 64) * 1.13) def indexToTuple(num): # used to reference the ...
90e552006875ac9ab9d1b7740130ec8128022562
NathanKinney/class_ocelot
/Code/jon/lab14_bogosort.py
673
3.609375
4
import random def random_list(n): lst = [] for i in range(n - 1): lst.append(random.randrange(0, 20)) return lst def shuffle(lst): for i in range(len(lst)): s = random.randrange(len(lst)) t = lst[i] lst[i] = lst[s] lst[s] = t def is_sorted(lst): for i in...
0ac9c1e00bf08f0f3abcbcdfd9a72cc05041f91f
jbp4444/PyGenAlg
/nc_dist12/check_files.py
1,932
3.5
4
import csv def main(): zip_to_congr = {} with open('zip_to_congr.csv','r') as fp: readCSV = csv.reader( fp, delimiter=',' ) # skip 2 headers next( readCSV, None ) next( readCSV, None ) # now read all the actual data for row in readCSV: zip_to_congr[row[1]] = 1 nc_zips = {} with open('nc_data.zip.t...
970e66a9151074cbbe3c5226f9fb5083ceab437b
kennycaiguo/Heima-Python-2018
/15期/00Python基础/1-3 面向对象/02-面向对象练习/01-小明爱跑步.py
476
3.5625
4
class Personal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "我的名字叫%s,体重是%.2f公斤" % (self.name, self.weight) def run(self): print("%s可以跑步"%self.name) self.weight -=0.5 def eat(self): print("%s可以吃东西"%se...
1a08e6c80c0e72e886a3b4a393be45d017c260bd
adiG48/voice_assistant_app
/document.py
18,215
3.8125
4
'''Voice_assistant_app: I was inspired by following things(voice assistants like Alexa, Siri,Google,Jarvis etc.) and it made me to search more about it and make a one for me. I made my Voice Assistant(@diG48)using Python. The query for the assistant can be manipulated as per the user’s need. Speech recogniti...
cd7f67f8c7cf41654e6b6357eb25c100583ee88b
yddong/Py3L
/src/Week2/s2-dict-1.py
264
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- German = 0 English = 1 Polish = 2 mydict = {} mydict["krava"] = [ "Kuh", "cow", "krowa" ] mydict["pas"] = [ "Hund", "dog", "pies" ] mydict["konj"] = [ "Pferd", "horse", "koń", "使" ] print( mydict["konj"] )
c09a012d002dd7b15e8b4396965333555f8b5ce1
ShimpeiARK/python-for-trainig
/a.py
3,603
3.703125
4
#!/usr/bin/python # -*- Coding: utf-8 -*- array = list(map(int, input(),split(' '))) 2転換距離 ''' ============================= import random def randomlist(size): list=[] for i in range(1,size+1): list.append(random.randint(0,100)): return list print (list) ============================= list...
10483d09762a412329daf776194a3713fe1176fd
sinystr/hackbulgaria
/week11/task_2_laptop_bg.py
1,978
3.71875
4
class Product: def __init__(self, name, stock_price, final_price): self.name = name self.stock_price = stock_price self.final_price = final_price def profit(self): return self.final_price - self.stock_price class Laptop(Product): def __init__(self, name, stock_price, fin...
f90a5a51eaaec5fb56d2aeee0120fc59315d28cc
MahrukhKhaan/IDLE-based-LMS
/win2.py
1,722
3.59375
4
from tkinter import * class MainMenu(Frame): def __init__(self,parent): Frame.__init__(self, parent) Frame.config(self, width=500,height=500,bg='misty rose') Frame.pack(self, side=LEFT) self.parent=parent labelmain= Label(self,text="MAIN MENU",font=("bold",...
a9faf34499ef85ad3a0ad07db3fdbb0894ef0afe
celeist666/ProgrammersAlgo
/전화번호 목록.py
374
3.65625
4
# 문자열을 정리해두면 접두사인 번호가 앞에 나오고 그 바로 뒤에 해당 번호를 접두사로 두는 번호가 # 나온다. 그렇기에 n번씩만 비교하면된다. def solution(phoneBook): phoneBook = sorted(phoneBook) for p1, p2 in zip(phoneBook, phoneBook[1:]): if p2.startswith(p1): return False return True
b43f9be62b3f456075051fd48bbeae47a80e7832
Taving40/Python_Design_Patterns
/Strategy_pattern/Strategy_pattern_solution.py
1,943
4.1875
4
from __future__ import annotations from abc import ABC #abstract base class (deriving from this results in an abstract class) from abc import abstractmethod """The solution is to turn the fly method into an interface in the base class to ensure that every child Duck class implements it (since all Ducks should hav...
986bfa374e8bf0e454af9778c76251408ec77c5a
madtyn/pythonHeadFirst
/pythonDesignPatterns/src/composite/menuiterator/menu.py
2,826
3.6875
4
from abc import ABCMeta, abstractmethod from pythonDesignPatterns.src.composite.menuiterator.iterator import NullIterator, CompositeIterator, Iterator class MenuComponent(metaclass=ABCMeta): """ A class which allowes to contain another instances of the same class """ def add(self, menuComponent): ...
43d7e9182242b6040a77407126643db1fa963edb
klich1984/holberton-system_engineering-devops
/0x16-api_advanced/2-recurse.py
1,138
3.65625
4
#!/usr/bin/python3 """ Write a recursive function that queries the Reddit API and returns a list containing the titles of all hot articles for a given subreddit. If no results are found for the given subreddit, the function should return None. """ from requests import get def recurse(subreddit, hot_list=[], after=Non...
6fd446499ca33c7865ef1c6b292c5b224708b1eb
Hasib404/Python-problems
/palindrome.py
917
4.3125
4
""" #PROBLEM A palindrome is a word that reads the same backward or forward. Write a function that checks if a given word is a palindrome. Character case should be ignored. def is_palindrome(word) For example, isPalindrome("Deleveled") should return true as character case should be ignored, resulting in "deleveled", ...
5d6d7106c67e09ab44afd18cb8bf0ac548e8b1f8
Pythonyte/Algorithms
/binray_tree_mirror_image.py
549
4.03125
4
''' Mirror(Tree) (1) Call Mirror for left-subtree i.e., Mirror(left-subtree) (2) Call Mirror for right-subtree i.e., Mirror(right-subtree) (3) Swap left and right subtrees. temp = left-subtree left-subtree = right-subtree right-subtree = temp ''' def mirror_Tree(self,root): i...
944545e661dd563e223f9415ee23817b146cc222
davemccann4130/UCDPA_davidmccann
/numpy_happy_life_expect.py
1,623
3.546875
4
import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt # https://www.kaggle.com/unsdsn/world-happiness happydata = pd.read_csv('world-happiness-report-2021.csv') #print(happydata.columns) # Set variables to hold data to join into 2d numpy array np_happyscore = happyda...
b7f91697352f0f4fa12e6dbf9ef7525d9a6a4553
grk44/host_scripting
/Python/chapter4_project_flips.py
762
3.5
4
import random numberOfStreaks = 0 for experimentNumber in range(10000): flips = [] #creates array/list of 100 flips, 0 or 1 for x in range(100): rnum = random.randint(0,1) flips.append(rnum) #sets counts of streak to 0 headcount = 0 tailcount = 0 #iterates through the array/list of 0 and 1 ...
0131cab8dc79656f0d3f0ec383755c26e4143306
nuga99/daily-coding-problem
/Problem 15/solve.py
1,259
4.125
4
#!/usr/bin/python ''' Good morning! Here's your coding interview problem for today. This problem was asked by Facebook. Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. Upgrade to premium and get in-depth solutions to every problem. Since you...
195b4955345859075d9a736281f5399680a37557
mikolajf/sailing-tdd
/sailboat.py
655
3.609375
4
from utils import sides class Sailboat(object): def __init__(self, initial_heading): self._heading = initial_heading def get_heading(self): return self._heading def change_course(self, course_diff): self._heading = (self._heading + course_diff) % 360.0 ...
13798e11dfe409bdda7f6018e106c1ca4031400b
imji0319/checkio
/Checkio/scientific_expedition/common_word.py
570
3.734375
4
''' Created on 2018. 1. 21. @author: jihye ''' def checkio(first, second): first=first.split(',') second=second.split(',') common=[] for i in range(len(first)): for j in range(len(second)): if first[i]==second[j]: common.append(second[j]) common=sorted(common) ...
c3a978dd68c9b31ad35cbaf1b488ded089be48cc
cedwardsmedia/compare
/compare.py
1,210
3.625
4
#!/usr/bin/python3 import sys import hashlib try: file1 = sys.argv[1] file2 = sys.argv[2] except: print("I need two files you idiot!") exit() try: open(file1, 'r') except FileNotFoundError: print("Cannot open " + file1) exit() try: open(file2, 'r') except FileNotFoundError: print...
1b97becd5535df33e0232d4e1eb3892b6f03ed9f
liucheng2912/py
/leecode/study/树的非递归先序遍历.py
648
3.859375
4
#使用栈来实现 #若是右子节点存在,入栈 #若是左子节点存在,入栈 #最后出栈 def preorder(node): stack=[node] while len(stack)>0: print(node.val) if node.right is not None: stack.append(node.right) if node.left is not None: stack.append(node.left) stack.pop() def midorder(node)...
d36fba4bdff5dc3778c1210d843fa564e614bcfd
wikipycoder/ds-algo-in-py
/maze_runner.py
1,239
3.984375
4
#this script is a simple version of maze runner in python maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0 ], [1, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 1], [0, 0, 1, "End"] ] maze_runner = "*" #maze runner character def display_maze(): for d1 in maze: for row in d1: ...
09592e3943bb7f52d0dd2db30a1d88b3b6dfc8fe
yujin0719/Problem-Solving
/프로그래머스/2019 KAKAO BLIND RECRUITMENT/오픈채팅방.py
511
3.609375
4
# 오픈채팅방 from collections import defaultdict def solution(record): answer = [] dict = defaultdict(list) for r in record: r = r.split(" ") if r[0] != 'Leave': dict[r[1]] = r[2] for r in record: r = r.split(" ") if r[0] == 'Change': continue i...
8411166d3b4014fc9e41599512aa1b964e53cc0b
Vitalius1/Python_OOP_Assignments
/Hospital/register.py
1,148
3.734375
4
from hospital import Hospital from patient import Patient # creating 6 instances of Patient class p1 = Patient("Vitalie", "No allergies") p2 = Patient("Diana", "No allergies") p3 = Patient("Galina", "Yes") p4 = Patient("Nicolae", "Yes") p5 = Patient("Ion", "No allergies") p6 = Patient("Olivia", "Yes") # Create the hos...
81d3794dc323a6b7047135e301a2b1194b4b9470
EgorZamotaev/PythonLabs
/Lab1/4.py
106
3.671875
4
N=int(input("Введите N ")) C=12 D=100 P=(N/C*1/3)**D print('Вероятность равна: ',P)
35f86cb70aad5a8b2af72b819feea93688e112f9
MattB17/googleMemoryAutoScaling
/MemoryAutoScaling/Models/Sequential/TraceExponentialSmoothing.py
4,849
3.71875
4
"""The `TraceExponentialSmoothing` class is used to construct a predictive model based on exponential smoothing. For exponential smoothing, the prediction at time `t` is `p_t = alpha * x_t-1 + (1 - alpha) * p_t-1` where `alpha` is a configurable weight constant between 0 and 1, `x_t-1` is the actual data observation at...
6d501e12d7d8c7ce59a5d52fea2b3f1de0a848c7
melany202/programaci-n-2020
/talleres/tallerquiz2.py
2,769
3.625
4
#ENTRADAS Temperatura_Corporal = [36,37,38,35,36,38,37.5,38.2,41,37.4,38.6,39.1,40.3,33] #Preguntas preguntaMenu = ''' Por favor igrese alguna de estas opciones 1-Convertir temperaturas 2-Estado de salud de c/u de las temperaturas 3-Ver maximo y minimo de temperaturas 4...
c9cb4c5b9a35df7b5a72fec175bd0ac61324ebc0
malaika-chandler/triple-triad-python
/agents.py
7,074
3.65625
4
from textdisplay import TripleTriadColors from abc import ABCMeta, abstractmethod class Agent: """Base class for implementing a game player Attributes: index (int): The index of the player Methods: initialize: Prepares agent for a new game get_action: Throws NotImplemented error;...
5b07a1e623816033a157a27316d095177154ee4e
Ahmedrajiv/hello-world
/defcalculatorS9.py
331
3.921875
4
#def function def add (a,b): return (a+b) def sub (a,b): return (a-b) def mul (a,b): return (a*b) def div (a,b): return (a/b) x= int(input("Enter X value")) y= int(input("Enter Y value")) print (add(x,y), "Addition") print (sub(x,y),"Subtraction") print (mul(x,y),"Multiplication") print (div(x,y),"Divs...
b464a61efab059d53cd9e0e5a5028cd4a653c23b
kelr/practice-stuff
/leetcode/83-removeduplicatessorted.py
988
3.921875
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # Use two pointers, if fast is the same as slow, increment fast until it no longer is. # Then set the next node on slow to the different value on fast, which skips duplicate values. # O(N) time, fast iterates N t...
49f2d9674b356ec1fa8e1b9d6cdeabdc93804163
GohJC/DPL5211Tri2110
/Lab 2 Q3.py
254
4.125
4
#student ID: 1201201564 #student Name: Goh Jia Chen FT = -17.2222 celcius = float(input("Please enter your Celcius temperature : ")) fahrenheit = FT * celcius print("For {:.2f} Celcius is equivalent to {:.2f} Fahrenheit".format(celcius, fahrenheit))
a2d78e2e6b4c3c000c0ccf91a45742e570cca30c
jieye-ericx/learn-python
/22/my/04.py
901
3.53125
4
import tensorflow as tf # 线性回归 def myregression(): x = tf.random_normal([100, 1], mean=1.75, stddev=0.5, name="x_data") y_true = tf.matmul(x, [[0.7]]) + 0.8 weight = tf.Variable(tf.random_normal([1, 1], mean=0.0, stddev=1.0, name="w")) bias = tf.Variable(0.0, name="b") y_predict = tf.matmul(x, w...
0aa27946dbe9f13346f86c95408c03d40650a319
nyghtowl/HB_Wk4_LAMP
/model.py
3,261
3.578125
4
""" model.py """ import sqlite3 import datetime def connect_db(): return sqlite3.connect("tipsy.db") def new_user(db, email, password, fname, lname): c = db.cursor() query = """INSERT INTO Users VALUES (NULL, ?, ?, ?, ?)""" result = c.execute(query, (email, password, fname, lname)) if result: db.commit() re...