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 |
|---|---|---|---|---|---|---|
9036deafb3980f8f986cdd902fab447f91c55c32 | danielle8farias-zz/hello-world-python3 | /meus_modulos/numeros.py | 2,770 | 4.28125 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Funções para:
# validar número float;
# validar número inteiro;
# validar o divisor da operação de divisão;
# validar índice de raízes;
# validar números naturai... |
aa7511a1809dca85ec719f4618ad10910e0c651d | danielle8farias-zz/hello-world-python3 | /exercicio_py/ex0010_fatorial/fatorial_test.py | 459 | 3.75 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: função que recebe um número inteiro e retorna o seu fatorial.
########
def fat(n):
fat = 1
if n == 1 or n == 0:
return fat
else:
for i in range(n, 0, -1):
fat *= i
... |
411322bca02b7298f435eb49f576f9d4c5ffc14c | danielle8farias-zz/hello-world-python3 | /meus_modulos/mensagem.py | 3,045 | 4.15625 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Funções para:
# ler e criar um cabeçalho;
# criar um rodapé;
# criar linha;
# ler e validar resposta se deseja continuar
# validar recebimento de uma string form... |
da6fd8966f25f0a99bbd0afc55eed1b261998930 | danielle8farias-zz/hello-world-python3 | /exercicio_py/ex0030_ordena_lista_composta/main_v0.py | 761 | 3.921875 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: ordenação de lista composta usando expressões lambda
########
def lamb_crescente(lista: list) -> list:
#sort() função de ordenação
lista.sort(key=lambda lista: lista[1]) #pegando apenas o item 1 da list... |
8a877ca81e83e3d17c459a72648a7d1486203f7a | danielle8farias-zz/hello-world-python3 | /exercicio_py/ex0000_boas_vindas/main_v5.py | 2,449 | 3.609375 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição:Captura o nome da pessoa e retorna uma mensagem de boas-vindas na tela.
########
#importando módulo criando em outro diretório:
# módulo sys fornece acesso a algumas variáveis usadas ou mantidas pelo interpre... |
063f4a09c22c84ceda6c4afe227b6ba105500465 | danielle8farias-zz/hello-world-python3 | /exercicio_py/ex0001_soma_numeros/main_v2.py | 489 | 3.65625 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Usuário digita dois números inteiros e programa retorna a soma entre eles.
########
#função lambda:
# funciona semelhante a uma função
# lambda recebe_valor(es) : retorno da função
somar = (lambda x, y: x +... |
a111704cbd5bbf5ac5cd9a314fd753634aef4f00 | nyannko/leetcode-python | /alg/house_robber.py | 536 | 3.625 | 4 | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
odd = even = 0
for i in range(len(nums)):
if i & 1 == 0:
print("1", odd, even)
odd = max(odd + nums[i], even)
print("2", ... |
bd697dab9e2a0fa17f5474c48108fde09d2f6149 | nyannko/leetcode-python | /alg/recover_binary_search_tree.py | 906 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.a = None
self.b = None
self.prev = TreeNode(-sys.maxint-1)
def reco... |
01ca1b2e8e00f002cabb2ef4e4a895c511df274d | nyannko/leetcode-python | /alg/dfs.py | 891 | 3.640625 | 4 | class Solution(object):
def dfs(self, graph, start):
visited = []
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.append(vertex)
for neighbor in reversed(graph[vertex]):
stack.appe... |
7bcf56164dfa660e8a582d2ca34cdc046501562a | nyannko/leetcode-python | /alg/interleaving_string.py | 1,186 | 3.625 | 4 | class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
# create a table for dp
row = len(s1) + 1
col = len(s2) + 1
print(row + col, len(s3) + 2)
if row + col !=... |
ccad672561069bfeea8525a1bd425db8625f8469 | nyannko/leetcode-python | /alg/wildcard_matching.py | 1,052 | 3.71875 | 4 | class Solution(object):
def isMatch(self, string, pattern):
"""
:type s: str
:type p: str
:rtype: bool
"""
s, p, match, starIdx = 0, 0, 0, -1
while s < len(string):
# advance both pointers
if p < len(pattern) and (pattern[p] == '?' or p... |
d9f65f45814077b0098f568eef6e96ad4c5551d3 | nyannko/leetcode-python | /alg/averange_of_levels_in_binary_tree.py | 856 | 3.59375 | 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 averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
# bfs
f... |
aa9c4b8d671ec31a12cb545be51e0a227c6c92e8 | nyannko/leetcode-python | /test/test_two_sum.py | 643 | 3.546875 | 4 | import unittest
from alg.two_sum import Solution
class TestTwoSum(unittest.TestCase):
def setUp(self):
self.obj = Solution()
def tearDown(self):
del self.obj
def test_two_sum(self):
nums = [1, 3, 4, 6]
target = 10
self.assertEqual(self.obj.two_sum(nums, target),... |
31dfcf427f787e3515a0463d7bcb65ce26fe0022 | nyannko/leetcode-python | /alg/merge_intervals.py | 1,727 | 3.78125 | 4 | # Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
# Convert to a list
intervals = [[i... |
4de8c10de2f80e090d63c07bdb4164e436e3b2c0 | nyannko/leetcode-python | /alg/word_break.py | 1,781 | 3.515625 | 4 | class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
ok = [True]
max_len = max(map(len, wordDict + ['']))
wordDict = set(wordDict)
for i in range(1, len(s) + 1):
ok += any(ok[... |
447e5fa781aebf30545813eab9f82806146fd988 | nyannko/leetcode-python | /alg/fair_candy_swap.py | 304 | 3.5 | 4 | class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
diff = (sum(A) - sum(B)) // 2
A = set(A)
for b in set(B):
if diff + b in A:
return [diff + b, b]
|
a72b4ba2b7e7838593211a39b1e1087737e119be | nyannko/leetcode-python | /alg/union_find_set.py | 896 | 3.546875 | 4 | class UnionFind:
def __init__(self):
# size of the array
self.up = [0 for _ in range(12)]
def find(self, val):
i = val
while self.up[i] != 0:
i = self.up[i]
return i
def find_compress_path(self, val):
# find root
r = val
while sel... |
edfa13bf778e622dfecdc4e8610bff5578e5f4ec | rjrobert/daily_coding_problems | /daily15.py | 1,254 | 3.90625 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
"""
import random
class RandomPicker:
def __init__(self):
self.result = 0
... |
3e78404cada917e50ee6d87aac4e26a3181f8f19 | rjrobert/daily_coding_problems | /daily9.py | 1,198 | 3.9375 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Airbnb.
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] sho... |
7db3286c9184aa0405e47981b84fa87624ac8cee | rjrobert/daily_coding_problems | /daily12.py | 1,580 | 4.125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
... |
79daaac9dec2b91abffe15f5b8eee98da0c27202 | rbamos/py-readability-metrics | /readability/scorers/gunning_fog.py | 1,197 | 3.609375 | 4 | from readability.exceptions import ReadabilityException
class Result:
def __init__(self, score, grade_level):
self.score = score
self.grade_level = grade_level
def __str__(self):
return "score: {}, grade_level: '{}'". \
format(self.score, self.grade_level)
class GunningF... |
f7da2127c74015f35de8ab57cfb387309c3eb8cf | yuwuxin/python3.5 | /case100/c1.py | 566 | 3.671875 | 4 | #!/usr/bin/env python
# _*_coding:utf-8_*_
# Author:li hang
print('题目:有1、2、3、4个数字 能组成多少个互不相同且无重复数字的三位数?都是多少!')
print('程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。')
print('程序源代码:')
d = []
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if(i != k) and (i != j) and (j != k):... |
0e2f1747f7870b55574adf8000634cca4752d1bf | DWaseoh/Hola-mundo | /Gandalf pruebas objeto.py | 1,578 | 3.6875 | 4 | class Mago:
def __init__(self, v, a, d):
self.Vida = v
self.Ataque = a
self.Defensa = d
self.VidaMaxima = 1000
def recibirdano(self, ArmaAtaque):
self.Vida = self.Vida - ArmaAtaque / self.Defensa
return ArmaAtaque / self.Defensa
def pocion(self, Consumible):... |
28eaa82ee0b381a078a2f67877b2d9e4f3f0b9f5 | jeffsantos/curso-ebape-prog-aplic-cur2021-turma2021 | /5-python-sql/2-sqlalchemy/py03-variaveis-ligadas.py | 621 | 3.515625 | 4 | from sqlalchemy import create_engine, text
import sys
engine = create_engine('postgresql://postgres:postgres@localhost:5432/secretariadb')
connection = engine.connect()
bairro = " ".join(sys.argv[1:])
zona = input("Informe também a zona: ")
sql = text("SELECT * \
FROM professores p \
INNER ... |
56885a3c9d8775bc41a19a62e1a6a167280b3f02 | JohnDS4/team13gp | /puzzles.py | 5,149 | 3.953125 | 4 |
import random
def dice_game():
"""Plays a game of dice, using code from:
https://code.sololearn.com/cjQ6V2Aj2rJk/#py
by user PacketStorm, accessed 22/10/2018
"""
def cee_lo_player():
combo = roll()
win = [4,5,6]
loss = [1,2,3]
w=9
l=0
print("Yo... |
4c99212e73dae6ef65f581a30c682addabf84a76 | juanpablocastro96/Curso-Python-PildorasInformaticas | /Ejercicios Propuestos/ejercicios_propuestos1a.py | 256 | 3.84375 | 4 | nombre = input("Ingrese su nombre: ")
direccion = input("Ingrese su dirección: ")
telefono = input("Ingrese su teléfono: ")
lista =[nombre, direccion, telefono]
print("Su nombre es "+lista[0]+", su dirección es "+lista[1]+" y su teléfono es "+lista[2]) |
04a088280e82201d3abd04734b119019437a1c6f | juanpablocastro96/Curso-Python-PildorasInformaticas | /generadores_2.py | 666 | 3.625 | 4 | #nueva instruccion yeild from
#simplificar el codigo del generador en caso de utilizar bucles anidados
#podria tener un ejemplo matrices
#una serie de ciuddes
#el asteristo antes de un argumento, que va recibir un numero indterminado de elementos y lo recibira en forma de tubla
#def devuelve_ciudades(*ciudades):
# for... |
a7160c2fca3b192eba65401ce0e6dcc865ee56b0 | dafajon/upschool_regression_and_ts | /demo/lr.py | 2,881 | 3.734375 | 4 | import streamlit as st
import pandas as pd
import numpy as np
from sklearn.datasets import make_regression
import altair as alt
def content():
st.title('Linear Assumption 🤔')
st.markdown('When life gives you lemons, you fit a model through them...')
st.header('Generate Data')
mu = st.sl... |
872ca9322969a238935dc87c7f6518bf1208d9f8 | jonAhmeti/Sudoku_CspBacktracking.py | /sudoku.py | 1,843 | 3.703125 | 4 | from pprint import pprint
def find_next_empty(puzzle):
for r in range(9):
for c in range(9):
if puzzle[r][c] == -1:
return r, c
return None, None # if no spaces in the puzzle are empty (-1)
def is_valid(puzzle, guess, row, col):
row_vals = puzzle[row]
if guess i... |
1901e6e18d17b4595391d581443e672a924e2089 | cse210-spring21-team4/cse210-tc06 | /src/mastermind/game/player.py | 1,259 | 4.15625 | 4 | class Player:
"""A person taking part in a game.
The responsibility of Player is to record player moves and hints.
Stereotype:
Information Holder
Attributes:
_name (string): The player's name.
_move (Move): The player's last move.
"""
def __init__(self, players=list)... |
b875750a64ead5ec64ca05427733c97fd31d6968 | wenjie-lu/AOC2020 | /day13.py | 2,406 | 3.625 | 4 | import math
from utils.io_util import read_file
from functools import reduce
# input_path = 'inputs/day13_test.txt'
input_path = 'inputs/day13.txt'
inputs = read_file(input_path)
time0 = int(inputs[0])
buses = inputs[1]
def find_wait_times(time0, buses):
wait_times = {}
min_wait_times = math.inf
ans = 0
... |
b173ae5288c8266ea228bb14e4d38d7598739ad3 | ThereWasALlama/Wikipast_StatBot | /load_birthdays.py | 554 | 3.578125 | 4 | import xml.etree.ElementTree as ET
def load_birthdays():
''' Load all the birthday information from the database and return it as a pagename bday dictionary'''
savename = 'database.xml'
tree = ET.parse(savename)
root = tree.getroot()
# Take the pagenames as the names of the people and ta... |
387d60ae34141de46de84c91515321887615e7fa | yanzixiong/Python_Test | /11day/05-名片.py | 156 | 3.65625 | 4 | dict= [{"name":"尹天","age":20},{"name":"豪哥","age":19},{"name":"崔健","age":18}]
for i in dict:
for k,v in i.items():
print("%s的值是%s"%(k,v))
|
e92378161c5a696e66f17868122c7da87386024a | yanzixiong/Python_Test | /08day/02-求和.py | 59 | 3.546875 | 4 | a = 0
b = 0
while a < 100:
print(a)
a+=1
b=a+b
print(b)
|
e96b5b0943a26f058f3000ceedec85bb4de0944a | yanzixiong/Python_Test | /13day/03-计算器.py | 430 | 3.796875 | 4 | def jisuanqi(x,y,fuhao):
if fuhao =="+":
z = x+y
print("和是%0.2f"%z)
elif fuhao == "-":
z= x-y
print("差是%0.2f"%z)
elif fuhao == "*":
z = x*y
print("积是%0.2f"%z)
elif fuhao =="/":
z = x/y
if y!= 0:
print("商是%0.2f"%z)
else:
print("输入有误")
x = float(input("请输入一个数字"))
y = float(input("请再输入一个数字"))... |
2074579d8a1cadb9eb3f143391eb768ff7b6b023 | yanzixiong/Python_Test | /09day/08-结束当前循.py | 174 | 3.71875 | 4 | #1-10号美女 8号不要面试 直接跳过
i = 0
while i < 10:
i+=1
if i ==8:
print("8号美女直接晋级")
continue
print("%d号美女正在面试"%i)
|
db5a479238bbde8984e5afcb485cb6fd4a2f2be7 | yanzixiong/Python_Test | /08day/03-求和.py | 68 | 3.546875 | 4 | i = 0
sum = 0
while i <=100:
print(i)
sum=i+sum
i+=2
print(sum)
|
174e4d94d62ebd4007c0845264d1477be7266c36 | MidasDoas/royal-game-of-ur | /board.py | 3,307 | 3.71875 | 4 | '''
Tai Warner
Written 22/05/2020
Board class for the Royal Game of Ur
'''
from square import Square
from piece import Piece
import numpy as np
class Board:
def __init__(self):
letters = ['A','B','C','D','E','F','G']
numbers = ['1','2','3','4','5','6','7']
# init all the squares
self.a = Square('a', True)... |
8093570607aa2a11f4cbad0d25ade36f63aee65c | salimildere/SalimIldereMetGlobalTalentProject | /main.py | 10,373 | 3.671875 | 4 | checkers = {1: 3, 6: 1, 10: 2, 12: 1, 13: 1}
#def CalculateScore ():
def find_moves(checkers, dice1, dice2):
locations = []
score = {}
# locations ile her pul değerinin konumu belirtilecek ve sonraki satırlarda kullanılacaktır.
o = 1 # pul değerini temsil eder ve her döngüde bir artar
for key, ... |
267e0aa8b8b053c92d1a19e77f9a2e493409f6dd | TGM-HIT/acc-2017 | /gol/python/src/main/python/gameoflife.py | 3,605 | 3.6875 | 4 | """
:author Markus Re1
:version 2017-12-17 20:30:00 UTC+1
"""
import argparse
class GameOfLife:
def __init__(self, pattern: str):
"""
Set up default values by interpreting the given GoL pattern of 1 generation.
The following format is required:
{width}";"{height}";"{generation}";... |
ae8fa201dffa6aa573ede043721b819a6357b706 | Mishrasubha/Codeforces-Training-sheet | /codeforces/Q8.py | 181 | 3.828125 | 4 | s = input()
arr = []
for i in range(len(s)):
a = s[i]
if a not in arr:
arr.append(a)
if len(arr) % 2 ==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
bf2d0a161d580a7656e1d524604fb2cf69b11ea4 | pash0107/python-programs | /blackjack/index.py | 5,144 | 3.546875 | 4 | import random
#Tuples variable
suits = (
'Hearts',
'Diamonds',
'Spades',
'Clubs'
)
ranks = (
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Jack',
'Queen',
'King',
'Ace'
)
#Dictionary variable
values = {
... |
84a3a04c5a6ee38edde40076e17e78fbc309a944 | LukaszMalucha/Python--Machine-Learning-Regression | /Polynomial Regression.py | 3,219 | 4.03125 | 4 | ## Polynomial Regression (with comparison to linear regression)
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:,1:2].values ## Skip position name column as redundant to ... |
e4c9e7c6473430c6122c112c658132262035f473 | Pawan243/Sweep-line-Algorithm | /Minimum Enclosed Circle/MinimumEnclosedCircle.py.py | 3,313 | 4.40625 | 4 | # a randomized algorithm for finding the minimum area circle enclosing a given point set P.
import matplotlib.pyplot as plt
import random
from math import sqrt
class Circle:
def __init__(self, center, radius):
self.center = center
self.radius = radius
def get_circle_3(A, B, C):
... |
98d5caf14526d3ce3dde7f979a9170cea12aac6b | hemae/neural_networks | /add_ex1_grad_des.py | 1,431 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import time
def f(x):
return x * x - 5 * x + 5
def df(x):
return 2 * x - 5
N = 100 # число итераций
xn = 0 # начальное значение x
lmd = 0.8 # шаг сходимости (коэффициент)
x_plt = np.arange(0, 5.0, 0.1)
f_plt = [f(x) for x in x_plt]
plt.ion() # вклю... |
cd9c916edc4500e96393eba7e41c50400087fed1 | hemae/neural_networks | /ex1_simple_network.py | 1,011 | 3.59375 | 4 | import numpy as np
def act(x):
return 0 if x < 0.5 else 1
def go(vect):
x = np.array(vect)
w11 = [0.3, 0.3, 0]
w12 = [0.4, -0.5, 1]
weight1 = np.array([w11, w12]) # матрица 2х3
weight2 = np.array([-1, 1]) # вектор 1х2
sum_hidden = np.dot(weight1, x) # вычисляем сумму на нейронах срытого ... |
60be6528d7abf2db0f31dcae009081b6448530ab | saceandro/DataAssimilation | /src/4DVar6h_discrete_1parameter.py | 9,226 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 17:01:40 2017
@author: yk
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import math
def handler(func, *args):
return func(*args)
#%%
class Lorenz96:
def __init__(self, N, dt):
s... |
1320362af84f65b52b47f5ec782141a54dcfa14c | saceandro/DataAssimilation | /src/4DVar6hNMC_obs_oscillator.py | 9,768 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 17:01:40 2017
@author: yk
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import math
def handler(func, *args):
return func(*args)
#%%
class Linear:
def __init__(self, N):
self.N ... |
e17792c43909aeb873441ff67efb33b42c2d1f84 | vburnin/PythonProjects | /CompoundInterestLoops.py | 2,028 | 4.53125 | 5 | import locale
locale.setlocale(locale.LC_ALL, '')
# Declare Variables
nDeposit = -1
nMonths = -1
nRate = -1
nGoal = -1
nCurrentMonth = 1
# Prompt user for input, check input to make sure its numerical
while nDeposit <= 0:
try:
nDeposit = int(input("What is the Original Deposit (positive value): "))
e... |
163e2660f0b38f1a9a7aede3824c9f0e8ca70a1f | nlac10/springboard | /00.0-admissions_prework/data_science_career_prep/tech_interview/product_dupes.py | 2,171 | 3.78125 | 4 | # user_input = input("Please enter product info: ")
def unique_products(str):
# reads in file and returns list via .split()
# before making list, make sure to remove whitespaces
# lower case
# what about punctuations? ## should learn how to do error handling
with open(str,"r") as file:
tex... |
0c9957f6774050eb988a2ea2de48a043e94821f2 | leafsummer/keeplearning | /python-gems/online_judge/problem.py | 2,300 | 4.0625 | 4 | """
Every Problem should inherit from Problem class.
The rationale for using python class to define problems
as opposed to persistent data (JSON file, DB) is:
1. Some problems require the program to modify data structures in place,
so you need code to validate its correctness.
2. For some problems, input/expected o... |
9665cd55b81907472661c7d542cfb97b6b532c18 | leafsummer/keeplearning | /python-gems/online_judge/utils.py | 978 | 3.96875 | 4 | """
This module defines a few data structures and utility functions
for use in problem solution and solver
"""
LISTNODE_DEF = """
<pre>
# Definition for singly-linked list node.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
</pre>
"""
class ListNode(object):
"""
... |
1b422fe0f3decbb066f8ac928c2fca1c7e68b272 | mgstabrani/tabpython | /pembahasan-soal/semester-1/tugas-pendahuluan-1/H01_16519171_02.py | 603 | 4.03125 | 4 | '''This program is a simple calcultaor which can do addition, subtraction,
multiplication, division, and modulo'''
A = float(input("Please, input the first number : ")) #a float
B = float(input("Please, input the second number : ")) #a float
C = str(input("Please, input the operator : ")) #operator
if (C == "+"):
... |
170d44051270564cfa5c76d5824740fbe793b8d7 | mgstabrani/tabpython | /pembahasan-soal/semester-1/tugas-pendahuluan-2/H02_16519171_01.py | 174 | 4.15625 | 4 | '''This program requires an input, which is called as N, and
then the program will display 1..N in one line.'''
N = int(input())
for i in range(1,N+1):
print(i,end=" ") |
343e43016f793b6f56dcca61a38bc7ee7eb479a5 | ajuliaseverino/tutoring | /tut/basics.py | 1,420 | 4.21875 | 4 | # print('Hello world')
# x = 5.6
# print(x)
#
# print("\nFor loop from 0 to 9.")
# for i in range(10):
# print(i)
def input_switch():
"""A function definition.
Calling the function by typing input_switch() will run this code.
The code does *not* get run when you create the function.
"""
user_i... |
20259f2957bf42bc89b981d5637ebe2411e239ab | dgroso/pset3 | /Problem 2 | 1,004 | 3.828125 | 4 | #!/usr/bin/python
#### Problem 2 ####
### Collab with Heba El-Ahmad ###
### open and read the file using handle
data = 'wl.csv' # rename filename accordingly
wlhandle = open(data, 'r')
### define function
def highest_num(wlhandle):
### import pandas
import pandas as pd
### create dataframe w... |
c4ba4e49e1fa76932e2d3216c70e4e6a7e8910ab | RahulPhpDev/pyPro | /error_handling.py | 236 | 3.5 | 4 | #The try block will generate a NameError, because x is not defined:
try:
print(x)
except NameError as e:
print(e)
print("Variable x is not defined")
print("""Hello
Hi""")
except:
print("Something else went wrong")
|
4df533571d34c881dae5350fb2203ccfa16a7388 | Abdelbasset-Aidouni/Problem-Solving | /Longest Substring Without Repeating Characters.py | 498 | 3.8125 | 4 | # Given a string, find the length of the longest substring without repeating characters.
class Solution:
def lengthOfLongestSubstring(self, s):
actual_str = ''
res = 0
for c in s:
if c in actual_str:
if res < len(actual_str):
res = len(actual_str)
actual_str = ''
else:
... |
303198fa365d54f0079c672ae797b81537438f7f | Tmstone/Python-Adv | /for_loop_basic1.py | 1,173 | 4.03125 | 4 | #Basic - Print all integers from 0 to 150.
for i in range(0,151,1):
print(i)
#Multiples of Five - Print all the multiples of 5 from 5 to 1,000
for five in range(5, 1005, 5):
print(five)
#Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Coding... |
1a2c0fe1e0abc6c1c02b94ae1fb5006577acb830 | Tmstone/Python-Adv | /for_loops_basic2.py | 4,137 | 4.5 | 4 | #Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big".
#Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5]
def biggie_size(num):
for i in range(len(num)):
if (num[i] > 0):
num[i] = "big"
... |
a08b7a6ad5696fa4c24ac5247f00c925d3183ae2 | pterodragon/asyncio_internals_presentation | /python/run_once_demo.py | 871 | 3.515625 | 4 | import asyncio
async def coro_stub():
"""
From Python docs:
sleep() always suspends the current task,
allowing other tasks to run.
"""
await asyncio.sleep(0) # this is like "yield" in generator
async def coro_p():
for _ in range(3):
print('coro_p: 1')
await co... |
94adb3c9cce3d65357bc0fcc29bb1f0986d73877 | sinadadashi21/Wave-4 | /pig-latin.py | 758 | 4.21875 | 4 | ay = "ay"
way = "way"
consonant = ("B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "Y", "V", "X", "Z")
vowel = ("A", "E", "I", "O", "U")
word = input("Enter the word to translate to Pig Latin: ")
first_letter = word[0]
first_letter = str(first_letter)
first_letter=first_letter.upper()
if... |
f84b276516ec427557727d6c664fcd4ed77910f7 | pdkappel/automail | /compose.py | 1,962 | 3.640625 | 4 | """
compose.py
Copyright (c) 2017 andynines
MIT License
"""
import logger, settings
import random
prev = None
def daily_selection():
"""
Select a random piece of material from what is available. A piece is defined
by a newline; every line is a new piece of content.
"""
logger.log("Selecting today... |
b72bc30d3b2564563a4fb571066921e823136bbe | Hamsik2rang/Python_Study | /Day5/Sources/Day5_2(OOP_Coffee_Machine).py | 1,244 | 3.6875 | 4 | from Menu import Menu, MenuItem
from Coffee_Maker import CoffeeMaker
from Money_Machine import MoneyMachine
class CoffeeMachine:
"""1. print report
2. check resources sufficient
3. process coins
4. check transaction successful
5. make coffee"""
def __init__(self):
self.coffee_maker = ... |
66536ba1353fcefb8951dec0ad9f47e4557f30b3 | Hamsik2rang/Python_Study | /References_Of_Object/Tuple.py | 764 | 4.40625 | 4 | # tuple
# tuple is immutable object. so when you create tuple once, you can't change or delete element(s) in it.
t = (1,)
print(t)
print(" remark: you can't create tuple that have an element without using comma(,). because it is confused with parenthesis operation.\n")
t = (1,2,3)
print(t)
t = 1,2,3
print(t)
# ind... |
25e2a2710fa3cd1bba2c602e41944b7162fbc8fb | Hamsik2rang/Python_Study | /Mini_programming_project/Hangman/Project01_hangman.py | 976 | 4 | 4 | # Step 1
import random
from hangman_art import stages, logo
from hangman_words import word_list
from os import system
print(logo)
answer = random.choice(word_list)
display = ["_" for _ in range(len(answer))]
game_end = False
lives = 6
last_guess = ""
while not game_end:
blank_count = 0
guess = input("Guess... |
4c48dcea0f9ed12c7e86d478166932ea1f59b53f | Hamsik2rang/Python_Study | /Day6/Sources/Day6_3.py | 582 | 3.671875 | 4 | import turtle as t
import random
class RabbitController:
def __init__(self, rabbit, move_count):
self.rabbit = rabbit
self.move_count = move_count
def process(self):
for _ in range(self.move_count):
rgb = (random.random(), random.random(), random.random())
self... |
c2a9066390cb0d0ce79d70dd8af196d41eceb496 | Hamsik2rang/Python_Study | /Mini_programming_project/Snake_Game/game_manager.py | 951 | 3.71875 | 4 | from turtle import Turtle
class GameManager(Turtle):
def __init__(self, snake, food_spawner, collider):
super().__init__()
self.hideturtle()
self.color("white")
self.penup()
self.goto(0, 260)
self.game_is_on = True
self.score = 3
self.update_scoreboa... |
7039ed0143de5d54703a17ec95b1ff4f1887d3ec | Hamsik2rang/Python_Study | /Day14/Sources/Day14_3.py | 526 | 4.0625 | 4 | # Raise Exception if string inputted is not Pelindrome.
class StringNotPelindromeError(Exception):
def __init__(self):
super().__init__("It's not pelindrome.")
def is_pelindrome(s):
if len(s) < 2:
return True
if s[0] != s[-1]:
return False
return is_pelindrome(s[1:-1])
s = in... |
939754732124b0267b59c28aabf69348e6e9c922 | Hamsik2rang/Python_Study | /Day9/Sources/Day9_5.py | 388 | 3.828125 | 4 | # make iterator
class MyIter:
def __init__(self, stop):
self.current = 0
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.current < self.stop:
r = self.current
self.current += 1
return r
else:
... |
b5b661c4c6a50e6195d672b23b9d7ce00eb18490 | Hamsik2rang/Python_Study | /Day13/Sources/Day13_2.py | 234 | 4.3125 | 4 | def is_pelindrome(word):
if len(word)<2:
return True
elif word[0]!=word[-1]:
return False
return is_pelindrome(word[1:-1])
word = input("Type word to check it is pelindrome: ")
print(is_pelindrome(word))
|
bae6500abb2b0d3c9cb42b5820fa2e6862d12a8d | Hamsik2rang/Python_Study | /Day1/Sources/Ex2_1.py | 304 | 3.640625 | 4 | # Remain times Calculator until 90 years old
# 90살까지는 살겠지?
age = input("What is your current age?")
remain_year = 90 - int(age)
days = (remain_year) * 365
weeks = (remain_year) * 52
months = (remain_year) * 12
print(f"your remain age is {days} days, {weeks} weeks, and {months} months")
|
0a0dc9ded80d12e492f2d6715e2dfcb9e7400cfb | Hamsik2rang/Python_Study | /Day9/Sources/Day9_2.py | 266 | 3.609375 | 4 | # list comprehension
a = [i for i in range(10)]
print(a)
b = list(i for i in range(5))
print(b)
c = [round(i * 3.3, 2) for i in range(5)]
print(c)
d = [i for i in range(0, 10) if i & 1]
print(d)
e = [i * j for i in range(2, 10) for j in range(1, 10)]
print(e)
|
a257eed71d1ef198141dc4dcdd95d2044d45fa28 | Hamsik2rang/Python_Study | /Day9/Sources/Day9_8.py | 118 | 4 | 4 | # set comprehension
a = {i for i in "rabbit"}
print(a)
a = {i for i in "rabbit" if ord(i) % ord("a") < 13}
print(a)
|
85e66d664d4f9b7b92c90917b51267b0daaaa4d3 | Hamsik2rang/Python_Study | /Mini_programming_project/Pong/paddle.py | 1,278 | 3.890625 | 4 | from turtle import Turtle
from vector import Vector
DISTANCE = 20
class Paddle:
def __init__(self, collider):
self.paddle = []
self.vector = Vector()
self.starting_pos = ((0, 20), (0, 0), (0, -20), (0, -40))
self.collider = collider
def create_paddle(self):
"""새로운 발판을... |
cd0e80bafd2a6c761dab0c92e11c4aa82b145466 | Hamsik2rang/Python_Study | /Day14/Sources/Day14_6.py | 514 | 4.375 | 4 | # Generator
# Generator is a function contain 'yield' keyword.
# Generator works like iterator object.
def my_generator():
# When Interpreter(Compiler) meet 'yield' keyword, Literally yield program flow(resources) to main routine.
# It means return value there is next 'yield' keyword, and stop routine until nex... |
87578912fbfeadc41774c42416ce99bc646a57cf | Hamsik2rang/Python_Study | /Day13/Sources/Day13_11.py | 958 | 4.125 | 4 | # Multiple Inheritance
# Python support Multiple Inheritance.
class Dragon:
def breath(self):
print("브레스!!!! 피해욧!!!!!")
class Elf:
def heal(self):
print("치유 마법")
class Player(Dragon, Elf):
def attack(self):
print("얍!")
me = Player()
me.breath()
me.heal()
me.attack()
# Diamond... |
fff168696e44e99657e92f1eba2d48da670c0dca | nataliamedinat/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/9-print_last_digit.py | 137 | 3.734375 | 4 | #!/usr/bin/python3
def print_last_digit(number):
ldigit = abs(number) % 10
print("{}".format(ldigit), end="")
return(ldigit)
|
1525444d60392a65146f0768911ab592ea24591a | nataliamedinat/holbertonschool-higher_level_programming | /0x0A-python-inheritance/11-square.py | 1,534 | 4.09375 | 4 | #!/usr/bin/python3
class BaseGeometry:
"""Define a BaseGeometry class
"""
def area(self):
"""Public instance method
"""
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
"""TypeError: If value is not an integer
ValueError: ... |
71935d8a4dc6470d8a99c2268f18020442f07571 | nataliamedinat/holbertonschool-higher_level_programming | /0x03-python-data_structures/1-element_at.py | 273 | 3.515625 | 4 | #!/usr/bin/python3
def element_at(my_list, idx):
ln = 0 # Iterator and store the index of the list
if idx < 0:
return None
if idx >= len(my_list):
return None
for a in my_list:
if (idx == ln):
return (a)
ln += 1
|
4c5f9fb3bca62d5ddcb90512c8616667b9789401 | gitmbar2/mike-calculator | /mikes_calculator_start.py | 1,039 | 3.96875 | 4 | # goal is to build a calculator that works with postfix notation
import operator
from collections import deque
operations_map = {
'+': operator.add,
'-': operator.sub,
'/': operator.truediv
}
class PostfixCalculator:
def __init__(self):
self.stack = deque()
def operation_right_side(self, ... |
0546b6ba33b11f0e8be2eed560f7c6ce32bf8df3 | summerbr/Class | /Week1-Python/list_summer.py | 1,778 | 3.875 | 4 | #sum the numbers
number_list = [2, 17, 76, 99, 200, 501]
print(sum(number_list))
##try as function
#largest number
print(max(number_list))
#smallest number
print(min(number_list))
#even numbers
for even in number_list:
if even % 2 == 0:
print(even)
#positive numbers
for num in [-20, -9, 0, 18, 35]:
... |
84dbd53d0d3a0c7b5bc983acc1cadefb46e49eaf | summerbr/Class | /Week1-Python/loop_summer.py | 1,679 | 3.96875 | 4 | #1 to 10
for num in range(1, 11):
print(num)
#n to m
user_input1 = int(input('Enter start: '))
user_input2 = int(input('Enter stop: '))
user_input2 = user_input2 + 1
for num in range(user_input1, user_input2):
print(num)
#Odd numbers
for num in range(1, 11):
if num % 2 != 0:
print(num)
#print a squa... |
7eb49a9a1ae819769a8014182d27710f6635965e | MikhailAmeerally/PuzzleSolver | /mn_puzzle.py | 3,267 | 3.671875 | 4 | from puzzle import Puzzle
class MNPuzzle(Puzzle):
"""
An nxm puzzle, like the 15-puzzle, which may be solved, unsolved,
or even unsolvable.
"""
def __init__(self, from_grid, to_grid):
"""
MNPuzzle in state from_grid, working towards
state to_grid
@type self: this ... |
8dba06972c08167a973e68a4081fd9d0c6834a05 | daniellehoo/python | /week 3/dictionaries.py | 252 | 3.78125 | 4 | stock = ["Microsoft," "MSFT", "NASDAQ", "108.25", "106.23"]
stock[1]
# Dictionaries let you label values using strings
stock = {"name": "Microsoft",
"ticker": "MSFT",
"index": "NASDAQ"}
print(stock["name"])
print(f"{stock['name']}") |
c00c114531ecc3ccf2d29dd7457ed7c6c68ede60 | daniellehoo/python | /week 1/math2.py | 467 | 4.1875 | 4 | # in Python you can do math using the following symbols:
# + addtion
# - subtaction
# * multiplication
# / division
# ** exponent (not ^)
# > greater than
# >= greater than or equal to
# < less than
# <= less than or equal to
# and more!
answer = (40 + 30 - 7) * 2 / 3
print("what is the answer to life, the universe, ... |
f49620f89678d514469a427c9231e3575e737139 | csudcy/outrun | /outrun.py | 3,621 | 3.546875 | 4 | def load_graph(path):
"""
Load an outrun graph from the given file
Return an array of arrays e.g.
[
[1],
[1,2],
[1,2,3],
...
]
Each node can talk to the node directly below it & the node to the right
"""
graph = []
with open(path, 'r') as f:
f... |
30df44021f52beb12e54d3e7251ab9b0110164da | SmitaPandey/oopsconspt | /createlinklist.py | 349 | 3.859375 | 4 |
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
mylist = UnorderedList()
print (mylist.isEmpty)
mylist.add(3)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
... |
a1ef6a58cb90b888d47d5ee9940db7a15ceea86f | psouare/Algos | /quicksort.py | 278 | 3.640625 | 4 | def partition(A,p,r):
pivot=A[r]
i=p-1
for j in range(p,r-1,1):
if(A[j]<=pivot):
i=i+1
A[j],A[i]=A[i],A[j]
A[r],A[i+1]=A[i+1],A[r]
return i+1
def quicksort(A,p,r) :
if(p<r):
q=partition(A,p,r)
quicksort(A,p,q-1)
quicksort(A,p,q+1)
|
625df95fa8af658396f5f3f78453db5cbe7432af | tianshufu/Leetcode_study | /121.Best time Stock2.py | 453 | 3.5 | 4 | class Solution:
def maxProfit(self, prices) -> int:
if not prices:
return 0;
else:
profit=0
for i in range(1,len(prices)):
#define a value to store the money earned by each dat
tmp=prices[i]-prices[i-1]
if (tmp>0):
... |
d290012469a97dce836ab126de042f32203db029 | tanvi-arora/datasecurity | /code/cipher.py | 3,065 | 4.125 | 4 |
def caesar_dec():
print("inside decipher")
#ask for user input
ciphertext = input("Enter sentence to dencrypt")
#since we have 26 letters run a loop for bruteforce logic to check for shift values from 0-25
for shift in range(0,25):
print("shift value is ",shift)
str_dec =... |
6a1b3a66ad75b0a4f77cdd35687f2bb2b8474509 | Folgue02/lakeCLIAddons | /mdindexer/mdindexer.py | 1,306 | 3.8125 | 4 | #!/usr/bin/env python3
import os
from sys import argv
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("file", type=str, help="File to read")
parser.add_argument("-i", "--indentation", type=int,help="Number of spaces for indentantion (default is 2)")
arguments = pars... |
a00b4d7b781ae078c273abe3a64ec4d332868866 | pendlm1/Python | /lab9_graded.py | 2,141 | 3.515625 | 4 | # Lab 9 UNGRADED exercises
# These exercises are for practice only
# Mario Pendleton
# B01158863
from turtle import*
import math
def flSquare(n,s):
speed(0)
shape("turtle")
goto(0,0)
setheading(0)
for i in range(4):
fd(n)
lt(90)
pu()
setx(n+s+s)
pd()
def frSquare(n... |
7e61bb6949a8bfd79cddec34dc520152925c14df | AndrianusTinas95/learning-python | /consitions.py | 552 | 4.09375 | 4 | x = 2
#print(x==2)
#print(x==3)
#print(x < 3)
name = 'cai'
age = 23
#if name == 'cai' and age == 23 :
# print('your name is cai , and you are also 23 years old')
#if name == 'cai' or name == 'coi':
# print('your name is either cai or coi')
name ='andri'
#if name in ['cai','coi'] :
# print('your name is eithe... |
433c526ccb02610b1a86a8194295e0aa41cacd30 | brijsavla/Project2 | /Part1/GraphSearch.py | 3,080 | 3.546875 | 4 | # Prijesh Dholaria
# CS 435 Section 6
# Question 3
from Graph import Graph
from queue import Queue
class GraphSearch:
def _init_(self):
pass
def DFSRec(self, nodeStart, nodeEnd):
visitedListNode=[];
if nodeStart!=nodeEnd:
HelperDFSRec(nodeSt... |
9994ce8bb0ab1e4c2c4797f5a6e59a31ba325f7f | lance-lh/Data-Structures-and-Algorithms | /剑指offer/NumberOf1.py | 1,053 | 3.578125 | 4 | # -*- coding:utf-8 -*-
'''
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
'''
'''
def NumberOf1(n):
if not isinstance(n,int):
return None
cnt = 0
if n < 0:
# 对于负数,最高位为1,而负数在计算机是以补码存在的,往右移,符号位不变,
# 符号位1往右移,最终可能会出现全1的情况,导致死循环。与0xffffffff相与,就可以消除负数的影响
# 相当于求补码
n = n & 0xffffffff
... |
c92f0b239c93c37966774573e80496678d007f8e | lance-lh/Data-Structures-and-Algorithms | /剑指offer/printMatrix.py | 1,505 | 4.21875 | 4 | # -*- coding:utf-8 -*-
'''
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
例如,如果输入如下4 X 4矩阵:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
则依次打印出数字
1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
'''
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
res = []
# 类似于旋转魔方,每次先输出matrix第一行并删除
# 然... |
45ae0599587889e0113d163702471f494f7d1508 | lance-lh/Data-Structures-and-Algorithms | /DSA/十大排序/CountSort.py | 428 | 3.53125 | 4 | def countsort(arr):
maxval = max(arr)
bucketLen = maxval+1 # index from 0
bucket = [0]*bucketLen
ind = 0
arrLen = len(arr)
for i in range(arrLen):
bucket[arr[i]]+=1
for j in range(bucketLen):
while bucket[j] > 0:
arr[ind] = j
ind += 1
buc... |
3089da776ab332f3a99ee61ab8d2f098ea50aa25 | lance-lh/Data-Structures-and-Algorithms | /剑指offer/mergeAB.py | 855 | 3.78125 | 4 | # -*- coding:utf-8 -*-
'''
有两个从小到大排序以后的数组A和B,其中A的末端有足够的缓冲空容纳B。
请编写一个方法,将B合并入A并排序。
给定两个有序int数组A和B,A中的缓冲空用0填充,
同时给定A和B的真实大小int n和int m,请返回合并后的数组。
'''
class Merge:
def mergeAB(self, A, B, n, m):
# write code here
k = n + m - 1
i,j = n-1,m-1
while i >= 0 and j >= 0:
if A[i] ... |
cfab81c0e5b79dbd020758b8059451a622f2bf8e | lance-lh/Data-Structures-and-Algorithms | /nowcoder/Union_Find_template.py | 2,232 | 3.546875 | 4 | '''
三步走:
1. 初始化pre和ranks数组,pre为每个元素的父结点(上一级),
ranks为每个元素作为根节点时的树的秩(树的深度),
一开始设置pre的每个值为每个元素自己,设置ranks每个值为0.
2. find() 查询该元素的首级,顺便做路径压缩
3. join() 合并两个集合,按秩合并,秩小的树的根节点指向秩大的树的根节点。
————————————————
原文链接:https://blog.csdn.net/AivenZhong/article/details/89148862
'''
def find(x, pre):
"""
查找x的最上级(首级)
:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.