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
ad9be274f3f72de34d1adafccb473bbcb637556b
ridhamaditi/tops
/basics/factorial.py
149
4.15625
4
n= int(input("Enter: ")) fact = 1 # while n > 1: # fact = fact * n # n -= 1 for i in range(1, n+1): fact = fact * i print("Factorial: ", fact)
609812d3b68a77f35eb116682df3f844ab3a44c9
ridhamaditi/tops
/Assignments/Module(1)-Exception Handling/a3.py
216
4.15625
4
#Write function that converts a temperature from degrees Kelvin to degrees Fahrenheit try: k=int(input("Enter temp in Kelvin: ")) f=(k - 273.15) * 9/5 + 32 print("Temp in Fahrenheit: ",f) except: print("Error")
5f9d82659fbfcaac9008b379d82726bcc28b1e96
pdevezeaud/Python
/range.py
256
3.984375
4
tableau = list(range(10)) print (tableau) start = 0 stop = 20 x = range(start,stop) print(x) print(list(x)) #on peut définir un pas dans la liste x = range(start,stop,2) print(list(x)) #on peut boucler sur un range for num in range(10): print (num)
7b8e48108d95aa59aa9cd5af63b5672ee99aa0d1
pdevezeaud/Python
/tuple.py
553
3.9375
4
t=(4,1,5,2,3,9,7,2,8) print(t) print(t[2:3]) t +=(10,) #concenation print(t) print(len(t)) ch ='trou du cul' st = tuple(ch) print(st) print("*******************************************") ''' (!) Tuple : conteneur imuable (dont on ne peut modifier les valeurs) création de tupe : mon_tuple = () #vide ...
e5779f5e61468032d5f28b432938c279e9c3af3b
pdevezeaud/Python
/liste_en_comprehension.py
415
3.9375
4
liste = [x for x in 'exemple'] print (liste) liste2 = [x**2 for x in range(0,11)] print(liste2) # possibilite de mettre des conditions dans la liste liste2 = [x**2 for x in range(0,11) if x%2 == 0] print(liste2) celsius = [0,10,20.1,34.5] farenheit = [((9/5)*temp + 32) for temp in celsius ] print(farenheit) #imbri...
6940e23dfdfc93a23dab888ead9fe54b8b7baefe
pdevezeaud/Python
/fonction_detaillee.py
970
3.90625
4
def est_premier (num): ''' Fonction simple pour determiner si un nombre est premier parametre : num, le nombre à tester on par de 2 jusqu'au numero entré (num). Utilisation du range dans ce cas. ''' for n in range(2,num): if num % n == 0: print("Il n'est pas premier") ...
3ec7e25277951842988d506ed16428575601e0a2
pdevezeaud/Python
/graven_developpement/boucle_while.py
88
3.640625
4
a = "q" b = 0 while b = "q": a = a+1 print ("Vous êtes le client n° 1")
144177f8c8d260cbac5c161036564151afe30d1c
pdevezeaud/Python
/gestion_erreur.py
1,113
3.875
4
# iNSTRUCTION POUR GERER LES EXCEPTIONS (BASE) ''' Gérer les exceptions : try /except (+ else, finally) type d'exception : ValueError NameError TypeError ZeroDivisioçnError OSError AssertionError exemple try: age = in...
4d6c8205dee0f10c9ceb4f3e647f5599679e02c1
MrLanka/algorithm008-class02
/Week_01/d12_559_N-maxDepth.py
506
3.515625
4
#还是递归,O(N)和O(logN) #define N-Tree Node class Node: def __init__(self,val=None,children=None): self.val=val self.childeren=children class Solution(object): def maxDepth(self, root): """ :type root: Node :rtype: int """ if root is None: return...
f56fc3015bdf8de048436f333b1109886768a67a
MrLanka/algorithm008-class02
/Week_01/homework2_189_rotate.py
742
3.96875
4
#使用三次旋转数组 class Solution: def rotate(self, nums: List[int], k: int)->None: """ Do not return anything, modify nums in-place instead. """ n=len(nums) k=k%n #k对n取余,确定最终旋转的长度 def reverse_nums(list,start,end): #定义一个反转数组的函数 while start<end: ...
4c69d23e20efafc0e6fa5ac96bd51e5c43fecb2d
annamiklewska/GA
/generate_points.py
3,852
3.609375
4
import numpy as np import random import matplotlib.pyplot as plt import numpy.polynomial.polynomial as p class Points: #domain = np.linspace(0, 10, 200) # 100 evenly distributed points in range 0-10 domain = [random.random()*10 for _ in range(100)] def __init__(self, M): ''' :param M: de...
d6f2e7a6ea51d7a7c9d7841349264e77e5b70832
StechAnurag/python_basics
/33_docstrings.py
317
3.5625
4
# DOCSTRINGS - are used to document the action within a function def test(a): ''' Info: this function tests and prints param a ''' print(a) # to read documenation there are 3 ways # 1 - our text editor helps with it # 2 - help function # 3 - .__doc__ dundar method print(help(test)) print(test.__doc__)
f33e25913c4ad29958ec26a9742055d9a80c5803
StechAnurag/python_basics
/16_list_patterns.py
474
3.921875
4
# Common List Patterns basket = ['Apple', 'Guava', 'Banana', 'Lichi'] #1) length print(len(basket)) #2) sorting basket.sort() print(basket) #3) Reversing basket.reverse() print(basket) #4) copying a list / portion of a list print(basket[:]) #5) Joining list items new_sentence = ' '.join(basket) print(new_sentence...
927346c7283cb20b708aa151b94679eebb28a330
StechAnurag/python_basics
/27_is_vs_==.py
328
3.96875
4
# is VS == # Implicit type conversion takes place wherever possible print(True == 1) print('' == 1) print(10 == 10.0) print([] == []) print('1' == 1) print([] == 1) # == checks if the two values are equal # is - checks the exact reference of the values in memory print(True is True) print('1' is 1) print([1,2,3] is ...
44952b8458de5ee13c724e4bd172e400c4caa165
StechAnurag/python_basics
/09_string_immutability.py
529
4.03125
4
# CONCEPT: STRINGS ARE IMMUTABLE in pyhton fruit = 'Apple' print(fruit) # we can reassign a whpole new value to fruit fruit = 'Orange' print(fruit) # but we can't replace any character of the string # strings are immutable #fruit[0] = 'U' # ERROR # print(fruit) quote = 'To be or Not to be' # we're just overriding t...
5426ce922c71f599e2336eea57b9ad0a08458e03
StechAnurag/python_basics
/03_numbers.py
405
3.71875
4
print(2+4) print(type(6)) print(9*9) print(type(4/2)) print(type(10.56)) # implict type conversion print(type(20 + 1.1)) #float # exponentail operator print(2 ** 3) #equals 8 # divide and round operator print(2 // 3) #equals 0 print(5 // 4) #equals 1 # modular division print(5 % 4) #equals 1 #Math Functio...
bf498bfa0db5373377e0403bbee3bedc259bd9a1
rahimnathwani/combogrid
/combogrid/plot.py
2,463
3.75
4
import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mtick import datetime def plot( df, x, y_line, y_bar, facet_dimension, ncols=2, percent_cols=[], style="fivethirtyeight", ): """Plots a grid of combo charts from a p...
6419a504a30690b864264b1e013cd4eb7a4f4a9e
mpcalzada/data-science-path
/3-PROGRAMACION-ORIENTADA-OBJETOS/algoritmos_ordenamiento/ordenamiento_burbuja.py
590
3.59375
4
import random def ordenamiento_burbuja(lista): n = len(lista) for i in range(n): for j in range(0, n - i - 1): if lista[j] > lista[j + 1]: # O(n) * O(n - i -1) = O(n) * O(n) = O(n ** 2) lista[j], lista[j + 1] = lista[j + 1], lista[j] return lista if __name__ == '__...
a9e6082aca888bbdbfe81e75e533b49f92ef397e
mpcalzada/data-science-path
/1-CURSO-BASICO-PYTHON/prueba-primalidad.py
310
3.78125
4
def es_primo(numero): if numero < 2: return False for i in range(1, numero): if (numero % 2) == 0: return False return True if __name__ == '__main__': n = int(input('Ingrese un numero: ')) print(f'El numero {n} {"es primo" if es_primo(n) else "no es primo"}')
ffe4d01767371c73cc5b1e7ab0bb5b30e0046def
drishtim17/supervisedML
/sML_example.py
386
3.515625
4
#!/usr/bin/python3 import sklearn from sklearn import tree #features about apple and orange data=[[100,0],[130,0],[135,1],[150,1]] output=["apple","apple","orange","orange"] #decision tree algorithm call algo=tree.DecisionTreeClassifier() #train data trained_algo=algo.fit(data,output) #now testing phase predict...
7040b3a51e04a8a5956ef2b56fe8f3ef08705323
IndigoShock/data_structures_and_algorithms
/data_structures/graphs/graph.py
971
3.96875
4
class Vertice: def __init__(self, value): self.value = value self.vertices = [] def __repr__(self): pass def __str__(self): pass class Graph: def __init__(self): self.graph = {} def __repr__(self): pass def __str__(self): pass de...
693d6e422863cd963e49b729d9e1201d0b75f40d
IndigoShock/data_structures_and_algorithms
/challenges/ll_insertions/linked_list.py
1,596
3.828125
4
from typing import Any from .node import Node class LinkedList(object): def __init__(self, iterable=None): self.head = None self._length = 0 if iterable is not None: try: for value in iterable: self.insert(value) except TypeError:...
642f978df2fdfbd359ddd36c494191dc6527b372
AndrewSpano/AI-2-Projects
/Project2/Notebooks/network2_utils.py
7,244
3.609375
4
import torch import nltk import numpy as np from nltk.stem import PorterStemmer from nltk.corpus import stopwords nltk.download('stopwords') def compute_lengths(X): """ function used to compute a dictionary that maps: size of sentence -> number of sentences with this size in X """ # the dic...
5c1464de6abbc235483d3e3f4c35d91fa4009fb8
gulaki/code-timer
/codetimer/codetimer.py
8,065
4.25
4
from time import clock, time import sys if sys.platform == 'win32': timer_func = clock else: timer_func = time UNITS = {'s': 1, 'ms': 1000, 'm': 1/60, 'h': 1/3600} MUNITS = {'b': 1, 'kb': 1024, 'mb': 1024**2} class Timer(object): """ Timer() is a class to measure time elapsed and count number of pas...
e839a7462e1befd6293fbba078feff0f755c51d4
Swapnil2095/Python
/8.Libraries and Functions/Unicodedata – Unicode Database/unicodedata.category(chr).py
257
3.953125
4
import unicodedata print (unicodedata.category(u'A')) print (unicodedata.category(u'b')) ''' This function returns the general category assigned to the given character as string. For example, it returns ‘L’ for letter and ‘u’ for uppercase. '''
35c340635b063ecebc478a1ab8d7f527d6fe2f3f
Swapnil2095/Python
/8.Libraries and Functions/copy in Python (Deep Copy and Shallow Copy)/Shallow copy/shallow copy.py
533
4.5625
5
# Python code to demonstrate copy operations # importing "copy" for copy operations import copy # initializing list 1 li1 = [1, 2, [3, 5], 4] # using copy to shallow copy li2 = copy.copy(li1) # original elements of list print("The original elements before shallow copying") for i in range(0, len(li1)): print(li1[i]...
e0a7301220375162a880cad99931126313fe2cd2
Swapnil2095/Python
/5. Modules/Complex Numbers/asinh.py
719
3.765625
4
# Python code to demonstrate the working of # asinh(), acosh(), atanh() # importing "cmath" for complex number operations import cmath # Initializing real numbers x = 1.0 y = 1.0 # converting x and y into complex number z z = complex(x, y) # printing inverse hyperbolic sine of the complex number print("The inverse...
e4fddb93c4fb6fe92012f32f1738f2fa1ede48b7
Swapnil2095/Python
/5. Modules/Mathematical Functions/fact.py
346
4.09375
4
# Python code to demonstrate the working of # fabs() and factorial() # importing "math" for mathematical operations import math a = -10 b = 5 # returning the absolute value. print("The absolute value of -10 is : ", end="") print(math.fabs(a)) # returning the factorial of 5 print("The factorial of 5 is : ", end="")...
b91b8609d687dd362ac271c349fdc3c81ebfe0f3
Swapnil2095/Python
/8.Libraries and Functions/Regular Expression/findall(d).py
621
4.3125
4
import re # \d is equivalent to [0-9]. p = re.compile('\d') print(p.findall("I went to him at 11 A.M. on 4th July 1886")) # \d+ will match a group on [0-9], group of one or greater size p = re.compile('\d+') print(p.findall("I went to him at 11 A.M. on 4th July 1886")) ''' \d Matches any decimal digit, this is e...
077d5e9531b2db59b3fc73655f385935a5a4712e
Swapnil2095/Python
/3.Control Flow/range()/getsize.py
250
3.546875
4
# Python code to demonstrate range() # on basis of memory import sys # initializing a with range() a = range(1,10000) # testing the size of a # range() takes more memory print ("The size allotted using range() is : ") print (sys.getsizeof(a))
2be154a4143a049477f827c9923ba19198f4a4e3
Swapnil2095/Python
/8.Libraries and Functions/copyreg — Register pickle support functions/Example.py
1,312
4.46875
4
# Python 3 program to illustrate # use of copyreg module import copyreg import copy import pickle class C(object): def __init__(self, a): self.a = a def pickle_c(c): print("pickling a C instance...") return C, (c.a, ) copyreg.pickle(C, pickle_c) c = C(1) d = copy.copy(c) print(d) p = pickle.dumps(c) print(p...
6c804224dd0a9bc2544563b958137c1002ac77fc
Swapnil2095/Python
/8.Libraries and Functions/Regular Expression/findall(all).py
117
3.71875
4
import re # '*' replaces the no. of occurrence of a character. p = re.compile('ab*') print(p.findall("ababbaabbb"))
3dc8226bfc786cf6bbea43a20a0cf5dbbdeeb72e
Swapnil2095/Python
/5. Modules/Mathematical Functions/sqrt.py
336
4.5625
5
# Python code to demonstrate the working of # pow() and sqrt() # importing "math" for mathematical operations import math # returning the value of 3**2 print("The value of 3 to the power 2 is : ", end="") print(math.pow(3, 2)) # returning the square root of 25 print("The value of square root of 25 : ", end="") print...
2d1587bce7ce01c8316ade04b2cf17ee5d300071
Swapnil2095/Python
/5. Modules/Time Functions/sleep.py
352
3.703125
4
# Python code to demonstrate the working of # sleep() # importing "time" module for time operations import time # using ctime() to show present time print ("Start Execution : ",end="") print (time.ctime()) # using sleep() to hault execution time.sleep(4) # using ctime() to show present time print ("Stop Execution :...
762ff5c6fe386f1bad2c2f304eb6f3460a622eab
Swapnil2095/Python
/2.Operator/Division Operators/Division.py
434
3.984375
4
# A Python 2.7 program to demonstrate use of # "/" for integers print (5/2) print (-5/2) print("\n------------------------------") # A Python 2.7 program to demonstrate use of # "/" for floating point numbers print (5.0/2) print (-5.0/2) print("\n------------------------------") # A Python 2.7 program to demonstra...
1ca59efae74f5829e15ced1f428720e696867d9a
Swapnil2095/Python
/2.Operator/Inplace vs Standard/mutable_target.py
849
4.28125
4
# Python code to demonstrate difference between # Inplace and Normal operators in mutable Targets # importing operator to handle operator operations import operator # Initializing list a = [1, 2, 4, 5] # using add() to add the arguments passed z = operator.add(a,[1, 2, 3]) # printing the modified value print ("Va...
7ffe6b1ac7437b0477a969498d66163e4c4e0584
Swapnil2095/Python
/5. Modules/Time Functions/ctime.py
450
4.15625
4
# Python code to demonstrate the working of # asctime() and ctime() # importing "time" module for time operations import time # initializing time using gmtime() ti = time.gmtime() # using asctime() to display time acc. to time mentioned print ("Time calculated using asctime() is : ",end="") print (time.asctime(ti)) ...
fc98a4b1e6c25c0063a0c5fcacecce1cd1b37f97
Swapnil2095/Python
/5. Modules/Mathematical Functions/gcd.py
381
3.953125
4
# Python code to demonstrate the working of # copysign() and gcd() # importing "math" for mathematical operations import math a = -10 b = 5.5 c = 15 d = 5 # returning the copysigned value. print("The copysigned value of -10 and 5.5 is : ", end="") print(math.copysign(5.5, -10)) # returning the gcd of 15 and 5 print...
40c510c23348cf7cbecc3adad8e318d7aef1df98
Swapnil2095/Python
/8.Libraries and Functions/NumPy/linalg.solve.py
263
3.515625
4
import numpy as np ''' Let us assume that we want to solve this linear equation set: x + 2*y = 8 3*x + 4*y = 18 ''' # coefficients a = np.array([[1, 2], [3, 4]]) # constants b = np.array([8, 18]) print("Solution of linear equations:", np.linalg.solve(a, b))
9091de76643f812c44e1760f7d73e2a28c19bde6
Swapnil2095/Python
/8.Libraries and Functions/enum/prop2.py
724
4.59375
5
''' 4. Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. ''' # Python code to demonstrate enumerations # iterations and hashing # importing enum for enumerations import enum # creating enumerations using class class Animal(enum....
f0a0f758c7e274508da794d35c71c52f7da7e0f9
Swapnil2095/Python
/5. Modules/Calendar Functions/firstweekday.py
486
4.25
4
# Python code to demonstrate the working of # prmonth() and setfirstweekday() # importing calendar module for calendar operations import calendar # using prmonth() to print calendar of 1997 print("The 4th month of 1997 is : ") calendar.prmonth(1997, 4, 2, 1) # using setfirstweekday() to set first week day number ca...
9df048f40e3298108b96ab25b71761875c1a05b3
Swapnil2095/Python
/4.Function/Function Decorators/func_as_para.py
488
4.03125
4
# A Python program to demonstrate that a function # can be defined inside another function and a # function can be passed as parameter. # Adds a welcome message to the string def messageWithWelcome(str): # Nested function def addWelcome(): return "Welcome to " # Return concatenation of addWelcome() # and str...
f60dcd5c7b7cc667b9e0155b722fd637570663ef
Swapnil2095/Python
/8.Libraries and Functions/Decimal Functions/logical.py
1,341
4.65625
5
# Python code to demonstrate the working of # logical_and(), logical_or(), logical_xor() # and logical_invert() # importing "decimal" module to use decimal functions import decimal # Initializing decimal number a = decimal.Decimal(1000) # Initializing decimal number b = decimal.Decimal(1110) # printing logical_and...
489ed9868abd2b5275f7f1c9fac5a817e231c598
Swapnil2095/Python
/5. Modules/Fraction module/test3.py
260
3.765625
4
from fractions import Fraction print (Fraction('8/25')) # returns Fraction(8, 25) print (Fraction('1.13')) # returns Fraction(113, 100) print (Fraction('3/7')) # returns Fraction(3, 7) print (Fraction('1.414213 \t\n')) # returns Fraction(1414213, 1000000)
95a5a87944d4bff8b2e1b03a939d0277cd150fe1
Swapnil2095/Python
/3.Control Flow/Using Iterations/unzip.py
248
4.1875
4
# Python program to demonstrate unzip (reverse # of zip)using * with zip function # Unzip lists l1,l2 = zip(*[('Aston', 'GPS'), ('Audi', 'Car Repair'), ('McLaren', 'Dolby sound kit') ]) # Printing unzipped lists print(l1) print(l2)
06fda82a4d6e2463dfedcb1343b883db03976e0d
Swapnil2095/Python
/5. Modules/Inplace Operators/imod.py
478
3.859375
4
# Python code to demonstrate the working of # itruediv() and imod() # importing operator to handle operator operations import operator # using itruediv() to divide and assign value x = operator.itruediv(10, 5) # printing the modified value print("The value after dividing and assigning : ", end="") print(x) # using ...
9aebe2939010ff4b2eca5edf8f25dfc5362828c6
Swapnil2095/Python
/5. Modules/Complex Numbers/sin.py
593
4.21875
4
# Python code to demonstrate the working of # sin(), cos(), tan() # importing "cmath" for complex number operations import cmath # Initializing real numbers x = 1.0 y = 1.0 # converting x and y into complex number z z = complex(x, y) # printing sine of the complex number print("The sine value of complex number is ...
58bd237b612559cd7082821a740ce52963379dd9
Swapnil2095/Python
/8.Libraries and Functions/pickle — Python object serialization/Functions/pickle.loads.py
586
3.9375
4
# Python program to illustrate # pickle.loads() import pickle import pprint data1 = [{'a': 'A', 'b': 2, 'c': 3.0}] print ('BEFORE:',pprint.pprint(data1)) data1_string = pickle.dumps(data1) data2 = pickle.loads(data1_string) print ('AFTER:',pprint.pprint(data2)) print ('SAME?:', (data1 is data2)) print ('EQUAL?:', (...
519813ef69e8cf4ed6340257705bd963181ed61a
yusraSenem/programlama
/ODEV1_05mart2018.py
2,551
3.921875
4
##1) KAR HESAPLAMA def start(): print("İşletme Takip Programı") print("Kar hesabı için 1 \n OEE için 2 \n Adam Başı Ciro için 3 ü tuşlayınız") state = int(input("İşlem Numarası Giriniz")) if(state == 1 ): kar() elif(state==2): oee() elif(state==3): abc() ...
f64ba5aae02316163d73b265b7b4e8e3d1d7a015
JacquesVonHamsterviel/USACO
/10.Dual Palindromes /dualpal.py
1,249
3.53125
4
""" ID: vip_1001 LANG: PYTHON3 TASK: dualpal """ def tranverter(n,int): a=[0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] b=[] res=0 while True: s=n//int # 整数-商 y=n%int # 余数 b=b+[y] if s==0: ...
ca8e34316aad56d028e027b4f54631907829f48d
tdow90/ProjectEuler
/ProjectEuler1.py
196
3.59375
4
# Problem 1 from projecteuler.net def Multiple_of_3or5(limit): sum = 0 for i in range(limit): if i%3==0 or i%5==0: sum = i + sum print(sum) Multiple_of_3or5(1000)
cfce81f53ed00bb8421999063dc3e982ac5ffe37
chengong8225/leetcode_record
/sort/0_bubble_sort.py
678
3.84375
4
# 整体思路: # 两两对比,调整逆序对的位置。如果没有逆序对,说明排序已经完成,可以跳出排序过程。 nums = [2, 15, 5, 9, 7, 6, 4, 12, 5, 4, 2, 64, 5, 6, 4, 2, 3, 54, 45, 4, 44] nums_out = [2, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 9, 12, 15, 44, 45, 54, 64] def bubble_sort(nums): while 1: state = 0 # 如果没有逆序对,那就跳出排序过程 for i in range(len(nums) - ...
e7d09d8d38f4df4f2221ba3963b53467cef66cfb
bregman-arie/python-exercises
/solutions/lists/running_sum/solution.py
659
4.25
4
#!/usr/bin/env python from typing import List def running_sum(nums_li: List[int]) -> List[int]: """Returns the running sum of a given list of numbers Args: nums_li (list): a list of numbers. Returns: list: The running sum list of the given list [1, 5, 6, 2] would return [1...
2facd54b08dd52181d83631e42b018f0e806c414
keyehzy/Kattis-problems
/goatrope.py
1,155
3.59375
4
from sys import stdin, stdout input = iter(stdin.read().splitlines()).__next__ def write(x): return stdout.write(x) def euclid(A, B): from math import sqrt, pow return sqrt(pow(A[0]-B[0], 2) + pow(A[1]-B[1], 2)) def distance(A, B, C): from math import sqrt AB = euclid(A, B) AC = euclid(A, C...
6953a1b7ac04b9953512ff5feb4b64d2cc685ad4
keyehzy/Kattis-problems
/pot.py
235
3.703125
4
def pot(): n = int(input()) result = 0 for _ in range(n): s = list(input()) pow = int(s.pop(-1)) result += int(''.join(s))**pow print(result) return if __name__ == '__main__': pot()
7bf365ca3355e386038e2ef186b06d3a31051d1e
keyehzy/Kattis-problems
/planina.py
163
3.71875
4
def planina(): j = int(input()) x = 2 while(j): x += x - 1 j -= 1 print(x*x) return if __name__ == '__main__': planina()
12359883985bb50aeb4279711c06aa118c6cdbe1
killabayte/codewars
/sort_the_odd_kata/main_my.py
387
3.65625
4
def sort_array(source_array): even_state = [] new_source_array = [] for one, two in enumerate(source_array): if two % 2 == 0: even_state.append((one,two)) else: new_source_array.append(two) new_source_array.sort() for new_even in even_state: new_source...
9a3ecfad05a80abe490885249fb761a0ca77afb6
milenamonteiro/learning-python
/exercises/radiuscircle.py
225
4.28125
4
"""Write a Python program which accepts the radius of a circle from the user and compute the area.""" import math RADIUS = float(input("What's the radius? ")) print("The area is {0}".format(math.pi * math.pow(RADIUS, 2)))
2d35b9d5142ed983ef986af641457a21a3e4949d
milenamonteiro/learning-python
/exercises/jokenpo.py
1,910
3.96875
4
"""Make a two-player Rock-Paper-Scissors game.""" import os import time def cls(): os.system('cls' if os.name=='nt' else 'clear') def rps(text): pedra = set(['pedra', 'pe', 'pdra', 'pedr', "1"]) papel = set(['papel', 'pap', "2", 'pape', 'ppel', 'pa', 'papl']) tesoura = set(['tesoura', 't', "3", 'tsou...
88a268f20d6681db86dcebe9348812f83564a7dc
cbz1902/capturador_tweets
/tweets.py
984
3.890625
4
######################Clase que nos premite modelar un tweets como un objeto############################################ class tweets: def __init__(self,tweet,user,mencion,localizacion,hashtag): """Inicializador de la clase""" self.tweet = tweet self.user = user self.mencion = ...
332c0b3254b0e565e0056193ab36204421e46aa0
jundet/jundet.github.io
/2018/10/08/algorithm/cheaper04/maximum_subarray.py
1,402
3.84375
4
# 最大子数组 分治法 import math import sys def max_cross_subarray(A, low, mid, high): left_sum = float("-inf") sum = 0 max_left = mid max_right = mid for i in range(mid-low): sum = sum + A[mid-i] if sum > left_sum: left_sum = sum max_left = mid - i right_sum = f...
29cb5bea079b380e867470354ea4e538eb70338b
SSeadog/Algorithm-Practice-Python
/greedy/greedy7.py
1,244
3.625
4
# 만들 수 없는 금액 # 나동빈씨의 해결 방법을 이용 # 동전 개수 n 입력 n = int(input()) # 동전 종류 coin 입력 coin = list(map(int, input().split())) # coin 오름차순으로 정렬 coin.sort() # target-1까지 만들 수 있다는 의미를 위해 target 선언 target = 1 # target을 갱신하며 target보다 작은 동전이 없다면 target을 만들 수 없으므로 종료 for c in coin: if c > target: break else: # c가...
6d57b987fa90804134b4b5edbc07ab05bd4a59fa
SSeadog/Algorithm-Practice-Python
/search/bfs.py
948
3.671875
4
# BFS # 큐를 이용한 bfs import queue # bfs 함수 생성 def bfs(graph, start): # 시작 값을 큐에 넣고 방문 처리 q.put(start) visited[start] = True # 큐가 빌때까지 반복 while q.qsize() != 0: # 큐에서 값을 꺼냄, 출력해서 꺼낸 순서 확인 v = q.get() print(v, end=" ") for near_node in graph[v]: # 방문하지 않은 ...
4978aa906cf99b18f54d0f24145eeab60ac967ea
SSeadog/Algorithm-Practice-Python
/simulation/simulation2.py
888
3.578125
4
# 시각 n = input() # 시계 구현 0번째 인덱스는 시간 1번째 인덱스는 분 2번째 인덱스는 초 clock = [0, 0, 0] # 결과 저장 result = 0 # 시간이 n보다 작을 때까지만 반복 while clock[0] <= int(n): # 시분초에 3이 있다면 결과 1증가 if clock[0] % 10 == 3 or int(clock[1] / 10) == 3 or clock[1] % 10 == 3 or int(clock[2] / 10) == 3 or clock[2] % 10 == 3: result += 1 ...
f6a3b5a620203e8d05d31b43e5e98efd52a9b5f2
tricelex/startng-task2
/user_validate.py
2,007
3.953125
4
import random import string def generate_password(fname, lname): letters = string.ascii_lowercase randomvars = ''.join(random.choice(letters) for i in range(5)) rand_password = fname[0:2] + lname[0:2] + randomvars return rand_password def validate_password(my_password): new_user_input_password = '' length = 7...
399a4d526917be7644a04ecd7bc72de480390533
flyfreejay/Python
/CCC/02/0123456789.py
2,261
3.875
4
''' Date: 01/06/2019 Author: Jay Lee Version: 1.0 Purpose: to find the prime numbers from 3 to 100 ''' i = str(input()) def Write0(): print(" * * *") print("* *") print("* *") print("* *") print("") print("* *") print("* *") print("* *") prin...
4a712daf753218a2fbb46209a38d647640cf0369
alexramirez106/issue-quiz
/issue-quiz.py
2,319
3.9375
4
userScore = 0 # Question 1 - Barbara Mikulski question_1 = input("Was Barbara Mikulski the first woman endorsed by EMILY's List? If yes, please write 'Y'. If no, please write 'N'. : ") if question_1 == "Y": userScore = userScore + 1 print("Correct! Your score is " + str(userScore) + "!") else: print("Sorry!...
eea96998bf055dbadf9735177491c26586698cb9
ufo9631/pythonApp
/test/for_else.py
83
3.734375
4
nums=[11,22,33,44,55] for item in nums: print(item) else: print("========")
ab9c7dbe972d537de2981a7e8de84b9917fbd7fa
ufo9631/pythonApp
/for01.py
669
3.734375
4
age=17 if age<18: print("去叫家长把,孩纸") gender="男" if gender=="女": print("美女 你好!") else: print("吔屎啊你") #score=input("请输入分数:") #score=int(score) #字符串转int #print(score) #if score>=90: # print("优秀") #elif score>80 and score<90: # print("良") #python 没有switch-case ''' for 变量 in 序列: 语句 ''' for name in...
e5dd6b083b14b15019b04d4056030ac75602ebcf
ufo9631/pythonApp
/variableDemo.py
8,478
4.09375
4
#变量 #全局变量(global):在函数外部定义 #局部变量(local):在函数内部定义 #提升局部变量为全局变量 def fun(): global bl b1=100 print(bl) print("I am in fun") b2=99 print(b2) #print(b1) #globals,locals函数 #可以通过globals和locals出局部变量和全局变量 a=1 b=2 def fun(c,d): e=111 print("Locals={}".format(locals())) print("Globals={}".form...
eb25947e284a7afc0235865eb1f76818515a0517
ufo9631/pythonApp
/FunctionProgramming/02.py
1,661
3.90625
4
#函数作为返回值返回 def myF2(): def myF3(): print("In myF3") return 3 return myF3 f3=myF2() print(type(f3)) print(f3) f3() #返回函数稍微复杂的例子 #args:参数列表 def myF4(*args): def myF5(): rst=0 for n in args: rst+=n return rst return myF5 f5=myF4(1,23,5,6,7,8) print(f5(...
2b6eae0c835ffaa59af7ff51c99d588a3ff32751
ufo9631/pythonApp
/test/listOpera.py
526
4.09375
4
#list 增删改查 names=['老王','老李','老刘'] names.append('老赵') #添加到list最后 print(names) # names.insert(位置,要添加的内容) names.insert(0,'老陈') print(names) names.insert(2,'老汪') print(names) names2=['葫芦娃','叮当猫','蜘蛛侠'] names3=names+names2; print(names3) names.extend(names3) #将 names3合并到names print(names) names.pop() #将最后一个删除 并返回删除的元...
e4c083a7a08f3e3f973ecc6ca70d912ea79279fb
ufo9631/pythonApp
/test/strtest.py
719
3.609375
4
l=[1,2,3,4,5] print(1 in l) print(1 not in l) s="hell world{0}{1}".format(1,2) print(s) s1='name is %s,age is %d'%('张三',18) print(s1) print(s is s1) print(s is not s1) i=1 while i<2000: i=i+1; print(1,end="|") if i==10: break i=0 while i<10: print(i,'\n') i=i+1 else: print('循环结束') i=1...
39f2f5cb8ca7709e491870793ce0a3923718d3a2
AfkZa4aem/pong_game
/score.py
575
3.625
4
from turtle import Turtle ALIGNMENT = "center" FONT = ("Courier", 40, "normal") class Score(Turtle): def __init__(self, position): super().__init__() self.color("white") self.speed("fastest") self.penup() self.ht() self.goto(position) self.cur...
7e7c8eb9d88df0ab625913abe74d093ba1ed8a14
SAMUELVJOSHUA/HeapSort
/HeapSort.py
319
4.0625
4
def heapsort(MyList): m = len(MyList) for i in range(m//2, -1, -1): heapify(MyList, n-1, i) for i in range(m-1, -1, -1): # swapping last element with the first element MyList[i], MyList[0] = MyList[0], MyList[i] # exclude the last element from the heap heapify(MyList, i-1, 0)
b43b9cbf051659b1fe818de7774cd848e9004020
foytingo/cs50x
/pset6/mario_less.py
424
3.890625
4
from cs50 import get_int def main(): height = get_valid_int() mario_wall(height) def mario_wall(height): for i in range(height): for _ in range(height-i-1): print(" ", end="") for _ in range(i+1): print("#", end="") print() def get_valid_int(): while Tr...
9da34a38cc05d00a5f363595f2d7cd0f1fbb9e14
deeGraYve/UpennCoursework
/lines/robot.py
12,443
3.65625
4
from robotUtilities import * from guiHelp import * import heapq class PriorityQueue: def __init__(self): """heap: A binomial heap storing [priority,item] lists.""" self.heap = [] self.dict = {} def setPriority(self,stuff,priority): """inserts element into the q...
9e23c4a3830d6d00d9f8a5f06a6b970ba45ae042
deathgaze/cse1310
/hw06/hw06_task3.py
3,298
4.3125
4
''' Kirk Sefchik UTA ID 1000814472 10/14/13 Description: Task 3 (55 points) This task will implement the functionality of creating a list from a string that contains numbers separated by commas (with possibly blank space between them). For example the string "1,2,3, 4.5, 6.7, 8" would become the list: [1, 2, 3, 4.5, 6...
91f9f66291f74b12ba7cb4820073a520732a1b3e
deathgaze/cse1310
/hw05/hw05_task3.py
520
3.828125
4
# Kirk Sefchik # UTA ID 1000814472 # 10/03/13 # Description: Show all the actions and states that the machine (the computer) goes through as it runs the folowing program. You must show the state after each instruction is executed. L = [] x = 13 count = 0 while x > 0: if (x % 4) == 0: x = x // 2 else: ...
df5bf198f20b1d5def054a935af800645fc73faa
deathgaze/cse1310
/hw02/hw02_task1.py
508
4
4
# Kirk Sefchik # UTA ID 1000814472 # 09/05/13 # Description: displays the quotient of n and 25. also displays the remainder # (if any) # Take inputs and perform operations. denominator = 25 numerator = int(input("n = ")) remainder = numerator % denominator quotient = numerator // denominator # Check fo...
7e0a96d8d9ddb9e5e0fa5c33419818766298acd6
Davies-Career-and-Technical-High-School/unit-1-project-silly-sentences-Alex-Rodrigues22
/silly_sentences.py
782
3.828125
4
print("Let's play Silly Sentences!") name1 = input("Enter a name: ") adj1 = input("Enter an adjective: ") adj2 = input("Enter an adjective: ") adverb1 = input("Enter an adverb: ") food1 = input("Enter a food: ") food2 = input("Enter a food: ") noun1 = input("Enter a noun: ") place1 = input("Enter a place: ") verb1 = i...
3f9d68c2c48571b411c94567c6e33c4b11090a8d
taosenlin/python_file
/sel/day1/作业.py
1,532
3.515625
4
# Time:2020-02-13 21:49 # Author:TSL from selenium import webdriver import time def get_weathermsg(): driver = webdriver.Chrome("D:\\ruanjiananzhuang\chromedriver.exe") #创建浏览器实例 driver.get("http://www.weather.com.cn/html/province/jiangsu.shtml") #搜索天气网址 #取出所有城市的天气信息 city_list = driver.find_e...
81f33df9eecce588d9b503cd6e92fadbc727d4df
taosenlin/python_file
/untitled/py_sel/dict/2字典-常见操作.py
790
4
4
dict = {'name':'赵四','sex':'男'} # (1)测量字典中,键值对的个数 # len() # print("字典的长度:",len(dict)) #字典的长度: 2 # (2)返回一个包含字典所有KEY的列表 # keys # print("字典的所有KEY的列表:",dict.keys()) #字典的所有KEY的列表: dict_keys(['name', 'sex']) # (3)返回一个包含字典所有value的列表 # values # print("字典的所有value的列表:",dict.values()) #字典的所有value的列表: dict_values(['赵四',...
eb435a425703fb25430a6522ccdd33cd3bcafa75
deepak-mandal/code
/parentheses.py
1,424
3.921875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'isBalanced' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # class stack: def __init__(self): self.items=[] def is_empty(self): ret...
58f5d5cfa7b6d569b1e5384b46d94190fbc4f507
maosa/codecademy
/python/ml/logic_gates.py
5,830
4.5
4
##### LOGIC GATES - PERCEPTRONS PROJECT """ In this project, we will use perceptrons to model the fundamental building blocks of computers — logic gates. For example, the table below shows the results of an AND gate. Given two inputs, an AND gate will output a 1 only if both inputs are a 1: Input 1 Input 2 Output 0 ...
2758434c33b732d60d058fb5a9688e5a41759fe6
maosa/codecademy
/python/ml/k_means.py
17,786
4.3125
4
##### K-MEANS CLUSTERING """ >>>>> Introduction to Clustering Often, the data you encounter in the real world won’t have flags attached and won’t provide labeled answers to your question. Finding patterns in this type of data, unlabeled data, is a common theme in many machine learning applications. Unsupervised Learni...
fd46f768c7d22f46892f7c99f56ec1d5f2b5faa9
maosa/codecademy
/python/ml/perceptron.py
13,676
4.375
4
##### PERCEPTRON """ >>>>> What is a Perceptron? Similar to how atoms are the building blocks of matter and how microprocessors are the building blocks of a computer, perceptrons are the building blocks of Neural Networks. If you look closely, you might notice that the word “perceptron” is a combination of two words:...
9aa7b00b7246318c9a818b91b155b257c2eed8ed
maosa/codecademy
/python/basics/pandas_part3.py
6,026
4.34375
4
################### ##### PANDAS PART 3 import pandas as pd import numpy as np sales = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/sales.csv') print(sales) targets = pd.read_csv('/Users/maosa/Desktop/programming/codecademy/python/basics/targets.csv') print(targets) men_women = pd.read_csv('...
f8d2873a56e915681c5a4229c9a842626e6f10bd
wonghoifung/learning-python
/r2_5.py
463
3.8125
4
text = 'yes,no,yes,no' text = text.replace('yes','yep') print text text = '11/1/2015, 12/30/2014' import re print re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text) pat = re.compile(r'(\d+)/(\d+)/(\d+)') print pat.sub(r'\3:\1:\2', text) from calendar import month_abbr def change_date(m): mon_name = month_abbr[in...
4ad91e1cd661f5b7ce3b6c0960cb022136275e0a
testergitgitowy/calendar-checker
/main.py
2,618
4.15625
4
import datetime import calendar def name(decision): print("Type period of time (in years): ", end = "") while True: try: period = abs(int(input())) except: print("Must be an integer (number). Try again: ", end = "") else: break period *= 12 print("Type the day you want to check f...
a485ed23f0437665d6fcaf057b2f961aaa714000
Kruti235/111
/main.py
2,582
3.609375
4
import csv import pandas as pd import random import statistics import plotly.figure_factory as ff import plotly.graph_objects as go df= pd.read_csv("studentMarks.csv") data = df["Math_score"].tolist() #fig= ff.create_distplot([data],["Math Scores"], show_hist=False) #fig.show() mean = statistics.me...
3c8a796bd9e2bbcb6b11e1ba00c3986d40c4982b
DiogoOliveira111/ProjectoTese
/WBMTools/sandbox/data_processing.py
12,615
3.515625
4
import pylab as pl import pandas as pd import datetime as dt import numpy as np import seaborn as sns import matplotlib.pyplot as plt import matplotlib as mpl def survey_results(dir_survey, survey): """ This function gets the survey scales and put it in a data frame named survey_scales. This function gets some surv...
170368ef9881d616bb55722129a4076855157efc
BREAD5940/Offseason-Croissant
/src/main/python/statespace/LTVDiffDriveController.py
4,509
3.546875
4
#!/usr/bin/env python3 # Avoid needing display if plots aren't being shown import control as ct # import control as cnt # import numpy as np import math import numpy as np import frccontrol as frccnt def __make_cost_matrix(elems): """Creates a cost matrix from the given vector for use with LQR. The cost m...
681e2ef15a450cae0db70cd9994554396ea97916
glennneiger/git_better
/server/django_server/utils.py
921
3.5
4
from BeautifulSoup import BeautifulSoup import urllib2 def get_trending_links(language=None, since="daily"): """Return a list of trending GitHub repositories for the specified parameters. Args: language (None, optional): The programming language. If not set, all languages are included since (...
1d7293afa6c9288a768cb72796c46290bbaf525d
lieta96/30-days-of-python
/day_05/lists.py
5,598
4.3125
4
# Level 1 #1 empty_list=[] #2 more_than_five=[0,1,2,3,4,5,6] #3 lenght_list=len(more_than_five) #4 middle_index=lenght_list//2 first_item=more_than_five[0] middle_item=more_than_five[middle_index] print (middle_item) last_item=more_than_five[lenght_list-1] print(last_item) #5 mixed_data_types=["Julieta",24,1.60,"...
72b1efd985e668f70ebc55376f18c57cde06b96e
OlgaFimbresMorales/ProgramacionF
/Producto2/hola.py
452
3.671875
4
# -*- coding: utf-8 -*- #!/usr/bin/python import time print "Hola! Trataré de adivinar un número" print "Piensa un número entre 1 y 10." time.sleep( 5 ) print "Ahora multiplícalo por 9." time.sleep( 5 ) print "Si el número tiene 2 dígitos, súmalos entre si: Ej. 36 -> 3+6=9. Si tu número tiene un solo dígito, súmal...
c5e0d8fc3cf45e5098827ceba965d581cda6c16f
shankar7042/coding-questions
/binary_tree.py
6,451
3.953125
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def __repr__(self) -> str: return str(self.data) def levelorder(root): if root is None: return queue = list() queue.append(root) queue.append(None) # To verify t...
32abbab0341942f882ad0a2e9c1a94a9579c9f86
shankar7042/coding-questions
/binary_search.py
4,846
3.5
4
def binary_search_asc(arr, key): start = 0 end = len(arr)-1 while start <= end: mid = start + ((end-start) // 2) if arr[mid] == key: return mid elif arr[mid] > key: end = mid-1 else: start = mid+1 return -1 def binary_search_desc(arr...
2080631a6342415fb739524ce136b011d164380f
xuehanshuo/ref-python-numpy
/np_05_矩阵的索引.py
614
3.859375
4
import numpy as np A = np.arange(3, 15).reshape((3, 4)) print(A) print("*" * 100) # 索引某一行/某一列 print(A[2]) print(A[2, :]) print(A[:, 0]) print("*" * 100) # 索引单个值 print(A[0, 0]) print(A[0][0]) print("*" * 100) # 索引部分值 print(A[0, 1:3]) # 第0行,[1,3)的所有数 print("*" * 100) # 迭代每一行 for row in A: ...
e4a0d20e8f094a49ad535014b0a751bf4e81976d
Cosmo65/Velha-AI
/robodificil.py
1,958
3.53125
4
class RoboDificil(object): '''Robo bom com MinMax''' def __init__(self, nome, marca): self.marca = marca self.nome = nome if self.marca == 'X': self.oponente = 'O' else: self.oponente = 'X' def jogada(self, tabuleiro): posicao,score = self.m...