blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4b25ba1132d2b737d566db80dbd5f34dd4a7e193
felipevitalrc/CursoEmVideoPythonExercicios
/aula08c.py
265
3.765625
4
import math catetoOposto = float(input('Digite o valor do cateto oposto: ')) catetoAdjacente = float(input('Digite o valor do cateto subjacente: ')) hipotenusa = math.hypot(catetoOposto, catetoAdjacente) print('A hipotenusa dessa conta é: {}'.format(hipotenusa))
4dfcfab7b4230f55d8758d12e0bfb7cae0ee44fd
kateryna-turchyna/calculator
/calculator.py
808
4.125
4
def add (x,y): return x+y def subtract (x, y): return x-y def multiply (x, y): return x*y def divide (x,y): return x/y while True: question=input("do you want to use a calculator: yes/no ") if question == 'yes': choice_op=input("select operation: add, sub, mul, div "...
2ef6048b7b78069146e0950d0462f79067da76a0
kainpets/Zelle-introduction-to-CS
/6.5.py
511
4.28125
4
import math diameter = float(input("Enter the diameter of your pizza: ")) price = float(input("Enter the price of your pizza: ")) def areaOfPizza(diameter): return math.pi * (diameter/2)**2 def costSquareInch(diameter, price): return price / areaOfPizza(diameter) def main(): print("The area ...
abdc3f0a0306d00330af99008a7b67e4ed451792
TaylorGrover/func
/stats.py
5,789
3.890625
4
from decimal import Decimal import matplotlib.pyplot as plt import numpy as np import os ### Set of useful statistics functions def pearson(x, y, population = True): return covariance(x, y, population) / (stddev(x, population) * stddev(y, population)) def covariance(x, y, population = True): if population: ...
5028c3a6323ad95dac85abb0b602b9c8f596ec1b
vitgusmao/SuperResolutionGANs
/nets/utils.py
390
3.71875
4
import numpy as np DIV2K_RGB_MEAN = np.array([0.4488, 0.4371, 0.4040]) * 255 def normalize(x, rgb_mean=DIV2K_RGB_MEAN): '''This function will normalize image by substracting RGB mean from image''' return (x - rgb_mean) / 127.5 def denormalize(x, rgb_mean=DIV2K_RGB_MEAN): ''' This function will denormal...
a60ab382013b7fb6e1200ce57b0a63e3a0064ef8
DebRC/My-Competitve-Programming-Solutions
/Codechef/XYSTR.py
269
3.609375
4
# cook your dish here t=int(input()) while(t>0): t-=1 s=input() pair=0 i=0 while(i<len(s)-1): if((s[i]=='x' and s[i+1]=='y') or (s[i]=='y' and s[i+1]=='x')): pair+=1 i+=2 else: i+=1 print(pair)
5204079c67a44488d3cc9c92828dd2f5cfff496e
codingninja614/python
/raising'error.py
346
4.03125
4
while True: try: age=int(input("What is your age:")) 10/age raise ValueError("hey cut it out!") continue except ZeroDivisionError: print("Please enter a number other than zero!") else: print("THANK YOU!") break finally: print(...
fae8b26d2e40f8c8a882e1bac6dc5dbcfc472b39
sukunadotjpg/faculdade
/sorteio.py
1,144
3.84375
4
import random #cabecalho text = 'algoritmo para sorteio beta alpha test v1.0' tam = len(text) print('+','-' * tam,'+') print('|',text,'|') print('+','-' * tam,'+') #funcao para adicionar dados na lista lista_doadores = [] def dados(doadores, valor): lista_doadores.extend(((doadores+' ') * int(valor//10)).split())...
8ae9f44df5d691dfebd65a1d93b014fd9f513bde
ijnji/sandbox
/python/epi/coin_game.py
1,124
3.8125
4
#!/usr/bin/env python3 # # Description: # # Given an even list of coins with integer values, two players take turns # choosing and keep a coin from either end of the current list. Find the maximum # total revenue of the first player if both players play optimally. from enum import Enum class Turn(Enum): ONE = 1 ...
0a4f2146cc7840687f9f75227db230a3df269ac9
akashvshroff/DSA_Coursera_Specialisation
/Algorithmic_Toolbox/week2_assigment/lcm.py
301
3.765625
4
# Uses python3 import sys def gcd_naive(a, b): return a if not b else gcd_naive(b, a % b) def lcm(a, b): return (a*b)//gcd_naive(a, b) if __name__ == "__main__": input = sys.stdin.read() a, b = map(int, input.split()) a, b = (a, b) if b <= a else (b, a) print(lcm(a, b))
64c4e2fd80c102d1ca9da4a87b95f67efab9678f
zenmeder/leetcode
/565.py
452
3.9375
4
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" class Solution(object): def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ maxlength = 0 record = {} for num in nums: length = 0 while num not in record and num < len(nums): record[num] = 1 num =...
5f962a483738289904566c56284739bb931b6bd7
prudentprogrammer/Programming-Challenges-Solutions
/uriProblems/Beginner/1009 - Salary with Bonus.py
143
3.515625
4
name = input().strip() salary = float(input().strip()) sales = float(input().strip()) print('TOTAL = R$ {:.2f}'.format(salary + 0.15 * sales))
675108650339602a3426e0aedddb7502c365e7c7
dojciech1997/Truck-Packing-Algorithm
/Code/algorithm_data.py
11,828
3.59375
4
from typing import List, Tuple, Dict import os import random import pandas as pd import numpy as np class DataFromFile: """Class needed for work with files (.txt), which contains class function to return data from specific .txt file""" def __init__(self, filename_p: str, filename_t: str, filename_s: str, id_...
3ef37afde427abbd6f5285336626662faee40efd
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/leap/2bae77c06e8447e0b61142598951940c.py
389
4
4
#!/usr/bin/env python def is_leap_year(year): year = int(year) if (year % 400) == 0: return True if (year % 100) == 0: return False if (year % 4) == 0: return True return False if __name__ == '__main__': import sys if len(sys.argv) != 2: print "Usage is ./y...
c1fe5b3a8f69bc0507b1c85fa2b1d6594d9589cb
andreibratu/bachelor
/sem5/avdp/lab/helper/bits.py
1,533
3.5625
4
import json from typing import List def add_one_binary(binary: List[int]) -> List[int]: carry = 1 answer = binary[::-1] for idx, _ in enumerate(answer): answer[idx] += carry carry = answer[idx] // 2 answer[idx] %= 2 if carry != 0: answer.append(1) return answer[::-1...
3b893f37c2922dd0649de0dfacd3d77de7137ea2
joynsonellist/tkinter_login_menu
/python_tkinter_login_screen.py
1,947
3.734375
4
import tkinter login_window = tkinter.Tk() login_window.title("Login") # ======================================== # usernames = ["Username"] "EDIT" passwords = ["Password"] "EDIT" # ======================================== # def confirm_login(): global login_window username = login_window_entry_username.get(...
a63eeb12f65b4a62747a83a3a6c4af5a78b1a97d
rahulmahajann/CSES_ProblemSet_Solutions
/Introductory Problems/Coin Piles.py
467
3.703125
4
for _ in range(int(input())): a,b=map(int,input().split()) if(a>b): a,b=b,a if(2*a < b): print('NO') # elif(2*a == b): # print('YES') else: a%=3 b%=3 if((a==0 and b==0) or (a==1 and b==2) or (a==2 and b==1)): print('YES') ...
4668424040023144ab936ef40008f515ea133fa3
5udarshan/Functions-and-Modules
/argument.py
77
3.5
4
def addition(n1,n2): n3=n1+n2 print(n1,"+",n2,"=",n3)
18daea54d893d3a2d1347e93765364e19b59edc7
Anirban2404/LeetCodePractice
/70_climbStairs.py
1,333
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 19 10:01:49 2019 @author: anirban-mac """ """ You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive ...
68bba111fcd52009dcc5b568ba4ae2ed4a23b91f
liuluyang/openstack_mogan_study
/myweb/test/checkio/oreilly/friends-9-simple.py
1,302
3.8125
4
#coding:utf8 class Friends(object): def __init__(self, connections): #connections = ({'a','b'},{'f','s'}) self.connections = self.make_connections(connections) def make_connections(self, connections): conn = [] for i in connections: if i not in conn: ...
f2799854b3f299de59796651521194d3f7f25439
tecmaverick/pylearn
/src/19_collections/custom_iterator.py
649
3.9375
4
class myiterator: def setValue(self, myStrlist): if type(myStrlist) != str: raise Exception("myStrlist must be of type String") self.mylist = myStrlist.split(",") def __iter__(self): self.counter = 0 return self def __next__(self): if self.counter < le...
7de1f57b6ec6fd6313124610804cff52fccb7247
vikramzsingh/Python
/insertelementinlist.py
470
4.0625
4
#program to take input into an empty list lst=[] n=int(input("Enter the number of elements: ")) for i in range(0,n,1): ele=int(input("Enter the element of the list: ")) lst.append(ele) print("Element inputted in the list",lst) print("Manual list: ") for i in range(0,n,1): if(i==n-1): ...
439242f069010dd04ab5bcfabb95b482b19c7676
KevinAnn/ML-learn
/numpy_demo.py
1,562
3.546875
4
import numpy as np # 使用np.array()创建矩阵 na = np.array([[1, 2, 3], [4, 5, 6]]) print("========== array() ==========") print(na) print( """ 对象类型:{}\n 矩阵形状:{}\n 维度(秩):{}\n 元素个数:{}\n 元素类型:{}\n """ .format(type(na), na.shape, na.ndim, na.size, na.dtype) ) # 使用np.zeros()创建矩阵,矩阵中所有元素为0 na1 = n...
357d0cee00db1942d696981f5b813b7868dc59dc
x4nth055/pythoncode-tutorials
/gui-programming/maze-game/maze.py
1,202
3.59375
4
import pygame from cell import Cell class Maze: def __init__(self, cols, rows): self.cols = cols self.rows = rows self.thickness = 4 self.grid_cells = [Cell(col, row, self.thickness) for row in range(self.rows) for col in range(self.cols)] # carve grid cell walls def remove_walls(self, current, next): dx...
29eeeef89ea28a4b3d8069d2d0c159af5381fe23
IGORYUCH/pygame-animations
/sun_system.py
8,864
3.578125
4
import pygame,random,math class Planet(object): def __init__(self,center,r,speed,angle,size,color): self.r = r self.b = 0.3 self.a= 1 self.x,self.y = 0,0 self.center = center self.size = size self.distance = 0 self.speed = speed se...
334160c62808e2773cedaa66bf106855532a4b31
samlaudev/LeetCode
/Python/Implement Queue using Stacks/Solution.py
1,527
4.46875
4
# Problem: Implement Queue using Stacks # # Implement the following operations of a queue using stacks. # # 1. push(x) -- Push element x to the back of queue. # 2. pop() -- Removes the element from in front of queue. # 3. peek() -- Get the front element. # 4. empty() -- Return whether the queue is empty. # # No...
598f1d5287738d8724779273df806898e9389a40
qmnguyenw/python_py4e
/geeksforgeeks/python/easy/27_14.py
4,401
4.8125
5
numpy.argmax() in Python The **numpy.argmax()** function returns indices of the max element of the array in a particular axis. **Syntax :** numpy.argmax(array, axis = None, out = None) **Parameters :** **array :** Input array to work on **axis :** [int, opt...
ed723b3cfc430bfe113be51f9272ef574f3a233b
AlexGuDu/UABC-Python
/Parcial 1/crash_course (extra)/functions.py
811
4.15625
4
# FUNCTIONS # Create a function def sayHi(name): 'This is not getting parsed' print('Hi', name) sayHi("it's me, ya boi.") # Return a Value def getSum(num1, num2): total = num1 + num2 return total numSum = getSum(5, 10) print(numSum) def addOneToNum(num): num = num + 1 print('Value insid...
1e3b9aad629ce86d7bf3b6cbbad3352c96f11c6e
whenhecry/Rokken
/myFilters.py
955
3.6875
4
# assuming the input is a list of articles sorted by date # return a list of article list divided by month # eg. [..., [article1 of 2015/7, article2 of 2015/7, ...], [article1 of 2015/6, ...], ...] def listOfMonth(articlesList): myList = [] year = None month = None for article in articlesList: t...
f1fffc3632762e0166fefb7636d1ddf07ad8dca6
achkataa/Softuni-Programming-Fundamentals
/PF - self-preparation exam/National Court_2.py
305
3.875
4
employee1 = int(input()) employee2 = int(input()) employee3 = int(input()) people = int(input()) hours = 0 total_efficiency = employee1 + employee2 + employee3 while people > 0: hours += 1 people -= total_efficiency if hours % 4 == 0: hours += 1 print(f"Time needed: {hours}h.")
8678d4e7b7754c9efedab5bb3e10ee8814d29698
JIM66/test1
/Automatically send mail/finance.py
1,786
3.734375
4
def npv_f(rate, cashflows): ''' net present value is defined as different between the present value of all the benefit and cost. :param rate: :param cashflows:every year cashflow :return: ''' total = 0 for i, cashflows in enumerate(cashflows): total += cashflows/(1+rate)**i ...
8156e1934f7ea97e6258e9824f6f01c89873f1b0
ghjbku/python_ibiza
/RSA_data.py
1,128
3.546875
4
import random import modular_functions import primecheck def random_number_gen(lengthofnumber): return random.getrandbits(lengthofnumber) def RSA_prime_gen(lengthofnumber): n1= random_number_gen(lengthofnumber) index = 0; while(primecheck.isprime(n1,[40])==False): index=index+1; n1= ...
41e518b95da67d1bca5dcc38f372b05f0b87c751
acekavi/SD1-Project
/functions-BU.py
4,535
3.6875
4
class CharInput: def __init__(self, question, param): self.question = question self.param = param def int_input(self): while True: try: x = int(input(f"{self.question} : ")) if x in self.param: return x els...
b1651b98c7d79c20d96844d43f7f7bbba9e474b4
biwenKey/Python_study01
/函数学习/函数作业04.py
452
3.734375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- #写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容 def f2(p): #jieguo = [] for i in p: if i.isspace(): #jieguo.append("确实是包含了空内容") print(i,"是空格") else: #jieguo.append("没有包含空内容") print(i) #return jieguo f2(("wo...
fd069a624dae8cc0b405479f8427c146ae0684e3
Rikharthu/LearningPython
/advances_collections/ordered_dict.py
1,556
4.1875
4
from collections import OrderedDict def main(): # OrderedDict is a dictionary that remembers the order by what items were inserted # list of sport teams with wins and losses sportTeams = [("Royals", (18, 12)), ("Rockets", (24, 5)), ("Cardinals", (20, 10)), ...
bac0d0776842203f5353db7e116f21caec6d3162
andrade-marco/python_masterclass
/basic/FileWriting.py
184
3.5625
4
cities = ['Adelaide', 'Alice Springs', 'Darwin', 'Melbourne', 'Sydney'] with open('../data/cities.txt', 'w') as cityData: for city in cities: print(city, file=cityData)
009ae73e78409069605287722324b1b4106c845d
goldA233/python-portfolio
/ricky_C_Portfolio_Exercise_5.py.py
213
3.609375
4
count = 0 for num in range(2,1001): for i in range(2,num): if (num%i==0): break else: print(num ,end=' ') count += 1 if(count%8==0): print(end="\n")
1d5baea89a975838ea5fd31d08b343aecc8db4e6
sammshelia/pythonGit
/Task2.py
2,406
3.828125
4
# Zenith Crest Bank from datetime import datetime, date # Welcome the customer with a greeting print("Welcome to Zenith Crest Bank. \nPlease proceed with your registration \n") # Get User details First_Name = input("Enter First Name: ") Last_Name = input("Enter Last Name: ") Midddle_Name = input("Enter Middle Name:...
a168dfb202d7e885ffdd3381edb078e4b4026630
MochamadAmri/Labspy2
/ProgramBilanganTerbesar.py
699
3.953125
4
print ('=====================================') print ('PROGRAM MENENTUKAN BILANGAN TERBESAR') print ('=====================================') print ('') print ('Masukkan 3 Bilangan yang diinginkan!') a=int(input('Bilangan 1 = ')) b=int(input('Bilangan 2 = ')) c=int(input('Bilangan 3 = ')) if a>b and a>c: print('')...
af5f4c78bcf0cbf7d7a9a0d107feb31ac776a9a6
julioaviladias/Econometria
/Exercícios 25 de maio/Ex12.py
206
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri May 25 21:05:22 2018 @author: Asus """ #Entrada a=int(input("Insira o número da tabuada:")) #Processamento i=1 while i<=10: print(a+i) i+=1
48160e993f26ae8fab111cea6257e19cc58a68d8
xztor/EulerProject
/problems/0025/p25.py
830
4.15625
4
#!/usr/bin/python # -*- coding: latin-1 -*- # # The Fibonacci sequence is defined by the recurrence relation: # # Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. # Hence the first 12 terms will be: # # F1 = 1 # F2 = 1 # F3 = 2 # F4 = 3 # F5 = 5 # F6 = 8 # F7 = 13 # F8 = 21 # F9 = 34 # F10 = 55 # F11 = 89 # F12 =...
48314e2c2743c43dae6da17c1503629dc4b7f645
inJAJA/Study
/keras/keras110_1_sigmoid2.py
984
3.578125
4
#1. 데이터 import numpy as np x_train = np.array([1,2,3,4,5,6,7,8,9,10]) y_train = np.array([1,2,3,4,5,6,7,8,9,10]) #2.모델구성 from keras.models import Sequential, Model from keras.layers import Dense, Input model = Sequential() model.add(Dense(10, input_shape = (1, ))) # activation : default = 'linear' model.add(Dens...
6841c3ee219ad471301ed32cd02bfd20c826c0c3
delta94/Code_signal-
/Arcade/Intro/Exploring the water/pallindromRearranging.py
762
4.1875
4
"""" Given a string, find out if its characters can be rearranged to form a palindrome. Example For inputString = "aabb", the output should be palindromeRearranging(inputString) = true. We can rearrange "aabb" to make "abba", which is a palindrome. """"" def palindromeRearranging(inputString): l = len(inputSt...
a0492c73bc26843dff1615ab1b3f8d1ede052e29
ramkishorem/pythonic
/session7_file_except/01.py
585
4.46875
4
""" We'll learn to work with files so your programs can: > Persist data user adds between executions. > Analyse huge amount of data by quickly loading them. > Convert open form of file to another. (eg: txt -> html) > and more.. When you want to work with the information in a text file, the first step is to re...
43c3786dd496becc278f2217e48bbf488b0ed5fc
atashi/LLL
/algorithm/剑指offer/11.py
1,085
4
4
# 调整数组顺序使奇数放在偶数前面 # 题目描述 # 输入一个整数数组,实现一个函数来调整 # 该数组中数字的顺序,使得所有的奇数位 # 于数组的前半部分,所有的偶数位于数组 # 的后半部分,并保证奇数和奇数,偶数和 # 偶数之间的相对位置不变。 class Solution: def reOrderArray(self, array): i = 0 while i < len(array): if array[i] & 1 == 0: j = i while j < len(array) and ar...
889c52e2d9ff7de286da742ab60304c9a072965d
adamvm/BoardGame
/Compass.py
2,470
3.6875
4
import unittest class Compass(object): def __init__(self, possible_directions, current_direction): self._current_direction = current_direction self._dir_iteration = list(possible_directions.keys()) self._directions = possible_directions def get_direction(self) -> str: return s...
6dd799c7e549df2eec5caac17803441b6b525169
lncs/python_tool_box
/modify_filename.py
738
3.609375
4
import os def modify_filename(new_filename, suffix, path='./modify_filename/'): """ :param new_filename: 目标文件名模式 :param path: 存放需要修改文件名的文件夹 :return: """ # 列出当前路径下的所有文件 files = os.listdir(path) # print(files) i = 0 for filename in files: # print(filename) i = i +...
df8020193ff8ce780c7cc9dfd5bbbfcb281acf4a
wattsjon2/HW-10-18
/Week 2 Day 1 HW.py
925
3.984375
4
def cubes_under1000(): num = 1 while num*num*num <= 1000: print(num*num*num) num += 1 cubes_under1000() def age_type(): age_input = int(input('What is your age?')) if age_input < 18: print("kids") elif age_input > 65: print("seniors") else: print("ad...
988a79afcdfa61a67848a976e53f0fb3400bcb02
amogchandrashekar/Leetcode
/Hard/Minimum XOR Sum of Two Arrays.py
702
3.765625
4
from functools import lru_cache from typing import List class Solution: def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: @lru_cache(maxsize=None) def dfs(ind, mask): if mask == 0: return 0 ans = float('inf') num = nums1[ind]...
a4c131ec196c920543f032d9c4a49802087305db
dheerosaur/project-euler
/python/002.py
1,418
4
4
#!/usr/bin/env python3 # There are some interesting mathematical proofs and approaches on # this page: https://projecteuler.net/thread=2;page=5 N = 4e9 # 4 million def main3(): """ Every 3d cycle. Fewer iterations first second => next =========================== odd even ...
3383d1cc05128902c09e40abfaf673dc35a3884c
richkris91/Python.01
/Modules/Modules_01/Biggest_array_element.py
282
4
4
def biggest_string_in_a_array(list1): biggest_str = list1[0] for element in range(len(list1)): if len(list1[element]) > len(biggest_str): biggest_str = list1[element] print('Biggest element in the list detected') return len(biggest_str)
2859d48e2e326dfeb858d404268e949a42b4ff91
dmallows/Crayon
/crayon/point.py
8,346
3.8125
4
"""Smart, immutable points which act as a 'remote control' for a graphics context """ from math import sqrt from spaces import Space2D, LinSpace2D, LinSpace class Compass(object): _norm = lambda x, y: (x/sqrt(2), y/sqrt(2)) """Object to store directions. Preferred over a dict for clarity and for making a...
38591ba48e448462e4e7c8cd2871ab66e24d5708
alekao/CCC-Solutions
/2015/J5v3.py
355
3.53125
4
# --- IMPORTS --- from sys import stdin input = stdin.readline def readInt(): return int(input()) N = readInt() K = readInt() MAX = N/K+1 # n = pieces of pie; k = people in line def piDay(n, k, m): if n == 0 or k == 0: return 1 t = 0 for i in range(m, MAX): t += piDay(n-i, k-1, i) ...
de61547f9d6df52c370ce22c23cd1097e8b2d960
MajPaji/ml_material_proj
/MLCS.py
5,826
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 1 19:07:09 2021 @author: Dell This is just summary of diffrerent commands """ # some import import pandas as pd import numpy as np # replace A by B df.replace(A, B, inplace = True) # assume we have NaN how to make those NaN to True in df df.isnull() df.notnull()...
b67a1adee371fb9c2387adee4cb7aeb28cd3e6b4
devak23/python
/reader/swap_numbers.py
541
3.96875
4
def read_user_input(): a = int(input("Enter First Number : ")) b = int(input("Enter Second Number : ")) return a, b def swap_numbers(a, b): b = a + b a = b - a b = b - a return a,b def main(): before_swapping = read_user_input() print(f"Numbers BEFORE swapping: {before_swapping[0...
e52ca70027a0b3263a169b749bc42dc48c7081c4
bssrdf/pyleet
/M/MinimumOneBitOperationstoMakeIntegersZero.py
1,543
3.921875
4
''' -Hard- Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return t...
2b7eab50904664194aaf601e3ea4f21bf4f46cc1
D3ee/StudentManagerSystem
/student.py
225
3.515625
4
class Student(object): def __init__(self,name,gender,tel): self.name=name self.gender=gender self.tel=tel def __str__(self): return f'{self.name},{self.gender},{self.tel}'
4d4f1a96981155e558f7fd485eb40c47f82e1208
Houchangxi/LeetCode-practice
/134. Gas Station.py
573
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 23 12:03:31 2020 @author: andrew """ class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: # 判断是否有解 整体gas是否涵盖整体cost if sum(gas)<sum(cost):return -1 ind_now,oil_now = 0,0 #查找index ...
9f3585c45727767d5b85fae7a523b1e02ef76602
Ikusey/itc110-sum2019
/ITC 110/projects/ch3exercises.py
367
3.84375
4
#exercises chapter 3 import math def b2(): n = int(input("Enter a number: ")) equa = (n * (n-1)) / 2 print(equa) def c2(): r = int(input("Enter a sphere radius: ")) area = 4 * math.pi * r**2 print(area) def d2(): r = 3 a = 2 b = 4 equa = math.sqrt(r * (math.cos(...
5e496424293731b6821505615dc6bc29e0e74344
james4388/algorithm-1
/algorithms/google/InsertRandom.py
1,488
3.953125
4
from random import randint # https://leetcode.com/problems/insert-delete-getrandom-o1/ # - Implement data structure that allow insert delete and random in constant time # Solution: use hashmap store value to index and array to store value # - delete: swap last element to current element if current is not last ...
d3e17048d24f5fc97f865d126ca300f5b3ac3403
MarcinRe/Rozdzialy
/Rozdzialy/5/5.8.py
274
3.6875
4
# -*- coding: utf-8 -*- print"---------------4.22----------------" def f(x): return x*2 print f(3) g = lambda x: x*2 print g(3) print (lambda x: x*2)(3) print"---------------4.23----------------" s="this is\na\ttest" print s print s.split() print " ".join(s.split())
c8605f21634ec24fe7e814d83f7c5fcec0bf08a7
tubaDude99/Old-Python-Exercises
/Unit 1/Python 3.1 3.2 Exercise.py
211
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[2]: x = int(input()) if x >= 89.5: print("A") elif x >= 79.5: print("B") elif x >= 69.5: print("C") elif x >= 59.5: print("D") else: print("F")
01aa02a97d628427af648e20058e0a75e36450fe
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/mthkhi001/question3.py
891
3.9375
4
message = input("Enter the message:\n") repeat = eval(input("Enter the message repeat count:\n")) frame = eval(input("Enter the frame thickness:\n")) #Top part if frame != 0 : print("+" + (len(message) + (frame)* 2)* "-" + "+") straight_line = 1 count = 0 + (2 * (frame - 1)) for j in range (frame - 1): ...
984da8d07057e5673dfc2a9d05897e2b6eed045b
ChrisIJH/chrisijh.github.io
/mergesort_t.py
389
3.71875
4
def mergeSort(alist): print "Splitting" , alist if len(alist) > 1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf=alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i<len(lefthalf) and j<len(righthalf): if lefthalf[i]<righthalf[j]: alist[k]=lefthalf[i] i+=1...
0ca256275199501975437f5c532d3235f10ff269
sagarmane123/MachineLearning
/Find_S_Algo/Find_S_Algo.py
1,438
3.796875
4
''' This program is machine learning FindS concept learning algoritham Goal : Induced a general function from specific tranning example Given: A (large) set of training data of examples labeled as being members or non-members of a concept Compute: A general function that fits the training data well and generali...
764806ffb6bf2f634b35509c7466a64c91e1a268
RozenAstrayChen/Data_Mining
/Apriori/htree.py
2,835
3.53125
4
class HNode: """ Class which represents node in a hash tree. """ def __init__(self): self.children = {} self.isLeaf = True self.bucket = {} class HTree: """ Wrapper class for HTree instance """ def __init__(self,): self.root = HNode() self.frequ...
4227c0afc295030e7fea578e3c8da18da6796a3c
abusamrah2005/Python
/Week-2/Day-7.py
1,048
4.15625
4
""" السلاسل النصية / النصوص في لغة البايثون """ print("السلاسل النصية / النصوص في لغة البايثون") print('Hello World') # ' ' print("Hello World") # " " print("--------------------------") # تعريف متغير يخزّن فيه نص print("تعريف متغير يخزّن فيه نص ") text = "Welcom To Python Lessons" print(text) print("----...
f43e3272487abd1b74efbe0eac1dc22d3baa8ffb
vnayak187/cisco_prep
/tuesday/dateDiff.py
848
4.21875
4
import datetime as dt #function for finding time difference def dateTimeDiff(time1, time2): time1 = dt.datetime.strptime(time1, '%d/%m/%Y %H:%M:%S') print (time1) time2 = dt.datetime.strptime(time2, '%d/%m/%Y %H:%M:%S') print (time2) res = '' if time1 > time2: res = time1 - time2 else: res ...
c1f971983507679ee308aea9b97559263a91f8d1
sathibabunaidu58/Pytno_Problems
/method.py
323
3.875
4
def method(a,b): print('incremented value') result=0 for i in range(a): result+=i print(result) sum=b print('decremented values') for j in range(b): sum-=1 print(sum) a=int(input('entern value for increment: ')) b=int(input('enter value for decrement: ')) method(a...
146eba43dced8a5af52437720338e40e04136bd2
enxicui/Python
/PythonAssignments/p5/p5p1.py
92
4.1875
4
x=int(input('please input your integer:',)) if x<0: print("This is a negative number.")
dcb9695870c2c8a0c069441eaf374af5a3d46d84
vishalpatil0/Python-cwh-
/Tkinter Course/Image Label.py
715
4
4
from tkinter import * #importing all classes and methods from tkinter package root=Tk() #creating instance of TK() class it aslo creates basic gui #gui logic here root.geometry("700x500") #width X height root.minsize(200,80) #can't minimize it more than this size r...
d6ac8aebf5b754ca515eade3ce4e6afc0ec3fd1b
gatordevin/ActionPotentialAnalysis
/utils.py
3,901
3.78125
4
#IMPORT REQUIRED PACKAGES import csv import random import numpy as np from sklearn.preprocessing import MinMaxScaler #READ IN DATA FROM CSV def read_data(file_name): with open(file_name, 'r') as data_file: #Open CSV data file data_csv = csv.reader(data_file) #Read CSV data file to a varaible data_c...
76b7732e21350d7d9f0407920b645d0553a3df80
eduardogomezvidela/Summer-Intro
/6 Functions/poly_circle.py
837
4.28125
4
#polygon and circle import turtle def drawPolygon(t, sideLength, numSides): #Define polygon turnAngle = 360 / numSides for i in range(numSides): t.forward(sideLength) t.right(turnAngle) def drawCircle(anyTurtle, radius): #Define circle using polygon anyTurtle.b...
6d5f31a4d62c0d31a05bc59ea12e38415b6638bd
edsakamoto/python-guanabara
/mundo02/ex067.py
638
4.0625
4
# faça um programa que mostre a tabuada de varios numeros, um de cada vez, para cada valor digitado pelo usuario. O programa será interrompido quando o numero solicitado for negativo n = 0 #contador = 0 contador_tabuada = 0 #n = int(input('Digite o número da tabuada que gostaria de visualizar (digite numero negativo pa...
6d0f7fc6d9c405c6e63b134039bf5d7a66d942d2
AlexYangLong/Foundations-of-Python
/day016-day020/day016/graps-text.py
1,859
3.75
4
import random def main(): num_list = [1, 2, 3, 4, 5, 6] computer_bet = 100 player_bet = 100 flag = True while True: # computer_stake = int(input('请电脑输入赌注:')) # 这里还需要判断一下 player_stake = int(input('请玩家输入赌注:')) computer_stake = player_stake graps1 = random.c...
03d24df2c266584004ee3a5417a3b2bdcfecc5da
KeithPallo/independent_coursework
/1 - MOOC - Intro to CS & Programming/Problem Set 1/ps1_problem_2.py
632
4.5
4
# Prints the number of times a substring appears in string 's' # The target substring is "bob" # Defines a string 's' s = 'pobboboobobbobobbbobobbobbbybx' # Creates a substring to search for within larger string 's' find = 'bob' # Function to count the number of times a substring appears in a string def count_subs...
215ccc4c20e4cb432d2424f9bef513a70aa87ba2
emanmacario/dsa
/ctci-solutions/ch-04-trees-and-graphs/08-first-common-ancestor.py
2,832
4.03125
4
# First Common Ancestor: Design an algorithm and write code to find the first # common ancestor of two nodes in a binary tree. Avoid storing additional nodes # in a data structure. NOTE: This is not necessarily a binary search tree. # Hints: #70, #76, #28, #36, #46, #70, #80, #96 # From EPI: # Any two nodes in a bi...
3f33aefd47d84b1be366d6c9df9008d54db2d595
harshal1596/python-practices
/dictionaries_ops.py
1,138
4.34375
4
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } # Get values in the dict print(len(thisdict)) print(thisdict.get('model')) print(thisdict.keys()) print(thisdict.values()) print(thisdict.items()) # Insert item in the dict thisdict["colour"] = 'Red' print(thisdict) # Update an item thisdict["col...
20940371fc786be278790f1e129487ed65daf8f7
ALMTC/Logica-de-programacao
/TD/33.py
1,397
3.921875
4
print 'Digite os 4 valores' a = input() b = input() c = input() d = input() print 'Em ordem crescente' if a < b and a < c and a < d: print a if b < a and b < c and b < d: print b if c < a and c < b and c < d: print c if d < a and d < b and d < c: print d if b < a < c < d or b < a < d < c o...
506b3cb37f1280f392df5e61eec0fd7cd573a224
charlieb954/code_snippets
/python/abstraction_syntax.py
1,146
4.21875
4
from abc import abstractmethod, ABC class Toyota(ABC): def __init__(self, engine_size, colour): self.engine_size = engine_size self.colour = colour @abstractmethod def drive(self): pass def stop(self): return "Car is stopping" class Yaris(Toyota): def __init__(...
418380ff4ef9bc985656256aef41de289057f5b5
chuanyedadiao/Python-Practice
/course/5/5-9.py
334
3.90625
4
username = ['chuanye','xiaozhong','zhouxiang','xiaocui','admin'] if username: for user in username: if user == 'admin': print('Hello admin,would you like to see a status report?') else : print('Hello '+user+' ,thank you for logging in again') else: print('We need to find...
1d2693d18cedde939941ffd5ecc67faff41771c1
glock3/Learning-
/Alexey/Text/check_if_palindrome/main/check_if_palindrome.py
376
3.96875
4
import re def main(): sentence = int(input("Please input your sentence: ")) print(check_if_palindrome(sentence)) def check_if_palindrome(sentence): sentence = re.sub(r'[^\w]', '', sentence).lower() reversed_value = sentence[::-1] if sentence == reversed_value: return True else: ...
4157843053890acadc337e4cb0c2e8a1fde94aab
Antrikshhii17/myPythonProjects
/DataStructure_Algorithm/Rotate_array.py
725
4.1875
4
""" Program to rotate array K times in anti-clockwise direction if Dir = 'A' or in clockwise direction if the Dir = 'C'. A is the input array. From Numerator coding interview for Data Engineer """ def rotateKtimes(N, A, Dir, K): for v in range(K): rotateArray(N, A, Dir) def rotateArray(N, A, Dir): # Rotating t...
c98148d7ebc9ea4ef18a104c316b1a9c5f690b82
slothman5566/TDDPractice
/32. Longest Valid Parentheses/test.py
1,011
3.703125
4
import unittest from main import Solution class ExampleCase(unittest.TestCase): def setUp(self): self.testObject=Solution() def test_case_1(self): input= "(()" target=2 self.assertEqual(target,self.testObject.longestValidParentheses(input),"The longest valid parentheses su...
1f314e3c30d911091dcd8a678e18cd9bf8636fe0
karan10/Top-10-algorithms
/Graph/dfs.py
800
3.75
4
# link - http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph/ from collections import defaultdict class DFS: def __init__(self): self.graph = defaultdict(list) def create_edge(self, u, v): self.graph[u].append(v) def __dfs_traverse(self, n, visited): visited[n] = Tru...
f6322aa9582d0337925e773934a06402db5ead30
LukeBreezy/Python3_Curso_Em_Video
/Aula 21/ex103.py
344
3.796875
4
# =-=-=-= FUNÇÕES =-=-=-= def ficha(nome, pts): if nome == '': nome = '<desconhecido>' if pts == '' or pts.isnumeric() is False: pts = 0 return f'O jogador {nome} fez {pts} ponto(s) no torneio.' nome = input('Nome do jogador: ') pts = input('Quantidade de pontos: ') infos = ficha(no...
bf41dfc536b11ab13b16eb411256344d2e3f1b40
SnehalSutar9823/PythonAssignments-Marvellous
/Assignment6_1.py
493
4.15625
4
def PositiveOrNegative(NO): if NO>0: return "TRUE" elif NO==0: return "ZERO" else: return "FALSE" def main(): num=int(input("Enter number")) ans=PositiveOrNegative(num) if ans=="TRUE": print("{} is Positive Number".format(num)) elif ans=="ZERO"...
56be07225ffcd151361b1a6554e0098838c8abde
aashishravindran/interview_prep
/puthon_files/binaryTreeZigZagLevelOrderTraversal.py
1,138
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 # 103. Binary Tree Zigzag Level Order Traversal # https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/submissions/ class Solution(o...
7c05fbaf896605ac79287cd518dc599b36b46688
RuslanYu/ry
/ReversString.py
150
3.890625
4
# -*- coding: utf-8 -*- """ Created on Wed May 23 01:15:27 2018 @author: Ruslan """ x = input('enter any string: ') x = x[-1::-1] print(x)
7cc2db8fbda45039e01cdd8fa913a466aceaee5e
oliviaspark0825/TIL
/algorithm/PycharmProjects/0128/연습3_bruteforce.py
1,529
3.71875
4
# find 구현 p = "is" t = "this is a book. this is a computer" m = len(p) j n = len(t) i def bruteForce(p, t): i = 0 # t의 인덱스 j = 0 # p의 인덱스 check_list = [] while j < m and i < n: if t[i] != p[j]: i = i - j j = -1 i = i + 1 # 다음 인덱스 확인해야하니까 하나씩 증가 j = j + 1...
8ae5636c498c72c11bdf4fbb48e9ab7ef77f1978
sraisty/hb_guessinggame
/game.py
3,518
4.09375
4
"""A number-guessing game.""" from random import randint def getNum(prompt, start=None, end=None): try: num=int(input(prompt)) except ValueError: print("Invalid number.") num = None if start is not None: if num < start: print ("Number must be greater than {}".fo...
9243207b661496400a9fb0382aefabe3da95154b
himanshu8426/python-assignment
/13.py
517
4.34375
4
""" PROGRAM ---13--- The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list ...
0a45e1c048156201693f7934c65671bef5546894
nfredrik/pyjunk
/Games/Roulette/test_bin.py
807
3.65625
4
import unittest from bin import Bin from outcome import Outcome class TestBin(unittest.TestCase): def setUp(self): self.first = Outcome('one', 17) self.second = Outcome('one', 17) self.third = Outcome('two', 32) self.fbin = Bin(self.first) self.sbin = Bin(self.second) ...
e0335b444e244d599a66c5f6814a42bfbe452030
anaelleadhoute/Python_Uni
/ex (5).py
5,360
3.96875
4
''' Exercise #5. Python for Engineers.''' ######################################### # Question 1 - do not delete this comment ######################################### def sum_nums(file): f = open(file, 'r') lst = f.readlines()[0].split(' ') num = 0 for n in lst: num += int(n) ...
35413179904f92e595d84249845b4ce271d95810
AdamZhouSE/pythonHomework
/Code/CodeRecords/2934/60638/287764.py
859
3.5625
4
def block(string, res): i=0 while i<len(string): if string[i] != '[': res = res + string[i] else: i = i + 1 temp = '' num = '' while string[i] >= '0' and string[i] <= '9': num = num + string[i] i = i + 1 ...
3c902d0b5c2ffb2570ae09ec237824fc874ae223
ivovilar1/exercicios
/ex027.py
217
3.828125
4
nome = input('Digite seu nome completo:').strip() lista = nome.split() print('Muito prazer em te conhecer!') print('Seu primeiro nome é {}'.format(lista[0])) print('Seu ultimo nome é {}'.format(lista[len(lista)-1]))
e0a74db90ef741effeb8b0e61f3231e29f693ae8
tonysyu/yutils
/yutils/mpl/_coll.py
3,342
3.5
4
""" Matplotlib's patch collections are sized by pts instead of data sizes. The collections implemented have sizes based on data. In addition, these sizes are specified by some linear dimension (e.g. radius or width)---in contrast to Matplotlib collections, which use areas to size patches. """ import numpy as np from m...
2cb37b70ea50f5f6dc54a4f87d33cb7b8408b226
mfitzp/qna
/28797498.py
1,596
4.3125
4
import random import time def display_grid(grid): #Task 2. Making the random words into a 3x3 grid grid = [words[i:i + 3] for i in range(0, len(words), 3)] for x,y,z in grid: print("%s %s %s" % (x.rjust(10), y.rjust(10), z.rjust(10)) ) def clear_screen(): print("\n"*1000000) #importing th...
f8576b094f7f0676433b035d8630f2a64477eb85
Huitzoo/Rosalind_Bioinformatics
/rabbits.py
299
3.671875
4
def main(): months = int(input('Enter the months')) litters = int(input('Enter the number of litters')) fibo = [1,1] if months <= 2: print('1') else: for i in range(2,months): fibo.append(litters*fibo[i-2]+fibo[i-1]) print(fibo) main()
5579af152b6eb684e8c80dc7794073838545dc5e
coderRPN/python-first-project
/strings.py
400
4.125
4
first_name = "prabhdeep" last_name = "singh" first_name = "modified" age = 30 is_male = True first_name = first_name.upper() print("First name is: \n \"" + first_name) print("Last name is: " + last_name) print(age) print(is_male) print(first_name.isupper()) print(len(first_name + last_name)) print(first_name[4].low...