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 |
|---|---|---|---|---|---|---|
42761c5565047d57a00f6f83a052e94447014545 | paul-manjarres/coding-exercises | /python/com/jpmanjarres/hackerrank/algorithms/strings/CamelCase.py | 101 | 3.6875 | 4 | s = input().strip()
words = 1
for c in s:
if c.isupper():
words = words+1
print(words) |
9b58cea25b4a2205867469eaf1ef957a16729092 | pierrevermeulen/data-challenges-v2 | /03-Maths/02-Statistics-Probabilities/02-Toss-a-Coin/simulate_reality.py | 372 | 3.5625 | 4 | # pylint: disable=missing-docstring
import random
def play_one_game(n_toss):
'''TO DO: return the number of heads'''
pass
def play_n_game(n_games, n_toss):
'''TO DO: return a dictionary.
The keys will be the possible head counts of each game
The values will correspond to the probability of a game... |
0ccaf43f403809e53256470ff62abdb922394b1b | skyg4mb/researchPython | /copies.py | 100 | 3.6875 | 4 | import copy
x = [1, [2]]
y = copy.copy(x)
z = copy.deepcopy(x)
print(y is z)
#pruebas una vez mas |
41aaa190c5dad3fbf8e1f267ca1d060397e87f02 | PrincetonUniversity/intro_debugging | /02_python/python_debug/src/MyShapes.py | 2,131 | 3.515625 | 4 | """Find bugs is the functions."""
import math
class RightTriangle(object):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.base * self.height
class Trapezoid(object):
def __init__(self, par_side_1, par_side_2, height):
self.par_side_1 = par_sid... |
f0acdbf05c2fa9c52cbd2719d56d3496d88d5b77 | r00t4ccess/MITx_6.00_intro_to_computer_science_and_programming_using_python | /pset5/genPrimes.py | 251 | 3.578125 | 4 | def genPrimes():
primes = []
iterator = 1
while True:
iterator += 1
for i in primes:
if iterator % i == 0:
break
else:
primes.append(iterator)
yield iterator |
16e0a88ac89443aee4be439abfa5050381626fa4 | Stupidism/algorithm | /utils/AvlTree.py | 3,891 | 3.625 | 4 | class TreeNode(object):
def __init__(self, val, parent):
self.val = val
self.parent = parent
self.left = None
self.right = None
self.height = 1
def __str__(self):
res = [['--' for t in range((2 ** self.height) - 1)] for i in range(self.height)]
self.fillStringArray(res, 0, self.height)
... |
b12faa2bd47b5e678e475da7685f7b459e7aa923 | Stupidism/algorithm | /leetcode/399.evaluate-division.py | 1,763 | 3.5625 | 4 | from typing import List
class Solution:
def __init__(self):
self.graph = {}
def addLine(self, start, end, value):
if (self.graph.get(start, None) is None):
self.graph[start] = {}
self.graph[start][end] = value
def constructGraph(self, equations, values):
size = len(equations)
for i i... |
83308b9dc2ac327a93ac410f34b9a7a2a22ace80 | maheshkorlam/descriptor-tools | /src/descriptor_tools/unboundattr.py | 5,401 | 3.578125 | 4 | # coding=utf-8
from descriptor_tools import name_of
from warnings import warn
__author__ = 'Jake'
__all__ = ['UnboundAttribute']
DEFAULT = object()
class UnboundAttribute:
"""
-----------------
Warning: :UnboundAttribute is a subpar method for implementing unbound
attributes. It's not what the us... |
1922590e27d513d5bcbcf3ec65c2dadccc8aa334 | maheshkorlam/descriptor-tools | /src/descriptor_tools/storage.py | 5,563 | 3.890625 | 4 | from abc import ABC, abstractmethod
from . import name_of, DescDict, id_name_of
__author__ = 'Jake'
__all__ = ['DescriptorStorage', 'InstanceStorage', 'DictStorage', 'identity',
'protected', 'hex_desc_id']
# TODO: document
class DescriptorStorage(ABC):
"""
:DescriptorStorage is an abstract base ... |
0dd341429a103dac0de82320e305b64fffdf582d | leohowell/leetcode-python | /round-01-2017/2.Add_Two_Numbers.py | 1,019 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def add(self, node, value):
node.val = node.val + value
if node.val > 9:
node.val = node.val - 10
... |
84efc4214f7cdaaf5e819970dac104c3a30476ed | leohowell/leetcode-python | /round-01-2017/155.Min_Stack.py | 1,464 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.values... |
49083dbddd26400d1812798ab6e8921f5e85bf37 | leohowell/leetcode-python | /round-01-2017/268.Missing_Number.py | 278 | 3.515625 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (len(nums) + 1) * len(nums) / 2 - sum(nums)
s = Solution()
print s.missingNumber([0, 1, 2,3,4,6,7,8,9]) |
9f9d2b97bdf36dd4976181d3020ba20ed0fdee3a | leohowell/leetcode-python | /catalog-two-pointers/876.py | 432 | 3.71875 | 4 | # 876. 链表的中间结点
# https://leetcode-cn.com/problems/middle-of-the-linked-list/
# 我的解法 (同官方解法,快慢指针法)
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
left, right = head, head
flag = True
while right is not None:
right = right.next
flag = not flag
... |
9afb76aceb3070f4329918536dbef51d234f91ba | leohowell/leetcode-python | /catalog-two-pointers/287.py | 531 | 3.578125 | 4 | # 287. 寻找重复数
# https://leetcode.cn/problems/find-the-duplicate-number/
from typing import List
# 参考题解
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# 快慢指针
fast, slow, start = 0, 0, 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
... |
708bbe5d0cc4f9404e061a952cd197f9d2fbe8b9 | leohowell/leetcode-python | /catalog-stack/143.py | 871 | 3.65625 | 4 | # 143. 重排链表
# https://leetcode.cn/problems/reorder-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# 我的解答
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return an... |
5ef205513c133d71e3f9c6b528e7dadf0f987bf9 | Chris4496/code | /Script/rangeTestingScript.py | 1,704 | 3.90625 | 4 | maxOhm = int(input("Max ohm (darkest):"))
minOhm = int(input("Min ohm (lightest):"))
fixedOhm = int(input("Fixed ohm:"))
maxVoltageDrop = maxOhm / (fixedOhm + maxOhm)
minVoltageDrop = minOhm / (fixedOhm + minOhm)
maxVout = 5 * (1 - minVoltageDrop)
minVout = 5 * (1 - maxVoltageDrop)
# ====================... |
70e759634d967837b0faed377ced9807c4a604f8 | xct/aoc2019 | /day1.py | 920 | 4.125 | 4 | #!/usr/bin/env python3
'''
https://adventofcode.com/2019/day/1
Fuel required to launch a given module is based on its mass.
Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
'''
data = []
with open('data/day1.txt','r') as f:
data = f.readlines()
#... |
5ccfcf98a3a4b58c8321491c18c9b373bdc24605 | elijabesu/playground | /Python/learning/calendar.py | 843 | 3.859375 | 4 | import calendar
# Plain text calendar
c = calendar.TextCalendar(calendar.MONDAY)
st = c.formatmonth(2020, 9, 0, 0)
print(st)
# HTML calendar
#hc = calendar.HTMLCalendar(calendar.MONDAY)
#hst = hc.formatmonth(2020, 9)
#print(hst)
# loop over the days of a month
#for i in c.itermonthdays(2020, 9):
# print(i)
# extr... |
135f5b617489a082ab5eca36d30228859f38f20e | LittleTB/checkio | /O'Reilly/Median.py | 334 | 3.828125 | 4 | def median(data: list) -> [int, float]:
data = sorted(data)
x = len(data)
if x % 2 == 0:
result = (data[int(x/2)] + data[int(x/2-1)]) * 0.5 # Python3中:/ 得到浮点数,// 得到的是整数(地板除)
else:
result = data[int((x-1)/2)]
return result
print(median([3, 6, 20, 99, 10, 15])) |
970fdbc9e40930e3d8f8b6c4918e9bfbd1eaf4b7 | LittleTB/checkio | /Mine/Time Converter(24h to 12h).py | 377 | 3.78125 | 4 | def time_converter(time):
if int(time[:2]) < 12:
if int(time[:2]) == 0:
return '12' + time[2:5] +' a.m.'
else:
return str(int(time[:2])) + time[2:5] +' a.m.'
elif int(time[:2]) == 12:
return time + ' p.m.'
else:
return str(int(time[:2]) - 12) + time[2:5] +' p.m.'
print(time_converter('12:30') == '12... |
0bf130f7522f0e7f2cb088fd1c663ee09cf17391 | LittleTB/checkio | /Elementary/correct_sentence.py | 243 | 3.71875 | 4 | def correct_sentence(text: str) -> str:
lst = list(text)
if not lst[0].isupper():
lst[0] = lst[0].upper()
if lst[-1] != '.':
lst.append('.')
return ''.join(lst)
print(correct_sentence("greetings, friends")) |
84029f2f12db9e35ec634b58bdef61f5b2ce2887 | LittleTB/checkio | /Incinerator/Binary Count.py | 414 | 3.671875 | 4 | def checkio(num:int):
count = 0
for i in range(32):
if num > 2 ** i and num < 2 ** (i + 1):
count = 1
dif = num - 2 ** i
while dif > 0:
for j in range(i):
if dif >= 2 ** j and dif < 2 ** (j + 1):
count += 1
dif -= 2 ** j
break
elif num == 2 ** i or num == 2 ** (i+1):
count =... |
677c229c224be7079df9f68151e69e70a3d66ce0 | awx1/stat410-final | /preprocess.py | 5,047 | 3.5625 | 4 | import csv
def subName(name, listNames):
return [n for n in listNames if n in name] + [n for n in listNames if name in n]
def sal_stat_per_year(year, links):
with open('/Users/alexanderxiong/Documents/STAT 410/stat410-final/Salary/format/salaries-' + year + '.csv', encoding = "latin-1") as sal:
sal_tot = csv.read... |
3f26a0de9a124b493c1dc5734a2f9e9d30ef6114 | vaishalibhayani/Python_example | /Python_Datatypes/sequence_types/dictionary/dictionary1.py | 516 | 4.28125 | 4 | emp={
'course_name':'python',
'course_duration':'3 Months',
'course_sir':'brijesh'
}
print(emp)
print(type(emp))
emp1={1:"vaishali",2:"dhaval",3:"sunil"}
print(emp1)
print(type(emp1))
#access value using key
print("first name inside of the dictionary:" +emp1[2])
#access value using ... |
931254c4d04db39a2814822ce5fa17d11277b9b8 | vaishalibhayani/Python_example | /Python_Datatypes/sequence_types/string/str.py | 192 | 4.0625 | 4 | str="hello"
print("str")
print(type(str))
str1="""hello world"""
print(str1,type(str1))
str3="""
hello
my name is vaishali
"""
print(str3,type(str3))
|
a7a47ea2f5c2d5806957828e3c7015797c0f3fd9 | vaishalibhayani/Python_example | /Output_method/addsion2.py | 114 | 3.96875 | 4 | a=float(input("Enter a the number="))
b=float(input("enter a the number="))
c=a+b
print("Addtion of number=",c) |
a3a776dcd52307b82d9d8609ba7912b15e937952 | luispaiva40200280/ALG.E.Dados | /ficha1 AED resuloção/ex2.py | 163 | 4 | 4 | #converter celcios em fahrenheit
celcios=int(input("escreve uma temperatura em celcios:",))
fh=1.8*celcios+32
print("temperatura em fh",fh)
input()
|
1b3949bc02c0dcf8871e67540213ce078f089420 | luispaiva40200280/ALG.E.Dados | /ficha n04 AED/ex08.py | 344 | 3.71875 | 4 | #gerador de passwords
import random
username = input("nome:")
password = ""
for i in range(len(username)):
if i % 2 != 0:
password+= username[i]
password+= str(random.randint(1,9))
password+= str(len(username))
print("password é:" , password)
input()
#correto, precissa de se re... |
dca71f704fc2d2a6be18b1531671f78d7eb9de6b | luispaiva40200280/ALG.E.Dados | /ficha 2 AED/ex3.py | 288 | 3.625 | 4 | #peso ideal
genero=input("genero M/F:")
h=int(input("escrevea altura em cm:"))
pesoideal= (h-100) - (h-150) / k
if genero == "F":
k==2
print("o peso ideal é {0} kg" .format(pesoideal))
else:
k==4
print("o peso ideal é {0} kg" .format(pesoideal))
input() |
63653c8dd0893b2e367636fc1b0bdfda4761113c | luispaiva40200280/ALG.E.Dados | /ex03.py | 1,541 | 4.03125 | 4 | #matrix com menu: (valor max); (list trans)
import os
import random
#1
def criar_lista():
lista = []
dimen = int(input("dimenção da matriz: "))
for i in range(dimen):
lista.append([])
for j in range(dimen):
numero = random.randint(10,100)
lista[i].append(... |
74c0ebcd4aad633c1a1a31a83f8939e62f4d0cf1 | luispaiva40200280/ALG.E.Dados | /ficha09.aed/ficheiro03.py | 1,262 | 3.90625 | 4 | #Crie uma aplicação que permita gerir um ficheiro de países
import os
def inserir():
os.system("cls")
file = open( "paises.txt" , "r+")
pais = int(input(""))
if pais == True:
print("pais já existe no ficheiro")
else :
file.append(pais)
def consulta():
file = open... |
526fde39a2bb2eb86272595da29355d27aebd398 | luispaiva40200280/ALG.E.Dados | /ficha n04 AED/ex01.py | 172 | 3.9375 | 4 | #ler caracteres ao contrario
frase=input("escreve uma frase:")
comp=len(frase)
for i in range(comp-1,-1,-1):
print(frase[i], end="")
input()
#esta correto
|
ab925ef40fcebe3fca6adc8b0fe156118b8eb38d | luispaiva40200280/ALG.E.Dados | /ficha03 AED/ex3.py | 225 | 4.03125 | 4 | # calcular o fatorial de um numero
numero=int(input("escreve um numero:"))
faturial=1
for i in range (numero ,1 , -1):
faturial*=i
print("o fatorial de {0} é {1}" .format(numero,faturial))
input()
|
5102c8ee5a424f59c4afd1cf5cc1deb8725ea7d8 | luispaiva40200280/ALG.E.Dados | /ficha 2 AED/ex2.py | 356 | 4.03125 | 4 | #cassificar triangulos
lado1=int(input("valor de 1 lado:"))
lado2=int(input("valor do 2 lado:"))
lado3=int(input("valor do 3 lado:"))
if lado1 == lado2 == lado3:
print("o triangulo é equilatro")
elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3:
print("o triangulo é isósceles")
else:
pri... |
38a32b76978275ca1d750f82caa9ef575e3f039d | luispaiva40200280/ALG.E.Dados | /ficha1 AED resuloção/Ex03.py | 240 | 3.78125 | 4 | # Calcula o peso ideal, de forma simplificada
# Peso Ideal = (altura - 100) * 0.9 (homem) (ou 0.85 no caso de mulher)
altura = int(input("Altura em cm: "))
pesoIdeal = (altura -100) * 0.9
print("Peso Ideal: ", pesoIdeal)
input()
|
cf0eb1c7849ded84619cb6c13adcf65604fee0d3 | joaompinto/sassh | /sassh/string.py | 233 | 3.515625 | 4 | # -*- coding: utf-8 -*-
DIGITS = '0123456789'
LOWERCASE = ''.join([chr(n) for n in range(ord('a'), ord('z')+1)])
UPPERCASE = ''.join([chr(n) for n in range(ord('A'), ord('Z')+1)])
LETTERS = "{0:s}{1:s}".format(LOWERCASE, UPPERCASE)
|
a1bd5bf37a2a52ead039de098b4f041586d7d63c | pbauer99/basic | /ex5.py | 1,110 | 3.921875 | 4 | #my_name = 'Patrick J. Bauer'
#my_age = 18
#my_height = 72 #inches
#my_weight = 130 #lbs
#my_eyes = 'Hazel'
#my_teeth = 'White'
#my_hair = 'Brown'
#print "Let's talk about %s" % my_name
#print "He's %d inches tall." % my_height
#print "He's %d pounds heavy." % my_weight
#print "That's pretty light."
#print "He's got ... |
78408afd4ccc3e0b00cbd68efa9687e985f60518 | fustfust/- | /2주차_2nd_1.py | 248 | 3.71875 | 4 | fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']
count = 0
def count(fruit_name):
count = 0
for(fruit in fruits):
if fruit == fruit_name:
count +=1
return count
count("사과")
|
2f6c6ce5733652e4db3edc0f29483a7d4577d371 | ultraman-agul/python_demos | /实验报告/流程控制03/p4.py | 468 | 3.75 | 4 | # -*- coding: utf-8 -*-
# @Author : agul
# @Date : 2020/11/18 9:13
# Software : PyCharm
# version: Python 3.7
# @File : p4.py
# description :
n = int(input())
if n % 2 != 0:
str = "*"
print(str.center(n, ' '))
for i in range(1, int(n/2)+1):
str = str + "**"
print(str.cent... |
609a98799e0edd3ecc9f55c049bcac31815f1b6c | ultraman-agul/python_demos | /实验报告/模块应用05/guess.py | 1,162 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# @Author : agul
# @Date : 2020/12/2 11:13
# Software : PyCharm
# version: Python 3.7
# @File : guess.py
# description :猜数字游戏。在程序中预设一个 0-9 之间的整数,让用户通过键盘输入
# 所猜的数,如果大于预设的数,显示“你猜的数字大于正确答案”;小于预设的
# 数,显示“你猜的数字小于正确答案”,如此循环,直至猜中该数,显示“你猜
# 了 N 次,猜对了,真厉害”,其中 N 是用户输入数字的次数。
guess = 0
tim... |
e8beb5510ba0f0b01efa2f9cce9da55fe39e3e99 | ultraman-agul/python_demos | /字典集合/test.py | 656 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Author : agul
# @Date : 2020/10/30 14:34
# Software : PyCharm
# version: Python 3.7
# @File : test.py
# description :
x = [1, 2, 3]
y = x[:]
print(y) #[1, 2, 3]
print(y is x) #False
# x = [1, 2, 3, 4, 5]
# del x[:3]
# print(x)
# print(list(str([1, 2, 3])) == [1, 2, ... |
38e3235da3ade9764823588b76461c90598e3631 | ultraman-agul/python_demos | /实验报告/数据类型02/p2_2.py | 510 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Author : agul
# @Date : 2020/11/4 11:11
# Software : PyCharm
# version: Python 3.7
# @File : p2_2.py
# description : 、根据输入字符串 s,输出一个宽度为 15 字符,字符串 s 居中显示,以 “=”填充的格式。如果输入字符串超过 15 个字符,则输出字符串前 15 个字符,最终输出其全小写形式
str = input()
if len(str) > 15:
str1 = str[: 15]
print(str1... |
cc7601b9b60b4a5e0db543111f2b1ee791daeec0 | ultraman-agul/python_demos | /实验报告/数据类型02/p2_8.py | 871 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Author : agul
# @Date : 2020/11/5 15:25
# Software : PyCharm
# version: Python 3.7
# @File : p2_8.py
# description :(1) 输出表 2.2 和表 2.3 均包含的商品信息
# (2) 输出属于表 2.2,但不属于表 2.3 的商品信息
# (3) 输出属于表 2.2 但不属于表 2.3,或者属于表 2.3 但不属于表 2.2 的商
# 品信息
# (4) 输入商品名称,查询其价格。
dict1 = {
'苹果': 5... |
c6e7f278efa5bb39925d1242ad53b31ce90b1295 | smd29/HackerRank_ProblemSolving | /Sorting/Quicksort 1 - Partition | 679 | 4.03125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the quickSort function below.
def quickSort(arr):
pivot = arr[0]
left_list = []
right_list = []
for i in arr:
if(pivot>i):
left_list.append(i)
elif(pivot<i):
right_list.append(i)
... |
65b1c865fd98c9e00f50a52ae2cbbd0757dfea61 | smd29/HackerRank_ProblemSolving | /Implementation/Minimum Distances | 661 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumDistances function below.
def minimumDistances(a):
res = sys.maxsize
dic = {}
for i in range(0,len(a)):
if(a[i] not in dic):
dic[a[i]] = i
else:
res = min(res, i - dic[a[i]... |
c65bb2e9d21b6012be00178a7899199335d70049 | salmaekaaa/DataSains | /rekursif.py | 258 | 3.875 | 4 | def faktorial(n):
if n==1 or n==0:
return 1
else:
return(n* faktorial(n-1))
#fungsi rekursif telah selesai sampai disini
#berikutnya adalah memanggil fungsi
x=int(input("berapa faktorial?"))
print(x, "!= ", faktorial(x))
|
ce691486272c3e815985bd862f373b05c63459b2 | kikiwongweb/kikiwongweb.github.io | /Python/task76.py | 138 | 4.03125 | 4 | a = 35
b = 33
if b > a:
print("b is bigger than a")
elif a == b :
print("a is equal to b")
else:
print("a is bigger than b")
|
0d392a51311a1da24c84669dc57a50610bccb111 | Daroso-96/estudiando-python | /index.py | 1,168 | 4.1875 | 4 | if 5 > 3:
print('5 es mayor que 3')
x = 5
y = 'Sashita feliz'
#print(x,y)
email = 'sashita@feliz.com'
#print(email)
inicio = 'Hola'
final = 'mundo'
#print(inicio + final)
palabra = 'Hola mundo'
oracion = "Hola mundo con comillas dobles"
lista = [1,2,3]
lista2 = lista.copy()
lista.append('Sashita feliz jugan... |
4a0bff665817428f30af3dadb78c9b97ce02df4e | jcuaran7/Videogames | /Python/scripts_python/function.py | 103 | 3.5 | 4 | def sumar(x = 0, y = 0):
sum = x+y
return sum
a = 12
b = 8
print ("la suma es ",sumar(a,b))
|
a743fb6363c7534da4c28e196d666cad8fcb6abd | 3n20w7f03/Proyecto-10 | /Proyecto_10.py | 27,048 | 4 | 4 | print ("1 = mostrar regiones")
print ("2 = mostrar comparación entre la primera y segunda dosis de una región")
print ("3 = mostrar las 5 regiones mas vacunadas con la primera dosis")
print ("4 = mostrar las 5 regiones mas vacunadas con la segunda dosis")
print ("5 = mostrar cantidad de personas que se va... |
653292c6a4b191a69dd436f68776fd2c3f1aa365 | samuelbelo/exercicios-tp3-python | /ex2.py | 270 | 3.796875 | 4 | """Escreva um programa em Python que leia um vetor de 5 números inteiros e mostre-os. """
vetor_de_5_numeros_inteiros = [10, 20, 30, 40, 50]
def mostraNumInteiro():
print("o vetor de 5 numeros contém ", vetor_de_5_numeros_inteiros)
mostraNumInteiro() |
c168517f9cc667fceaf388e01c7edc867044d0c1 | NaveenSingh4u/python-learning | /basic/python-oops/employee-class.py | 968 | 4.0625 | 4 | class Employee:
# use can write doc string by using '''
'''class for handling employee data'''
# self is a reference variable which always refer to current object.
# For defining constructor method name should always __init(self)
# while creating the object this method will be automatically called.... |
52c255ca2ffcc9b42da2427997bcfa6b539127d2 | NaveenSingh4u/python-learning | /basic/python-oops/python-other-concept/generator-ex4.py | 1,121 | 4.21875 | 4 | # Generators are useful in
# 1. To implement countdown
# 2. To generate first n number
# 3. To generate fibonacci series
import random
import time
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
for n in fib():
if n > 1000:
break
print(n)
names = ['sunny', 'bunny'... |
bbb15cfc351270d4c09f884ac0e9debb4804aae5 | NaveenSingh4u/python-learning | /basic/python-oops/book.py | 920 | 4.125 | 4 | class Book:
def __init__(self, pages):
self.pages = pages
def __str__(self):
return 'The number of pages: ' + str(self.pages)
def __add__(self, other):
total = self.pages + other.pages
b = Book(total)
return b
def __sub__(self, other):
total = self.page... |
062f3ee72daa4387656af289b2ee3bef90e70a1f | NaveenSingh4u/python-learning | /basic/python-oops/outer.py | 494 | 4.21875 | 4 | class Outer:
def __init__(self):
print('Outer class object creation')
def m2(self):
print('Outer class method')
class Inner:
def __init__(self):
print('Inner class object creation')
def m1(self):
print('Inner class method')
# 1st way
o = Outer()
... |
6437394d02f33af201cf24cbff36ed76e86effb1 | C-SON-TC1028-001-2113/parcial-practico-2-BryantOchoa | /assignments/17NCuadradoMayor/src/exercise.py | 214 | 3.984375 | 4 |
def main():
#escribe tu código abajo de esta línea
numero = int(input("Escribe un numero : "))
res = 1
while res**2<=numero:
res += 1
print(res)
if __name__=='__main__':
main()
|
35d02329429a7cfa5c5c193ba8af873fec81f83c | YuchenZhangU/Algs | /records/14_Longest_Common_Prefix.py | 692 | 3.75 | 4 | def getCommonPrefix(str1, str2):
l1 = len(str1)
l2 = len(str2)
for i in range(min(l1,l2)):
if str1[i]!=str2[i]:
return str1[:i]
return str1 if l1<l2 else str2
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
... |
9e360e29c76d7c74b92d2618a3ec35354844f09d | wesmayne/Word-Jumble | /wordjumblev1.1.py | 1,561 | 3.90625 | 4 | #wordjumblev1.1 - Player has to guess a random word from dictionary, if player fails they can 'cheat' and get the word
import urllib.request
import random
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = respon... |
6e1c92ebea9f4b666d4381e71132ee02d48e485f | SHalawi-Dev/Data-Structures-And-Algorithms | /Algorithmic Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.py | 917 | 3.6875 | 4 | # Uses python3
from time import perf_counter
# Here are three implementations of fib algorithm
def fib_iter(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def fib_memo(n, computed={0: 0, 1: 1}):
if n not in computed:
computed[n] = fib_memo(n-1, computed) + fib_memo(n-2,... |
7fc438eac5b3c689f7e568dee1c07f08663119ba | RihanZer0/Titanic | /titanic/Pclass.py | 903 | 3.53125 | 4 | """
Какие доли составляли пассажиры первого, второго, третьего класса?
"""
import pandas as pd
def percentage(perc, whole):
return (perc * 100) / whole
def get_nubmer_of_pclass(pclass, data=None):
pclassratio = data.value_counts()
if pclass == 1:
return pclassratio[1]
elif pclass == 2:... |
c1a3ee82f1c10cc499283df4e4e95f00df71dc1b | Dhanshree-Sonar/Interview-Practice | /Guessing_game.py | 808 | 4.3125 | 4 | ##Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number,
##then tell them whether they guessed too low, too high, or exactly right.
# Used random module to generate random number
import random
def guessing_game():
while True:
num = 0
while num not in range... |
1dd51685c6f369a3afeb5bfe98ee712339893104 | Bsmurfy/MolecularEvolution | /HuntingtonsEvolution.py | 6,223 | 3.71875 | 4 | '''
Brendan Murphy
A program to simulate the molecular evolution of the huntingtin protein, with
the ultimate goal of determining how long it would take for half of a population
to display Huntington's disease.
'''
import csv
import random
from datetime import datetime
# define dictionaries for transitio... |
b2adba82db478ca2444b9bef7d5d15f179296974 | full-time-april-irvine/intsructor_wes | /python_oop/SList.py | 893 | 3.734375 | 4 | class Node:
def __init__(self, value):
self.val = value
self.next = None
class SList:
def __init__(self):
self.head = None
def add_front(self, val):
new_node = Node(val)
new_node.next = self.head
self.head = new_node
return self
def display(self... |
cd7387affb328e482934cc3118bfa90a25ccbbb2 | full-time-april-irvine/intsructor_wes | /python_oop/users_bank_accounts/bank_account.py | 781 | 3.703125 | 4 | class BankAccount:
def __init__(self, int_rate, balance=0):
self.balance = balance
self.int_rate = int_rate
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
... |
7620d57967c33c8086a20ca09e7e4188dec39df7 | chocoluffy/leetcode-cpp | /Company/Airbnb/OA/q1.py | 2,276 | 3.5 | 4 | from collections import defaultdict
def evaluateActions(actions):
loc_map = defaultdict(list)
support_map = defaultdict(lambda: [[], None, 0]) # [supported, location, if attacked]
for line in actions:
data = line.strip().split(" ")
if len(data) > 3:
name, location, action, action... |
f2531217f02da868da5ba2af163de2aadd0e2398 | chocoluffy/leetcode-cpp | /Leetcode/5-Longest-Palindromic-Substring/solution.py | 2,259 | 3.765625 | 4 | import pprint
"""
Typical question convert:
- finding longest common suffix in all prefix pairs of two string.
=> "all prefix pairs" equals to a dp table, where dp[i][j] represent the prefix pair of s1[:i+1] and s2[:j+1]
=> given such dp table, to find the longest common suffix:
constantly aligning with last element... |
8639d846082a47f8ecd1ecf3d9c5bda21c4599f1 | chocoluffy/leetcode-cpp | /Leetcode/130-Surrounded-Region/solution.py | 1,413 | 3.59375 | 4 | class Solution(object):
# DFS version.
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) > 0 and len(board[0]) > 0:
N = len(board)
M = len(board[0])
... |
703daddb62bfa6c0a2b214e84cca3343418c09fa | chocoluffy/leetcode-cpp | /EPI/notes/【python】OJ-tricks/solution.py | 448 | 3.578125 | 4 | """
When I want to loop over lines from stdin, I generally use sys.stdin instead. In that case you could ignore the count.
For a test case like the following, giving N integers and sum them up, then divide by K.
1 #test cases
3 2 #N #K
4 5 7 #N integers
"""
raw_input() # ignore the size
for line in sys.stdin:
n... |
31caaa9fb14160193c0fe3baf1856d2dae0f5e56 | chocoluffy/leetcode-cpp | /Others/Maximum-Lowest-Height-Matrix-Path.py | 976 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Amazon OA2:
2. 给一个二维矩阵,表示某点的高度,人从左上角出发, 只能向下或向右走,最终到达右下角。
求所有可能的路径中每个路径最低点的最大值。
典型DP, 类似LC174
"""
import pprint
class Solution():
def max_min_height(self, matrix):
n = len(matrix)
m = len(matrix[0])
dp = [[0] * m for _ in range(n)]
for j in range(m):
... |
a1a3b03a817ee36fe7414dcbbc7da82ecdc810fa | chocoluffy/leetcode-cpp | /Leetcode/722-Remove-Comments/solution.py | 2,291 | 3.625 | 4 | """
Input: ["a/*comment", "line", "more_comment*/b"] Output: ["a","b"] Expected:
["ab"]
A good edge case: meaning that we only create new empty new_s [], when it's in
search mode. since after removing several lines, for the next line, if we have
some char remained, we need to append it to the previous string output ... |
226843bbc68bab71fbe2cfb3416925baa898a273 | simplex06/clarusway-aws-devops | /ozkan-aws-devops/python/coding-challenges/cc-003-find-the-largest-number/largest_number.py | 270 | 4.25 | 4 | # The largest Number of a list with 5 elements.
lst = list()
for i in range(5):
lst.append(int(input("Enter a number: ")))
largest_number = lst[0]
for j in lst:
if j > largest_number:
largest_number = j
print("The largest number: ", largest_number)
|
5305f309bd9d88092faedd1309413ee0a655e934 | simplex06/clarusway-aws-devops | /ozkan-aws-devops/python/coding-challenges/cc-006-generate-password/password_v2.py | 221 | 3.671875 | 4 | name = input("Please enter your full name: ").lower().replace(" ", "")
import random
n = str(random.randint(1000, 10000))
random_letter = random.sample(name, 3)
password = ''.join(random_letter) + n
print(password)
|
9ca861896547f7e54704f1c59d108c91aa195ca8 | Voltty/Python | /note2.py | 102 | 4.03125 | 4 | c = 1
d = int(input('escolha um numero: '))
s = d + 1
while c < s:
print(c)
c = c + 1
|
5497e72bea26aaad2d50fcd837135ed7ce4725db | joaovicentefs/cursopymundo2 | /aulas/aula13d.py | 242 | 3.921875 | 4 | #Usando estrutura de for a nosso favor com múltiplas variáveis:
i = int(input('Início: '))
f = int(input('Fim: '))
p = int(input('Passo: '))# Passo é a mesma coisa que ritmo ou cadência
for c in range(i, f+1, p):
print(c)
print('FIM!')
|
b6baf7354123f5584dde6cb4b45b2647c5ef49f8 | joaovicentefs/cursopymundo2 | /exercicios/ex0037.py | 805 | 4.34375 | 4 | num = int(input('Digite um número interiro: '))
#Colocando três aspas simples no print é possível fazer múltiplas linhas
print('''Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL''')
options = int(input('Sua opção: '))
'''Utilizado o conhecim... |
df058957390d98f8d2f5621d2a5bd80afeeb218b | joaovicentefs/cursopymundo2 | /exercicios/ex0036.py | 540 | 3.734375 | 4 | vCasa = float(input('Valor da Casa: R$ '))
salario = float(input('Salário do comprador: R$ '))
tempo = int(input('Quantos anos de financiamento? '))
prestacao = vCasa / (tempo * 12)
# Quebrei o print em dois apenas para mostrar o uso do Recurso end= que deixa dois prints em uma linha só
print('Para pagar uma casa de R$... |
4dd941cc5f0834047b63e12f438cf3aec9d85ecb | joaovicentefs/cursopymundo2 | /aulas/aula21a.py | 366 | 3.90625 | 4 | # Exemplo de Return:
def fatorial(num=1):
f = 1
for c in range(num, 0, -1):
f *= c
return f #Os returns podem ser valores
# n = int(input('Digite o valor que você gostaria de calcular o fatorial: '))
# print(f'O Fatorial de {n} é {fatorial(n)}')
f1 = fatorial(5)
f2 = fatorial(4)
f3 = fatorial()
pr... |
fbfb0d29fdba07a8083493af527a596f52236a1f | joaovicentefs/cursopymundo2 | /aulas/aula16c.py | 256 | 4 | 4 | numeros = (1, 92, 34, 54, 23, 4, 9)
num_sorted = sorted(numeros)
print(num_sorted) # A função Sorted apresenta a tupla ordenada na forma de lista
num_sorted = tuple(num_sorted)
print(num_sorted)
#Tuplas são imutáveeis
'''del(numeros)
print(numeros)'''
|
54312a473f411843b3987f9fc1f7fef7d584eabc | joaovicentefs/cursopymundo2 | /exercicios/ex0050.py | 232 | 3.78125 | 4 | soma = 0
cont = 0
for c in range(1,7):
n = int(input('Digite o {}° número inteiro: '.format(c)))
if n % 2 == 0:
soma += n
cont += 1
print('Somando apenas os {} números pares digitados o resultado é {}'.format(cont, soma))
|
105927ce2d00b0cc59f6900d20286abd523ffd1b | joaovicentefs/cursopymundo2 | /exercicios/ex0057.py | 227 | 3.890625 | 4 | sex = str(input('Informe seu sexo: [M/F] ')).strip().upper()[0]
while sex not in 'MmFf':
print('Dados inválidos.', end=' ')
sex = str(input('Por favor inform seu sexo: '))
print('Sexo {} registrado com sucesso'.format(sex))
|
64edeb78c92d0204524c5522dc5d7a036590b48d | kieron560/Daily-Interview-Pro | /Validate Balanced Parathesis.py | 1,346 | 4.09375 | 4 | # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
# An input string is valid if:
# - Open brackets are closed by the same type of brackets.
# - Open brackets are closed in the correct order.
# - Note that an empty string is also considered valid.
#... |
f256b9d97d08e0eac2a603fbe62973903c292c3e | N-eeraj/perfect_plan_b | /search.py | 185 | 3.765625 | 4 | import read
string = read.Read(str, 'String')
key = read.Read(str, 'Substring')
if read.inList(key, string):
print(key, 'found in', string)
else:
print(key, 'not found in', string)
|
b86d5d0f2b570cfad3678ce341c44af297399e32 | N-eeraj/perfect_plan_b | /armstrong.py | 343 | 4.15625 | 4 | import read
num = str(read.Read(int, 'a number'))
sum = 0 #variable to add sum of numbers
for digit in num:
sum += int(digit) ** len(num) #calculating sum of number raised to length of number
if sum == int(num):
print(num, 'is an amstrong number') #printing true case
else :
print(num, 'is not an amstrong number'... |
28139eefa5ca456be8a2f4c0bc6454509e53ffa0 | N-eeraj/perfect_plan_b | /in_list_for.py | 175 | 3.9375 | 4 | import read
lst = read.ReadList()
key = read.Read(str, 'Key to Search')
for i in lst:
if i == key:
print(key, 'is in the list')
exit()
print(key, 'is not in the list')
|
cfd96e0c8e5db2534009c572ab3f5c618c0129a9 | elsenorbw/advent-of-code-2019 | /day6/day6_part2.py | 8,282 | 4.25 | 4 | # --- Day 6: Universal Orbit Map ---
# You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often involves transferring between orbits, the orbit maps here are useful for finding efficient routes between, for example, you and Santa. You download a map of the local orbits (your puz... |
1e8c1b6877a26925000355706cd7b2c5f864461c | elsenorbw/advent-of-code-2019 | /day2/day2_part1.py | 9,191 | 3.671875 | 4 | # --- Day 2: 1202 Program Alarm ---
# On the way to your gravity assist around the Moon, your ship computer beeps angrily about
# a "1202 program alarm". On the radio, an Elf is already explaining how to handle the situation:
# "Don't worry, that's perfectly norma--" The ship computer bursts into flames.
#
# ... |
b35a34a9193e50472258d680c4769251a6d20b52 | Index197511/AtCoder_with_Python | /math1.py | 491 | 3.6875 | 4 | import numpy as np
from matplotlib import pyplot as plt
def f(x):
"""最小値を求めたい関数"""
return x ** 2
def df(x):
"""最小値を求めたい関数の一階導関数"""
return 2 * x
def main():
x = np.arange(-2, 2, 0.1)
y = f(x)
plt.plot(x, y, label='f(x)')
y_dash = df(x)
# 一階導関数の符号を反転させる
plt.plot(x, -y_dash,... |
6a6066c6ba91db50858c41c929b54cfdfd1a7f38 | Index197511/AtCoder_with_Python | /ABC7_B.py | 124 | 3.96875 | 4 | A=input()
length=len(A)
if length>1:
print('a')
elif length==1 and A!='a':
print('a')
else:
print('-1')
|
ce67e655c03979bc7091437879933ecd3cae720b | Index197511/AtCoder_with_Python | /ARC29_C.py | 2,286 | 3.5625 | 4 | from operator import itemgetter
import sys
input = sys.stdin.readline
class UnionFind():
# 作りたい要素数nで初期化
# 使用するインスタンス変数の初期化
def __init__(self, n):
self.n = n
# root[x]<0ならそのノードが根かつその値が木の要素数
# rootノードでその木の要素数を記録する
self.root = [-1]*(n+1)
# 木をくっつける時にアンバランスにならない... |
79a2104bd95f494f794c229fb5c0c953bd59ea19 | Index197511/AtCoder_with_Python | /ABC18_A.py | 528 | 3.71875 | 4 | a=int(input())
b=int(input())
c=int(input())
first=max(a,b,c)
last=min(a,b,c)
if first==a:
print('1')
if b>c:
print('2')
print('3')
else:
print('3')
print('2')
elif first==b:
if a>c:
print('2')
print('1')
print('3')
else:
... |
d43239f51414010682f6b2f5ffb3fe46be98a890 | atg-abhishek/adventofcode2017 | /Solutions/day3.py | 2,578 | 3.6875 | 4 | from pprint import pprint
from collections import defaultdict
target_number = 347991
def part1():
i = 3
square_thickness = 1
while i*i <= target_number:
i += 2
square_thickness += 1
diff = target_number - (i-2)*(i-2) #tells how far away is the number in this spiral
# pprint(diff)
... |
5d98bed0b69f809374548e933b44c7cacd44e1a4 | HylianPablo/TallerPythonFeriaIngenio2020 | /printWithWhile.py | 157 | 3.828125 | 4 | a=input("Identificación por favor: \n")
while (a != "Pepe"):
a=input("Usuario no reconocido. Identificación por favor: \n")
print("¡Bienvenido Pepe!") |
21d3af7697e513231e96c3f527829754fd7a651f | Deepanshu0799/Python_Assignments | /Py_2.py | 455 | 3.78125 | 4 | import random
maxTicketsAvailable=int(input("Enter the total number of person:"))
m=[]
for i in range(maxTicketsAvailable):
m.append(input("Enter one name:"))
n=random.randint(0,maxTicketsAvailable-1)
print("The winner of the lottery is:",m[n])
#OUTPUT
#Enter the total number of person:5
#Enter one name:... |
24c07b9bead0c1ddcd5f06cea34df078246df317 | jinzengnju/Pyproject | /PythonMultiline/Start_and_Run.py | 742 | 3.578125 | 4 | import threading
class myThread(threading.Thread):
def __init__(self,threadID,name,counter):
threading.Thread.__init__(self);
self.threadID=threadID
self.name=name
self.counter=counter
def run(self):
currentThreadname=threading.current_thread()
print("running in",... |
282889e7d63f3269707c26002fb60f0681ae71f3 | JASchu314/Coding-Dojo | /group.py | 1,456 | 3.671875 | 4 | #1
greeting = "hello"
name = "dojo"
print name , greeting
#2
list = ['wish' , 'mop' , 'bleet' , 'march' , 'jerk']
for i in range(0 , len(list)):
print list[i]
#3
def nf(num):
list = []
for i in range(0,25):
num *= 2
list.append(num)
print list
nf(3)
#4
def funstrin... |
4b20faae3875ba3a2164f691a4a32e61ca944a27 | harishassan85/python-assignment- | /assignment3/question2.py | 226 | 4.21875 | 4 | # Write a program to check if there is any numeric value in list using for loop
mylist = ['1', 'Sheraz', '2', 'Arain', '3', '4']
for item in mylist:
mynewlist = [s for s in mylist if s.isdigit()]
print(mynewlist)
|
64932f647d0d8e17e9938e17f5ccf9014f89bdd1 | Skoppek/Fractals-Turtle | /FractalPlant.py | 1,135 | 3.578125 | 4 | import turtle
str = 'X'
queue = []
def evolve(str):
new_str = ''
for ch in str:
if(ch == 'X'):
new_str += 'F+[[X]-X]-F[-FX]+X'
elif(ch == 'F'):
new_str += 'FF'
elif(ch == '['):
new_str += '['
elif(ch == ']'):
new_str += ']'
... |
2e68132943be61755d639d792ed2b01c9599f69a | ctam91/crypto | /helpers.py | 913 | 3.859375 | 4 | import string
def alphabet_position(letter):
alphabet = string.ascii_lowercase
letter = letter.lower()
position = 0
for character in range(len(alphabet)):
if alphabet[character] == letter:
position = character
return position
def rotate_character(char,rot):
... |
3e18d05ad63fb51ae895b54069f6ae581064e2a4 | akshayjagtap/workspace | /Notes/topics/OOP/oop_python.py | 8,746 | 4.78125 | 5 | """
Python OOP
"""
'''
CLASSES:
Whenever we have a use case where we have a number of data points and each data point will
have certain attributes and certain actions that it can preform, then instead of defining
them for each of the data point, we create a class defining those attributes & actions once
and then maki... |
fa261cdf75ffb7e8a586acc884edfc63db14a6a2 | hiratekatayama/math_puzzle | /leet/Binary_tree_zigzag.py | 1,044 | 3.8125 | 4 | from collections import deque
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 zigzagLevelOrder(self, root):
if not root:
return []
queue = deque([root])
result, direction = [], 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.