blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4f5facb6a2c28c7ae37ba291c33535cefa8bd4ec
Eric-cv/QF_Python
/day4/while.py
2,246
3.703125
4
# for i in range(1,50,5): # print('--->',i) ''' range的范围正常执行完毕,而没有异常break跳出。就可以执行else, 只要有break旧不会执行else range(n) ~ range(0,n) range(m,n) ~ range(start,end) range(m,n,step) ~ range(start,end,step) 3,4 for i in range(5): print(i) 0,1,2, for i in range(5): pass else: pass beak 跳出 ''' ''' while:...
610b6f91ff7015e14065a4d4b5d5f24c2e33df48
nargiza-web/python
/python-thursday-exercises/5p_work_or_sleep_in.py
463
4.09375
4
# 5. Work or Sleep In? # Prompt the user for a day of the week just like the previous problem. Except this time print "Go to work" if it's a work day and "Sleep in" if it's a weekend day. Example session: # $ python work_or_sleep_in.py # Day (0-6)? 5 # Go to work # $ python work_or_sleep_in.py # Day (0-6)? 6 # Sle...
cb6005830f2910b59f7409449bca557cb139753c
summercx1988/bellmanford
/test/negative_cycle.py
667
4.34375
4
""" A simple shortest path problem on a digraph with a negative cycle. Expected solution: - Negative cycle? True - Shortest path length = -100 (length of negative cycle) - Shortest path = [3, 2, 3] (negative cycle) """ import networkx as nx import bellmanford as bf G = nx.DiGraph() G.add_edge(1, 2, lengt...
02b820b9e226674dbc6d1cbd3af0af07c59e942d
boymennd/100-day
/Beginner (Day 1 - day 14)/day 4/Ex1.py
1,376
3.859375
4
from random import choice dam = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' la = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' keo = ''' _______ ---' ____)____ ______) __________) (____...
16bf048af07ecaf5dc76a9f4774c74e173ee1e73
soply/mpgraph
/mpgraph/tilingElement.py
30,913
3.59375
4
# coding: utf8 """ Implementation of elements of a tiling as a class. Each object of this class, called TilingElement, constitutes a single tile of the tiling, ie. a connected area of parameters that leads to the same support and sign pattern. """ __author__ = "Timo Klock" import numpy as np from create_...
f7a2ce4468ac7711e1a890e07811a77eaa5f49e4
mateuszpoleski/maze-game
/player.py
4,175
3.71875
4
"""File with implementation of Player class.""" import copy import turtle import utl import writers from constants import BLOCK_PIXEL_SIZE class Player(turtle.Turtle): """A class to represent a player of the game.""" def __init__(self, level, treasures, maze_size): """ Constructs all the nece...
171136077892dabb1ebee765ebff4359433ebc3f
pvanh80/intro-to-programming
/round08/Writing_numbered_rows_file.py
540
4.0625
4
# Intro to programming # Writing numbered rows to a file # Phan viet Anh # 256296 def main(): file_name = input('Enter the name of the file: ') file_open = open(file_name, 'w') print('Enter rows of text. Quit by entering an empty row.') row = 1 while True: file_line = input("") ...
6286de34c76ca3bcefec36960fca01462bf250ed
Yuu-taremayu/school
/simuration/class_11_5/pi1.py
1,063
3.5625
4
import math def leibniz(): n = 1000000 print('n =', n) s = 0.0 for i in range(n+1): s += (-1)**i / ((2*i) + 1) pi = s * 4 return pi def machin(): n = 10 print('n =', n) num_1 = 0.0 for i in range(3*n+2+1): num_1 += ((-1)**i / (2*i+1)) * ((1/5)**(2*i+1)) num_...
ecc1bf50a8ad01f0829764d31385efe9953bbbfc
yurifrost/FAMCS_Python
/ex2/straight_line_test.py
482
3.5
4
import numpy as np a = 4 c = 2 def f(x): return 4 * x + 1 def checkFunc(x): return float(f(x) - f(c)) / (x - c) correct = 0 incorrect = 0 for x in np.random.uniform(0, 10, 100): if checkFunc(x) == a: correct += 1 else: incorrect += 1 print('Wrong: %.20f' % checkFunc(x)) p...
9a8e1dafd59ffb05f893250c063bf9128b9a49ed
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/df2b6a76cf6b4955818241631cc1ecdc.py
456
3.640625
4
import re class Phrase: def __init__(self,text): self.text = text def word_count(self): """ Split text stream by words, and return word counts """ # Split by non-alphanumerical boundaires split_text = re.split('\W',self.text.lower()) # Count occurences counts = {} for word in split_...
46e6b2cdfd6a9709d2ce219fc76381ad3045ba06
kylzhng/OtherProjects
/TicTacToe/TicTacToe.py
3,275
4.125
4
import random game_on = True # keeps track of whether or not there is a winner player = 'X' winner = None board = ['-', '-', '-', '-', '-', '-', '-', '-', '-'] def play_game(): global ans print('Welcome to TicTacToe!') while (True): ans = input("Would you like to play again...
166363dc193a68b4411319b87920208999a75073
yumendy/OJ
/ZOJ/1240AC.py
260
3.65625
4
num = int(raw_input()) for _ in xrange(num): wrd = [] word = raw_input() for letter in word: if ord(letter) == 90: wrd.append('A') else: wrd.append(chr(ord(letter) + 1)) new_word = ''.join(wrd) print "String #%d" %(_ + 1) print new_word + '\n'
9e9fe4c093027183a77f02b8d60c34c2b57f0c1d
jsheppard95/RPi
/sheppard_homework/sheppard_hw2/p6_hw2.py
1,642
4.6875
5
#!/usr/bin/env python3 # P6) Write File # This program creates a file containing two user-provided strings, one per line in the file: def careful_write(outlines, filename): """Write a list of strings to a file, if the file doesn't yet exist. outlines: a list of the strings to be written filename: where...
6682c74ba9e14173dbebef88b00e44882654d272
zorzonp/Mini_Proj_3
/MySQL_Helper.py
8,929
3.796875
4
import MySQLdb import sqlConnectInfo HOST = "localhost" #This function connects to a MySQL instance and returns the connection def connectToInstance(): USER = sqlConnectInfo.USERNAME PASSWORD = sqlConnectInfo.PASSWORD #attempt to connect to the instance of the MySQL try: connection = MySQLdb.connect(host=H...
dcc7254c6a672d857568a3f565ba90fee159b6bb
stanilevitch/python_learning
/pelta_while.py
167
3.75
4
n = 5 if n > 0: print(n, 'pierwszy') n = n - 1 print(n, 'koniec_1') ######################### while n > 0: print(n, 'drugi') n = n - 1 print(n, 'koniec_2')
1e3b397b786a8b5a7478015dfd9d80489baceaec
sanyamcodes26/Efforts
/DerekBanas_UDEMY/Section_33.py
1,602
3.71875
4
import re def initial(): rand_str = "1. Dog 2. Cat 3. Turtle" print(rand_str) regex = re.compile(r"\d\.\s(Dog|Cat)") print(re.findall(regex, rand_str)) rand_str = "11-23-2014" print(rand_str) regex = re.search(r"(\d{1,2})-(\d{1,2})-(\d{4})", rand_str) print(regex.group()) print(re...
6aa8d22cc3136c5f82a48bd14e98332ad46c620c
JavaRod/SP_Python220B_2019
/students/shodges/lesson08/inventory.py
2,047
3.59375
4
""" Functionality to allow inventory management for HP Norton. """ import csv from functools import partial def add_furniture(invoice_file, customer_name, item_code, item_description, item_monthly_price): """ Add a new record to the CSV invoice_file in this format: customer_name,item_code,item_descriptio...
a5118a1ede7c8c9f4bd1e7d99e2ee1204a8b9f6e
ecominguez/coursera-python
/AssignmentWeek3.4.py
330
3.859375
4
#Agregando el try al ejercicio anterior try: hrs = input("Enter Hours:") rph = float(input("Enter rate per hour:")) h = float(hrs) except SystemExit: print("Error. Enter a numeric value.") raise if h>40: pay = 40 *rph pay += (h-40)* (rph*1.5) else: pay = h*rph print("Should pay {}".for...
c7ff184cc6cbe9970ace732c48c284ded483e6f7
vladspirin/python-learning
/self-learning/based/objects.py
582
4.21875
4
# Неизменяемые типы данных # x = 10 # print(x, id(x)) # x = 20 # print(x, id(x)) # s = 'hello' # print(s, id(s)) # s += ' world' # print(s, id(s)) # Изменяемые типы данных # l = [1, 2, 3] # print(l, id(l)) # l.append(5) # print(l, id(l)) # x = 10 # y = x # print(x, id(x), y, id(y)) # # x = 15 # print(x, id(x)) # pri...
65098d7c2e179886bfa55b44b00a9138890a9ba4
rctorresn/Mision-Tic-2021
/Programación/16. RaizCuarta_EjecicioSesion16.py
202
3.8125
4
import math print("Ingres el numero: ") numero = int(input()) def raizCuarta(numero): raizC=math.sqrt(numero) raiz4Ta = math.sqrt(raizC) return(round(raiz4Ta,3)) print(raizCuarta(numero))
236b366d504a4a0d9e1125a1622a1782c9ed8df3
NMcIntosh91/Connect4
/connect4.py
3,765
3.9375
4
#from termcolor import colored def setUpField(width, placeHolder): f = [] for col in range(width): row = [] for r in range(width): row.append(placeHolder) f.append(row) return f #Displays game field def printField(noOfTurns): print("Turn Number " + str(noOfTurns) + "\n") width = len(field) for i in ran...
e8b64559237c9198321ee82e2e1516c44f721444
mishrabiswajeet/python
/swapping of number.py
114
3.65625
4
a=32 b=23 a= a+b b= a-b a= a-b print("The value of a after swapping",a) print("The value of b after swapping",b)
2e0e0c53452d60775f3d111e1bb32711976fa371
SoraUmika/PROJECTS
/flappy burb/physic.py
1,193
3.640625
4
from pygame.draw import circle from pygame import rect NORTH = (0, -1) SOUTH = (0, 1) EAST = (1, 0) WEST = (-1, 0) class Body(rect.Rect): def __init__(self, term_velocity, *pargs): super().__init__(*pargs) self.v = 0 self.term_v = term_velocity def set_velocity...
57434aaee8a6acf40f9b8d5185a39b9fc6783f9d
AkashGandhare/python_pract
/if_loop_pract.py
138
3.9375
4
name = "Tranky" if name == "sammy": print("Hi sammy") elif name == "Franky": print("Hi Franky") else: print("Please tell your name")
2460d21b07e9e378308be529feb3155b63f16b58
dkaramit/ASAP
/Artificial_Neural_Networks/python/FeedForwardANN/FFANN_backProp.py
1,967
3.5
4
def backPropagation(self): ''' Define Delta^{f}_{ji} = \dfrac{\partial s^{[N-1)]}_{k}}{\partial s^{[N-(f+2)]}_{i}}. For f=0,1,2,...N-2 this is n^{(N-1)} \times n^{(N-(f+2))} matrix Notice that the Delta^{self.total_layers-2}_{ji} = \dfrac{\partial s^{[N-1)]}_{k}}{\partial s^{(0)}_{i}} ''' ...
0f8513632ec1ade1b56ebcbfcf366497d424353e
bkreiser01/python-small
/BadBreak.py
342
4.0625
4
#Put your name here. while True: #Prompt user and receive input. print("Please enter the letter 'X'.") userLetter = input() #Handle user's input appropriately. if userLetter == 'X': break else: print("That's not what I asked for!") print("Very good! You clearly have superior ...
e4d39a2c2159181242d10dee424fc1dd94b83f94
mikechen092/MorseQuestion
/database.py
3,572
3.859375
4
import day_info import datetime class Database(): # initialize Database class with an array to store the di_objects in def __init__(self): # array of sorted date_price obj by date self.db = [] #add_entry - takes in a new day_info and inserts it in the correct place # @param di_ob...
3462155cc0a935213a87c5ec0c7decb8275b4094
sapanpatel/Python-1
/guessing_game.py
974
3.5625
4
import sys def yesno(s=''): r = False try: yn = input(s + ' [Y/n] ') except EOFError: sys.exit() if yn != '' and yn[0].lower() == 'y': r = True return r try: name = input('Hi, What is your name? ') except EOFError: sys.exit() print('Hello ' + name + '! Let\'s play...
500db13dc0194185784047e14686594c533d609a
ref1821/blackjack
/venv/Include/classes.py
792
3.796875
4
from random import * # clase para el juego class game : def __init__(self): a = randint(1, 13) b = randint(1, 13) print("number 1=") print(a) print("number 2=") print(b) c = a + b print("total=") print(c) while c < 21: pri...
dc5cfafa73789a4e5ff46e2c23ac1171247efe0f
Swapnil7711/Python-Programming-Challenges
/Easy/04 A Very Big Sum.py
662
4.09375
4
''' You are given an array of integers of size N. You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large. Input Format The first line of the input consists of an integer N. The next line contains N space-separated integers contained in the array. Output...
46a2f4df735406148c4d9fec4300e49e37acff6a
CERN/CAiMIRA
/caimira/dataclass_utils.py
2,684
3.5
4
import dataclasses import typing def nested_replace(obj, new_values: typing.Dict[str, typing.Any]): """Replace an attribute on a dataclass, much like dataclasses.replace, except it supports nested replacement definitions. For example: >>> new_obj = nested_replace(obj, {'attr1.sub_attr2.sub_sub_attr3': 4}...
ac60ba71704efe75e36b46ce277b6d2b6b55b3d2
MasonEgger/advent-of-code-2020
/dec01/solution.py
1,014
4
4
def find_two_sum_and_mult(expenses, sum): for x in expenses: for y in expenses: if x + y == sum: return x * y def find_three_sum_and_mult(expenses, sum): for x in expenses: for y in expenses: for z in expenses: if x + y + z == sum: ...
d5674c11fcd417674d3e25c1d70c0fc4f030f557
kumar88862/python_practice
/q12.py
243
4.28125
4
# 12 Take values of length and breadth of a rectangle from user and check if it is square or not. length=int(input("Enter lenght:")) breadth=int(input("Enter breadth:")) if length==breadth: print("Square") else: print("Not a Square")
5d9b412f11db9fdfe32d9c5c436c72b9660f4ffb
yousefalamri/Ensemble_Learning
/Adaboost/Adaboost_train.py
12,033
3.53125
4
import math import statistics import numpy as np import matplotlib.pyplot as plot ############################# supporting functions for Decision Tree ################################ # Load train.csv and test.csv with open('train.csv') as f: training_data = []; for line in f: terms = line.strip().spli...
674f828d721eb9dcb3c422c6fda39f76f57a47d0
darkleave/python-test
/Test/venv/Example/2/8.py
341
3.6875
4
#成员资格 permissions = 'rw' isIn1 = 'w' in permissions print('isIn1:' + str(isIn1)) isIn2 = 'x' in permissions print('isIn2:' + str(isIn2)) users = ['mlh','foo','bar'] isIn3 = input('Enter your user name: ') in users print('isIn3:' + str(isIn3)) subject = '$$$ Get rich now!!! $$$' isIn4 = '$$$' in subject print('isIn4:' ...
4ed0fd2fcbb6febe51391a132993a3de1c02dcba
himanshu98-git/python_notes
/exmple_of_instnce_mthd.py
1,244
4.34375
4
# SOME EXAMPLES OF INSTANCE METHOD # # """ # class Test: # def __init__(self,name,age,marks = 14.0): # self.name = name # self.marks = marks # self.age = age # def disp(self): # print("Hello",self.name) # print("Your marks is",self.marks) # # def div(self): ...
7b2c561d2c34b3250a42fa1560f780a1353bb940
i300/AdventOfCode
/2020/six/solution.py
800
3.609375
4
def countAnswers(group): answers = set() for answer in group.replace(',', ''): answers.add(answer) return len(answers) def countAllYesAnswers(groups): numGroups = len([group for group in groups.split(',') if group]) answers = dict() for answer in groups.replace(',', ''): if answ...
99a7e8c2a8a185849dc7ea486a5bca2fb398b32a
ido20-meet/meetyl1201819
/lab_7.py
1,030
4.03125
4
from turtle import * import random import turtle import math class Ball(Turtle): def __init__(self,radius,color,speed): Turtle.__init__(self) self.shape('circle') self.shapesize(radius/10) self.radius = radius self.color(color) self.speed(speed) ball1 = Ball(30,'red', 10) ball2 = Ball(20, 'blue',10) balls...
c95292f8af608a9618ea7e2321e9dbb50643411f
zuikaru/2110101_Com_Prog_2018_2
/04/04_P23.py
363
3.84375
4
s = input().lower() search = input().lower().strip() str_list = [] # Tokenize token = "" for c in s: if c not in [' ','\'','"','.',',']: token += c else: if len(token) > 0: str_list.append(token) token = "" if len(token) > 0: str_list.append(token) # Search print('Fou...
7a7a0fe1645fef60da60e0fe3233053bd786ed27
Akbotam/BFDjango
/Week1/HackerRank/eazy11.py
256
3.78125
4
def mutate_string(string, position, character): for i in range(0, len(string)): if i == position: string[i] = character return string s = input() position = int(input()) character = input() mutate_string(s, position, character)
59fcddeaad67da4ded6eeb5ee5e4be62ae0bc0dc
Astro-ibha/Code-Practice
/python exercise/hw0b.py
241
3.765625
4
#BT3051 Assignment 0b #Roll number: ED14B028 #TIme 0:20 x=int(input("enter a number > ")) print(x) while(x!=1): if x%2==0: x = x//2 print(x) else : x = 3*x+1 print(x)
7e8b487c8ac791b4d7d22daf403515b5560d5a76
way2muchnoise/Advent2018
/day05/part2.py
741
3.890625
4
import string import StringIO def is_opposite(a, b): return a == b.swapcase() and b == a.swapcase() def react(f): chars = f.read(1) next_char = f.read(1) while next_char: if len(chars) > 0 and is_opposite(chars[-1], next_char): chars = chars[:-1] else: chars +...
13a592adf46fdf79db709dc3a003ad9d34e14a46
MariusDanutIancu/PythonLabs2017
/lab1/ex_9.py
1,539
4.125
4
""" Author: Marius-Danut Iancu Email: marius.danut94@outlook.com Creation date (mm-dd-yyyy): 1/27/2018 Version: 0.1 Status: Production Python version: 3.x A. I. CUZA UNIVERSITY OF IAŞI Faculty of Computer Science Iasi Exercise: Write a function that returns the largest prime number from a string given as a parameter...
68b9dd2a2f4a2bd074d3ff6a618cdf325ac4ad69
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc025/A/4926675.py
344
3.59375
4
def string25(S: str, N: int) -> str: sortedS = sorted(S) count = 1 for c1 in sortedS: for c2 in sortedS: if count == N: return c1 + c2 count += 1 return "hoge" if __name__ == "__main__": S = input() N = int(input()) ans = string...
feb9637e915d9be3aa3557315dbeca6c4b934662
jschuringa/damage-calculator
/weapon/tests/tests.py
2,574
3.828125
4
import unittest from weapon import weapon class TestCalculator(unittest.TestCase): def test_type_does_more_damage(self): """ Asserts attack with matching weapon type does more damage """ axe_with_fire = weapon.Axe(10, 20, 5, "fire", 10) axe_without_fire = weapon...
93035b482e2c8f06493ff170ffb0c4f994db7b17
m3ngineer/interview-generator
/intprep.py
2,628
3.625
4
import numpy as np from questions_answers import question_dict_tech, answer_dict_tech def pick_nontech(num_questions=1): question_dict = { 0: ["Tell me about yourself. How did you get here?"], 1: ["Why are you interested in this position?", "What are you looking for in your next position?"], 2: ["Why th...
b81603db91395b2f1c362bffec0a8cefde930cca
JorJeG/python
/3/countries.py
328
4.03125
4
countries = ['Germany', 'USA', 'Spain', 'UK', 'Australia'] print(countries) print(sorted(countries)) print(countries) print(sorted(countries, reverse=True)) print(countries) countries.reverse() print(countries) countries.reverse() print(countries) countries.sort() print(countries) countries.sort(reverse=True) print(cou...
959d59abc59d99836d25fa8b46ef9740de98be40
gmrdns03/Python-Introductory-Course_Minkyo
/Python_Pandas_Basics/Pandas02_06_lambdaEx02_김민교.py
365
4.03125
4
# lambda 활용법 x = lambda a : a+ 10 print(x(5)) x = lambda a, b : a*b print(x(5,6)) def myfunc(n): return lambda a : a* n mydoubler = myfunc(2) #mydoubler = lambda a: 2*a print(mydoubler(11)) #11이 --> a라는 변수에 들어가서 출력된다. def myfunc(n): return lambda a : a* n mydoubler = myfunc(3) print(myd...
d36c3c0f1a60c37cb4b3ff724ab0495ea54cc5b2
fabiovpcaumo/curso-de-python
/semana02/aula01/exercicio_04.py
938
3.53125
4
from unittest import TestCase from problema03 import Calc class TestCalculadora(TestCase): def setUp(self): print("\nNo setUp") self.calculadora = Calc() def tearDown(self): print("No tearDown") del self.calculadora def test_soma_deve_retornar_2_com_1_e_1(self): ...
b7f121c7d31656bd4c97e22f2da58f282dcd4b59
cococ0j/ThinkPython-answers
/16-2.py
608
4.25
4
import copy class Time(): """ represent time with hour,minute,second """ def print_time(time): print('%.2d:%.2d:%.2d'%(time.hour,time.minute,time.second)) def is_after(t1,t2): tuple1 = (t1.hour,t1.minute,t1.second) tuple2 = (t2.hour,t2.minute,t2.second) return tuple1 > tuple2 def alt...
ca79ec3dc0c6b49a53bbca633a3c319929ce36c5
LouisYLWang/leetcode_python
/206.reverse-linked-list.py
1,016
3.78125
4
# # @lc app=leetcode id=206 lang=python # # [206] Reverse Linked List # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # iterative method class Solution: def reverseList(self, head): cur = head pre = Non...
55d4a3a3c1412daed762a4eaf1990663d3f880ba
brandontrabucco/diffopt
/diffopt/taylor_series.py
2,565
3.671875
4
"""Author: Brandon Trabucco, Copyright 2019, MIT License""" import tensorflow as tf def first_order( nonlinear_model, inputs ): """Linearize a nonlinear vector model about a center. Args: - nonlinear_model: a nonlinear model that is a distribution the function acce...
28d4c8918b358875eda68e9ab111eb091e7680f1
nikita-ananiev/project
/test.py
1,887
3.703125
4
import pygame pygame.init() size = int(input()), int(input()) screen = pygame.display.set_mode((800, 800)) screen2 = pygame.Surface(screen.get_size()) running = True x = 0 v = 10 fps = 120 clock = pygame.time.Clock() screen.fill((0, 0, 0)) class Board: # создание поля def __init__(self, width, height): ...
96beb7360b32cd3440df01b0ff7336a13c6f8f1c
Akshat1276NSP/CBJRWDhome_assignment
/Python revision full course/62.py
117
3.546875
4
def multiply_table(n): for x in range(1, 11): c = x*n print(n,"X",x," =", c) multiply_table(7)
19ae0643b4eeb43f57755c5ed2b9da2f5d4591a5
afcarl/Practical-Data-Wrangling
/Chapter04/code/pandas_intro.py
923
4.03125
4
import pandas ## read the csv file into a pandas dataframe roads = pandas.read_csv("../data/input_data/artificial_roads_by_region.csv") ## print out the column headers # print("column headers:") # print(list(roads)) ## extract roads from 2011 roads_2011 = roads['2011'] # print(roads_2011) ## convert the data type f...
13a289ef71749d4de509943dbe6314b18a68f2ae
Sruthi-hemadri/python
/src/assign24d.py
215
4.125
4
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' no_punct = "" mystr = "Hello!!!, he said ---and went." for char in mystr: if char not in punctuations: no_punct = no_punct + char print(no_punct)
2e68a950a589f410fb2f6fddd16d5a0a215f1eee
Will-is-Coding/exercism-python
/robot-simulator/robot_simulator.py
1,922
4.28125
4
NORTH, EAST, SOUTH, WEST = ((0, 1), (1, 0), (0, -1), (-1, 0)) class Robot: """Robot simulator that has coordinates, bearing, and can advance Variables: directions {list} -- Cardinal directions in a list coordinates {tuple} -- Contains x, y coordinates bearing {tuple} -- Conta...
497bd908cc7eabc779dcb580045437afbaaac53c
SeongwonChung/CodingTest
/dongbinbook/BinarySearch/2-부품찾기_set.py
487
3.8125
4
""" 집합자료형 set을 활용한 풀이. 한번씩 등장여부만 확인하면 되므로 set을 사용하여 처리한다. 집합자료형의 특징은 1. 중복을 허용하지 않는다. 2. 순서가 없다. """ N = int(input()) array = set(map(int, input().split())) M = int(input()) for x in list(map(int, input().split())): if x in array: print('yes',end=' ') else: print('no', end=' ') """ example i...
bc11da046803ce184352bfd98888c54b6350d271
afairlie/katas
/find-smallest.py
405
4.03125
4
def find_smallest(arr): smallest = arr[0] for n in arr: if n < smallest: smallest = n return smallest print(find_smallest([78, 56, 232, 12, 11, 43])) # 11 print(find_smallest([78, 56, -2, 12, 8, -33])) # -33 # better solution def find_smallest_int(arr): return min(arr) print(find_smallest_int([78,...
23a84b1883254357598927c13d4aa82b9e4730d4
Mithun-1234/Letsupgrade-Assignment
/Day 1 assignment.py
86
3.53125
4
A = [int(i) for i in input('Enter the values:').split()] A.sort(reverse=True) print(A)
f07cfc8ed1a13bab721d46c8d263747d702628f4
michal0janczyk/interview_preparation
/Coding Challenges/Techie Delight/Binary Tree/find_minimum_depth_binary_tree.py
2,077
4.21875
4
from collections import deque class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right # Queue node for storing a pointer to a tree node and its current depth class qNode: def __init__(self, node=None, depth=None): s...
1888109c5160f0fb7438d824df81e92839539d9c
jothamsl/Algorithms-n-Data-Structures
/Algorithms/Sort/bubble_sort.py
907
4.3125
4
""" TASK ---- Given an array, sort the array in an ascending order EXPLANATION ----------- The bubble sort algorithm takes in an array and compares each successive pair of elements and inverts the elements if they are not in order. [4, 2, 1, 0] -> [4, 2, 1, 0] -> [0, 1, 2, 4] ^ ^ |-...
e7b1ebd641c896be7bba253a03011e57c8b73e12
mlsh1112/python-for-coding-test
/Recursive/factorial.py
273
4.0625
4
def factorial_iterative(n): result=1 for i in range(1,n+1): result*=i return result def factorial_recursive(n): if n<=1: return 1 return n*factorial_recursive(n-1) print(factorial_iterative(5)) print(factorial_recursive(5))
ba5fc8d0c44ca5bb0c855eeb1079f4043b2239a3
Nogueira-Candido/CursoPython---Modulo_01
/ex042.py
596
4
4
a = float(input('Digite a medida A do triângulo: ')) b = float(input('Digite a medida B do triângulo: ')) c = float(input('Digite a medida C do triângulo: ')) if (b - c < a and a < b + c) and (a - c < b and b < a + c) and (a - b < c and c < a + b): print( 'Medidas informadas formam um triângulo ', end='') if ...
9b7d0751cfc7c08d1ab9f70847cd5220e9e00a60
Zzpecter/Coursera_AlgorithmicToolbox
/week5/1_money_change.py
552
3.84375
4
# Created by: René Vilar S. # Algorithmic Toolbox - Coursera 2021 DENOMINATIONS = [0, 1, 3, 4] INF = 100000 def coin_change(n): num_denominations = len(DENOMINATIONS) - 1 coins_to_use = [0]*(n+1) for j in range(1, n+1): minimum = INF for i in range(1, num_denominations+1): i...
7d4c85d7ec528fa85e3384abb8bdbebb57fcbebb
Brunoenrique27/Exercicios-em-Python
/desafio71 - Simulador de Caixa Eletrônico.py
843
3.921875
4
##programa que simule o funcionamento de um caixa eletrônico. No início # pergunte ao usuário qual será o valor a ser sacado (número inteiro) # o programa vai informar quantas cédulas de cada valor serão entregues. # OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. valor = int(input('Valor do saque:...
af4282d2ead58cddd150b47b5068ce07be81d419
Vasallius/Python-Journey
/Automate the Boring Stuff With Python/Ch7-Pattern Matching and Regular Expressions/strong_password_detection.py
1,093
4.40625
4
# Strong Password Detection ''' Description: Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. ''' import...
76a91fb235e511137b25bdc82a5c71e62fc3b160
Ken-LiuL/data-structure-and-algorithms-with-python
/sequence/stack.py
512
3.828125
4
class Stack: def __init__(self): self.items = [] def empty(self): return len(self.items) == 0 def pop(self): if self.empty(): raise RuntimeError('Attempt to pop from an empty stack') item = self.items[-1] del self.items[-1] return item def...
e3044018833829b70ce9f0b57943960453c3061e
jonathanlei/python-oo-practice
/serial.py
803
3.78125
4
class SerialGenerator: """Machine to create unique incrementing serial numbers. >>> serial = SerialGenerator(start=100) >>> serial.generate() 100 >>> serial.generate() 101 >>> serial.generate() 102 >>> serial.reset() >>> serial.generate() 100 """ def __init...
ef4ddb489377ad40d2faf5be9649ca5dd3660180
jaegr/jrats
/rat.py
7,249
3.65625
4
# -*- coding: utf-8 -*- import random import pygame import tile import weapons class Rat(pygame.sprite.DirtySprite): """Base class for all rats, which both regular rats and terminator rats inherit from""" def __init__(self, direction=None): """Optional input argument direction for when a new r...
373b6fc9449c2f92cfbf11e420ecfb32e6912a83
volknet/TwitterBot
/filetest.py
190
3.515625
4
import re file_handle = open('putfile.txt', 'r') readFile = file_handle.readlines() for line in readFile: data = line.strip() search = re.search('text:', data) if search: print(search)
5e287821f943108d7bd3ffddf0390dd5a56dc29e
Th3Lourde/l33tcode
/problemSets/fb/238.py
587
3.734375
4
''' Ok so calculate the right product then calculate the left product [0,1,2,3] RHS 1*2*3,2*3,*3,1 LHS 1,0*,0*1,0*1*2 ''' class Solution: def productExceptSelf(self, nums): resp = [1 for _ in range(len(nums))] lProd = 1 for i in range(1, len(nums)): lProd *= nums[i-1] ...
20783cc85bb7906f2c37e923753f8989d6f9ddbc
kastnerkyle/tfbldr
/examples/vq_vae_music/decode.py
5,068
3.546875
4
import numpy as np import itertools def dijkstra_path(graph, start, end, visited=[], distances={}, predecessors={}): """Find the shortest path between start and end nodes in a graph""" # we've found our end node, now find the path to it, and return if start == end: path = [] while end != No...
090f5d06eb3f43f4cb269afaff5ba4576f7a7649
pjoachims/ees-pees
/backend/webotsgym/utils/io.py
550
3.734375
4
import pickle def save_object(obj, path): """Save object via pickle. Parameter: ---------- obj : object object that should be saved at the specific path path : str path to where to save the specific object """ filehandler = open(path, 'wb') pickle.dump(obj, filehandle...
2e570974842ad2b9c7225e3a280bf907b7a502a5
ShanDeng123/CS313E-DataStructuresAndAlgos
/ERsim.py
6,026
4.0625
4
# File: ERsim.py # Description: HW5 - Creating queues to deal with ER priorities # Student's Name: Shan Deng # Student's UT EID: SD33857 # Course Name: CS 313E # Unique Number: 50739 # # Date Created: 3/12/19 # Date Last Modified: 3/12/19 #Creation of a Queue class as given by Dr. Bulko class Queue: #All...
d90e676a00bbd4912d57fe3a4e553d4218dba287
Lee-3-8/CodingTest-Study
/level2/괄호_회전하기/규빈.py
626
3.578125
4
def solution(s): answer = 0 l = len(s) for i in range(l): after = s[:i] before = s[i:] string = before+after if iscorrect(string): answer += 1 return answer def iscorrect(s): symbols = { '(': ')', '{': '}', '[': ']', } op...
0dfee264f75369f4e8a17aeb3bf742de01b2ee11
Senbagakumar/SelfLearnings
/Demos/InterviewPrepration/Prepration/Prepration/HackerRank/Implementation/Larry's Array/Solution.py
677
3.6875
4
#!/bin/python3 import sys """ A rotation does not change the parity of the number of inversions. The array can be sorted only if the initial number of inversions is even (since we want 0 inversions at the end, i.e. an even number). """ if __name__ == "__main__": t = int(input().strip()) for a0 in range(t): ...
c7b3e2f329fcb3da19454bf0683eb638e49785f4
Simochenko/stepic_python
/sixth_module/6.1_numeric_data_types.py
11,031
3.765625
4
# Тема урока: числовые типы данных # Целочисленный тип данных int # Числа с плавающей точкой float # Встроенные функции max(), min(), abs() # Решение задач # Аннотация. Числовые типы данных. Вспомним особенности работы с целыми числами, научимся # работать с числами с плавающей точкой. Изучим три встроенные функции для...
8d0269420ac9404b7b27139dc2881425e29731aa
juny0/advent-of-code
/2020/2020-day10-pt1.py
1,044
3.65625
4
input = """73 114 100 122 10 141 89 70 134 2 116 30 123 81 104 42 142 26 15 92 56 60 3 151 11 129 167 76 18 78 32 110 8 119 164 143 87 4 9 107 130 19 52 84 55 69 71 83 165 72 156 41 40 1 61 158 27 31 155 25 93 166 59 108 98 149 124 65 77 88 46 14 64 39 140 95 113 54 66 137 101 22 82 21 131 109 45 150 94 36 20 33 49 146...
16c7f62d727da5720d21055e2ddb1d58ae2012ad
scottherold/simple_python
/for_loop_basic2.py
1,791
3.765625
4
def makeItBig(arr): i = 0 for element in arr: if arr[i] > 0: arr[i] = "big" i = i+1 return arr def countPositives(arr): i = 0 x = 0 for element in arr: if arr[i] > 0: x = x+1 i = i+1 arr[i-1] = x return arr def s...
fd1f597a6222da5dbe968bdce88f156312b22395
topherCantrell/class-IntroPython
/Topics/09_Exceptions/simdisk.py
995
3.703125
4
def read_byte(): print('Reading a byte') a = 0 # If you wanted to return a code, what would it be? #raise Exception('disk error') print('Got the byte') return a def read_word(): print('Reading a word') a = read_byte() b = read_byte() print('Got the word') return a*256 + b d...
2cba216dafb4c94d5ebb2caaa458381c82c17b97
Mystified131/DAPSupplementalCode
/Chapter_One.py
794
4.15625
4
print("Hello, world!") print("") input("Please press any key:") print("") reps = input("How many times shall I say 'Hello World'?: ") res = int(reps) for ctr in range (res): print ("Hello, world!") print("") ##Algorithm-- Write a plan for how to make the logic to have the computer write "Hello, world!" 20 t...
13d691453e9290af8554b8a963f536ae41009826
ssarangi/algorithms
/epi/arrays/sudoku.py
1,980
3.5625
4
def valid_row(board, row): seen = 0 for col in range(0, len(board[row])): if board[row][col] is None: continue if seen & (1 << board[row][col]): return False else: seen |= (1 << board[row][col]) return True def valid_column(b...
6f0032160b5cc6c9dae324ef9438be213b180dd4
FelixSeptem/Practice
/Data Structure/Linked_list.py
3,701
3.953125
4
# -*- coding:utf-8 -*- class Node(object): def __init__(self, data, next=None): self._data = data self.next = None def __str__(self): return 'Node:{}'.format(self._data) def __bool__(self): return self.next!=None def get_data(self): return self._data de...
5941e4100a0e7c47ced79ad7c6f21dc5246bffbf
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/2193.py
1,382
3.5
4
# Hey there. -- Joshua Allum -- # Prints the largest tidy number less than N t = int(input()) # read a line with a single integer for i in range(1, t + 1): N = int(input()) last_tidy = N digits = [] while N != 0: digits.append(N % 10) N //= 10 index = len(digits) - 1 ...
f49e5cfb6aa35661934200ddf64c66fed17b11b5
paul0920/leetcode
/question_leetcode/1091.py
1,135
3.796875
4
import collections grid = [[0, 0, 0], [1, 1, 0], [1, 1, 0]] if not grid or not grid[0] or grid[0][0] == 1 or grid[-1][-1]: print -1 exit() size_y = len(grid) size_x = len(grid[0]) q = collections.deque([(0, 0, 1)]) visited = set((0, 0)) def check_boundry_valid(y, x): if y < 0 or y >= s...
e0d58308a6bb2920554b46984a9b670ea4225e85
khushmeet29/PPL-Assignment
/a1/q6.py
369
3.9375
4
print("To find the first 10 pairs of amicable numbers") def sum_of_divisors(n) : sum = 0 for i in range (1, n): if(n % i == 0) : sum = sum + i i += 1 return sum num1 = 1 count = 0 while count != 10 : num2 = sum_of_divisors(num1) if (num1 < num2): num3 = sum_of_divisors(num2) if (num3 == num1) :...
5074d8b82211d8cfa9c70a8b578a165bb94946ad
NaveenKumar444/naveen1
/8.py
268
3.875
4
# while loops i = 1 while i <= 5: print("*" * i) i = i + 1 print("Done") # guessing game i = 1 while i <= 3: nav = int(input("guess: ")) if nav == 9: print("your won!") break i = i + 1 else: print("sorry, you failed... ")
5e7cfcc728b0c90cabaad1156615613dab5396cc
yannickkiki/programming-training
/Leetcode/python3/1290_binary_linked_list_to_integer.py
850
3.65625
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def get_decimal_value(self, head: ListNode) -> int: result = head.val head = head.next while head: result = result * 2 ...
67b9b49924ea2014fd110e8ad3dfbf3839d33769
subham1994/Algorithms
/Trie/trie.py
2,733
3.5625
4
class TrieNode: def __init__(self): self.value = None self.children = {} def __repr__(self): return '<TrieNode: {children}>'.format(children=list(self.children.keys())) class Trie: def __init__(self): self._root = TrieNode() def _get(self, root, key, pos=0): if not root: return None if pos == len...
26fddab3da91f8fa4ae78cba270f435262aaad89
Yash-YC/Source-Code-Plagiarism-Detection
/gcj/gcj/188266/iamFIREcracker/168107/0/extracted/A.py
922
3.671875
4
def ReadInts(): return list(map(int, raw_input().strip().split(' '))) def ChangeBase(n, b): target_num = [] while n: n, d = divmod(n, b) target_num.append(str(d)) return ''.join(reversed(target_num)) def IsHappy(n, b): s = ChangeBase(n, b) hystory = [s] for i in xrange(b**3): next = sum(int(...
5649fc8859dde70724010e9620d2e15ae00a3c15
sunnyhyo/Python-Study
/Algorithm/sort2.py
4,147
3.78125
4
# -*- coding: utf-8 -*- # insert sort # input : 리스트 a def insert_sort(a): n = len(a) for i in range(1, n): # 1부터 n 까지 key = a[i] # i 번 위치에 있는 값을 key 에 저장 j = i - 1 # j 를 i 바로 왼쪽으로 저장 # 리스트의 i 번 위치에 있는 값과 key 를 비교해 key 가 삽입될 적절한 위치를 찾음 while a[j] > key and j >= 0: ...
5fe238b84ee73ef846eb6240d5995c7534689687
Njihia413/python-intro
/functions.py
469
3.921875
4
#Functions are blocks of code that begin with the def keyword def fun_a(): #function declaration print("I have been called") fun_a() #calling the function #passing arguments to functions def fun_a(a,b): print(a+b) fun_a(1,4) #functions that take in keyword arguments def fun_a(a=6,b=7): print(a+b) fun...
02946a722221040372d6406ec1db0831d233e6d3
mywns123/dojangPython
/tkinter_gui/tkinter_gui_09scale.py
1,358
3.671875
4
from tkinter import * # 창 띄우기 window = Tk() window.title("영남인재 교육원") window.geometry("800x500+100+100") window.resizable(False, False) bx = 0 by = 0 def selectV(event): value = str(scaleH.get()) + "," + str(scaleV.get()) buttonQselect.config(text=value) buttonQselect.place("위치:", x=scaleH.get(), y=sca...
2a5e87ffe2c1b37c997433c895076d3b9043a8d9
RamonCastill/PonGame
/player.py
908
3.5625
4
from turtle import Turtle STARTING_POSITIONS = [(-380, -60), (-380, -40), (-380, -20), (-380, 0), (-380, 20), (-380, 40), (-380, 60)] MOVE_DISTANCE = 20 UP = 90 DOWN = 270 STAR_POSITION = (-230, -200) class Player(Turtle): def __init__(self, x_position, y_position): super().__init__() self.shape(...
2faf60dc78a471e1f3962d9861fb48bf0404a9ca
tekkoloji/AlgoritmaAnalizi
/sinav/matris.py
280
3.640625
4
a=[[2,3],[4,5]] b=[[1,4]] for x in range(0,len(a)): list=a[x] for y in range(0,len(b[0])): toplam=0 for z in range(0,len(list)): #print list[z]+" "+b[z][y] toplam=toplam+list[z]*b[z][y] print toplam, print " "
72666e84ed4f318e911203436b8bf4b88a887e93
bc2009/HuaWei-Machine-test
/坐标移动.py
2,013
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/19 17:34 # @Author : 一叶知秋 # @File : 坐标移动.py # @Software: PyCharm """ 题目描述 开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。 输入: 合法坐标为A(或者D或者W或者S) + 数字(两位以内) 坐标之间以;分隔。 非法坐标点需要进行丢弃。如AA10; A1A; $%$; YAD; 等。...
f18e49df29222e779831cff0ce0a6ff1234329ae
IrfaanDomun/Dataquest
/python-programming-beginner/Challenge_ Files, Loops, and Conditional Logic-157.py
726
3.671875
4
## 3. Read the file into string ## file = open("dq_unisex_names.csv",'r') data = file.read() ## 4. Convert the string to a list ## f = open('dq_unisex_names.csv', 'r') data = f.read() data_list = data.split("\n") first_five = data_list[:5] ## 5. Convert the list of strings to a list of lists ## f = open('dq_un...
c17a844a3c356a31df156ad99cd42da5b2bfe690
SK7here/learning-challenge-season-2
/Kailash_Work/Strings/Palindrome.py
616
4.4375
4
#Function which return reverse of a string def Reverse(s): #Syntax-> [Start:End:Step] #'-1' means in reverse order return s[::-1] def isPalindrome(s): # Calling reverse function rev_text = Reverse(s) # Checking if both string are equal or not if (s == rev_text): return True ...
f0c6f3fe37b85abda5392a4d0c01085f6807b131
thornb/FoFSimulation
/2013-milgram-project-new/newSimulation.py
7,486
3.734375
4
#New simulation of a Friend of Friend network using Gowalla Data #Coded by Brandon Thorne and Miao Qi import pprint, pickle from math import radians, cos, sin, asin, sqrt, floor import sys import random #Functions to load the .pck data def load_network(): pkl_file = open('data/gowalla_spatial_network.pck', 'rb') re...