blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
81f9ffb5e49a38b96fb96ba1229d9fb634e08f85 | ghimireu57/AssignmentCA2020 | /Task 2/Q.6.py | 365 | 4.25 | 4 | # 6 What is the output of the following code examples?
x=123
for i in x:
print(i)
#int obj is not iterable(error)
i = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print('error')
#output: 0,1,2
count = 0
while True:
print(count)
count += 1
if cou... |
f8053aa22c586606ffe61d586a3c2b6f97e78ae7 | amakumi/Binus_TA_Session_Semester_1 | /CLASS - EXERCISE/CLASS.py | 1,008 | 4.15625 | 4 |
class Students: #naming convention, class title capitalised
def __init__(self): #call the constructor by def and initializing
self.name = name
self.gpa = gpa
self.gender = gender
self.age = age
def view(self): #creates the interface!
print("Name: ",self.name)
... |
3c94fb6849373d4fac490066611ee3402884bbf3 | jschnab/leetcode | /binary_trees/get_next.py | 1,853 | 4.25 | 4 | # given a binary search tree node, get the value of the next node
class TreeNode:
def __init__(self, val=None, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
# the function get_next() is better than this one
def get_ne... |
d10371e25ced48fdb2661a47fd2519e8c642593e | thales-mro/python-cookbook | /1-data-structures/named_tuple.py | 337 | 3.859375 | 4 | from collections import namedtuple
def main():
Subscriber = namedtuple('Subscriber', ['addr', 'joined'])
sub = Subscriber('thales@itaporanga.com', '2012-10-19')
print(sub)
print(sub.addr, sub.joined)
# still works as a tuple
print(len(sub))
addr, joined = sub
print(addr, joined)
if __n... |
88049ac909b0adf193fafebf59db868bf8cd758b | jiroyamada/Essence-of-ML | /ch4/plot1.py | 162 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0,1,2,3])
y = np.array([3,4,7,8])
plt.plot(x,y,color="r")
plt.show() |
a66f1c8e93f5b714cc0c8c700bcba541793aa283 | naveen519/data_science | /Algorithms/chatbot/Chatbot AP/save_and_restore.py | 2,808 | 3.734375 | 4 | # Saving the variables
'''
Lets see how to save the parameters into the disk and restore the saved parameters from the disk.
The savable/restorable paramters of the network are Variables (i.e. weights and biases)
'''
# Example 1 - Save variables
'''
We will start with saving and restoring two variables in TensorFlow. ... |
9a0757bf14abd099b4f3ffb0d9072bdc52fd49a0 | nicollebanos/Programacion | /Clases2/clasesyobjetos/talleres/tarea1.py | 2,078 | 3.703125 | 4 |
class Perro ():
'''Es un mamífero domestico carnívoro de la familia de
los cánidos. Lo caracterizan varios atributos que los diferencian
entre ellos:
nombreEntrada: Hace referencia al nombre del perro
generoEntrada: Hace referencia a si es macho o hembra
habitadEntrada: Hace referencia si es... |
c11cc39028ca9cbd1a9e9fca15734fd18b61b9b4 | Diqosh/PP2 | /TSIS1/additionalTasksInformatics/DataType/105.py | 250 | 3.875 | 4 | class Toupper:
def __init__(self, a, b):
self.a = a
self.b = b
def print(self):
print("yes") if self.a == self.b else print("no")
if __name__ == '__main__':
myclass = Toupper(input(), input())
myclass.print() |
f8574f5cb208c77d0df5c3371459bb653b3b3006 | Hani1-2/All-codes | /Untitled Folder/stackwithlist.py | 937 | 3.984375 | 4 | class mystack:
def __init__(self):
self.elements = list()
def isEmpty(self):
return len(self.elements) == 0
def pop(self):
assert not self.isEmpty(),"Empty stack!"
x = self.elements.pop()
#self.top -= 1
return x
def push(self,value):
#self.top +... |
a37e361b4554039b4f39848ef2e8bf4c528a1512 | sgorbaty/lexisort | /lexisort.py | 1,182 | 3.640625 | 4 |
# O ( n*m (log n) )
# m is length of string element
def lexicographicsort(args):
listToSort, lexP = args
global lexParam, cache
cache = dict()
lexParam = buildMap(lexP)
return _mergesort(listToSort)
def _mergesort(listToSort):
aSize = len(listToSort)
if aSize == 1:
return listToSort
elif aSize > 1:
mid... |
e3115059a052e910490f1209ecb64cccd84ab94f | heykarnold2010/blackjack_demo | /main.py | 5,568 | 3.671875 | 4 | import random
from IPython.display import clear_output
class Deck():
def __init__(self):
self.deck = []
def make_deck(self):
ranks = (['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'])
for rank in range(len(ranks)):
temp = (ranks[rank])
self.de... |
70083657af587a9bdba9984b3803391e0b485d58 | guomxin/cvnd-facial-keypoints | /models.py | 8,287 | 3.65625 | 4 | ## TODO: define the convolutional neural network architecture
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
'''
def __in... |
203eb0a1f804345019a1292ba49b7cff8e2660c7 | EatTheGiant/PSA | /cvic 2.py | 3,270 | 3.953125 | 4 | #! /usr/bin/env python
APP_VERSION = "1.0"
class Movie:
def __init__(self, paTitle, paYear, paGenre, paEarnings, paRating, paDuration):
self.aTitle = paTitle
self.aYear = paYear
self.aGenre = paGenre
self.aEarnings = paEarnings
self.aRating = paRating
self.aDuration... |
f6402fa4f65ce8159945eaaca505e8d024e2185b | ohadlights/tensorflow-without-a-phd | /tensorflow-rl-hanabi/entities/color.py | 356 | 3.671875 | 4 | class Color:
def __init__(self, color_id: int, name: str):
self.color_id = color_id
self.name = name
def __str__(self):
return self.name
def __eq__(self, other):
return self.color_id == other.color_id
def __hash__(self):
return hash(repr(self))
BLUE = Color(0... |
d2e33377beb764670f14c3ab7b83c69a11adf690 | Th3Lourde/l33tcode | /problemSets/top75/191.py | 249 | 3.515625 | 4 | class Solution:
def hammingWeight(self, n):
ones = 0
while n:
if n % 2 == 1:
ones += 1
n = n // 10
return ones
print(Solution().hammingWeight(11111111111111111111111111111101))
|
4d39a7e890f466f1ab18ba8fa0f57d6adb14ac98 | Parva1610/Multi-Programs | /Cryptography Codes/OTP.py | 795 | 3.703125 | 4 | import random
charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
def encrypt(plaintext):
otp = "".join(random.sample(charset, len(charset)))
result = ""
for c in plaintext.upper():
if c not in otp:
continue
else:
result += otp[charset.find(c)]
return otp,... |
c437a32b84a7263617641e00f443692385c08115 | Gab-Aguilar/PRELIMINARIES | /ASSIGNMENT/R2.39/agr2.39try.py | 4,256 | 4.15625 | 4 | from abc import ABC, abstractmethod # need these definitions
class Polygon(ABC):
def __init__(self, lengths_of_sides):
self.number_of_sides = len(lengths_of_sides)
self.lengths_of_sides = [0] * self.number_of_sides
self.assign_values_to_sides(lengths_of_sides)
def print_num_sides(se... |
c5ab1d20bf5c74d60dcc044b91eff1b8422f96d6 | Xievv/Portfolio | /schoolWork/DatabaseManagement/informationGenerator/employee/employee_generator.py | 13,455 | 3.5 | 4 | #!/usr/bin/env python
# Script by Shawn Giroux
# Date: February 13 2016
#
# This Python script generates fake information for an Oracle Database.
# The output will be a .sql file.
import os # For finding out directory
import time # Finds our time elapsed
import random # Used to generates phone numbers and se... |
d3822b886c58571088a545c57b0fce52a24c2e05 | sonji16/pythonPractice | /one_bite_prime_number.py | 5,923 | 3.546875 | 4 | # 55 튜플 = 값 변경 불가
# clovers_1 = (1, 2, 3)
# clovers_2 = [1, 2, 3]
# clovers_2[2] = 4
# print (clovers_2[2])
# 56 패킹, 언패킹
# clovers = 1, 2, 3
# print(clovers)
# r, g, b = 240, 248, 255
# print(r, g, b)
# 57 패킹, 언패킹 예제(사탕 바꾸기)
# dodo = '박하맛'
# alice = '딸기맛'
# dodo, alice = alice, dodo
# print('도도새:', d... |
2f02d243dba8f3e1ae3527b19e6e60d89d9833c8 | another-computer/hanabi-py | /Hanabi/Card.py | 1,781 | 3.71875 | 4 | # The deck is a randomized list of cards
# 5 colors
# 1 five, 2 fours/threes/twos, 3 ones per color
# Total 50 cards
# Hands are lists of 5 cards each
# Discard pile is a list of all cards that have been removed from a hand through discard
# Cards have color, number, and clue status for both
colors = {'Unk... |
c90231464e7ca095b795cc804ea919e16ae8865b | al00014/covid19-sir | /covsirphy/analysis/predicter.py | 5,553 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from datetime import datetime, timedelta
import pandas as pd
from covsirphy.analysis.simulation import simulation
from covsirphy.util.plotting import line_plot
class Predicter(object):
"""
Predict the future using models.
"""
def __ini... |
c01c7cbc495513921a21f6df9c674a298e9f0f82 | arossbrian/my_short_scripts | /flip.py | 224 | 3.53125 | 4 | from random import randint
heads = 0
tails = 0
for trial in range(0, 1000):
while randint(0,1) == 0:
tails = tails + 1
heads = heads + 1
print("heads/ tails", heads/tails)
print(heads)
print(tails)
|
1d93915e737224b111597ada58ece5ba299d0c52 | liuyang1/test | /codeforces/problemset/653/653B.py | 777 | 3.796875 | 4 | #! /usr/bin/env python3
def applyRule(rule, s):
a, b = rule[0], rule[1]
if a == s[0]:
return b + s[1:]
return None
def applyRules(rules, ss):
ret = [applyRule(r, s) for r in rules for s in ss]
return [i for i in ret if i is not None]
def search(rules, m):
"""
search from 'a', ext... |
62c9e35cc9d3bb0d2c7e1045f3b114d1001a1817 | heymrtoufiq/uri-online-judge | /problemas/1100/1144.py | 157 | 3.640625 | 4 | for i in range(1, int(input()) + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}')
|
d3ac2a490896b844e9f4f5e2e14ff5ad70c0ac28 | HenriqueLBorges/WI-FI-Fingerprints-with-Machine-Learning | /Raspberry Pi/compassTest.py | 594 | 3.75 | 4 | import json
with open('config.json') as json_data_file:
data = json.load(json_data_file)
#Gets compass bearing
def getCompassBearing():
destination = raw_input('destination = ')
return destination
#Returns the offset in between two cardinal points
def getDifference (cardinal1, cardinal2):
differenc... |
d22921da777f3609dbd6a49a43f32063f9d34deb | cuitianfeng/Python | /python3基础/3.Python修炼第三层/day3_预习/函数的返回值和调用_预习.py | 1,176 | 4.25 | 4 |
#函数的返回值和函数调用的三种形式
# def func():
# print('from func')
# # return 0
#
# res=func()
# print(res)
'''
大前提:return的返回值没有类型限制
1.没有return: 返回None 等同于return None
2.return 一个值:返回该值
3.return val1,val2,val3: 返回:(val1,val2,val3)
返回值
什么时候该有?
调用函数,经过一系列的操作,最后要拿到一个明确的结果,则必须要有返回值
通常有... |
e10b1374cfd759ee56e4b6ad5641d592a4876bdb | kituu02/lab3 | /py/4.c.py | 110 | 3.953125 | 4 | a = input()
b = input()
print("string is present in it") if b in a else print("string is not present in it") |
4906c10b1fbefd139e8dd046b68d4d91916dd8cf | hungry-me/General-programming | /DS/src/Strings/Spacing/PutSpaces.py | 570 | 4.125 | 4 | #You are given an array of characters which is basically a sentence. However there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after following amendments:
#(i) Put a single space between these words.
#(ii) Convert the uppercase letters to low... |
c2b5bf503885f798ecf934fc26de47cce7397de8 | rizkysaputra4/coding-test | /nawadata/Untitled-1.py | 501 | 3.671875 | 4 | def Factor(inputList):
print("Input: ", inputList)
n = 0
result = []
loop = True
t = bool
while (loop == True):
n += 1
for i in range(2, n-1):
mod = n % i
if ((mod == 0)):
t = False
if t :
... |
28e816f83da2323d4b1742f0cb616335c33c71f0 | hissue/Python | /Python_sw_academy/python_beginner/python_02/ex_47.py | 487 | 3.984375 | 4 | '''
반지름 정보를 갖고, 원의 면적을 계산하는 메서드를 갖는 Circle 클래스를 정의하고,
생성한 객체의 원의 면적을 출력하는 프로그램을 작성하십시오.
출력
원의 면적: 12.56
'''
class Circle:
def __init__(self,value):
self.values=value
self.ca=0
def mun_cal(self):
self.ca=pow(self.values,2)*3.14
return self.ca
result=Circle(2)
print('원의 면적: {:0... |
68fc576bfc52bda308a3418e4647a500c0d02cb2 | krohak/Project_Euler | /LeetCode/Hard/First Missing Positive/sol-improve.py | 910 | 3.59375 | 4 | def firstMissingPositive(nums):
size = len(nums)
i = 0
nums.append(-1)
while (i<size):
# if num at correct index, negative or greater then size of array
if nums[i] == i or nums[i] < 0 or nums[i] > size:
i+=1
else:
if nums[nums[i]] == nums[i]: # nums... |
5d88511fde2e0be0d08b7220a1884c8a575d6122 | Dean-Coakley/ProgrammingTraining | /Kattis/40_Easiest_Python/Easiest.py | 215 | 3.625 | 4 | N = 1
while N != 0:
N = int(input())
sum1 = 0
for a in range(1, N):
sum1 += int(a)
print(sum1)
if sum1 > 10 and len(str(sum1)) == len(str(N)):
print(sum1)
N = input()
|
3eb63126dc6614155c1377b457ae4fdc6debb33a | justien/lpthw | /ex31_MakeDec.py | 1,550 | 3.578125 | 4 | # -*- coding: utf8 -*-
# Exercise 32: Making Decisions
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 32: Making Decisions"
print
print
print """
You enter a dark room with two doors. ... |
ad5462f9874146f0b2fd48968baed6e9ea5e3fa7 | geniousisme/CodingInterview | /leetCode/Python/344-reverseString.py | 468 | 3.671875 | 4 | class Solution1(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for i in xrange(len(s) - 1, -1, -1):
res.append(s[i])
return "".join(res)
class Solution(object):
def reverseString(self, s):
"""
:t... |
2bc1d78e21bb52996e7f098601705accb9a9570d | salesvictor/DesignPatterns | /state.py | 1,258 | 3.75 | 4 | from abc import ABC, abstractmethod
class StateMachine:
def __init__(self):
self._state = S1()
def set_state(self, state):
self._state = state
def action(self):
self._state.action(self)
class S1:
class __Singleton:
def action(self, machine):
print('Doing action with state S1')
ma... |
f52874f5628a2672c0585e30d3944fbb09490599 | pscx142857/python | /作业/Python基础第五天/第三题.py | 321 | 3.828125 | 4 | #3.封装函数,实现返回三个数的最小值
def min_3(a,b,c):
"""
返回三个数的最小值
:param a: 第一个数字
:param b: 第二个数字
:param c: 第三个数字
:return: 返回三个中最小的数字
"""
ls = [a,b,c]
mi = min(ls)
return mi
print(min_3(101,2,99)) |
099c36205dad8e4baa6aaceb9c41a2004e74b2e1 | NakonechnyiMykhail/py1902 | /start/10-11/logic.py | 1,316 | 4.3125 | 4 | # логические операции
print('and:')
print(False and False)
print(False and True)
print(True and False)
print(True and True)
print()
print('or:')
print(False or False)
print(False or True)
print(True or False)
print(True or True)
print()
print('not:')
print(not False)
print(not True)
print()
# логические выражения
... |
25ffe5d8c831203a268dbf106b5ee7b096c273df | Geneveroth/Coding_Dojo_Assignments | /Assignments/Python_Stack/Python/OOP/Bank_Account.py | 1,195 | 3.953125 | 4 | import math
class BankAccount:
def __init__(self, name, int_rate, balance=0):
self.name=name
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance+=amount
return self
def withdraw(self, amount):
if self.balance<=0:
... |
617b83d89bcef190f63099ea56c615aec54b9edd | plsmaop/leetcode | /python/easy/007.py | 287 | 3.5 | 4 | class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
ans = 0
if x < 0:
ans = int('-' + str(x)[1::][::-1])
else: ans = int(str(x)[::-1])
return ans if -(1<<31) < ans < (1<<31) - 1 else 0
|
d8900354994b8fb64bc73b692811d1619592d1f5 | hshrimp/letecode_for_me | /letecode/121-240/193-216/204.py | 615 | 3.75 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: wushaohong
@time: 2020/7/16 下午4:30
"""
"""204. 计数质数
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。"""
class Solution:
def countPrimes(self, n: int) -> int:
val = [1] * n
val[0] = val[1] = 0
for i in range(... |
8210b019628d8a1a3e24ac0140ac30fa0f5d908a | KrishnaPramodParupudi/Face_Recognition | /match.py | 914 | 3.78125 | 4 | ''' Finding whether people in two images are the same '''
# import necessary stuff
import face_recognition
# load images first one is used to train and second one to verify the person
image1 = face_recognition.load_image_file('Gal1.jpg')
image2 = face_recognition.load_image_file('Gal2.jpg')
# face_encodings gives a... |
1fb2029cff8cd48713dd51380f0e8d841f612c8d | ICT710-TAIST/Project-Cloud | /reviser.py | 1,992 | 4.03125 | 4 | # Check if the values of the message are in a possible range
def in_range(val, min, max):
if min <= val <= max:
return True
else :
return False
# Check if the values can parse to integer
def is_integer(val):
try:
num = int(val)
except ValueError:
return False
... |
fca1aa40bf1b5c924c83c9d8fedc43d1462470c5 | gdparra/lpthw | /ex38.py | 552 | 3.765625 | 4 | ten_things="Apples Oranges Crows Telephone Lights Sugar"
print "Wait there are not 10 things in the list. Lets fix that"
stuff=ten_things.split(' ')
more_stuff=["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
while len(stuff)!=10:
next_one=more_stuff.pop()
print "Adding: ", next_one
stuff.append(next... |
f6d668b922b4d60dac9fc8df5ce945281cfda699 | kumarhegde76/Scripting-Language | /SL Lab/SL_Lab_Test1/lettersaround.py | 413 | 3.84375 | 4 | def LettersAround(s):
flag=True
equal=0
plus=0
for i in range(0,len(s)):
if(s[i] == '='):
equal+=1
continue
elif(s[i] == '+'):
plus+=1
continue
elif(s[i].isalpha()):
if(s[i-1] == '+' and s[i+1] == '+'):
continue
else:
flag==False
break
if(flag == True and equal>0 and plus > 0):... |
4b822f110750157b455e8dacfb8e82089cc2a1fe | TahsinTariq/Python | /Projects/Class_Work/Intro_to_AI/Adversareal Search/MinMax_DLS.py | 1,527 | 3.53125 | 4 | def MinMax_DLS(node, depth, Is_Max):
if depth == 0:
return EvalFunction[node]
if node in TerminalValue.keys():
return TerminalValue[node]
if Is_Max:
value = -float('inf')
for child in OwO[node]:
print(child)
value = max(value, MinMax_DLS(child, depth-1... |
ecea150d164a9a629c349b67a4757560724e6d9a | jakubfolta/AddDigits | /AddingNumbers.py | 331 | 3.71875 | 4 | def adding(numbers):
return sum(int(dig) for dig in str(numbers))
print(adding(11234))
def add(numbers):
total = 0
for dig in str(numbers):
total += int(dig)
return total
print(add(12765))
def add(numbers):
total = []
for dig in str(numbers):
total.append(int(dig))
return sum(total)
print(a... |
02dc0aa7da6e5c89ecc1d8cdabab39f577226d97 | nishanthgampa/PythonPractice | /Unsorted/whileloop.py | 201 | 3.9375 | 4 | while True:
print("Who are you?")
name = input()
if (name != "Nishanth"):
continue
print("What is the Password?")
password = input()
if password == 'Harshini':
break
print('Access Granted') |
f7045baabd744f4326fa34b3c9e453fcbb970f47 | bssrdf/pyleet | /R/ReplaceElementsinanArray.py | 1,741 | 4.03125 | 4 | '''
-Medium-
*Hash Table*
You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].
It is guaranteed that in the ith operation:
operations[i][0] exists in nums.
opera... |
13df24a077117b855725ee76245db55ee8d30c92 | andrest50/CS362-HW3 | /andres_tobon_hw3.py | 1,086 | 4.3125 | 4 | """
This is an updated version of the file from homework 1, except
there is now some error handling.
To run the script, use the following command:
python3 andres_tobon_hw3.py
"""
def main():
valid = False
""" Continuously receive input until valid input or force quit """
while(valid == False):
... |
5c6e9e5b58366990eabfb05b869bfc1593d83aed | Mbiederman/qbb2017-answers | /day2-afternoon/00-iteration.py | 344 | 4.09375 | 4 | #!/usr/bin/env python
import sys
f = open( sys.argv[1] )
#the most basic way
#while True:
#the_line = f.readline().rstrip("\r\n")
#if not the_line:
#break
#print the_line
#my_iter = iter( f )
#while True:
#the_line = my_iter.next()
#print the_line
for line in f:
print lin... |
86d911e3459cede99bda30b21b5f812ec5042e9a | btonasse/RandomSampler | /random_sampler/logger/__init__.py | 2,012 | 3.5 | 4 | import logging
import types
level_map = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
def add_separator(self: logging.Logger, level: str, message: str = '') -> None:
'''
Create a log record with a given st... |
94701e9e3588c587cdda3cd69c2285dfa368d6a7 | juanfepi27/DatosYAlgoritmos1 | /ordenamiento_202110146010_202110129010_202110015010/11 ordListas.py | 2,719 | 4.03125 | 4 | """
11. (10) se tiene una lista A con 100 elementos A[ a1……a100 ]
B de 60 elementos B[ b1……b60 ]
Se desean resolver las siguientes tareas
a.) Ordenar cada lista aplicando el método Quicksort
b.) Crear una lista C que sea la unión de la lista A y B
c.) Ordenar la li... |
72074eefc15e0ae68c82ff467350589c5a070ae5 | ocornel/Andela | /fizz_buzz.py | 472 | 4.09375 | 4 | def fizz_buzz(number):
if number % (3 * 5) == 0: #Numbers devisible by x and y are divisible by xy
return 'FizzBuzz'
elif number % 3 == 0:
return 'Fizz'
elif number % 5 == 0:
return 'Buzz'
else:
return number
def range_fizz_buzz(limit):
#accepts an ending number then does fizzbu... |
2e9edffab36e3a907ab516f39292092dc082a982 | CodecoolKRK20173/erp-mvc-project-predator | /model/common.py | 1,082 | 3.984375 | 4 | """ Common functions for models
implement commonly used functions here
"""
import random
def generate_random(table):
"""
Generates random and unique string. Used for id/key generation:
- at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letter
- it must be uniqu... |
2d30297726d3ecfc58a8b71b3590f63c673f2701 | samridhrakesh/test | /inheritance.py | 553 | 4.1875 | 4 | class Fish:
def __init__(self, first_name, last_name="Fish", skeleton="bone", eyelids=False):
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def Swim(self):
print("Fish is swiming")
def swim_back(self):
... |
671d69e80ae454b80db2c2a0bf9624196a59efbd | cankutergen/Other | /LowestCommonAncestorBT.py | 1,072 | 3.703125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return N... |
618347e5e223b33c081dd5554cbbf7421eee8ded | miango1904/bucles_python | /ejercicios_profundizacion.py | 14,242 | 3.84375 | 4 | #!/usr/bin/env python
'''
Bucles [Python]
Ejercicios de profundización
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para que practiquen los conocimietos
adquiridos durante la semana
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.... |
320a20094d8085f682590c72584bc750afa12039 | zjz2018/pyproject | /basic-kw/zjz_04_list.py | 3,386 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 专门用于存储 一串 信息
# 列表用 [] 定义,数据 之间使用 , 分隔
# 列表的 索引 从 0 开始
# 列表 通常存储相同类型的数据
# 通过 迭代遍历,在循环体内部,针对列表中的每一项元素,执行相同的操作
# ------------------基本使用-------------------
name_list = ["zhangsan", "lisi", "wangwu"]
# 1. 取值和取索引
# list index out of range - 列表索引超出范围
print(name_list[2])
#... |
9ff663ef879c820d6bcae96adf3cc19cdb689d34 | krzysztof-kozak/practicePythonClass | /main.py | 2,112 | 3.71875 | 4 | from math import ceil
from copy import copy
class Person:
def __init__(self, name, age):
print("Pozdrowienia od konstruktora!")
self.name = name
self.age = age
self.semester = 7
self.address = None
def set_address(self, address: object):
self.address = address
... |
13fbc3ed5e4168fbb59ee015c3b7e6c2fb2455e1 | banjin/everyday | /questions/fab.py | 2,770 | 3.6875 | 4 | #!/usr/bin/env python
# coding:utf-8
"""斐波那契数列
"""
def fabltion(n):
if n < 2:
return 1
return fabltion(n-2) + fabltion(n-1)
def fabltion2(n):
a, b = 0, 1
while n:
yield b
a, b = b, a + b
n -= 1
def fabltion3(n):
"""斐波契纳数列1,2,3,5,8,13,21............根据这样的规律
编... |
07de19fbd68ce2aeba25f41985c08c8bf9df6134 | sosoivy/PythonChallenge | /pythonchallenge 15.py | 294 | 3.515625 | 4 | # -*- coding:utf-8 -*-
import datetime
# 闰年
years = [y for y in range(1006, 1997) if str(y)[-1] == '6' and y % 4 == 0]
# date和weekday对应
year_c = []
for y in years:
d = datetime.date(y, 1, 27)
if d.weekday() == 1:
year_c.append(y)
# second youngest
print year_c[-2] |
6ca00500ac6342c00c9c9f09c5f0b3279432a5dc | sishirsubedi/common_problems | /12_DyanmicProg_IV_LongestCommonSubstring.py | 1,686 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 03 14:50:29 2016
@author: ibm-lenovo
"""
def maxCommonSubstring(str1,str2):
len1 = len(str1)
len2 = len(str2)
common =[]
K = [[0 for x in range(len2+1)] for x in range(len1+1)]
for i in range(len1+1):# 0 to n
for j i... |
f4fc1f9733ae09be4e27a718a19f9707a17c67cf | Mikaelia/hashmap_vending-machine | /interface.py | 2,731 | 3.734375 | 4 | #!/usr/bin/env python3
"""
Interactive console
"""
import sys
import cmd
import shlex
from vending_machine import VendingHash
class VendingCommand(cmd.Cmd):
"""
A console allowing users to interact with vending machine
"""
prompt = ("*Beep* ")
def do_quit(self, args):
"""
Quit comm... |
d20d5154b22450148d92a8cdf7a4000fb516fc8a | dindaya28/School-Work | /Python/CLASS/test.py | 3,382 | 3.578125 | 4 | # Lists
listOfKeywords = []
pacificScore = []
mountainScore = []
centralScore = []
easternScore = []
# Function for calculating happiness score within each tweet
def happinessCalculator():
wordValue = 0
for el in range(5, len(line)): # Need to make this a function to repeat within the other timezones
... |
e83ce1a4ec7e447c5eb2eb6941493837f3ffa8aa | Saalim95/Data-Structure | /Tree Comparison.py | 988 | 3.96875 | 4 | class Node:
def __init__(self, val):
self.right = None
self.left = None
self.data = val
def __str__(self):
return str(self.data)
def add(root, x):
if root==None:
root = Node(x)
return root
if x>root.data:
if root.right==None:
roo... |
c95bf7dd5175de5793f6a22e04edbfd1bfca2299 | bourneagain/pythonBytes | /addSubMulDiv.py | 625 | 3.921875 | 4 | def add(a,b):
return a+b
def mult(a,b):
if a==0 or b==0:
return 0
count=1;
result=0;
while count<=abs(b):
print count
result+=a
count+=1
if(b<0):
return neg(result)
else:
return result
def subt(a,b):
return a+neg(b)
def divide(a,b):
if b==0:
raise Exception("divide by zero")
#a/b=x
#a=bx
c... |
f274dfa6ae29a15699bef58b6adc3e0765a388b2 | Gackle/leetcode_practice | /53.py | 889 | 3.640625 | 4 | # coding: utf-8
""" 53. 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
"""
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
import sys
... |
f9e4a1941cd9ad3e7d224be041ed22b847962fdc | Amit-CBS/Machine-Learning-with-Python | /Day6/age_calc_from_dob_gui.py | 3,023 | 3.671875 | 4 | # age_calc_from_dob_gui.py
# Testing Tkinter features with Python
# calculating age from DOB
from tkinter import *
from tkinter import messagebox as msg
from datetime import datetime, date
class GetAge:
# Constructor
def __init__(self, root1):
self.f = Frame(root1, height=350, width=500)
... |
3b504da6cc8f61ac4265f6dbb6825d1db4ef964e | bbj3/cracking-the-coding-interview | /3 - Stacks/1_ArrayStack.py | 2,257 | 3.625 | 4 | # 3.1
class ThreeStacks:
def __init__(self, cap):
self.capacity = cap
self.lst = [None] * 3 * cap
self.size = [0,0,0]
def push(self, data, stackNum):
if stackNum < 3 and stackNum >= 0:
if self.isFull(stackNum):
print("Full - please pop")
... |
40488a28faa75e34725410d03ccb6ef93e700cd8 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4007/codes/1590_842.py | 240 | 3.5 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
n = input()
soma = sum(int(i) for i in str(n))
print(soma) |
d40d68dbeee03f6d633d8986c4e25b57eefa3946 | coledixon/Tech_Academy_coding_drills_2015 | /Python_drills/training_drill/% inserts.py | 302 | 3.515625 | 4 | my_name = "Cole"
my_age = "27"
my_height = 5
my_height2 = 10
my_weight = 145
my_eye = "hazel"
print("My name is %s." % my_name )
print("I am %s years old." % my_age)
print("I am %sft %sins tall." %(my_height, my_height2))
print("I weigh approx. %slbs." % my_weight)
print("My eyes are %s." % my_eye)
|
ccdf4c7262c5968154d0736510da2bf1205c4a48 | MahmudHossain/Solved-Problems-C-Java-Python- | /Hackerrank_Python/diamond.py | 130 | 3.65625 | 4 | n=int(input())
for i in range(n-1):
print((n-i)*' '+(2*i+1)*'*')
for i in range(n-1,-1,-1):
print((n-i)*' '+(2*i+1)*'*')
|
282f8b4152e5cf57e33509640d8079ca085ade15 | wclau/ENGG4030 | /hw34/mf_corrected.py | 2,434 | 3.84375 | 4 | #!/usr/bin/python
#
# Created by Albert Au Yeung (2010)
# http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python
# An implementation of matrix factorization
#
from __future__ import print_function
try:
import numpy
numpy.random.seed(1)
except:
print("This im... |
8ced80c2fcc35bb0416be0ecfa15099a0f8747f8 | eencdl/leetcode | /python/binaryTreeZigZagLevelOrderTraversal.py | 2,208 | 4.03125 | 4 | __author__ = 'don'
"""
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level o... |
c756ca96d4adf2bcc117cfa834b1e2f08a00f7e0 | gayatri-p/python-stuff | /challenge/problems/infinite_array.py | 704 | 3.953125 | 4 | '''
You are given an array A of size N.
You have also defined an array B as the concatenation of
array A for infinite number of times.
Eg:
A = [1, 3, 5]
B = [1, 3, 5, 1, 3, 5, 3, 5, ...]
given range x to y in B, print sum of that range in B
L = initial value of ranges
R = final value of ranges
'''
def solve (a, r,... |
a93d891f0d3264bdc6cd183af22058c1ccf110ab | vivek1395/python-code | /fibonacci.py | 413 | 4.09375 | 4 | #write a program to print fibonacci series.
n=10
def fibonacci():
a=0
b=1
global n
while (n>0):
sum=a+b
yield a,b,a+b
a=b
b=sum
n=n+1
f=fibonacci()
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print... |
4e233fcda368ed34c74a6503700d31085c720278 | Psingh12354/GeeksPy | /CumulativeSum.py | 238 | 3.53125 | 4 | list1 = [10, 20, 30, 40, 50]
list2 = []
count=0
for i in range(len(list1)):
if i==0:
count=list1[i]
list2.append(count)
if i>0:
count+=list1[i]
list2.append(count)
print(list2)
|
a120eda00f26fa85edb534fccfd59ed32930d663 | BriBean/Variables | /variables_primary.py | 3,565 | 4.46875 | 4 | # author: <Brianna Blue>
# date: <7/2/21>
#
# description: <variables>
# --------------- Section 1 --------------- #
# 1.1 | Variable Creation | Strings
#
# Relevant Documentation
# - https://www.w3schools.com/python/python_variables.asp
# - https://www.w3schools.com/python/python_variables_names.asp
#
# Variable... |
95e324940b556ba041a7cb66318d7fdb7f5e7bd3 | alrod2005/HackerRankChallenges | /triplets.py | 758 | 3.5625 | 4 | #!/bin/python3
import os
import sys
def solve_a(a0, a1, a2, b0, b1, b2):
alice_score = 0
bob_score = 0
if a0 > b0:
alice_score += 1
elif a0 < b0:
bob_score += 1
if a1 > b1:
alice_score += 1
elif a1 < b1:
bob_score += 1
... |
c058414b5483ff4d62777f01574f2909a695e5d2 | capncrockett/Udemy_PY_MC | /7_DictAndSet_Remaster/dict_intro.py | 1,332 | 3.8125 | 4 | vehicles = {'dream': 'Honda 250T',
# 'roadster': 'BMW R1100',
'er5': 'Kawasaki ER5',
'can-am': 'Bombardier Can-Am 250',
'virago': 'Yamaha XV250',
'tenere': 'Yamaha XT650',
'jimny': 'Suzuki Jimny 1.5',
'fiesta': 'Ford Fiesta Ghia ... |
53cf9831c943f0fd8dfcaffb84452b3217b63699 | yalothman97/Python | /loops_task.py | 568 | 3.921875 | 4 | print("\nCASHIER HELPER 9000 🧾")
print("The Coded Electronics Store")
items=[]
while True:
name=input('\nInsert product name (enter "done" when finished): ')
if name=='done':
break
price=float(input("Insert price: "))
quantity=int(input("Insert quantity: "))
items.append({'name':name,'price':price,'quantity':q... |
c17d2dee7f5cffed2c23ef9428f841a3bc4e8357 | ashi-06-jul/Chatbot | /db.py | 1,291 | 3.796875 | 4 |
import sqlite3
class DB:
def __init__(self, dbname="details.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def setup(self):
stmt = "CREATE TABLE IF NOT EXISTS INFO(city text, locality text, pincode integer, req text, standard text, board text, medium text, subject... |
aa4a1b238a58b29dda036325d6a23111fea8b9da | wenxinjie/leetcode | /tree/python/leetcode106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py | 1,112 | 4.09375 | 4 | # Given inorder and postorder traversal of a tree, construct the binary tree.
# Note:
# You may assume that duplicates do not exist in the tree.
# For example, given
# inorder = [9,3,15,20,7]
# postorder = [9,15,7,20,3]
# Return the following binary tree:
# 3
# / \
# 9 20
# / \
# 15 7
# Definit... |
57b0a8be724704ddbab70111d432bcfa44144833 | ronvoluted/kaggle-nba | /src/data/getAbsolute.py | 744 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import logging
import pandas as pd
import joblib
def abs(df, name):
"""Convert the dataframe value to absolute:
***WARNING*** This module converts all negative values to positive values in dataframe.
Parameters
----------
df : dataframe
Features of d... |
a98142829352c73d3c980e314a39d415b92531ac | Hellofafar/Leetcode | /Easy/475.py | 2,294 | 3.90625 | 4 | # ------------------------------
# 475. Heaters
#
# Description:
# Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
# Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all ... |
903dd0e2f64716914fc1eaa860859fe2bd54a790 | yehnan/project_euler_python | /p031.py | 1,152 | 3.546875 | 4 |
# Problem 31: Coin sums
# https://projecteuler.net/problem=31
# dynamic programming
def coin_sum(total, coins):
ways = [1] + ([0] * total)
for coin in coins:
for i in range(coin, total+1):
ways[i] += ways[i - coin]
return ways[total]
# recursion
def coin_sum_r(total, co... |
32e9bbc093b5a2dbca7f850df2559f03dc022d6a | mkai5/McGalaxy | /constellation.py | 1,362 | 3.53125 | 4 | import star
class Constellation:
constellations = ["Big_Dipper","Aquila"]
def __init__(self, stars):
self.stars = stars
self.size = len(stars)
def get_centroid(self):
x=0
y=0
for i in self.stars:
x = x + i.coordinates[0]
y = y + i.coordinat... |
1864ad17fe89a83edf4237f51e81a8e44c23688e | sergio-lira/data_structures_algorithms | /project_3/submission/problem_1.py | 1,801 | 4.4375 | 4 | def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if not is_valid_input(number):
return None
return sqrt_recursive_sol(number/2, number)
def is_valid_in... |
b9963d31b685095c633d3e7be218b2fc70898e69 | candyer/leetcode | /May LeetCoding Challenge/29_canFinish.py | 1,975 | 4.03125 | 4 | # https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/538/week-5-may-29th-may-31st/3344/
# Course Schedule
# There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, ... |
57ea61813e2d3a4070ed6e0d3dbb5d46f0b14f30 | nunberty/au-fall-2014 | /python/hw3/4.py | 2,599 | 3.6875 | 4 | #!/usr/bin/env python3
"Alina Kramar"
import math
class Vector3(object):
dim = 3
def __init__(self, vector):
self.value = [0] * Vector3.dim
for i in range(Vector3.dim):
self.value[i] = vector[i]
class Matrix(object):
dim = 3
def __init__(self, matrix=None):
if no... |
2696ced25664aa0f87ccc89520f60c5101efbbc1 | yKuzmenko740/Geek_Brains_tutorial | /Fifth_lesson/chain_map.py | 979 | 3.875 | 4 | from collections import ChainMap
# цепочка из словарей, позволяет организовать роботу с несколькими словарями
d_1 = {'a': 2, "b": 4, 'c': 6}
d_2 = {'a': 10, "b": 7, 'd': 40}
d_map = ChainMap(d_1, d_2)
print(d_map)
d_2['a'] = 100 # ссылочная структура данных
print(d_map)
print(d_map['a'])
print(d_map['d'])
print("... |
8a578a0f5214a04a01c7992aff167c47d75aa85b | arayariquelmes/curso_python_abierto | /41_ejercicio_28.py | 382 | 3.9375 | 4 | #Realiza una función llamada area_circulo(radio)
#que devuelva el área de un círculo a
#partir de un radio. Calcula el área de un
#círculo de 5 de radio.
#El área de un círculo se obtiene al elevar
#el radio a dos y multiplicando el resultado
#por el número pi
from math import pi
def area_circulo(radio):
return pi... |
97dd00850f95fa542e58cbfa8ba4337e73d14b88 | paulobazooka/intro-python-ifsp | /2018-05-14/jogo-simples.py | 738 | 3.75 | 4 | # Jogo Desenvolvimento na Classe
# Paulo Sérgio do Nascimento 160013-3
from random import randint
# Classe personagem
class Personagem:
pontos = 0
def __init__(self, patas, idade):
self.idade = idade
self.patas = patas
def getIdade(self):
return self.idade
def addPonto(self):
self.pontos = self.pontos... |
98bd014f0d842ff265ba64ddea97f39b65713217 | artcheng/eular | /palindrome.py | 294 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def palindrome(num):
return str(num) == str(num)[::-1]
i=999
while i>900:
j=999
while j>=i:
x=i*j
if palindrome(x):
print x
j=j-1
i=i-1 |
26f9bd1d93ac1d74ff6943961a1592fa45b9f60b | ZackPashkin/3d-game-with-neural-network | /player.py | 1,314 | 3.609375 | 4 | from settings import *
import pygame as pg
import math
class Player:
def __init__(self):
self.x, self.y = PLAYER_POSITION
self.angle = PLAYER_ANGLE
@property
def position(self):
return (self.x, self.y)
def movement(self):
"""
Play... |
7ddd256f5b13343c21c058d9a99f57320b4599e7 | 0x0400/LeetCode | /p169.py | 679 | 3.65625 | 4 | # https://leetcode.com/problems/majority-element/
from collections import Counter
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt = Counter(nums)
return cnt.most_common(1)[0][0]
def majorityElementV2(self, nums: List[int]) -> int:
nums.s... |
20777c27393a0b1099dc887546cd35fdb57ebdf8 | meankiat95/TeamDF | /historyscrap/ExtractBrowserHistory.py | 5,181 | 4.03125 | 4 | import csv
import os
import sqlite3
import sys
def get_username():
"""
Get username of the computers
"""
drives = input("Please input the drive (e.g. C): ")
username = input("Please enter user profile name (case-sensitive & space sensitive): ")
name = drives +":\\" +"Users"+ "\\... |
9c454266e5c3eeb134149cd1247a3b7a0bfcaaa0 | vrtineu/learning-python | /funcoes/ex102.py | 699 | 4.28125 | 4 | # Crie um programa que tenha uma funçao fatorial() que receba dois parametros: o primeiro que indique o numero a calcular e o outro chamado show, que sera um valor logico(opcional) indicando se sera mostrado ou nao na tela o processo de calculo do fatorial.
def fatorial(n, show=False):
"""
-> Calcula o fatori... |
29303abbd54b03233ab8a8a9b46812a29f1059a5 | BabyPringles/10ISTB-work | /Area of the circle.py | 404 | 4.25 | 4 | """
Program to combine the area of a circle.
"""
# import libraries
import math
# define functions
def areaofcircle(r):
area = math.pi * r * r
print("Returning area to main program.")
return(area)
# main program
radius = float(input("What is the radius of the circle in cm?"))
print("Radi... |
2b1459a924238853e7792785b5b58c6f15ec28a1 | mauricioZelaya/QETraining_BDT_python | /WilmaPaca/Practice1/Applying_operators.py | 1,791 | 4.34375 | 4 | # Defining the triangule type
import math
def isosceles(a,b,c):
if a != 0 and b != 0 and c != 0:
if a == b:
text = print("a: %d = b: %d and c: %d is not equal" %(a,b,c))
elif a == c:
text = print("a: %d = c: %d and b: %d is not equal" % (a, c, b))
elif b == c:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.