blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ff2eeacc298bc2880171f045d36c65a59e23710e
piyush09/LeetCode
/Remove All Adjacent Duplicates In String.py
969
3.71875
4
""" Algo: Use Stack approach for this solution. Keep a stack as a characters stack. Iterate characters of S (String) one by one. If the next character is same as the last character in stack, pop the last character from stack. If the next character is different, append it to the end of stack. T.C. - ...
80dabb328d39c7e90adbd7db23e9e702a9c8a090
rlsharpton/crash
/apiPractice.py
925
3.546875
4
import requests resp = requests.head("http://api.open-notify.org/") print(resp.status_code, resp.text, resp.headers) # Make a get request to get the latest position of the international space station from the opennotify api. response = requests.get("http://api.open-notify.org/iss-now.json") # Print the status code o...
62c52bd1498b9aba6662d596e337476c504f847b
andrade-paulo/Python-TDD
/test_avaliador.py
1,914
3.59375
4
from excecoes import LanceInvalido from unittest import TestCase # Biblioteca padrão para TDD from dominio import Leilao, Usuario # python3 -m unittest {nome_arquivo.py} -> Realiza todos os testes do arquivo # python3 -m unittest {nome_arquivo.py}.{nomeClasse}.{nome_funcao} -> Realiza o teste de uma função específica ...
72445a498caa06d91ba6f334d9028cd0124a7213
eskalnes/RL_memory
/rl_memory/memory.py
1,085
3.546875
4
import numpy as np """ idea: could create a graph that gets the optimal discounted_reward given observations """ class Memory: def __init__(self): self.past_states_reps = [] self.past_discounted_rewards = [] def memorize(self, state_representation, discounted_reward): self.past_state...
369cdd39ce0ef3abaa02bf91f56e8ab7ab960578
oceancoll/leetcode
/搜索旋转排序数组/answer.py
1,876
3.734375
4
# coding:utf-8 """ 33. 搜索旋转排序数组 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 你可以假设数组中不存在重复的元素。 你的算法时间复杂度必须是 O(log n) 级别。 示例 1: 输入: nums = [4,5,6,7,0,1,2], target = 0 输出: 4 示例 2: 输入: nums = [4,5,6,7,0,1,2], t...
1c080728a19d93ef753eb678807736a7cfd98a37
kprashant94/Codes
/BinaryTree/bst_ds.py
1,433
4.1875
4
######################################################################## # Title: Binary Search Tree # Project: codewarm.in # # Description: # A binary search tree is organized, as the name suggests, in a binary # tree. We can represent such a tree by a linked data structure in which # each node is an object. In addit...
0fd75bc9e2c6d7f579c9aeb00b5629dfdf7717f4
Sandip-Dhakal/Python_class_files
/class18.py
797
3.765625
4
# def is_date_valid(date_as_string): # day, month, year = map(int, date_as_string.split('-')) # return day <= 31 and month <= 12 and year <= 3999 # what = is_date_valid('41-11-2010') # print(what) list1 = ['Sandip', 'dhakal', 'Rambazar','Hello'] for id, val in enumerate(list1): print(id,val) def ...
e62ea5282941d78d2bc9904e2dda4e9b072b1395
CaptainSherry49/Python-Project-Beginner-to-Advance
/50 Setters & Property Decorators.py
835
4.25
4
# ------------------------- Setters & Property Decorators -------------------- # class Employee: def __init__(self, fname, lname): self.fname = fname self.lname = lname def who_is_employee(self): return f'Employee name is {self.fname} {self.lname}' @property def email(self): ...
a3bdde78335dc4af2aee6c4dc46d9c888b70d0b9
tribessdieter/PythonFundamentos
/aula2/a2-4-4.py
624
4
4
# Curso: PYTHON FUNDAMENTOS PROWAY # AULA : DIA 4 PARTE 4 - 3 # ASSUNTO: FOR COM LISTAS # DATA : 2021-09-04 produto ={'nome':'cerveja', 'desc': 'larger', 'cat':'bebida','valor' :1.89 } produto2 ={'nome':'vodka', 'desc': '500ml', 'cat':'bebida','valor' :18.99 } produtos_lista = [produto, produto2] #imprimindo cada di...
00221c988d7320fdd7417a775f38c8967046de97
julissel/Practice_with_Python
/venv/include/number_belongs_to_given_intervals.py
267
4.1875
4
""" There are given intervals {-10}and(-5, 3]and(8, 12)and[16, infinity). The program returns 'True' if the number belongs to any of interval's part? and 'False' if it not. """ numb = int(input()) print((-10 == numb)or(-5 < numb <= 3)or(8 < numb < 12)or(numb >= 16))
c3ee38068a3fee0765bdaea7796fc5ed7e02b106
kontai/python
/面向對象/運算符重載/右側加法和原處加法__radd__和__iadd__/__radd__類傳播避免嵌套.py
563
3.6875
4
# Copyright (c) 2019. # 類傳播避免嵌套.py # class Commuter: def __init__(self, val): self.val = val def __add__(self, other): if isinstance(other, Commuter): other = other.val return Commuter(self.val + other) def __radd__(self, other): return Commuter(other + self.val) de...
d82562454fd9b91643c324dfa9b743777299f206
ArijitMitra1999/Python-Codes
/Tutes24_WithBlocksToOpenFiles.py
183
3.75
4
"""with block in file open""" with open("Harry.txt") as f : print(f.read(4)) """ If we use with block then file will automatically closed after reading so no need to use close """
91e559b1c7f164d766f6832b20febbdc85a5ad31
vila74223/hi
/hi.py
105
3.609375
4
height = input('Please tell me your height:') weight = input('And your weight^ ^:') print(height, weight)
a0517e7c8c95c8920b36e52fcf968192eac87e79
chaitdwivedi/team-coding-challenge
/longest_consecutive_sequence/solution.py
4,957
3.5625
4
def solution(nums): '''Easy solution using sorting Complexity - Time: O(NlogN), Space O(1) Issue: Destroys input - doesn't maintain ordering ''' # easy way to remove duplicates nums = list(set(nums)) if not nums: return [] if len(nums) == 1: return [nums[0], nums...
18b4df62239e551c4647ebede3516866443521d2
hoangtuyenblogger/nhap-mon-khoa-hoc-du-lieu
/15092020_String_list_bai_tap.py
753
3.703125
4
''' #Bài 1 name = input("Nhap vao ho va ten: ") print("Ten cua ban la: " + name[0:]) print("In nguoc ten cua ban: " + name[::-1]) print("-----------------------------------------") #Bài 2 long = input("Nhập vào tên của Long :") tuyen = input("Nhập vào tên của Tuyến :") if len(long) < len(tuyen): print(tuyen +" là b...
e892944e2752455191389a866252d9eaa9fe8b54
Jainam2848/Usask-CMPT141-Assignments
/Assignment 2/a2q3.py
810
4
4
# NAME :- SHAH JAINAM DINESHKUMAR # NSID :- AYQ754 # STUDENT NUMBER :- 11321534 # INSTRUCTOR'S NAME :- Nisha Puthiyedth # COURSE :- CMPT 141 encoded_string = input("Enter the encoded string :") location = int(input("Enter the location of the number in the encoded string :")) string_before = encoded_string[0: location...
bca025ec489be75944eba993d13b99562cbb8a64
BrianHyuk/python
/day 2/python2_6.py
619
3.96875
4
import turtle turtle.shape("turtle") turtle.speed(1) #무식한 방법 turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(100) #조금 똑똑한 방법 for i in range(3): turtle.forward(100) turtle.right(90) turtle.forward(100) # 조금 더 똑똑한 방법 def drawRec(...
5468a32504d047a9ba1f0226b55c7f8302046d34
ashleykeeling2021/game-survey-
/market research.py
2,165
3.53125
4
import itertools from tkinter import * from matplotlib import pyplot import graphs answers = [] window = Tk(className='Market Research') window.geometry("400x750") def question(question): questionTitle = Label(text = question) questionTitle.pack() topic = StringVar() entr...
f83c27ad3939d84a524df40ffd0035cad720ea23
piotr-kalanski/programming-exercises
/exercises-python/basic_data_types/lists/solution.py
937
3.6875
4
def read_input(): n = int(input()) commands = [input() for _ in range(n)] return commands def solve(commands): current_list = [] result = [] commands_parsed = [c.split(' ') for c in commands] for command in commands_parsed: cmd = command[0] if cmd == "insert": ...
a9dab788ace3326a8d5c0ecd189f39e4c67847f0
xueharry/Chinese-Homonym-Script
/homonyms.py
624
3.703125
4
import pandas as pd import pinyin import sys NUM_CHARS = 3000 # If no arguments provided use all characters by default if len(sys.argv) == 1: pass elif len(sys.argv) == 2: NUM_CHARS = int(sys.argv[1]) df = pd.read_csv("chars.csv") df.columns = ["number", "character", "entry"] # Only consider the number of charac...
c17b68b5866b3e1e8b83c8504c0f8e3d2c7f9094
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-322-reading-progress.py
918
4.21875
4
""" Happy New Year! How many books do you aim to read this year? In this Bite you will complete ontrack_reading that takes the amount of books you want to read (books_goal), the amount of books read (books_read) and the day of the year (day_of_year, if None or not provided, it defaults to today, that is the offset in ...
90780298db10730c4c26e539cb11ca99eaa076bf
Acytoo/leetcode
/python3/1078occ.py
317
3.609375
4
from typing import List class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: words = text.split() res = [] for i in range(len(words)-2): if words[i] == first and words[i+1] == second: res.append(words[i+2]) return res
3884d06d851287b886ad576797e649cd14ae426b
sublingbling/coding-everyday
/10_26_2016_valid-parentheses/up.py
1,017
3.8125
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ # build parentheses dictionary D = {')':'(', '}':'{', ']':'['} stack = [] left, right= '({[', ')}]' # loop for c in s: # it's a parenth...
7dc531f436fa15ea57909b1c9a25ee08ba611332
KleinTong/Daily-Coding-Problem-Solution
/min_sum_level/main.py
973
3.640625
4
from binary_tree import BTree from node import Node def level_split(root): def helper(node, level): if not node: return if level not in level_dict: level_dict[level] = [node] else: level_dict[level].append(node) helper(node.left, level+1) ...
aaf37718720536db7b09ab2d72efeb95a5571c9d
kkudumu/Python
/Car.py
836
3.8125
4
class Car(object): def __init__(self, price, speed, fuel, mileage): self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage self.tax self.tax() self.display_all() def tax(self): if self.price >= 10000: self.tax = .15 else: sel...
3f1ac035c0c30960e1155c613014d69127d49e88
mosamy/Algorithms
/NthElement.py
405
3.859375
4
__author__ = 'mohamed' #nth element from the bottom def nthelementfrombottom (n, my_list): if len(my_list) > n: return my_list[len(my_list)-n] else: return -1 def main(): my_list = [7, 2, 6, 5, 1, 29, 6, 4, 19, 11] print(nthelementfrombottom(3, my_list)) # Standard boilerplate to c...
5028c84947b1907dbf9f47ce2cde6501ebf97fab
nowacki69/Python
/Udemy/Python3Bootcamp/Challenges/109_list_check.py
420
4.0625
4
# Write a funcion called list_check, which accepts a list and returns True if each value in the list is a list. # Otherwise the function should return Falseself. def list_check(aList): for item in aList: if not isinstance(item, list): return False return True print(list_check([[],[1],[2,3], (1,2)])) ...
cffee64660c8ab58d9dbadce5a51497cbab14730
wuhao2/Python_learning
/Python3的新特性/5-2dict变化.py
272
4.09375
4
# _*_ coding: utf-8 _*_ __author__ = 'wuhao' __date__ = '2017/9/16 15:53' d = {1: "dead", 2: "parrot"} print(d.items()) # 返回了可迭代对象字典 for values in d.items(): print(values) keys = list(d.keys()) print(keys) values = list(d.values()) print(values)
b48683b58fc764aa6a8d1e9cf66cc0f0575c189c
agampreet2209/PythonClasses
/daily_class/2021- 03-03/tuple_example.py
526
4.34375
4
stationary = ("pencil", "pen", "eraser", "sketchpen") print(stationary) print(len(stationary)) stationary = ("pencil",) print(type(stationary)) fruits = tuple(("orange", "mango", "guava")) print(fruits) cars = ("suv", "sedan", "hatchback", "crossover") print(cars[1]) print(cars[-1]) print(cars[1:3])#range of index...
0a88636ab90a55dc5600920088567225727a476a
prabhjot-dehal/RPG
/Prabhjots_library.py
2,608
3.546875
4
__author__ = 'prabh_000' def ui(*args, border_width=5, border_symbol="="): # this function gets what the user wants to prints and puts it into a list # then it send it to another function, it also gets the lenght of the biggiest word # and then prints that length of the symbol thyey want to pri...
56998c27c4587092877797f816702071c923b943
JuliethOmbita/CodingBat_Python
/Warmup-2/string_bits.py
381
4.1875
4
''' Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". string_bits('Hello') → 'Hlo' string_bits('Hi') → 'H' string_bits('Heeololeo') → 'Hello' ''' def string_bits(str): # I want to star ar 0 and go up by 2 # Initialization: 0 # Condition: Length of t...
f19d17e2cbc30857cf62cde24b5df5688554a567
newbieeashish/LeetCode_Algo
/3rd_30_questions/ReverseString2.py
622
4.21875
4
''' Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters ...
2be8557bc0d1aefed67af95d387bb5f7326609e8
noahhi/comp6040-ai
/lab4_jailors_and_prisoners.py
4,461
4.03125
4
''' Problem description: Three jailers are transporting three convicts on foot. They come to a river, which can only be crossed in a rowing boat. The boat is only large enough to contain two people, but it can be rowed by one. The simplest way for everyone to get across would be for any two of the party to cro...
ad9255986c7d9be894a5b5d53d8cf79cbae24130
luckydimdim/grokking
/two_heaps/next_interval/main.py
1,642
3.828125
4
from heapq import * class Interval: def __init__(self, start, end): self.start = start self.end = end def find_next_interval(intervals): ''' Given an array of intervals, find the next interval of each interval. In a list of intervals, for an interval ‘i’ its next interval ‘j’ will have the smallest...
31963330b8a4bd8a5e828b5838c2be2f6d6c28fb
LWinger/Python_Project
/Web Scraping Test.py
735
3.71875
4
# coding: utf-8 # In[1]: import urllib.request as ul #url.request lib for handling the url from bs4 import BeautifulSoup #bs for parsing the page url = "http://www.slate.com" #Do stuff necessary to get the page text into a string url_response=ul.urlopen(url,timeout=5) soup = BeautifulSoup(url_response) #Soup st...
c52a6bff652f71e644d66188e32d010ba56a48b8
Maksim-Dobrozhanov/osnovi_yasika_python
/task_1_lesson_1.py
545
4.28125
4
# Поработайте с переменными, создайте несколько, выведите на экран. # Запросите у пользователя некоторые числа и строки и сохраните в переменные, # затем выведите на экран. a = 5 b = 6 c = 7 print(a) print(b) print(c) a = int(input('Введите первое число ')) b = int(input('Введите второе число ')) c = (input('Введите...
c48faacc8357d0050e381e3d2ae79bd15cdf4f4c
gcherchye/Games
/flAApy_bird/pipe.py
2,018
3.75
4
"""Some pipes to kill the dumbest flap""" from __future__ import absolute_import import random import pygame from settings import Settings class Pipe: """The Mario's friends""" def __init__(self, x) -> None: self.settings = Settings() self.x_coord = x self.height = 0 self.p...
0e20fbb2a3c792a68adca21df62dcbe64946b223
alex-xia/leetcode-python
/lib/remove_duplicate_letters.py
4,560
3.671875
4
__author__ = 'Qing' ''' Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example: Given "bcabc" Return "abc" Given "cbacdcbc" Return "acdb" ...
c4e884027e5592679c8c53b242a2a3a1c2ed9d77
mjocc/cipher-crackers
/ciphertool/__main__.py
3,883
3.53125
4
import click from ciphertool.identifier import main as identifier import ciphertool.ciphers.vigenere_cipher as vigenere import ciphertool.ciphers.transposition_cipher as transposition ciphers = {"vigenere": vigenere, "transposition": transposition} def cipher_name_argument(function): function = click.argument( ...
4ec8edc5186b79f0e9fa92b96b62a72c8698561e
murali3036/myPython_Works
/sumofelelmentsList.py
222
3.84375
4
#Python program to find sum of elements in list def sumofelelments(a): sum = 0 for i in a: if type(i) == int: sum = sum + i print(sum) l = [10,30,20,'a',10] sumofelelments(l)
e1f60d5d6a0744651c9a53f1d003d288842a2b41
Ge0f3/PractisePython
/classPrac/main.py
285
3.6875
4
#! /usr/bin/python3 from sub import sub class main(object): """docstring for main""" def __init__(self): print("Constructor from the main class") def main1(): sub = sub() username=str(input("Enter your name : ")) sub.greet(username) if __name__ == '__main__': main1()
18f2423930182408a507638d1ef0ef9d625e2b6e
LennyBoyatzis/code-wars
/array-diff.py
159
3.59375
4
def array_diff(a, b): return [ y for y in a if y not in b ] if __name__ == "__main__": a = [1,2,3,4,4,4,4,5] b = [4,5] print(array_diff(a,b))
937cdb51b04feb4ef9275bfc6a77c46a0857f526
marvjaramillo/ulima-intro210-clases
/s021-selectivas/multiple.py
748
4.40625
4
''' Los resultados de el examen de Ingles en un Instituto manejan las siguientes descripciones en funcion a las calificaciones obtenidas: [0 - 30>: Nivel Basico [30 - 60>: Nivel Intermedio [60 - 100]: Nivel Avanzado Implemente un programa que lea la calificacion y muestre la descripcion ''' def main(): calificac...
c5bed2bfb3d8426b0aa9e9630644340e320e5b9c
tonyiovino/endurance
/endurance2.py
621
3.875
4
quantita_str = input("Inserite la quantità in galloni del carburante: ") quantita = float(quantita_str) consumo_orario_str = input("Inserite il consumo orario: ") consumo_orario = float(consumo_orario_str) if quantita <= 0: print("La quantità del carburante deve essere maggiore di 0.") elif consumo_orario <= 0: pri...
3043706920f4a821c9f486bfbd0b2d9ba26229dd
YogeshSingla/balia
/2_neural_networks/mlp_part3_with_images/river/river_mlp_classifier.py
3,059
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 12 10:32:49 2018 @author: kirito Assignment 5: Binary Classification of river and non-river using neural network: Take river64.png image as input and read the all pixel value of grayscale image. First convert the each pixel in two categori...
7f9f56112dba30b99c1d9ed6e43d01fdb2433fee
ksvtmb/python
/dz3.py/1.py
341
4.125
4
start=finish=step =0 print (start) start=input("начальная цифра: ") start=int(start) finish=input("конечная цифра: ") finish=int(finish) step=input("шаг счета: ") step=int(step) if not step or step==0: step=1 chislo=0 for i in range(start,finish,step): chislo+=i print("число: ", chislo)
3376613484e3d5280d5042e9f436025b280e68a2
abhi8893/Intensive-python
/exercises/combine_dict_values.py
1,583
3.796875
4
def combine_dict_values(dict_list): """ Return a dict with values added to existing keys d_list = [{'Money': .3, 'Strength': .25, 'Speed': .05}, {'Money': .3, 'Age': 25, 'Speed': .7}, {'Money': .3, 'Strength': .25, 'Power': 5}] >>> combine_dict_values(d_list) {'...
5d51a862a0f4830794306c2a7b1cd3556b427f6d
rivergillis/ctci
/4-trees-graphs/4_check_balanced.py
3,129
3.984375
4
# implement a function to check if a binary tree is balanced. For the purposes of this question, # a balanced tree is defined to be a tree such that the heights of the two subtrees of any # node never differ by more than one # Hints 21, 33, 49, 105, 124 from bst import Node from collections import defaultdict # O(n) ...
44988527412de61578458e42dcf947afd094a9a8
o87702623/270201011-
/lab7/example2.py
320
4.03125
4
def is_prime(n): if n > 1: for i in range(2,n): if n % i != 0 : return True def print_primes_between(x,y): for i in range(x,y): if is_prime(i): print(i) first = int(input("enter the first number:")) second = int(input("enter the second number:")) print_primes_between(first, second)
5d9ef4adc002fac2a8f1a1e884a6bb8da04ad65a
nsossamon/100daysofcode
/Day3/Exercise3-2_BMI2.0.py
834
4.53125
5
# Program that interprets BMI and interprets into a statement based on the value: # Under 18.5 they are underweight # Over 18.5 but below 25 they have a normal weight # Over 25 but below 30 they are slightly overweight # Over 30 but below 35 they are obese # Above 35 they are clinically obese. height = float(input("en...
048e9063d767dee6d48058e65226d024c9603119
VicnentX/MachineLearning_PorjectsAndNotes
/function_note_&_cs231n_note/test.py
267
3.59375
4
import math import numpy as np def dist(x, y): return np.linalg.norm(a - b) num = math.fabs(-6) print(num) print(type(num)) a = np.array([1, 2, 3]) b = np.array([2, 4, 6]) distance = dist(a, b) print(distance) print(distance ** 2) print(math.sqrt(1 + 4 + 9))
7744f2da0d93970ee6f822e9038d7481e001b0b9
themoah/exercism-python
/armstrong-numbers/armstrong_numbers.py
243
3.75
4
def is_armstrong(number): numberString = str(number) numberLength = len(numberString) numberList = list(numberString) sum = 0 for num in numberList: sum += int(num) ** numberLength return sum == number
bc3b99221393ddd95507483914e4c555af3f5166
MagdalenaSvilenova/Programming-Basics-Python
/Exams/Cat walking.py
363
3.921875
4
min_walking = int(input()) counter = int(input()) calories = int(input()) burned_calories = min_walking * 5 * counter if burned_calories >= calories / 2: print(f"Yes, the walk for your cat is enough. Burned calories per day: {burned_calories}.") else: print(f"No, the walk for your cat is not enough. Bu...
11fba19a72be0352ea299198d7fe7618105ffa8f
kefirzhang/algorithms
/leetcode/python/easy/p690_getImportance.py
978
3.765625
4
# Employee info class Employee: def __init__(self, id, importance, subordinates): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subordinates ...
96a546dd6211c959a04374d540abe4f4a7d832b5
marcus-gee/CS-1
/lab5/lab5_c_template.py
606
3.5
4
from tkinter import * import random # Graphics commands. <your code goes here> # Event handlers. def key_handler(event): '''Handle key presses.''' <your code goes here> def button_handler(event): '''Handle left mouse button click events.''' <your code goes here> if __name__ == '__main__': roo...
e75af7f93ef22d1e4d3ebc454e49eae9d55f39ab
AndreySperansky/ALGORITHMS
/Lesson_1/task_2.py
1,161
4.15625
4
""" Задание 2. Выполнить логические побитовые операции "И", "ИЛИ" и др. над числами 5 и 6. Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. Подсказка: это стандартные операции, которые осуществляются с помощью стандартных операторов. Попробуйте найти каких именно. """ BITNUM_1 = int('110', 2) BITNU...
95d68a9b49ed69c40ca7c79f96033abcfcb91706
Dragonfly774/all_life
/dz1810/dz/01.py
1,609
3.875
4
class Point: def __init__(self, name, x, y): self.name = name self.x = x self.y = y def __str__(self): return f'{self.name}({self.x}, {self.y})' def __repr__(self): return f"Point('{self.name}', {self.x}, {self.y})" def __invert__(self): return Point(se...
9f9150ce977b08fed005a19539ab2862699879c2
nickfuentes/Python-Practice
/python/car_dealer.py
605
4.125
4
cars = [] # creating the Car class class Car: # constructor or initializer def __init__(self, make, model, color): self.make = make # set property make to the arguement make self.model = model self.color = color # Passing self makes the the drive function availble to thte Car Objects...
7849119062d32d92e35a527a3dfc4d20cf7f72a1
Gustavokmp/URI
/1018.py
773
3.5625
4
valor = int(input()) cedulas_de_100 = int(valor/100) resto_de_100 = (valor % 100) cedulas_de_50 = int(resto_de_100 / 50) resto_de_50 = (resto_de_100 % 50) cedulas_de_20 = int(resto_de_50 / 20) resto_de_20 = (resto_de_50 % 20) cedulas_de_10 =int(resto_de_20 / 10) resto_de_10 = (resto_de_20 % 10) cedulas_de_5 = int(resto...
c28d19c34abd98a73d4411b095a8fb9fc85e0cba
jensecj/code-challenges
/advent-of-code-2019/04/main.py
2,010
3.734375
4
import sys import itertools from collections import Counter from ubench import * def generate_passwords(x, y): """ Generate all number-only passwords of length 6, with subsequent numbers never decreasing """ for a in range(int(x[0]), 10): for b in range(a, 10): for c in range(...
aa83485ee56f0659b589e4eacca1b817501f839f
Shruti1229/LeetCode
/populating-next-right-pointers-in-each-node-ii.py
979
3.78125
4
""" # Definition for a Node. class Node(object): def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next """ from collections import defaultdict class Solution(object): def connect(self, root): """ :type root...
6f3840c8672b798c6bc06cac0ad76e98568383a2
gabreuvcr/curso-em-video
/mundo1/ex022.py
642
4.125
4
## EX022 ## nome = str(input('Digite seu nome completo: ')).strip() #eliminando espaços separado = nome.split() #separando palavras para lista nospace = ''.join(separado) #juntando a lista sem espaço #nospace = nome.replace(' ', '') tambem tira espaço print('Maiusculo: {}'.format(nome.upper())) print('Minusculo: {}'....
68782955025d62acc1f050ae119acb43bc647fba
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/tmxtha006/question2.py
2,727
4.0625
4
#You Droppe food on the floor #Student Name: TEMA, Thabo Hebert #Student Number: TMXTHA006 #Date: 11 March 2014 print("Welcome to the 30 Second Rule Expert") print("------------------------------------") print("Answer the following questions by selecting from among the options.") ansM = input("Did anyone see...
51fbb503957cdc0f161bef2c111d3a3c77a27810
tangwz/leetcode
/leetcode/python/median-of-two-sorted-arrays.py
2,020
3.953125
4
# -*- coding: utf-8 -*- class Solution(object): """ The easiest way is merging the two lists and find the median number. But this way need time complexity O(m+n). We need the overall run time complexity should be O(log(m+n)). So we must search efficiently such as using binary search. "...
eeb1db68b5de4be2b9cd7162b91ffcf2310f6fa2
smercado1237/rock-paper-scissors
/sm_rps.py
1,422
4.0625
4
from random import choice compscore = 0 userscore = 0 print "Hi, I'm Sydney the computer. Let's play a game of rock-paper-scissors!" def sydney(move, compscore, userscore): x = choice("rps") if move == "r" and x == "r": print "I play rock." print "We tied!" return compscore, userscore elif move == "r" and x ...
56ecf879a8bdb3e092e67420ac5cec03838aa527
papasmf1/python1018
/DemoRE.py
564
3.515625
4
# DemoRE.py import re #특정한 규칙이 있는 패턴 검색 #함정을 추가 result = re.search("[0-9]*th", " 39th") print( result ) print( result.group() ) #다중 라인 주석: ctrl + / # result = re.match("[0-9]*th", " 39th") # print( result ) # print( result.group() ) print( bool(re.search("apple", "this is apple")) ) print( bool(re.match("apple...
86ae607f8e6a28592f90e7707840b243ba460072
ThallesTorres/Curso_Em_Video_Python
/Curso_Em_Video_Python/ex079.py
1,092
4.1875
4
# Ex: 079 - Crie um programa onde o usuário possa digitar vários valores numéricos # e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será # adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem # crescente. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja be...
2a0e08100599f0a22392823f20bb60966714623d
shedrinav88/python-homeworks
/less05_4.py
997
3.8125
4
""" Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. ""...
97454b9adf37bf55c4a7eda715dfacf294cad155
20050924/All-projects
/Assignment 10 Self defined split.py
502
3.796875
4
#Michael Li #Computers 10 #2021/6/10 #Take in a input then output a list of the words form the input. def splitfunction(user_response): user_response = user_response.strip("., ") split = [] a = "" for j in range(len(user_response)): if user_response[j] !=" ": a += user_response[j] ...
80dfaf534a32ecc86d75e62fbd9e3a40717e5c82
the-last-crusaderr/Python-150-Challenges
/076.py
284
4.125
4
x = [] print("Who are the 3 people,do you want to invite in the party?: ") for i in range(3): x.append(input()) more = input("Do you want more?") more = more.lower() while more != "no": x.append(input("What's the name? ")) more = input("Do you want more? ") print(x)
3dfa3b931b21d8f326154d6af9abdea875762150
kolevatov/python_lessons
/week_1/task_1_5.py
229
3.671875
4
# Степень двойки # Формат ввода # Вводится целое неотрицательное число N. N≤100. # Формат вывода # Выведите 2ᴺ. N = int(input()) print(2**N)
8329cdea15ce5640c1a34863e8128653886ac5e2
safados/Rock-Paper-Scissors-GAME
/starter_code.py
3,603
3.78125
4
# Refrences https://www.youtube.com/watch?v=Q5cewb4_epM # Refrences https://www.geeksforgeeks.org/class-method-vs-static-method-python/ # Refrences https://github.com/eduardoportilho/rock-paper-scissor # Refrences https://www.youtube.com/watch?v=9Kdn9uIYhKw import random m = ['r', 'p', 's'] class Player: def __i...
48bd787d97f4075ae02acda2260939952412f1b7
chunamanh/PY4E-PythonForEveryOne
/python_codes/Course-3/Week-5/Extracting_Data_from_XML.py
782
3.5625
4
import requests import xml.etree.ElementTree as ET ''' Structure of the XML tree, in this Excercise: <comments> <comment> <name>Cillin</name> <count>93</count> </comment> .... </comments> So, to get the number, we need to get to comments/comment first (line 23), ...
701abde41646c56857a397f43790353ccf7bf391
DrM00G/machine-learning
/analysis/8_queens.py
2,950
3.75
4
import random def show_board(locations): empty_board=[["." for x in range(8)] for x in range(8)] count=0 for coord in locations: empty_board[coord[0]][coord[1]]=str(count) count=count+1 row_array = ['0', '.', '.', '.', '.', '.', '.', '.'] for row_array in empty_board: row_string = ' '.join(row_ar...
86f2376fd2c78f566cc326edcdd7c2c35b83f2c9
rueckstiess/mtools
/mtools/util/grouping.py
5,060
3.65625
4
#!/usr/bin/env python3 """Utility for grouping items and working with grouped items.""" import re from mtools.util import OrderedDict class Grouping(object): """Grouping object and related functions.""" def __init__(self, iterable=None, group_by=None): """Init object.""" self.groups = {} ...
11934630e0ad6fd71661983d666e2950ebe98211
martinbudinsky3/BP-tumor-classifier
/hrdtools/lengths_data_processor.py
555
3.6875
4
import pandas as pd def process_lengths_data(lengths): """ Function for preprocessing of chromosomes lengths data Parameters ---------- lenths : pandas.DataFrame DataFrame with unprocessed lengths data Returns ------- lengths: pandas.DataFrame DataFrame wi...
9a6c124e8417bee82f451c5749abd27ee44e9078
Brece/CS50
/Brece-cs50-2018-x-sentimental-vigenere/vigenere.py
953
4.3125
4
import sys import cs50 # check for proper usage and key argument value if len(sys.argv) != 2: print("Usage: python <program> <key>") sys.exit(1) key = str(sys.argv[1]) if key.isalpha() == False: print("<key> argument must consist on letters only") sys.exit(1) # get user input print("plaintext: ", ...
79310aed9f151e77975e4da8b2649fc5102304a7
jenny-chou/tensorflow_practices
/dnn_vanilla.py
3,268
3.609375
4
import tensorflow as tf import tensorflow.keras as keras import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing.image import ImageDataGenerator...
2ac7e013a742e1e50635f75f8db9ca93d3e70e08
peterjunlin/PythonTest
/practices/process_multiprocessing.py
601
3.5
4
from multiprocessing import Pool import os import time def process_info(): # Number of CPU print("\n\nProcess info:") print("Number of CPU: {0}".format(os.cpu_count())) print("Process ID: {0}".format(os.getpid())) print("Parent process ID: {0}".format(os.getppid())) def f(x): p...
d819755cdff4abf65c1677af5af0d66fe2f9eb03
daredevil786/devil
/gamestonepaperandscissors.py
725
3.953125
4
import random r=["stone","paper","scissors"] #range computer=r[random.randint(0,2)] player=input("enter the choice"); if player==computer: print("draw") elif player=="paper": #condition for paper outcome if computer=="scissors": print("lose","computer has",computer) else: print("wo...
0930cbb8ed9e3fec3df547a6e606f3a65c1a25c0
RachelEW/module2
/ch11_while_loop/ch11_biased_dice_roll_game_rachel.py
3,100
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 18 13:36:16 2018 @author: winkl """ from random import randint ################################ """Biased Dice Guessing Game""" ################################ def playGame(): print("""Welcome to The Dice Game. I will roll two dice and add the numbers together. Yo...
6782fe8fa7f6b48c0177cd17538798218d97ba10
KuanZhasulan/Python-Games
/user43_pSeA0N4kRrYMcGq.py
1,906
4.28125
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math low = 0 high = 100 secret_number = 0 number_of_guesses = 7 # helper function to start and restart the game def n...
6604432cf393c8d40157a63899ff5b4b5fc5d9e4
ictcubeMENA/Training_one
/codewars/7kyu/speed control/bench.py
950
3.515625
4
import timeit def benchmarkarraydiff(): setup_code =''' import main''' test_code = ''' x = [0.0, 0.23, 0.46, 0.69, 0.92, 1.15, 1.38, 1.61] s = 20 main.gps(s, x) ''' times = timeit.repeat(setup = setup_code,stmt = test_code, repeat = 3, number = 1000...
e7f6044ce1bb7520540212f97252a5bb9a1f5617
Ppasha9/check_triangulation
/main.py
5,723
4.03125
4
""" Main file of program. Lab for checking the triangulation of polygon. Usage: main.py (--input PATH) main.py (--help) Options: -i --input PATH Path to the file, containing input arguments -h --help Show this message """ import os import docopt from typing import Tuple, List class P...
00070f1c65a359c904bdd604f08dabb6a544e3b5
Jaelyn-Lim/leetcode
/2018-10/872.py
771
3.890625
4
# -*- coding: utf-8 -*- # @Time : 2018/10/6 19:39 # @Author : jaelyn # @FileName: 872.py # @Software: PyCharm # 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 leafSimilar(...
4dd333684793d14eec9c804fafcccc19f06ab5ad
cal1log/python
/sets.py
286
3.921875
4
#!/usr/bin/env python3 '''creating a set that is a type of unique elements''' s = {100, 200, 300, 400} '''set type does not have indexes''' try: print(s[2]) except: print("set type does not have indexes to get values. Used for Venn Math\ like union, intersection, etc")
9fb61a2ecd33672587a2080ab4e6bc7b6954d85c
alexeyZay/Python
/Function/Functions.py
1,882
3.84375
4
# def print_greeting(): # ''' # # :return:NONE # ''' # print('Hello') # print_greeting() # with param # def print_greeting_with_param(user_name='Jack'): # Jack is default value # ''' # # :param name:user_name # :return: None # ''' # print('Hello ' + user_name + ' !') # # print_gree...
70abea7520d2ad6774840b820ca9dcf742d5ef49
kttaroha/AtCoder
/src/ABC1xx/ABC16x/ABC161/ABC161D.py
827
3.515625
4
from collections import deque def main(): k = int(input()) if k <= 9: print(k) else: queue = deque() for i in range(1, 10): queue.append(i) flag = 1 cnt_lunlun = 9 while flag: first_element = queue.popleft() lunlun_nums = ...
db09fcbcf4d0ad9bf305343179261a481319e4e9
Fatoumata964/Proba
/loiuniform.py
523
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 29 11:27:07 2020 @author: Fatou Badji """ from random import random def uniforme(a,b): return(a+(b-a)*random()) import numpy as np import matplotlib.pyplot as plt def densuni(x): #densité pour a=-1 et b=2 if (-1<=x and x<=2): return(1/3) ...
0dd1c68525af3d197244066c8aa8b4f4b7a0757d
KrushnaDike/My-Python-Practice
/TutorialsPy/tute12.py
1,768
4.34375
4
s = set() # print(type(s)) #We can declare the set by using following two methods refer (s1, s2) s1 = {10, 92, 20, 59, 30, 40, 89} l = [10,20, 25, 30, 63, 40, 93] s2 = set(l) # print("s1 contains :",s1) # print("s2 contains :",s2) # print("type of s1 :",type(s1)) # print("type of s2 :",type(s2)) """ Don...
b6705b7109e4c56b42167aa355b833ac58487c7e
eduhmc/CS61A
/Teoria/Class Code/19_factors.py
700
3.921875
4
from math import sqrt def count(f): def counted(*args): counted.call_count += 1 return f(*args) counted.call_count = 0 return counted def divides(k, n): """Return whether k evenly divides n.""" return n % k == 0 def factors(n): """Count positive integers that evenly divide n."...
105494466d1de0dc4e00d96b3a9cad9b7df426a9
dikshaa1702/ml
/day1/ridecost_cal.py
198
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue May 7 12:04:45 2019 @author: DiPu """ distance=float(80) cost_per_litre=float(80) cost=(1/18.0)*distance*cost_per_litre print("cost for a day is:",cost)
7c40b89a5f63092cdad138d230fb45d63c3148cf
m4nux/pypolygones
/dadprogram.py
4,040
3.5625
4
#Périmètre-Surface et CDG d'un polygone #****** fonctionnel le 21-11-2020 ***** # Ce programme permet de calculer la surface,le périmetre et le centre # de gravité d'un polygone quelconque (considéré comme une somme de triangles # adjacents quelconques). # Le point de depart est en 0,0 et les deplacements se font ave...
c70e7d9da617793e9cec2f4adea63e5b81844068
Mahdi-Hosseinali/CtCI-6th-Edition-Python
/Chapter1/4_Palindrome Permutation/PalindromePermutation.py
849
3.796875
4
# O(N) import unittest from collections import Counter def pal_perm(phrase): '''function checks if a string is a permutation of a palindrome or not''' counter = Counter(phrase.replace(' ', '').lower()) return sum(val%2 for val in counter.values()) <= 1 class Test(unittest.TestCase): '''Test Cases''' ...
9e7d64fbc8fd69a5d56e3f65a057a2a3ce08da27
revanth465/Algorithms
/Searching Algorithms.py
1,403
4.21875
4
# Linear Search | Time Complexity : O(n) import random def linearSearch(numbers, find): for i in numbers: if(i==find): return "Found" return "Not Found" numbers = [1,3,5,23,5,23,34,5,63] find = 23 print(linearSearch(numbers,find)) # Insertion Sort | Time Complex...
34165ff9a757d35b72ad843ad4dfaffe76d95c8e
BOYGABAS/CSC124
/sort2.py
6,642
4.46875
4
''' Isaiah Andre Pabillon BSCS-2 2018-5769 Algorithm: 1) Create an empty list to be filled with random elements 2) Set a random range from 0 to 25 and add it to the ASCII equivalent of "A" to produce random letters from "A" to "Z" and append it to the empty list 3) Repeat step #2 at yo...
41a6b81e3c669c30b2ec9823ff6b528c56ba9cde
ramirovazq/algorithmexamples
/example_algorithms/abbreviation.py
3,902
3.875
4
def sum_recursive(current_number, accumulated_sum): print("current_number {}, accumulated_sum {}".format(current_number, accumulated_sum)) if current_number == 5: return accumulated_sum else: return sum_recursive(current_number + 1, accumulated_sum + current_number) def second_abbreviation(...
91526486f3f1b78df6c885b83c2d72e09c8770a7
rengeten/lesson1
/homework/mike_finder.py
151
3.921875
4
names = ['Jake', 'Bill', 'Mike', 'Jade'] while names: x = names.pop() if x == 'Mike': print('Here is the Mike!') break input()
7beb9578f1fafc98a7eed4e34b4294e0f7252244
Rodin2333/Algorithm
/剑指offer/33丑数.py
918
3.765625
4
#!/usr/bin/env python # encoding: utf-8 """ 把只包含质因子2、3和5的数称作丑数(Ugly Number)。 例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。 """ class Solution: def GetUglyNumber_Solution(self, index): """ :param index: 第index个 :return: """ if index < 7: return ind...
eb69f18bad3649600c2eadd98cda10425a2104f7
alyssonalvaran/kaizend
/session-5/medium/1.py
584
3.625
4
from time import sleep from functools import wraps def delay(seconds): output = None print(f"Sleeping for {seconds} second(s)") sleep(seconds) def inner_function(function): @wraps(function) def wrapper(*args, **kwargs): print("[START]") output = function(*ar...