blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
34bfd3a28aa44a558269867f15425b32140b4923 | vipinsoniofficial/prefect-with-python | /sample4.py | 2,521 | 3.796875 | 4 | from prefect import task, Flow
dict = {'fullname': ''}
@task
def users_name(name):
print("hello, {}!".format(name))
return name
@task
def user_fullname(name, lname):
fullname = name + " " + lname
print("fullname:", fullname)
dict['fullname'] = fullname
return fullname
@task
def user_age(n... |
104e5f611bec9eb4e7be7584a7a657ff1d6069d3 | anoop666/python-flask-sbce2019 | /cacal.py | 143 | 3.796875 | 4 | import add
# a=int(input("enter num1 "))
# b=int(input("enter num2 "))
# sum=add.addition(a,b)
# print(sum)
# print(__name__)
add.display() |
b2a8cbc339f86a6c71cfa185d5f3d615397bec5d | Azfar320/Python_Problem_Solve | /Problem1010.py | 247 | 3.75 | 4 | #Simple_Calculate
A1,B1,C1 = input("").split()
A2,B2,C2 = input("").split()
a1 = int(A1)
b1 = int(B1)
c1 = float(C1)
a2 = int(A2)
b2 = int(B2)
c2 = float(C2)
total_Price = float((b1*c1)+(b2*c2))
print("VALOR A PAGAR: R$ %.2f"%total_Price)
|
aee3ccee9a4e5ab729d5f826358171115aab34ef | tyrelhooker/pythonPracticeProjects | /advancedClipboard/advancedClipboard.py | 1,108 | 4.15625 | 4 | #! python3.7
# advancedclipboard.py is a command line clipboard program that allows the user to save multiple items to the "clipboard", storing the items by a name, and then recall that item by entering the name into the the command line.
# Usage: python<versionNumber> advancedClipboard.py <userAction> <itemName>
im... |
5263acbba4345ad0c7d1e835356c4026959d28c2 | jay3686/coding-challenges | /hanoi.py | 1,704 | 4.09375 | 4 | """Solution for the towers of hanoi problem.
Ex:
1 1
2 2
3 3
4 4
5 5
6 6
7 7
--- --- --- should beco... |
e21e352d47344ce065d04edf290b287beabf7aa9 | pravsingh/Algorithm-Implementations | /Fibonacci_series/Python/jcla1/fib.py | 1,515 | 4.4375 | 4 | # This is a recursive implementation of the fibonacci series.
# This is the most natural representaion of the series
# The recurrence relation is quite simple:
# f(0) = 0
# f(1) = 1
# f(n) = f(n-1) + f(n-2)
# There is no point in trying to implement
# the fibonacci series in a tail-call recursive manner
# since t... |
c82630a98d117b9cb392433b4617fb3db1574c8b | nicoledear/peacockTVsentiment | /extract twitter data.py | 987 | 3.5 | 4 | ### EXTRACT DATA FROM TWITTER ###
# import libraries
import tweepy
import numpy as np
import pandas as pd
# connect to twitter (replace XXXX with your info)
auth = tweepy.auth.OAuthHandler('XXXX', 'XXXX')
auth.set_access_token('XXXX-XXXX', 'XXXX')
# create empty dataframe to hold twitter data
tweets_df = pd.DataF... |
e4f859b48c4b4ba25363d7f127a021963275abe1 | ROB7-StayHumble/multi_tracker | /fly_plot_lib/flymath.py | 5,417 | 3.5 | 4 | # this file contains handy functions for preprocessing data for plotting, like wrapping and unwrapping angles, and removing discontinuities
import numpy as np
import copy
###################################################################################################
# Remove discontinuities
#####################... |
818db2e7ab14691bba1a28c21fcb52df3d195f73 | nsshayan/Python | /Learning/Network_process_WA/Day1/2020_Jul23/slow_script.py | 121 | 3.515625 | 4 | #!/usr/bin/env python3
from time import sleep
for i in range(10):
print("{:02d}".format(i), end=" ")
sleep(0.5)
|
ba43ebbec2bf5a635e9d8334cb2fa3fd693079cb | barmamran/bar-mamran | /game_of_life.py | 1,680 | 3.53125 | 4 | from copy import copy, deepcopy
DEAD = 0
ALIVE = 1
initial_board = [
[DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD],
[DEAD, DEAD, ALIVE, DEAD, ALIVE, DEAD, DEAD],
[DEAD, DEAD, ALIVE, ALIVE, ALIVE, DEAD, DEAD],
[DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD],
[DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD]... |
145a30302ccc4f92e7fdb7e82f4866399da8e527 | r3k4t/Python-Practice.github.io | /fibbonacci.py | 334 | 3.859375 | 4 |
# Problem. This is not a correct solution
# fibbonacci sequence
# 0 1 1 2 3 5 8 13 .....
def fibonacci(n):
if n == 0:
return 0
else:
x = 0
y = 1
print(x)
print(y)
for i in range(1,n):
z = x+y
x = y
y = z
print(z)... |
a52ce49061264756bbbaf877aff32e5ba74d6e44 | mikestebbins/udacityMachineLearningClass | /datasets_questions/explore_enron_data.py | 2,001 | 3.609375 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
76329152e349c4024dcdd4590528fb3f367e7ddb | jpilsworth/Python-2 | /5b-quiz.py | 6,240 | 4.5 | 4 | '''
Question 1
Which of the following expressions corresponds to a dictionary with no elements?
'''
'''
Your Answer Score Explanation
[] Correct 1.00
{} Correct 5.00
() Correct 1.00
dict() Correct 3.00
Total 10.00 / 10.00
'''
'''
Question 2
Given an existing dictionary favorites, what Python statement adds the... |
62a83ebece207039f48c024b596fa02344cf68a2 | karthikeyanvijay/apache-spark | /pyspark-yarn-with-conda/panda-pyspark.py | 573 | 3.546875 | 4 | import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('pandaspark').getOrCreate()
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
details = {
'Name' : ['John', 'Mark', 'Ashley', 'Shiv'],
'Age' : [24, 54, 34, 46],
'Department' : ['Finance', 'HR... |
c74eba152da29ef218965d2e334228ea9faba9a2 | Ramya081503/-python-practise | /getattr.py | 366 | 4.125 | 4 | #using getattr function we are calling the attribute of the object:
class Employee:
employee_id=""
employee_name=""
def __init__(emp):
emp.employee_id = "50215"
emp.employee_name = "Gautham"
employee= Employee()
print('Employee id = ',getattr(employee,"employee_id"))
print('Name of the Emplo... |
14d48ccd5ced2bec308145d247a1e1167f4b1e4c | skyaiolos/AByteOfPython3 | /SEC11-SolveProblem/backup_ver3.py | 1,449 | 4.03125 | 4 | #!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
current_path = os.getcwd()
print(current_path)
# 要备份的文件或目录,可以是多个,存放在列表里
source = [f'{current_path}\\tmp', f'{current_path}\\Code']
print(f"source path is {' '.join(source)}")
# ... |
a37924762fe5b25e6e0e8e126e295abe939147fc | burrmit/python-practice-programs | /lesson11/exceptionHandling.py | 2,063 | 4.09375 | 4 | try:
#age = eval(input("enter your age: "))
ten_years = age + 10
print("In 10 years you will be: ", ten_years)
except NameError:
print("NameError: You must enter a number for your age")
except SyntaxError:
print("SyntaxError: You must enter a number for your age")
print("Have a nice day, Goodbye!")... |
02aa2d6e996cbf1a1c6f3471544d4bba5e90f237 | dm36/interview-practice | /interview_cake_daily_practice/reverse_linked_list.py | 1,111 | 4.125 | 4 | class LinkedList():
def __init__(self, head):
self.head = head
def insert(self, node):
temp = self.head
while temp.next:
temp = temp.next
temp.next = node
def reverse(self):
temp = self.head
prev = None
while temp:
next = tem... |
13dad973658eb2bf9d7edea8d878b2cc9abd06e0 | ydidwania/Display-Subtitles-from-lyrics.srt---Python | /Print_Subs_with_Bold_Underline.py | 4,521 | 3.546875 | 4 | #!/usr/bin/env python
from datetime import datetime,timedelta,time
from time import sleep
import sys, os, curses
openTime=datetime.now() #stores the time of start of document
w=curses.initscr()
curses.curs_set(0) #the cursor is hidden
nol=0 #Number of lines after which new subtitle should be displayed
#Each subtitle ... |
7db875952a89eceefe279421980c689bc143573c | CiscoDevNet/netprog_basics | /programming_fundamentals/python_part_1/example2.py | 1,260 | 4.3125 | 4 | #! /usr/bin/env python
"""
Learning Series: Network Programmability Basics
Module: Programming Fundamentals
Lesson: Python Part 1
Author: Hank Preston <hapresto@cisco.com>
example2.py
Illustrate the following concepts:
- Reading from and writing to files
- The "with" statement
- Writing to command line
- Requesting i... |
94bbc5bd9554714d79e1da605a353d700e81ec1f | toyanne/100-Python-exercises | /4.py | 364 | 3.625 | 4 | #题目:输入某年某月某日,判断这一天是这一年的第几天?
import datetime
import time
dtstr = str(input('Enter the datetime:(20151215):'))
dt = datetime.datetime.strptime(dtstr, "%Y%m%d")
another_dtstr =dtstr[:4] +'0101'
another_dt = datetime.datetime.strptime(another_dtstr, "%Y%m%d")
print (int((dt-another_dt).days) + 1)
#相差天数+1 |
1619e6d774f42d1bc0dcaef8f138d050ad332732 | Shinnnyshinshin/LeetCode | /mymodules/BinaryTree.py | 2,014 | 4.125 | 4 | # First thing I will need to do is build my own binary tree and traversal algorithm
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(TreeNode):
def __init__(self):
self.root = None
def getRoot(self):
return se... |
731ef6aacb37e3191b45ba36b643f065338b341f | ashuChufamo/2048 | /2048.py | 12,970 | 4 | 4 | import random
class entry:
def __init__(self,matrix=[]):
self.matrix=matrix
def start (self):
'''starts the first matrix with the 2 elements non 0'''
size=eval(input('give size: '))
for temp1 in range(size):
temp1=[]
for temp2 in range (size):
... |
c0f739265e17e9ddb6b25f2d32f79f3b61111a47 | vaishali-khilari/COMPETITIVE-PROGRAMMING | /leetcode/rotate by one.py | 259 | 4.25 | 4 | Given an array, rotate the array by one position in clock-wise direction.
Example 1:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
5 1 2 3 4
code:-
def rotate( arr, n):
x=arr[n-1]
for i in range(n-1,0,-1):
arr[i]=arr[i-1]
arr[0]=x
|
60e7286a4e887beb242c2199a4fec4d4812af855 | AchWheesht/ProjectEuler | /problem19.py | 1,910 | 4.09375 | 4 | # You are given the following information, but you may prefer to do some research for yourself.
#
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on lea... |
f7dc2b706d6c988884c0346992f9931c7c17f25d | mly135/mycode | /PycharmProjects/Test/练习/20170914_异常.py | 979 | 3.515625 | 4 | #coding=utf-8
#成功示例
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容写入文件成功"
fh.close()
#报错示例
try:
fh = open("testfile", "w")
fh.read(10)
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容读入文件成功"
... |
149dedb97fcb64ac7dc87fa785022e7b1ac5e8fd | brudolce/codewars | /7-kyu/Sum of a sequence.py | 177 | 3.59375 | 4 | def sequence_sum(begin_number, end_number, step):
sum = 0
while begin_number <= end_number:
sum += begin_number
begin_number += step
return sum
|
6812581a48e9c7c9ea6e83c2cffd78fcd3edd959 | oppih/projecteuler-solve | /overComed/p035/p035.py | 1,411 | 3.890625 | 4 | #!/usr/bin/env python
"""
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
http://projecteuler.... |
2b79de18378c1bd2ffbe4bdf6273cb5fb7fa7b9b | Insookim0702/python_Algorithm | /중요노트/소수판별/에라스토테네스체2.py | 334 | 3.71875 | 4 | import math
def is_prim_num(n):
arr = [True for _ in range(n+1)]
print(arr)
for i in range(2, n+1):
if arr[i]:
j = 2
while i*j <=n:
arr[i*j] = False
j+=1
for i in range(2, n+1):
if arr[i]:
print(i, end=' ')
print(is_... |
78f6ea9c6fd77d69b176c7503f8a914cd0bd5173 | alihassanansari/PythonAssignment-1 | /Assignment 1/6. Two Value Addition.py | 253 | 3.734375 | 4 | ################################
#--- 6. Two Value Addition ---#
################################
input1 = int(input('Please First Number : '))
input2 = int(input('Please Second Number : '))
total = input1 + input2
print("Your Total is %.2f" %total); |
80864d286364cec9ba1f2a9acaf710db5ae688a7 | vishal-1codes/python | /FUNCTIONS/abs.py | 113 | 3.59375 | 4 | #The abs() function always returns a positive value
#Its take only one value
absolute = abs(-42)
print(absolute) |
f94bdc62231cbb24f69dc1aeaaa8650a5570868a | Kingcitaldo125/Python-Files | /src/string_conversion_object.py | 190 | 3.71875 | 4 | class Player(object):
def __init__(self, newname):
self.name = newname
def __str__(self):
return str("Hi, I'm ") + self.name
P1 = Player("Bob")
x = str(P1)
print(x)
|
c11c174ed244ee85052f94354445e19175ee2bf8 | godinenbicicleta/IntroComputation | /handlingExceptions/handlingExceptions3.py | 292 | 3.765625 | 4 | def readVal(valType, requestMsg, errorMsg):
while True:
val = input(requestMsg+' ')
try:
return(valType(val)) #converts string to valType
except ValueError:
print(val, errorMsg)
val = readVal(int, 'Enter an integer:', 'is not an integer')
|
0ec2578a82e72848494a2e99b004d464eebc98e9 | cihanyklmaz1/Ramazan-Cihan-YIKILMAZ | /Lesson 3/11-draw.py | 761 | 3.890625 | 4 | import math
#dikdörtgen çizme
def printRectangle(height,width):
for i in range(height):
print("* "*width)
#kare çizme
def printSquare(edgeSize):
printRectangle(edgeSize,edgeSize)
#daire çizme
def calculateIfPointIsInRadius(i, j, radius):
centerX = radius
centerY = radius
pointDistance = m... |
8f969b6c4b5afdf51bf811f6cd8473d103aaf80d | OZ-T/leetcode | /0/55_jump_game/main.py | 1,022 | 3.75 | 4 | class Solution:
def canJump(self, nums: list[int]) -> bool:
# pos marks the left most index, where it can reach to the end of the array
# the last element can reach itself,even its value is zero
# so, we initialize pos as len(nums)-1
pos = len(nums)-1
# searching backwards
... |
c24a434d814fdfcf157eeb6a0d646aeffc5afee6 | AyeAyeZin/python_exercises | /ex29.py | 453 | 4.15625 | 4 | people=20
cats=30
dogs=15
if people<cats:
print("Too many cats! The world is doomes!")
if people>cats:
print("Not many cats! The world is saves!")
if peopple<dogs:
print("The world is drooled on!")
if people>dogs:
print("The world is dry!")
dogs+=5
if people>=dogs:
print("People are greater than or ... |
8c7ab83cc7a2d37745ff4b9549e8e4b639e48100 | Chrisgarlick/Python_Projects | /My_Projects/Mean_median_mode.py | 517 | 3.84375 | 4 | import math
lst = [1, 4, 5, 67, 2, 3, 5, 6, 1, 23, 4, 6, 7, 1, 2, 2, 234, 3, 32, 1, 12, 2, 2]
# Mean - Add all up and divide by length
def mean(lst):
total = sum(lst)
average = total / len(lst)
return average
# Median - Sort and find middle number
def median(lst):
lst.sort()
length = len(lst)
... |
cda306d9d1e5ce61571b40d71f1776758c7b80bf | JohannLieberto/TicTacToe-Hyperskill | /tictactoe.py | 4,701 | 4 | 4 | """ How an amateur like me does it"""
def empty_grid():
print(9 * "-")
for i in range(3):
print("|" + ' ' * 7 + "|")
print(9 * "-")
class Tictac:
def __init__(self):
self.symbs = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.board = [[self.symbs[6], self.sym... |
0be5cd0830a8470ff598f0f733d50b5e2505296c | kaioraf/Python-3 | /Python3 oefening3-Func.py | 184 | 4.0625 | 4 | def printer(number, string):
for i in range(number):
print(string)
string = input("Which character")
number = int(input("How many times"))
printer(number, string)
|
9c1a8b860fea215ec033fc42820efaa9e8b4fb41 | chocolatebunny-0/Task7-isthisarealjob | /utils/confidence_score.py | 780 | 3.625 | 4 | '''Calculating prediction score of model'''
#Code for model creation before this part
#Model is CLASSIFIER
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.cross_validation import cross_val_score
#Making Confusion Matrix
CM = confusion_matrix(y_val, y_pred)
print("... |
9cbd4164d22208c3f4c701857ef7b14cd3241bee | RustPython/RustPython | /extra_tests/snippets/intro/3.1.2.10.py | 226 | 3.796875 | 4 | word = 'Python'
assert 'P' == word[0] # character in position 0
assert 'n' == word[5] # character in position 5
assert 'n' == word[-1] # last character
assert 'o' == word[-2] # second-last character
assert 'P' == word[-6]
|
cc70186af12aaa18ff9e26882dae1f3ae8c35947 | KadenRamirez/ICS2019_2020 | /PythonPractice.py | 859 | 3.765625 | 4 | import math
from math import sin
# ~ s= "the squirrel has landed"
# ~ s = s.replace(" ", "*")
# 012345678901234567890
# ~ print(s)
# ~ print( s[4:][:8])
#RUNTIME ERRORS
#LOGIC ERRORS
#SYNTAX ERRORS
#for(int i=0;i<10;i++)
# ~ for i in range(10):
# ~ print(i)
# ~ s="%5d%5d%5d"%(4,5,6)
# ~ print(s)
# ~ def multiplic... |
5915c54b98ba3bf3fd577f0f0ddaab74afbbd40f | chandni-asnani/Exercism | /raindrops/raindrops.py | 493 | 4.1875 | 4 | def convert(number):
if number% 3 == 0 and number%5 ==0 and number%7==0:
return "PlingPlangPlong"
elif number% 3 == 0 and number%5 ==0:
return "PlingPlang"
elif number%5 ==0 and number%7==0:
return "PlangPlong"
elif number%3 ==0 and number%7==0:
return "PlingPlong"
el... |
6f8ba403ae91be911b9f3779d19846a2474dc01e | CianLR/judge-solutions | /leetcode/valid_parentheses.py | 437 | 3.734375 | 4 | from collections import deque
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = deque()
open_to_close = {'{': '}', '[': ']', '(': ')'}
for b in s:
if b in open_to_close:
stack.append(open_to_close[b])
... |
fe62d10843442c2505574a49d38921e64506648f | birsandiana99/UBB-Work | /FP/ConnectFour/program.py | 6,593 | 3.640625 | 4 | from texttable import Texttable
from random import choice
from ctypes.test.test_array_in_pointer import Value
import unittest
class GameException(Exception):
def __init__(self, msg):
self._msg = msg
@property
def message(self):
return self._msg
'''
0 - empty sq... |
85c8fae12459b4065e6d261147b3eeccf9073ccb | dhesse/IN-STK-5000-Autumn-21---Exercises | /solutions/ex6_solution.py | 2,921 | 3.953125 | 4 | import pandas as pd
class Ex6:
"""We will solve various tasks using a data set containing information
about patients suffering from heart disease.
You have to complete the code to complete the tasks. The
data set is loaded for you, no need to do anything with this.
More information about the da... |
0bdcf7765f7e24b37c076017d1759c0752f6d45e | diegchav/chat-flask | /chat/utils.py | 365 | 4.21875 | 4 | def is_float(num):
"""
Check if a given number is of float type.
:param num: Number to check
:return: True if num is of type float, False otherwise
"""
if isinstance(num, str):
try:
f = float(num)
return True
except ValueError:
return False
... |
5c066536f687134c82f24780a3405c0917e3edf1 | devang191/algorithms_competitions | /codeforces/problem_set/545A.py | 374 | 3.515625 | 4 | import math
import sys
def main():
n = int(raw_input())
out = []
for i in range(n):
nums = map(int, raw_input().split())
good = True
for num in nums:
if num == 1 or num == 3:
good = False
break
if good:
out.append(str(i + 1))
print len(out)
if len(out) > 0:
pri... |
146a9b957eccedea833035cd71984ab929301d19 | jameskaron/MLDemo | /test_1/test.py | 442 | 3.796875 | 4 | # importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("nba.csv")
# retrieving rows by loc method
# row1 = data.loc[3]
# row1 = data.iloc[0][['Team', 'Position']]
row1 = data.iloc[0][['Team', 'Position']]
# retrieving rows by iloc method
# row2 = data.iloc[3]
row2 = data.i... |
a1cf12f93c5e4d4da70a39647231742985c2c90f | ambuilding/Python | /mitPython/inheritance/MITPerson.py | 1,037 | 3.8125 | 4 | class MITPerson(Person):
nextIdNum = 0 # next ID number to assign
def __init__(self, name):
Person.__init__(self, name) # initialize Person attributes
# new MITPerson attribute: a unique ID number
self.idNum = MITPerson.nextIdNum
MITPerson.nextIdNum += 1
def getIdNum(self):... |
d5d8a25e0d1473a4382ed6e020e08f0610a6fa7c | alonarenberg/AI | /previous_semester/hw0/part2/6.py | 315 | 3.5625 | 4 | #!/bin/python3 -tt
import sys
import random
def sub_list(list, num):
res = []
for i in range(num):
res.append(random.choice(list))
return res
def main():
l = list(range(1, 10))
num = int(sys.argv[1])
print(sub_list(l, num))
if __name__ == '__main__':
main()
|
c7847bc270884886a04563d7f0ba635b8d292b7d | Hz-Lin/wur_bioinfomatics | /Advanced_Bioinformatics/week12_python/r01_Variables_and_Some_Arithmetic/vasa.py | 983 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 11:33:32 2017
Rosalind exercise "Variables and Some Arithmetic"
@author: Huizhi Lin
"""
import sys
test = False
#define the values of a and b
if test == True:
#ask user input for values
a = int(input('Please enter a positive number a'))
... |
4ae20c669b5eb5837aa44055da75ca63e3616b8a | 7colorlotus/pythonLearn | /asyncIo/async_hello.py | 820 | 3.71875 | 4 | #hello()会首先打印出Hello world!,然后,yield from语法可以让我们方便地调用另一个generator。
#由于asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环。
#当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。
import asyncio
import threading
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThr... |
60cf8aba07a5d10a5a3cece8a3cf0f79f21392b7 | YevgenyY/Python_Course1 | /week4/noisy_int.py | 274 | 3.75 | 4 | import random
class NoisyInt:
def __init__(self, value):
self.value = value
def __add__(self, obj):
noise = random.uniform(-1, 1)
return self.value + obj.value + noise
a = NoisyInt(10)
b = NoisyInt(20)
for _ in range(3):
print(a + b)
|
658d107901268dcc79e348e1a2e43a8342e61c1d | wympiel/power | /power.py | 324 | 3.546875 | 4 | #TODO: create power function
def power(base, exp):
if exp == 0:
return 1
temp = power(base, exp // 2)
temp *= temp
return temp if exp % 2 == 0 else temp * base
def neg_power(base, exp):
neg = exp < 0
pos_result = neg_power(base, abs(exp))
return 1/pos_result if neg else pos_resu... |
593647742a21ae5a5e0f4d42543b8e2103243f9a | eronekogin/leetcode | /2023/maximum_ice_cream_bars.py | 601 | 3.5625 | 4 | """
https://leetcode.com/problems/maximum-ice-cream-bars/
"""
from collections import Counter
class Solution:
def maxIceCream(self, costs: list[int], coins: int) -> int:
cnt = Counter(costs)
maxCost = max(cnt.keys())
currCoins = coins
rslt = 0
for cost in range(1, maxCos... |
f8d121279803f9f6bca1e720760328209a9d8cca | Jeoungseungho/python-coding-study | /정승호/이상한_문자_만들기/solution.py | 236 | 3.515625 | 4 | def solution(s):
new_s = s.split(' ')
answer = ''
for word in new_s:
for i, spell in enumerate(word):
answer += spell.upper() if i % 2 == 0 else spell.lower()
answer += ' '
return answer[:-1]
|
47485303b074d898a9ddba1e7d6b08f3047ce28d | giovannaspro/CS50 | /PSET 7 - Houses/roster.py | 625 | 3.765625 | 4 | from cs50 import SQL
from sys import argv
#Checks if gives csv and txt files
if len(argv) != 2:
print("Incorrect number of command-line arguments.")
exit()
else:
# Open db
open("students.db","r").close()
db = SQL("sqlite:///students.db")
house_argv = argv[1]
line = db.execute("SELECT... |
22daee35842ee5f3361679b6168e87fac586056b | pliba/kaminpy | /references/2018/ch0-Calculator/v0/evaluator.py | 1,538 | 3.5625 | 4 | import collections
import operator
class EvaluationError(Exception):
"""Error while evaluating expression."""
def __init__(self, value=None):
self.value = value
def __str__(self):
msg = self.__class__.__doc__
if self.value is not None:
msg = msg.rstrip(".")
... |
5fa7d14085c7ce2337c79c6708b21d3f7b03fa57 | Aishu-1801/object-oriented-programming-python | /program3.py | 380 | 3.640625 | 4 | class Bank(object):
def __init__(self):
self.balance=0
def deposite(self,amount):
self.balance += amount
return self.balance
def withdraw(self,amount):
self.balance -= amount
return self.balance
chris = Bank()
chris.deposite(100)
chris.withdraw(22)
chrisLoan.ma... |
0af149ebe29b38b3916644207bde4213b89e4c59 | jiabaozhou/NLP-Spring-2021 | /a2-distrib/models.py | 6,792 | 3.625 | 4 | # models.py
import torch
import torch.nn as nn
from torch import optim
import numpy as np
import random
from sentiment_data import *
num_of_classes = 2
class FFNN(nn.Module):
"""
Defines the core neural network for doing multiclass classification over a single datapoint at a time. This consists
of matri... |
3b23d4cb566d59ed7b43ca73cb826a3a33889421 | patrickaduarte/Python | /ex007.py | 188 | 3.828125 | 4 | nota1 = float(input('Primeira nota do aluno: '))
nota2 = float(input('Segunda nota do aluno: '))
print('A média entre {:.1f} e {:.1f} é {:.1f}'.format(nota1, nota2, ((nota1+nota2)/2)))
|
97f71017939ad24aa120e883b5cb2a0a21c43f4e | NickKletnoi/Python | /01_DataStructures/02_StackQueue/02_StackWithQueues.py | 2,314 | 3.90625 | 4 |
#Copyright (C) 2017 Interview Druid, Parineeth M. R.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from __future__ import print_function
import sys
#Queue in python 2.7 has been r... |
bbf36d2aba22386e7591209ab12496e779fb7a91 | Faizah-Binte-Naquib/Program-List | /Factorial/11.py | 627 | 4.40625 | 4 | # ### 11. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequences the sum of two successive terms given the third term. Following are the first few term of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55…
#
# * Function: fibonacci()
# * Summary: finds fibonaci num... |
9a30ab85ded49b35d86a169829c05057e94ed956 | eabasir/algo | /basics/valid_parentheses/vp.py | 767 | 3.734375 | 4 | class Solution:
pairs = {'{': '}', '(': ')', '[': ']'}
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
stack: list = []
for c in s:
if(c in self.pairs):
stack.append(self.pairs[c])
# closing
else:
... |
1f153df65e1565482b97bc2af29b5cb5a893b550 | MinghuaJiang/learn-python | /class-advanced.py | 2,019 | 3.5 | 4 | #customized decorator
#class decotrator can only be used on function insteaed of class method
class tracer:
def __init__(self, func):
# Remember original, init counter
self.calls = 0
self.func = func
def __call__(self, *args):
# On later calls: add logic, run original
self.... |
a884fde4467f78fdfdc0c7c7912a3ab18a55f84e | HarshaaArunachalam/guvi | /code/82.py | 84 | 3.609375 | 4 | N,K=input().split()
N=float(N)
K=float(K)
product=N*K
print(format(product,'0.5f'))
|
ffe5aafb7a496a519bdb3292e77ed626903f32f9 | cpaszul/advent-of-code-2019 | /day3.py | 2,377 | 3.640625 | 4 | from collections import defaultdict
DEFAULT_INPUT = 'day3.txt'
def day_3(loc=DEFAULT_INPUT):
with open(loc) as f:
wire_a = f.readline().rstrip().split(',')
wire_b = f.readline().rstrip().split(',')
points = defaultdict(set)
steps_a = {}
x,y = 0,0
i = 1
for move in wire_a:
... |
42581f467b967e988762685bdae6751abfc79a57 | VPerrollaz/pyjanitor | /janitor/utils.py | 19,424 | 3.546875 | 4 | """Miscellaneous internal PyJanitor helper functions."""
import functools
import os
import sys
import warnings
from typing import Callable, Dict, List, Union
import numpy as np
import pandas as pd
from .errors import JanitorError
def check(varname: str, value, expected_types: list):
"""
One-liner syntactic... |
6b963b910e218b4c085ef93a176f757cf69432b2 | suhyeun/pythonStudy | /cospro.py | 2,441 | 3.671875 | 4 | # 후보2
def solution(password):
capital_count, small_count, digit_count = 0, 0, 0
for p in password:
if p >= 'A' and p <= 'Z':
capital_count += 1
elif p >= 'a' and p <= 'z':
small_count += 1
elif p >= '0' and p <= '9':
digit_count += 1
if c... |
1138568707c982bb04d899c605b92ee7ff622308 | ashlie-li/GeorgiaTech | /cs8803-ai-for-robotics/project2/partA.py | 14,669 | 4.3125 | 4 | """
Author: Vincent La; GTech ID: vla6
"""
##########
# === Introduction ===
#
# In this problem, you will build a planner that helps a robot
# find the best path through a warehouse filled with boxes
# that it has to pick up and deliver to a dropzone.
#
# Your file must be called `partA.py` and must have a class
... |
f7785e4d06edd1f6c3e4ec6390c29c07914bec20 | Lindisfarne-RB/GUI-L3-tutorial | /Lesson27.py | 4,990 | 4.5625 | 5 |
'''
Working with frames
In a tkinter frame you can set background colors and other things as parameters, but not with a ttk frame.
The good thing about frames is that if you need to rearrange your GUI, then you can just move the frames instead of each individual widget. In this task we're going to change our frames t... |
feefb455b20043375ebbe299c9f49923c73834b8 | AwesomeHunter/MaturyPython | /Matura2015Zad4/Matura2015Zad4.py | 1,078 | 3.59375 | 4 | def load_data(filename: str) -> list:
with open(filename, "r") as file:
return list(map(str.strip, file))
def zad_1(data: list) -> int:
return sum(1 for num in data if num.count('0') > len(num)//2)
def zad_2(data: list) -> int:
ans = 0
for num in data:
pom = 0
while num[pom] ... |
9aa02ef1e654f59737cee112a6cd00c097bba4ea | KaranbirSingh7/python3-sysadmin | /exercises/using_functions.py | 278 | 3.921875 | 4 | #!/usr/bin/env python3
# FUNCTION
def myPrinter(message, count):
for c in range(int(count)):
line = c+1
print(f"\n#{line}: {message}")
# MAIN EXECUTION
message = input("Favourite sports? ")
count = input("Repeats: ").strip()
myPrinter(message, count)
|
2367961dc3e9cfea9fb4448905e71807c8fe89c2 | RoboJackets/robocup-software | /rj_gameplay/stp/role/__init__.py | 7,525 | 3.671875 | 4 | from enum import IntEnum
from typing import Optional, Protocol
import stp.rc
from rj_msgs.msg import RobotIntent
from abc import ABC, abstractmethod
BIG_STUPID_NUMBER_CONST_FOR_UNASSIGNED_COST_PLS_CHANGE = 9999
class Role(ABC):
"""Complex single-robot role, such as Goalie or Striker. Uses Skills to achieve be... |
6f78442c2ba92f099a692a2a819790b0bdc4079d | mbkim95/Algorithm | /Leetcode/best_time_to_buy_and_sell_stock.py | 371 | 3.640625 | 4 | from typing import List
import sys
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
min_price = sys.maxsize
for price in prices:
min_price = min(min_price, price)
profit = max(profit, price - min_price)
return profit
prices = [7, ... |
833f968f1deb7526017ab296c4765daeea6b7867 | scikit-learn/scikit-learn | /examples/model_selection/plot_learning_curve.py | 6,830 | 4.0625 | 4 | """
=========================================================
Plotting Learning Curves and Checking Models' Scalability
=========================================================
In this example, we show how to use the class
:class:`~sklearn.model_selection.LearningCurveDisplay` to easily plot learning
curves. In addit... |
6d9de3d6b2be3a55a53e962fcf42329413fd0180 | Touchhub/Ahri | /lian/用户名密码.py | 255 | 3.53125 | 4 | name_="250375052"
passward_="2503750520"
import getpass
name=input("name: ")
passward=input("ward: ")
if name_==name and passward_==passward:
print(name,passward)
print("hello {name} welcome login...".format(name=name))
else:
print('fuck off') |
d12bd2c29cc62eda77256de51c20231727202b43 | sarureddi/midelement | /middle.py | 206 | 3.5 | 4 | p1=input()
q1=list(p1)
r1=len(q1)
if(r1%2!=0):
s1=r1/2
t1=round(s1)
q1[t1]='*'
print(*q1,sep="")
else:
s1=r1/2
t1=round(s1)
q1[t1-1]='*'
q1[t1]='*'
print(*q1,sep="")
|
2f3fb0c494b884cf39710024ebb7c46603cc66ae | Bharadwaj-G/Maximl-labs-python- | /substring.py | 1,041 | 4.1875 | 4 | #max_sistinct_char() - function to return the max distinct characters in a string
def max_distinct_char(S):
distinct_char = set(S)
max_distinct_char = len(distinct_char)
return max_distinct_char
#substrings() - function to return all the substrings as a list
def substrings(S,n):
l1 = []
for i in rang... |
2a2a2adbefc6704b1e993bb2a7bf5e9bc2325fc5 | hauphanlvc/CS114 | /tuan1.2/XuLyChuoi.py | 217 | 3.5625 | 4 | def Solve(x):
x = x.lower()
NguyenAm= ['a','o','y','e','u','i']
Res = ''
for i in x:
if i not in NguyenAm : Res+='.'+i
return Res
x = str(input())
print(Solve(x))
|
d278d8c5efedbd61317118887461b052690dd605 | wulinlw/leetcode_cn | /常用排序算法/quicksort.py | 828 | 3.8125 | 4 | #!/usr/bin/python
#coding:utf-8
# 快速排序
def partition(arr,low,high):
i = ( low-1 ) # 最小元素索引
pivot = arr[high]
for j in range(low , high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
# print(i,arr)
arr[i+1],arr[... |
3283ef4580d889c9189523a282a5bcbd7cc0e29a | frarteaga/myScripts | /Python_mods/gcd.py | 723 | 3.890625 | 4 | #!/usr/bin/python
__author__ = "Frank Arteaga Salgado"
import sys
def gcd(a, b):
'''Computes the Greatest Common Divisor of a and b using the standard quadratic time improvement to the Euclidean Algorithm.
Returns the GCD of a and b.'''
if b == 0:
return a
elif a == 0:
return b
count = 0
if a < 0:
a = -... |
941074af565321169866cc6008c8f2387043f91c | rathalos64/hgb-algo5 | /03_kmeans_gmm/kmeans/lib/cluster.py | 1,892 | 3.796875 | 4 | #!/usr/bin/env python
import math
from functools import reduce
class Clusters:
def __init__(self):
self.clusters = {}
def __iter__(self):
return iter(self.clusters.values())
def append_cluster(self, cluster):
self.clusters[cluster.id] = cluster
def append_to_nearest_cluster(self, observation, dist, D):
... |
57b8940ebf63261511c2916f3ccbbb8a1d657b8d | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/056 Функции all и any/02 Проверка условий.py | 635 | 4.09375 | 4 |
#a = 100
a=99 # all уже не будет подходить и выдаст false так как 1 условие не выполняется
condition_1 = a%2==0
condition_2 = a>50
condition_3 = a<1000
print(all([condition_1,condition_2,condition_3]))
print(any([condition_1,condition_2,condition_3]))
#a = 100
a=1 # all уже не будет подходить и выдаст false
condi... |
89f6d5af63727ffa441b87095691373fdd4aacaf | Superilosa/python-gr.19 | /homework2.py | 2,785 | 4.03125 | 4 | #1
class Book:
def __init__(self, name, author, year, pages):
self.__name = name
self.__author = author
self.__year = year
self.__pages = pages
def info(self):
return f"სახელი: {self.__name}, \n ავტორი: {self.__author} \n გამოშვების წელი: {self.__year} \n გვერდე... |
8e6509bc70f28c46f1cbb84bf9e8a0b812ff7247 | courtney-rosenthal/python-examples | /dice.py | 157 | 3.609375 | 4 | from random import randint
print("Rolling two dice ...")
a = randint(1, 6)
b = randint(1, 6)
print("You rolled a", a, "and a", b)
print("Your total is", a+b) |
f1f1b376cf49e647cbc3772fddca07374471f9a0 | arnabid/QA | /graphs/DGraph.py | 6,173 | 3.90625 | 4 | class DGraph(object):
"""
Directed graph - adjacency list representation using dictionaries
node_neighbors[node] = {}, the value pointed to by each node is also a dictionary.
This dictionary represents its adjacent nodes along with the edge weights.
Example: node_neighbors[u][v] = wt --> weight... |
25eb36a5664a3bdb0e6b45fce3a471e77be56da1 | ImLemni/ada-epfl | /project/ada/ordering.py | 496 | 4.28125 | 4 | def default_comparator(left, right):
"""
Comparator function using the comparison operators defined on the compared objects.
It returns `-1` if `left < right`, `0` if `left == right` and `1` otherwise.
This can be used for custom sorting functions.
:param left: Left element to compare
:param ri... |
03eb14f39d99fd0ef8ed8590fef3440468729beb | alok-kumar8765/basic_python_practicse | /practice.py | 1,315 | 3.625 | 4 | #***** unzip file *************
import shutil
from typing import Pattern
shutil.unpack_archive('unzip_me_for_instructions.zip','','zip')
#let try to open with python
with open('extracted_content/Instructions.txt') as f:
content =f.read()
print(content)
'''
unzip_me_for_instructions.zip= it represent the name of... |
6e8f7a1d93b0c9ee52504ac069b183f0553eb038 | sambluestone/CSCI-111-Projects | /project9/rainbow.py | 1,367 | 4.15625 | 4 | """
Author: Evan Phaup
File: rainbow.py
Project 9
Makes an image rainbow-like
"""
from images import Image
def main():
colors = [(255, 0, 0),
(255, 255, 0),
(0, 255, 0),
(0, 255, 255),
(0, 0, 255),
(255, 0, 255)]
img = Image(... |
1c9511e6c99cc43439856697f88ec7c552cb933b | nikhilgurnani/dailyproblems | /maximum_product_of_3_numbers.py | 745 | 4.625 | 5 | """
You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array.
Example:
[-4, 4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128.
[ 5, 6, 8, -4, -9, 0, 1 ]
[ -9, -4, 0, 1, 5, 6, 8 ]
https://www.geeksforgeeks... |
cdfffdee08eb5d5d4a60f84a664bd5b6d47abdf5 | damarisgch/Funciones | /invertir.py | 394 | 3.796875 | 4 | #Invertir un número (Ejm entrada =123,salida = 321)
numero_ingresado = (input("Ingrese un número Entrada: "))
revertir = 0
try:
valor = int(numero_ingresado)
while valor > 0:
residuo = valor % 10
revertir = (revertir * 10)+ residuo
valor //=10
print('Salida: ', revertir)
except V... |
f4bc8c540516c606da58ab1c894094f368e6caa1 | hmswrth/guvi-codekata | /pro_11.py | 79 | 3.546875 | 4 | x=int(input())
if x%2==0:
print(x*(x//2)-(x//2))
else:
print(x*(x//2))
|
55defb5d283a8162816c8af5c8ccb759391efdf1 | engrjislam/uva_python | /uva10738.py | 1,026 | 3.5 | 4 | '''
uva: 10738
description: https://uva.onlinejudge.org/external/107/10738.pdf
'''
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
... |
8d7f189c14419c7c9787d8e6a7511d4156798d9f | nimu77/Sprint-Challenge--Data-Structures-Python | /singly_linked_list/singly_linked_list.py | 3,022 | 4.21875 | 4 | class Node:
def __init__(self, value, next_node=None):
# the value that the node is holding
self.value = value
# reference to the next node in the linked list
self.next_value = next_node
# method to get the value of the node
def get_value(self):
return self.value
... |
ae483d8422077143f276a4defe1c8a0fc2cc5f29 | cvitanov/reducesymm | /blog/burak/KuramotoSivashinsky/KushnirRokhlin.py | 1,313 | 3.671875 | 4 | #!/usr/bin/env python
"""
http://www.cs.yale.edu/publications/techreports/tr1435.pdf
A Highly Accurate Solver for Stiff Ordinary Differential
Equations
Dan Kushnir∗ Vladimir Rokhlin†
"""
import numpy as np
def KushnirRokhlin(f, x0, t)
"""
USAGE:
x = KushnirRokhlin(f, x0, t)
INPUT:
f - fu... |
1d4d8e943c3d0d9705a4c88a92574ef9c977de84 | solnotka/learn-homework-1 | /6_exception1.py | 1,349 | 3.828125 | 4 | """
Домашнее задание №1
Исключения: KeyboardInterrupt
* Перепишите функцию ask_user() из задания while2, чтобы она
перехватывала KeyboardInterrupt, писала пользователю "Пока!"
и завершала работу при помощи оператора break
"""
def ask_user():
"""
Замените pass на ваш код
"""
questions_dict... |
2b023e9f479ac59567b508d6f7d9b3e2a387bb77 | jdanray/leetcode | /longestIncreasingPath.py | 589 | 3.53125 | 4 | # https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
class Solution(object):
def longestIncreasingPath(self, matrix):
deltas = [[-1, 0], [1, 0], [0, -1], [0, 1]]
M = len(matrix)
N = len(matrix[0])
memo = {}
def dp(i, j):
if (i, j) in memo:
return memo[i, j]
res = 1
for (di, d... |
a538f68fa6e69958f5204d32a617395ec62c1513 | BrunoFafibe/prova14-09 | /ex3/cdg.py | 835 | 3.671875 | 4 |
class Carro:
def __init__(self, marca, velocidade_max=0, quilometragem=0):
self.marca = marca
self.quilometragem = quilometragem
self.velocidade_max = velocidade_max
def __str__(self):
return f'Carro {self.marca}'
def ligar(self):
print(f'{self} ligado.')
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.