blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
68c773b526dc0b3601274352a1d15c327a49cfa0 | ahmetcanozturk/HackerRank-ProblemPortfolio | /Python/circular-array-rotation.py | 949 | 3.90625 | 4 | # solution to the HackerRank problem "Circular Array Rotation"
# https://www.hackerrank.com/challenges/circular-array-rotation/problem
# For each array, perform a number of right circular rotations and return the values of the elements at the given indices.
# Ahmetcan Ozturk
def circularArrayRotation(a, k, queries):
... |
c05b04d1763be126ae5c0ae3d1486a45b92ef017 | codewithsandy/Python-Basic-Exp | /15 TryCatch_Exception_Handling/first.py | 190 | 3.828125 | 4 | print("Enter Num 1 : ")
num1 = input()
print("Enter Num 2 : ")
num2 = input()
try:
print("Sum = ", int(num1)+int(num2))
except Exception as e:
print(e)
print("\tThis is important") |
e78c6a1c3d2378af649337f924fb5d31e593b14b | dmc87/ASCIIencryption | /ASCII Block Cipher.py | 19,223 | 3.71875 | 4 | # Darcy McIntyre, 10522336
# Created 27/03/2021
# Meet Alice next to the fridge in Building 18 at ECU.
# 1100111
def ascii_to_binary(plaintext): # This function converts text to binary via decimal
value = '' # and spits it out in 7 bit strings for easy reading
for character in p... |
4530924dc591135a544cd52bed96fff9031bc220 | verifier-studio/python-data-structures-algorithms | /algorithms/sort/shell_sort.py | 616 | 3.5 | 4 | '''
希尔排序
'''
'''
可以理解为通过步长优化的插入排序
'''
def shellSort(arr):
length = len(arr)
# 步长
gap = length // 2
while gap >= 1:
for k in range(0, gap):
for i in range(k+gap, length, gap):
for j in range(i, 0, -gap):
if arr[j] < arr[j-gap]:
... |
a0b5b5829c963418c9df656111ff65fad0154150 | khp3040/Python-Demo-In-Spyder | /CaseStudy_With_Cart/check_quantity.py | 841 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 18:05:15 2021
@author: 0014CR744
"""
class Quantity():
def quantity():
try:
quant = int(input("Enter Quantity you wish to purchase : "))
return quant
except ValueError:
print("Please enter a number and not a str... |
cead83ed5601e75dc5fda3aa6468b6cd590ca783 | TianyaoHua/LeetCodeSolutions | /Letter Combinations of a Phone Number/Letter_Combinations_of_a_Phone-Number.py | 912 | 3.53125 | 4 | class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
digit2str_map = {'1': [1,"*"],'2': [3,"abc"],'3': [3,"def"],'4': [3,"ghi"],'5': [3,"jkl"],'6': [3,"mno"],'7': [4,"pqrs"],'8': [3,"tuv"],'9': [4,"wxyz"],'0': [1," "]}
... |
e8adc5007f04e288d6c13778fce184ebec2313df | YitingWang25436/Animal-Crossing-exploration | /What recipes can I make or are close to make?.py | 9,748 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# 
# 
#
# In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what ... |
6af3ea24e38c1638d4fc86ccd1bc76914f8e1591 | daniel-reich/turbo-robot | /662nTYb83Lg3oNN79_19.py | 922 | 3.953125 | 4 | """
Given a list of four points in the plane, determine if they are the vertices
of a parallelogram.
### Examples
is_parallelogram([(0, 0), (1, 0), (1, 1), (0, 1)]) ➞ True
is_parallelogram([(0, 0), (2, 0), (1, 1), (0, 1)]) ➞ False
is_parallelogram([(0, 0), (1, 1), (1, 4), (0, 3)]) ➞ True
... |
03a4dba0f142ed9f5573fbb33e6769beaa72898a | malipalema/python-journey | /16511111004Magret.p75.py | 299 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 6 14:32:06 2019
@author: Pale
"""
def exponential(n,x):
sum=1
for i in range(n,0,-1):
sum=1+x*sum/i
print("e(x) is about= ",sum)
n=int(input("Enter the nth term: "))
x=int(input("Enter a number: "))
exponential(n,x) |
f0d8fc01da1e9b86fbb365f4704ca6514870a14f | JonahMerrell/LinearAlgebraPackage | /VectorMethods/vector_1norm.py | 440 | 3.578125 | 4 | '''
coding language: Python 3.7.0
written by: Jonah Merrell
date written: October 29 2019
written for: Homework4 Task2
course: Math 4610
purpose: Calculate the 1-norm of a vector
'''
def vector_1norm(vector):
sum = 0.0
for i in range(len(vector)):
sum +=... |
cb3381ee38f9e5135aa753e19b555e71166d968c | dataAlgorithms/algorithms | /recurBacktrack/hanoiTower.py | 3,852 | 4.03125 | 4 | '''
Solve tower of hanoi using recursive way
'''
def towerOfHanoiUsingRecur(n, from_rod, to_rod, aux_rod):
if n == 1:
print "Move disk 1 from rod", from_rod, "to rod", to_rod
return
towerOfHanoiUsingRecur(n-1, from_rod, aux_rod, to_rod)
print "Move disk", n, "from rod", from_rod, "to rod",... |
0d729431796f1e012cb745894ff64b701bc9b58b | Gaurav927/Dynamic-Programming | /buy_sell_stocks_1.py | 951 | 3.625 | 4 |
from functools import lru_cache
class Stock:
def maxProfit(self, share_price):
@lru_cache(maxsize=None)
def get_best_profit(day, have_stock):
if day<0:
return 0 if not have_stock else -float('inf')
price = share_price[day]
... |
26124c28b6f468c1b21f56e953867fed85f43981 | YONGJINJO/Python | /Algorithm/Dynamic Programming/fib_tab.py | 198 | 3.765625 | 4 | def fib_tab(n):
fib = [0, 1, 1]
for i in range(3, n + 1):
fib.append(fib[i - 1] + fib[i - 2])
return fib[n]
# 테스트
print(fib_tab(10))
print(fib_tab(56))
print(fib_tab(132)) |
2523914b51897da2d9212651792802377356a454 | vbarrera30/python-a-fondo | /Capitulo_4/clase_definiendo__len__.py | 660 | 3.921875 | 4 | class Planta:
def __init__(self, nombre, tipo, altura):
self.nombre = nombre
self.tipo = tipo
self.altura = altura
def __eq__(self, otra_planta):
return self.tipo == self.tipo
def __gt__(self, otra_planta):
return self.altura > otra_planta.altura
def __ge__(sel... |
cae4413049f1682975d5854b94530771d6e06fa4 | vijay2249/stress-relief | /copies.py | 4,105 | 3.828125 | 4 | import os
import sys
import hashlib
import send2trash
def usage():
print("[+] python file.py <folder1> <folder2> <folder3> delete -> to permanently delete the repeated files")
print("[+] python file.py <folder1> <folder2> <folder3> trash -> to send the repeated files to trash/recycle bin")
print("[+] pyt... |
07d6116ad1fcc5a0abc6a4bc4c0923a08e2ca1d4 | syeeuns/week1-5_algorithm | /week1_algorithm/problem/하노이탑.py | 527 | 3.546875 | 4 | # 하노이탑 원반 개수 n개면 이동 횟수 2^n -1
def move(n, start, stop):
if n == 1:
print(f'{start} {stop}')
return
else:
move(n-1, start, 6-start-stop)
print(f'{start} {stop}')
move(n - 1, 6 - start - stop, stop)
def move_big(n, start, stop):
if n == 1:
return
else:
... |
0095b71fdeffcb27e7c71e626a286e28035d0f50 | caiosuzuki/exercicios-python | /ex035.py | 416 | 4.1875 | 4 | print('-=-'*8)
print('Analisador de Triângulos')
print('-=-'*8)
c1 = float(input('Digite o comprimento da primeira reta: '))
c2 = float(input('Digite o comprimento da segunda reta: '))
c3 = float(input('Digite o comprimento da terceira reta: '))
if c1 < c2 + c3 and c2 < c1 + c3 and c3 < c1 + c2:
print('Essas três ... |
ffd35cfdf67267417a3dae2045200a72de61f52e | AndrewW-coder/Coding-class | /difficult/games/blackjack.py | 2,703 | 3.8125 | 4 | import random
your_decision = 0
###########################################
Ace = 1
King = 10
Queen = 10
Jack = 10
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 10]
card1 = random.randint(1, 10)
card2 = random.randint(1, 10)
card3 = random.randint(1, 10)
card4 = random.randint(1, 10)
your_value = card1 + card3
d... |
df0d4e91567fd96b69d01a4f06eab6925478215b | 11lixy/Little-stupid-bird | /even_or_odd.py | 478 | 4.125 | 4 | number = input("Enter a numbr, and I'll tell you if it's even or odd: ")#input让程序暂停运行,等待用户输入一些文本
number = int(number)#函数int()将输入转换为数值
if number % 2 == 0:#运算符%将两个数相除,返回余数.一个数number和2执行求模运算,余数为0,就是偶数。
print("\nThe number " + str(number) + " is even.")#str函数转换为字符串输出
else:
print("\nThe number " + str(number)... |
1834461ee3b46ef0c8245a42061f1b33fdd67a4d | vik-jhun/word_ladder | /word_ladder.py | 2,999 | 4.1875 | 4 | #!/bin/python3
from collections import deque
import copy
def word_ladder(start_word, end_word, dictionary_file='words5.dict'):
'''
Returns a list satisfying the following properties:
1. the first element is `start_word`
2. the last element is `end_word`
3. elements at index i and i+1 are `_adjacen... |
0733166d40bc1807d9c95c5f89228da93d15bb0d | HermanLin/CSUY1134 | /labs/lab8.py | 260 | 3.515625 | 4 | def is_balanced(inp_str):
lefty = "([{"
righty = ")]}"
tmp_stack = ArrayStack()
for i in inp_str:
if i is.in lefty:
tmp_stack.push()
else:
#is of same type as stack.top()
#if not, return false |
44063cf1001c74827325153186428f80db586ae4 | achisum94/projects | /portfolio/typing speed.py | 475 | 3.65625 | 4 | print('welcome to the first interview')
print('please enter your typing speed')
typing_speed=int(input())
if typing_speed>60:
print('congratulations')
print('you passed the first interview')
print('the company will contact you')
print('later regarding the second interview')
else:
print('sorry')
... |
8579b36f40a906a495a48495d7950183c4c6058f | aroseartist/Lessons-In-Python | /Ch5-Playground2.py | 2,262 | 4.3125 | 4 | # ################# NUMBER LOOP ################# #
# Write a program which repeatedly reads numbers until the user enters "done".
# Once "done" is entered, print out the total, count, and average of the numbers.
# If the user enters anything other than a number, detect their mistake using
# try and except and print an... |
c7dc669aee53df98168e24b2d7329ec3d3f85fd0 | immanuel-odisho/ASTM-Material-Load-Blast | /src/SeqServices.py | 1,525 | 3.9375 | 4 | ## @file SeqServices.py
# @title SeqServices
# @author Immanuel Odisho
# @date Feb/7/2018
## @brief will check if a sequence of numbers is ascending
# @param X is the sequence of numbers
# @return boolean
def isAscending(X):
for i in range(0,len(X)-1):
if (X[i+1] >= X[i]):
pass
else:
return False
return ... |
7e9562dd4cf034ae114fee62ef76f735eb9fd4ec | Krishrawat/Rock-paper-scissors--lizard-spock | /JUST A MINI PROJECT1.py | 1,131 | 4 | 4 | #BY_KRISH_RAWAT
import random
def name_to_number(name):
if name=="Rock":
return 0
elif name=="Spock":
return 1
elif name=="Paper":
return 2
elif name=="Pizard":
return 3
elif name=="Scissors":
return 4
else:
print("invalid input")
... |
7c90844dc5e7f271433e67d6f3c506226e659188 | S4RT-4K/VIRANK | /virank.py | 1,391 | 3.5 | 4 | import os
import time
import sys
time.sleep(1)
os.system('clear')
print("\033[1;32;40m ")
os.system("figlet VIRANK")
print(" Developer: S4RT-4K")
print(" VERSION: 1.0")
print(" ")
First_name = input("\033[1;32;40m Your First Name:- ")
if len(First_name) == 0:
print(" ")
print("Please Enter Your First Name")
pr... |
32192c22ffa96f39657dd551593f1366a4af401a | Tiger-tech893/Physics-with-Python | /Getting acceleration due to gravity.py | 1,148 | 3.546875 | 4 | import pyttsx3
import time
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
speak("This is program for finding acceleration due to gravity of any planet whose mass and radius is given")
... |
e0a74e90d8516839775df30b4143eea4ef51c89e | VBres/RobotObjectPerception | /color_detection/src/rgb2hsv.py | 2,112 | 3.640625 | 4 | import numpy as np
#Function that takes a RGB image and returns the corresponding HSV image
# INPUT : (nbPixels,3) data, the image to convert
# size, the size of the image
# OUTPUT : (nbPixels,3) imageHSV, the HSV image as an array
# see http://www.rapidtables.com/convert/color/rgb-to-hsv.htm for more explan... |
dfff319d36e9a69226858dc08009530f245e6c1f | smchng/Image-Editing | /cmpt120YAIP.zip/main.py | 12,133 | 3.5 | 4 | # CMPT 120 Yet Another Image Processer
# Starter code for main.py
# Author: Samantha Chung
# Date: December 7 2020
# Description: Multiple piel manipulation functions that can be used to edit a photo
# - This file is where all the functions are called and the use interface is created and shown
import cmp... |
86eae8e6560ca36102342a16c0d6692d38130c90 | dshmatkou/S7_TestingLabs | /5/task_5.py | 3,503 | 3.890625 | 4 | from __future__ import unicode_literals, absolute_import
import collections
from random import randint
KEY_FILE = 'key.txt'
def is_prime(n):
"""Check if n is prime
:param n: number > 2
:type n: int
:rtype: bool
"""
if n == 2:
return True
if n < 2:
return False
k = ... |
446658d96fb3ded704d0fc3c34be1be33c729381 | xiyangxitian1/heima_learn | /leetcode/二叉树/二叉树展开成链表.py | 1,362 | 3.96875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root i... |
6d2243fab316c2c8c2dc4eaaef8e47e60ae4256e | Danielhsuuu/LearnPythonTheHardWay | /ex32.py | 1,141 | 4.59375 | 5 | #The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
#You can just go elements = range(0,6)
#there are many functions of list: add, contains, delitem, delslice, eq, ge, getattribute, getitem, getslice, gt, iadd, etc.
the_... |
ccf76bea71ec4666bc4dfce5edd1e29ae7381efa | myroom9/python-practice01 | /14.py | 1,113 | 3.796875 | 4 | # 문제14
# 숨겨진 카드의 수를 맞추는 게임입니다.
# 1-100까지의 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는 게임입니다.
# 아래의 화면과 같이 카드 속의 수가 57인 경우를 보면 수를 맞추는 사람이 40이라고 입력하면
# "더 높게", 다시 75이라고 입력하면 "더 낮게" 라는 식으로 범위를 좁혀가며 수를 맞추고 있습니다.
# 게임을 반복하기 위해 y/n이라고 묻고 n인 경우 종료됩니다.
import random
random_value = random.randint(1, 100)
user_select = 'y'
count = 1
p... |
af4f32cef965ce65049262fa46ae922039448c9c | geniousisme/CodingInterview | /leetCode/Python/208-implementTrie.py | 2,056 | 3.9375 | 4 | '''
TC: O(N) per action
SC: O(1)
'''
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.is_string = False
self.leaves = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
... |
4230ef1b88d2bbabc2185e4edee27559bf7c59b8 | JosiahMc/python_stack | /python_fundamentals/muliplication.py | 581 | 3.96875 | 4 | for row in range(0, 13):
str_row = []
str_format = "{0:{width}} {1:{width}} {2:{width}} {3:{width}} {4:{width}} {5:{width}} {6:{width}} {7:{width}} {8:{width}} {9:{width}} {10:{width}} {11:{width}} {12:{width}}"
if row == 0:
str_row.append("x ")
pass
for col in range(0, 13):
if (... |
f7aca5c34a50332d12895770269801296e32e3be | Pie-R-Square/ExpenseRecorder1 | /SQLite_Basic.py | 1,129 | 3.9375 | 4 | import sqlite3
# create data base
conn = sqlite3.connect('Expense.db')
# create operater
c = conn.cursor()
# create table
'''
'Details(details)'
'Rate(rate)'
'Quantity(quantity)'
'Discount(discount)'
'Total(amount)'
'Timestamp(now)'
'Transaction ID(transactionID)'
'''
c.execute("""CREATE TABLE IF ... |
38816b78c89acf4942e65d0715349edf907ad1d7 | vedika000lodha/c97_project | /c97.py | 515 | 4.21875 | 4 | import random
print("number guessing game")
number = random.randint(1, 9)
chances = 0
while chances < 5:
guess = int (input("guess a number between 1 - 9 : "))
if guess == number:
print("Congrats u won!!")
break
elif guess < number:
print("ur guess was too low : guess a number hi... |
9508415755919213c4735e9bdf00048cb7aad99f | sebaspasker/Competitive | /CodeWars/5 kyu/first_non_rep_char.py | 212 | 3.609375 | 4 | def first_non_repeating_letter(string):
string_lower = string.lower()
for i in range(0, len(string_lower)):
if string_lower.count(string_lower[i]) == 1:
return string[i]
return ''
|
02893020480221fc1df16c5af2f71c2b16d6bfeb | INNOMIGHT/hackerrank-solutions | /LinkedLists/deleting_a_node.py | 580 | 3.71875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def delete_node(self, position):
pointer = self.head
for i in range(position - 1):
pointer = pointer.next
temp... |
ff8761800538e485b2e06c1c5267d2a8a2d50110 | Dasem/psu | /cripta/utils/eiler.py | 1,076 | 3.734375 | 4 | #!/usr/bin/env python3
# coding: utf8
import sys
n = int(sys.argv[1])
def step(deg, osn, mod):
acc = 1
summ=osn
while deg != 0:
if deg % 2 != 0:
acc=(summ*acc)%mod
summ=(summ*summ)%mod
deg//=2
return acc
def ferma_test(a, p):
return step(p-1, a, p) == 1
def e... |
20f9d3923f548cc1937c59f6e6934105f41648ee | sabb1r/ProjectEuler | /problem7.py | 565 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 15:04:26 2018
@author: sabbir
"""
from math import sqrt
def is_prime(num):
if num < 2:
return False
elif num == 2:
return True
elif num % 2 == 0:
return False
for i in range(3, int(sqrt(num))+1, ... |
fa390ef1c1fcf9183ce45b89871dcceff44374e8 | ashjambhulkar/objectoriented | /LeetCodePremium/101.symmetric-tree.py | 735 | 3.953125 | 4 | #
# @lc app=leetcode id=101 lang=python3
#
# [101] Symmetric Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, ... |
df3882dbb144e1ae14bc2dc6213929a59555ceb2 | JaoLucass/atividades-de-poo | /conta.py | 1,343 | 3.703125 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite, data_abertura):
self.numero = numero
self.titular = titular
self.saldo = saldo
self.limite = limite
self.data_abertura = data_abertura
def deposita(self, valor):
self.saldo += valor
... |
13e7a0419643d87c883a97918f7dac7d8c38fa1c | logic27/Codes | /DSA codes/DSL_assignment_3.py | 3,501 | 4.03125 | 4 | class Matrix:
def __init__(self):
self.matrix = []
self.row = 0
self.col = 0
def get_mat(self):
self.row = int(input("Enter no of rows in matrix :"))
self.col = int(input("Enter no of columns in matrix :"))
self.matrix = [[int(input("enter element")) for i in ran... |
ebded9516b55eb209e1e4f341d2448d6f332cf2b | jcebo/pp1 | /04-Subroutines/16.2.py | 157 | 3.65625 | 4 | def czytajLiczbe():
x=float(input("Podaj pierwsza liczbę: "))
y=float(input("Podaj drugą liczbę: "))
print(f"suma tych liczb to: {x+y} ")
|
15977e97daf18502cf94fa2752c6bd5f3842f16f | NPHackClub/BeginnerRoom-2020 | /Week 10 - math/Week 10 - Math.py | 302 | 4.125 | 4 | #User input and statement
n = int(input("Enter number: "))
print("multiplication table of", n)
#Multiplication of n to 10
for x in range(1,11):
print(n*x)
#Sum of all numbers until n and statement
print("sum of all numbers until", n)
total = 0
for y in range(n+1):
total += y
else:
print(total) |
ff0fd1569f4c8fa095a543522cd80c3547abfffc | MadDogofDarkness/data-stuff | /inter.py | 2,258 | 4.0625 | 4 | syntax = ["the syntax of the language is each operation is on a single line",
"each operation can have one or more operators",
"no one function name or operator can be longer than 4 characters",
"new functions can be defined"]
functions = ["low", "big", "add", "sub", "mult", "div", "deff"]... |
b1d50d7863f3efbe15208fa669cd926958abb931 | Vijendrapratap/Machine-Learning | /Week2/Tuple/6. WAP to check whether an element exists within a tuple.py | 298 | 4.125 | 4 | """
Write a Python program to check whether an element exists within a tuple.
"""
new_tuple = (12, 23, 34, 45, 56, 67, 78)
element = int(input("Enter element : "))
if element in new_tuple:
print("{} is present in tuple ".format(element))
else:
print("{} is not present in tuple".format(element)) |
c58d807653035847ec8efd10c643e4d51099b2f5 | thewritingstew/lpthw | /ex30.py | 711 | 4.21875 | 4 | people = 30
cars = 40
trucks = 15
# checks to see if there are more cars than people
if cars > people:
# if there are more cars, it prints this
print "We should take the cars."
# otherwise it checks to see if there are less cars than people
elif cars < people:
# and if so it prints this
print "We shoul... |
98e1ec11d2c48ca3bb1af3e3582a0c9c1762e5d0 | Brinda2510/Assignment5 | /a.py | 2,803 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
import cv2
import pandas as pd
num = ["TRUE" if i%2==0 else "FALSE" for i in range (1301)]
print(num)
import functools
q=range(1,10)
print (functools.reduce(lambda x,y:x*y,q))
def f(x):
def g(y):
return y +... |
d4ceb2b07f26490f4e492c96ac6890c527cf923d | dewlytg/Python-example | /48-sched调度模块 | 1,242 | 3.71875 | 4 | #!/usr/bin/python
#coding=utf-8
"""
通过调用scheduler.enter(delay,priority,func,args)函数,可以将一个任务添加到任务队列里面,当指定的时间到了,就会执行任务(func函数)。
delay:任务的间隔时间。
priority:如果几个任务被调度到相同的时间执行,将按照priority的增序执行这几个任务。
func:要执行的任务函数
args:func的参数
"""
import time,sched
#周期性执行给定的任务
#初始化sched模块的scheduler类
#第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时... |
f3029e182ec3e5d41db752e29c78a3112da2ef2f | nbrahman/HackerRank | /04 Cracking the Coding Interview/BFS-Shortest-Reach-in-a-Graph.py | 1,085 | 3.578125 | 4 | from queue import Queue
def readInputs_buildGraph():
n, m = map(int, input().strip().split(' '))
graph = [0]
for j in range(n):
graph.append([])
for j in range(m):
(x, y) = map(int, input().strip().split(' '))
graph[x].append(y)
graph[y].append(x)
return n, graph
... |
9251af164f1604e594e99f48b837556a58b1cd73 | zenyj/lab-08-for-loops | /tens.py | 83 | 3.5625 | 4 | #for (i = 20; i <= 100; i = i + 10)
for i in range (20,110,10):
print(i)
|
8f5c389fe1d4d7c87ee48368a3120fdbfe0501e2 | souvikb07/DS-Algo-and-CP | /leetcode/easy_1.py | 1,990 | 4 | 4 | """
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], t... |
a8bb2ea221dc3aa27efe6471ae7ca17c2d993e7b | PuppeteerQ/Cristina-s-CS-Final-Project | /Car_Inventory/cardb.py | 7,341 | 4.0625 | 4 | """
The goal of Car_inventory project is to write a program that can manipulate a car inventory database and accessories database with functions of:
1.find car
2.add car
3.remove car
4.show database
5. find accessories by car
6.export inventory
7. quit program
The cardb.py file is to create a program that can initiali... |
163249718b991047cfb3c5245332ec871080a1e4 | kingwongf/basic_algos | /basic_algos3.py | 4,180 | 3.8125 | 4 |
def merge_sort(arr):
if len(arr)>1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
... |
ae2b7ec87540f34bc939985edcfed83fc895d76b | AeroX2/ncss-challenge | /2013/week-3/challenge35.py | 1,160 | 3.875 | 4 | import string
from math import sqrt
def sim(a,b):
while (len(a) != len(b)):
if (len(a) > len(b)):
b.append(0)
else:
a.append(0)
sum = 0
sumA = 0
sumB = 0
for i in range(len(a)):
sum += a[i] * b[i]
sumA += a[i]**2
sumB += b[i]**2
re... |
3bd9cafa9e28d879b801f5264bd4fd2c69d90168 | EnriquePinto/Coursera-DiscreteOptimization | /week2/knapsack/solver_greedy.py | 1,205 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
Item = namedtuple("Item", ['index', 'value', 'weight'])
def density(item):
val=item.value
weight=item.weight
return val/weight
def greedy(input_data):
# Modify this code to run your optimization algorithm
# parse the in... |
0989662fcba1b2f0290b50f71981cdf5cde5e4ae | iagsav/AS | /T2/SemenovaDS/2.1.py | 248 | 3.671875 | 4 | def is_prime(var):
for i in range(2,var+1):
a=0
for j in range(2,i):
if i%j==0:
a=1
break
if a==0:
print(i);
b=int(input("Введите число:"))
is_prime(b)
|
9ffd37059a6700adb4244a1b0155292bc0277417 | zuozuo12/usualProject | /python/Final18F_scripts/DerIntRoot.py | 7,517 | 4.3125 | 4 | #
# name:
# email:
#
# Note you are not allowed to change the any of the function interface defined below,
# you should call these functions by using propers inputs to solve the problems
# specified in the handout.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.integrate import qu... |
e18945288442346b9de22ea4780bbc673ac7c8e4 | guti7/hacker-rank | /python_OOP/ex5/animal.py | 1,767 | 3.890625 | 4 | # Make School OOP Coding Challenge Python Problem 5
import sys
# Implement Animal superclass
class Animal(object):
# Initializer
def __init__(self, name, food):
self.name = name
self.favoriteFood = food
# Sleep
def sleep(self):
print "%s sleeps for 8 hours" % self.name
# ... |
3a6c0ad57224028392e2cbc9131850c2bb7db6f4 | reinaaa05/python | /paiza_05/paiza_05_005.erb | 639 | 3.78125 | 4 | # coding: utf-8
# Your code here!
# リストの整列
weapons = ["イージスソード", "ウィンドスピア", "アースブレイカー", "イナズマハンマー"]
print(weapons)
print(sorted(weapons))
print(sorted(weapons,reverse=True))
#数字を含む
weapons2 = ["4.イージスソード", "1.ウィンドスピア", "3.アースブレイカー", "2.イナズマハンマー"]
print(sorted(weapons2))
print(sorted(weapons2,reverse=True))
#漢字を含む
... |
e0cb09e427d7e2b1cbe80f3ddf57bb066dcc4b1b | Innocent19/week3_day3 | /day four/app/power.py | 237 | 4.28125 | 4 | a = int(input("Enter integer a : "))
b = int(input("Enter integer b : "))
def power(a,b):
if b==0:
return 1
if b<0:
return 1/a*power(a,b+1)
return a*power(a,b-1)
print(power(a,b)) |
7cdabddac31b26f9b398338365a68ddc29b7a40b | RashiKndy2896/Guvi | /Dec18_hw_05oddprint.py | 114 | 3.84375 | 4 | odd=[]
even=[]
i=1
for i in range(1,101):
if i%2 == 0:
even.append(i)
else:
odd.append(i)
print(odd) |
ca21d2f2abb0a557d166c4ad9c482d3bcb1d3314 | Kvazar78/Skillbox | /6.3_while_break/dz/task_5.py | 951 | 4.1875 | 4 | # Ваня увлекается историей, а в особенности календарями. Он изучает
# календари разных времён, эпох и народностей. Для исследования ему нужно
# посчитать, у кого сколько было месяцев с чётным количеством дней.
#
# Напишите программу, которая считает количество только чётных чисел
# в последовательности (последовательно... |
07c538bd93fb2d4c78cf908110d00e216370ec67 | to-Remember/TIL | /May 31, 2021/1_var.py | 558 | 3.671875 | 4 | #주석: 프로그램 실행에 영향을 안줌. 없는 놈
'''
여러줄 주석
asdfasfd
asdff
asdasf
'''
# 변수를 정의함. 변수의 타입은 할당한 값의 타입을 따라감
str_val = 'abc'#문자열
int_val = 12 #정수
float_val = 23.345 #실수
bool_val = True #불
#type(): 괄호안에 넣은 값의 타입을 반환
print('str_val:', str_val, ', type:', type(str_val))
print('int_val:', int_val, ', type:', type(int_val))
print('f... |
c858262f5a2fd5bee1b8f3d33da10c37ea7eca6e | zhuiwang/python_work | /huawei_jishi/4_daxiezimu.py | 215 | 3.75 | 4 | #!/usr/bin/env python3
while True:
try:
string = input()
num = 0
for s in string:
if 'A' <= s <= 'Z':
num += 1
print(num)
except:
break
|
b89587c149c1aa5d143706c799fa1858fe8f42a9 | SachinPitale/Python3 | /Python-2021/10.Loop/7.for-loop.py | 597 | 3.890625 | 4 |
my_string="Working with for loop"
print (my_string)
for each_char in my_string:
print (each_char)
print (" ".join(my_string))
print ("\n ".join(my_string))
my_list = [4,5,6,7,8]
for i in my_list:
print (i)
my_list1 = [(1,2),(3,4),(5,6)]
for i in my_list1:
print (i)
for i in my_list1:
for m in 0, ... |
6a651eb751fa9b756a16743f86422fe605f70e05 | gadoid/PythonNote | /thread_practice.py | 1,200 | 3.796875 | 4 | from threading import Thread,Lock
import time
# def counter():
# for i in range (10):
# print(i)
# time.sleep(1)
# def main():
# t1=Thread(target=counter)
# t1.start()
# t2=Thread(target=counter)
# t2.start()
# t1.join()
# t2.join()
class Account():
def __init__(self... |
8bf364ddecb1fdb62d7745b3e825f0ee066aa788 | GabriellyBailon/Cursos | /CursoEmVideo/Python/Mundo 2/ex048.py | 464 | 4.0625 | 4 | #Mostrar a soma dos múltiplos inteiros de 3 que existem entre 1 e 500
soma = 0;
cont = 0;
for c in range(3, 501, 6):
soma = soma + c;
cont = cont + 1;
print(f"A soma desses {cont} números múltiplos de 3, é igual à {soma}");
#Realizando o laço com incrementação 3, se nota um padrão de que os n... |
81b42a7b772698b0cc41e9358d5e4656127b1987 | SoundaryaGajjam/PythonPractice | /oops/class_object.py | 754 | 3.5625 | 4 | class Employee:
'Common base cls for all emps'
empCnt=0
def __init__(self, nm, sal):
self.name=nm
self.salary=sal
Employee.empCnt+=1
def displayCount(self):
print("Total emp count : %d" % Employee.empCnt)
def displayEmp(self):
print("Name : ", self.name, " ... |
019838aa520ce2f7cda4486d319d5b6a7b983429 | MEng-Alejandro-Nieto/Python-3-Udemy-Course | /19 function exercises.py | 1,453 | 4.1875 | 4 | # write a function called "myfunc" that prints the string "Hello World"
def myfunc():
return print("Hello World")
myfunc()
print("")
# write a function called "myfunc" that takes in a Name, and prints "Hello Name"
def myfunc(Name):
return print(f"Hello {Name}")
myfunc("alejandro")
print("")
# define a function call... |
ef5cf40ec867346b44ec5d7a6afabba14b35c55a | jimmyhzuk/morning-stock-market-emails | /ScrapeInformation/economic_calendar.py | 1,452 | 3.5625 | 4 | import requests
from datetime import datetime
today_date = datetime.now().strftime("%Y-%m-%d")
def scrape_economic_calendar():
r = requests.get(
'https://finnhub.io/api/v1/calendar/economic?token=c1n20v237fkvp2lsh1ag')
for x in r.json()['economicCalendar']:
# try:
if x['country'] == 'U... |
4ed4e0083099a5ec65a673c5f3bfbde230a52520 | vermamit89/problem_solving | /pattern.py | 1,221 | 4.21875 | 4 | # Pattern #1: Simple Number Triangle Pattern
# for i in range(1,6):
# for j in range(i):
# print(i, end=' ')
# print('')
# Pattern #2: Inverted Pyramid of Numbers
# for i in range(5,0,-1):
# for j in range(i):
# print((6-i),end=' ')
# print('')
# Pattern #3: Half Pyramid Pattern of ... |
e2c92506657555e9a2d29a556a2e26680875666a | xuzifan08/LendingClub | /src/python/data_cleaning.py | 3,432 | 3.9375 | 4 | import pandas as pd
## This file is to read the raw csv file, clean the data and save it as cleaned data csv file
def removenull(dataframe, axis=1, percent=0.5):
"""
* removeNull function will remove the rows and columns based on parameters provided.
* dataframe : Name of the dataframe
* axis :... |
04f4cf5d60191f12eb6087c225c747c93d002e3f | daniel-zm-fang/Cracking-the-Coding-Interview | /Chapter 2/Palindrome.py | 2,042 | 4.25 | 4 | # Implement a function to check if a linked list is a palindrome.
# method 1: reverse the linked list and check if it's same as the original
# method 2: iterative approach, pushing the 1st half of the linked list onto a stack then compare it to the 2nd half
# method 3: recursive approach
class Node:
def __init_... |
edadf090594370372a66ee04467a1bdcd707ee24 | nicgirault/euler | /41.py | 1,807 | 4.03125 | 4 | # prime numbers are only divisible by unity and themselves
# (1 is not considered a prime number by convention)
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even pri... |
4c0d70a3f3d83e9c11cd57ad9d7d5d89069070ad | PauloAlexSilva/Python | /Sec_7_colecoes/c_dicionarios.py | 5,911 | 4.15625 | 4 | """
Dicionários
OBS: Em algumas linguagens de programação, os dicionários Python são conhecidos por
mapas.
Dicionários são coleções do tipo chave/valor.
Dicionários são representados por chaves {}
print(type({}))
<class 'dict'>
OBS: Sobre os dicionários
- Chave e valor são separados por dois pontos 'ch... |
5649e7958215c214968c06259c00898d9421cf86 | Jr-82/python_lessons | /task3_less2.py | 998 | 3.921875 | 4 | list_season = ['Зима', 'Весна', 'Лето', 'Осень']
list_month = ['Декабрь', 'Январь', 'Февраль']
diction_season = {1: 'Зима', 2: 'Весна', 3: 'Лето', 4: 'Осень'}
user_num = int(input('Введите номер месяца: '))
if user_num == 12:
print(f'{list_season[0]} --> {list_month[0]}')
print(f'{diction_season.get(1)} *** {l... |
393047177d30756ba577257add075131eaf43806 | aa2276016/Learning_Python | /LeetCode/p021_merge_two_sorted_list.py | 693 | 4.15625 | 4 | # p21 Merge two sorted list
# Easy
# Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
l1 = ListN... |
a15a911fe4a908938a4ea300768a384032a10bd4 | Mariama2006/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 175 | 3.5 | 4 | #!/usr/bin/python3
"""My class
"""
def is_same_class(obj, a_class):
"""
function
"""
if type(obj) == a_class:
return True
else:
return False
|
0e3d80c71fab28d2785b6f943ad67efb5e1414a1 | mttk/ProjectEuler | /026.py | 876 | 3.609375 | 4 | ### Reciprocal cycles
# https://projecteuler.net/problem=26
def division(n, d):
"""
A cycle is defined by the number being divided and the divisor. Such a pair uniquely defines
the sequence of numbers occurring as a result of the division - if such a pair occurs twice consequently,
then the numbers be... |
b7d202e631c9d76259715c776c39df79d254aa8d | LiprikON2/ITMO | /Informatics/labs/lab_03_11.py | 654 | 3.5 | 4 | def encodeHuffman(fileIn, fileOut):
pass
def decodeHuffman(fileIn, fileOut):
pass
def count_chars(file):
textDict = dict()
with open(file, 'r') as f:
for line in f:
for char in line:
if char in textDict:
textDict[char] += 1
else:
... |
3a3b579db8bcd4bf144cbcc60fb2619f21304a79 | him-28/Project-Euler | /prob53.py | 394 | 3.671875 | 4 | import time
tStart = time.time()
values = 0
def factorial(x):
y = 1
for i in range(1,x+1):
y = y * i
return y
def calc(n, r):
return factorial(n) / (factorial(r) * factorial(n-r))
for i in range(1,101):
for j in range(1, i):
if calc(i, j) > 1000000:
values +... |
3efa5fed62d596961b14549d7e9fd1f797d7ed2b | qqss88/Leetcode-1 | /3_Longest_Substring_Without_Repeating_Characters.py | 861 | 4.21875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
@author: Jessi... |
b824dbd1259a32c9a7b4073a9d980409d29b2919 | nanaboat/data-structures | /Linkedlist/LinkedList.py | 13,922 | 3.96875 | 4 | class Node:
'''Implements a node that stores the value and pointer to next node.'''
def __init__(self, data):
self._data = data
self._nextLink = None
def getData(self):
'''Returns the data in the node.'''
return self._data
def getNextLink(self):
'''... |
b2c899bb6bf765720bb22fe4caf6ef4fe4b39584 | RyanSamman/KAU-CPIT110 | /Chapter 4/BooleanValue.py | 293 | 3.953125 | 4 | x = 10 > 20 # False
y = 10 < 20 # True
print('x =', x)
print('y =', y)
x = int(False) # 0
y = int(True) # 1
print(x, y)
x = bool(0) # if the number is 0, it will be false
y = bool(1) # any number not 0 will be true
print(x, y)
x = bool(-25)
y = bool(2000)
print(x, y)
|
a8649f5988f35929bf8fb206d9bc8559e5259047 | DHDaniel/mc-tictactoe | /MonteCarloPlayer.py | 5,333 | 3.703125 | 4 |
import copy
import random
class MonteCarloPlayer:
def __init__(self, TTT_board, player, num_trials):
"""
Initialises a machine player which chooses moves based on Monte Carlo simulations.
TTT_board should be of the class TTTBoard
num_trials is the desired number of trials to use i... |
ce333be3e5bc1b3766868bf6fd5f526ac0f0cc9a | jrluecke95/python-102 | /long_vowels.py | 773 | 4.34375 | 4 | string = "good"
vowels = ["a", "e", "i", "o", "u"]
empty_string = ""
#for loop that runs through each index in string first
# then checks to see if each string[index] is in the list vowels
# after that - setting the letter to be replaced to string[index of letter] helped simplify things in end expression
# diong the s... |
beda147914ec1d253603ac64e8ac21b676a5e005 | baiyang20201207/baiyang20201207.github.io | /python学习/song/class/thefirstday/lesson02.py | 1,595 | 3.90625 | 4 | #conding=utf-8
#@time 2020/12/29 14:02
#@AUTHOR sx
'''
运算符:
1.算术运算符:+,-,*,/,//,%,**
2.关系运算符:>,>=,<,<=,==,!=
3.逻辑运算符:not,and ,or
4.赋值运算符:+=,-=,*=,/=,//=,%=,**=
5.成员运算符:in ,not in
'''
a=10
b=3
print(a/b,a//b,a%b,a**b)
print(not(1+2>7),8==8)
a+=b #a=a+b
print(a,b)
t=(1,2,3,4)
print(5 not in t)
'''
类型 :
1.数据类型:整型int(),... |
8eabe2107ba628a815833ff7fb98c879243e4f8b | Shreyans145/N_PUZZLE_AI | /First Choice/3.FirstChoiceHillClimbing.py | 2,818 | 3.703125 | 4 | import time
import random
tag = False
def sol_RandomHillClimbing(arr):
x = 500000
c = 0
while True:
distance = get_Manhattan_Distance(arr)
if distance == 0:
return arr
arr = Random_HillClimbing(arr)
c += 1
if(c >= x):
global ta... |
c4fc2e3f8a1fa3312bb33054d89a87ebd74b7901 | larsgimse/NodeMCU | /micropython/math_game.py | 536 | 3.875 | 4 | import random
import time
from machine import Pin
led_green = Pin(14, Pin.OUT)
led_red = Pin(12, Pin.OUT)
while True:
led_green.off()
led_red.off()
number_1 = random.randint(2,12)
number_2 = random.randint(2,12)
answer = int(input("What is " + str(number_1) + " * " + str(number_2) + "? "))
if ... |
a26dfcfb34a20b6340fff0ce648100025ca8a352 | estela-ramirez/PythonCourses | /LAB 3 Q1.py | 1,340 | 4.125 | 4 | '''
ICS 31 Lab 3 Question 1
Driver: UCI_ID: 18108714 Name: Estela Ramirez Ramirez
Navigator: UCI_ID: 69329009 Name: Karina Regalo
'''
def main():
i = get_n_of_people()
ns, ag = getsAgesAndNames(i)
maxb, index = maxAge(ag)
minb, index2 = minAge(ag)
s = sumAge(ag)
printOldestYoungestAverage(index,... |
24dbbcb5331116ebde11e87f87efb85a7e7ae55b | adamilyas/complex-networks | /week6/colorbar_help.py | 1,664 | 3.59375 | 4 | from matplotlib import pyplot as plt
import matplotlib as mpl
import numpy as np
"""
This file provides the function for plotting the colorbar in case plt.colorbar() fails to
output any colorbar at all.
In your script file, import this module with
import colorbar_help as ch
import networkx as nx
import matplotlib.... |
ad4273b2eeaa6f681f954a71474046390c217c01 | HenriqueSoares28/Python-EX | /ex052.py | 343 | 3.8125 | 4 | num = int((input('Digite um número: ')))
tot = 0
for c in range(1, num +1):
if num % c == 0:
print('\033[34m', end='')
tot += 1
else:
print('\033[m', end='')
print(f'{c} ', end='')
print('\033[m')
if tot == 2:
print('O número escolhido é primo!')
else:
print('O número escolhi... |
d03967c7f20ce1f930d234cc8f7eda298358e3e5 | ashwin-5g/LPTHW | /ex12.py | 357 | 4.03125 | 4 | age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
x = raw_input("Enter value for x: ")
y = raw_input("Enter value for y: ")
sum = int(x) + int(y)
print "The sum of the tw... |
bd8b4fa4480bc55fbfd635ea8f34d6a00e641460 | nemmiz/aoc2016 | /python/02.py | 1,100 | 3.515625 | 4 | #!/usr/bin/python3
def do_moves(lines, start, possible_positions):
x, y = start
for line in lines:
for c in line:
if c == 'U':
nx, ny = x, y-1
elif c == 'D':
nx, ny = x, y+1
elif c == 'L':
nx, ny = x-1, y
... |
e1ba530b1798fd1be9a3735362b487bb644df82b | tannerbender/E05a-Animation | /main2.py | 4,646 | 4.34375 | 4 | #Copy the contents from http://arcade.academy/examples/move_keyboard.html#move-keyboard and see if you can figure out what is going on. Add comments to any uncommented lines
"""
This simple animation example shows how to move an item with the keyboard.
If Python and Arcade are installed, this example can be run from t... |
aaa847bf6c9c984cf8877200790bd729d5f49c92 | xsong15/codingbat | /list-1/sum2.py | 474 | 4.09375 | 4 | def sum2(nums):
"""
Given an array of ints, return the sum of the first 2
elements in the array. If the array length is less
than 2, just sum up the elements that exist,
returning 0 if the array is length 0
"""
# if sum(nums) < 2:
# return sum(nums)
# elif len(nums) == 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.