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
e4170df0f1d957aff35d6ab6ceafdd834a52d4e4
Kalaiselvan1503/GuviPlayer
/fact_fun.py
182
3.671875
4
#jidskjflsk def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) s,k=input().split() s=int(s) k=int(k) d=factorial(s)//factorial(k) print(d)
f8202c0b6613dbf791d2e0f02dbe7896cd0cf166
cmgc/moocology-python-assignments
/week_1/fizz_buzz.py
341
4.125
4
#!/usr/bin/env python user_input = raw_input("Enter number:") def fizz_buzz(user_input): length = int(user_input) + 1 for i in range(1, length): if i % 3 == 0 and i % 5 == 0: print("%i FizzBuzz") % (i) elif i % 5 == 0: print("%i Buzz") % (i) elif i % 3 == 0: print("%i Fizz") % (i) f...
07ecbbc1a8bf0e46b6432dbea343063da6d55a7b
medisean/python-algorithm
/quick_sort.py
645
4.125
4
''' Quick sort in python. Quick sort is not stable. Time complexity: O(nlogn) Space complexity: O(log2n) ''' def quick_sort(lists, left, right): if left >= right: return lists first = left last = right key = lists[first] while first < last: while first < last and lists[last] >= key: last = last - 1 ...
1b701f89effed4ee99b65c9c32b2cfce913f5c80
jarhun88/PracticePython
/List Comprehensions.py
140
3.640625
4
def evens(lst): new_list = [] for n in lst: if n % 2 == 0: new_list.append(n) print (new_list)
2a08e13cc70178001f6cfe6ae1611bb2af9ade40
jarhun88/PracticePython
/Character input.py
243
3.78125
4
# Character Input def agemaster(): name = input("What is your name?") age = int(input("What is your age?")) current_year = 2017 year = str(100 - age + current_year) print (name + ", you will turn 100 in the year " + year)
1b5fc66ec82be17bd7819f06d7e9b57b7f2585f1
aidandgaf/CS1030UAssignment2
/Part1.py
1,275
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 2 10:39:39 2017 @author: aidan """ class Stack: def __init__(self): self.stacks = [] def top(self): return self.stacks[len(self.stacks)] def pop(self): return self.stacks.pop() def push(se...
19adac4e6b7c3168a84b2d9875ac3771afc8fa4d
sat5297/hacktober-coding
/Mergesort.py
2,754
4.125
4
# Python program for implementation of MergeSort # Merges two subarrays of arr[]. # First subarray is arr[l..m] # Second subarray is arr[m+1..r] def merge(arr, l, m, r): n1 = m - l + 1 n2 = r- m # create temp arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(...
0cfbe3731d78b5486ad00edd25fbaed88bf96bd2
sat5297/hacktober-coding
/invert-binary-tree.py
408
3.890625
4
def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root is None: return root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root # Example: # Input: # 5 # / \ # 3 7 # / \ ...
ea14c47f080d650dae7bf8ba2a281e904aa1ed19
sat5297/hacktober-coding
/python programs/counting_frequency_of_letters.py
219
3.703125
4
from collections import Counter as c def frequency_counter(s): """ >>>frequency_counter("aaabbcbdde") returns a dictionary with the following data: 'a' : 3, 'b' : 3, 'c' : 1, 'd' : 2, 'e' : 1 """ return c(s)
aac431e7223e65aecebf1952ee5acb05bd668c2a
Kenji79217/guess
/guess.py
490
3.65625
4
import random start = input('請決定隨機數字範圍值開始值: ') end = input('請決定隨機數字範圍結束值: ') start = int(start) end = int(end) r = random.randint(1, 100) conut = 0 while True: conut += 1 num = input('請猜數字: ') num = int(num) if num == r: print('YA! 你猜中了! ') print('這是你猜的第', conut, '次') break elif num < r: print('在大一點~ ') ...
42be025af77499da11952a946e1644468436fe29
junhao69535/pycookbook
/chapter2/search_and_replace_of_str.py
1,423
3.9375
4
#!coding=utf-8 """ 字符串搜索和替换 """ # 对于简单的字面模式,直接使用str.replace(): text = 'yeah, but no, but yeah, but no, but yeah' print text.replace('yeah', 'yep') # 这个函数会返回新的str对象,原text不变 # 对于复杂的模式,使用re的sub()函数 text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' import re print re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', tex...
20de36ec7faf9800fef4e5a72981a91e9ff54085
junhao69535/pycookbook
/chapter4/generator_func_with_outer_status.py
1,354
3.59375
4
#!coding=utf-8 """ 带有外部状态的生成器函数 """ # 想定义一个生成器函数,但它的会调用某个你想暴露给用户使用的外部状态值 # 可以实现一个类,把生成器函数放在__iter__()方法中 from collections import deque class linehistory(object): def __init__(self, lines, histlen=3): self.lines = lines self.history = deque(maxlen=histlen) def __iter__(self): fo...
b0615293aad215dfbd2d9d19a3666b95a36a1795
junhao69535/pycookbook
/chapter3/transfer_datetiem_and_time.py
1,108
4.0625
4
#!coding=utf-8 """ 基本的日期与时间转换 """ # 为了执行不同时间单位的转换和计算,使用datetime模块。比如,为了表示一个时间段, # 可以创建一个timedelta实例: from datetime import timedelta a = timedelta(days=2, hours=6) b = timedelta(hours=4.5) c = a + b print c.days print c.seconds print c.seconds / 3600 # c.seconds获取的仅仅是针对hours得到的, print c.total_seconds() / 3600 # ...
0d31b00864cf9ca4c43c1d683594399ad9480f5d
junhao69535/pycookbook
/chapter2/del_unneed_char_from_str.py
967
4.1875
4
#!coding=utf-8 """ 删除字符串中不需要的字符 """ # 想去掉文本字符串开头,结尾或者中间不想要的字符,比如空白 # strip()方法用于删除开始和结尾的字符。lstrip()和rstrip()分别从左和从右执行 # 删除操作。默认情况下,这下方法会删除空白字符,但也可以指定 s = ' hello world \n' print s.strip() # 'hello world' 会把换行符也删掉 print s.lstrip() # 'hello world \n' print s.rstrip() # ' hello world' t = '-----hello=====' print...
5884711de2f5b7cadbbc4c2b317d4c388e4ae145
junhao69535/pycookbook
/chapter2/bytestr.py
1,140
4.15625
4
#!coding=utf-8 """ 字节字符串上的字符串操作 """ # 想在字节字符串上执行普通的文本操作(比如移除,搜索和替换)。 # 字节字符串同样支持大部分和文本字符串一样的内置操作。 data = 'Hello World' # 在python2,str就是字节字符串,不需要加b print data[0:5] print data.startswith('Hello') print data.split() print data.replace('Hello', 'Hello Cruel') # 这些操作同样也适用于字节数组 data = bytearray('Hello World') print d...
c0a8885c68e16e698a931f7db51156980a5c309e
junhao69535/pycookbook
/chapter8/use_propery_manage_attrs.py
1,954
3.828125
4
#!coding=utf-8 """ 创建可管理的属性 """ # 你想给某个实例attribute增加除访问与修改之外的其他处理逻辑,比如类型检查或合法性验证。 class Person(object): def __init__(self, first_name): self.first_name = first_name # 这里会调用@first_name.setter修饰的first_name()方法 # Getter function @property def first_name(self): # 当外部访问属性first_name就会调用这个函数 ...
882c2faa3ca3aed3faebdb2a261ef8c9a5411bac
junhao69535/pycookbook
/chapter4/permutation.py
1,171
4.1875
4
#!coding=utf-8 """ 排列组合的迭代 """ # 像迭代遍历一个集合中元素的所有可能的排列或组合 # itertools模块提供了三个函数来解决这类问题,其中一个是 itertools.permutations() , # 它接受一个集合并产生一个元组序列,每个元组由集合中所有元素的一个可能排列组成。 from itertools import permutations # 排列 items = ['a', 'b', 'c'] for p in permutations(items): # A33 print p # 如果想得到指定长度的所有排列,可以: for p in permutat...
a7a5fe118048a5217f599a41a062dd076862f5e9
junhao69535/pycookbook
/chapter8/expand_property_in_subclass.py
3,298
3.9375
4
#!coding=utf-8 """ 在子类中扩展property """ # 在子类中,想要扩展定义在父类中的property的功能 class Person(object): def __init__(self, name): self.name = name # Getter function @property def name(self): return self._name # Setter function @name.setter def name(self, value): if not isi...
d009a68a8f251ed60487f3bcb375c8ba2cbdb9e6
junhao69535/pycookbook
/chapter8/call_super_func.py
1,750
4.0625
4
#!coding=utf-8 """ 调用父类方法 """ # 想调用父类某个已经被重写的方法 class A(object): def spam(self): print 'A.spam' class B(A): def spam(self): print 'B.spam' super(B, self).spam() # 在python3里是super().spam(),根据mro调用 B().spam() class Base(object): def __init__(self): print 'Base.__i...
23b7379b9cd6ed2c871c0006da9bd04194661374
junhao69535/pycookbook
/chapter8/call_methods_by_str.py
1,618
3.625
4
#!coding=utf-8 """ 通过字符串调用对象方法 """ # 你有一个字符串形式的方法名称,想通过它调用某个对象的对应方法。 # 最简单的情况可以使用getattr(): import math class Point(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return 'Point({!r:},{!r:})'.format(self.x, self.y) def distance(self, x, y): ...
7143ecdd7a8c91921786a6b3f8b4c78073eda6ee
junhao69535/pycookbook
/chapter3/calculate_complex.py
741
3.796875
4
#!coding=utf-8 """ 复数的数学运算 """ # 复数可以使用complex(real,imag)或者是带有后缀j的浮点数来指定 a = complex(2, 4) b = 3 - 5j print a print b # 对应实部和虚部和共轭复数都很容易获取 print a.real # 实部 print a.imag # 虚部 print a.conjugate() # 共轭复数 # 也支持数学运算 print a + b print a * b print a / b print abs(a) # 如果需要执行其他的复数函数比如正弦、余弦或平方根,使用cmath模块 import cma...
6a2bafd2b5b582e3248108c0dca196c7a14b1329
bergercookie/demo-selfdriving
/basic_types.py
1,745
3.609375
4
# Contains the basic types for the HashCode Problem from utils import print_ import numpy as np class Point(object): def __init__(self, r=0, c=0): self.r = r self.c = c def __repr__(self): msg = "({},{})".format(self.r, self.c) return msg def distance(p1, p2): return (np....
c082637890b6bdf42c1216df98380c705421d079
lyltsh/pythonlearn
/src/chapter1/cookbook/keep_last_n_numbers.py
559
3.625
4
# 保留最后N个元素 from collections import deque def serach(lines, pattern, history=5): previous_lines = deque(maxlen=history) for li in lines: if pattern in li: yield li, previous_lines previous_lines.append(li) # yield 生成器函数 # example use on a file if __name__ == '__main__': with ...
4eec7dce66ee380c61c8e0c1b5b680a03b6fa4ad
ccaniano15/inClassWork
/text.py
338
4.25
4
shape = input("triangle or rectangle?") if shape == "triangle": width = int(input("what is the length?")) height = int(input("what is the height?")) print(width * height / 2) elif shape == "rectangle": width = int(input("what is the length?")) height = int(input("what is the height?")) print(width * height) else:...
92ee8590fe225771bfe68922f36d0d3f600c573f
ArunKarthi-Git/pythonProject
/Program79.py
280
3.546875
4
if __name__=='__main__': L=[] i=0 L.append(input("Enter the Character")) while L[i] != '$': i+=1 L.append(input("Enter the Character")) L[i]='.' i=0 C=[] while L[i] !='.': C.append(L[i]) i+=1 print(L) print(C)
b760f52a14e6f008c983bf64ebcf7cc37f519ed2
ArunKarthi-Git/pythonProject
/Program26.py
200
3.984375
4
if __name__=='__main__': year=int(input("Enter the year:")) if(year%4): print("The given year is leap",format(year)) else: print("The given year is not leap",format(year))
b6375a70de01303ae87311ff5d37816cd853742c
ArunKarthi-Git/pythonProject
/Program54.py
467
4.1875
4
if __name__=='__main__': a=input("Enter the character:") while a != '$': if ord(a) >=65 and ord(a)<=90: print("The given character is upper",a) elif ord(a)>=96 and ord(a)<=122: print("The given character is lower",a) elif ord(a)>=46 and ord(a)<=57: pri...
2fb30de1a77a34b8c675d3dfeba85995077e4fcb
ArunKarthi-Git/pythonProject
/Program46.py
313
3.875
4
if __name__=='__main__': a=int(input("Enter the begining year:")) b=int(input("Enter the end year:")) while a <= b: if a % 4 == 0: print("Printing year is {0} is leap year".format(a)) else : print("printing year is {0} is not leap year".format(a)) a +=1
ab4f8c263b20b7b9e1479c7a198d66a9dbc47b40
ArunKarthi-Git/pythonProject
/Program226.py
412
3.703125
4
import sys if __name__ =='__main__': def file(f1): a = True while a: fl = f1.readline() if not fl: print("EoF") a = False print(fl) argc = len(sys.argv) if argc != 3: print("Argument is not valid") sys.e...
652eee5f775ce49a22440aac1dbeb512a1f76843
ArunKarthi-Git/pythonProject
/Program49.py
324
3.9375
4
if __name__=='__main__': a=int(input("Enter a value:")) while a !=0: if a > 0: print("Given No. is Positive") elif a < 0: print("Given No. is Negative") else : print("Given No. is Zero") a=int(input("Enter a value:")) print("Given No. is Ze...
06b31092c1cf6cf3da8f4dafe48bd16c5892a6d1
ArunKarthi-Git/pythonProject
/Program170.py
875
3.8125
4
class Student: def __init__(self,name,age,address): self.name=name self.age=age self.address=address def writeIntoFile(self): f = open("/home/karthi/Document/Student1.txt", "w") #content="name:"+self.name+"age:",self.age,"address:",self.address[0],self.address[1],self.ad...
ff2d2b5683f507a45e15d4f179f41e8fdbba15ea
ArunKarthi-Git/pythonProject
/Program208.py
491
3.9375
4
if __name__=='__main__': def circle(r): return 3.14*r*r def sphere(r): return 4.0/3.0*3.14*r*r def cylinder(r,h): return 3.14*r*h a=int(input("Enter a no. for area")) print("The area of circle is:",circle(a)) b=int(input("Enter a no.for sphere")) print("The area ...
063d3f444a79f4f99862138486300d38e2b05831
ArunKarthi-Git/pythonProject
/Program107.py
335
3.96875
4
if __name__=='__main__': for j in range(int(input("Enter a start no.")),int(input("Enter a end no."))): print(j) for j in range(int(input("Enter a start no.")),int(input("Enter a end no."))): if j % 2 ==0: print(j,"The given No.is even") else : print(j,"the giv...
0143881a4e66babed1a2e04a5e5c2d51d24ca1da
ArunKarthi-Git/pythonProject
/Program131.py
667
3.546875
4
if __name__=='__main__': L=[] i=10 for j in range(i): L.append(int(input("Enter the No."))) pb1=0 big1=0 for j in range(len(L)): pb1=j if L[j] > L[pb1] else pb1 print("The Position of i st biggest No. is:",pb1) pb2=0 big2=0 for j in range(len(L)): pb2=j...
25846d7fcd249c7d392a6b0a67e52c0bad7bc29e
ArunKarthi-Git/pythonProject
/Program198.py
455
3.65625
4
import sys # python Program190.py /home/karthi/Document/file11.txt if __name__=="__main__": argc=len(sys.argv) if argc !=2: print("Argument is not valid") sys.exit(1) L=[] L.append(input("Enter the Name")) L.append(int(input("Enter the age"))) L.append(float(input("Enter the Sala...
ce9f1256399d14dbc9b666dc3f81904a4b9e3f5e
ArunKarthi-Git/pythonProject
/Program224.py
334
3.65625
4
import sys if __name__ =='__main__': def file(f1): ch=input("Enter the character") while ch !='$': f1.write(ch) ch=input("Enter the character") argc = len(sys.argv) if argc != 2: print("Argument is not valid") sys.exit(1) f=open(sys.argv[1],"w"...
d03b2a6a44cae8d7a5a2829f3d25040e47932f66
ArunKarthi-Git/pythonProject
/Program72.py
1,186
4.1875
4
if __name__=='__main__': matrix = [] print("Enter the entries rowwise:") i=0 while i<3: i+=1 a=[] j=0 while j<3: j+=1 a.append(int(input())) #print(a) matrix.append(a) matrix1 = [] print("Enter the entries rowwise:") i ...
f000dfdc12f23effcf85d5bd8f0cd1ce7d787425
ArunKarthi-Git/pythonProject
/Program130.py
332
3.671875
4
if __name__=='__main__': L=[] i=10 for j in range(i): L.append(int(input("Enter the No."))) big=0 for j in range(len(L)): big=L[j] if L[j] > big else big big2=0 for j in range(len(L)): big2=L[j] if L[j] > big2 and L[j] != big else big2 print("The second biggest...
b3c390ae43436478605b057c08b61d32f398b3b6
ArunKarthi-Git/pythonProject
/Program42.py
180
3.640625
4
if __name__=='__main__': i=1 while i < 10: if i % 2 == 0: print("The No. is even",i) else : print("The No. is odd", i) i +=1
7d86e310ddf0e0d62039ed74d699a49d527fa748
MobinaZmn/IntroductionToPythonProgramming
/ex1/AreaX.py
1,008
4.03125
4
import math ''' Calculates the area between the 4 numbers given and if a number is 0 It calculates the area between the other 3 ''' def AreaX(A,B,C,D,E): if (A or B or C or D == 0): if (D == 0): P1 = A P2 = B P3 = C S = (P1 + P2 + P3) / 2 ...
953f98b68c708b40b32bdc581a3eaeaf74662549
Floreit/PRG105
/KyleLud4.1.py
994
4.15625
4
#Declare variables to be used in the while loop stop = 0 calories = 4.2 minutes = 0 time = 0 #while loop with if statements to count the intervals, increments by 1 minute every iteration, when it hits an interval it will display the calories burned while stop != 1: minutes = minutes + 1 if minutes == ...
a4ea7979555464c2ec2b953a15cc5d42428e154a
Floreit/PRG105
/GuiKyleL.py
377
3.5
4
import tkinter class MyGui: def __init__(self): self.main_window = tkinter.Tk() self.label_1 = tkinter.Label(self.main_window, text='Hello Dave') self.label_2 = tkinter.Label(self.main_window, text='You are looking well') self.label_1.pack(side='left') self.label_2.pack(side...
e2c5a10a32e1be6b1e32090a66430e0803796580
Floreit/PRG105
/kyleL 8.1.py
349
3.984375
4
# input for user enterying there name name = input('Type your name and press ENTER. ') # split the input name_list = name.split() print(name_list) # separate the initials first = name_list[0][0] second = name_list[1][0] last = name_list[2][0] # print out the initials for a user print(first.title(),'.', second.title()...
77c1d163b9b26a4609d4d0950aa14440e2838418
Floreit/PRG105
/KyleL12.2.py
294
3.953125
4
# function to do the recursion def get_sum(piece): if len(piece) == 0: return 0 else: return piece[0] + get_sum(piece[1:]) # main function def main(): numbers = [1, 2, 3, 4, 5] output = get_sum(numbers) print(output) # calling main main()
1885b7c5930b016b448bff1741f70d7b2ab74941
Hank310/RockPaperScissors
/RPS1.py
2,028
4.1875
4
#Hank Warner, P1 #Rock, Paper Scissors game # break int0 pieces # Welcome screenm with name enterable thing # Score Screen, computer wins, player wins, and ties # gives options for r p s & q # Game will loop until q is pressed # Eack loop a random choice will be generated # a choice from thge player, compare,...
7ac469e315b5f624320ac29cfdfbf0b7b8b1824a
jlese/CS-1111
/maydate.py
178
3.890625
4
def creepy(age1, age2): """ take two ages and return true if it is ok to date and false if not """ age1 = age1 * 2 - 13 return bool(age1 <= age2)
42fb5fe30762ba496a31f256d663fe217b75d97f
jlese/CS-1111
/calculator.py
1,602
4.03125
4
# Jack Lesemann jwl4vg def binop(string): ''' takes a string and extracts the two numbers and operator. it will then return the answer to the extracted expression :param string: two integers and +, -, /, or * :return: answer as float ''' if "/" in string: string_strip = strin...
0d46f34cabffb304c7150af0d63c88a5ac651026
jlese/CS-1111
/dating.py
203
3.90625
4
age = int(input("How old are you? ")) age1 = age // 2 + 7 age2 = age * 2 - 13 if age >= 14: print("You can date people between", int(age1), "and", int(age2), "years old") # Jack Lesemann jwl4vg
87c3c1b86f6e82c6c3c231ff9bd5e182d69bd238
PranaKnight/Dominando-Python
/Exercicios/Exercício5.py
842
3.9375
4
#Sequencia5 prod1 = input("Digite o nome do produto: ") qnt1 = int(input("Digite a quantidade desse produto: ")) valor1 = float(input("Digite o valor do item: ")) rec1 = qnt1*valor1 print("=+"*40) prod2 = input("Digite o nome do proximo produto: ") qnt2 = int(input("Digite a quantidade desse produto: ")) valor2 = floa...
1cfb98d1eec5c0a1a69abfd47fe702cd3b94c721
PranaKnight/Dominando-Python
/Exercicios/Exercícios2.py
373
3.9375
4
#Mais Exercícios from typing import AsyncIterable X = 0.0 Y = 18 print(type(X)) print(type(Y)) Z = X + Y print(Z) print(type(Z)) #Exercícios Propostos Base = 9 Altura = 6 Area = Base * Altura/2 print(Area) #Exercício 2 Base = float(input("Digite a base do triângulo: ")) Altura = float(input("Digite a altura do t...
7d11564338a3b1f1add3d647eb7bf2fff00910fd
PranaKnight/Dominando-Python
/print.py
1,000
4.34375
4
#Formas de imprimir o número para o usuário em Python print("Este é o capítulo 2 do livro") A = 12 print(A) B = 19 print(B) print(A, B) print("Valor de A =", A) print("Valor de A = {0} e valor de B = {1}" .format(A, B)) print("=+"*40) print(A, B, sep="-") print(A, B, sep=";") #utilização de separadores print("...
e2fbe803a41a511ee61d54e4ce0a30cce767455f
Wangjielong/RecNet
/codes/metrics.py
2,448
3.5
4
import numpy as np epsilon = 0.00001 def corr(x, y): """ calculate the correlation coefficient """ dim_x = len(x.shape) dim_y = len(y.shape) assert dim_x == dim_y if dim_x <= 2: x_mean, y_mean = np.mean(x), np.mean(y) numerator = np.sum((x - x_mean) * (y - y_...
360f67c84b59993cbe965e6838af19b4d759b227
che-phd/codingbat-python
/Logic-2/make_chocolate.py
821
4.0625
4
''' We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done. make_chocolate(4, 1, 9) → 4 make_chocolate(4, 1, 10) → -1 make_chocolate(4, 1, ...
8098951d28b3ca5f954b63e74ab6d887b0664e9f
lyndsiWilliams/cs-module-project-iterative-sorting
/src/searching/searching.py
1,337
4.25
4
def linear_search(arr, target): # Your code here # Loop through the length of the array for i in range(len(arr)): # If this iteration matches the target value if arr[i] == target: # Return the value return i return -1 # not found # Write an iterative impleme...
583d8cdb70b8c62045ae09fd10892ef15c01a5d7
srhtkaya/project-euler
/problem-10/code.py
453
3.953125
4
#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. #Find the sum of all the primes below two million. def is_prime(n): if n == 2 or n == 3: return True if n % 2 == 0: return False for i in range(3, int(n**0.5)+1, 2): if n % i == 0: return False return True def...
d7882832e58255c2eebbc8960a87f0dd7a338992
BaseCampCoding/unit-project-2-matthew-and-andy
/database.py
724
3.515625
4
import sqlite3 con = sqlite3.connect('highscore.db') cur = con.cursor() try: cur.execute("""CREATE TABLE HighScore( Name TEXT, Wave INTEGER, Kills INTEGER )""") except: pass def close(): return con.close() con.commit() def insert_score(score):...
17608b1b5ccab68c060363c1f7e5b7b369e950c0
murugan007vijay/python
/Sum of natural number upto N.py
115
3.625
4
# python sum of natural number upto N limit=int(input()) s=0 for count in range(1,limit+1): s+=count print(s)
50625f0de7315158259ecc08c3cf50bfbe1e0ec0
izza-khalid/ICS3U-Unit4-07-Python
/1_2.py
387
4.0625
4
#!/usr/bin/env python3 # Created by: Izza Khalid # Created on: November 2019 # This program prints the numbers from 1000-2000 def main(): # this function prints the numbers from 1000-2000 # process & output for counter in range(1000, 2001): print(str(counter) + " ", end="") if (counter %...
40e6c03c83f1e75aff2411e53ff5cab840ea4b84
cezarygarbacz/pyt0
/wsti.py
420
3.796875
4
#a = 2 #print(a) #a = 'Tekst' #print(a) #b = input('Podaj swoje imie: ') #c = int(input('Podaj swoj wiek')) #print('Witaj ' + b) #if c < 18: # print('Jestes pelnoletni ' + b ) #elif c == 25: # print('Zaraz skonczysz studia ' + b) #numers = [1,2,3,4,5,6] #for numer in numers words = ['WSTI',' ', 'studia'...
bb4eebc523c16d08fa53eecfa4a303749792b2f9
zhanghaiting001/PythonCoding
/SpellingCorrector/spell.py
4,263
3.640625
4
import re from collections import Counter def words(text): return re.findall(r'\w+',text.lower()) #WORDS = Counter(words(open('big.txt').read())) #file没有close with open('big.txt') as f: #text = f.read() #这样要分配内存?应该是都要分配的 #print(type(text),len(text),type(words(text))) # str , 6488666 ,list WORDS = Counter(wo...
d3c8ad91369d4e03877958efdb9c055807668a18
cdong223/2019-09-02Class
/basics.py
542
3.96875
4
# basics.py script #easier if broken down into modular functions x = input("Input a command: ") print("You entered {}.".format(x)) #print variable within string if x == 'add' or x == 'a': #start defining new code block print("Add") a = 1 b = 2 print("a = {}".format(a)) c = a + b print("{} + {} =...
c37468a0dccbbef24200605af97c46cecb03b80a
mayukhrooj/Hackerrank
/setbuild.py
495
3.84375
4
# #!/udr/bin/env python # # for x in range (1,7): # # print (2**x) # for x in range (1,14): # if x%2==1: # print(x) # months_of_year = ["january","february","march","april","may","june","july","august"] # for x in months_of_year: # if x.startswith("j"): # print(x) # for x in range (1,10)...
6ecc16083a8049d65df15b0589e35aac4adaedd5
JiaMingLin/privbayes
/src/main/python/find_max_min.py
747
3.796875
4
import pandas as pd df = pd.read_csv('../../../resources/fakedata_pandas.csv') print "age1 maximal: "+str(df["age1"].max()) + ", minimal: "+str(df["age1"].min()) print "age2 maximal: "+str(df["age2"].max()) + ", minimal: "+str(df["age2"].min()) print "height maximal: "+str(df["height"].max()) + ", minimal: "+str(df["he...
ddfd2a9d33efe3a77ba01b143b3466e571b3ca5c
cameronbrennan/tt-companion
/scripts/races-scrape.py
2,224
3.75
4
# Python API Scraper to populate Races in the DB from logging import error from dotenv import load_dotenv, find_dotenv import urllib3 import json http = urllib3.PoolManager() load_dotenv(find_dotenv()) API_URL = "https://www.dnd5eapi.co" def get_database(): from pymongo import MongoClient import pymongo ...
f04167639ad0509853dc1c01fa872b250fc95863
mraguilar-mahs/AP_CSP_Into_to_Python
/10_23_Lesson.py
429
4.1875
4
#Lesson 1.3 Python - Class 10/23 #Obj: #Standard: #Modulus - Reminder in a division: # Ex 1: 9/2 = 4 r 1 # Ex 2: 4/10 = 0 r 4 # modulus: % --> 9 mod 2 print(9%2) print(234%1000) print(10%2) print(9%2) # <- with mod 2, check for even/odd # Mod can check for divisibility, if equal to 0 #User Input: user_name = str(in...
d8c4c9b73b5537685496a2216616a341bc10ac05
krishnagrover1000/My-Python-Work
/Lists Refrence.py
470
4.25
4
#%% # List == Collection Of Data Types a = [1, 2, 3, 9, 8, 6, 12, 456] b = [1, "String", 'icji', 0.765, True] c = ["Aryan", "Vardaan", "Niya"] x = ["Aryan", "Vardaan", "Ajay"] y = ["Cool", "Is", "Cool"] z = ["Niya", "Is", "Smart"] #%% # Printing Out Index's From [] print(x[0], y[1], z[2]) #%% # This Rever...
c8d7a64827316fdd18c9cdfe17185a9f8e9d4c05
wsprin3/Cryptochecker
/CoinMarketCap.py
4,628
3.6875
4
import locale import requests locale.setlocale(locale.LC_ALL, '') url = "https://api.coinmarketcap.com/v2/ticker/" data = requests.get(url) data_json = data.json()["data"] def searchanother(): print("Search for another coin? (Y/N)") answer = input().lower() # userinput if answer == "Y".low...
f32ebf5bd8597507dbbe23ac786bf5c458a56f96
daniloroddrigues/rdcompare
/rdcompare.py
1,696
4.0625
4
""" Compartilhamento de dados, procurar pelo email achar em outro base de dados o mesmo cliente e verificar se o mesmo tem outros atributos caso tenha pegar estes dados e colocar no cliente que fez a requisiçao. """ def list_compare(d1, d2): if d1 == {} or d2 == {}: return 'Email vazio' return organiz...
55e5d0b66d05be9f64ae849237a68062c14c6006
wisnuaga/kriptografi-uts
/caesar_cipher.py
1,265
3.765625
4
class Caesar: _start_char = 65 _length_of_char = 26 _end_char = 90 def __init__(self, message, key): self.message = message.upper() self.key = key #hapus karakter selain (A s/d Z) def __remover(self, char): return (ord(char) >= self._start_char) and (ord(char) <= self._...
3305914312e878a5e9de8f95b10519d67c929592
nadralia/iReporter_ch3
/api/helpers/validations.py
3,978
4.25
4
import re class Validation: def check_if_input_is_number(self, input_value): """function to checks if input value is a number""" if isinstance(input_value, int) or isinstance(input_value, float): return True return False def check_if_input_value_is_string(self, input_v...
064717582f1799c539e0df68005379819f932491
cristianoxavier/Campinas-Tech-Talents
/Exercicios/15.py
779
4.1875
4
# Fazer um sistema de Feira Livre(Deve imprimir uma lista com as frutas e pedir para o solicitante colocar o nome e selecionar a fruta e depois deve imprimir o nome do solicitante e a fruta). frutas = { "Banana" ,"Maça" ,"Tomate" ,"Melancia" ,"Uva" ,"Ameixa" ,"Pera" ,"Goiaba" ,"Ac...
546fe8f41c1ced9ca14bada2ae7474e4d7bf9110
cristianoxavier/Campinas-Tech-Talents
/Aula_012 - Dicionarios/deletando-elementos-dicionario.py
373
3.625
4
dict_compras = {"Nome":"Secador de cabelo","Preço":"R$ 1000,00", "Tamanho":"Médio"} print(dict_compras) # #Excluí todos os elementos mas não excluí o dicionario da memória # dict_compras.clear() # print(dict_compras) # #Exclui o dicionário da memória # del dict_compras # print(dict_compras) # #Excluí um elemento do di...
e6a292d99dae34dd81c792d81910d0f2095663ec
cristianoxavier/Campinas-Tech-Talents
/Aula_004/dicionarios.py
802
4.21875
4
''' Dicionario é mais proximo do JSON. Dicionarios recebem valores sensiveis, devem se respeitar os tipos de dados(string, int, float, boolean...) São definidas chaves e valores. Ex: dict = {'Keys': 'value', key: value, key: true or false} ''' dict = {} dict['one'] = "This is one" dict[2] = "This is two"...
936e7c95398e6ba7664f1bc2f5e31f8b14d13a91
cristianoxavier/Campinas-Tech-Talents
/Aula_010 - Listas/funcoes-lista.py
640
3.71875
4
lista_suco = ['laranja', 'uva', 'abacaxi', 'manga'] tupla_suco = ('laranja', 'uva', 'abacaxi', 'manga') lista_refrigerantes = ['coca','guaraná','laranja', 'uva'] # #Não existe cmp no python 3 # #print(cmp(lista_refrigerantes, lista_suco)) # print(max(lista_suco)) # print(min(lista_suco)) # print(len(lista_suco)) # pri...
a4bd5e100a710fb1e8efdd0132324795da4f64af
cristianoxavier/Campinas-Tech-Talents
/Exercicios/3.py
648
4.21875
4
#Algoritmo para trocar o pneu do carro (Imprimir a sequência para trocar o pneu do carro). print("Bem vindo, você gostaria de trocar o pneu do carro?") trocar = input("Sim? ou Não?: ") if trocar == "Sim" or "sim": print("Qual dos pneus quer trocar?") escolha1 = input("Os da frente? ou os de tras?: ") if ...
91a183ff1698476f7599e0ae17d5f33e1543eb27
cristianoxavier/Campinas-Tech-Talents
/Aula_013 - Depurar/debbuger.py
141
3.921875
4
entrada = input("Coloque um valor") if entrada.isnumeric(): print("Você digitou um número") else: print("Voce digitou outra coisa")
b153ca6d2a85480e3f4c8de2ee521c72709c69d2
cristianoxavier/Campinas-Tech-Talents
/Exercicios/1.py
220
3.90625
4
#Algoritmo para ligar um carro (Imprimir a sequência para ligar um carro) print("Voce deseja ligar o carro?") ligar = input("Digite sim ou não. ") if ligar == "sim": print("Ligou") else: print("Não ligou")
e7e0fd0276916232451379dc8783c055aaf3d501
Harshi4501/1-7-20
/7(4).py
128
4.28125
4
#program to find the length of a dictionary dict1={1:'a',2:'b',3:'c',4:'d',5:'e'} x=len(dict1) print("length of dict1 is",x)
72bd1d07ce5608403557ab8daeba3132fac1b1b8
anakind/anagram-webapp-python-flask
/anagram.py
2,578
3.8125
4
class Anagram: def __init__(self): self.requests = {} @staticmethod def checkIfAnagram(word1, word2): """ check if two words are anagram TC: O(n), n is max character of the two words Args: word1 (str): The first parameter. word2 (str): The se...
415c7fdb912facb7ba4ac4d5c57de598374a8dea
merimus/coding-bootcamp
/euler/merimus/27/27.py
1,202
3.875
4
import math class GenPrime(object): def __init__(self): self.primes = [2, 3, 5, 7] def Primes(self): for p in self.primes: yield p while True: yield self.GenPrime() def IsPrime(self, n): cuttoff = math.sqrt(n) for p in self.primes: ...
a68fdd9358fcf12395ab54812119a0def2c1d3ab
merimus/coding-bootcamp
/euler/merimus/38/38.py
597
3.59375
4
import math def pandigital(n, m): digits = [] # take n and multiply it by 1..m, return true # if the results are pandigital. for i in range(1, m+1): digits += list(str(n * i)) if len(digits) != 9: return False s = set(digits) if len(s) != 9: return False if '0' i...
6b47f775f3db0057c3d0573051687cbc05a5afe6
dariianastasia/Instructiuni-de-introducere-aplicatie-practica-
/exercitiul.5.py
238
3.5
4
""" Ion si Vasile joaca urmatorul joc: Ion spune un numar iar Vasilii trebuie sa gasesca cinci numere consecutive, crescatoare, numarul e mijloc fiind cel ales de Ino.""" n=int(input("Introdu numarul:")) print(n-2,n-1,n,n+1,n+2,sep=" ")
6abf7952614dfc1d17f235c7050f599be5d9f8ae
dariianastasia/Instructiuni-de-introducere-aplicatie-practica-
/exercitiul.12.py
552
3.5625
4
"""Intr-o gospodarie sunt 4 gaini.Introduceti in calculator prin variabilele a,b,c,d numarul de oua pe care-l da fiecare gina intr-o zi.Afiseaza cate oua se obtin intr-o saptamina""" a=int(input("introdu a:")) b=int(input("introdu b:")) c=int(input("introdu c:")) d=int(input("introdu d;")) sa=a*7 sb=b*7 sc=c*7 ...
cd43f3e8377c6915d315cd71e0d9d5be0e894fd8
GustavoMarzullo/Livro-Guttag
/Integrais/Integral_Simpson.py
807
3.75
4
import numpy #regra de simpson para integrais definidas def integral(f,a,b,n=1e3 ): '''Usa a regra de simpson para retornar uma integral definida. Precisa-se definir uma função f anteriormente.''' assert n%2==0, 'O n precisa ser par.' deltax=(b-a)/n try: soma_I= f(a)+f(b) so...
f245fc351674c0c9c3355c9315080ff376255015
siddharthsingh/cracking-the-coding-interview-solutions-in-python
/chapter4/4_4BalancedBinaryTree.py
881
3.859375
4
class Node(): def __init__(self,name): self.name = name self.left = None self.right = None def __str__(self): return self.name def __repr__(self): return self.name root1 = Node(5) root14 = Node(5) root13 = Node(5) root16 = Node(5) root17 = Node(5) root1.left = roo...
4227497ba20129c71e4a9a6d9f836b482cac7740
siddharthsingh/cracking-the-coding-interview-solutions-in-python
/chapter4/4_9BSTSequence.py
1,217
3.734375
4
class Node(): def __init__(self,name): self.name = name self.left = None self.right = None self.parent = None def __str__(self): return str(self.name) def __repr__(self): return str(self.name) root3 = Node(12) root310 = Node(10) root39 = Node(9) root38 ...
75d3af6f722c3f1682b216829807793188598816
siddharthsingh/cracking-the-coding-interview-solutions-in-python
/chapter2/2_8loopDetection.py
1,447
3.96875
4
class Node(): def __init__(self, data): self.data = data self.next = None node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node6 = Node(6) node7 = Node(5) node8 = Node(6) head = node1 node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node2 head2 ...
1fffe9ae02c65e0ded73b72547c86e1628470475
siddharthsingh/cracking-the-coding-interview-solutions-in-python
/chapter5/5_4NextNumber.py
926
3.625
4
def next_largest(number,size): first_one_found = False for i in range(size): bit = get_bit(number,i) if bit == 0 and first_one_found: number = clear_bit(number,i-1) number = set_bit_one(number,i) return number elif bit: first_one_found = Tr...
1624c76e5a4cbe05203712959673e9242e3834a5
siddharthsingh/cracking-the-coding-interview-solutions-in-python
/chapter1/1_9stringRotation.py
572
4.0625
4
def stringRotation(str1,str2): if not str1 or len(str1)!= len(str2):return False for i,char in enumerate(str1): wrong = False for j in range(len(str1)): if str1[(j+i)%len(str1)] != str2[j]: wrong = True if not wrong: return True return False...
7f5fdc6d6bb833da16ede7d4946c27ad3a7a9565
siddharthsingh/cracking-the-coding-interview-solutions-in-python
/chapter3/3_6AnimalShelter.py
1,991
3.84375
4
class Node(): def __init__(self, name): self.name = name self.next = None self.prev = None class shelter(): def __init__(self): self.queue = None def enqueue(self,animal): if not animal or animal not in ('cat','dog'): raise Exception("Animal not suppor...
71facb2002e13faf50d5f93aadb0d3420c49bc5d
sumukhbh/SearchingandSorting
/BinarySearch.py
564
4.09375
4
# Implementation of Binary Search # # Returns the index of the element if it's found else return -1 # def binary_search(array,target): low = 0 high = len(array)-1 while low <= high: mid = (low+high)//2 if array[mid] == target: return mid else: if array[mid...
64d928cb5450e0fc4728e0fa8562c73ed62b94b2
wilkice/Algorithms
/a3+b3=c3+d3.py
717
3.578125
4
''' find integer under 1000 to make a3+b3=c3+d3 ''' all_result = {} pairs_result = [] def add(num): for i in range(1,num+1): for j in range(i, num+1): result = i ** 3 + j ** 3 # 不在字典里就添加 if result not in all_result.keys(): all_result[result]=[(i,j)] ...
a1f4cc9a7b531b3bcbd01ac5eb1285ee44d1e51f
abhishekk26/NashVentures
/Random number Generation.py
2,066
4.1875
4
import math, time class MyRNG: # MyRNG class. This is the class declaration for the random number # generator. The constructor initializes data members "m_min" and # "m_max" which stores the minimum and maximum range of values in which # the random numbers will generate. There is another variable ...
c9fbbb34297ae59dde495f9b7ed3d2890ae1148e
Vikasshende/Competive-programming
/ThreeNProblem.py
370
3.53125
4
def Problem(x): count=1 while( x != 1): if( x%2 == 0): x= x / 2 count = count+1 else: x = 3 * x + 1 count = count +1 return count x,y=input().split(' ') x=int(x) y=int(y) max =Problem(x) while(x<=y): max1=Problem(x) x=x+1 if(max>=max1): ...
d6c3ad79ba0ef333539b47ec29d69c1be4aed1ab
bmogo01/ew432_Battleship
/human.py
8,150
4.125
4
import ship, game_board, sprites from random import randint from typing import List, Tuple, Optional class Human: """ A human player""" def __init__(self): # list of ship objects self._my_ships: List[ship.Ship] = [] # list of (row,col) coordinates self._my_misses: List[Tuple...
991fd4bcff231bf250e2defde4d18840cf90aad4
44zakk44/ZakkWorks
/test.py
161
3.65625
4
name = "Luc" if name is "Lol": print("Hey Lol") elif name is "Lucy": print("Whats up") elif name is "Maciek": print("eee") else: print("go out")
1c5eba44ed3bc1ae234f376092f030fe5128a613
priscrisant/python_exercises
/passw.py
578
3.765625
4
#!/usr/bin/env python class Passw: def __init__(self): print "------------------------------------" print "Hello! This is your Password Manager" print "------------------------------------" def info(self): user = raw_input(''' Hello. Please, type the option you want to access: 1) Insert a new information...
bb5d6c3a34becee068d91b8ea4ff272dbc574ef2
priscrisant/python_exercises
/tuple_parameters.py
279
3.859375
4
#!/usr/bin/env python class Base: def __init__(self, *letters): self.letters = letters def print_out(self): print str(self.letters) + "\n" for item in self.letters: print item if __name__ == '__main__': root = Base("Apples", "Juice", "Fruits") root.print_out()
848d8423674938a034be006fb703910f2ef4aaaa
priscrisant/python_exercises
/most_common_word.py
586
3.8125
4
#!/usr/bin/env python d = {} planets = ["Jupiter", "Mars", "Jupiter", "Venus", "mars", "mars", "mars", "Uranus"] print "this is the list of planets:\t" + str(planets) '''for name in planets: if name not in d: d[name]= 1 else: d[name] = d[name] + 1 print d''' #short line code for name...
58a77f35419cdd208fd3772c380b95a4592be7c6
ashishrawat13/git
/db/assg-15.py
1,407
3.75
4
#Ques_1. import sqlite3 try: con=sqlite3.connect('Students.db') cur=con.cursor() query='create table Marks(Name varchar(10),Marks int(3))' cur.execute(query) print("Succesful") con.commit() except: if con: con.rollback() print("Rolled Back") finally: if con:...