blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1afb2e4b5772a71ace603b6908b47876eb109cb5
Matthew-P-Lee/Python
/verticalc.py
1,139
4.28125
4
import math #speed, distance, time calculations class Verticalc(object): grade = 0.0 distance = 0.0 speed = 0.0 time = 0.0 def __init__(self, grade,distance,speed,time): self.grade = grade self.distance = distance self.speed = speed self.time = time def getVerticalFeet(self): vert = ((float(grade...
a19a25dc98ba53d6f72fedd6141191e48dd56706
exploring-curiosity/DesignAndAnalysisOfAlgorithms
/Assignment2/q1_1power_Rec.py
206
4.21875
4
def power(a,n): if n==1: return a else: return a*power(a,n-1) a=int(input("Enter the value of x : ")) n=int(input("Enter the value of power : ")) print("The result is ",power(a,n))
d3017f73eed8174a200c80027fe20babbf55aa62
Mjcanson/TCP-UDP-Centralized-Client-Server-Network
/client/client.py
4,121
3.75
4
######################################################################################################################## # Class: Computer Networks # Date: 02/03/2020 # Lab3: TCP Client Socket # Goal: Learning Networking in Python with TCP sockets # Student Name: Michael Canson # Student ID:920601003 # Student Github U...
e6db1f936b5e8d5619e72298476718505fcba09b
gtalarico/ironpython-stubs
/release/stubs.min/Rhino/Geometry/__init___parts/Arc.py
9,956
3.625
4
class Arc(object,IEquatable[Arc],IEpsilonComparable[Arc]): """ Represents the value of a plane,two angles and a radius in a subcurve of a three-dimensional circle. The curve is parameterized by an angle expressed in radians. For an IsValid arc the total subtended angle AngleRadians()=Do...
e96ee14920798627d606a7389129a65ba31ce7d1
advaith-unnikrishnan/Getting-started-with-Python
/Basic Programs/palindrome.py
346
4.125
4
""" Program: To find whether a number is palindrome or not. Eg: 121 is a plaindrome number Author: Advaith n-stores the number r-stores the reverse of the number """ n=int(input("Enter the number ")) i,r=n,0 while(i>0): r=r*10+i%10 i=i//10 if n==r: print(n," is a palindrome number") else: print(n," is ...
0a1f9f7a18d4c22d47830b5a85ba70f7cfcbe722
WinterMute1000/Algorithm_Practice
/target_index.py
710
3.6875
4
class TargetIndex: def inputData(self): self.num_list=list(map(int,input("Input:").split())) self.target=int(input("Target:")) def searchIndex(self): result=False for i in range(len(self.num_list)): temp=self.target-self.num_list[i] if temp in self...
a3c4ab4e4028eaf087d3aa94cec53b88e1503000
mass234/broPython12hoursTutorials
/Ball.py
688
3.625
4
class Ball: def __init__(self,canvas,x,y,diameter,xVelocity,yVelocity,color): self.canvas = canvas self.image = canvas.create_oval(x,y,diameter,diameter,fill=color) self.xVelocity = xVelocity self.yVelocity = yVelocity def move(self): coordinates = self.canvas.coor...
536bf3674c4f4b44a3ad264b93963d7d3ae19a37
GUTINGLIAO/sonne
/file/rename_file.py
1,025
3.765625
4
from pathlib import Path def rename(root: str, base_name: str, skip_dir: bool = True): """重命名目录下的所有文件 根据base_name重命名文件,按照次序修改名字,保留文件后缀,所有文件均放置在同一级目录下 :param skip_dir: 重命名是否跳过目录 :param root: 根目录 :param base_name: 基础名称 """ root_file = Path(root) for i, file in enumerate(root_file.rglob(...
d9bc03fc5a2157268cecbae2f25dd694431c604a
Gabrielatb/Interview-Prep
/elements_of_programming/Array/delete_dup_sorted_array.py
424
3.625
4
#deleting repeated elements from a sorted array #input [2,3,5,5,7,11,11,13] #output [2,3,5,7,11,13] #Time: O(n) #Space: O(1) def delete_dup(lst): if lst == []: return 0 write_indx = 1 for i in range(1, len(lst)): if lst[write_indx-1] != lst[i]: lst[write_indx] = lst[i] ...
c2c41dbf8728fe5c3e4fd44f46620938ef8b9398
amandameganchan/advent-of-code-2020
/day23/day23code.py
1,791
3.609375
4
#!/bin/env python3 import sys import re from collections import defaultdict def solution(filename): data = [] with open(filename) as f: for x in f: data.extend(list(x.strip())) data = list(map(int, data)) return collectLabels(playGame(data)) def collectLabels(final_cups): # start at 1 and collect cups cloc...
68d22f4f4bf0b43997a8afb78d3039249c0a9b97
lportinari/DarkSoulsInShell
/DSS.py
19,183
3.53125
4
from time import sleep import random import math class Class: def __init__(self, name='', phyAttack=0,max_phy_attack=0, magAttack=0, max_mag_attack=0, phyDef=0, magDef=0, criticalChance=0, hp=0, mp=0, souls=0, level=0, weapom='', shield='', estus_flask=2, class_name=''): self.phyAttack = ...
2e728336dc03b6a5650a39424869caad3e2a4d31
kamekame/alpha
/module/lxml_.py
2,414
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Often used function for extracting data from a XML-file. This file is not ready yet. """ # from lxml import etree import xml.etree.ElementTree as ET def parse_xml(topic): xmlpath = '' if topic == 'contacts': xmlpath = "/home/kame/Dropbox/data/contac...
177cce3a76c3a46b87ec9beb33f4b52728212de7
rockdonald2/leetcode
/iteratorBST/index.py
1,071
3.8125
4
from typing import List class TreeNode: def __init__(self, val: int=0, left=None, right=None): self.val = val self.left = left self.right = right class BSTIterator: def __init__(self, root: TreeNode): self._st = [] self._index = 0 self._traverse(root) def _...
21833eed52139390e9de371bf7e41ae2bd326efb
laraflynn/tipcalculator
/main.py
1,935
3.90625
4
# Author: Lara Flynn # Created: June 19 2020 # Last Updated: June 22 2020 import tkinter from tkinter import Entry, Frame, Button, Label, StringVar, END # get the numbers from input def retrieveEntry(): bill = 0 percent = 0 try: bill = float(my_entry1.get()) except ValueError: re...
fe32b21f23ea1cda37ee656592f42970b083604c
ParulProgrammingHub/assignment-1-devang2011
/9.py
396
3.71875
4
s1=float(input( " Enter Marks of subject 1 ")) s2=float(input( " Enter Marks of subject 2 ")) s3=float(input( " Enter Marks of subject 3 ")) s4=float(input( " Enter Marks of subject 4 ")) s5=float(input( " Enter Marks of subject 5 ")) tot=(s1+s2+s3+s4+s5) mean=(tot)/5 print ( " mean ",mean) per=(tot*100)/500 print ( ...
f6c898d25cab7bd1ccba0f048829b68c56d14532
musale/advent-of-code-2018
/day_2/part_2.py
855
3.828125
4
"""Get the common letters between two correct IDs.""" def main(): """Check for the common letters and remove them.""" with open("day_2/input.txt") as file: file_input = file.readlines() for i, word in enumerate(iter(file_input)): for next_word in iter(file_input[i+1:]): ...
916eaebe04a76c2646bf42dde6d2eea444c18901
smcnearney/python2
/dictionaries3.py
358
4.34375
4
meal = { "drink": "beer", "appetizer": "chips", "entree": "tacos", "dessert": "churros" } print(meal) #Change drink to green tea and get rid of dessert #When you pass a dictionary a NEW key, it creates the key #When you pass a dictionary a key it already has, it REPLACES the key meal["drink"] = "green...
36419e717c2f90ffd40bd02b551d1470c740e55a
codeGoogler/MyPythonPrintF
/test3.py
381
3.625
4
# 读取生成的input.txt内容 if __name__ == '__main__': f1 = open('input.txt') # 读取的数据类型为str number1 = int(f1.read()) # 执行你要执行的程序(例子为计算平方) number2 = number1 * number1 # 把运行的结果写入result.txt中 f2 = open('result.txt', 'w') f2.write((str(number2))) f1.close() f2.close()
06c441e79832a80519c9101113fac1e0decad80a
fainaszar/pythonPrograms
/maxim.py
377
3.5
4
input_params = raw_input().split() lists=[] for i in range(int(input_params[0])): list = raw_input().split() list = map(int ,list) lists.append(list) sum = 0 from itertools import product product(*lists) print product print "Sum is %r" % sum for list in lists: maxItem = max(list) square = maxItem **2 ...
a4ba0daddb3d42c24d3034a41ad3740f0527220e
zake7749/TensorFlow-Study-Notes
/1. MNIST/MNIST_CNN.py
3,815
3.671875
4
'''' Use a CNN to solve MNIST. ''' import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Hpyer parameter TRAINING_EPOCH = 5 BATCH_SIZE = 128 LEARNING_RATE = 1e-2 CLASS = 10 KEEPRATIO = .75 class CNN(object): def __init__(self, session): self.features =...
8e3378c32800b0e88358bc1ebb1036ce44c39643
DiyanKalaydzhiev23/OOP---Python
/Encapsulation - Exercise/Pizza/pizza.py
1,533
4
4
class Pizza: def __init__(self, name, dough, toppings_capacity): self.name = name self.dough = dough self.toppings_capacity = toppings_capacity self.toppings = {} @property def name(self): return self.__name @name.setter def name(self, value): if no...
400b8f09bc0bc97e9e779641126672723d9265a2
Ashok-Mishra/python-samples
/python exercises/dek_program083.py
405
3.96875
4
#!/usr/bin/python # -*- coding: utf-8 -*- #- Author : (DEK) Devendra Kavthekar # program083: # Please write a program to print the running time of execution of "1+1" # for 100 times. # Hints: # Use timeit() function to measure the running time. from timeit import Timer def main(): time = Timer("...
e9100ef719d45a22962437858e414764073b8127
sivaprasadkonduru/Python-Programs
/Dreamwin5/nestedfor.py
200
3.6875
4
a = [3, 4, 5] b = [7, 8, 9] #c = [(3, 7), (4, 8), 5, 9] c = [] for i in enumerate(a): #(0, 3) for j in enumerate(b): #(0, 7) if i[0] == j[0]: c.append((i[1], j[1])) print(c)
83e014847357a65a186184432bdccdaa74f150ff
PushkarIshware/pythoncodes
/bridgelabz_pythonproj/functional/stockqueue.py
1,083
3.765625
4
''' /********************************************************************************** * Purpose: stock management queue * * @author : Janhavi Mhatre * @python version 3.7 * @platform : PyCharm * @since 8-1-2019 * ***********************************************************************************/ ''' from utilities ...
37b1c34af974874f5732707966129b731ed0eb29
hanjasn/ctci
/recursion_and_dynamic_programming/towers_of_hanoi/stack.py
823
3.625
4
from typing import TypeVar T = TypeVar('T') class Stack: def __init__(self) -> None: self.top = None self.size = 0 def push(self, data: T) -> None: node = StackNode(data) node.next = self.top self.top = node self.size += 1 def pop(self) -> T: ...
632d47d846347fa3c78bbcee501ffd30008f683b
iman1000000/pygcurses60
/demo_maze.py
6,824
3.828125
4
# Pygcurse Maze # By Al Sweigart al@inventwithpython.com # Maze Generation code by Joe Wingbermuehle # This program is a demo for the Pygcurse module. # Simplified BSD License, Copyright 2011 Al Sweigart import pygcurse, pygame, sys, random, time from pygame.locals import * BLUE = (0, 0, 128) YELLOW = (255, 255, 0) ...
30f8d17fab25c7622e3581b53eb86c1689f78cf9
MokahalA/ITI1120
/Lab 11 Work/Lab11Ex2.py
346
3.96875
4
def count_digits(n): """(int) -> int Return the number of digits in the integer n. Precondition: n >= 0 """ if n // 10 == 0: return 1 return 1 + count_digits(n//10) #test print(count_digits(0)) #1 print(count_digits(7)) #1 print(count_digits(73)) #2 print(cou...
aa73390273cea301ec3b5049bfc59b073cea61d3
Gurpreet-Moudgill/Python-Lab
/strings.py
170
4.03125
4
v = "My name is" w = " Gurpreet Moudgill" print(v) print(w) # concatenation vw = v+w print(vw) # string slicing print(v[3:9]) print(v[2:7]) # extended slicing print(v[2: 9: 2])
9f4b2149b3df9008be66423ee1a5506c9ec8b030
claw0ed/Python3Lab
/List.py
8,167
3.671875
4
# 파이썬 자료구조 # 리스트 : sequence 자료구조를 사용 # sequence : 순서가 있는 데이터 구조를 의미 # 리스트, 튜불, 레인지, 문장열등이 sequence 구조 사용 # 리스트 [] 을 이용해서 각 요소에 접근할 수 있다 msg = 'Hello, World!!' # 파이썬에서는 자료구조를 의미하는 접미사를 # 변수명에 사용하기도 한다 list1_list = [] # 빈 리스트 list2_list= [1,2,3,4,5] # 숫자 list3_list = ['a','b','c'] ...
c367877e183cedf3c2a2b17d6a4ccea036984742
ansarhub/python
/gcd1.py
141
3.84375
4
a=int(input("enter a number")) b=int(input("enter a number")) i=1 while(i<=a and i<=b): if(a%i==0 and b%i==0): gcd=i i=i+1 print(gcd)
e7db5c284c6061f542c0d4dcb0a911c48697759c
jcarball/python-programs
/funciones.py
502
3.59375
4
def mensaje(numero): print("Ingresa un número:", numero) mensaje(1) print() def mensaje(numero): print("Ingresa un número:", numero) numero = 1234 mensaje(1) print(numero) print() def presentar(primerNombre, segundoNombre): print("Hola, mi nombre es", primerNombre, segundoNombre) presentar("Luke", "Skyw...
e0abca4cdbb58398cb4b2b870f4d821adf137133
punch2177-cmis/punch2177-cmis-cs2
/cs2quiz3.py
2,133
4.53125
5
#Section 1: Terminology # 1) What is a recursive function? #A recursive function is a funcation that calls itself within the function # # 1 pt # 2) What happens if there is no base case defined in a recursive function? #The recursive function will keep calling itself and there will be an error. # # # 3) What is the fir...
908d6e6463824640d88a1cba1e0c920feb987151
pavan-2001/Python-Basics
/Classes/Basic_classes/Modifying object properties.py
472
4.125
4
class person: def __init__(self,first_name='Default_first_name',second_name='Default_second_name'): self.first_name=first_name self.second_name=second_name def hello(self): print(f'Hey user this is a member function that says HELLO to the person') print(f'Hello !! ',self.fir...
a641c07ad1068c74c171439b18ef9141f18bd820
minzhou1003/intro-to-programming-using-python
/practice5/11_11.py
610
3.78125
4
# minzhou@bu.edu def decimal2binary(number): binary_seq = [] while number: binary_seq.append(number % 2) number = number // 2 while len(binary_seq) < 9: binary_seq.append(0) return binary_seq[::-1] def print_res(binary_seq): for i in range(9): if binary_seq[i] ...
3923ba595510ae791fad648eaf36ad307088a344
LucaCappelletti94/dictances
/dictances/chebyshev.py
870
3.640625
4
"""Determine the Chebyshev distance beetween the given dictionaries.""" from typing import Dict def chebyshev(a: Dict, b: Dict) -> float: """Determine the Chebyshev distance beetween the given dictionaries. Parameters ---------------------------- a: Dict, First dictionary to consider. b: ...
36c940c3e8ade41a5c18d8e8daacd59f5efdd239
ColinBeeby-Developer/LondonUsers
/integration_tests/test_londonersapi.py
1,842
3.5625
4
''' Module contains integration tests for londoners API ''' import unittest import requests class TestLondonersApi(unittest.TestCase): def testUsersLondon_cityLeeds(self): ''' Test to ensure that 404 is returned when an unknown city is passed in ''' (text, statusCode) = self._per...
5505d40dd55bb9feb8359d959658d1f2108593a3
Skp80/mle-tech-interviews
/data-structure-challenges/leetcode/268. Missing Number.py
1,893
4.0625
4
""" Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 sin...
8e91a7f48f4542e8f9b5290f2a50d4c805d6744a
eharris99/class
/ascii2.py
171
3.796875
4
#Name: Elise Harris #Date: January 31, 2019 #This program prints ascii mess=input('Enter a phrase: ') print("In ASCII: ") for j in range(0,len(mess)): print(ord(mess[j]))
766aade3a15cc9b6458c88ed849b8e74c979d79a
koketsomotse/Snake-Game-Python-
/snakegame.py
4,378
3.828125
4
#imporintg modules import turtle import time import random import os delay = 0.1 #score score = 0 high_score = 0 #set up the game screen wn=turtle.Screen() wn.title("Snake Game in Python") wn.setup(width=600, height=600) #remives the animation wn.tracer(0) wn.bgcolor("green") #Creating a Sna...
94f87e3709da20a54ad12126536d8a2b5032e4e0
OphelieAbb/Projets_Python
/Annee_bissextile.py
548
3.921875
4
annee = input("Saisissez une année :") try: annee = int(annee) # Conversion de l'année if annee<=0: raise ValueError("l'année saisie est négative ou nulle") except ValueError: print("La valeur saisie est invalide (l'année est peut-être négative).") if annee % 4 == 0: bissextile = True elif anne...
237825c21138bb6d50e033de78d08aaf907dfe3d
Sirpy-Palaniswamy/HackerRank-Solutions
/Iterable-and-Iterators.py
489
3.546875
4
#Problem """ You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list. Find the probability that at least one of the K indices selected will contain the letter: 'a'. """ #Code from itertools import combi...
f22d0886ef0b20f13ce8427575efb721b37ad485
minminmail/PrepareData
/MaxMin.py
2,347
3.53125
4
# -*- coding: utf-8 -*- class MaxMin: # dataFile = open(r"C:\phd_algorithms\datasets_2021\A1\tra.dat","r") f1_max = -1 f1_min = 100 f2_max = -1 f2_min = 100 class_green_number = 0 class_red_number = 0 def __init__(self,dataFile): self.dataFile = da...
f1cbc11872774d0465a6f2b0a0c213fb09e3ae35
stuntgoat/search
/util/__init__.py
420
3.8125
4
""" Utility functions for search problems and solutions. """ def path_from_start(current_node, parent_map): """ Return a list of nodes in order from the starting node to the current node. """ path = [current_node] while True: current_node = parent_map.get(current_node) if not cu...
c0d6393b5f1c18b4945600a1c9b53c7ae9b96701
juhideshpande/LeetCode
/ReverseLinkedList.py
533
3.796875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev=None ...
c30e99e5204cfbe4344e6add5b10aaa48c4fc817
skumarpi/sphinx-example
/examplecode/functions.py
232
4.03125
4
def x_squared(x): """ A function to return the square of X. Args: x (float): A float or numpy array Returns: float: The value of x-squared """ return x*x def x_cubed(x): return x*x*x
715f2cc3ee1caf4fef0662f48da3edb7b9984464
madeibao/PythonAlgorithm
/PartA/py二叉树的前序遍历.py
538
3.6875
4
from typing import List class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None class Solution(object): def preOrder(self,root)->List[int]: res = [] def dfs(root): # 调用外部的变量的值。 nonlocal res if not root: return res.append(root.val) dfs(root.left) ...
b940011987b8bee25d298b280399701048e16c96
snowlance7/Python-Projects
/week2/Sales Tax Calculator/stcUI_module.py
488
4.03125
4
def get_input(): print("\nENTER ITEMS (ENTER 0 TO END)") item_cost = -1 total = 0.00 while item_cost != 0: item_cost = float(input("Cost of item: ")) total += item_cost return total def display_total(total): print("Total: " + str(total)) def display_...
deeeeb17ae60e2bec02f474d74d3b2ff2fa2b186
leeejin/python_
/Assignment_5weeks/6W_ex1.py
167
3.875
4
age = int(input('나이는?')) mon = int(input('요금은?')) if age>=65: print('요금은',mon * 50/100,'입니다') else: print('요금은',mon,'입니다')
7e0bb490e940a70e4854ed778acff682c498a26b
hoang-ng/LeetCode
/Array/131.py
871
3.921875
4
# 131. Palindrome Partitioning # Given a string s, partition s such that every substring of the partition is a palindrome. # Return all possible palindrome partitioning of s. # Example: # Input: "aab" # Output: # [ # ["aa","b"], # ["a","a","b"] # ] class Solution(object): def partition(self, s): rs =...
989d2604f268defc382b0336c5f6dc82f4d96e6e
BeniyamL/alx-higher_level_programming
/0x08-python-more_classes/2-rectangle.py
2,489
4.3125
4
#!/usr/bin/python3 """ class defintion for Rectangle """ class Rectangle: """ Rectangel class """ @property def width(self): """ getter method of width Arguments: nothing Returns: the width of the rectangel """ return self.__width @wid...
2ed1707aec010c3e6f9c503f702c258fc001311a
pimbi98/Python
/Udemy/AprendeAProgramarPythonConProyectos/10POO/107HerenciaMultiple.py
458
3.65625
4
class A(): def mensaje(self): print("Esto es clase A") def primera(self): print("ESTAS DENTRO DE CLASE A") class B(): def mensaje(self): print("Esto es clase B") def segunda(self): print("ESTAS DENTRO DE CLASE B") class C(A,B): pass c = C() c.mensaje() #Toma la pri...
3003c4d43dea35a9ab3ae733aeb03a306b30b25a
msagi/advent-of-code-2020
/12/solution.py
1,264
4.34375
4
# https://adventofcode.com/2020/day/12 from dataclasses import dataclass @dataclass class Ferry: directions = ['N', 'E', 'S', 'W'] north: int = 0 east: int = 0 facing: int = 1 # directions[facing] = 'E' def navigate(self, action: str, value: int): if action == 'N': self.nort...
a424866970aa0002e806903b5cbd09b518cbb260
key70/day0411
/ex03.py
2,372
3.59375
4
# 어떤 feature가 그것을 결정하는 가장 중요한 요인인가를 파악중요하다. # 그것을 결정하는데 필요한 데이터를 수집하는것이 중요 import numpy as np import pandas as pd from sklearn import linear_model, model_selection names = ['age','workclass','fnlwgt','education','education-num','marital-status', 'occupation','relationship','race','sex','capital-gain'...
fae5afce687ed1b7eee4063990c345b689fe9414
ChristianF23/Listas_Pilas_Colas
/ListaEncadenada.py
2,175
3.515625
4
from ListaAbstracta import ListaAbstracta class Nodo: """ Representa un nodo para la lista encadenada """ elemento = None siguiente = None def __init__(self, elemento, siguiente): self.elemento = elemento self.siguiente = siguiente class ListaEncadenada(ListaAbstracta): ...
5b9f56a182635ed76e51b4e7ba35cad58e4e313a
hughluo/wexort_img
/rect2circle.py
1,529
3.578125
4
from PIL import Image from math import sqrt from sys import argv def rect2square(img): w, h = img.size if w > h: padding = (w - h) / 2 cropped_img = img.crop((padding, 0, padding + h, h)) else: padding = (h - w) / 2 cropped_img = img.crop((0, padding, w, padding + w)) ...
f73820bb598d8094245c8097a2799fbc6d7672d3
SalihTasdelen/Hackerrank_Python
/Check_Strict_Superset.py
334
3.53125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT aset = set(map(int, input().split())) flag = 0 for _ in range(int(input())): tset = set(map(int, input().split())) if aset.issuperset(tset): flag = 1 else: flag = 0 break if flag == 1: print("True") else: p...
33c0bc7a0fdb2c73448b4e046ca1d7b34d0d7266
jungyr24/algo-rhythm
/이코테/CH07 이진 탐색/떡볶이 떡 만들기.py
1,335
3.5
4
# 갖고 있는 떡 들에서 기준 길이만큼 자르고 남은 자투리 떡들을 모아서 손님한테 판매 # 손님이 요청한 총 떡의 길이가 M일 때 적어도 M만큼의 떡을 얻기 위해 절단기에 설정할 수 있는 높이의 최댓값을 구하는 프로그램 def binary(rice, target, start, end): global m_target if start > end: return m_target mid = (start+end) // 2 # 떡 자르기 total = 0 for r in rice: if m...
7dac6ae18904018c6dd8105d9b0b960b1ad1f4ab
navazl/cursoemvideopy
/ex106.py
153
3.8125
4
while True: ajuda = str(input('[FIM para terminar] help: ')).upper() help(ajuda) if ajuda == 'FIM': break print('Obrigado por usar!')
a3fb3104e1fdaae2df4096164708d0f045d4dc2d
rishabhvaish/Python
/Search/Hash Tables: Ice Cream Parlor.py
589
3.765625
4
#!/bin/python3 import math import os import random import re import sys # Complete the whatFlavors function below. def whatFlavors(cost, money): cost_map = {} for i, c in enumerate(cost): sunny = c johnny = money - c if johnny in cost_map.keys(): print(cost_map[johnny]+1, i...
a54997c186fc07315a436987b02a5c135412cc74
LeynilsonThe1st/python
/curso-em-video/Desafio57.py
174
3.625
4
import colors sair = False while not sair: sexo = str(input('Degite o seu sexo: ')) if sexo in 'Mm' or sexo in 'Ff': sair = True print(colors.red, 'Terminou')
5d52463d60e1f348fe25b1d58f4eba1d8a7a5a8f
helioh2/oficina2018
/templates/template_funcao.py
634
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest ''' PROBLEMA: <enunciado do problema> ''' #ESCREVA O CÓDIGO AQUI '''Para cada nova funcao criada, voce deve criar uma funcao dentro da classe Test para testá-la, conforme o template ''' class Test(unittest.TestCase): pass #retirar esta linha após...
eb3d1bcec574412af74d846fe1736275ac1631ce
osmanozden/basic_python_fundamental
/dictionary.py
627
3.5
4
#Bir key birde volue bilgisi ile çaışmasını istedğimiz ifadeler {} ile kullanılır --> # sozluk1 ={"ADAPAZAR":54,"İSTANBUL":34,"SAMSUN":55} # print(sozluk1["ADAPAZAR"]) #BU SEKİLDE CALISIRLAR. # sozluk1["ADAPAZAR"] =99 #SONRADAN BU SEİLDE ATAMA YAPILABİLİR. # print(sozluk1) #İç İçe SÖZLÜKLER EKLEYEBİLİYORUZ. k...
ee5b552661dfc603c19b02949cec5ea9172b9c26
l2m2/leetcode
/search-insert-position/main.py
654
3.875
4
''' @File: main.py @Author: leon.li(l2m2lq@gmail.com) @Date: 2018-09-15 21:54:00 @Last Modified By: leon.li(l2m2lq@gmail.com>) @Last Modified Time: 2018-09-15 22:05:29 ''' class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ for i i...
5e0a712ee4d0ece37fefe6b8931e510edc25d85a
greenfox-zerda-lasers/brigittaforrai
/week-04/day-03/copy02.py
305
3.9375
4
from tkinter import * root = Tk() canvas= Canvas(root, width="300", height="300") canvas.pack() def square_line(a): x = a b = a for l in range(0, 6): square = canvas.create_rectangle(x, x, x+a, x+a, fill= "purple") x = x+a a = a +b square_line(10) root.mainloop()
148cc73e2c0cdf84d63783a85fea5ea989492bdb
codexdelta/DSA
/tree/bst.py
2,759
3.875
4
__author__ = 'ashwin' # binary search tree in python """ user: bst = Tree() bst.insert(14) bst.preorder() bst.inorder() bst.postorder() class insert (self, data) find (self, data) preorder() postorder() inorder() Node : insert(self, data) find(self, data) preorder() postorder() inorder() """ class Node: def __i...
b290ca2c53f1eb44fa7c9b0f5dfeec8fc66e969c
Aswin-Sureshumar/Python-Programs
/For.py
259
4.375
4
##for letter in 'python': ##print ('current letter:',letter) fruits=['banana','mango','apple'] ##for fruit in fruits: ##print ('current fruit:',fruit) ##print('good bye') for index in range(len(fruits)): print ('current fruit:',fruits[index])
267c4cb347d11740d15560d592dcf3ddd7fdfae6
MulengaKangwa/PythonCoreAdvanced_Files
/142WritingMutipleStrings.py
140
4
4
f=open("myfile.txt","w") print("Enter Text(Type # when you are done)") s='' while s != '#': s = input() f.write(s+"\n") f.close()
878aa0c89c766f4a5106f43278469b839fd0c124
AakashOfficial/ChallengeTests
/challenge_1/python/wost/main.py
262
4.15625
4
def reverse_string(string): for i in range(len(string) - 1, -1, -1): print(string[i], end="") print() def main(): reverse_string("this was a triumph") reverse_string("hello world") reverse_string("42") if __name__ == "__main__": main()
9b8eaf92a3384ae848cae589c602cbf9bb952432
soumya9988/Python_Machine_Learning_Basics
/Python_Basic/5_Dictionaries/basics_of_dict.py
436
3.640625
4
spam = {'Alice' : 30, 'planets' : ['mars', 'venus', 'earth', 'pluto'], 'pi' : 3.14, 1: 13} # Key, values and items in dictionary print(spam.keys()) print(spam.values()) print(spam.items()) # setdefault method in dict spam.setdefault('colour', 'black') print(spam) spam.setdefault('colour', 'pin...
cc44973070dee6c4209a828622ee36fd886eee32
MerajBighamain/python_projects-1
/reverse_str.py
261
4.125
4
def reverse_str_v1(s): r='' for char in s: r=char+r print("\n",r) s=input("give a string:\n") reverse_str_v1(s) #------------------------- def reverse_str_v2(s): r='' for i in range(len(s)-1,-1,-1): r=r+s[i] print(r)
2f689dab16d5d9e8467ee14fc2f84f3888b67060
Rockyzsu/StudyRepo
/python/my_py_notes_万物皆对象/算法/tree.py
1,081
3.609375
4
#!/usr/bin/env python # encoding: utf-8 import json from collections import defaultdict def tree(): """ 定义一棵树 python 字典的特性,赋值操作必须事先声明,所以这里使用 collections 很方便的为字典设置初始值 :return: """ return defaultdict(tree) if __name__ == '__main__': users = tree() users['jack_1']['jack_2_1']['jack_3_...
9a1e0977d5690f5ae6ca7f608bf5f09e048c5220
ricarcon/programming_exercises
/2021/maxSubArray.py
591
3.796875
4
import sys def maxSubArray(nums): min_index = 0 max_index = 0 current_min_index = 0 current_max_index = 0 maxsum = 0 current_sum = 0 for i in range(len(nums)): if nums[i] > 0: current_sum += nums[i] current_max_index = i elif current_...
ed379a6dce86ce57032a41a083a9562c8c52e982
Jaskirat1/jaskirat
/venv/controller.py
306
3.953125
4
#Arithmetic Ooperators:+,-,%,** dish1= 100 dish2= 400 bill = dish1 + dish2 print ("bill is:",bill) #Assume taxes to be 5% taxes = .05*bill print("taxes:",taxes) totalbill =bill +taxes print("Totalbill",totalbill) num1= 2 num2 =3 num3 = num1//num2 print("num3:",num3) num= 149 data= num//100 print(data)
8366bb4ffeed75644a304bbccd7db5a1f47ad999
doplab/act-tp
/2021/week06/solutions/question5-1.py
734
3.578125
4
def recherche_binaire_recursive(L, s, r, x): if r >= s: mid = int((s + r)/2) print(f'Le milieu de la liste {L} est {L[mid]} situé à l\'indice {mid}') if L[mid] == x: return mid elif L[mid] > x: return recherche_binaire_recursive(L, s, mid-1, x) else: ...
0e37d9fdbd4fd231ecf9d42977117f7557b12812
WindWalker19/Traslator
/translate.py
982
4.53125
5
# The translate function converts all the vowels to a. Just for fun to look how the words look like if i convert the vowel letter # present in them. #first we want to ask the user for an input text. def translate(phrase): #get an empty string where we could store the letters. new_phrase = "" #Then we want ...
686f5bf2361dadf1e1c8dbd4cd94e2d6fb0fa5f9
leodan87/EjerciciosPython
/dictsFecha.py
573
4.1875
4
''' Escribir un programa que pregunte una fecha en formato dd/mm/aaaa y muestre por pantalla la misma fecha en formato dd de <mes> de aaaa donde <mes> es el nombre del mes. ''' meses={'01':'Enero', '02':'Febrero','03':'Marzo', '04':'Abril', '05':'Mayo','06':'Junio', '07':'Julio', '08':'Agosto','09':'Septiembr...
d65f2347f9e73a045e5b05728c497f91b3bfb714
raianyrufino/URI-OnlineJudge
/1066.py
385
3.53125
4
contpar = 0 contim = 0 contpos = 0 contneg = 0 for i in range(5): i = int(raw_input()) if i % 2 == 0: contpar += 1 else: contim += 1 if i > 0: contpos += 1 elif i < 0: contneg += 1 print "%d valor(es) par(es)" %(contpar) print "%d valor(es) impar(es)" %(contim) print "%d valor(es) posi...
2771b06176016bc62796393fdf98220aa6c64db9
Joshcosh/AutomateTheBoringStuffWithPython
/Lesson_23.py
1,727
4.5625
5
# %% # 1 | What does it take to recognize a phone number without regex # 415-555-0000 - Phone number # 415,550,0000 - Not a phone number def isPhoneNumber(text): if len(text) != 12: return False # not a phone number for i in range(0, 3): if not text[i].isdecimal(): return False # n...
b35fcc06f47e901c0b4f7f21ddd942360241d099
portugol/decode
/Algoritmos Traduzidos/Python/Algoritmos traduzidos[Diogo]/ex4.py
111
3.53125
4
a=input('Digite o numero de três casas:') d=0 d=int(a)/100%10 print('Algarismo na casa das centenas:',int(d))
ff3b04f6a055c1b57d4f912824cdd92fbafe5e94
MTrajK/coding-problems
/Arrays/find_one_missing_number.py
940
4.34375
4
''' Find the missing number in a sequence Find the only missing integer in a sequence, all numbers are integers and they're smaller or equal to N+1 (N is length of the array). Input: [2, 1, 4] Output: 3 ========================================= Searching for 1 unknown, math problem. Use the sum formula for the first...
1f3b503110d129a36b6cd46f265a148679a05476
Hemanthtm2/Python
/exceptions.py
152
3.734375
4
#!/usr/bin/python filename=raw_input("Enter the file name") try: f=open("filename","r") except IOError: print "There is no file named",filename
67ee5f2cdc78b6f77cce1f0156448aa78fb66adc
j1-aggie/python-challenge-
/PyBank/PyBank.py
2,714
3.984375
4
# pybank # import the os module import os # module for reading csv file import csv # set the path for the data file PyBankcsv = os.path.join('.' , 'Resources' , 'Budget_Data.csv') # Set Variables Total_Months = 0 Net_Profit = 0 Greatest_Increase_Profits = 0 Greatest_Decrease_Losses = 0 Monthly_changes = [] Greatest_...
1a7001821a003d90655ef3b989987023ea313550
csparpa/robograph
/robograph/datamodel/nodes/lib/randoms.py
2,798
3.546875
4
import random import uuid from robograph.datamodel.base import node class IntegerRandomizer(node.Node): """ This node gives a random integer from the specified range. Randomization has a uniform pdd and range defaults to: [0-10) Requirements: range_lower --> lower boundary or randomization rang...
2186ca62d22541a6c799300d8f223da382195153
jyq920203/python
/SoloLearn网站课程/propertyTest.py
377
3.90625
4
# 写代码的时候遇到很有意思的一个问题,就是在我使用property的时候,我定义的方法跟我的属性名称不一致,结果debug的时候,多出来一个属性 class A: pramA="" pramB="" @property def pramA(self): return self.pramA @pramA.setter def pramA(self,value): self.pramA=value a=A() a.pramA = "b"
c8293311adfaf58008ec1d179af8f329b1de7d4d
tongxindao/shiyanlou
/shiyanlou_cs892/animation.py
342
3.703125
4
#_*_ coding: utf-8 _*_ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() x = np.arange(0, 2 * np.pi, 0.01) line, = plt.plot(x, np.sin(x)) def update(i): line.set_ydata(np.sin(x + i / 10.0)) return line animation = animation.FuncAnimation(fig...
f1ad55ba2dae13342e60e075d11798ee83a4c959
madisontg/Intro-programs-part-two
/cities_in_countries.py
777
3.796875
4
# Madison Thorburn-Gundlach # Due November 11, 2015 # exercise 17 # establish a dictionary cities = {} # open a file for reading file = open("cities.txt", "r") # go through the file line by line for line in file: # create a list for each city line = line.strip() city = line.split(", ") # if the secon...
5a9bffdd07233affcd6c862b3a6eb388651a371c
renchao7060/studynotebook
/基础学习/p68.py
1,016
3.6875
4
#猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个。 #第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。 #到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 ''' 这题得倒着推。第10天还没吃,就剩1个,说明第9天吃完一半再吃1个还剩1个,假设第9天还没吃之前有桃子p个, 可得:p * 1/2 - 1 = 1,可得 p = 4。以此类推,即可手算出。 代码思路为:第10天还没吃之前的桃子数量初始化 p = 1,之后从9至1循环9次,根据上述公式反推为 p = (p+1) * 2 可得第1天还没吃之前的桃子数量。for循环中的print()语句是...
975a4e47959aeb74b07098726cc8e240efb7d371
DarioCozzuto/list
/access list items.py
1,051
4.5625
5
#List items are indexed and you can access them by referring to the index number: thislist = ["apple", "banana", "cherry"] print(thislist[1]) #-1 refers to the last item, -2 refers to the second last item etc. thislist = ["apple", "banana", "cherry"] print(thislist[-1]) #This will return the items from ...
6c27dc894628f6de885d3521fdb7a5c45fb83eac
Programmer-Admin/binarysearch-editorials
/Largest Tree Sum Path.py
985
3.984375
4
""" Largest Tree Sum Path For each node, we can check whats the path with the greatest sum that goes through it by checking the max value of the following possibilites: - The path starting at the node (if children are negative), - The path coming from the left child, - The path coming from the right child, - The path...
7743c91823ffdbf069e86478bd5754d325a0fabc
MinhKMA/ghichep-python
/exercises/Ex1,2_Chapter3-.py
862
3.890625
4
#Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. #Exercise 2: Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. ===============================...
d30102e793c3d74d08c5ef1f1bc7d4f583945252
NasirOrosco/Python
/Comments/CommentsDebug.py
561
4.28125
4
''' Created on Dec 4, 2020 @author: NasirOrosco ''' ''' The goal of this function is to calculate the volume of an object, when the user inputs height, width, and depth. The function should print the sentence plus the volume and return the volume.''' def volumeCalculator(height, width, depth): area = height * w...
a174a379279da459d9e82d3429303ab193b86024
karanjhand/Catch_The_Thief
/flappybird/swap.py
137
3.796875
4
def swap(a,b): tmp = a print(a) print(b) print(tmp) a = b print(a) print(b) print(tmp) b = tmp print(a) print(b) print(tmp)
5e1517280f26db60b40402416d7ec4d5c3f35cf5
willian8000/uri-online-judge
/Problems/1040.py
720
3.5625
4
import math a, b, c, d = map(float, input("").split(" ")) media = round((a * 0.2) + (b * 0.3) + (c * 0.4) + (d * 0.1), 2) def truncate(f): return math.floor(f * 10 ** 1) / 10 ** 1 if media >= 7.0: print("Media: {0}".format(truncate(media))) print("Aluno aprovado.") elif 5 <= media < 7.0: prin...
22dc3e63b45d093f5b8678a6ea42d581e2fde85c
azulus/interviewprep
/solutions/algorithms/algorithm_knuth_shuffle.py
1,373
3.90625
4
import random # Class which maintains a shuffled and unshuffled list of chars class Shuffler: def __init__(self): print "initializing", self self._shuffled = [] self._unshuffled = [] # add a character to the shuffler def addChar(self, char): self._unshuffled.append(char) charLen = len(self....
dbb6df55149a5c5498ca95a6335b4879a9e26e91
sctu/sctu-ds-2019
/1806101061李劲潮/day20190409/stack.py
221
3.96875
4
#定义栈 stack = [] #push stack.append(1) stack.append(2) stack.append(3) for i in range(1,11): stack.append(i) #pop print(stack.pop()) #pop一直到栈不为空 while len(stack) is not 0: print(stack.pop())
2d983a00af8e4f9a69c1b4a82a44a4cf04dd0845
eggeggss/BigData
/ch04/19for6-exam99No4.py
203
3.796875
4
#!/usr/bin/env # -*- coding:utf-8 -*- for x in range(1,10): for y in range(1,10): if x==4 or y==4: print("") else: print(" %d*%d=%d" % ( x,y,x*y)) print("end")
07a2788df754316a37eb4f914c4eec7417310e49
toddaulwurm/extras
/selection_sort.py
274
3.859375
4
def selectionSort(list): for i in range(0, len(list)): min = i for j in range(i+1, len(list)): if list[min] > list[j]: min=j list[i], list[min] = list[min], list[i] print(list) selectionSort([1,3,4,2,5,8,7,6,9])
e89c38149f147786647bccc4ffff4948664569e8
Aasthaengg/IBMdataset
/Python_codes/p04033/s927676383.py
311
3.546875
4
a,b = map(int,input().split()) if a > 0: print("Positive") exit(0) if (a == 0 or b == 0) or (a < 0 and b > 0): print("Zero") exit(0) # only negative a,b cases left from this point on if (a == b): print("Negative") exit(0) if (a - b) % 2 == 1: print("Positive") else: print("Negative")
72a8f8cf816b6702816bb86c24104ee5941fc19a
yuchien302/LeetCode
/leetcode257.py
932
3.828125
4
# 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 binaryTreePathsHelper(self, root, s): """ :type root: TreeNode :rtype: List[str] """ ...
a16ff0d97b2f854d34c9434476d9142710734596
sashaobucina/interview_prep
/python/hard/median_of_two_sorted_arrays.py
881
4.03125
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. NOTE: This solution is in O(n) time and is not optimized """ def findMedianSortedArraysBad(nums1: list, nums2: list) -> float: nums3 = [] i, j, m, n = 0, 0, len(nums1), len(nums2) while i < m ...