blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c7f05f29fa4e84594a2e11a8937b527417e8ecd9 | cris/ruby-quiz-in-python | /src/rock_paper_scissors.py | 3,738 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
class Player(object):
players = []
@classmethod
def inherited(cls, player):
cls.players.append(player)
@classmethod
def each_pair(cls):
for i in xrange(len(cls.players)-1):
for j in xrange(i+1, len(cls.pla... |
905a6cfbf0fd34b3183ddfd0ad77731c1ccdf541 | dykim822/Python | /ch04/insert1.py | 402 | 3.828125 | 4 | a = [1, 2, 3]
a.insert(0, 4) # 인덱스 0번째에 4를 대입
print(a)
a.insert(2, 2)
a.insert(2, 5)
print(a)
a.remove(2) # 첫번째 2인 값 1개을 삭제
# del은 해당 인덱스 값을 삭제/ remove는 해당 값을 삭제
print(a)
print(a.pop()) # 마지막 데이터를 끄집어서 출력하고 삭제
print(a)
print(a.pop(0)) # 인덱스 0번째 데이터를 출력하고 삭제
print(a) |
884d7958db9768889cb9855cdd7ebfe58afe1a3d | yaricom/neat-libraries-compared | /src/pole/cart_pole.py | 5,948 | 3.71875 | 4 | #
# This is implementation of cart-pole apparatus simulation based on the Newton laws
# which use Euler's method for numerical approximation the equations on motion.
#
import math
import random
#
# The constants defining physics of cart-pole apparatus
#
GRAVITY = 9.8 # m/s^2
MASSCART = 1.0 # kg
MASSPOLE = 0.5 # kg
TO... |
f8c4f473d11a881e44e6c0f3502b2eb9cd96af7a | OCCOHOCOREX/HuangXinren-Portfolio | /Weekly Tasks/Week2/HuangXinren-Week2-Task1.py | 150 | 4.09375 | 4 | # Task 1
multiple_list = []
number = [10, 35, 3]
for i in range(10, 36):
if i % 3 == 0:
multiple_list.append(i)
print(multiple_list) |
d160ed0d02a145aa82fce602cb6a3b35951df8e3 | M0G1/learning_python | /python_feachure/key_words_build_in_func.py | 1,297 | 3.609375 | 4 | import numpy as np
def enumeration():
letters = "абвгдеёжзийклмнопрстуфхцчшщьыъэюя"
let_enum = enumerate(letters, start=1)
print(*list(let_enum), sep="\n")
def compile_():
str_commands = \
"""
x = 1
z = 2
print(f"{x} + {z} = {x + z}")
"""
print("We will execute code:")
print... |
19cfebc702f598e1c4c93963ba4024e62681b362 | organization0012/PythonRepo | /File/iterate_directory.py | 430 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
if __name__ == '__main__':
dir = "/tmp"
for fname in os.listdir(dir):
# print(fname)
path = os.path.join(dir, fname)
if os.path.isdir(path):
print("%s is a directory" % path)
elif os.path.isfile(path):
... |
5e4d61d333bfc6980912097483cac08d3e422204 | Harshj16/Project-Euler-Problems | /Project-Euler-1.py | 395 | 4.15625 | 4 | #Project Euler No.1
#If we list all the natural numbers below 10 that are multiples of 3 or 5
#we get 3, 5, 6 and 9.
#The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
#definig natural number
num = int(input("Enter number = "))
add = 0
for iterate in range(1,num):
... |
99639910be9162f95ef96373d012e6e3d3d4eb32 | DukhDmytro/py_cart | /cart.py | 1,053 | 3.984375 | 4 | """The csv module implements classes to read and write tabular data in CSV format"""
import csv
class Product:
"""Product class"""
def __init__(self, name, price, qty):
self.name = name
self.price = float(price)
self.qty = float(qty)
def get_total_price(self):
"""return to... |
29701b8d0784ef60e0a5aa1e8a358411ee45d471 | techduggu/DataStructuresPlayGround | /Trees/first-common-ancestor.py | 2,646 | 3.65625 | 4 | import sys
# sys.stdin = open('Trees/input.txt', 'r')
# sys.stdout = open('Trees/output.txt', 'w')
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
... |
daa06604cd81410c46d2d598789b9c18c30ac110 | Puthiaraj1/PythonBasicPrograms | /DictionariesSets/sets.py | 1,654 | 4.1875 | 4 | # farm_animals = {"sheep","cow","hen"}
# print(farm_animals)
#
# for animal in farm_animals:
# print(animal)
#
# print("-" * 30)
# wild_animal = set(["lion", "tiger", "panther", "wolf"])
# print(wild_animal)
#
# for animal in wild_animal:
# print(animal)
#
# farm_animals.add("horse")
# wild_animal.add("horse")
... |
2341f67f8a2271bcea2646d633dca4bd4d224f26 | kamal0072/classes | /class/class.py | 531 | 3.53125 | 4 | # class MyScool():
# myname='kamal'
# def __init__(self):
# print('hello Constructor')
# def Show(self):
# print('Class Methods')
# x=MyScool()
# x.Show()
# print(x.myname)
class School():
def __init__(self,p):
self.name='kamal'
self.place='delhi'
def studnt(self)... |
b8937df1199f1bd3cc8a7608618ff2a986ddede7 | MisaelAugusto/computer-science | /programming-laboratory-I/5guh/tabela.py | 204 | 3.875 | 4 | # coding: utf-8
# Aluno: Misael Augusto
# Matrícula: 117110525
# Problema: Tabela de Quadrados
X = int(raw_input())
Y = int(raw_input())
if X > Y:
print "---"
else:
for i in range(X, Y + 1):
print i, i**2
|
debfcc855154ac7dc1ef52eb6a24df322bd06f2d | code4love/dev | /Python/demos/practice/条件和循环语句.py | 358 | 3.890625 | 4 | #! /usr/bin/python
#条件和循环语句
x=int(input("Please enter an integer:"))
if x<0:
x=0
print ("Negative changed to zero")
elif x==0:
print ("Zero")
else:
print ("More")
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print (x, len(x))
#知识点:
# * 条件和循环语句
# * 如何得到控制台输入
|
fc2405b7cf5568ff8656cf43bbb1fc5c435a7eec | anushanav/python_logical_solutions | /guess_game.py | 423 | 4.125 | 4 | # Guessing game between 1 to 8 in 5 chances
import random
def guess_number(guess):
x = random.randint(1,8)
chances =0
while chances <4:
if guess == x:
print ("You guessed it correct.Congo!!")
break
else :
print ("Wrong Guess.Sorry")
chances += 1
... |
30b7b5e5c1879ef18f67620c23f24917e8c48463 | rodriguezofelia/hb-homework | /accounting-scripts/melon_info.py | 431 | 3.71875 | 4 | """Print out all the melons in our inventory."""
from melons import melons
def print_all_melons(melons):
"""Print each melon with corresponding attribute information."""
for melon, characteristics in melons.items():
print(melon.upper())
for characteristic, value in characteristics.items():
... |
7a5f512612b4b52d5cda3b5f2fffb0e9b2599f5a | Johnxjp/aoc2019 | /python/helper.py | 946 | 3.734375 | 4 | from typing import Sequence
def load(file: str) -> Sequence[int]:
"""Loads a list of numbers each on a new line"""
data = []
with open(file) as f:
for line in f:
data.append(int(line.strip()))
return data
def loadv2(file: str) -> Sequence[int]:
"""Loads a list of numbers sepa... |
aac178e66edebda8f34a7e3a55f1a7cbf11e30b9 | akshatmawasthi/python | /nested.py | 439 | 4.0625 | 4 | #!/usr/bin/python
# Try the exercises below
# Given a tic-tac-toe board of 3x3, print every position
# Create a program where every person meets the other
#persons = [ “John”, “Marissa”, “Pete”, “Dayton” ]
xax = [1,2,3]
yax = [1,2,3]
for x in xax:
for y in yax:
print(x, y)
persons = ["John", "Marissa"... |
33c3ff8bce601536ba903bc383621b2a45760555 | ilhnctn/flask-rest-example | /apps/factorial/service.py | 330 | 3.546875 | 4 |
class FactorialService:
def get_factorial_of_number(self, target: int) -> int:
if not isinstance(target, int):
raise Exception(f"Unsupported input type. int expected, got {type(target)}")
result: int = 1
for mid in range(1, target + 1):
result *= mid
retu... |
177b9e9ccc553ddac6f4fe55f01c5bc533083d0d | dongxutian/test2 | /function_practice.py | 667 | 4.09375 | 4 | def f(*args):
for x in args:
print(x)
f(5)
f("I am here",9,5)
def summation(*nums):
count=0
for x in nums:
count+=x
return count
y=summation(10,20)
print(y)
#######We can specify default values in our functions\n by creating keywaord arguments
def nums(**kwargs):
for x,y in kwa... |
b4d77d0c762e76cbb55062c37630f93056379ae4 | Yufeng-L/myLeetCode | /1103-distributecandies.py | 604 | 3.6875 | 4 | # 依次分糖果
# hard code 对位置进行遍历,若最后一次candies数量小于0,返回并修复正确数量
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
# length = num_people
res = num_people*[0]
count = 1
while (candies != 0):
for i in range(num_people):
res[i] =... |
66e1c73d83323e8ad3e3be0df387940c08b12e09 | ruifengli-cs/leetcode | /BFS/863. All Nodes Distance K in Binary Tree.py | 2,519 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# APP1: add parent link, then do BFS
# Time: O(n) Space: O(n)
# def distanceK(self, root: TreeNode, target: TreeNode, K: int)... |
664c13a01b48957caea12d574b7384317410744c | masande-99/email-sending-app | /main.py | 1,750 | 3.6875 | 4 | from tkinter import *
def send_email():
root = Tk()
root.title("Sending Emails")
root.geometry("1000x600")
def my_function():
import smtplib
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
sender_email = txt1.get()
receiver_email = txt2.get()
... |
2d122a979961bb7bdafbb1fde571f5c7d5f8a87c | DreenTS/skillbox_yurikov | /lesson_011/01_shapes.py | 1,629 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import simple_draw as sd
# На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику,
# которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д.
#
# Функция рисования должна принимать параметры
# - точка начала рисования
# - угол наклона
... |
2965467f356c1722120cd5e2d838a10056e4e8a8 | eugennix/python | /Coursera/23_flags.py | 236 | 3.71875 | 4 | n = int(input())
print(' '.join(['+___' for i in range(1, n+1)]))
print(' '.join([('|' + str(i) + ' /') for i in range(1, n+1)]))
print(' '.join(['|__\\' for i in range(1, n+1)]))
print(' '.join(['| ' for i in range(1, n+1)]))
|
d618213f4b802a1f45bdd60b929db96e44cb3fd8 | Prashant4M/Project-Euler-Solutions | /Problem_1.py | 88 | 3.609375 | 4 | sum=0
for i in range(1,1000):
if((i%3==0)|(i%5==0)):
sum+=i
print(sum)
|
b378dd1387aaa1d61a7b43e4d89c7aed0ba47589 | thc2125/csclassifier | /corpus_utils.py | 3,824 | 3.53125 | 4 | import random
from math import sqrt
import numpy as np
from alphabet_detector import AlphabetDetector
from sklearn.preprocessing import label_binarize
import utils
ad = AlphabetDetector()
def np_idx_conversion(sentences, slabels, maxsentlen, maxwordlen, char2idx, idx2label, char_count=None):
# Convert the sen... |
f728cfdc95df860a04d8a5d202fc24f6901d111c | sampada22/sqlite3 | /inserting_into_table.py | 1,798 | 3.953125 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
"""create connection to the SQLite database specified by db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
... |
0889e680f055cdfc693ac9fe8871922b47567d2a | Wintus/MyPythonCodes | /swap.py | 1,057 | 4.375 | 4 | # Python 3.4.0
'''Swap the values of a and b without any extra variables'''
# use tuple in assignment (basic version)
a, b = 0, 1
print("a: {}, b: {}".format(a, b))
print("Swapping")
a, b = b, a
print("a: {}, b: {}".format(a, b))
print()
# with closure (it seems same with above one essentially)
def main():
'''us... |
993b68ef208e8fdb034eece00af437e62620701d | caojohnny/dupe | /dupe.py | 601 | 3.90625 | 4 | import sys
argv = sys.argv
argvLen = len(argv)
if argvLen < 2:
print("No file name provided")
exit(1)
fileName = argv[1]
print("Parsing file " + fileName)
file = open(fileName, "r")
words = []
lineNumber = 0
while True:
line = file.readline()
if not line:
break
lineNumber += 1
line ... |
19692a8c41141698461e1ffc25ce89d73795645c | sudheendra02/competetive_programming | /week1/day1/highest_multiplication.py | 250 | 3.65625 | 4 | a=[1,2,3,4,5]
if (len(a)>=3):
x=max(a)
y=x
a.remove(x)
x=x*max(a)
a.remove(max(a))
x=x*max(a)
if (len(a)>=2):
y=y*min(a)
a.remove(min(a))
y=y*min(a)
a.remove(min(a))
print(max(x,y))
else:
print(x)
else:
print("not enough values") |
3b92a240cf4996dce16fd4a57d090ceec15623a5 | castjosem/customer-search | /single_file_project.py | 4,872 | 3.90625 | 4 | """
Let’s say we have some customer records in a text file (customers.txt, see below) – one customer per line,
JSON-encoded. We want to invite any customer within 100km of our Dublin office (GPS coordinates 53.3381985, -6.2592576)
for some food and drinks on us.
Write a program that will read the full list of custo... |
1a18c3b99223fadd4093d5fc95a4662b2a3c748e | jackie-mcaninch/Hash-Code-2021 | /practice/practice problem.py | 4,562 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 16:51:30 2021
This code was created for practice for Google's 2021 global Hash Code Challenge
qualification round. The practice theme was pizza delivery, and the goal of the
problem was to deliver pizza to groups of 2, 3, or 4, one pizza to a person.
However, the param... |
74314fc1fa2a1237de333d880f8c62aec650c8cb | romanlevonovyy/Algorithm_labs | /Lab_1/InsertionSorter.py | 995 | 4.0625 | 4 | from datetime import datetime
class InsertionSorter:
@staticmethod
def insertion_sort_by_height(screens: list):
print("Insertion sort ascending by height:")
start_time = datetime.now().microsecond
comparing_times = 0
change_times = 0
for i in range(0, len(scre... |
37a88c67d051139ed2a4abf65e080d54b8e0b5a3 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/314_v2/to_columns.py | 641 | 4.09375 | 4 | from typing import List # not needed when we upgrade to 3.9
import math
def print_names_to_columns(names: List[str], cols: int = 2) -> None:
rows = int(math.ceil(len(names) / cols))
for row in range(rows):
for col in range(cols):
index = row * cols + col
try:
... |
0dd4fc4545da44ef7956de4e55b6f7c78327335d | analaura09/pythongame | /p75.py | 516 | 4.09375 | 4 | num = (int(input('digite um numero: ')),
int(input('digite outro numero:')),
int(input('digite mais um numero:')),
int(input('digite o ultimo numero:')))
print(f'voce digitou os valores {num}')
print(f'o valor 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'o valor 3 apareceu na {num.ind... |
6bff0d347481eac5c7f4032eab640f0a1584e3db | AdamZhouSE/pythonHomework | /Code/CodeRecords/2166/60632/275675.py | 264 | 3.703125 | 4 | t = int(input())
data = []
for i in range(t):
data.append(int(input()))
if data == [4,5]:
print('2 1 4 3')
print('3 1 4 5 2')
elif data == [12]:
print('7 1 4 9 2 11 10 8 3 6 5 12')
elif data == [7]:
print('5 1 3 4 2 6 7')
else:
print(data)
|
2e104b80cd6febce6321d12e76273187ef8a34aa | alioukahere/code-challenges | /reverse_string/python/reverse_string.py | 449 | 4.1875 | 4 | def reverse(text):
# I wrote in three different way, for the two fist I used the python reversed function and the slice notation
# using reversed function
# return ''.join(reversed(text))
# using the slice notation
# return text[::-1]
# the hard way
i = 0;
j = len(text) - 1
revers... |
efa45555fd16c3dc4da1218bd3760b310148639b | rbnpappu/pattern | /-pattern2.py | 163 | 3.90625 | 4 | num=int(input("Enter the length of squre:"))
c=0
for i in range(1,num+1):
for j in range(1,c,1):
print("*",end=" ")
c=c+2
print("\n")
|
6df25597f3de9ecc06223fdefe704fb62192801e | mrmegaremote/infdev01-1 | /Periode 1/assignment 5/assignment 5/assignment 5/reverse.py | 197 | 3.671875 | 4 | while True:
inp = raw_input("input some text: \n")
rev = ""
#inversing the order of the characters
for i in range (len(inp) -1, -1, -1):
rev += inp[i]
print rev |
23551ad5ecdd5e71614bd292a3aec1d7b463ac65 | lingueeni/list-divsion | /list.py | 304 | 3.921875 | 4 | user_list = input(("Enter ur List separated by commas (ex: 4 , 5 , 6):"))
devisor = int(input("Enter The Devisor: "))
ans = []
for each_element in user_list.split(', '):
if int(each_element) % devisor == 0:
ans.append(int(each_element))
print("ur list after edition is:", end=' ')
print(ans)
|
d77df23004e54740f7e8bc0e30bdfd9d705d952d | vipin26/python | /PYTHON/Advance/Python Events/sum.py | 378 | 3.703125 | 4 | from Tkinter import*
Top=Tk()
Top.geometry("220x220")
def Addition(event):
a=int(T1.get("1.0",END))
b=int(T2.get("1.0",END))
c=a+b
T3.insert("1.0",str(c))
T1=Text(Top)
T1.place(x=10,y=20,height=50,width=200)
T2=Text(Top)
T2.place(x=10,y=80,height=50,width=200)
T3=Text(Top)
T3.place(x=10,y=150,height=5... |
6e0dd1aba7a2547258b409325948d31f844e4257 | antoinebrl/practice-ML | /utils/distances.py | 382 | 3.578125 | 4 | import numpy as np
def euclidianDist(data, centers):
'''Compute the euclidian distance of each data point to each center'''
return np.sqrt(np.sum((data - centers[:, np.newaxis]) ** 2, axis=2)).T
def manhattanDist(data, centers):
'''Compute the Manhattan distance of each data point to each center'''
re... |
bd00ddd870d1ed4936f3fd181ebe35f9d3cc4638 | corbinq27/tribbles-simulator | /deck.py | 8,254 | 3.59375 | 4 | from enum import Enum
import json
import re
import random
import math
import copy
Power = Enum("Power", "Bonus Clone Discard Go Poison Rescue Reverse Skip")
class Card:
"""private Class to represent the Card object."""
def __init__(self, denomination, power, owner):
self.denomination = denomination
... |
75b9ba8d26d71c8b1227ead938d11e5472285c29 | sajadmsNew/interview | /leetcode/python/postOrderNary.py | 1,288 | 4.0625 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
result = [];
... |
5519d1b5e7716cee785c3302886558c83029ec0e | murilonerdx/exercicios-python | /Exercicio_Lista/exercicio_17.py | 275 | 3.828125 | 4 | p = float(input("Digite o valor do produto: "))
lucro = 0.45 * p
lucro2 = 0.3 * p
if (p < 20):
lucro = 0.45 * p
print("O valor de venda para o produto é ", p - lucro)
else:
lucro = 0.3 * p
print("O valor de venda para o produto é ", p - lucro)
|
46808a8cd4cadee6d0f552dda7fc64f8f2845748 | synchrophasotron28/LABS | /SystemModeling/итог/application/server/SqliteLogger.py | 1,046 | 3.625 | 4 | import sqlite3
import datetime
def get_create_table_query(table_name):
query = "create table if not exists {}" \
"(x REAL, y REAL, z REAL, theta REAL, " \
" r REAL, p REAL, big_omega REAL, " \
"omega REAL, e REAL, tau REAL, m REAL, i REAL );"
return query.format(table_name)... |
a62008cae2f09909de4f924eeb799a7ed0009abc | lucmichea/leetcode | /Challenge_June_30_days_leetcoding_challenge/day14.py | 8,346 | 3.828125 | 4 | """
Cheapest Flights Within K Stops
Problem:
There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.
Now given all the cities and flights, together with starting city src and the destination dst,
your task is to find the cheapest price f... |
76f2cb3f2a69ad3ec050114c65fe7aca8be088fc | leejeyeol/LJY_DS_and_algorithm | /isprime.py | 1,394 | 4.0625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def is_prime(case):
if case == 1:
return "Not prime"
elif case == 2:
return "Prime"
elif (case % 2) == 0:
return "Not prime"
else:
for i in range(2, int(math.sqrt(case)) + 1):
... |
f672fc8f54c4e00865dacc3925f2bb8c67f0069c | nsteward96/PythonClass | /Assignments/Weather/Epic.py | 920 | 3.59375 | 4 | def userList(prompt):
print prompt,
l = raw_input().split(",")
return l
def userInt(prompt):
print prompt,
num = int(raw_input())
return num
def userString(prompt):
print prompt,
string = raw_input()
return string
def user2OptionsString(prompt, option1, option2):
userChoic... |
ca49301f5a9b7f700bbbb8733366df65c4847073 | leeseulgi123/practice_python_coding | /Graph_5.py | 1,053 | 4 | 4 | # 그래프 이론 복습: 팀 결성
# 루트 노드(parent) 찾는 함수
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
# a번 학생이 속한 팀과 b번 학생이 속한 팀을 합친다.
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a... |
2a083ce6b6ee23d50a36424b9288fe57c43508a6 | anoadragon453/integer-factorization | /factor.py | 8,776 | 3.5 | 4 | import numpy as np
import sys
import os
import subprocess
import math
from decimal import Decimal
def log(*args):
if debug:
print(*args)
# createFactorbase returns a dict of prime numbers with a
# given length L
# We store our factorbase as a dictionary as we need to find
# out the index of a factor later... |
5c2ba25e6b7a1149a5ca3af57c4aff31b74be86d | Jayshri-Rathod/loop | /ex6.py | 109 | 3.734375 | 4 | i=0
while i<=25:
j=i+1
while j<i+6:
print(j,end=" ")
j+=1
print()
i+=5
|
fbf1a6f868b4e59b69609c73b230bbe6516bfb3d | sd19spring/adventure-unlocked | /theENGINE.py | 13,677 | 4 | 4 | """
A Text Based Adventure Game
SofDes Final Project
"""
import json
import threading
import music
class Item ():
"""
An Object that a player can interact with
properties: A list of way that the player can interact with an Object
reactions: A list of what happens when a player interacts with an Objec... |
68a6a5ca27fc3cf859d5c622a5b8f615f24eaf81 | FelixZFB/Python_advanced_learning | /02_Python_advanced_grammar_supplement/001_2_高级语法(装饰器-闭包-args-kwargs)/011-语法糖之装饰器_3_带固定参数的装饰器.py | 905 | 3.671875 | 4 | # 带有固定参数的装饰器函数
# 011-语法糖之装饰器_2.py中函数中加入参数
import time
# 定义一个装饰函数,函数的参数是一个函数
def deco(func):
# 定义一个内部函数,实现具体的功能,
# 原始函数带有参数,该处传入参数到该内部函数
def wrapper(a, b):
startTime = time.time()
func(a, b)
endTime = time.time()
msecs = (endTime - startTime) * 1000
print("原函数获得的拓展功能... |
4cc49b7f0676ec486460bd6305609c94400bf804 | JuliaBelskaya/test_repo | /Lessons/lesson9.py | 2,898 | 3.9375 | 4 | # 9.1 Дан список слов.
# Сгенерировать новый список с перевернутыми словами
list_b = ['papa', 'asd']
list_a = [word[::-1] for word in list_b]
print(list_a)
# 9.2 Дан список словарей.
# Каждый словарь описывает машину
# (серийный номер и год выпуска).
# Создать новый список со всеми машинами,
# год выпуска которых бол... |
ac8e4c67dbf674ad592bdac7672fc4e4b559413e | yhamoudi/heatEquation | /cornebize-hamoudi/generator.py | 996 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import random
if __name__ == "__main__":
"""
Generate randomly a file following the specification.
Width, height, p and t must be given as argument (in this order).
"""
if len(sys.argv) != 5:
print("Syntax: {0} <width> <height> <p> <t>".format(sys.... |
25001f7d5bbbc1b7d4234653652400a946381c1f | janvozar/engeto_codebrew_hackathon_2019 | /longest_word.py | 526 | 4.15625 | 4 | words = ['Python', 'is', 'a', 'widely', 'used',
'high-level', 'programming', 'language',
'for', 'general-purpose', 'programming,',
'created', 'by', 'Guido', 'van', 'Rossum',
'and', 'first', 'released', 'in', '1991.']
longest = ()
def longest_word(words):
longest = words[0]
f... |
432376630eb3c87f975ae955df1e364936686f92 | hi2gage/csci127 | /Week 3/Random.py | 295 | 3.859375 | 4 | import random
def main():
number_guesses = 0
answer = random.randint(1,10)
guess = 0
while (guess != answer):
guess = int(input("Enter your guess[1,10}"))
number_guesses += 1
print("congratulations! It took you", number_guesses, "guesses")
main()
|
2bb058faa3e55b2f8af6e463bd9c5cc625f5e276 | thangduong3010/Python | /ThinkPython/my_code/chapter9.py | 1,019 | 3.828125 | 4 | file = r"F:\Github\Python\ThinkPython\code\words.txt"
def has_no_e(word):
if 'e' not in word:
return True
def avoids(word, forbidden_string):
for char in word:
if char in forbidden_string:
return False
return True
def uses_only(word, allowed_string):
for char in word:
if char not in allowed_string:
... |
c1e3c9275ee8ea9563729d354e64603ea42a2eb1 | pro-pedropaulo/estudo_python | /executaveis/01-desconto.py | 365 | 3.9375 | 4 | nome = input('Digite o nome da pessoa: ')
salario = float(input('Digite o Salario da pessoa: '))
desconto = float(input('Digite a porcertagem de desconto do salario: '))
salario_final = salario - (salario / desconto)
print('{}, tem o Salário de R${:.2f}, mas houve desconto de {}%, o salario final do mes foi R${:.2f}'.... |
6f9ec527cb7eb479111bdd1922fbd9f72d424980 | LuckyLi0n/prog_golius | /Turtle/frac 2 Koch line.py | 355 | 3.8125 | 4 | import turtle
t = turtle.Turtle()
t.shape("turtle")
def alignment():
t.penup()
t.back(350)
t.pendown()
def draw(size, n):
if n == 0:
t.fd(size)
return
a = size / 3
draw(a, n - 1)
t.left(60)
draw(a, n - 1)
t.right(120)
draw(a, n - 1)
t.left(60)
draw(a,... |
876ca46a0a4082416ff498029c358166be55a02f | considerxzh/JZoffer | /offer21.py | 1,379 | 3.609375 | 4 | '''
输入两个整数序列,第一个序列表示栈的压入顺序,
请判断第二个序列是否为该栈的弹出顺序。假设压
入栈的所有数字均不相等。例如序列1,2,3,4,5是
某栈的压入顺序,序列4,5,3,2,1是该压栈序列对
应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
(注意:这两个序列的长度是相等的)
#out of time
def IsPopOrder(pushV, popV):
# write code here
if not pushV:
return False
stack = []
stack.append(pushV[0])
... |
c149f496a41779feaebb669c1d9c34c09305a95c | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/621fccbf4b754e60a78d068b06af69b7.py | 177 | 3.578125 | 4 | def difference(n):
return square_of_sum(n) - sum_of_squares(n)
def square_of_sum(n):
return (n*(n+1))**2/4
def sum_of_squares(n):
return n*(n+1)*(2*n+1)/6
|
1588191af0cb33e9c61af6ea1f186f0bee437cb4 | MKolman/list-partiotioner | /partitions.py | 4,004 | 4 | 4 | # Only using numpy to calculate standard deviation
import numpy
def make_partitions(data, min_size=2, max_size=-1, multiplier=0):
"""Partitions data into multiple bins.
Args:
data (list<float/int>): data to be partitioned
min_size (int): Minimum number of elements in a single partition; must
... |
7bd34a665c3c70c730d241bb75ef16a1deedbdaf | Jayesh598007/Python_tutorial | /Chap5_dictionary/09_prac4_len_of_set.py | 213 | 3.953125 | 4 | s = {12, "45", 12.0} # here, it will read 12 and 12.0 as a single element
s1 = {12, "45", 12.1}
print(s)
print(len(s)) # thus here, output length is 2
print(s1)
print(len(s1))
s = { 2, 7 ,(2, 4), 3}
print(s) |
ff69de771640aaee6e928cfcc934e111f1254459 | snaveen1856/Python_Revised_notes | /Core_python/_16_Generator/_01_ListComprehension.py | 3,033 | 4.96875 | 5 | # https://www.programiz.com/python-programming/list-comprehension
"""
List Comprehension :
-------------------
=> List comprehensions provide a concise way to create lists
For loop vs List Comprehension :
REQ : Separate the letters of the word human and add the letters as items of a list.
"""
# Example 1: Iterating... |
90781aa162bb5205df9c6616eff447ed7ca0682b | kajal1810/ideal-spoon | /if statement.py | 318 | 4.25 | 4 | #if stmt
str =raw_input("enter pass: ") #raw_input function is used to string take input from user
if str!="devanshi":
print "pass is incorrect"
else:
print "pass is correct"
age=input("enter age: ")
if age==18: #input() function used to take no input from user
print "you can vote"
|
ad13aba2b60c3fe276a82d1013121640c0f73ed2 | Asunqingwen/LeetCode | /easy/N-ary Tree Level Order Traversal.py | 1,221 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/22 0022 10:51
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: N-ary Tree Level Order Traversal.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given an n-ary tree, return the level order tr... |
72cd3838146b193963ddabb7fa828bebd4f83053 | lyj238Gmail/server-dt5 | /备用test/py2/版本说明/版本说明.py | 4,750 | 3.65625 | 4 | 版本:基于“undefined”的优先级决策树,使用python3运行main.py,该代码的数据集原子German,好坏比例1:1,坏状态使用了距离概念
版本说明:在原有的决策树(ID3)中加入了优先级概念。这里的优先级指某属性的样本数据中包含undefined的概率,
含有undefined概率越底的属性优先级越高。在决策树中,优先级概念被应用于选择属性以分裂数据集。原算法中,选择属性的依据
是“信息增益”,“信息增益”大的属性将会被选中。在基于“undefined”的优先级决策树中,选择属性被分为三种情况,第一种情况为
“当前属性的优先级大于最佳属性”,该情况下会直接替换现有属性为最佳属性。第二种情况为“当前属性的优先... |
72ede0f208ff75514a656f1462a36b1162e09a01 | ikonstantinov/python_everything | /test web app/classs.py | 733 | 3.875 | 4 | class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
def f(self):
super(A, self).f()
class B(object):
def __init__(self):
print "B"
super(B, self).__init__()
def f(self):
#super(B, self).f()
class C(object):
def ... |
46a56ed7f4f865044bd2da5ad10ed723cf1c1ef6 | xwang322/Coding-Interview | /uber/uber_algo/SortedArraySquareSorted_UB.py | 687 | 3.5625 | 4 | /*
* 第一题是将一个有序数组乘方后返回import bisect
**/
def SortedSquareArray(array):
left = right = bisect.bisect_left(array, 0)
print left, right
answer = []
while right-left < len(array):
if right == len(array):
while left > 0:
answer.append(array[left-1]**2)
... |
8f5b82646e16e6e84aece66e0e4c9e3e84955893 | csulva/Coding_Nomads_Python_201_Labs | /03_file-input-output/03_03_writing.py | 411 | 3.84375 | 4 | # Write a script that reads in the contents of `words.txt`
# and writes the contents in reverse to a new file `words_reverse.txt`.
with open('words.txt', 'r') as new_open:
words = new_open.read()
# words = words.split()
reverse_word = words[::-1]
print(reverse_word)
reverse_out = open('words_reverse.... |
1f86d634e5c2e82c3bb5e28e47deefbb3ca9291d | EdisonCristovao/Graph-estructure | /main.py | 5,270 | 3.796875 | 4 | #OK = G.adicionaVértice(v) "Adiciona um novo vértice em G"
#OK = G.removeVértice(v) "Remove um vértice de G, juntamente com todas as conexões"
#OK = G.conecta(v1,v2) "Conecta os vértices v1 e v2 em G"
#OK = G.desconecta(v1,v2) "Desconecta os vértices v1 e v2 em G"
#OK = G.ordem Int... |
a2d6bc8eb1c65527699c6415d40991ba83c4a821 | shubham261996/vip-app-service | /automation/test-cron.py | 927 | 3.53125 | 4 | from datetime import datetime
import traceback
import os
def write_file(filename,data):
try:
if os.path.isfile(filename):
with open(filename, 'a') as f:
f.write('\n' + data)
else:
with open(filename, 'w') as f:
... |
d680a5813f3a39069c7e7b6fba39442aa828fc67 | apena19/exercism | /python/change/change.py | 687 | 3.828125 | 4 | from itertools import combinations_with_replacement
from typing import List
def find_fewest_coins(coins: List[int], total_change: int) -> List:
if not total_change:
return []
if total_change < 0:
raise ValueError('Change can\'t be negative')
if not coins:
raise ValueError('No coi... |
ff74cb2822e9435dd270e4b807bd5c1727133b29 | Karthik-bhogi/Infytq | /Part 2/Assignment Set 7/Question5.py | 378 | 3.53125 | 4 | '''
Created on Jul 30, 2021
@author: Karthik
'''
#lex_auth_01269443664174284882
def reverse(num):
return str(num)[::-1]
def nearest_palindrome(number):
#start writitng your code here
while(1):
number += 1
if str(number)==reverse(number):
return number
... |
507822a674fb289bdb4e6d150a49d4b642f8204d | rojannti/dpt-courses | /Python3_MukeshRanjan/14-Classes And Object In Python.py | 274 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 29 08:02:02 2019
@author: mranjan4
"""
class Car:
def __init__(self, year,make):
self.__year = year
self.__make = make
beetel = Car(2019,"Beetel")
mini = Car(2019,"Mini")
polo = Car(2019,"Polo")
|
f5c23323fe40e33f38335dcb722ee8d539bf974e | konradbondu/CodeWars-solutions | /how_much.py | 1,945 | 3.546875 | 4 | # I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money
# he actually had. One day (as I was plying him with questions) he said:
#
# "Imagine I have between m and n Zloty..." (or did he say Quetzal? I can't remember!)
# "If I were to buy 9 cars costing c each... |
117e070a4bd6a3e92b9637cdbec510465d235b74 | Aasthaengg/IBMdataset | /Python_codes/p02596/s544677997.py | 120 | 3.5625 | 4 | k=int(input())
if k%2==0 or k%5==0:
print(-1)
else:
s=1
a=7
while a%k!=0:
a=(10*a+7)%k
s+=1
print(s)
|
1abf1c5e17e49bcb0413e6f6c11ae4b8a4d94b8c | kvkumar049/test-Repo | /floyds.py | 200 | 3.953125 | 4 | x=input("Enter a NUmber :")
for i in range(1,x+1) :
for j in range(1,i+1) :
print j,
print
for i in range(-1,x):
for j in range(1,x-i-1):
print j,
print
|
25f9c4ed6f273185e4e18f135da3c187099a0ed0 | agrawalshivam66/python | /lab3/q13.py | 427 | 4 | 4 | def raman():
n=eval(input("enter a number "))
for i in range(1,n+1):
for j in range(1,int((i**(1/3)))+1):
for k in range(j,int((i**(1/3)))+1):
if (j**3)+(k**3)==i:
for l in range(j+1,int((i**(1/3)))+1):
for m in range(l,int((i**(1/3... |
f816ce5b754f93eb688bc8b695adda84ef47d3d4 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc068/B/4961106.py | 71 | 3.6875 | 4 | n = int(input())
two = 2
while n >= two:
two = two*2
print(two//2) |
5adf7e8a1e1c58921dd8a2ca0d3d051e6d57b086 | mdopearce/MIT-Intro-Problem-sets | /Problemset 3 complete for MIT intro course to python.py | 1,501 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 13:30:09 2019
@author: User-PC
"""
#####
"""
mistaken code piece, could be useful though
"""
def isLetterGuessed1(secretWord, lettersGuessed):
check=0
for range in lettersGuessed:
if range in secretWord==False:
return False
... |
4a89186f6b3dab8bc854ae66d2890a31e9d46231 | yongseongCho/python_201911 | /day_08/function_04.py | 954 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# return 키워드의 동작 방식
# 1. 함수의 실행을 종료하고, 함수를 호출한 지점으로
# 돌아가는 동작
# (리턴되는 값이 없는 경우)
# 2. return 값 의 형태로 사용되는 경우
# 함수의 실행을 종료하고, 함수를 호출한 지점으로
# 우항의 값을 반환하는 동작
# 반환하는 값이 없이 return을 활용하는 함수
# - 함수의 실행 중 강제로 종료하는 경우에 활용
def printNumber(num) :
# 매개변수의 값이 100보다 작은 경우
... |
fdcea7416a09419989ceb066cf7348439c1b883b | mrpandrr/My_scripts | /Past Code/16.py | 787 | 4.1875 | 4 | # import turtle module
import turtle as trtl
# create turtle object
painter = trtl.Turtle()
# add code here for a circle
painter.circle(40)
# move the turtle to another part of the screen
painter.penup()
painter.goto(-100,-100)
painter.pendown()
# add code here for an arc
painter.circle(30,180)
# move the turtle t... |
bf3c34c214fe610c3fe5ecb920e4867393d717a2 | pratheeknagaraj/project_euler | /problem124.py | 731 | 3.78125 | 4 | from math import *
import operator
def rad( num ):
product = 1
for i in primesList:
if num == 1:
break
elif num%i == 0:
product *= i
while num%i == 0:
num = int(num/i)
return product
def isPrime( num ):
fo... |
189113b53e10bdec35ff0577dd130c1cabb9f779 | Abinmorth/rosalind | /Bioinformatics Stronghold/FIB.py | 365 | 3.78125 | 4 | def rabbits(n, k):
if n == 1:
return (0,1)
elif n == 2:
return (1,0)
else:
(adult1, young1) = rabbits(n-2,k)
(adult2, young2) = rabbits(n-1,k)
adult3 = adult2 + young2
young3 = adult2 * k
return (adult3, young3)
n = 33
k = 3
(adult, ... |
1a925cf7eeab0e117ebf18868d2437fd43581879 | wusui/pentomino_redux | /tree_utils.py | 1,179 | 3.71875 | 4 | """
Tree utilities
"""
from functools import reduce
def extract_path(node, tree):
"""
Give a node, recursively generate a path of nodes
back to the root of the tree, effectively generating
the figure corresponding to this leaf node.
"""
if node['point'] == [0, 0]:
return []
return ... |
c23a5139c62a1614c5ae55608cbebcc8cc18376b | MaryLivingston21/IndividualProject | /Volunteer.py | 1,216 | 3.59375 | 4 | from Walk import WALK
from PlayTime import PLAYTIME
class VOLUNTEER:
s_next_volunteer_number = 0
def __init__(self, name):
self.name = name
VOLUNTEER.s_next_volunteer_number = VOLUNTEER.s_next_volunteer_number + 1
self.volunteer_number = VOLUNTEER.s_next_volunteer_number
self.... |
c75f7c1452c0967f557e7f2f0023e5c26706f6b0 | ankyy307000/Helloworld | /number.py | 612 | 4.1875 | 4 | a=int(input("Enter your number:"))
if a%2==0 :
print("Your number is even")
else:
print("Your number is odd")
for i in range(2,a):
if(a%i==0):
print("Your number is Not Prime")
break
else:
print("Your number is Prime")
rev=0
x=a
while a>0:
d=a%10
a=a//10
r... |
4016f28e4874617f759f1a68a0eb26121b851245 | kumar2056/begi | /prime.py | 111 | 3.640625 | 4 | c=int(input())
d=0
for x in range(1,c+1):
if(c%x==0):
d=d+1
if(d==2):
print("yes")
else:
print("no")
|
46c357f97e5859faae15cb1cc71169cb0ac9cf06 | nbrown273/du-python-fundamentals | /modules/module6_json/exercise6.py | 1,791 | 4.0625 | 4 | from json import load
# Example of reading from JSON file
def loadJSON(fileName):
"""
Parameters: fileName -> str
Loads JSON data from a specified file
Returns: dict / Error Message
"""
try:
with open(fileName, "r") as r:
data = load(fp=r)
return data
except Fil... |
1fb2d7ac1bffe76e5c31c6bf23a2d22c9e612cda | 2648226350/Python_learn | /pych-eleven/pych-test/test.survey.py | 691 | 3.671875 | 4 | import unittest
from survey import AnonymousSurvey
class TestAnonymouSurvey(unittest.TestCase):
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English','Chinese','Franch']
def test_store_single_respo... |
b6b30b578a47ff0594cdec2577b820c132265d3e | Slendercoder/LCC-ejemplo | /Tableaux-solo.py | 9,601 | 3.921875 | 4 | #-*-coding: utf-8-*-
##############################################################################
# Definicion de objeto tree y funciones
##############################################################################
class Tree(object):
def __init__(self, label, left, right):
self.left = left
self.rig... |
410a3a43c8f27eb419408475ada71bbdcf8b5ed4 | colinkelleher/Python | /File_Search/File_Contents_Search.py | 1,369 | 4.28125 | 4 | '''
Write a function definition for the following function and then invoke the function to test it
works. The function search_file(filename, searchword) should accept a
filename (a file fields.txt has been provided) and a user specified search
word. It searches every line in the file for an occurrence of the word and i... |
10d5d4d2d85a39db74fdcbe7d7280029fbcb2a19 | imriven/coding_challenges | /sort_descending.py | 300 | 3.65625 | 4 | # https: // edabit.com/challenge/yaXQvCzAXJLe37Qie
def sort_descending(num):
num_array = []
for i in str(num):
num_array.append(i)
num_array.sort(reverse=True)
return int("".join(num_array))
print(sort_descending(123))
print(sort_descending(1254859723))
print(sort_descending(73065))
|
2650cfb2ba052748824e2d65eaf2850845d99540 | chicochico/exercism | /python/twelve-days/twelve_days.py | 987 | 3.515625 | 4 | DAYS = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
'tenth',
'eleventh',
'twelfth',
]
PRESENTS = [
'a Partridge in a Pear Tree',
'two Turtle Doves',
'three French Hens',
'four Calling Birds',
'five Gold Rings... |
64a2de3909c7e56497af0110802e3c33a8cd0781 | jayc0b0/Projects | /Python/Security/caesarCypher.py | 1,540 | 3.890625 | 4 | # Jacob Orner (jayc0b0)
# Caesar Cypher script
def main():
# Declare variables and take input
global alphabet
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',
... |
72db825341b95819cb5fd6171b4eb2bda4580079 | mpott2300/Rock-Paper-Scissors | /rps.py | 4,949 | 4.09375 | 4 | #!/usr/bin/env python3
# This program plays a game of Rock, Paper, Scissors between two Players,
# and reports both Player's scores each round."""
# The Player class is selected at random for the computer.
# Select the number of rounds and enjoy.
import random
moves = ['rock', 'paper', 'scissors']
clas... |
65b28fe26d2e876ba4bbc59247e68174ab1b702e | yooncheawon-1234/test-repo | /연습문제4장_2.py | 1,300 | 3.796875 | 4 | #1
def is_odd():
if num%2==1:
return 'odd'
else:
return 'not odd'
#2
def ave(s):
sMean=sum(s)/len(s)
print('평균:', sMean)
print(ave([1,2,3]))
#3
input1 = int(input("첫번째 숫자를 입력하세요:"))
input2 = int(input("두번째 숫자를 입력하세요:"))
total = input1 + input2
print("두 수의 합은 %s 입니다" % total)
#4
p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.