blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1010491a2e598931545a8544c9e24f85efa2f061 | AndersonANascimento/curso_python | /ex_agreg.py | 2,135 | 3.5 | 4 | #-*- encoding=UTF-8 -*-
import pandas as pd
import numpy as np
# Dados das eleições primárias dos EUA
eleicoes = pd.read_csv('./datasets/primary-results.csv')
# print eleicoes.head()
# No aggregate, analisamos a coluna 'votes', aplicando 3 funções
# print eleicoes.groupby('candidate').aggregate({'votes':[min, np.mean... |
67ad34d4159f06772fbd39e04165ba2a320c659e | akalya23/gkj | /71.py | 68 | 3.6875 | 4 | n2=input()
a2=n2[::-1]
if(n2==a2):
print('yes')
else:
print('no')
|
6c0dfa87461d062d42a0904e8752309f6c98be50 | charlesjhlee/mitx_6.00.1x | /gcdIter.py | 506 | 3.96875 | 4 |
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
smallest = min(a,b);
gcd = 0;
if (a%smallest == 0 and b%smallest == 0):
return smallest;
while (smallest > 1):
i... |
1a0e4c19544437c449721380cf18b7291c3a1ae4 | KKira/KKira.github.io | /static/images/euler/code/advent/2019/day1.py | 419 | 3.59375 | 4 | def readfile():
with open("day1.txt") as fp:
contents = fp.read().strip()
all_rows = []
for row in contents.split('\n'):
all_rows.append(int(row))
return all_rows
instructions = readfile()
total_fuel = 0
for module_mass in instructions:
fuel = int(module_mass/3) - 2
total_fuel += fuel
while fuel > 0:
... |
81a6cd972a43e3c8068b4966c4318cabb227b28e | 8v10/eprussas | /1_LogicaDeProgramacao/0_Python/1_Python_Parte1/1 - Introdução/5 - Math.py | 63 | 3.5625 | 4 | x=5
y=10
print (x+y)
print (x*y)
print (y-x)
print (y/x)
|
7060ad71868ff7c9cc5346db70d88629f242f38a | UoLPythonGroup/training | /PROJECTS/benchmarking/Parallelising/Parallel(shared_memory)_MC_calculation_of_pi.py | 1,157 | 3.53125 | 4 | from multiprocessing import Process,Queue,Manager,Value,Lock
from random import random
from sys import argv
def get_pi(N,pi,lock):
"""Monte Carlo method of calculating pi the first argument is the number of samples to use, the second one in this case it for the return value."""
n=0
while n<N:
x=random()
... |
74d11483870ca425de5d9c5150cfbe55e18900d0 | Rafaellinos/learning_python | /exercises/fibonacci_numbers.py | 1,338 | 4.09375 | 4 | from time import time
def performance(func):
def wrap_func(*args, **kw):
t1 = time()
result = func(*args, **kw)
t2 = time()
print(f'took {t2-t1} s')
return result
return wrap_func
# not a generator, just prints the number
@performance
def fib(n):
a = 1
b = 0
... |
372162f426507a981eec9e7e85425b2314f68009 | Sebas1130/Python_Ejemplos | /proyecto4/stack.py | 1,033 | 3.953125 | 4 | """
Code used for the class 'Crear un stack'.
"""
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
self.size = 0
def push(self, data):
""" Appends an element on top. """
node = No... |
ba78aaa5b8ed535d6ae91aeea2243f242ceafe87 | as1014/Daily-Code_Problem | /Problem1.py | 961 | 3.78125 | 4 | #problem 1
#Given a list of numbers and a number k
#Return whether any two numbers from the list add up to k
#test values
l = [15, 13, 10 , 7]
k = 17
#get length of list
l_len = len(l)
def sum(lst, k):
#loop through the list
for i in range(l_len):
lst_len = len(lst)
base_num = lst[0]
... |
841e146c2274841d4722abe24376b748e69a3397 | JLowborn/CS50 | /pset6/mario/less/mario.py | 274 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from cs50 import get_int
from cs50 import get_string
height = 0
while height < 1 or height > 8:
height = get_int("Height: ")
for i in range(height):
print(f" " * (height - 1 - i), end="")
print(f"#" * (i + 1)) |
9e4661e4f27f1d713c65923e0a5e3fd46a098aaf | sdzx1985/Project | /Practice/Web_Scraping_Practice/Web_Scraping_Practice #1/4_Re.py | 760 | 3.578125 | 4 | import re
p = re.compile("ca.e")
# . (ca.e) : one word > care, cafe, case | caffe
# ^ (^de) : start point > desk, destinatio | fade
# $ (se$) : end point > case, base | face
def print_match(m):
if m:
print(m.group()) # matchs string
print(m.string) # inserted string
print(m.start()) # matc... |
893e4306cb5d7254f573bd82d1f07d1e97d745b1 | jlittle576/jlittle576.github.io | /articles/data_parsing/technique_examples/string_methods/string_methods_demo.py | 979 | 3.640625 | 4 | # File are arrays of sting, so naturally,
# the built in method for arrays any strings are critical to data file parsing
# String methods
# there is no str.remove(), use replace instead
print '233.4, 232.33, 342.34'.replace(' ', '')
# >>> 233.4,232.33,342.34
# line from files will have trailing EOL and often padded... |
cd60b5cd27ee91f01b075c050a06b1d76a52fa0d | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex011.py | 293 | 3.78125 | 4 | largura = float(input('Qual a largura, em metros, da parede? '))
altura = float(input('Qual a altura, em metros, da parede? '))
area = largura * altura
litros_de_tinta = area/2
print('Você precisará de {} litros de tinta para pintar a sua parede de {}m²'.format(litros_de_tinta, area))
|
bd9e96e3af0016a1302c469b1ba25edebfa79dad | roguewei/python_yspc | /demo/spider.py | 2,366 | 3.640625 | 4 | # 引入Python内置的http操作库
from urllib import request
# 引入re正则表达式包
import re
# 爬虫框架可以使用BeautifulSoup,Scrapy
class Spider:
# 需要爬取的网页地址
url = 'https://www.huya.com/g/lol'
root_pattern = '<span class="txt">([\s\S]*?</span>[\s]*<span class="num">[\s\S]*?</span>[\s]*)</span>'
name_pattern = '<i class="nick" title... |
a95043d658ea4ec83ef5fa3032b642e004cb948c | morristech/cipherama | /substitution.py | 1,307 | 3.734375 | 4 | import sys
import argparse
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
" ",",", "!","?", ".", "'", "\n", ";",":", "’"]
class SubstitutionCipher:
def __init__(self, key, offset = 0):
self.original_alphabet... |
e338f16108191b9066f7047b06f3dd5aa6f1196d | mkskyring/PIAIC-136742- | /Numpy _Task1.py | 2,949 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Reading Recipes
#
# Note: Data file is recipes.csv Attached with jupyter notebook
1. Start by importing NumPy as np
# In[3]:
#type your code here
import numpy as np
# 2. All of Alize’s recipes call for milk, eggs, sugar, flour, and butter. For example, her cupcake recipe... |
27e44127f2ab7bbfd56eef0a227d0c4d167c316e | dexapier/python-regex | /address_book.py | 2,829 | 4.375 | 4 | # coding:"utf-8"
# \w -> cualquier unicode letra por letra
# \W -> lo que no sea unicode
# \s -> whitespace, space, tabs, etc
# \S -> lo que no sea whitespace, tabs, space, etc
# \d -> número 0 al 9
# \D -> lo que no sea número
# \b -> extremo de la palabra
# \B -> no en el extremo de la palabra
# {3} -> cuenta exact... |
407c3708cf5ac04bbd1013c529883e6f7b75919d | krenevych/algo | /source/T3_Find_Search/P1_Search/L6_binary_continuous.py | 1,151 | 3.65625 | 4 | import math
def binary_continuous(f, c, a, b):
""" Для монотонної на відрізку [a, b] функції f розв'язує рівняння
f(x) = c
:param f: Монотонна функція
:param c: Шукане значення
:param a: Ліва межа проміжку на якому здійснюється пошук
:param b: Права межа проміжку на якому зді... |
2c12e848f86cf9bc4c16264040f5f9bc712d5fe6 | jack-x/HackerEarthCode | /E_BobAnIdiot.py | 728 | 3.609375 | 4 |
def main():
N=int(input())
alphadict = dict()
for character in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':
alphadict[character] = character
for x in range(0,N):
i=input()
inp = i.upper()
inp2 = i.lower()
temp = alphadict[inp[0]]
alphadict[inp[0]] = alphadict[inp[2]]
alphadict[inp[2]] ... |
cfee29e770dfe259a68da4c0e125d64205b213f5 | leobalestra/pyhton-aulas-alura | /AulasPython/ContaCorrente.py | 855 | 3.828125 | 4 | class ContaCorente:
def __init__(self, codigo):
self.codigo = codigo
self.saldo = 0
def deposita(self, valor):
self.saldo += valor
def __str__(self):
return (f"Código: {self.codigo} saldo: {self.saldo}")
conta_leo = ContaCorente(292)
conta_lari = ContaCorente(666)
conta... |
ab4864820d500672d1db47af423140366ccc9e5d | weltonvaz/Zumbis | /exercicio02_welton_02.py | 326 | 3.671875 | 4 | # coding:utf8
#
# Determine se um ano é bissexto. Verifique no Google como fazer isso...
#
import os
os.system("clear") # Limpando a tela
bissexto = int(input("Digite o Ano com 4 digitos, ex: 1968 : "))
if bissexto % 400 == 0 or bissexto % 4 == 0:
print ("Este ano é bissexto")
else:
print ("Este ano NÃO é bissexto"... |
b6bb619cf72498f3da1dbb3597f012024bd993bc | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/ClassMethods/methods.py | 1,327 | 3.890625 | 4 | #class Car:
# wheels_number = 4
# def __init__(self, name, color, year, is_crashed):
# self.name = name
# self.color = color
# self.year = year
# self.is_crashed = is_crashed
#def drive(self, city):
# print(self.name + ' is driving to ' + city)
#def change_color(self, ... |
f1ab95f58476c480e8ef999b492265356dea98ad | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/projects-DS/data_struct_and_algo/max_in_array.py | 219 | 3.796875 | 4 | def find_max(arr, l):
temp = arr[0]
for i in range(l):
if temp < arr[i]:
temp = arr[i]
return temp
arr = [1, 2, 3, 4, 5, 6, 55, 6, 7, 8, 8, 8]
max = find_max(arr, len(arr))
print(max)
|
180d63381575ad8399a416e91c868e2036bde8b9 | aryanvichare/eco.life | /basic.py | 1,523 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the dataset
# emissions_X, emissions_y = datasets.load_emissions(return_X_y=True)
f = open("emissions.csv")
f.readline() # skip the header
data = np.... |
f39969d020ebf95d8ce11ce09166b8ecc65a726b | qlccks789/Web-Study | /17_python/part3-control/test04_for3.py | 214 | 3.546875 | 4 | # 구구단
index = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in index[1:]:
for j in index:
print(str(i) + " * " + str(j) + " = " + str(i*j))
print()
"""
2 * 1 = 2
2 * 2 = 4
....
9 * 8 = 72
9 * 9 = 81
"""
|
49760cdbfea03ddfad8965303863ac1761bb1577 | ramondfdez/57Challenges | /2_Calculations/8_PizzaParty.py | 1,114 | 4.65625 | 5 | # Division isn’t always exact, and sometimes you’ll write
# programs that will need to deal with the leftovers as a whole
# number instead of a decimal.
# Write a program to evenly divide pizzas. Prompt for the
# number of people, the number of pizzas, and the number of
# slices per pizza. Ensure that the number of pie... |
62bcf01bc4aedf276fff05e52a684ba789d35e26 | youkaede77/Data-Structure-and-Algorithm | /剑指offer/32. 从上到下打印二叉树(不分行).py | 1,440 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: wdf
# datetime: 2/9/2020 1:23 PM
# software: PyCharm
# project name: Data Structure and Algorithm
# file name: 32. 从上到下打印二叉树(不分行)
# description: 层序遍历、不分行
# usage:
# 队列实现层序遍历
class Node(object):
'''节点类 '''... |
171e5c83d3a61c95eb52ab73f82ece6d517086f8 | eng-lenin/Python | /ex13.py | 165 | 3.65625 | 4 | s=float(input('Digite o salário do funcinário: R$ '))
r=s*1.15
print('O funcionário recebia {} R$, com o reajuste passou a receber {:.2f} R$.'.format(s,r)
) |
c5b67543f2bf0db5ca426c7ce655426874b2b006 | fanliugen/Hello-world | /generatorTest.py | 282 | 3.796875 | 4 | #yield 装入数据,产出generator object,使用next释放
def fun3():
for i in range(1,5):
yield i
if __name__ == '__main__':
gob = fun3()
print(gob)
print(next(gob))
print(next(gob))
print(next(gob))
print(next(gob))
print(next(gob)) |
236d4a267f73cba94998aae8f9585877a28157f2 | mabdulul/DigitalCrafts_Week2 | /ex3.py | 416 | 4.03125 | 4 | '''Write a letter_histogram program that asks the user for input, and prints a dictionary
containing the tally of how many times each letter in the alphabet was used in the word. '''
words = input(" The words? ").upper()
letters_count_dict = {}
count = 0
for i in words:
if not i in letters_count_dict:
l... |
70e03ad7088f74beeea70adb0fff694fb8131da0 | bradelement/coding_exercise | /leetcode-master/060/main.py | 606 | 3.6875 | 4 | import math
class Solution(object):
def get_permutation(self, n, k, arr):
if k == 0: return ''.join(arr)
prev = math.factorial(n-1)
cur = k / prev
return arr[cur] + self.get_permutation(n-1, k%prev, arr[0:cur] + arr[cur+1:])
def getPermuta... |
cb136aee077e057fdcbdb552ef8714413dcd0bc1 | songyqdevote/Python-100-Days-Practisetice | /Day01-15/code/Day08/printnum2.py | 718 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :printnum2.py
# @Time :2021/6/14 20:29
# @Author :宋业强
import threading
import time
def threada():
with con:
for i in range(1, 10, 2):
time.sleep(0.2)
print(threading.current_thread().name, i)
con.wait()
... |
e24b614100421b1ab4e8774f3204b8636e641abd | hack1973/web-caesar | /caesar.py | 1,243 | 4.0625 | 4 | def alphabet_position(letter):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_index = ''
letter = letter.lower()
for char in alphabet:
letter_index = alphabet.index(letter)
if char == letter:
return letter_index
return letter_index
#print(alphabet_position("Z"))
def rota... |
8288f649569bcc95c5f80631e8d8b4648f369663 | H-Bouhlel/H-Bouhlel | /Memoire_Haithem/Code/file.py | 455 | 3.515625 | 4 | import csv
def create_file(path,file_name):
with open(path+file_name, mode='w',newline='') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
return
def add_row(path,file_name,col1,col2,col3):
with open(path+file_name, mode='w',newline='') as file:
... |
ffac43e3d69573dfd688d316883eab54b118c3e1 | xiaokongkong/some-tricks-about-python | /刷题/剑指offer/字符串/翻转单词顺序 VS 左旋转字符串.py | 517 | 4.25 | 4 | # 翻转单词顺序
# 要求:翻转一个英文句子中的单词顺序,标点和普通字符一样处理
# 思路: Python中字符串是不可变对象,不能用书中的方法,可以直接转化成列表然后转回去
def reverse_words(sentence):
tmp = sentence.split()
return ''.join(tmp[::-1])
# 左旋转字符串
# 思路: 把字符串的前面的若干位移到字符串的后面
def rotate_string(sentence,n):
if not sentence:
return ''
return sentence[n:] + sentence[:n... |
06c541c88b5c467465be4e0aa870abc49acb5081 | A-fil/repeating_algorithms_python | /sorting/heap_sort.py | 1,059 | 3.984375 | 4 | # IN PROGRESS
from typing import List, Any
from test_data.sorting_data import UNSORTED_NUMERICAL_SEQUENCE
from utils.array_utils import swap
def parent_index(index: int):
return int((index - 1) / 2)
def left_index(index: int):
return 2 * index + 1
def right_index(index: int):
return 2 * index + 2
... |
1359614d9ebebc008bc2d2f0858f02dea31b4619 | Dayook/Algorithm | /python/divide_and_conquer/consecutive_sum.py | 326 | 3.671875 | 4 | # 1부터 n까지 더하기
def consecutive_sum(start, end):
mid = (start + end)// 2
if start == end:
return start
return consecutive_sum(start, mid) + consecutive_sum(mid + 1, end)
print(consecutive_sum(1, 10))
print(consecutive_sum(1, 100))
print(consecutive_sum(1, 253))
print(consecutive_sum(1, 388)) |
a32e36770f5c2974a1bd1c288a808e1d78d885a5 | ozcayci/01_python | /gun10/draw_a_box.py | 658 | 4.28125 | 4 | ## Draw a box outlined with asterisks and filled with spaces.
# @param width the width of the box
# @param height the height of the box
def drawBox(width, height):
# A box that is smaller than 2x2 cannot be drawn by this function
if width < 2 or height < 2:
print("Error: The width or height is too... |
fb47bc86a8e53d015aae0fadda87b9764e55817c | MxMossy/aoc2017 | /3_day.py | 462 | 3.828125 | 4 | number = int(input("What number: "))
#construct spiral
spiral = []
spiral.append([1])
ring_lev = 1
num = 2
while num <= number:
ring = []
while len(ring) < ring_lev * 8:
ring.append(num)
num += 1
ring_lev += 1
spiral.append(ring)
def Manhat_Dis(a):
for i in a:
if number in... |
843475ced4ee5fefaf2a40a42139b16493882d8d | dinobobo/Leetcode | /346_moving_average_data_stream.py | 702 | 3.8125 | 4 | from collections import deque
class MovingAverage:
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.size = size
self.count = 0
self.q = deque([])
def next(self, val: int) -> float:
if self.count < self.size:
... |
d49e579592993517fa84815aa9a92a2b5f46004b | sudheeramya/python | /ifelseconditon3.py | 133 | 3.640625 | 4 | is_hot = True
is_cold = False
if is_hot:
print('It is Summer')
elif is_cold:
print ('It is Cold')
print('It is ENJOY DAY ')
|
3bf086b5ec3521b977f7f9c831c2080a6c6fd5b3 | RHaran98/data-mining | /k_means.py | 2,350 | 3.625 | 4 | import random as r
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as pl
k = int(input("Enter number of clusters : ")) #Number of clusters
epochs = int(input("Enter number of epochs : "))
ipf = int(input("How would you like your points?\n1. Random gen\n2. CSV File \n3. Type in the p... |
926bfb54be334af3ee648d7a68e7fdff66eae656 | 3Nakajugo/challenge2 | /numbersq.py | 287 | 4.25 | 4 | from datetime import date
def age():
yob = int(input('Please Enter your year of Birth:'))
today= date.today().year
age = today- yob
if (age < 18):
print('Minor')
elif (age >= 18 and age < 36):
print('Youth')
else:
print ('elder')
age()
|
eb6b3878c32abb66eca58ed04bf4101a8e826649 | d-m/project-euler | /007.py | 676 | 3.9375 | 4 | """
Project Euler Problem 7
=======================
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.
What is the 10001st prime number?
"""
import math
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0:
r... |
779bb639636c70792b3d6a063153986245eec38c | henryscala/leetcode | /py/p75_sort_colors.py | 1,738 | 3.765625 | 4 | # problem 75 of leetcode
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
leftindex = 0
rightindex = len(nums)-1
while leftindex < rightindex:
while leftin... |
0eca322d4c353a80a7899430ce105872c963b691 | TatianaMatveeva/Learning_Python | /OPPC 1.10/C10_4/PartyforEverybody.py | 656 | 3.703125 | 4 | class Guests:
def __init__(self, name, location, status):
self.name = name
self.location = location
self.status = status
class Human(Guests):
def get_person(self):
return f'''{self.name}, {self.location}, stile IN life "{self.status}"'''
Vol1 = Human('Джони пуля в... |
2e1cebb79c7daa8071803397697aac48e6acf615 | Acid2510/Python | /suff/week3/while_exercise.py | 142 | 4.03125 | 4 | Word=raw_input('Input a word:')
num=input('how many times:')
loop=0
while loop<num:
print ('{0} {1}'.format(Word,loop+1))
loop=loop+1
|
7c269d2af52f620210f373214fe2580cd5a2e5c1 | subbbbbb/Python-Archives | /1st Semester/caesarCipher.py | 3,139 | 4.4375 | 4 |
# getMode() is a getter method that either prints out decrypt/encrypt, or tells you to do it over again if invalid input
def getMode(): # defines the specific mode that you want
# converts single letters to lowercase to preventp roblems later
mode = input("do you want to encrypt or decrypt?").lower()
# ... |
0622cbd52fd5f2ec4958c9bdce5bc1d03ad6362d | dotslash-web/PY4E | /Course 3 - Using Python to Access Web Data/Chapter 11/Lecture Material/RegularExpressions.py | 2,941 | 4.3125 | 4 | ''' Regular Expressions-
Regular expressions are a language unto themselves. It's an "old school" language
In computing , a regular expression, also referred to as "regex" or "regexp", provides
a concise and flexible means for matching strings of text, such as particular characters,
words, or patterns of charac... |
d332fe3eda2383dced74cc9c47475abf55990856 | LucasLeone/tp1-algoritmos | /estructura_secuencial/es4.py | 306 | 3.59375 | 4 | '''
Teniendo como dato el lado de un cuadrado,
calcular e imprimir la superficie y perímetro.
'''
lado_cuadrado = float(input('Cuantos cm mide el lado del cuadrado? '))
print('La superficie del cuadrado es: ', lado_cuadrado*lado_cuadrado)
print('El perimeto del cuadrado es: ', lado_cuadrado*4) |
c1a019da9107d704a098cb778a4b2d49cb985e2a | Graver75/python_study | /pack_1/problem1_0.py | 431 | 4.09375 | 4 | def shift_list_for(arr, n):
for i in range(n):
arr.insert(0, arr.pop(len(arr) - 1))
return arr
def get_list():
return list(input('Enter list: ').split())
print('Moving lists')
arr = get_list()
try:
shift = int(input('Enter value for move: ')) % len(arr)
print('Your new list: ', shift_list_f... |
895d5b8ac85f2890c710c7c14daa76c6d96e95dc | jamwyatt/simpleProgrammingChallenges | /python/nthPrimeNumber.py | 827 | 4.0625 | 4 |
import sys
def findPrimePositional(primePos):
primeCount = 0
n = 2
while True:
isPrime = True
max = n/2+1
if (n>2) and (n%2 == 0):
# Even above two are not primes
isPrime = False
elif n%3 == 0:
isPrime = False
else:
x... |
c1af35363798f3dce977a99ae491696db32e87da | KeeJoonYoung/keras | /keras30_split2_DNN.py | 685 | 3.5 | 4 | # 30_split 커피
import numpy as np
a = np.array(range(1,11)) # 뒤에꺼 하나 뺀거까지
size = 6
print(a) # [ 1 2 3 4 5 6 7 8 9 10]
def split_x(seq, size):
aaa = []
for i in range(len(seq) - size + 1):
subset = seq[i : (i+size)]
aaa.append(subset)
print(type(aaa))
retur... |
49dcfb8f1d5c0304ecb7e13f08aeb570aea8ec71 | chatsuboctf/chatsubo | /app/helpers/rand.py | 510 | 3.671875 | 4 | import string
import random
def randstr(length=8):
"""
Generates a random password having the specified length
:length -> length of password to be generated. Defaults to 8
if nothing is specified.
:returns string <class 'str'>
"""
letters = string.ascii_letters
numbers = string.di... |
fefd85a88a9e00562de1eba2765ac583a6cc2cd8 | minaazol/CP3-Meena-Kittikunsiri | /Lecutre71_Meena_K.py | 387 | 3.8125 | 4 | menuList = []
priceList = []
def bill():
print("------My Shop------")
for i in range(len(priceList)):
print(menuList[i], priceList[i])
print("Total :",sum(priceList))
while True:
menu = input("Please enter menu : ")
if menu.lower() == 'exit':
break
else:
price = int(input("Please enter pric... |
6442953bed319234789b4ba580b3de6d04421671 | ramamohanraju/RPi | /led/led_blink.py | 700 | 3.84375 | 4 | # This program will Blink the LED connected to GPIO 7.
import RPi.GPIO as GPIO # import RPi.GPIO module
from time import sleep # lets us have a delay
GPIO.setmode(GPIO.BCM) # choose BCM or BOARD
GPIO.setup(7, GPIO.OUT) # set GPIO7 as an output
try:
while True:
... |
4ddfb7af82bf9d7b2ad258e2a242558b8d9ce899 | runningcost2/Learning_Python_from_Zero | /22. oneline_for.py | 482 | 3.890625 | 4 | # Changing attendance number. ex)1, 2, 3, 4 => 101, 102, 103, 104
students = [1,2,3,4,5]
print(students)
students = [i+100 for i in students] #loading every i in students and add 100 each
print(students)
# changing name to length of name
students1 = ["Zeus", "Hestia", "Poseidon", "Julius Caesar"]
students1 = [len(i) ... |
50a98ba589183b8630fa8d5b60dc55b98d567711 | skp96/DS-Algos | /Leetcode/Trees and Graphs/build_tree.py | 1,873 | 3.796875 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self, preorder_idx=0):
self.preorder_idx = preorder_idx # keep track of preorder position
def build_tree(self, preorder, inord... |
b961ebd12eb25a3b8479053e140f0183de7a25ce | swjjxyxty/study-python | /base/each.py | 394 | 3.53125 | 4 | # -*_ coding:utf-8 -*-
names = ["1", "2", "3"]
for name in names:
print(name)
sum = 0
for x in range(101):
sum += x
print(sum)
sum = 0
n = 99
while n > 0:
sum += n
n -= 2
print(sum)
n = 1
while n < 1000:
if n > 10:
break
print(n)
n = n + 1
print("END")
n = 1
while n < 1000:
... |
d287f9b94043561998bcf729d996c923778cc01b | jadenpadua/ICPC | /Python/sorting/selection-sort.py | 890 | 3.859375 | 4 | # Idea, iterate through an array with a pointer on each index, find min element and swap with that index
# O(n^2) time | O(1) space
def selectionSort(array):
# Idx that will iterate through our array
currentIdx = 0
# Breaks when array is fully traversed
while currentIdx < len(array) - 1:
# At ea... |
a32f336b6d5746d5377ad4e231ba1fc19919a334 | minhyeong-joe/coding-interview | /Graph/Dijkstra.py | 1,903 | 4.0625 | 4 | # Given a weighted graph, a source vertex and a goal vertex,
# find the shortest distance from the source vertex to the goal vertex.
# Assume there IS a path between the source and the goal.
# Using Dijkstra's Algorithm:
from queue import PriorityQueue
from Graph import ListGraph
def dijkstra(graph, src, goal):
... |
6bc04717059fc803deb222b41e3351501e544669 | nowstartboy/my_code_new | /the_exam/weiruan3.py | 598 | 3.578125 | 4 | def maxStipend2(numOfDays,taskList,state):
if not taskList or not numOfDays:
return 0
if state==1: #前一天工作了
max1=taskList[0][0]+maxStipend2(numOfDays-1,taskList[1:],1)
else:
max1=taskList[0][1]+maxStipend2(numOfDays-1,taskList[1:],1)
max2 = maxStipend2(numOfDays - 1, taskList[1:],... |
3a5d1991ff1a3e59260746c3edc712f47dc3ba07 | cmhedrick/mysticquest | /mysticquest.py | 1,973 | 3.703125 | 4 | class Room:
def __init__(self, id, name, desc, doors):
self.id = int(id)
self.name = name
self.desc = desc
self.doors = doors
def __str__(self):
return "{0}\n{1}\n{2}\n{3}\n".format(self.id, self.name, self.desc, self.doors)
class House:
def __init__(self):
... |
8d4d46aa87d3e133b3695e554a89c0497dde9391 | v-72/go_play | /algo/rain_water_1.py | 565 | 3.609375 | 4 | def findWater(arr):
low = 0
high = len(arr) - 1
left_max = 0
right_max = 0
water = 0
while(low < high):
if arr[low] < arr[high]:
if arr[low] > left_max:
left_max = arr[low]
else:
water += left_max - arr[low]
low += 1
... |
fbd6fd869278bc065fbe77c72315798d717b49c3 | xiongxiong109/algorithm_study | /py/algorithm/radix_sort.py | 1,221 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 定义一个模块需要上面的声明, 这样才可以被其他模块执行
# 使用队列实现基数排序 py
from queue import Queue
from math import floor
def radix(args=[]):
# 创建10个队列 bin0 - bin10
bin_arr = []
data_arr = []
for i in range(10):
bin_item = {
'id': 'bin%s' % i,
'queu... |
83a65ee2a97e3e4f7291d326f2e1c90234eda3c7 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/Craig_Morton/Lesson04/json_save/json_save/saveables.py | 6,601 | 3.546875 | 4 | #!/usr/bin/env python
"""
The Saveable objects used by both the metaclass and decorator approach.
"""
import ast
# import json
# import json.import.xy
# import.json.element.xy
# import.rh.ty.element
# import.ty.rh.identity.x
# import.identity.name.space.x.json
__all__ = ['Bool',
'Dict',
'Float'... |
b899e93387e05a12f52fef5d6a90ebd98f01c2c3 | khushboojain123/python-code | /armstrong in an interval.py | 760 | 4.15625 | 4 | # program to display all the armstrong number in which interval which is given by user
# take input from user
def arm():
return()
def main():
lower = int(input("enter lower range:"))
upper= int(input("enter upper range:"))
for num in range(lower, upper+1):
sum=0
temp = n... |
8242561d5e671fa9c15323f3696db9c577805bd5 | drewherron/class_sheep | /Code/charlie/python/lab20.py | 2,326 | 4.25 | 4 |
def credit_number_check(user_input):
#this while statement allows the user to input a list of numbers until they are input 'done'
while True:
credit_number = input("enter your credit card number\n:")
if credit_number == 'done':
break
credit_number = int(credit_number)
... |
90cc0a3662896b3a2d33718c8519573b4c5a85bd | kamyu104/LeetCode-Solutions | /Python/construct-the-longest-new-string.py | 277 | 3.671875 | 4 | # Time: O(1)
# Space: O(1)
# constructive algorithms, math
class Solution(object):
def longestString(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: int
"""
return ((min(x, y)*2+int(x != y))+z)*2
|
3ea50073baefb984e73aec23f2ef86b0c9a2fdef | Chizzy-gem/My_python_class | /square2.py | 1,423 | 4.375 | 4 | # Homework
# Read more about if statement
# Implement option for B to compute the perimeter of the square
# Implement option AP, calculate both Area and Perimeter
# Implement for anything that is not A or B or AB let this end the program
# Create square2.py and do the homework there
#ANSWER
# Ask the user fo... |
4546c9cf4b86764564e9416271da97cb68c6c7d6 | masterfung/LPTHW | /ex14.py | 790 | 3.828125 | 4 | from sys import argv
script, user_name = argv
prompt = '-****->>> '
print "Hi awesome %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few short questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where is your residence %s?" % user_name
lives = raw_input(pr... |
c22bd7923f484cbf7c73d5737ecd9d6d28013c6f | nmante/cracking | /chap-3/python/stack.py | 711 | 3.5625 | 4 | """
Nii Mante
Stack implementation
"""
from node import Node
class Stack:
def __init__(self, data):
self.top = Node(data)
def __str__(self):
tmp = self.top
out_str = "Stack\n"
out_str = out_str + "====\n"
while tmp:
out_str = out_str + str(tmp.dat... |
83cf3c375cf7f2942c6ded20ed34bad43b5bdb45 | Lights19/Python | /Python_introductory/exceptions.py | 959 | 4.40625 | 4 | #'exceptions' are the errors detected at the time of program execution
# #handling the exception, by using "try and except"shuld be in the part of program where exception is
#expected to occur
x=input("Enter a number1: ")
y=input("Enter a number2: ")
try:
z=int(x)/int(y)
except ZeroDivisionError as e:
print("Di... |
b489e48634ed1bdd7286e8b46978c7fccbd556b0 | tuouo/selfstudy | /learnfromBook/PythonCookbook/DataStructure/about_priority_queue | 919 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return... |
7f2dff0b06bc40e2e55cc38a57b75ca5335cfacd | ReeseAEJones/CatanAI | /src/core.py | 2,835 | 3.75 | 4 | import enum
import math
import random
class TileTypes(enum.Enum):
sheep = 1
wheat = 2
wood = 3
clay = 4
ore = 5
desert = 6
class PlayerColors(enum.Enum):
red = 1
blue = 2
orange = 3
white = 4
class Tile:
# Uses Cube coordinates
def __init__(self, x, y, z, tile_type... |
2f8bb126e66e403953cf4f827d0f45256e384a2d | xx-m-h-u-xx/Python-Exercises | /Python-Getters-Setters.py | 731 | 3.671875 | 4 | class MyClass:
def __init__(self, lst):
self.my_list = lst
@property
def my_list(self): # getter
return self._my_list
@my_list.setter
def my_list(self, value): # setter
self._my_list = value
''' Different approach '''
class MyProperty:
def _... |
36db69a2a886e230e7408a752a385dc27deb863d | simozhou/data_structure | /bst.py | 5,039 | 3.890625 | 4 | # Binary Search Tree
class TreeNode(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.payload = value
self.leftChild = left
self.rightChild = right
self.parent = parent
def has_left_child(self):
return self.leftChild... |
74456c81ec3924009193c3d5da7bddeb4953f57b | kartiktanksali/Data-Structures | /CircularLinkedList.py | 4,030 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 10:07:23 2019
@author: kartiktanksali
"""
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
... |
4e045126a66aa199ece057e4b1517df997ca61e2 | B10532021/Information_Security_Class | /hw4/B10532030_楊博惟/Rsa.py | 3,957 | 3.8125 | 4 | from math import gcd
import random
def extend_gcd(a, b):
"""
compute extend_gcd: ax + by = gcd(a, b) to generate x, y, gcd(a, b)
:param a: coefficient
:param b: coefficient
:return: x, y, gcd(a, b)
"""
if b == 0: # find gcd
return 1, 0, a
else:
x, y, g = extend_gcd(b, ... |
2988f8f8b94a9efcbbb0ce87aeaeecb2a4cb32f5 | Damns99/4BreviLezioniDiPython | /errori python.py | 1,288 | 3.5625 | 4 | ###Errori comuni
##sintax error
#syntax error è l'errore che appare ogni qualvolta che un comando viene scritto male o viene usato un carattere sbagliato, qui sono riportati alcuni esempi
#print("ciao')
'''
d=5
print("f=%f", %d)
'''
#impord numpy
'''
import numpy
a=numpy.array(dtype=int , [1,1,1,1,1,1,1])
'''
'''... |
00aebb104e812449f195fb009691e26c94c3e129 | DilipBDabahde/PythonExample | /RP/count_digits.py | 422 | 4 | 4 | '''
9. Write a program which accept number from user and return number of digits in that number.
input: 3235545
output: 7
input: 10
output: 2
'''
def count_digits(no):
icnt = 0;
while no != 0 :
no = no//10;
icnt = icnt + 1;
return icnt;
def main():
ival = int(input("Enter number: "));
result = ... |
24d79e35d709ee9b312f274c3c4b544c917cc782 | sreekar7/LearningPython | /while.py | 253 | 3.9375 | 4 | # Simple demonstration on while loop
i,j = 1,1
while i < 5:
print("hello ", end="") # end="" will stays on the same line
j = 1
while j < 4:
print("Srikar ", end="")
j += 1
i += 1;
print() #Simply prints the newline |
a37193215baacfcfc1576c4e50390235bdfd54a3 | dmiruke/HackerRank-Python | /chocolateFeast.py | 401 | 3.765625 | 4 | #!/bin/python3
# Complete the chocolateFeast function below.
def chocolateFeast(n, c, m):
w = n//c
feast = n//c
while w >= m:
bought = w//m
feast += bought
w = (w - bought*m) + bought
return feast
t = int(input())
for _ in range(t):
ncm = input().split()
n = int(ncm[0... |
0ce414fbc2c894ae708dfe670f58f6e11211aa36 | QiuHongHao123/Algorithm-Practise | /Suanfa/Saunfa2_2.py | 429 | 3.609375 | 4 | #使子序列中最大值的和最小
from typing import List
def minsmax(nums:List[int],B:int)->int:
lenth=len(nums)
if lenth==1:
return nums[0]
sum=0
minmax=float('inf')
for i in range(lenth-1,-1,-1):
sum=sum+nums[i]
if sum<=B:
minmax=min(max(nums[i:])+minsmax(nums[:i],B),minmax)
... |
0aa0d1c6b9578d6357240b1d83b3657e09d86318 | k1oShd/WEB2021SPRING | /lab7/CodingBat/warmup_1/7.py | 233 | 3.671875 | 4 | def pos_neg(a, b, negative):
if(a>0 and b<0 and negative == False):
return True
if(a<0 and b>0 and negative == False):
return True
if(a<0 and b<0 and negative == True):
return True
else:
return False
|
bf9dfbe1eb376e38f059b629312086cda8a91b7c | waitingFat/pythonNotes | /listToCouple.py | 192 | 3.625 | 4 | def ListToCouple():
listFirst = ["zhangsan", "lisi", "wangwu"]
listSecond = ["23", "43", "19"]
print list(zip(listFirst, listSecond))
if __name__ == '__main__':
ListToCouple() |
3767109cdb69487fa54cc24e299487f7c657bf09 | MengSunS/daily-leetcode | /lintcode_578_LCA_iii.py | 1,447 | 3.921875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary tree.
@param: A: A TreeNode
@param: B: A TreeNode
@return: Return the LCA of the two nodes.
""... |
240c92b4570aa350a94ba42cb2a5ca45e9eeaab1 | eDerek/LeetCodeProblems | /Basic Calculator.py | 1,804 | 4.15625 | 4 | # Implement a basic calculator to evaluate a simple expression string.
# The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
# Example 1:
# Input: "1 + 1"
# Output: 2
# Example 2:
# Input: " 2-1 + 2 "
# Output: 3
# Example 3:
# In... |
7f3aff70c21664a5ac05bc4ff76066c95efab97a | Mporzier/piscine-python | /day00/ex04/operations.py | 921 | 3.96875 | 4 | import sys
if (len(sys.argv) != 3):
if (len(sys.argv) > 3):
print("InputError: too many arguments")
print("Usage: python operations.py")
print("Example:")
print(" python operations.py 10 3")
sys.exit()
test1 = sys.argv[1].replace('-', '', 1)
test2 = sys.argv[2].replace('-', '', 1)
if (no... |
895f2bc52fb4d9c5913329470786bad0f2649642 | Stanels42/python-data-structures-and-algorithms | /challenges/quick_sort/quick_sort.py | 954 | 4.0625 | 4 | from copy import deepcopy
from random import randint
def shuffle(lst):
"""
Takes in a list and returns a deep copy with all values in shuffled positions.
In: List
Out: Shuffled (new) List
"""
new_lst = deepcopy(lst)
for i in range(len(new_lst)):
rand = randint(i, len(new_lst) - 1)
new_lst[i], new... |
e79b561f4f71cd9b5bba58b15e38f922e294bc22 | kaviraj333/python | /pb79.py | 147 | 3.59375 | 4 | import math
ammu,abhi=map(int,raw_input().split(' '))
n1=ammu*abhi
if math.sqrt(n1)==int( math.sqrt(n1)):
print ("yes")
else:
print ("no")
|
77998abd2c9dd8c677f450e4f8d4bcd92c98a027 | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/332/101158/submittedfiles/principal.py | 157 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
D={'Júlia':(10,9),'Davi':(10,8),'João':(10,7)}
print('dicionario=',D)
D.keys()
print('Chaves do diconario:',D) |
15e88757e99a4285445e4641ff9e86df0c9ff134 | ARWA-ALraddadi/python-tutorial-for-beginners | /03-Workshop/Workshop-Solutions/fun_with_flags.py | 1,564 | 4.28125 | 4 | #--------------------------------------------------------------------
#
# Fun With Flags
#
# In the lecture demonstration program "stars and stripes" we saw
# how function definitions allowed us to reuse code that drew a
# star and a rectangle (stripe) multiple times to create a copy of
# the United States flag.
#
# As... |
91da7b96bad9b6280617aaa4e1a49104b45d5b4d | gauthamp10/100DaysOfCode | /005/replace_with_alphabet_pos_6kyu.py | 1,030 | 4.125 | 4 | """In this kata you are required to, given a string, replace every letter with
its position in the alphabet.If anything in the text isn't a letter, ignore it
and don't return it."""
import string
from random import randint
def alphabet_position(text):
"""Function to return alphabet pos"""
alpha_dict = dict(zi... |
1da8a353e8ee468c142132a81af6de95052c901d | lilsweetcaligula/sandbox-codewars | /solutions/python/390.py | 203 | 3.515625 | 4 | def logical_calc(array, op):
import operator, functools
op = (op == "AND" and operator.and_
or op == "OR" and operator.or_
or operator.xor)
return functools.reduce(op, array) |
59a875cc48207fc5bee788111de22ee25c114bda | VCloser/CodingInterviewChinese2-python | /50_01_FirstNotRepeatingChar.py | 326 | 3.828125 | 4 | def first_not_repeating_char(s):
maps = {}
for i in s:
if i not in maps:
maps[i] = 1
else:
maps[i] += 1
for i in s:
if maps[i] == 1:
return i
return None
if __name__ == '__main__':
res = first_not_repeating_char("qwertytrewqf")
prin... |
bd50c455079eaab37332233a6d2b76ba8813d679 | aston-github/CS101 | /F19-Assign4-Hangman/CheckMyFunctions.py | 1,377 | 3.859375 | 4 | '''
This module is for you to use to test your implemention of the functions in Hangman.py
@author: ksm
'''
import random
import Hangman
if __name__ == '__main__':
print('Testing createDisplayString')
lettersGuessed = ['a', 'e', 'i', 'o', 's', 'u']
misses = 4
hangmanWord = list('s___o... |
ffe61fdb7752ab81cf7cb79940ad1f054871c107 | iRaM-sAgOr/road_accident | /main.py | 360 | 3.546875 | 4 | import random
start = 0
end = 0
digit = ''
for i in range(1, 11):
start = (start * 10) + 1
end = (end * 10) + 9
print("start and end is ", start, end)
for j in range(1, 101):
k = random.randint(start, end)
print(j, k)
digit=digit +'\n'+ str(k)
with open("number.txt", "w") as tex... |
38769d6450d8f9bf199776ebfc34bb215829b4d1 | Rohini-Vaishnav/list | /log4.py | 195 | 3.8125 | 4 | a=["A","B"]
b=[]
i=1
n=int(input("enter the number"))
while i<=n:
j=0
while j<len(a):
b=b+[a[j]+str(i)]
j=j+1
i=i+1
print(b)
#Logical questions output: user 2 de to ["A1","B1","A2","B2"] |
7a31bed90fb97e497f1220929302bd69323ddc6d | Miloloaf/Automate-The-Boring-Stuff | /chapter_9/prefixadder | 764 | 4.09375 | 4 | #! python3
#! Adds specified prefix to start of all file names in the directory
import os, shutil
os.chdir(r"Directory") #Insert new directory here
items_list = os.listdir(os.getcwd())
appendage = str(input("Please enter a prefix to files: \n"))
remove = str(input("Would you like to remove the original files (y/n)?... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.