blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e9d2989735d55c509fc024da40cf942046683a44 | SHINE1607/coding | /problems/introductory/palindrome_reorder.py | 849 | 3.796875 | 4 | from collections import Counter
def palindrome_reorder(string):
if len(string) == 1:
print(string)
return
counter = Counter(string)
<<<<<<< HEAD
freq_arr = list(counter.values()).sort(reverse = True)
if freq_arr[-1]%2 == 1 and freq_arr[-2]%2 == 1:
print("NO SOLUTION")
r... |
104a2ee46119baba627d748a98ecc50f65d8757b | SHINE1607/coding | /dynamic_programming/recursive_staircase.py | 609 | 3.671875 | 4 | # given the number of steps we can take at a time howe mkany tyital number of ways to climb given number of steps
from collections import defaultdict
def find_climb(n, steps):
dp = defaultdict(lambda:[0] * (n + 1))
steps = [0] + steps
dp[0][0] = 1
for i in range(1, len(steps)):
if steps[i] > n:
... |
fb272460636079c87d718e04c6c404fcc9cbd4b4 | SHINE1607/coding | /problems/introductory/apple_division.py | 721 | 3.546875 | 4 |
diff = 0
final_ans = 0
def division_rec(arr, i, s, target):
global diff
global final_ans
if i == -1:
return
if abs(s - target) < abs(diff):
final_ans = s
diff = s - target
# print(s, diff, i, "check")
return division_rec(arr, i - 1, s, target) or divi... |
2edd67084f46c9f82718aaff7400834c77b3b9de | SHINE1607/coding | /DSA/Tree/test.py | 847 | 3.953125 | 4 | import random
def merge(left, right):
left_pointer = 0
right_pointer = 0
res = []
while left_pointer < len(left) and right_pointer < len(right):
if left[left_pointer] < right[right_pointer]:
res.append(left[left_pointer])
left_pointer += 1
else:
... |
0a6f3cc34c38e3206bc990fb6871c90c27540c46 | jainish008/Python-Tkinter-GUI | /Python Tkinter11.py | 692 | 3.578125 | 4 | import tkinter
james_root = tkinter.Tk()
james_root.title("Harrison GUI")
james_root.geometry("1020x920")
#For creating an event where you left click, right click and midddle click on mouse
#There will message printed on the screen
#Create function for each click
def left_click(event):
tkinter.L... |
e43a26b995241c17fa4aa011325e2516e6bf2673 | guyrt/teaching | /2017/Com597I/wordplay/exercise2_fancy.py | 1,755 | 4.09375 | 4 | # What is the longest word that starts with a 'q'?
# Since more than one word is as long as the longest q word, let's find them all.
import scrabble
longest_word_length_so_far = 0
longest_words = [] # empty list.
for word in scrabble.wordlist:
if word[0] == 'q':
# If the current q word is longer than t... |
5f51862837f6a87aa2428b8dc11a69c217876a61 | guyrt/teaching | /2017/Com597I/wordplay/words2.py | 348 | 3.96875 | 4 | import scrabble
# Print all letters that never appear doubled in an English word.
for letter in "abcdefghijklmnopqrstuvwxyz":
exists = False
for word in scrabble.wordlist:
if letter + letter in word:
exists = True
break
if not exists:
print("There are no English word... |
e8b6047ae138cc73b6faf3d02118daff26c6a5f6 | Sheetal777/ds-algo | /Codechef/Practice Problems/16_factorial.py | 150 | 3.828125 | 4 | import math
t=int(input())
while(t!=0):
n=int(input())
if(n==0):
print("1")
else:
print(math.factorial(n))
t=t-1 |
43643bcae9e44a206b904bfe1e6ca25622a3dc19 | YChaeeun/startPython | /problems/TODO_maze_findEVERYpath.py | 1,519 | 3.75 | 4 | # 미로탈출하기
# 그래프
# 다양한 경로를 모두 찾으려면 어떻게 해야 할까??? 흠...
def findPath(maze, start,end) :
qu = list()
visited = set()
result = list()
qu.append(start)
visited.add(start)
while qu :
path = qu.pop(0)
print(path)
print('v', visited)
v = path[-1]
if v == ... |
6d3c696a35a8620f6f23fa3e18b16acc0082cc3a | YChaeeun/startPython | /Algorithm/Search/linear_search_2.py | 790 | 3.9375 | 4 |
# 여러 개의 값들의 위치를 찾을 때 O(mn)
def linearSearch_2(listofNum, findNumList):
numidxList = list()
for i in range(0, len(listofNum)):
for findNum in findNumList :
if listofNum[i] == findNum :
numidxList.append(i)
findNumList.remove(findNum)
return numidxList
# 중... |
33dd6a8476e08c199627014c1942ba98865f027b | YChaeeun/startPython | /Algorithm/Search/binary_search.py | 931 | 3.859375 | 4 | # Binary Search
# O(logN)
def binarySearch(listofNum, num) :
start = 0
end = len(listofNum)-1
while start <= end :
mid = (start+end) //2
if listofNum[mid] == num :
return mid
elif listofNum[mid] < num :
start = mid +1
elif listofNum[mid] > num :
... |
47ae53a54f9ed6a820edeada248a32b26e63c4ad | manishaverma1012/Hackerank_Solution | /hackerrank_subset.py | 319 | 3.53125 | 4 | a = int(input())
for i in range(a):
x = int(input())
m = set(map(int,input().split()))
y = int(input())
n = set(map(int,input().split()))
if(m.intersection(n)==m):
print("True")
else:
print("False")# Enter your code here. Read input from STDIN. Print output to STDOUT
|
acdf7d7a23f60edc8c40c5fa2a6edf12953b365b | manishaverma1012/Hackerank_Solution | /Prob&Stats_hackerrank/day5_normaldist_I.py | 329 | 3.875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
n1=list(map(int,input().split()))
n2=float(input())
n3=list(map(int,input().split()))
def norm(x):
c=0.5+0.5*math.erf((x-n1[0])/(n1[1]*math.sqrt(2)))
return c
a=norm(n2)
print("%.3f"%a)
b=norm(n3[1])
d=norm(n3[0])
z=b-d
print("... |
2dcb7d75d6413a37b762ba3d6d084970ea19aa6d | huidou74/studypy | /abc_xyz.py | 395 | 3.734375 | 4 | #!/usr/bin/python
import itertools
#for a in itertools.permutations('abc'):
# print a[0], a[1], a[2]
# if ( a[0] != 'a' ) and (a[-1] != 'a' ) and (a[-1] != 'c'):
# print "x vs %s, y vs %s, z vs %s" % (a[0], a[1], a[2])
for i in itertools.permutations('xyz'):
if (i[0] != 'x') and (i[-1] != 'z') and (i[-... |
43a63cdbe3ae31d0b9fcf463f692314db5caba38 | tanksoga/leetcoetraining | /python/Array_List_Dict/E_reverseInteger.py | 561 | 3.546875 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x <= -2**31 or x >= 2**31-1:
return 0
xString = str(x)
if(x < 0):
xString = xString[1:]
reserved = "-" + xString[::-1]
... |
eeacf68f45fcd301029696cfed9d296c20b5bdc3 | tanksoga/leetcoetraining | /python/Array_List_Dict/M_productOfArrayExceptSelf.py | 818 | 3.5 | 4 | class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
left = [0]*length
right = [0]*length
result = [0]*length
if(length == 1):
return [0]
... |
1eea2ef3b2e2839b465b3ad53e10db717ac2584e | tanksoga/leetcoetraining | /python/Array_List_Dict/E_isomorphicStrings.py | 842 | 3.59375 | 4 | class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
exist1 = {}
exist2 = {}
pattern1 = []
pattern2 = []
for i in range(len(s)):
if(s[i] not in exist1):
... |
0a7ae1e3382702f86426b0e877c218ec99282ca5 | tanksoga/leetcoetraining | /python/LinkedList/E_mergeTwoSortedList.py | 1,032 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
#def main():
# l1 = [1,2,4]
# l2 = [1,3,4]
# print(mergeTwoLists(l1,l2))
def mergeTwoLists(self,l1, l2):
... |
d4b9a7934d27d1cf86d22569f3ddc5bb048bfaaf | tanksoga/leetcoetraining | /python/Tree/E_symmetricTree.py | 1,013 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def isSameTree(self, p, q):
if not p and not q:
return True
... |
8ec6d68bf147723fdd82c755843d96427687d1b1 | icyflame/cows-and-bulls | /solutionToRepeatedNumberIssue.py | 353 | 3.53125 | 4 | def digits(number):
return [int(d) for d in str(number)]
def bulls_and_cows(guess, target):
guess, target = digits(guess), digits(target)
bulls = [d1 == d2 for d1, d2 in zip(guess, target)].count(True)
bovine = 0
for digit in set(guess):
bovine += min(guess.count(digit), target.count(digit))
... |
1ae7cdf0c2e2b51586428e3627ee4244e9650cab | eduardrich/Senai-2.1 | /3.py | 529 | 4.1875 | 4 | #Definição da lista
Val = []
#Pede para inserir os 20 numeros para a media
for c in range(0,20):
Val.append ( int(input("Digite aqui os valores para a média: ")) )
#detalhamento da soma e conta dos numeros dentro da lista
SomVal = sum(Val)
NumVal = len(Val)
#Tira a media
MedVal = SomVal / NumVal
print("Media da... |
346439bc872487e4c174e4fa32c319e42890d673 | tokitsubaki/labcode | /exception/exception_python.py | 401 | 3.59375 | 4 | import traceback
def main():
try:
print("before exception.")
raiseException()
print("after exception.")
except Exception as e:
print(traceback.format_exc())
else:
print("not exception.")
finally:
print("finally.")
def raiseException():
print("before ... |
f80d5a2755c78577e7f72af1e800410841b4c1e1 | tokitsubaki/labcode | /string/string_python.py | 3,239 | 4.25 | 4 | # coding: utf-8
# +演算子による結合
s1 = "Hello"
s2 = "Python"
r = s1 + s2
print(r) # HelloPython
# 配列を結合
a = ["Python","Hello","World"]
r = " ".join(a)
print(r) # Python Hello World
# printf形式による文字列の埋め込み
s1 = "Python"
s2 = "Hello"
r = "%s %sWorld!!" % (s1, s2)
print(r) # Python HelloWorld!!
# formatメソッドによる文字列の埋め込み
s1 = "P... |
3fa2fe6caf2a0cfda09a745dc8c7fceb7d381e5a | YayraVorsah/PythonWork | /lists.py | 1,673 | 4.4375 | 4 | names = ["John","Kwesi","Ama","Yaw"]
print(names[-1]) #colon to select a range of items
names = ["John","Kwesi","Ama","Yaw"]
print(names[::2])
names = ["John","Kwesi","Ama","Yaw"]
names[0] ="Jon" #the list can be appended
print(names)
numbers = [3,4,9,7,1,3,5,]
max ... |
f2cacc2f354655e601273d4a2946a2b27258624d | YayraVorsah/PythonWork | /conditions.py | 1,769 | 4.1875 | 4 | #Define variable
is_hot = False
is_cold = True
if is_hot: #if true for the first statement then print
print("It's a hot day")
print("drink plenty of water")
elif is_cold: # if the above is false and this is true then print this
print("It's a co... |
be1c35404de416884e0f1bb3b7ea274580183d9e | tarunbodapati/sum.c | /67.py | 145 | 3.765625 | 4 | x=int(input())
count = 0
for i in range(1,x//2+1):
if(x%i==0):
count+=1
if(count==1):
print("yes")
else:
print("no")
|
bff63a51a92406fc98df5343b90e3e3f1f8a912e | tarunbodapati/sum.c | /72.py | 186 | 3.71875 | 4 | x=list(input())
count=0
for k in x:
if((k=='a')or(k=='e')or(k=='i')or(k=='o')or(k=='u')):
count=count+1
if(count>0):
print("yes")
else:
print("no")
|
4193da24dc0234d54099637767c82ec70fba8a94 | tarieli-d/vigenere_python | /list.py | 1,196 | 3.859375 | 4 | from src import *
def encrypt(start_text, keyword):
end_text = []
for e, let in enumerate(start_text):
if let.isalpha():
len_sum = char_position(let) + char_position(keyword[e])
end_text.append(pos_to_char(len_sum % 26, let))
else:
end_text.append(let)
re... |
c116516eaa8d833f3b7db5b3b52a6718db6bf353 | sbowl001/cs-module-project-hash-tables | /applications/histo/histo.py | 371 | 3.578125 | 4 | # Your code here
with open("robin.txt") as f:
words = f.read()
split_words = words.split()
cache = {}
for word in split_words:
if word not in cache:
cache[word] = '#'
else:
cache[word] += '#'
items = list(cache.items())
items.sort(key = lambda x: x[1], reverse= True)
for key... |
8e6a9399680541756605b4d687bf44b7388c5652 | Kul0l0/myLeetCode | /algorithms/1221. Split a String in Balanced Strings/Solution.py | 425 | 3.625 | 4 | class Solution:
def balancedStringSplit(self, s: str) -> int:
stack = []
res = 0
for i in s:
if len(stack)>0 and stack[-1]!=i:
stack.pop(-1)
if len(stack) == 0:
res += 1
else:
stack.append(i)
... |
23f02f1df0a5e3cf3f053a220e6482290f657f95 | LuisMalave2001/GarryTesting | /school_base/utils/commons.py | 559 | 3.90625 | 4 | # -*- coding: utf-8 -*-
def switch_statement(cases, value):
""" Simulate a swithc statement """
return cases[value] if value in cases else cases["default"] if "default" in cases else False
def extract_value_from_dict(parameter: str, values: dict):
""" Extract a value from values dict
Args:
pa... |
3dec2822d414f2848e1f2d6bf4e00b71b3e1e0a2 | choulilove/Sort__by__python | /DataStructure/排序/基数排序.py | 913 | 4.03125 | 4 |
'''
实现基数排序RadixSort, 分为:
最高位优先(Most Significant Digit first)法
最低位优先(Least Significant Digit first)法
'''
# 最低位优先法
def radixSortLSD(alist):
if len(alist) == 0:
return
if len(alist) == 1:
return alist
tempList = alist
maxNum = max(alist)
radix = 10
while maxNum * 10 > radix:
... |
cfc689c826196a77c7eb4e0c9873a78a668fc7e6 | ronniepereira/python-academy | /modulo_04/exercicio_01.py | 112 | 3.71875 | 4 | nota = int(input("Digite a nota do aluno: "))
if nota >= 60:
print("Aprovado")
else:
print("Reprovado") |
1a996993caa0dbcc09e7bd7450c2787d5d9b278f | GauravInprosys/AGS-intern-files | /Sujeet/assinment1.py | 309 | 3.59375 | 4 | import pyodbc
#https://towardsdatascience.com/sql-server-with-python-679b8dba69fa
conn = pyodbc.connect('Driver={SQL Server};''Server=DESKTOP-CAFAM2K\SUJEETPATIL;''Database=Agsdb;''Trusted_Connection=yes;')
mycursor = conn.cursor()
mycursor.execute("select * from table1")
for row in mycursor:
print(row) |
dc9b8ab9789c9fa3278a989e467d0e84098f9c71 | CodecoolBP20161/a-mentor-s-life-in-an-oo-way-act-1 | /story.py | 4,761 | 3.609375 | 4 | from assignment import Assignment
from codecool_class import CodecoolClass
from electronic import Electronic, Laptop
from feedback import Feedback
from mentor import Mentor
from student import Student
from colors import Colors
print(Colors.OKBLUE + "\nThe ACT presents an (almost) average day in codecool." + Colors.EN... |
eef2feeea33fd5b39b671f35d889b85306e8eb41 | colinsongf/SpellCheck | /test.py | 384 | 3.640625 | 4 |
def find_common_distinct_letters (word1, word2):
letters_word1 = []
letters_word2 = []
for i in range(0,len(word1)):
letters_word1.append(word1[i])
for i in range(0,len(word2)):
letters_word2.append(word2[i])
common_distinct_letters = list(set(letters_word1).union(set(letters_word2)))
return len(common_dis... |
881a8e4b1aa1eaed9228782eef2440097c2cb301 | siyangli32/World-City-Sorting | /quicksort.py | 1,439 | 4.125 | 4 | #Siyang Li
#2.25.2013
#Lab Assignment 4: Quicksort
#partition function that takes a list and partitions the list w/ the last item
#in list as pivot
def partition(the_list, p, r, compare_func):
pivot = the_list[r] #sets the last item as pivot
i = p-1 #initializes the two indexes i and j to partition with
... |
cd549e08ba3133720ce4e75ba416c4388c2a2e2c | sharanya-code/Basic-number-programs | /NUMBER GUESSING GAME.py | 513 | 4.03125 | 4 | #RANDOM NUMBER GUESSING GAME
import random#GETTING RANDOM IMPORT
n = random.randint(1, 99)
g = int(input("ENTER A NUMBER FROM 1-99: "))#INPUT A NUMBER
while n != g:
print
if g < n:#GUESS APPROXIMATION
print ("guess is low")
g = int(input("ENTER A NUMBER FROM 1-99: "))
elif g > n:
... |
5d686400257697cabfc20345ea4aa52c6a5cfc88 | sharanya-code/Basic-number-programs | /SUM OF DIGITS.py | 229 | 3.9375 | 4 | def sod():
#SUM OF DIGITS
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig#GETTING THE LAST DIGIT
n=n//10
print("The total sum of digits is:",tot)
sod()
|
08b37f326f0d4ab6dae5f95dd655ea2d9ef3f711 | mlobf/LogicRoutinePython | /logicTest/test9.py | 306 | 4.03125 | 4 | '''
Faça um Programa que peça a temperatura em graus Farenheit,
transforme e mostre a temperatura em graus Celsius. C = (5 * (F-32) / 9).
'''
temperatura_celsus = 0
def convert_celsus(temperatura_celsus):
celsus = ((temperatura_celsus - 32) / 1.8)
return celsus
print(convert_celsus(100))
|
415ae0cde3c5b6057f8bf2539d29917a253856ed | abhishekghz/Python-_Pygame- | /tut9..py | 625 | 3.65625 | 4 | import pygame
pygame.init()
# Colors
white = (255, 255, 255)
red = (255, 0, 0)
black = (0, 0, 0)
# Creating window
screen_width = 900
screen_height = 600
gameWindow = pygame.display.set_mode((screen_width, screen_height))
# Game Title
pygame.display.set_caption("SnakesWithSunny")
pygame.display.update... |
150810f760c409533200b7252912130cc72e792b | aiman88/python | /Introduction/case_study1.py | 315 | 4.1875 | 4 | """
Author - Aiman
Date : 6/Dec/2019
Write a program which will find factors of given number and find whether the
factor is even or odd.
"""
given_number=9
sum=1
while given_number>0:
sum=sum*given_number
given_number-=1
print(sum)
if sum%10!=0:
print("odd number")
else:
print("Even number")
|
ae7a9048dc6ab92cd5327423dadc83826494502f | aiman88/python | /Introduction/name.py | 143 | 4.125 | 4 | name = "Nurul Iman"
if len(name) < 3:
print("Less than 3")
elif len(name) > 50:
print("More than 50")
else:
print("Name look good")
|
96737e27981019e448f1eb5916ca21a80804f461 | igorlealantunes/APA | /diversos/prim/min_heap.py | 2,556 | 3.75 | 4 | class Min_heap:
def __init__(self):
self.list = [0]
self.size = 0
self.map = {}
"""
def fix_up(self, i):
while i // 2 > 0: # enquanto nao chegar na raiz
if self.list[i].v < self.list[i//2].v: # se pai for menor => troca
self.swap(i, i//2)
... |
a58b824da4b39594b99e05879c82a1e7bae54afd | mtoce/Intro-Python-I | /src/03_modules.py | 772 | 3.890625 | 4 | """
In this exercise, you'll be playing around with the sys module,
which allows you to access many system specific variables and
methods, and the os module, which gives you access to lower-
level operating system functionality.
"""
import sys
# See docs for the sys module: https://docs.python.org/3.7/library/sys.html... |
6724d61cc018556e22ea88f0617f66c72697aa35 | phoomct/Comprohomework | /combineString.py | 268 | 3.609375 | 4 | """ combineString """
def main():
""" Write a Python program to get a single string from two given strings, s
eparated by a space and swap the first two characters of each string. """
data = input()
data2 = input()
print(data2 +" " + data)
main()
|
1556d0ba32be359ed8f6955bd3957eb08bc6c6a2 | phoomct/Comprohomework | /Coffee Shop.py | 1,169 | 4.03125 | 4 | """ Coffee Shop """
def main():
"""The IT coffee shop sells 3 different types of coffess as follows:
Robusta coffee 390 baht per kg, ***Promotion Free 2 kg of Robusta coffee,
every 15 kg Robusta coffee order.
Liberica coffee 380 baht per kg, ***Promotion Free 2 kg of Liberica coffee,
every 15 kg Lib... |
42a3298e1978dfb8bc8e57114f4b1146a0389356 | phoomct/Comprohomework | /dayOfWeek.py | 276 | 3.953125 | 4 | """ dayOfWeek """
def main():
""" dayOfWeek """
import datetime
date = input()
day, month, year = date.split(":")
day, month, year = int(day), int(month), int(year)
dayofweek = datetime.date(year, month, day).strftime("%A")
print(dayofweek)
main()
|
3606dd083e4d948470fab5a3b2825a20140206a5 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Pattern/equilateralTriangle.py | 214 | 3.953125 | 4 | line = int(input("Enter the total line to print:"))
for i in range(1,line+1):
for j in range (i,line):
print(' ', end='')
for k in range (0, 2*i-1):
print('*', end='')
print() |
40df24e8679f2f9f829621c4c0672f8f1989c0a0 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Concepts/List/zip.py | 329 | 4.0625 | 4 | names = ['Bruce', 'Art', 'Peter', 'Tony', 'Steve']
heros = ['Batman', 'Joker', 'Spiderman', 'Iron Man', 'Captain America']
print(list(zip(names, heros)))
my_dict = {}
#for name, hero in zip(names, heros):
# my_dict[name] = hero
my_dict = {name: hero for name, hero in zip(names, heros) if name != 'Peter'}
print(m... |
ee60de3bbeeee63f6d5ed498a09f85f06c522a14 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Pattern/leftTriangle.py | 145 | 3.9375 | 4 | line = int(input("Enter the total line to print:"))
for x in range(1,line+1):
for y in range(1, x+1):
print('* ', end="")
print() |
3c0c83f6815358e853c8a01c1cbe2c5659870969 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Concepts/returnfun.py | 1,845 | 3.703125 | 4 | '''
def greet(lang):
if(lang == 'es'):
return('Holo')
elif(lang == 'fr'):
return('Bonjur')
else:
return('Hello')
print(greet('en'), 'Maxwell')
print(greet('es'), 'Steffy')
print(greet('fr'), 'Senthil')
list = ['a', 'b', 'c', 'd', 'e']
def list(lst):
del lst[3]
lst[3] = 'x'
... |
1dcd53777bbc5a41491d94db126568aeb489dffb | SenthilKumar009/100DaysOfCode-DataScience | /Python/Functions/packing.py | 136 | 3.578125 | 4 | def packing(*args):
sum = 0
for x in range (0, len(args)):
sum += args[x]
return sum
print(packing(1,2,3,4,5)) |
7aeea96916dbb1a0e22a6542b0472888a450cd7f | SenthilKumar009/100DaysOfCode-DataScience | /Python/OOP/classIntro.py | 451 | 3.78125 | 4 | class Dog():
species = 'Mammal'
myDogBreed = ['Lab', 'German', 'Country']
def __init__(self, breed, name):
self.breed = breed
self.name = name
def bark(self):
for breed in Dog.myDogBreed :
if self.breed == breed:
print('Woof!!!')
brea... |
f05174829075d9ae7eafb2cd345c3b2278e782cb | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/CollatzSequence.py | 131 | 3.78125 | 4 | def collatz(number):
if number % 2 == 0:
print(number/2)
else:
print(number * 3 + 1)
collatz(3)
collatz(4) |
9a1122730c0a44c5f9d19df4eb0cbc2b5ef04379 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/minoftwoArray.py | 381 | 3.90625 | 4 | pair = int(input('Enter the total pair of numbers:'))
list1 = []
list2 = []
for i in range(0,pair):
number1, number2 = input().split()
list1.append(int(number1))
list2.append(int(number2))
min = []
for i in range(0,pair):
if list1[i] > list2[i]:
min.append(list2[i])
else:
min.appen... |
436c848fe2a78858ee2b6b5528d9bfc1280ad837 | SenthilKumar009/100DaysOfCode-DataScience | /Python/File/file_pass_runtime.py | 263 | 3.640625 | 4 | from sys import argv
script, fileName = argv
txt = open(fileName)
print('The opened file {}', fileName)
print(txt.read())
fileAgain = input('Enter the file name again:')
print('The opened file {}', fileAgain)
txt_again = open(fileAgain)
print(txt_again.read()) |
5e2e9fb18dea2910c67e397f0bcf97046caf2a03 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Strings/string_format.py | 481 | 4.09375 | 4 | myName = 'SKK'
myJob = 'Data Scientist'
print('My name is ', myName)
print('My Name is {}, and Im working as a {}'.format(myName, myJob))
x = 10
y = 20
print('The given value is:%i' % x)
print('The Values are: %i %i' % (x,y))
print('The Values are: %d %d' % (x,y))
for i in range(11):
print('Number:{:.2f}'.format(... |
211009d3cd13c00e93323588d1b77a18bd14593d | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/make_bricks.py | 148 | 3.5625 | 4 | def make_bricks(small, big, goal):
#
return (goal%5)<=small and (goal-(big*5))<=small
print(make_bricks(3,1,8))
print(make_bricks(3, 2, 9)) |
0ec23c68dd87a2a2fab51238a6f26eb1d492fcc8 | SenthilKumar009/100DaysOfCode-DataScience | /Python/OOP/class_cons.py | 384 | 3.71875 | 4 | class ExampleClass:
def __init__(self, val = 1):
self.first = val
def setSecond(self, val):
self.second = val
exampleObject1 = ExampleClass()
exampleObject2 = ExampleClass(2)
exampleObject2.setSecond(3)
exampleObject3 = ExampleClass(4)
exampleObject3.third = 5
print(exampleObject1.__dict_... |
e840b77ca8e9fe15e8d6717d546ef49641db3243 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Concepts/Set/setComp.py | 123 | 3.9375 | 4 | nums = [1,1,1,2,2,2,2,3,3,4,4,4,5,5,5,5]
print(set(nums))
mySet = set()
for num in nums:
mySet.add(num)
print(mySet) |
0a6d7c918c741bf87ede054baa62685b2f9d480c | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/suminLoopPair.py | 315 | 3.8125 | 4 | pair = int(input('Enter the total pair of numbers:'))
list1 = []
list2 = []
for i in range(0,pair):
number1, number2 = input().split()
list1.append(int(number1))
list2.append(int(number2))
sum = []
for i in range(0,pair):
sum.append(list1[i]+list2[i])
for i in sum:
print(i, end=' ')
print() |
351f5b25fda523a7d07897159e7ec4c4642c9d1a | SenthilKumar009/100DaysOfCode-DataScience | /Python/Programs/date_month_year.py | 692 | 3.84375 | 4 | def isYearLeap(year):
if year % 4 == 0 and year % 100 != 0:
return True
elif year%100 == 0 and year%400 == 0:
return True
else:
return False
def daysInMonth(year, month):
if month in (1,3,5,7,8,10,12):
return 31
elif month in (4,6,9,11):
return 30
elif mo... |
2937f1c3d3cd5f3b96981d4658ef6e688966592a | SenthilKumar009/100DaysOfCode-DataScience | /Python/Concepts/generatorExp.py | 133 | 3.578125 | 4 | nums = [1,2,3,4,5,6,7,8,9,10]
def gen_func(nums):
for n in nums:
yield n*n
my_gen = gen_func(nums)
print(list(my_gen)) |
c9432a9c83d802bab1735c10df0cd8ae3899c4f5 | adilkhash/yandex-webinar-decorators | /method_decorators.py | 720 | 3.6875 | 4 |
def method_decorator(name, func):
def wrapper(cls):
def _dec(*args, **kwargs):
instance = cls(*args, **kwargs)
if hasattr(instance, name):
method = getattr(instance, name)
setattr(instance, name, func(method))
return instance
retur... |
cfe68b3f68c5b9b66d4599de2548ac5a8903b08d | enmorse/com.pythoncrashcourse2ndedition.favorite_languages.py | /main.py | 476 | 3.703125 | 4 | favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edwin': ['ruby', 'go'],
'phil': ['python', 'haskel'],
}
for name, languages in favorite_languages.items():
if len(languages) > 1:
print(f"\n{name.title()}'s favorite languages "
f"are: ")
elif len(languages... |
5830c5044839f32b6b548d814d400ed01f537d01 | gabrielmusker/UrGame | /UrGame.py | 1,088 | 3.9375 | 4 |
""" This is a Python script for running the ancient game of Ur. As I write this
on 05/07/2020, before actually coding anything, I hope it's not going to be too
complicated, but then again, you never know...
"""
from numpy.random import binomial
def roll_dice():
""" In Ur, instead of rolling one die (such as a D... |
9f228d157b8e58b9ff30e15d19b08a4256c31e5d | xeki/MITx--Paython-1 | /creditPayment.py | 1,070 | 3.609375 | 4 | def creditPayment(b,ai,mr):
b = b/1.0
annualInterestRate = ai
monthlyPaymentRate = mr
monthlyInterestRate = ai / 12.0
for i in range(12):
minimumMonthlyPayment = monthlyPaymentRate*b
b = b - minimumMonthlyPayment
b = b + b*monthlyInterestRate
print ("Remaining Balance: "+ str(i) + " " + str(round(b,2)))
r... |
05c85616cc19ed986ec786b4ceda06ccbbc14263 | Vlad-Kornev/PythonApplication12 | /Strings.py | 142 | 3.578125 | 4 | str = input()
substr = 'G'
substr1 = 'C'
p = str.upper().count(substr)
p1 = str.upper().count(substr1)
print (((p + p1) / len(str)) * 100)
|
cd9115ae031759129dd043eb92e61de58039d591 | Vlad-Kornev/PythonApplication12 | /Compare numbers 1.py | 438 | 3.984375 | 4 | a = int(input('введите первое число'))
b = int(input('введите второе число'))
c = int(input('введите третье число'))
m = a
if (m < b):
m = b
elif (m < c):
m = c
l = a
if (l > b):
l = b
elif (l > c):
l = c
if (l < a < m) or (l < a <= m):
ml = a
elif (l <= b < m) or (l < b <= m):
ml = b
elif (l... |
d91cf3c448ab2e39430749f822e8a7c81e009648 | Vlad-Kornev/PythonApplication12 | /Cycle for.py | 216 | 3.90625 | 4 | a = int(input('укажите ширину квадрата из звездочек'))
b = int(input('укажите длину квадрата из звездочек'))
for i in range(b + 1):
print ('*' * a)
|
764b1f8af7fee5c6d0d1707ab6462fc1d279be36 | dadheech-vartika/Leetcode-June-challenge | /Solutions/ReverseString.py | 863 | 4.28125 | 4 | # Write a function that reverses a string. The input string is given as an array of characters char[].
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
# You may assume all the characters consist of printable ascii characters.
# Exampl... |
fb89d7c5bf753cd3998c6622ef47610068b14f0e | majkelmichel/rock_paper_scissors | /game.py | 2,476 | 3.953125 | 4 | import random
default_options = ['paper', 'scissors', 'rock', 'paper', 'scissors', 'rock']
def game(points, possible_inputs, lenght = 3):
user_option = ''
while user_option != '!exit':
user_option = input()
computer_option = possible_inputs[random.randint(0, len(possible_inputs)-1)]
#... |
ca042af11712f32c4b089da67c4a9dcfecd6000d | darkblaro/Python-code-samples | /strangeRoot.py | 1,133 | 4.25 | 4 | import math
'''
getRoot gets a number; calculate a square root of the number;
separates 3 digits after
decimal point and converts them to list of numbers
'''
def getRoot(nb):
lsr=[]
nb=math.floor(((math.sqrt(nb))%1)*1000) #To get 3 digits after decimal point
ar=str(nb)
for i in ar:
ls... |
a49eb3130dd7c87fda205c47b9f37efae061bdd3 | darkblaro/Python-code-samples | /scientificNotation.py | 578 | 3.8125 | 4 | '''
Created on Oct 12, 2018
Scientific Notation
input: 9000
output: 9*10^3
@author: Roman Blagovestny
'''
def scinotdown(n):
cz=0
n=float(n)
if n<1 and n>-1:
while n<1 and n>-1:
cz+=1
n*=10
return str(n)+"*10^-"+str(cz)
if n>1 or n<-1:
whil... |
3952065cb4a9111433a2cf9752df296c7b8d1483 | Momo916/PythonFirst | /input&output.py | 381 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
print('hello world!')
print('Count', 'of 100 + 200 is:', 100 + 200)
print('Hi, %s! You have %d emails!' % ('Momo', 8))
print('please type your name:')
name = raw_input()
print('hello,', name)
abc = raw_input('hey, please type something')
print('[format] your type is: {0}... |
4af0217c44bbc9c8d997b772b2c3b4da410f31a7 | Momo916/PythonFirst | /ifelse.py | 346 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
age = 10
if age > 18:
print('your age is', age)
elif age > 10 and age <= 18:
print('teenager')
else:
print('child')
l = []
if l:
print(True)
else:
print(False)
str = input('please input a integer:')
birth = int(str)
if birth > 2000:
print('00后')
e... |
4e94792683d6e758ede916d8fce49f9e75c8f6a1 | LuisC137/Python | /02_AI/01_Explore_Exploit_Dilema/comparing_epsilons.py | 1,677 | 3.6875 | 4 | """
Author: Luis_C-137
First example to compare epsilon greedy
"""
import numpy as np
import matplotlib.pyplot as plt
class Bandit:
def __init__(self,m):
self.m = m
self.mean = 0
self.N = 0
def pull(self):
return np.random.rand() + self.m
def update(self, x):
self.N += 1
self.mean = (1 -1.0/self.N)... |
dab8cc7bf07b1298e550097e94f6c9b9b31457be | ImmanuelXIV/med_cnn | /train_cnn.py | 6,288 | 3.5 | 4 | # Main draft to run the CNN on the medical data set
from sklearn.cross_validation import KFold
import utils
import tensorflow as tf
import random
import pickle
# ToDo:
# implement more text pre-processing (see utils.py -> check which words are not recognized by word2vec model)
# experiment with network architecture (e... |
2733446c456f17e625f3bbe5ceab76b39697bf46 | namancg/LineComparisonPython | /LineComparison.py | 608 | 3.921875 | 4 | import math
import random
import cmp
def getLength(x1, x2, y1, y2):
val = ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))
result = math.sqrt(val)
return result
x1 = random.random() * 100
x2 = random.random() * 100
y1 = random.random() * 100
y2 = random.random() * 100
x11 = random.random() * 100
x12 =... |
0659a2fc05253f54b53a201848fc055ff2388c5d | jezhang2014/2code | /leetcode/LongestCommonPrefix/solution.py | 571 | 3.5 | 4 | # -*- coding:utf-8 -*-
class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if not strs:
return ''
prefix = []
first = strs[0]
if not first:
return ''
strs = strs[1:]
for i, c in enumerate(first):
for s in str... |
4b09c65f9d5c4ccf5e3b80a277e88e263c85ed99 | jezhang2014/2code | /leetcode/LengthofLastWord/solution.py | 241 | 3.515625 | 4 | # -*- coding:utf-8 -*-
class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
w_list = filter(None, s.split())
if not w_list:
return 0
return len(w_list[-1])
|
b9340da85f495cf9813c4b6d49f76629236aa83d | chskof/HelloWorld | /chenhs/module/demo3_fromImport.py | 1,125 | 3.515625 | 4 | """
Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中:
from modname import name1[, name2[, ... nameN]]
"""
from myModule import myPrint, myPrint2
myPrint("abc")
myPrint2("def")
"""
把一个模块的所有内容全都导入到当前的命名空间也是可行的,只需使用如下声明:
from modname import *
一个模块只会被导入一次,不管你执行了多少次import。这样可以防止导入模块被一遍又一遍地执行
"""
"""
__name__属性:
一个模块被另一个程序第一次引... |
4b98478ef980e2ca1c207d4e1814e2d3f92071a0 | chskof/HelloWorld | /chenhs/variable_test.py | 3,045 | 4.1875 | 4 | """
变量就像一个小容器,变量保存的数据可以发生多次改变,只要程序对变量重新赋值即可
Python是弱类型语言,弱类型语言有两个典型特征:
1、变量无须声明即可直接赋值:对一个不存在的变量赋值就相当于定义了一个新变量
2、变量的数据可以动态改变:同一个变量可以一会儿被赋值为整数值,一会儿可以赋值为字符串
"""
a = 5
b = "hello"
a = "mike"
c = 100
# 数字的类型是int 字符串的类型是str
# 如果想查看变量的类型,可以使用python内置函数type()
type(c)
type(b)
print("c的类型:", type(c))
print("b的类型... |
c0c9303b5127be01a420a033e2d0b6dcbc9e1f2d | chskof/HelloWorld | /chenhs/object/demo7_Override.py | 470 | 4.21875 | 4 | """
方法重写(覆盖):
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法
"""
# 定义父类
class Parent:
def myMethod(self):
print('调用父类方法')
class Child(Parent):
def myMethod(self):
print('调用子类方法')
c = Child() # 创建子类对象
c.myMethod() # 调用子类重写的方法
super(Child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
|
c0ae62b93519caa0ba33234b88721dd5800301e0 | GSvensk/OpenKattis | /MediumDifficulty/Union-find/__init__.py | 1,433 | 3.84375 | 4 |
class Node:
def __init__(self, nummer):
self.nummer = int(nummer)
self.friends = set()
def merge(self, b):
#self.friends = self.friends.union(b.get_friends())
self.friends = self.friends|b.friends
b.friends = self.friends
self.friends.add(b)
b.friends.a... |
845388d14e5b586b358933391fdc9db6e3431363 | GSvensk/OpenKattis | /LowDifficulty/cups.py | 400 | 3.515625 | 4 |
class Cup:
def __init__(self, color, size):
self.color = color
self.size = size
cases = int(input())
cups = []
for i in range(cases):
tmp = input().split()
if tmp[0].isnumeric():
cups.append(Cup(tmp[1], float(tmp[0])/2))
else:
cups.append(Cup(tmp[0], float(tmp[1])))... |
1a467f18bb89c8d1228d6aa2462ba8df7df87bef | pnll/Natural-Language-Processing-with-Python-Cookbook | /Chapter02/recipe2.py | 486 | 3.875 | 4 | str = 'NLTK Dolly Python'
print('다음의 인덱스에서 끝나는 부분 문자열:',str[:4])
print('다음의 인덱스에서 시작하는 부분 문자열:',str[11:] )
print('부분 문자열:',str[5:10])
print('복잡한 방식의 부분 문자열:', str[-12:-7])
if 'NLTK' in str:
print('NLTK를 찾았습니다.')
replaced = str.replace('Dolly', 'Dorothy')
print('대체된 문자열:', replaced)
print('각 문자(character) 액세스:')... |
1b63ffbac749549831c596f5c0864124e7546407 | pnll/Natural-Language-Processing-with-Python-Cookbook | /Chapter04/recipe3.py | 635 | 3.703125 | 4 | import re
#search for literal strings in sentence
patterns = [ 'Tuffy', 'Pie', 'Loki' ]
text = 'Tuffy eats pie, Loki eats peas!'
for pattern in patterns:
print('"%s"에서 "%s" 검색 중 ->' % (text, pattern),)
if re.search(pattern, text):
print('찾았습니다!')
else:
print('찾을 수 없습니다!')
#search a substr... |
078f5695b9b0db0027ae3ce9cdd059d0c2e93e78 | knowledgeftw/twitter_cli | /oauth_helpers.py | 2,583 | 3.78125 | 4 | #!/usr/bin/python
#
# Contains code taken from the python-oauth2 README.md here:
#
#
import urlparse
import oauth2
import os
class OauthToken(object):
"""
This is a simple class which we can pickle and restore.
"""
def __init__(self, key, secret):
self.key = key
self.secret = secret
class OauthUrls(obje... |
46b20781f3cf77eb9716479f61c3b2b4034ee96f | CodingPanda93/Full_Portfolio | /PythonStack/Fundamentals/stars.py | 191 | 3.640625 | 4 | x = [4, 6, 1, 3, 5, 7, 25]
char = ''
i = 0
def draw_stars(num_list):
for num in num_list:
char = ''
for i in range(num):
char += '*'
print char
y = draw_stars(x)
print y
|
cba7bb8aacc820c0fd03675aefc9e2bcfd411a1e | jtagoeASC/Allstar-Code | /list.py | 364 | 3.546875 | 4 | myList=[10,11,12,13,14,15,16,17,18,19,20]
myOtherList=[0,0,0,0,0]
myEmptyList=[]
myOtherList=[]
i=0
while i<5:
myOtherList
print(myOtherList)
i=i+1
theFifthList=["a",5,"doodle",3,10]
print(len(theFifthList))
theFifthList.append(90)
print(theFifthList)
theFifthList[0]=8.4
print(theFifthList)
th... |
37bcf019ef4658abd5629a3d9cf8ad22cd70cf39 | ioef/PyLinuxTools | /wc.py | 632 | 3.921875 | 4 | #!/usr/bin/env python
'''
Creation of the word count Linux utility in python
'''
import sys
def printStats(filename):
#data = sys.stdin.read()
with open(filename,'r') as data:
data = data.read()
chars = len(data)
words = len(data.split())
lines = len(data.split('\n'))
prin... |
11169db02f6dd002ea98668b9c15bfcc44686693 | DiegoTc/ProyectoCompiladoresI | /MiniPython/Ejemplos/sample2.py | 111 | 3.671875 | 4 | class ciclos:
def main:
for x in 1 ... 10+a:
if (x + 2):
y = y + x
print y
else:
print x
|
535e5ec1eb19d397ebad276759074ae847627f7a | nikky1731/spell-corrector | /spellcorrector.py | 2,341 | 3.96875 | 4 | #A simple spelling corrector python program using tkinter module
from tkinter import *
from textblob import TextBlob
from tkinter.messagebox import *
def select(event):
inputword.get()
def clearall():
inputword.delete(0,END)
correctedword.delete(0,END)
def correction():
input_word = inputword.get()
... |
af3c29d2b624127b718f1be930ceb82566b898fc | arfu2016/nlp | /nlp_models/algorithm/longestPalinDromicSubstring/LongestPalindromicSubstring.py | 2,146 | 3.734375 | 4 | """
@Project : text-classification-cnn-rnn
@Module : LongestPalindromicSubstring.py
@Author : Deco [deco@cubee.com]
@Created : 5/31/18 1:16 PM
@Desc :
5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Exa... |
19cce1157ae01ec838eeb6f290081681339c6f7e | eminetuba/7.hafta-odevler | /1. soru.py | 3,026 | 3.96875 | 4 | # telefon rehberi uygulamasi
# Bu odevde bir telefon rehberi simulasyonu yapmanizi istiyoruz.
# Program acildiginda kullaniciya, rehbere kisi ekleme, kisi silme, kisi isim ya da tel bilgisi guncelleme,
# rehberi listeleme seceneklerini sunun. Kullanicinin secimine gore gerekli inputlarla programinizi sekillendirin.
# O... |
a0c30fce1801dfc18ce77ce4cce562962dcd6cfa | ayoolaao/school-projects-2017 | /AyoolaAbimbola_HW6.py | 3,407 | 3.703125 | 4 | # Ayoola Abimbola
'''
List of functions:
index(fname, letter) - accepts filename and letter as args
rollDice() and crap()
STUDENT()
'''
### Problem 1
from string import punctuation
def index(fname, letter):
totalLines = len(open(fname, 'r').readlines()) - 1
infile = open(fname, 'r')
wordC... |
5141b2f70ee8ff1528ea633940007712c4d64b71 | Ortovoxx/NCC2019 | /Functions/Function - Key mapping.py | 1,021 | 3.828125 | 4 | def substitionKeyCipher(userCipherText,userKey): #maps a ciphertext to plaintext according to the key given to it
cipherText = convertToASCII(list(userCipherText)) #Converting cipher to numbers
key = convertToASCII(list(userKey)) #Converting key to numbers
def switchChar(cipherChar): #Switches a single char... |
1c4439c0dd9e504071d15a7ea8154b0f31e8bb59 | jarthurj/Python | /bankaccount.py | 778 | 3.8125 | 4 | class BankAccount:
def __init__(self, int_rate=.01, balance=0):
self.balance = balance
self.int_rate = int_rate
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print("Balance:",self.balance,"In... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.