blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
36d59d8a1a2efc18dba383797d90efbbf4bed1ee
thecoderarnav/C-98
/counting.py
340
4.28125
4
def countingwords(): fileName = input("ENTER FILE NAME") numberofcharacters = 0 file= open(fileName,"r") for line in file: data = file.read() #words = line.split() numberofcharacters = len(data) print ("Number of Characters") print(numberofcharacters) countingw...
a5d866d250308eeb1265a014c72e483058d6ea60
sne21star/404_ECE
/Homework6/solve_pRoot.py
913
3.546875
4
# Author: Tanmay Prakash # tprakash at purdue dot edu # Solve x^p = y for x # for integer values of x, y, p # Provides greater precision than x = pow(y,1.0/p) # Example: # >>> x = solve_pRoot(3,64) # >>> x # 4L import numpy as np import sys def solve_pRoot(p,y): p = int(p); y = int(y); # Initial g...
694cce2aef12b4ab45adc3caf1412a605df71fd0
chyidl/leetcode
/0036-valid-sudoku/valid-sudoku.py
2,614
3.65625
4
# Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: # # # Each row must contain the digits 1-9 without repetition. # Each column must contain the digits 1-9 without repetition. # Each of the nine 3 x 3 sub-boxes of the grid must contain the digit...
bcd2e33743c0415435f74f87b1c32ba9f3450e72
chyidl/leetcode
/0098-validate-binary-search-tree/validate-binary-search-tree.py
1,442
4.21875
4
# Given the root of a binary tree, determine if it is a valid binary search tree (BST). # # A valid BST is defined as follows: # # # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the l...
c77b48ed09ba00a5630ed11084638227ceadfe9f
chyidl/leetcode
/0102-binary-tree-level-order-traversal/binary-tree-level-order-traversal.py
1,800
3.890625
4
# Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). # #   # Example 1: # # # Input: root = [3,9,20,null,null,15,7] # Output: [[3],[9,20],[15,7]] # # # Example 2: # # # Input: root = [1] # Output: [[1]] # # # Example 3: # # # Input: root =...
430313f5df362d73c724145c87023fae43a7e591
TJBrunson/War
/deck.py
1,018
3.984375
4
import random from enum import Enum class Suits(Enum): Spades = 'Spades' Hearts = 'Hearts' Diamonds = 'Diamonds' Clubs = 'Clubs' class Deck: CARD_RANKS = ( '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', ...
e7df3aa457b5bdcfa8b0e8c35b431f31313c886e
septos/learnpython
/sets.py
705
4.21875
4
''' Sets 1.Unordered 2.Unindexed 3.newset = {orange,banana,fig} ''' new_fruits = {"lemon","fig","cherry"} print(new_fruits) print("-------------------------------------------------------------------------------") #for loop for x in new_fruits: print(x) print("------------------------------------------------------...
dcdb9d564f7f0fff26cfc8c7d37398576bf2a86a
bahtiyar05/python
/week2/Fibonnachi_nomer.py
302
3.53125
4
n = int(input()) f0 = 0 f1 = 1 chislo = -1 if n == 0: chislo = 1 elif n == 1: chislo = 2 elif n == 2: chislo = 3 else: k = 2 while k <= n: fn = f0 + f1 f0 = f1 f1 = fn if fn == n: chislo = k break k += 1 print(chislo)
01dca89b12be0d7518944bcade9db3b0f0095461
bahtiyar05/python
/week1/ex1.py
288
3.859375
4
def sum(a,b): '''(number,number) ->number Returns sum of two numbers ''' return a+b def convert_to_celsius(fahrenheit): '''(number)-> number >>>convert_to_celsius(32) 0 >>>convert_to_celsius(212) 100 ''' return (fahrenheit - 32 )* 5 / 9
7c98486847b47e5ccc05bccf113837005da19022
SahithiAmmana/Group2_HW1
/code/calculator.py
445
3.984375
4
#Simple Calculctor #Adds two numbers def addition(a,b): return a+b #Subtracts second number from the first def subtraction(a,b): return a-b #Multiplies two numbers def multiplication(a,b): return a*b #Divides first number by second def division(a,b): if b==0: return "Enter non-zero divisor" ...
0c86d4054540cd57ec6410f2bc092a1a2efe8246
PragmaticPhil/microbitDataGatherer
/data_MAcollector.py
3,318
4.09375
4
from microbit import * accReadingList = [] # This is a list - we will add each accelerometer reading we take to this list. totalNumberOfReadings = 150 # The code is limited to 150 data points - a few more is possible but there is an upper limit numberOfReadings = 0 # I don't use a ...
2b5622feb42582bdd45a2721a436442859e9aca7
SarathVakacharla/collisions
/ball.py
1,555
3.53125
4
import pygame import math import random from pygame.event import post from constants import * from util import * # Define a Ball object by extending pygame.sprite.Sprite class Ball(pygame.sprite.Sprite): def __init__(self, id, radius, pos=None, angle=None): super(Ball, self).__init__() self.id = id self.radius ...
b7af68c5a67678237aca4c7b48887154c5bab6a2
dpsholtes/AlgorithmProjects
/BSTRBT.py
8,491
3.84375
4
#Code by Dylan Sholtes #Binary Search Tree and Red-Black Tree searching #timing module import time import decimal #Node Class class Node(): def __init__(self, key): self.key = key self.parent = None self.left = None self.right = None class BinarySearchTree(): #On creation of the...
cc005a0ef1478af5a04abd97e248b06bb1e883ee
jasmine2018jixun/leetcode2020
/leetcode2019/lintcode_159_寻找旋转排序数组中的最小值.py
304
3.640625
4
class Solution: """ @param nums: a rotated sorted array @return: the minimum number in the array """ def findMin(self, nums): # write your code here for i in range(1, len(nums)): if nums[i] < nums[i-1]: return nums[i] return nums[0]
2157c758adaa8daf5a7b2a691e2aa4c112c2f290
jasmine2018jixun/leetcode2020
/leetcode2019/lintcode_111_爬楼梯.py
456
3.90625
4
class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): # write your code here if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 2 elif n == 3: return 3 else...
cb41f0ef61bbfb407f6b1a4f51cbcb11bc7c9e51
jasmine2018jixun/leetcode2020
/leetcode2019/leetcode129_求根到叶子节点数字之和.py
743
3.640625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumNumbers(self, root: TreeNode) -> int: if not root: return 0 res = 0 mystack = [(root, [root.va...
cc464e5eb16247b68b97e1f4c6b230fdfd1ec00e
jasmine2018jixun/leetcode2020
/leetcode2019/leetcode257_二叉树的所有路径.py
800
3.734375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: res = [] if not root: return res mystack = [(...
97cbc3370c1b648bb827f9c3dc2a800ccd76267e
learning-laboratory/cursos
/python/curso-em-video/exercicios/exercicio_041.py
430
4.0625
4
import datetime print('Federacao Nacional de Natacao') print('Detector de categoria') anoDeNascimento = int(input('\nAno de nascimento: ')) idade = datetime.date.today().year - anoDeNascimento if idade <= 9: print('Categoria: Iniciante') elif idade <= 14: print('Categoria: Infantil') elif idade <= 19: pr...
cc07597f388494ccc4065cb65cbd38f1cd546182
learning-laboratory/cursos
/python/open-source-it/content/learning_pages_84_193.py
3,300
3.8125
4
import datetime as dt #import dateutil #Python all in one Dummies # print(dt.date.today()) # print(f'{dt.date.today():%A, %B, %C, %D}') # print(f'{dt.date.today():%date/%m/%Y}') # print(dt.time()) # new_years_day = dt.date(2021, 1, 1) # duration = dt.timedelta(days=140) # print(new_years_day + duration) # start_time...
81a03cfdb9a4d88e8ad179c7b7d357a34a08e02d
learning-laboratory/cursos
/python/open-source-it/pratice/exercise_03.py
370
4.125
4
age = int(input('Age: ')) gender = input('Genger[M/F]: ') gender = gender.upper() if age < 18: if gender == 'M': print('son') else: print('daughter') elif 18 <= age < 65: if gender == 'M': print('father') else: print('mother') else: if gender == 'M': print('gr...
93f84164fc76a158a1d9f7f455848e12129df48b
learning-laboratory/cursos
/python/curso-em-video/exercicios/exercicio_071.py
582
3.984375
4
print(">> Notas disponiveis <<") print("50 MZN >> 20 MZN >> 10 MZN >> 1 MZN\n") valueOfWithdrew = float(input("Digite o valor de levantamento: ")) notesOfFifty = valueOfWithdrew // 50 notesOfTwenty = valueOfWithdrew // 20 notesOfTen = valueOfWithdrew // 10 notesOfOne = valueOfWithdrew // 1 print("O caixa ira retira...
35139818e12d75c3ec591a84492b893073d57ce9
learning-laboratory/cursos
/python/curso-em-video/aulas/Mundo 01/aula_06_tipo_permitivos_b.py
350
3.8125
4
n = input('Value: ') print('float {}'.format(n)) print('bool {}'.format(n)) print('int {}'.format(n)) print('str {}'.format(n)) print('IS NUMERIC {}'.format(n.isnumeric())) print('IS DECIMAL {}'.format(n.isdecimal())) print('IS LOWER {}'.format(n.islower())) # Existem diversas funcoes que identifica o seu tipo/estado/v...
154e04cc28a18947938a9efd32bf3a0697619f41
learning-laboratory/cursos
/python/curso-em-video/exercicios/exercicio_066.py
206
3.90625
4
counter = sum = 0 while True: number = int(input('Enter a number: ')) if number == 999: break sum += number counter += 1 print(f"Numbers {counter}") print(f'Sum {sum}') print('END')
4a7a090019680ae882f86c8fb579887d4b223ad4
learning-laboratory/cursos
/python/curso-em-video/exercicios/exercicio_032.py
215
3.671875
4
from datetime import date year = date.today().year #int(input('Type a year:')) answer = 'Bissexto' if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 else 'Comum' print('{} é um ano {}'.format(year, answer))
50592028f2d92043765e78c9f7bca5bc8392c288
learning-laboratory/cursos
/python/curso-em-video/aulas/Mundo 02/aula_014_estr_repeticao_while.py
408
3.859375
4
# counter = 1 # while counter < 10: # print('>> {}'.format(counter)) # counter += 1 # n = 1 # sum = 0 # while n != 0: # n = int(input('Digite um valor: ')) # sum += n # # print(sum) number = 1 par = impar = 0 while number != 0: number = int(input('Enter a number:')) if number % 2 == 0: ...
11f33082d7fc3e6c5494b671ad3f94b38348750c
learning-laboratory/cursos
/python/curso-em-video/exercicios/exercicio_043.py
450
3.828125
4
print('INDICE DE MASSA CORPORAL\n') peso = float(input('Peso: ')) altura = float(input('Altura: ')) indiceMassaCorporal = peso / altura ** 2 print('IMC: {}'.format(indiceMassaCorporal)) if indiceMassaCorporal < 18.5: print('Abaixo do Peso.') elif indiceMassaCorporal <= 25: print('Peso Ideal') elif indiceMassa...
5cb9653b6ccab04298f33a0511c0702a203f6a10
learning-laboratory/cursos
/python/open-source-it/pratice/files02/Car.py
299
3.671875
4
class Car: def __init__(self, name, serie): self.name = name self.serie = serie def getName(self): return self.name def setName(self, name): self.name = name def data(self): print(f'Name: {self.name}') print(f'Serie: {self.serie}')
c2b186a89d5f63e9e597d2a5fd782d16f5ab6489
TPSGrzegorz/PyCharmStart
/KodolamaczKurs/Prace domowe/Datetime_Time_Deltas.py
978
3.6875
4
from datetime import datetime, timedelta, date def duration(dt): years, seconds = divmod(dt.total_seconds(), YEAR) months, seconds = divmod(seconds, MONTH) days, seconds = divmod(seconds, DAY) hours, seconds = divmod(dt.seconds, HOUR) minutes, seconds = divmod(seconds, MINUTE) return { ...
0eb1fb1f8a0413b35aacb14762f62ba20ce6e987
TPSGrzegorz/PyCharmStart
/Kaggle/Exercise_Working_with_External_Libraries.py
1,951
4
4
def blackjack_hand_greater_than(hand_1: list, hand_2: list): """ Return True if hand_1 beats hand_2, and False otherwise. In order for hand_1 to beat hand_2 the following must be true: - The total of hand_1 must not exceed 21 - The total of hand_1 must exceed the total of hand_2 OR hand_2's total m...
9015ff024f1fe196251084963b1648d9698743ce
TPSGrzegorz/PyCharmStart
/KodolamaczKurs/Prace domowe/function_doctest_temperature.py
929
3.75
4
# Function Doctest Temperature # sorce: https://python.astrotech.io/basics/function/doctest.html#function-doctest-temperature def celsius_to_kelvin(degrees): """ >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(1) 274.15 >>> celsius_to_kelvin(-1) 272.15 >>> celsius_to_kelvin('a') ...
b41eda9c8fc780a99da12561f0d9322c216ef98f
TPSGrzegorz/PyCharmStart
/KodolamaczKurs/Prace domowe/OOP_Stringify_Nested.py
1,239
3.734375
4
class Crew: def __init__(self, members=()): self.members = list(members) def __str__(self): return '\n'.join([str(x) for x in self.members]) class Astronaut: def __init__(self, name, experience=()): self.name = name self.experience = list(experience) def __str__(self...
0aee81d237aa32fd1974a78a09f77a0798062c02
jdn5126/AoC2017
/day7/day7.py
3,738
3.9375
4
# Recursive Circuits import sys class Node: def __init__(self, name, weight, children=None, parent=None): self.name = name self.weight = weight if children: self.children = children else: self.children = [] self.parent = parent # Each node sto...
6888d431ef961b7c589e364bb1ff034aafd414cd
KungoJung/Cheetcode-Study-Prep-March-2021
/Luxmi/valid_palidrome.py
1,331
3.8125
4
class Solution(object): def isPalindrome1(self, s): """ :type s: str :rtype: bool """ lower_s = s.lower() l = len(lower_s) i = 0 j = l - 1 while(i<j): while(i<j and not lower_s[i].isalnum()): i = i+1 ...
f96936d3f45f3bd09850753959e5307f6665b5af
pegu1shekhar/jango
/spy_details.py
701
3.515625
4
#use this "lewis" and "1234" in user-name and password loginun="lewis" #variable taken loginps="1234" def details(): while 1 == 1: print "Enter your username:" # created username logi = raw_input() if logi==loginun: print "Enter your password:" # cr...
9b1fb9a5bf0592e7fa8ffd4ddc98f6f898c5580a
mdp-toolkit/mdp-docs
/source/examples/bimdp_examples/bimdp_simple_coroutine.py
968
3.5625
4
""" A minimal example for the bimdp coroutine decorator. """ import numpy as np import bimdp class SimpleCoroutineNode(bimdp.nodes.IdentityBiNode): # the arg ["b"] means that that the signature will be (x, b) @bimdp.binode_coroutine(["b"]) def _execute(self, x, n_iterations): """Gather all t...
758f34aaa9f494efaf867de84f7f1347204894af
mdp-toolkit/mdp-docs
/source/examples/backpropagation/perceptron.py
4,590
3.921875
4
""" Nodes for a multilayer perceptron with batch backpropagation learning. Formulas: ========= The vector and matrix indices are dropped. l = 1,..,n layer index x_0 : input x_l : output of layer l t : target output, ideally x_n = t W_l : weight matrix s : activation function s(x) = 1 / (1 + e^{-c*x}) with derivat...
c8786ff40c20ceac31b461dfdacf0c40f57137ee
otienonick/password_locker
/user.py
1,062
4
4
class User: """ Class that generates new instances of Users. """ def __init__(self,username,password): self.username = username self.password = password user_list = [] # Empty user list def save_user(self): ''' This method saves User objects i...
b181aed0ba232125420ab3dfa5a3d484f37a8bb0
ankurjaiswal496/Leetcode-Solutions
/problems-tab/lc367.py
358
3.546875
4
# class Solution(object): # def isPerfectSquare(self, num): # """ # :type num: int # :rtype: bool # """ # import math # x=int(math.sqrt(num)) # return (x*x) == num # obj=Solution() # print (obj.isPerfectSquare(14)) # b="abbc" # a=list(b) # pr...
e926d5b9a9f8e73cf5e0277853d7414fee12a5dc
navaneeth2324/256637_DailyCommits
/secondsmallest.py
245
4.1875
4
# Write a Python program to find the second smallest number in a list list=[] n=int(input("Size of list : ")) for i in range(0,n): item=int(input()) list.append(item) print("List : ",list) list.sort() print("Second Smallest :",list[1])
fe7fe216b2287feb3e059218d4bcfa5c4d47e986
alhart2015/mlb-rankings
/utils/stat_scraper.py
3,365
3.828125
4
""" I've always wanted to write something that scraped stuff from the internet daily, so here we go. This'll (hopefully) go to the MLB GameDay API and pull stuff down for that day. Currently this is able to pull the full scoreboard for any given day. There's a lot more info that can be pulled, it'll just take work. A ...
46723d520112a62babda6ec75b0d424fd162dd65
raamcoumar/CS50x
/Week 6 - Python/PSET6/hello.py
297
3.90625
4
def main(): while True: # Keep prompting for input untill valid try: name = input("What is your name?\n") if len(name) > 0: break except ValueError: pass print ("hello, "+name) if __name__ == "__main__": main()
e4f22d5139a52b390d72f9cd5290a8cd76d3558f
akhil21/QeX
/driver/histogram.py
890
3.59375
4
import numpy as np def normalize_histogram(histogram): """Devide the elements of the histogram with the sum of the elements Args: histogram (dict): population of the histogram before normalization Returns: histogram (dict): population of the histogram after normalization """ total =...
2c7f55a161747f33675e72d3d60d4464640521a2
Michal-Kok/WAR2021
/python tasks/chris.py
813
4.25
4
def name_in_str(sentence, name): return """ Simple as that, your task is to find name within given sentence, like in the example: Across the rivers. --- chris c h ri s Make it case sensitive. Letters must appear in the right order. """ assert name_in_str("Across the rivers", "chris") is True assert n...
7619a3e0784b7e68a12780f2c9bc529263413d80
SmartPracticeschool/llSPS-INT-1605-Predicting-Life-Expectancy-using-Machine-Learning
/life.py
3,666
3.65625
4
# Predicting Life expectancy # Import Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from math import sqrt import statsmodels.api as sm from scipy import stats from sklearn import metrics...
bf54d207b3862fe08cfc3a2739f8c0a268fd90c2
uktrade/icms
/web/utils/currency.py
316
3.796875
4
# TODO: Revisit this when we know how to calculate it. def get_euro_exchange_rate() -> float: return 1.11 def convert_gbp_to_euro(value_gbp: int) -> int: """Convert GBP to euros to the nearest euro.""" exchange_rate = get_euro_exchange_rate() return round(value_gbp * exchange_rate, ndigits=None)
e5852aaa0171d91f5fd51c6bfbb23c0e90831a1e
typernotypey/Gcoin
/genGraph.py
411
3.640625
4
import matplotlib.pyplot as plt import os def makePlot(): plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.savefig('d:\\xampp\\htdocs\\Gcoin\\graph.png') def deletePlot(): os.remove("d:\\xampp\\htdocs\\Gcoin\\graph.png") if(os.path.exists("d:\\xampp\\htdocs\\Gcoin\\graph.png")): deletePlot() ...
325242e1cb300102f65fb9adf98cf0c57062a52c
kosoviankrossover/some_code
/python/dfs.py
1,946
4
4
''' An n-by-n matrix codes for the relationship dynamics among n people. A value of 1 for element i,j in the matrix tells us that person i and person j are friends. Friendship edges are bidirectional. Thus, element i,j in the matrix will match element j,i. A person is always friends with themself. This sll means the...
d473b5b104272d2ddf85c9c7ee72fbb100a0b65f
Niqole-zhao/starting
/lib.py
2,202
3.8125
4
import time #打开time 库的入口 # time.time() #ctrl # lctime=time.localtime()#使用time库里面的localtime 这一方法 # first_time=time.time() # a=0 # for i in range(1000): # a +=1 # print(a) # last_time=time.time() # print(last_time-first_time) # print(time.gmtime()) #用户不能直接使用gmtime,gmtime获取的是世界统一时间,不是当地时间 # print(time....
dab1a151941d9876a5a012ab67f3b84d8d8eec1f
Niqole-zhao/starting
/work_28.py
637
3.9375
4
"""球的弹跳距离""" # flow=float(input("请输入初始高度(即球下落高度):")) # times=int(input("允许球弹跳次数:")) # d=0 # rate=0.6 # if times>=0: # for s in range(0,times): # d +=flow+flow*rate**times # print("球的弹跳距离是",d) def bounce_height_recursion(h,n,rate=0.6): d=0 if n >= 0: for s in range(0,n): ...
6f0850b6afae590cc516fedee6e6cfcfca23cf2c
Niqole-zhao/starting
/oct_29.py
498
3.640625
4
"""插入排序""" import random import time a=time.time() def insert_sort(li): for i in range(1,len(li)): #i表示摸到的牌的下标 tmp = li[i] j = i - 1 #j指的是手里的牌的下标 while j >= 0 and li[j] > tmp: li[j+1] = li[j] j -= 1 li[j+1] = tmp li = list(range(1000)) random....
d99768098dddb7049cf278ea2e4268e52bcede46
Niqole-zhao/starting
/firt1.py
426
3.703125
4
"""验证两次输入密码是否相等""" # first=input("") # second=input("") # if first==second: # print("same") # else: # print("different") """小乐乐坐电梯,前面n人""" # n=int(input()) # a=str((n+1)//12) # b=str((n+1)%12) # if b==0: # print(a) # else: # print(a+1) n=int(input()) a=n//12 if (n+1)%12 and a>0: ...
388479f26bdbaf73997fd3685d4f270d938c6dde
elOXXO/Tarea_03
/Datosdeunaesfera.py
1,489
3.828125
4
#Encoding: UTF-8 #Autor: Alberto López Reyes '''Descripción: Este programa calcula e imprime el radio, diámetro, volúmen, y área de una esfera al ser otorgado el radio de dicha figura.''' import math #Esta función calcula el díametro de la esfera al recibir el radio de la figura. def calcularDiámetro(fltRadio): ...
0f670947cddf2319081e8284760ce29622dce959
vonhraban/exif-concurrency-mapper
/gps_coordinates/writer.py
862
3.734375
4
import json """This modules writes the coordinates to the external JSON file so that they can be displayed by google maps """ FILENAME = "../static/markers.json" class Writer: def as_geojson(self, coordinates): data = { "type": "FeatureCollection", "features": [] } ...
7a7d6f5ddf7187128c91c3099c1c139749bc045f
AMN74/CS0008-f2016
/f2016_cs8_AMN74_a3/f2016_cs8_AMN74_a3.py
9,493
3.875
4
#CS 0008 – Fall 2016 Assignment #3 Due: 2016/11/18 #CS 0008 - Introduction to programming with Python #Fall 2016 #Assignment #3 #Available: 2016/11/15. Due: 2016/11/18 before midnight. #Students are to write a python program that address the problem describe below under the description #section. #Students will need to ...
0273aa9ea9cb6742095528de7c9ca6260ce34aa7
ScottYijun/pythonLearn
/BeginningPython/chapter01/importModule.py
433
3.59375
4
#导入模块 import math import cmath #复数模块 print("math.floor(32.9) = ", math.floor(32.9))#向下取整 print("int(32.9) = ", int(32.9))#取整 print("math.ceil(32.3) = ", math.ceil(32.3))#向上取整 print("math.ceil(32) = ", math.ceil(32))#向上取整 print("math.sqrt(9) = ", math.sqrt(9))#平方根 print("cmath.sqrt(-1) = ", cmath.sqrt(-1))#平方根 print("...
80576efe7740e1077e259f2caeb47e71647e1df1
ScottYijun/pythonLearn
/BeginningPython/chapter01/built-inFunctions.py
194
4.28125
4
#内置函数 #pow函数 print("pow(2,3) = ", pow(2, 3)) print("10 + pow(2, 3 * 5) / 3.0 = ", 10 + pow(2, 3 * 5) / 3.0) print("abs(-10) = ", abs(-10)) print("round(2 / 3) = ", round(2 / 3))
72fcc81cf6dc3e7e6e8994b445444b01c4b7e772
ufo1112/py_lab
/aver_num.py
126
3.96875
4
s = 0 n = int(input("n: ")) for x in range(1, n+1): a = float(input("%d: "%(x))) s += a print("average: %d"%(s/n))
d61398370b5c42ca516b335cc01818261aeb5e95
candlewill/Algorithms
/18.bracket_match.py
785
3.828125
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): ...
5a3ce7ce8c7427dc80261fba539a513b995de923
ritikkh/competative_programming
/primality_test.py
653
3.71875
4
#O(n) def approach1(n): divcount = 0 for i in range(1, n+1): if n%i == 0: divcount+=1 #print(divcount) if divcount == 2: return True else: return False from math import * #O(root(n)) def approach2(n): if n==0 or n==1: return Fals...
8803c66a6c99aa6fa50d4d45984234f14b13f124
zzzzzzhang/CV_learn
/test_1.py
963
3.765625
4
# coding: utf-8 # 螺旋数组求任意数到1的曼哈顿距离 def getSteps(num): if num == 1: return 0 elif num < 1: print('{} is not an positive integer'.format(num)) return None else: i = 1 while (2*i - 1) **2 < num: i += 1 i -= 1 length = 2*i - 1 m...
447184fde0ae6446f1e5c7e633aa4f2cd9c28644
Bo-Y29/KNN-winequality
/knn.py
8,649
3.515625
4
from random import seed from random import randrange from csv import reader from collections import Counter import math import operator import numpy # Load a CSV file def load_csv(filename): file = open(filename, "rb") lines = reader(file,delimiter=';') headers = lines.next() dataset = lis...
90423a473e51e7288a7e20fe1696dbd589d9b99e
rushtang/exercise
/data_structure/array.py
1,119
3.90625
4
L=[1,"3",None,True,1.22,1,1] #查找元素的序列 L.index('3') #list遍历 for index,ele in enumerate(L): a=L[index] L.reverse() L.count(1) L.extend([1,2,3]) #方法有:初始化、插入、删除、查找、修改、出现次数计算、排序、反转、复制、清空、合并 #iterable的区别:序列和键值对 d={1:2,3:4}.items() ll=list(d) #链式储存,插入和删除效率高,适合用于队列和栈 from collections import deque #链式队列;入队、出队 cla...
b237e9da29896ffa0fee894b8d81d2cbb20bbec9
AndresNunezG/ejercicios_python_udemy
/ejercicio_16.py
570
4.34375
4
""" Ejericio 16. - Solicitar al usuario un texto o cadena de caracteres - Devolver en pantalla el texto de entrada al revés: Ej: Entrada: 'hola' Salida: 'aloh' """ #Solicitar texto al usuario print('Ingrese el texto a ser invertido!') texto = input('') #Invertir el texto #Método 1. texto_inv = te...
8412c6e7a97e1cd5507aa3c2c9d30b0bea0abc6f
AndresNunezG/ejercicios_python_udemy
/ejercicio_08.py
613
4.0625
4
""" Ejercicio 8. - Solicitar al usuario un número real 'a' - Solicitar al usuario un número 'b' entre 0 y 100 - El programa debe responder a la pregunta: ¿Cuál es el porcentaje 'b' del número 'a'? """ #Solicitar número 'a' num_a = float(input('Ingrese el número: ')) #Solicitar el porcentaje número...
532f64dd08995567502da578f2dd4a7825cc37a6
elizavetakrasova/homework_python
/hw3/Pr5.py
200
3.71875
4
list1=[1,2,3,3,4,4,5,5] def f1(list1): for i in set(list1): if list1.count(i)>1: print(i, "повторяется", list1.count(i), "раз(а)") print(set(list1)) f1(list1)
91e687653e92d33b05be135715cfd5f5fce1dc8b
elizavetakrasova/homework_python
/hw3/Pr8.py
626
3.59375
4
text = 'слово слово слово привет привет привет как как как о о о кек кек кек лол лол лол хей хей хей\ хоп хоп хоп дд дд дд ррр ррр ррр ло алао вало дыфоваа алооло' def f1(text): d={} a=[] for name in text.split(): d[name] = text.split().count(name) a = sorted(d.items(), key=lambda x:x[1], r...
759d8fb2947f56affb9c1ab13114a06fc5f1c3b2
MALARVIKRAM/Zenefits_15PT18
/Question2/inorder.py
177
3.953125
4
inp_str=raw_input() print inp_str for i in range(len(inp_str)): if inp_str[i]=='}': if int(inp_str[i-3])!=0: print int(inp_str[i-2])
50148c9f2452cfbbb4a2f0656b25136b881c33e6
dedyannacacau/projeto-poo
/Batalha.py
5,665
3.796875
4
from Funcionalidades import Funcionalidade from Personagem import Personagem from random import randint class Batalha(Funcionalidade, Personagem): def escolher_personagens(array, personagem_batalha): i = 0 print("\nselecione os personagens que irão participar da batalha, minimo de 2 personagens.\n...
f30b5b27c4377429a12848268221f21a5eec5ad2
dmitriyVasilievich1986/mail_parser
/search_dead_mail/Choices.py
2,574
3.625
4
# region import libraries from .IterClass import IterClass # endregion # region all choices classes class Choice: def __str__(self, *args, **kwargs): """The method returns a string representation of an instance of the class. Returns: str: a string representation of an instance of the ...
da7b1a806466b382002dfbf7576bc630bcb3cb90
aliehlen/advent_of_code
/2020/code/day3.py
1,009
3.5625
4
import pandas as pd import numpy as np data_file = "../data/day3.txt" data = pd.read_table(data_file, names=['field']) def get_trees(field, right, down): # expand field to what we'll need nrows = len(field.index) ncols = len(field['field'][0]) # find what symbol is at the important place field['symbol_at_pos'...
cf37e6f4fd508e8ff33efd07e80e64fcf84af3ee
shaheryarshaikh1011/tcs_prep
/prime.py
565
4.125
4
lower = int(input("Enter Lower bound of the range")) upper = int(input("enter Upperbound of the range")) print("Prime numbers between", lower, "and", upper, "are:") #initialize variable to store sum of prime numbers sum=0; for num in range(lower + 1, upper ): # all prime numbers are greater than 1 if num == 1: ...
d557718e840f2b0e9e3e7dd7fe350649122e02a3
leosantosx/exercicios-em-python
/exercicios/ex87.py
1,057
4.1875
4
""" EXERCÍCIO 087: Mais Sobre Matriz em Python Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. 0 [_][_][_] 1 [_][_][_] 2 [_][_][_] 0 1 2 """ line = int(input('Quantas linhas tem a Matriz? '...
e9cb5656af018c6ac603b3ef4017171636f91f30
leosantosx/exercicios-em-python
/exercicios/ex97.py
316
4
4
""" Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável. """ def escreva(msg): pos = len(msg) print(f'{"~="*pos:^40}') print(f'{msg:^40}') print(f'{"~="*pos:^40}') escreva('Oi')
0c97ace37dce43968f96c1c3daabf5719ab0bd02
leosantosx/exercicios-em-python
/exercicios/ex67.py
500
4.09375
4
""" EXERCÍCIO 067: Tabuada v3.0 Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo. """ while True: print('-'*35) num = int(input('Quer ver a tabuada de qual número? ')) print('...
8fa3df7a5aea16aaf2b22007b378947ca0868977
leosantosx/exercicios-em-python
/exercicios/ex77.py
562
4.125
4
""" EXERCÍCIO 077: Contando Vogais em Tupla Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais. """ palavras = ('Mercado','morango', 'banana', 'Notebook', 'carro', 'celular') for palavra in palavras: ...
5856ee831a9902cca7a6e1471aea28b05835d090
leosantosx/exercicios-em-python
/exercicios/ex71.py
1,258
3.96875
4
""" EXERCÍCIO 071: Simulador de Caixa Eletrônico Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: Considere que o caixa possui cédulas de R$ 50,...
e0b2da770c4f6765119b599ea4812323b8598f00
leosantosx/exercicios-em-python
/exercicios/ex74.py
532
4.1875
4
""" EXERCÍCIO 074: Maior e Menor Valores em Tupla Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla. """ from random import randint numeros = (randint(0,9),randint(0,9),randint(0...
1ff8f127e7d8de6397cfab3db966ec1967b8f6f2
leosantosx/exercicios-em-python
/exercicios/ex36.py
699
4.15625
4
""" DESAFIO 036: Aprovando Empréstimo Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário, ou então o empréstimo será negado. """ casa = float(input('Qual o...
75916db89a34423484952dde8b7bdd0c210915d1
sornaG/python-program
/palindrome.py
79
3.515625
4
s=raw_input v=reversed(a) if list(s)==list(v): print("yes") else: print("no")
3b470d587812f64bd18906bc38b4c0c2635fbf8b
Matthew-Mullen/Sudoku-Solver
/Sudoku solver.py
2,567
4
4
def solve(board): empty = findEmpty(board) # if we have no emptys left that means the job is done and we have filled in the board and validated it if not empty: return True else: row, col = empty for num in range(1, len(board) + 1): if validate(board, num, (row, col)): ...
0a7b8d8f9150cc5c6c40f72a08f987bce1aab551
Sofia1306/Python_Clases
/funcion.py
545
3.984375
4
"""Funcion class""" def hello_world(): """Function that return 'Hello World'. return: string """ return 'Hello World!' string = hello_world() string = string.replace('Hello', 'Bye') print(string) def hello(name='persona', lastmane='exposito'): """Function that return 'name and ...
1a78f443005741e54a145729aab459c15793d4dc
Sofia1306/Python_Clases
/Ejercicio_Piramide.py
169
4.1875
4
"""Ejercicio Piramide de números""" num = int(input("Introduce un número")) for number in range(1, num + 1): pir = str(number) print (pir * number)
9a7c5b638ca4945a89915a3838646e764391427c
DanielSpecht/NERDataSetBuilder
/DBpedia/Associate with wikipedia page contents/pipeline/CsvPipeline/CsvWriter.py
1,956
3.53125
4
import os ''' This class Aims to describe the configurations of a csv file ''' class CsvFileConfiguration: def __init__(self, fileName, csvDelimiter=',', csvQuotechar='"'): self.fileName = fileName self.csvDelimiter = csvDelimiter self.csv...
4fb2217270773ea20a7f1c686a9743c9585182ce
marcusvongsykeo/Life-Trap---Psychological-Questionnaire-App
/LifeTrapApp.py
21,257
3.609375
4
import datetime # Life Trap Number Key # 0 Abandonment # 1 Mistrust and Abuse # 2 Vulnerability # 3 Dependence # 4 Emotional Deprivation # 5 Social Exclusion # 6 Defectiveness # 7 Failure # 8 Subjugation # 9 Unrelenting Standards # 10 Entitlement class LifeTrapProfile: life_trap = {0: "Abandonment", ...
337ea645d33fae9c0e22f863638b2e8b1a3efd6f
utcoupe/Coupe2012
/lib/doctests/poly.test.py
642
3.609375
4
import >>> from geometry import Poly init >>> poly = Poly(((0,0),(4,0),(2,2))) aabb >>> poly.AABB.p == (0,0) True >>> poly.AABB.w 4 >>> poly.AABB.h 2 adjacent >>> poly1 = Poly(((0,0),(4,0),(2,2))) >>> poly2 = Poly(((0,0),(2,-2),(4,0))) >>> poly1.adjacent(poly2) True >>> poly3 = Poly(((0,1),(4,1),(2...
986a02ea27004226663308d3ce3598e951e33ba3
C-CCM-TC1028-102-2113/tarea-4-A01661455
/assignments/10.1AlternaCaracteresContador/src/exercise.py
254
3.734375
4
#Carlos Peña Gutiérrez A01661455 def main(): #escribe tu código abajo de esta línea pass num=int(input()) for num in range(num+1): if num%2==0: print(num,"-#") else: print(num,"-%") if __name__=='__main__': main()
49ebcdcdeabf83eca6b1d9c2a6f59254e28d430e
am-ansari/Graph-algorithms
/Depth first search algo/depth_first_search.py
1,932
3.71875
4
# -*- coding: utf-8 -*- from collections import OrderedDict class Node: def __init__(self, key): self.id = key self.connectedTo = OrderedDict() self.status = 'unvisited' class Graph: def __init__(self): self.nodes = OrderedDict() def addNode(self, ke...
8bedc5c17bec27b7fe05629c00fc0588237edef0
Moaz-Morsy/coursera-data-structures-algorithms-specialization-UC-San-Diego
/3. Algorithms on Graph/Week2-Graph-Decomposition2/1_cs_curriculum/acyclicity.py
802
3.8125
4
#Uses python3 import sys def reach(adj, x, y): #write your code here if y in adj[x]: return 1 visited[x] = True for i in adj[x]: if not visited[i]: j = reach(adj, i, y) if j == 1: return 1 def acyclic(adj): for x in range(1, len(adj)): cycle = reach(...
a679a5448777fd29b5615ae51eec64711df6d8a4
flyingsilverfin/SpotMix
/tools/training_data_db.py
1,127
3.671875
4
import sqlite3 class SimilarityBoundsException(Exception): pass class TrackSimilarityDb(): def __init__(self, db_file_path): self._conn = sqlite3.connect(db_file_path) self._create_tables() def _create_tables(self): """ Create a three column table - track id 1 (text), track id ...
a89c08ee151d5ffc4228ab8e2546613e3f66bafe
kathy254/Questioner-API-v1
/app/api/v1/utils/validations.py
1,433
3.875
4
import re import datetime class Validations: """class to validate data""" def is_empty(self, items): for item in items: if bool(item) is False: return True return False def is_whitespace(self, items): for item in items: if item.isspace() is...
c3df02c9aa9caff660efbd2a345482e756dfb714
joemuiruri/CISC340-11
/CISC340BACKUP/AlarmApp/model.py
397
3.5625
4
import sqlite3 as sql def insertUser(password): con = sql.connect("database.db") cur = con.cursor() cur.execute("INSERT INTO userpassword (password) VALUES (?)", (password)) con.commit() con.close() def retrieveUsers(): con = sql.connect("database.db") cur = con.cursor() cur.execute("SELECT pas...
7547fa4f3687b5dc50826e50433c3a60bc3a34d2
ssavinash1/Algorithms_Stanford_full
/Algorithms-Design-and-Analysis-master/week10 Bellman-Ford Floyed-Warshall Johnson and APSP/johnson.py
5,724
3.90625
4
import time import dijkstra from collections import defaultdict def Bellman_Ford(source, num_nodes, edges): """Given the source, the graph nodes(labeled from 1 to 'num_nodes') and the graph edges(in form of {(tail, head): edge_dist}), computes the single source shortest path if graph does not contain neg...
3db87e92e90c829802edae69e08009b1a134f844
GiuliaCiaramella/ARIMA_ict_transport
/ARIMA/lab2/stationarity_unit_root.py
3,628
3.578125
4
#define function for ADF test from statsmodels.tsa.stattools import adfuller import pandas as pd def adf_test(timeseries): #Perform Dickey-Fuller test: print ('Results of Dickey-Fuller Test:') dftest = adfuller(timeseries, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-val...
ad6af6ef38d499b9f670112796c8b251c1d01831
goonhu/leetcode
/top100_liked/merge_two_sortedlist_21.py
1,176
3.96875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: list_1 = []; list_2 = [] current = l1 if current != None: ...
ec359a0c867a76745ba1d3dcf28aabb461041a59
goonhu/leetcode
/top100_liked/binary_tree_level_order_traversal_102.py
1,000
3.859375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # treenode is pre-defined by the question class Solution: def BFS(self, node): answers = []; temp = [] queue = [] if node !...
5180270cafbdee5fe149094d6dd5982169ba7995
goonhu/leetcode
/top100_liked/merge_k_sortedlist_23.py
946
4.03125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: num_linkedlist = len(lists); all_values = [] # print("len :", num_linkedlist) ...
ce0e4cfeb4a26485aa1d6a31b71c050ef7dab3cd
jasphercatherine/set2
/13.py
120
3.640625
4
z=int(input()) flag=0 for i in range (2,z-1): if z%i==0: flag=1 break if flag==0: print("yes") else: print("no")
a65b1ff98ba3df1b73a3c854fb04278ac804ff2f
chrishendrick/Python-Bible
/cinema.py
1,113
4.25
4
# cinema ticketing # working with dictionaries, while loops, if/elif/else # "name":[age,tickets] films = { "The Big Lebowski":[17,5], "Bourne Identity":[18,5], "Tarzan":[15,3], "Ghost Busters":[12,5] } while True: choice = input("Which film would you like to watch?: ").strip().title() if...
a1aded987b94ad026c5c3e1de1a5d1e8c66e60bd
chrishendrick/Python-Bible
/for.py
838
3.953125
4
for x in range (1,11,2): #iterate 1-10, not 11, by step 2 print(x) for letter in "asdfghjkl": #iterate letters in a string print(letter) vowels = 0 consonants = 0 text = "Hello" for letter in text: if letter.lower() in "aeiou": vowels = vowels + 1 elif letter == " ": pass else: ...
3dba113592a9be83107a4061980ab5633309bdf7
chrishendrick/Python-Bible
/while.py
305
4.0625
4
x=1 while x <= 10: if x%2 == 0: # divisible by 2 with a zero remainder i.e. even numbers print(x) x = x+1 list = [] #empty list while len(list) < 3: new_name = input("Please add a new name: ").strip().capitalize() list.append(new_name) print(list) print("Sorry, list is full.")