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 |
|---|---|---|---|---|---|---|
4506ada5bce184083c904335be49b57562ca2b98 | R0nald88/D002-2019 | /L4/Q2.py | 467 | 3.75 | 4 | def factors(n): # your code here
for x in range(1, n + 1):
if n % x == 0:
print("%d divides %d" % (x, n))
factors(40) # print 1 divids 40
# 2 divids 40
# 4 divids 40
# 5 divids 40
# 8 divids 40
# ... |
0856f3979515ea4cdbb0dba831baa8f70cc9ec90 | abeyer/adventofcode2015 | /03/aoc03.py | 3,248 | 4.125 | 4 | """
Advent of Code Day 3: Perfectly Spherical Houses in a Vacuum
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always... |
e53e80bc6817b76f4364d94fe471dc9b89c6dbec | chaitanyanalage/Patterns | /Number without reassingning.py | 203 | 3.890625 | 4 | """
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
"""
n = int(input("Enter triangle height: "))
num = 1
for i in range(n):
for j in range(i+1):
print(num,end=" ")
num = num+1
print() |
f47e2fac747082807248ed67462553a0ac7c84c1 | chaitanyanalage/Patterns | /ftl.py | 159 | 3.84375 | 4 | """
*****
****
***
**
*
"""
n = int(input("Enter Triangle height: "))
for i in range (n):
for j in range(n-i):
print("*",end=(""))
print()
|
d21d947473b1eade4fa6eb5317cf62920f23dc18 | kburd/HackingClub | /Checkers/GamePieces.py | 2,937 | 3.546875 | 4 |
def isLegalMove(board, movement, playerColor):
startX, startY, endX, endY = movement
#Piece off of board
if endY > 7 or endY < 0 or endX > 7 or endX < 0:
return False
#No piece at start position
elif board[startX][startY] == None:
return False
#Wrong color piece
elif boa... |
b7897aa5007f29d2fa5ffcba6a412cbe908ed407 | techcentaur/AdventToCode-2017 | /day1/captch.py | 160 | 3.515625 | 4 | def captcha(s):
sum=0
s=s+s[0]
for i in range(0,len(s)-1):
if s[i]==s[i+1]:
sum+=int(s[i])
print(sum)
if __name__=="__main__":
captcha(input()) |
00978c22ea8573e7054c1306ffacef889d70062b | junwo383/pyt1 | /구구단.py | 287 | 3.609375 | 4 |
print("|================구구단=======================|")
while True :
guign = int(input("숫자를입력하세요!:"))
for i in range(1,10):
print(guign,"x",i,"=",guign*i)
else:
print("고객님!구구단을 이용해주셔서 감사합니다.!") |
836d67544db247ec149f55ce2f0932780c43f3a2 | kiwillz21mahdi/AMCC-DESKTOP-MAHDI | /per2.py | 579 | 3.875 | 4 | angka2 = int(input('Masukan ANGKA Kedua:'))
angka2 = int(input('Masukan ANGKA Kedua:'))
print('operator : 1.penjmlahan \n2. Pengurangan \n2
'3. Perkalian \n4. pembagian')
pilih=int(input('Pilih Operator :'))
if pilih == 1:
tambah = angka1+angka2
print('Hasilnya adalah ',tambah)
elif pilih == 2:
kurang = ang... |
3ba77efc952b80a4aa501a2becc5e46a5a973208 | livash/Python_practice | /loops.py | 2,753 | 3.890625 | 4 | def count_matches(s1, s2):
""" (str, str) -> int
Return the number of positions in s1 that
contain the same character in s2.
Precondition: len(s1) == len(s2)
>>> count_matches('ate', 'ape')
2
"""
result = 0
for i in range(len(s1)):
if s1[i] == s2[i]:
result += ... |
f004d86a4c547ad7b4cbf5b03c08750b689ace3c | cmarro3/Class-work- | /CIS 103/Payroll Program/payroll03.py | 1,042 | 3.640625 | 4 | #-------------------------
# Payroll Program
#-------------------------
def blkln(a):
print('\n'*a)
def calcgp():
rate = float(input('Enter Rate of Pay: '))
hrs = float(input('Number of Hours worked: '))
gp = rate * hrs
return(gp,rate,hrs)
def calcfit(gp):
fitrate = .12
cfit = ... |
60c9b0cbf1fb204524c0bd6cacef673e1a5b235b | samgetanism/hangman | /hangman.py | 3,326 | 3.890625 | 4 | def hangman(word):#wordはhangmanを始める際に指定する
wrong = 0#プレイヤーの間違えた回数
stages = ["",
"------ ",
"| ",
"| | ",
"| O ",
"| /|\ ",
"| / \ ",
"| "
]#文字列のリスト 間違えのたびにハングマンが出... |
866ce0169275dadad1da38661eac0e2605ed46dc | mehmetyaylacci/CS461-Hws | /hw-4/topsort.py | 4,680 | 3.8125 | 4 | '''
@authors: Burak Turksever, Eralp Kumbasar, Mehmet Yaylaci
Citation for the Code (The Graph Class)
Title: Iterative Topological Sort
Author: Shihab Shahriar Khan
Date: Nov. 11, 2017
Availability: https://stackoverflow.com/questions/47192626/deceptively-simple-implementation-of-topological-sorting-in-python
Th... |
c644c148c271250fd557d967f8f0ca53e486618a | mehmetyaylacci/CS461-Hws | /hw-1/main.py | 10,614 | 4.0625 | 4 | # @authors:
# Burak Turksever
# Mehmet Yaylaci
# Eralp Kumbasar
import graph
choice = str(input("Would you like to run the program with the default data? (yes/no)"))
if choice.upper() == 'YES':#the program solves the 3 questions as default
solver = graph.Graph()
print("3 Cannibals 3 Missionaries and a Boat of Cap... |
d2cd539efea274a6108a02463519ffca5beb97d3 | qtxr/ruirui | /华氏到摄氏.py | 191 | 3.796875 | 4 | print ('这是一个把华氏温度换成摄氏温度的程序。')
print ('请输入您的华氏温度:')
f = float(input())
c = (f - 32) * 5.0 /9
print ('这个是', int(c), '摄氏度')
|
07cf1068ba24e8bc67544e8b03b77b422992c623 | ca-cao/colloids | /pyscrpts/cart2cil.py | 1,761 | 3.6875 | 4 | # python cart2cil.py leer.dat escribir.dat r0
# para hacerlo mas general calculamos el radio r0 a aprtir de parametros de la simulacion
# parametros que si tenemos
# python cart2cil.py leer.dat escribir.dat lambda rcyl
from math import atan,sqrt,pi,floor
import sys
# archivos a escribir
f = open(str(sys.argv[1]),"r... |
ea18111ac54929514bf222c4dafee6528982ea2c | cheetimloh/social-media-data-scripts | /01-apis/scripts/youtube-get-vids-from-channel.py | 5,516 | 3.5625 | 4 | import requests
import csv
import json
from utils import request_until_succeed, open_csv_w
from secrets import YOUTUBE_API_KEY
# make empty data array
rows=[]
# this is where we define the API query and all its variable
api_key = YOUTUBE_API_KEY
# the search API caps search results to approximately 500 videos. To maxi... |
b15b1ee38064115ab98f5c48062906a015e26e06 | artonge/aalto | /Sudoku/1_Random-Policy.py | 893 | 3.796875 | 4 | import gym
import matplotlib.pyplot as plt
import sys
import gym_sudoku
# The number of episode we will do
episodes_nb = 1000
# Create the environment using gym
env = gym.make('Sudoku-v0')
print env.action_space
print env.observation_space
# Create an array to store the reward for each episode
# Usefull to visalize... |
5f79a022ee4c91a5d3c3b780fe1bf6c54f87519b | ClarkThan/algorithms | /sort/MergeSort.py | 614 | 3.984375 | 4 | #MergeSort
def merge(left, right):
merged = []
while left and right:
merged.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
while left:
merged.append(left.pop(0))
while right:
merged.append(right.pop(0))
return merged
def mergeSort(seq):
length = len(seq)
if length <= 1:
return seq
middl... |
4bcb49fd95da3441282e8d114ca7f29c9f9274b9 | hpharmsen/antology | /settings.py | 886 | 3.609375 | 4 | import arcade
from dataclasses import dataclass
@dataclass()
class Settings:
SCALE = 1
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
SCREEN_TITLE = "Antology"
DRAW_BASE = True
NUM_WALLS = 60 # 60
WALL_COLOR = "#777"
BASE_COLOR = "#222"
FOOD_COLOR = arcade.color.APPLE_GREEN
NUM_FOOD_... |
d755f615039b736ac5b9098d1ee7f232891cd04a | cweiyu/a | /1.py | 526 | 3.703125 | 4 |
# coding: utf-8
# In[16]:
def reverse(word):
answer = ''
for i in word:
answer = i + answer
return(answer)
a= reverse("junyiacademy")
print(a)
# In[19]:
def reverse_2(word):
word = word + " "
alist = list()
answer_2 = ''
for i in word:
if i != ' ':
ans... |
ca021ba86a845e0c52c5377bdd43773fbbdf2358 | cdirocco/AstroProject | /AddingGalaxySubroutine.py | 1,304 | 3.859375 | 4 | #!/usr/bin/python
galaxyDict = {}
def addGalaxy(galaxyType):
while True:
try:
galaxyName = str(raw_input("Please give the galaxy a name: "))
try:
float(galaxyName)
int(galaxyName)
except ValueError:
break
except V... |
44e3075f330829b743c9fc81044e97aaa3fbc43d | FabianCh/ELEN060-2_Project-2 | /source_coding/compression.py | 4,940 | 4.03125 | 4 | import math
# # Source coding and reversible data compression
# lowercase letters [’a’,’b’,...,’z’]
lowercase_letter = list("abcdefghijklmnopqrstuvwxyz")
# all numbers [’0’,’1’,...,’9’]
number = list("0123456789")
# some additional characters, i.e. [’.’,’,’,’;’, ... ]
def import_text(file_name):
"""return the co... |
56ed47492c77824291cdc0a15ac6e20fa2a27b46 | deejay6/Practice-Problems | /codechef.py | 283 | 3.90625 | 4 | s = raw_input("Enter String: ")
flag = 0
for i, j in zip(range(0, len(s)-3), range(2, len(s)-1)):
if s[i] != s[j]:
flag = 0
print 'no'
break
else:
flag = 1
print 'yes'
if flag == 1:
print 'yes1'
else:
print 'no'
|
2d581b493dfedf28e374603d185af07059716883 | simonqiang/taming_big_data_spark | /friends-by-age.py | 2,587 | 3.8125 | 4 | from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("FriendsByAge")
sc = SparkContext(conf = conf)
def parseLine(line):
# for each line split input text into the fields list
fields = line.split(',')
# grab the 3rd value in the list and save it as an int
... |
89f60456dab24d8b8bbdd4524151037ee692a5f0 | alexandradev/brain-workout | /russian_declension.py | 344 | 3.734375 | 4 | x = int(input())
y = x % 10
z = x % 100
if 11 <= z <= 14:
print(x, 'программистов')
else:
if y == 1:
print(x, 'программист')
elif 2 <= y <= 4:
print(x, 'программиста')
elif 5 <= y <= 9 or y == 0:
print(x, 'программистов')
else:
print('error')
|
b99ccfb64d7bac9b50b7df3b8e0c4863eafddcdd | ymkNK/onmyoji | /supports/thread_management.py | 4,210 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# coding=utf-8
"""
@author: Li Tian
@contact: litian_cup@163.com
@software: pycharm
@file: thread_management.py
@time: 2021/1/18 17:42
@desc: 常用methods
1. [线程的关闭](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread)
"""
from threading impo... |
d3fd1a9a2a0452017cbee167003269c9e88edfa9 | khanhtran25/MindX-C4T | /Session 1/Ses 8/Ses 9/Minihack1.py | 390 | 3.84375 | 4 | R = "Red"
B = "Blue"
T = "Teal"
items = [R, B, T]
print(*items, sep=", ")
n = input("Enter New Color: ")
items.append(n)
print(*items, sep=", ")
a = int(input("Enter color number: "))
print("Color at position",a,":",items[a-1])
for i,item in enumerate(items):
print(i+1,".",item)
b = int(input("E... |
d6f8d38a2f1baefc83c3bfb43776f1646fa6f286 | khanhtran25/MindX-C4T | /Session 1/ses6/name_valid.py | 371 | 4 | 4 | while True:
n = input("Your name: ")
if n.isdigit():
print ("do not include number, please insert again")
else:
print ("naiceeee")
break
while True:
m = input("Password: ")
if m.isdigit():
print ("naice")
break
else:
... |
55dfe662665dfd4a024a4fc422ab15914b82a818 | khanhtran25/MindX-C4T | /Session 1/Ses 8/CRUD.py | 799 | 4 | 4 | items = [ 'com', 'pho', 'bun']
print(*items, sep= ", ")
C = "Create"
c = "create"
R = "Read"
r = "read"
U = "Update"
u = "update"
D = "Delete"
d = "delete"
while True:
x = input("Choose an action to proceed: ")
if x == C or x == c :
n = input("What do u want to add: ")
i... |
9426c02282a4b4b9ec1e655e68b4bf722044584b | forever0136789/data-structure | /剑指offer(python版)/代码/12.数值的整数次方.py | 254 | 3.765625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
s=1
for i in range(abs(exponent)):
s*=base
if exponent<0:
return 1/s
else:
return s
|
1a3b6fbbda80d5f2228e0d542156a4ac1ffadc62 | supercede/py-projects-repo | /books-project-file/utils/database.py | 2,080 | 4 | 4 | from helpers import save_book_file, display_results
def addBooks(books):
book = {}
name = input('Book Title: ')
author = input('Book Author: ')
book['name'] = name.lower()
book['author'] = author.lower()
book['read'] = False
books.append(book)
save_book_file(books)
print('Book ad... |
6a4db5a680fb4cf8999113fb92ca6983ea4ed0bd | KarnolPL/python-unittest | /06_functions/05_tax/tax.py | 844 | 4.03125 | 4 | def calc_tax(amount, tax_rate, age):
"""The function returns the amount of income tax"""
if not isinstance(amount, (int, float)):
raise TypeError('The amount value must be int or float type')
if not amount >= 0:
raise ValueError('The amount value must be positive.')
if not isinstance(t... |
01fe18819e29ae6806c6392f384ce6cbc39c81b7 | KarnolPL/python-unittest | /06_functions/04_tax/tax.py | 511 | 4.25 | 4 | def calc_tax(amount, tax_rate):
"""The function returns the amount of income tax"""
if not isinstance(amount, (int, float)):
raise TypeError('The amount value must be int or float type')
if not amount >= 0:
raise ValueError('The amount value must be positive.')
if not isinstance(tax_ra... |
e6f1f6d1a10ba552d2c4dbcca3d90576aaeb243f | qchui/qchui | /剑指offer/构建乘积数组.py | 462 | 3.703125 | 4 | """
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],
其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
"""
# -*- coding:utf-8 -*-
class Solution:
def multiply(self, A):
mult = 1
B = [1]*len(A)
for i in range(len(A)):
mult = mult * A[i-1] if i>0 else mult
for a in ... |
2ca1c12dae3d789d51763f02e2ce766f2f356d8a | qchui/qchui | /剑指offer/按之字形顺序打印二叉树.py | 3,103 | 3.578125 | 4 | """
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,
第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
"""
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Print(self, pRoot):
if not pRoot:
return []
if pR... |
5e9784d8234f727d81c03c7d3ab8e85ac48af7fe | qchui/qchui | /剑指offer/矩阵中的路径.py | 1,828 | 3.859375 | 4 | """
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。
例如 a b c e
s f c s
a d e e
这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,
但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
"""
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matr... |
5588dad39ce8b2d00d77f4497371df468016e4fe | Parzha/Assingment3 | /assi3project6.py | 583 | 4.125 | 4 |
flag=True
number_list = []
while flag:
user_input=int(input("Please enter the numbers you want? "))
number_list.append(user_input)
user_input_2=input("If you wanna continue type yes or 1 if you want to stop type anything= ").lower()
if user_input_2=="1" or user_input_2=="yes":
flag=Tr... |
9e26df615f6397a5e0c3df2863c7e09c382e545d | sidarthd/Deep-Learning-Assignment-1-Multilayer-perceptrons-on-MNIST | /HW1/simple_mlp_backprop_working.py | 3,607 | 3.671875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.preprocessing import scale
epsilon = 1e-5
# NOTICE!!!! The data/hidden units
# are in shape of (dimension, num_data).
# For example, for input data of size (4, 150),
# multiply with the first layer matrix of size (20, 4)
# ... |
89c8771cf039c405faad0a11123ed7434d821f0f | kellaJL/douyin-script | /common/compression.py | 864 | 3.546875 | 4 | from PIL import Image
import math
import os
def resize_image(origin_img, optimize_img, threshold):
"""
shrink image by size
:param origin_img:
:param optimize_img:
:param threshold:
:return:
"""
file_size = os.path.getsize(origin_img)
with Image.open(origin_img) as im... |
e68ce6ed23b536195d51f4d71f3e91521f133c68 | AaryanGoel/Homework-1 | /main.py | 1,684 | 4.25 | 4 | # author: Aaryan Goel apg5720@psu.edu
letter = input("Enter your course 1 letter grade: ")
credit1 = float(input("Enter your course 1 credit: "))
GradeP = 0
if letter == "A":
GradeP = 4.0
elif letter == "A-":
GradeP = 3.67
elif letter == "B+":
GradeP = 3.33
elif letter == "B":
GradeP = 3.00
elif letter == "B-... |
655943425aa2059f81775def713b0bc6a6f27ea3 | jfallgit/python-playground | /calculator.py | 186 | 3.859375 | 4 | #Write a calculator program in python
def multiply(a,b):
return a*b
def add(a,b):
return a+b
def subtract(a,b):
return a-b
def divide(a,b):
return a/b
x = multiply(2,3)
print x |
448f30ef7f1cd54975f2a7b4ccb106dab702dd1d | almensu/dfy_python_essential | /11_class.py | 1,079 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# class Dog():
# def __init__(self, name, age, weight=10):
# self.name = name
# self.age = age
# self.weight = weight
#
# def eat_bone(self):
# print(self.name + ' eatting bone!')
#
# def bark(self):
# print(self.name + ' is barking!')
#
# ... |
e42748ed030e92c694657695e48fdc29a3dafed8 | ConnorHoughton97/selections | /Water_Temp.py | 337 | 4.34375 | 4 | #Connor Houghton
#30/09/14
#telling the user whether ater is frozen, boiling or neither
water_temp = int(input("please enter the temperature of the water: "))
if water_temp >= 100:
print ("The water is boiling.")
elif water_temp <= 0:
print("The water is frozen.")
else:
print("The water is neit... |
b4883faf720d9aef7fa7ee4cb9f86b2e067d9481 | sanugrah007/Artificial-Intelligence | /A_star algorithm.py | 4,330 | 3.53125 | 4 | class Graph:
def __init__(self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
if not directed:
self.make_undirected()
def make_undirected(self):
for a in list(self.graph_dict.keys()):
for (b, dist) in ... |
7e518f4d7287cc5f6950943c225ca6b0dadeaf4c | ranbogmord/aoc2017 | /day4/first.py | 709 | 4 | 4 | # Read input data from file
with open("day4/input.txt", "r") as f:
# Read lines into list
lines = f.readlines()
# Create a counter to store the number of correct passphrases
correct = 0
# Go through each passphrase
for line in lines:
# Split the phrase into a list of words
input_arr = line.strip().spli... |
a6a0cdaafb8751aafa0b9245272afd255c076a3d | ruhee/advent-of-code-2018 | /05/solution.py | 1,029 | 3.65625 | 4 | #! /usr/local/bin/python3
def react(input):
for idx, char in enumerate(input):
if idx < len(input) - 1: # whoops
next_char = input[idx+1]
if (char.lower() == next_char.lower() and
char != next_char):
return input[:idx] + input[(idx+2):]
return input
with open('input.txt', 'r') as i... |
34daa296066002315e213aa6dacb290a3a6d82a0 | dadams39/Leilani_python | /example.py | 317 | 3.84375 | 4 | #! /usr/bin/env python3
import sys
def entry():
my_list = sys.argv
return my_list[-1]
def main():
print("Leilani is {} years old".format(12))
print(entry())
#loop entry 16 times
last_word = entry()
for x in enumerate(last_word):
print(x)
if __name__ == "__main__":
main()
|
bf64af691cff4ef9ed7044f92c6ce3509445181b | dharmesh-coder/Full-Coding | /Hackerrank/Utopian Tree.py | 285 | 3.9375 | 4 | def height1(n):
a=0
height=0
while (a<=n):
if (a%2==0):
height+=1
else:
height=height*2
a+=1
return height
n=int(input())
arr=[]
for i in range(n):
a=int(input())
arr.append(a)
for i in arr:
print(height1(i)) |
b08dfb7293f608344ff54d1c8a8d8307d8d58b99 | dharmesh-coder/Full-Coding | /Codevita/Round 2/C.py | 325 | 3.625 | 4 | def countWays(n) :
res = [0] * (n + 2)
res[0] = 1
res[1] = 1
res[2] = 2
for i in range(3, n + 1) :
res[i] = res[i - 1] + res[i - 2] + res[i - 3]
return res[n]
t=int(input())
ans=[]
for i in range(t):
x=int(input())
ans.append(countWays(x+1))
for i in ans:
print(i,end=... |
6ffb17fb047414e9807ac5eb19ce2ce32e8b471b | dharmesh-coder/Full-Coding | /Codechef/January Cookoff/primetuple.py | 490 | 3.859375 | 4 | import math
def isPrime(num):
if(num==1):
return False
if(num==2):
return True
if(num%2==0):
return False
i = 3
while(i<math.sqrt(num)+1):
if num%i==0:
return False
i += 2
return True
t=int(input())
ans=[]
for i in range(t):
n=int(input... |
388d4808ab700e2b530f0a07675412d44867374f | Protuhj/videotato | /myutil.py | 481 | 3.765625 | 4 | # Reads one of the input files (channels.txt, playlists.txt, etc.) and appends the valid entries to the given list.
# Lines that start with '#' are comments, and are ignored.
def readInputFile( filename, listToAppendTo ):
with open( filename, "r" ) as ins:
for line in ins:
stripped = line.strip(... |
3b473b276485f302a826621a6c61ac6b20e66aa9 | WhiteLie1/PycharmProjects | /alex_python/day4/生成器并行.py | 1,347 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/25 19:13
# @Author : chenxin
# @Site :
# @File : 生成器并行.py
# @Software: PyCharm
'''
import time
def consumer(name):
print('%s 准备吃包子了!'%name)
while True:
baozi = yield
print('包子[%s]来了,被[%s]吃了'%(baozi,name))
c=consumer('chenxin')
c.__... |
a9dd7f6698194127322ccb3430435f8bb70ce01f | WhiteLie1/PycharmProjects | /alex_python/day6/继承实例.py | 1,774 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/8 19:58
# @Author : chenxin
# @Site :
# @File : 继承实例.py
# @Software: PyCharm
class SchoolMember(object):
members = 0; #初始学校人数为0
def __init__(self,name,age):
self.name = name
self.age = age
def tell(self):
pass
def... |
2d5ac84f90e0d83ac071d5071e33332df0e3502e | WhiteLie1/PycharmProjects | /alex_python/day3/day3_25递归.py | 1,122 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/4 17:04
# @Author : chenxin
# @Site :
# @File : day3_25递归.py
# @Software: PyCharm
#print('hellp')
# def calc(n):
# print(n)
# return calc(n+1)
# calc(0) #耗光内存,陷入死循环 999次
#递归特性:
# 必须有一个明确的结束条件
# 每次进入更深一层递归的时候,问题规模比上次递归都应有所减少
# 递归效率不高,递归层次过多会导致栈溢出
'... |
16fb24e6334e2116d5f9903d327f3b49cfbaa9bf | dlech/lu-fall-2019-python-class | /class-6/01-guess.py | 4,112 | 4.46875 | 4 | # File: guess.py
# Author: David Lechner
# Date: 11/21/2019
'''A guessing game.
This is the classic game where someone thinks of a secret number and someone
else tries to guess it. In this case, the computer thinks of the number and we
(the user) have to guess what it is.
'''
# LEARN: Python has a standard module fo... |
bdea60d2258ec483abf683e87f496dcdbe2176b4 | dlech/lu-fall-2019-python-class | /class-3/demo2.py | 3,616 | 4.78125 | 5 | # File: demo2.py
# Author: David Lechner
# Date: 11/5/2019
'''Demonstrate how coordinate system works in turtle graphics.
This is just for demonstrating how the coordinate system works in turtle
graphics. We don't need to understand how all of the parts of the program
work yet.
Run the program. Click anywhere in the... |
ed1ad13442cde6d47dba6ea1ac955ad157929c16 | shreethi29/Python-for-Everybody-Specialization | /assignment6.py | 375 | 4.1875 | 4 | largest = -1
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n=float(num)
except:
print("Invalid input")
if smallest is None:
smallest=n
elif n>largest:
largest=n
elif n<smallest:
smallest=n
print("Maxi... |
efe0bf6327ec641c93d8c9c4f0a99a0a022700b4 | jhonielviloria/PythonChallenges | /leetcode/stringToInteger.py | 2,130 | 3.921875 | 4 | # Implement atoi which converts a string to an integer.
# The function first discards as many whitespace characters as necessary
# until the first non-whitespace character is found. Then, starting from
# this character, takes an optional initial plus or minus sign followed
# by as many numerical chars as possible, and ... |
d576dacbe017b3538162afd885bfa75a7e1023ca | ErylKennVictorino/Open_Source_Programming_in_Python | /Assignment 02.py | 1,430 | 3.90625 | 4 | """
AUTHOR: ERYL KENN VICTORINO
PURPOSE: ASSIGNMENT 2
from "Open Source Programming in Python" Course
with Professor Ivy Liu
MOD DATE: 3/24/2019
"""
"""
1. An investor’s stock portfolio consists of four Exchange Traded Funds (SPY,
QQQ, EEM, and VXX). Write a program that... |
7467d36f1cf428c0ec0c313d0dfad8079cb862bf | fcostin/cmepy | /cmepy/models/catalytic_reaction.py | 5,566 | 3.609375 | 4 | """
A simple catalytic reaction example.
Consider the following 'catalytic' reaction system:
A --k_1--> B
B --k_2--> C
B + D --k_3--> B + E
Here, the species B acts as a catalyst for the third
reaction. The rate constants are
k_1 = 1, k_2 = 1000, k_3 = 100;
while the initial species counts are
... |
df57072ac0eb017520e2c105342af62d6ce66fe2 | runnanzhou/RepositoryZhou | /python/calendar.py | 1,501 | 3.828125 | 4 | def intro():
print("This program reports information about DNA")
print("nucleotide sequences that may encode proteins.")
def region_name(i,words,region_list):
if i % 2 ==0:
region_list.append(words)
return region_list
def nucleotides(i,words,nuc_list):
if i%2==1:
nuc_list.append(wo... |
58b012754fcefb038babba917b0e1bf1447135bf | zhanshi06/DataStructure | /Project_1/Problem_1.py | 1,640 | 3.734375 | 4 |
import collections
class LRU_Cache(object):
def __init__(self, capacity):
# Initialize class variables
self.capacity = capacity
if capacity == 0:
print("Warning please provice the capacity larger than 0")
self.cache = collections.OrderedDict()
def get(self, key):
... |
fbf00374688203f1feacec0636e2f1d385439be0 | zhanshi06/DataStructure | /Project_1/Problem_2.py | 1,375 | 4.375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffi... |
59326a273589f2829374351e0f2f9e3b451f1846 | anglewf/fizzbuzz_2018_s02 | /fizzbuzz.py | 381 | 3.96875 | 4 | def fizzbuzz():
answer = ""
for num in range(100):
if(num % 3 == 0 and num % 5 == 0):
answer + "FizzBuzz"
print(num,"FizzBuzz")
elif num % 3 == 0:
answer + "Fizz"
print (num,"Fizz")
elif num % 5 == 0:
print (num,"Buzz")
answer + "Buzz"
return answer
def main():
answer = fizzb... |
20b79119128b9e504e4b9049cfba54c307e1849b | tom-sherman/alphabear-solver | /hashdict.py | 1,902 | 3.8125 | 4 | __author__ = "Tom Sherman"
"""
This script reads from a file (dictionary.txt), generates a hashmap (dict)
and dumps it to a json file. Only needs to be run once, unless the
dictionary changes.
It's quite slow, but once completed lookup of valid matches is blazing
fast.
"""
from collections import... |
690d98d16b3a212feadc6ce49e744127a8caad4f | olystrel/python-first-homeworks | /lesson02/home_work/hw02_easy.py | 2,109 | 3.953125 | 4 | # Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
print("Решение первого... |
a1d0d5748acf67388b2b12ecfbe7339a0a0f957c | 0xphk/python_tutorial1 | /04_variables.py | 1,583 | 4.09375 | 4 | # variables
var1 = 1
#var2 = input("enter 2nd input: ")
# var as specific input data type
#var3 = int(input("enter 3rd input: "))
# store results
result = eval('9 + 2')
# arithmetic
var1 = 22
var2 = 22 + 3
var3 = (22 - 2) * 3
# naming conventions
name = "James"
# underscore preferred over camelCase in PEP8
full_nam... |
f6d613e01c885dd622f78cbe8dbd38d54111a5b4 | 0xphk/python_tutorial1 | /13_functions.py | 678 | 3.859375 | 4 | # basic function with arguments
def greeter(name, age=-1):
print(f'Hello {name}')
if not age < 0:
print(f'Age is: {age}')
greeter('John', 18)
greeter('James')
# return values from functions
def isAdult(age):
if age >= 18:
print('Adult:',end=' ')
return True
print(isAdult(21))
# ... |
8456392830bb561c6f4156b270e445f10b0e67c4 | 0xphk/python_tutorial1 | /07_if_conditions_1.py | 241 | 4.28125 | 4 | age = int(input("age: "))
if age == 18:
print("age is 18!")
elif age < 21 > 18:
print("age over 18 but not yet 21!")
elif age == 21:
print("age is 21!")
elif age >= 21:
print("age over 21!")
else:
print("age under 18!")
|
96b845444f6ed66e278e5c58914c03ea840c6d1f | 0xphk/python_tutorial1 | /10_for_loops.py | 1,400 | 3.578125 | 4 | # define list
list = [1, 2, 5, 7, 9]
print('# increment through list using "for item in list:"')
print("list:", list)
for val in list:
print(val)
print("# use range(1,10) start stop")
for int in range(0, 10):
print(int)
print("# use range(1,10,2) start stop step")
for int in range(1, 10, 2):
print(int)
#... |
aa47bbac671b2fb72c5fc7c89b67f897925bdc02 | fffelix-jan/Python-Tips | /7-list-comprehensions.py | 590 | 3.625 | 4 | people = ["Olive", "Otto", "Olympia", "Otis", "Todd", "Weird Tom", "Shapeshifter"]
odd_squad_agents = [e for e in people if e[0].upper() == "O"] # filter out only the names that start with "O"
the_exact_same_agents = [e for e in odd_squad_agents] # or just copy everything without checking anything
print(odd_squad... |
32e95aacf766b380faaa2b8dc64d13b7bb062f24 | fffelix-jan/Python-Tips | /3a-map-those-ints.py | 239 | 4.15625 | 4 | print("Enter space-separated integers:")
my_ints = list(map(int, input().split())) # collect the input, split it into a list of strings, and then turn all the strings into ints
print("I turned it into a list of integers!")
print(my_ints) |
95b7a03682d6447eafd7ceedfc1a7aaa5be4e5ea | ebbitten/ScratchEtc | /538/ballColoring.py | 655 | 3.875 | 4 | import random
def outerLoop(trials):
total = 0
for i in range(trials):
total += ballRun()
avg = total/trials
print("The average number per trial was ",avg)
def ballRun():
balls = ['b','g','r','y']
index = [0,1,2,3]
ballsSame = False
counter = 0
while not ballsSame:
... |
1b65a804d2f938ea26c01c3fe146f7678df29b96 | ebbitten/ScratchEtc | /CodeFights/interview prep/firstDuplicate.py | 224 | 3.765625 | 4 | def firstDuplicate(a):
seen = []
for i, ele in enumerate(a):
if ele in seen:
return(i)
else:
seen.append(ele)
return(-1)
a = [2, 3, 3, 1, 5, 2]
print(firstDuplicate(a))
|
66f8fa77e7440480efa0aaac2235eb338fee043b | ebbitten/ScratchEtc | /Challenges/HutchesSepList.py | 1,867 | 3.578125 | 4 | import bisect
def answer(heights):
totalWater=0
#Populate walls list by checking to see if each hutch would trap water
numHutches=len(heights)
#really might want to switch to dicts, or even a list of dicts
lWallH=[-1] #populating so that max can be evaluated
lWallP=[-1]
rWallH=[-1] #populat... |
fd29919e8d045413a4ad740a0d1885b1834d0837 | elianajn/MA201_Diffie_Hellman | /dh.py | 1,682 | 3.875 | 4 | import math
import decimal
import random
import time
import os
#Thix is the Whole Algorithm
def compute_shared(g,p,k):
return (g ** k ) % p
def compute_random():
return random.randint(0,1000)
def sophie_germain(p,n):
for i in range(n):
p = (2*p) + 1
return p
p = sophie_germain(23,15) #computes a large prime nu... |
ce16118181aab9a8fcdced61655c4ba6832640bb | Banehowl/MarchDailyCode2021 | /DailyCode03132021.py | 601 | 3.640625 | 4 | # ------------------------------------------------
# # Daily Code 03/13/2021
# "Buggy Code (Park 2)" Lesson from edabit.com
# Coded by: Banehowl
# ------------------------------------------------
# Fix the code in the code tab to pass this challenge (only syntax errors)
# max_num(3, 7) -> 7
# max_num(-1,... |
a0f8e49e3d3715af8b340129af004db70287a8a3 | Banehowl/MarchDailyCode2021 | /DailyCode03212021.py | 727 | 3.890625 | 4 | # -----------------------------------------------------------------
# # Daily Code 03/21/2021
# "Sum of List Less Than 100 List Remix" Lesson from edabit.com
# Coded by: Banehowl
# -----------------------------------------------------------------
# Given a list of numberes, return True if the sum of the valu... |
5e822c7722c54e9fec15d8ebd6c55ddbf6dc1dc2 | Banehowl/MarchDailyCode2021 | /DailyCode03262021.py | 731 | 4 | 4 | # -----------------------------------------
# # Daily Code 03/26/2021
# "Moving House" Lesson from edabit.com
# Coded by: Banehowl
# -----------------------------------------
# I'd like to calculate how long on average I've lived in the same house.
# Given a person's age and the number of times they've mo... |
333b3c93771a0bbeaaa61c3da7d0cd83957965ae | JohnHoan/AI-HCMUT | /n_puzzle-dfs/action.py | 6,600 | 3.6875 | 4 |
import time
import sys
from math import sqrt
from collections import deque
from heapq import heappush, heappop, heapify
""" setting keys for a* heuristic comparisons """
action_dict = {'Up':1, 'Down':2, 'Left':3, 'Right':4}
class NPuzzle(object):
""" Low-level physical configuration of N-Puzzle tiles.... |
134fdecea1874b3942c256969eb12e59f878355a | SumedhKarnik/basics | /python/sorting/selection.py | 681 | 3.921875 | 4 | #!/usr/bin/python3
import random
def select_sort(lst):
for i in range(len(lst)):
min_val = lst[i]
min_idx = i
for j in range(i+1, len(lst)):
if min_val <= lst[j]:
continue
min_val = lst[j]
min_idx = j
lst[i], lst[min_idx] = ls... |
c250b9affcaf7ebef8e7f7ae9b0c54ab9904dbb0 | Tsukumo3/Atcoder | /algorithm/AtcoderTags/Searching/BinarySearch.py | 3,785 | 3.796875 | 4 | '''
二分探索アルゴリズム
単純な線形探索は O(n)
二分探索なら 0(log n)
'''
# *************************************
'''
1. ソート済みの配列の中から目的のものを探す
数あるときはどれになるかわからない。
'''
"""
a = [1, 14, 32, 51, 51, 51, 288, 299, 500, 910, 10000, 10930]
def binary_search(key):
'''
目的の値 key の index を返すようにする。ない場合は -1
'''
left = 0
right = len(... |
75ad463c944ef3ebe5dcadec03601e1f9dc3b924 | Tsukumo3/Atcoder | /ABC/149/C.py | 410 | 4.03125 | 4 | import math
def isPrime(n):
if n == 2:
return True
if n % 2 == 0:
return False
# nの平方根まで計算する
m = math.floor(math.sqrt(n)) + 1
for p in range(3, m, 2):
if n % p == 0:
return False
return True
if __name__ == '__main__':
X = int(input())
while(True):
if isPrime(X):
... |
909b8c2fc649d8c93e1f02cc2ce3b4f73ee794e9 | Tsukumo3/Atcoder | /ABC/142/a.py | 213 | 3.515625 | 4 | n = int(input())
if n == 1:
print('{0:.10f}'.format(1))
else:
a = n%2
if a == 1:
amari = ((n-1)/2 +1)/n
print('{0:.10f}'.format(amari))
else:
print('{0:.10f}'.format(0.5))
|
7818958667aa2bbb31266a3af09a522d4acfa5f5 | Tsukumo3/Atcoder | /ABC/006/py/A.py | 92 | 3.984375 | 4 | n = int(input())
if n%3 == 0 or "3" in list(str(n)):
print("YES")
else:
print("NO")
|
59083a51dfc42d9955dbfb65747e12f7bd9756a5 | Tsukumo3/Atcoder | /ABC/126/D.py | 766 | 3.59375 | 4 | class Node:
def __init__(self,n):
self.name = n
self.parents = []
self.children = []
self.color = 0
def main():
N = int(input())
lines = [list(map(int, input().split())) for i in range(N-1)]
nodes = [Node(i) for i in range(1,N+1)]
for line in lines:
pare... |
3d22c6dd8194a0601d6f40d49d33cf4b829eaf98 | chris-forbes/advent-2020 | /advent/days.py | 14,852 | 3.578125 | 4 | from typing import List, Union, Tuple
from advent.model.password_policy import PasswordPolicy
from advent.model.passport import Passport
from math import ceil
import re
def find_matching_sum_two(data_list: List[int], expected: int) -> Union[int, int]:
"""
Find which elements when summed together match the expected ... |
fa304481766f4230693bc98738e7b6edb59bbdce | RogShotz/Project-Euler | /python/p005.py | 746 | 3.953125 | 4 | import time
t0 = time.time()
divcap = 20 # how many can it evenly divide up to
# 12, 15 is redundant because higher multiple
check = [11, 13, 14, 16, 17, 18, 19,
20] # compile here instead of using range which recompiles to check for array every time
found = False
x = 0
# TODO: implement automatic check po... |
fde1d2f46173f4328b7f6899ae726e64d1c5a060 | Syeop-28/Snake | /Snake/Snake.py | 5,962 | 3.765625 | 4 | import turtle
import random
import time
retraso=0.1
nombre="Edgar"
segments = []
# score
score = 0
high_score = 0
comida=False
#Atributos de la ventana de juego
win = turtle.Screen()
win.title(nombre+"'s snake game")
win.bgcolor("black")
win.setup(width=600,height=600)
win.tracer(0)
# Cabeza de la v... |
44a4b09347debc9cbc1631a575eb5ea6b39b71c5 | Puzzle928/python_study | /prec.py | 118 | 3.59375 | 4 | b = input("정사각형 한변의 길이는?")
area = float(b) ** 2
print('정사각형의 넓이: {}'.format(area))
|
54e5477497f3ad2c5b54a98343b3a8638796b3c9 | phenderson123/pyt6 | /guess.py | 427 | 4 | 4 | import random
num = random.randint(1, 20)
flag = True
guess = 0
print('Take a guess at the number 1-20 :' , end = '')
while flag == True :
guess = input()
if not guess.isdigit()
print('Invalid! Please enter only 1-20')
break
elif int(guess) < num:
print('Too low dude:', end ='')
elif int(guess) >... |
630f4156d678a77abad59cfa5f32d2f0789a1116 | Ninjeneer/ioi-challenges | /niveau3/deblocage/inversion_dictionnaire/inv_dict.py | 220 | 3.546875 | 4 | nbMots = int(input())
dictionnaire = []
for i in range(nbMots):
mots = input().split()
dictionnaire.append((mots[1], mots[0]))
dictionnaire.sort()
for entry in dictionnaire:
print(entry[0] + " " + entry[1])
|
47fdc1b6e247ba8908f0d6c5a9f782eaf639d5e3 | nax1016cs/python | /0516097 HW9-1.py | 788 | 3.59375 | 4 | file_name= input('enter the file name:') #紀錄要開的檔案名字
f = open(file_name, 'r') #讀檔
count=0 #設定一開始的計算次數為0
for line in f:
if line.startswith('Subject: [sakai] svn commit:'): #找Subject: [sakai] svn commit:開頭的字串
line.strip() ... |
9f088916bc572cb613a0f8e574e5826d16d600ff | crazyboy9103/Data_Structures_in_Python | /LinkedList.py | 3,920 | 4.3125 | 4 | '''
Linked List : A linear data structure that holds data linked by pointers.
Pros over arrays
1) Dynamic size
2) Ease of insertion/deletion
Cons
1) Access takes O(n) time since we have to start at the first node every time
2) Extra memory space is required for a pointer
3) No reference to each element
The linked l... |
110b54bd26c9ff8f23a720144fb5f589e44b4ead | birdycoder/TNN | /Bp.py | 3,216 | 3.625 | 4 | import random
import numpy as np
class Network(object):
def __init__(self, size):
'''
param size: type:list store the number of every layer's neuron
'''
self.num_layers = len(size)
self.size = size
#Random seed
np.random.seed(1)
#bias initialization
self.bias = [np.random.randn(y,1) for y in siz... |
0ff46aa541476ec73d8dbe2de099a11048d0f560 | SS1908/30_days_of_python | /Day 16/properties_of_match.py | 342 | 4.21875 | 4 | """"
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function.
.group() returns the part of the string where there was a match.
"""
import re
str = "The train in Spain"
x = re.search("train",str)
print(x.span())
print(x.str... |
d62363750fa06239f769f4490b7c8dea0eeb06eb | SS1908/30_days_of_python | /Day 12/LIst_comprehension.py | 466 | 4.34375 | 4 | """
List Comprehension is defined as an elegant way to define, create a list in Python.
It consists of brackets that contains an expression followed by for clause.
SIGNATURE:
[ expression 'for' item 'in' list 'if' condition]
"""
letters = []
for letter in 'Python':
letters.ap... |
c07614f370a9f5b625593569cf89f2e98f15e01a | SS1908/30_days_of_python | /Day 17/type_of_variable_in_class.py | 940 | 4.34375 | 4 | """
we have a two type of variable in class :- 1) instance variable
2)class variable
instance variable is changes object to object.
class variable is same for all the instance/object of the class.
"""
class car:
#this is a class variable
... |
fd387c1326577773ffd0160714e64c7d6a84386d | SS1908/30_days_of_python | /Day 8/Default_parameter.py | 197 | 3.578125 | 4 | #if we don't pass an argument function will take default argument
def function1(name="USER"):
print("hello "+name)
function1("sagar")
function1("nayan")
function1()
function1("dallu") |
1638c972efd1532d8f8dd7d2adb386f67163fba9 | SS1908/30_days_of_python | /Day 4/Add_item_in_list.py | 184 | 3.8125 | 4 | #we can use append() method or insert() method
name = ["sagar","meet","jt","nayan","dallu","divlo"]
name.append("pankti")
print(name)
print()
name.insert(1,"jay")
print(name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.