blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cf656018e76bb9e78f946b92c9b56744bf1a42f4 | dasanchez/voldemot | /voldemot.py | 3,505 | 3.671875 | 4 | """
voldemot - a word de-scrambler by @dasanchez
Usage:
usage: voldemot.py [-h] [-d DICTIONARY] [-c COUNT] [-v] [-p] input
positional arguments:
input the letters to de-scramble
optional arguments:
-h, --help
show this help message and exit
-d DICTIONARY, --dictionary DI... |
ab7179425d164a7021c3a7ae8e935860a9972ff5 | Raushan-Raj2552/URI-solution | /2143.py | 244 | 3.796875 | 4 | while True:
a = int(input())
if a == 0 :
break
if a > 0 :
for i in range(a):
b = int(input())
if b%2 == 0:
print(2*b-2)
else:
print(2*b-1) |
a13b7cacf74910d9ea809589f045c238f552116e | 1phantasmas/stocal | /random_walk.py | 859 | 3.875 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
# position, each one denotes per iteration
x = []
# number of iteration
N = int(input("Enter the number of iteration : "))
# number of walks
n = int(input("How many times do you want to walk per iteration? : "... |
ff222bfc301470d10c64f81c7ec07860d92c4217 | nidhim12/DataStructuresAnd-Algorithms | /merge_sort.py | 684 | 3.53125 | 4 | def create_array(len=10, max=50):
from random import randint
new_arr = [randint(0,max) for _ in range(len)]
return new_arr
def merge(a, b):
a_idx =0
b_idx = 0
c = []
while a_idx<len(a) and b_idx<len(b):
if a[a_idx]<b[b_idx]:
c.append(a[a_idx])
... |
8e5df9a1c2da349aa98423af992f4bcb1517f090 | atkramer/advent-of-code-2018 | /two/two.py | 836 | 4.0625 | 4 | #!/usr/bin/python3
import sys
# Returns True if word contains exactly N occurences of any character,
# otherwise returns False
def exactlyN(word, n):
letterCounts = dict()
for letter in word:
if letter in letterCounts:
letterCounts[letter] += 1
else:
letterCounts[letter] = 1
return n in let... |
6835d6fe9cca624bd24f09924a24864f1967a2d7 | sweetysweets/Algorithm-Python | /myclass/homework3/problem1_final.py | 4,027 | 3.921875 | 4 | """
分配问题
Description
对给定的n个任务与n个人之间的成本矩阵完成成本最低的任务分配策略。使用匈牙利算法完成。
Input
输入:第一行为用例个数,之后为每一个用例;用例的第一行为任务个数,即n;用例的第二行为使用逗号隔开的人员完成任务的成本;每一个成本描述包括人员序号、任务序号和成本,使用空格隔开。人员序号和任务序号都是从1到n的整数,序号出现的次序没有固定规则。
Output
输出:每一个用例输出一行,从序号为1的人员开始,给出其分配的任务序号,使用空格隔开;使用逗号将多个解隔开。
Sample Input 1
1
4
2 1 6,1 2 2,1 3 7,1 4 8,1 1 9,2 2 4,... |
7cbe92e7b937caaf3422eabe1c55097be383bccc | Jjaaeessoonn/pythonWork | /pythonMain.py | 1,860 | 3.59375 | 4 | import sys
import os
import signal #h handles ctrl+c/SIGINT
'''
Practice for Python
'''
# Functions
def keyboardInterruptHandler(signalNum, frame):
#print('KeyboardInterrupt/SIGINT: {0} is caught...'.format(signal) )
print('In error handler')
sys.exit(0)
signal.signal(signal.SIGINT, keyboardInterruptHandler)
d... |
2992b3712b1c766f27b95c3131653beec54b031b | tylerhjones/advent_of_code | /2016/3/run.py | 873 | 3.65625 | 4 | from shared import *
import re
input_ary = read_input('input.txt')
count = 0
def is_triangle(arr):
largest = max(numbers)
numbers.pop(numbers.index(largest))
return largest < (numbers[0] + numbers[1])
for line in input_ary:
matches = re.findall('(\d{1,3})', line)
numbers = [int(x) for x in mat... |
4cacb12825c8694c7899fa2b542020da03686a10 | Shargarth/Python_exercises | /KyselyArpoja.py | 336 | 3.75 | 4 | from random import randint
koneenLuku = randint(1,10)
kayttajanArvaus = int(input("Arvaa luku 1 - 10 välillä: "))
while not kayttajanArvaus == koneenLuku:
if koneenLuku < kayttajanArvaus:
print("Liian suuri \n")
else:
print("Liian pieni\n")
kayttajanArvaus = int(input("Arvaa luku: "))
pr... |
7669ab36f69d009d51fb6b9f40a7fa2b4473b3f0 | zhankq/pythonlearn | /alivedio/base1/loop1.py | 363 | 3.609375 | 4 | '''
i = 1
j = 1
num = 1
while num<=81 :
while i <= j:
k = i * j
print("{0} * {1} = {2} ".format(i,j,k),end=' ')
i += 1
num = i * j
else:
print()
j = i
i = 1
'''
'''
i=1
while i<= 9:
j= 0
while j < i :
j += 1
print(f'{j}*{i}={i*j} '... |
1e86df98e66ae6142a51098b7278ca53eb68a352 | DemianLuna/python-01-basics-2020-course | /chap13_files/item02_intro_reading.py | 1,648 | 4.0625 | 4 |
def print_content( text_content= "", array_content=[] ):
"""
This prints a text, and then an array
And print the results in terminal
:param str text_content: The text to be printed
:param list array_content: The list to be printed
:return: This method is void (return nothing)
"""
size ... |
4a2e613e8bb67e2f0c09d0441c2f14ee25a7ddfc | CynYZY/course1-final-wordcloud | /str_list_dict/highlight_word.py | 373 | 3.671875 | 4 | def highlight_word(sentence, word):
start = sentence.find(word)
highlight = sentence[start : len(word)+start]
return sentence[0 : start] + highlight.upper() + sentence[len(word)+start : ]
print(highlight_word("Have a nice day", "nice"))
print(highlight_word("Shhh, don't be so loud!", "loud"))
print(hi... |
d27ab41cfb53de1493f41d09361f784373b892c1 | lizzymejia/mejia_lizzy_temp1 | /main.py | 398 | 3.625 | 4 | a = 70
b = 70 > b > 40
while True:
print("Temperature" + input.temperature(TemperatureUnit.FAHRENHEIT))
if input.temperature(TemperatureUnit.FAHRENHEIT) > a:
light.set_pixel_color(5, light.rgb(255, 0, 0))
elif input.temperature(TemperatureUnit.FAHRENHEIT) < b:
light.set_pixel_color(5, light.... |
5bd0f24a36af4307ec12412ef5d04a6f47f9aa9f | corey-puk/Python | /number_to_string.py | 3,406 | 4.09375 | 4 | def num2str():
while True:
try:
n = int(input("This program converts integer values into their respective worded format. Please enter an integer between 0 and 100: "))
n = int(n)
if n > 100 or n < 0:
raise ValueError("Please enter an integer between 0 and ... |
aa11fe62bf07e9a534983a658da87fb9015a4fc5 | I-Tingya/Data-structures-Algorithms | /symbol-table/binary-search-tree.py | 4,527 | 3.65625 | 4 | class Node():
def __init__(self, key, val):
self.key = key
self.val = val
self.left = None
self.right = None
self.count = 1
class BinarySearchTree():
def __init__(self):
self.root = None
def get(self, key):
if self.root is None:
return N... |
74d6bcce127dfc3f64b834d7fe58c86660c8b1e9 | csy0x1/Python3-learning | /算法与数据结构/search_insert_pos.py | 1,706 | 3.90625 | 4 | '''
搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
class Solution:
def searchInsert(self, nums, target):
for i,j in enumerate(nums):
if j... |
a38faf8d57e4b62c726b99a4e8eaa27b81e1c9a2 | santiguillengar/pytalian | /test.py | 2,521 | 3.703125 | 4 | import random
def testVocab():
input_func = None
try:
input_func = raw_input
except NameError:
input_func = input
filename = getUnit()
file = open(filename,"r") #opens file with name of "vocab.txt"
# PREPARATION OF VOCAB
messList = []
translation = ""
item = ()
correct = 0
total = 0
for line in ... |
8b4102bbd356b66f5eb84345d1f2dc3a63395a8c | ajing2/python3 | /Basics/funciton/production.py | 525 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/24 14:09
# @Author : lingxiangxiang
# @File : production.py
y = list()
x = [1, 2, 3, 4, 5]
y +=x
y.append(100)
print(y)
print(x)
a = [x*x for x in range(1, 30) if x%2 ==0]
print(a)
print(type(a))
b = (x*x for x in range(1, 30) if x%2 ==0)
print(... |
711fef9bb7375e2080290742431bcc80e936451b | h3h3da/CodeLib | /Python数据处理之幂律拟合/test.py | 3,341 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from scipy.optimize import curve_fit
from matplotlib.font_manager import FontProperties
# font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
def func(x, a, b):
return ... |
56681daf3c64a3f8b04e0d2f972684f140324ae3 | Matt-the-Marxist/schoolStuff | /docs/classwork/python/lessons/9.3.1.py | 351 | 3.75 | 4 | class Rectangle:
def __init__(self, length=0, width=0):
self.length = length
self.width = width
def __repr__(self):
return("a rectangle with "+str(self.__dict__))
def getArea(self):
return(self.length*self.width)
def getPerimeter(self):
return(2*(self.length+self.width))
r1 = Rectangle()
r2 = Rect... |
0d59b0cfc59db07ae7f027b90b53e5f510ec9726 | kobeomseok95/codingTest | /programmers/level2/60058.py | 1,393 | 3.734375 | 4 | ### 괄호 변환
def balanced_index(string):
tmp = list(string)
left, right = 0, 0
for i in range(len(tmp)):
if tmp[i] == '(':
left += 1
elif tmp[i] == ')':
right += 1
if left > 0 and right > 0 and left == right:
return i
return len(string)
def pr... |
9fb9be9fb841fe87b293837b1fa8fb000638b817 | skonienczwy/LearningPython | /ex0060.py | 1,690 | 3.5625 | 4 | print('##Exercicio 60##')
##Joao Solution
pessoas = list()
listaAux = list()
pesadas = list()
leves = list()
count = 0
minimo = list()
maximo = list()
name = list()
while True:
val = str(input('Insira o Nome: '))
listaAux.append(val)
val = float(input('Insira o Peso: '))
listaAux.appen... |
8a0e79bb9f63a847e95360416276d525f84c0652 | jieunjeon/daily-coding | /Leetcode/42-Trappint_Rain_Water.py | 4,189 | 4.0625 | 4 |
"""
https://leetcode.com/problems/trapping-rain-water/
42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (blac... |
0280936a439ecdbe205ee8c52d5836d86443409b | Vulpicidic/VulpDiscBot | /DiscordBot/DiscordBot/chatCommands.py | 1,546 | 3.546875 | 4 | import random
# returns list of usable commands.
def getHelp():
listOfCommands = ["!help -> Gives a list of commands.","!coin -> Flips a coin and returns either heads or tails.","!roll (amountOfDice) d(sidesOfDice) -> rolls specified amount of rolls with specified amount of sides.\n\t Ex. \"!roll 4 d20\" would... |
e64565dc7235d309317a9703fa53cc8fe4d7c881 | tpwrochna/projekty_python | /struktury danych/Zadanie1.py | 704 | 3.84375 | 4 | '''
W sesji interaktywnego środowiska konsoli stwórz tuplę zawierającą 10 różnych liczb całkowitych.
Korzystając z operatora dostęu oraz wycinania pobierz:
drugi element
przedostatni element
element od trzeciego do siódmego
co trzeci element
co drugi element od konca
'''
# KROTEI NIE MOZNA EDYTOWAC JEJ WCZESNIEJ ZDEFI... |
f94dd82cc92c8df1651fb878e4f55b48b644d2c6 | ELThornton/Unit6 | /prime_factors.py | 1,315 | 4.40625 | 4 | # Elena Thornton
# prime_factors.py
# 11/17/2017
# this programs makes a list of numbers and gets the prime factors out of it.
def prime_factor_number():
"""
this get the number that the program with get the prime factors out of
:return: number
"""
user_number = input("please put the number in tha... |
243fa09f33b873b827c1a69345df1da1f850bdf4 | HuuHoangNguyen/Python_learning | /membership_operators.py | 458 | 4.03125 | 4 | #!/usr/bin/python
a = 10
b = 20
list = [1, 2, 3, 4,5]
if a in list:
print "Line 1: a is available in the given list"
else:
print "Line 1: a is not available in the given list"
if b not in list:
print "Line 2: b is not availabale in the given list"
else:
print "Line 2: b is available in the given list"... |
10d78faa7aac47f998d010c63f952b2ffaaa15c3 | khanh2kjr/hill-cipher | /hill.py | 5,170 | 3.578125 | 4 | from tkinter import *
from tkinter import messagebox
from string import ascii_uppercase
import itertools
# Tạo mảng chữ cái Alphabet [A, B,..., Z]
alphabets = [alphabet for alphabet in ascii_uppercase]
# Hàm chuyển chuỗi thành mảng ký tự
def split(word):
return [char for char in word]
def removeSpaceString(strs... |
aae59c9272088d6a4fb2f7eede6917dd80e87a5e | soheilina/CodeEval_projects_python | /ReverseWords.py | 272 | 3.765625 | 4 | __author__ = 'Soheil'
with open("ReversWords.txt", "r") as my_text:
for line in my_text:
if line in ['\n', '\r\n']:
print
else:
reversed = [word for word in line.rstrip('\n').split()[::-1]]
print ' '.join(reversed)
|
cd6f8904093cf8cccdfdcc2cd153d1f2fd9fabd6 | SugaanthMohan/Python_DSA | /Search_Algorithms/Sequential_Search.py | 663 | 4 | 4 |
def process(container_, search_element_) -> int:
"""
Search the container for the element.
:param container_: The list of elements
:param search_element_: The element to search
:return: return position of the element.
"""
position = 0
iteration = 0
while position < len(container_):... |
fb78c0ea2334f7186f4999fcddbeebfdff353b9d | dash7ou/Learn_Python | /Dr.chunk/Classes/firstClass.py | 888 | 3.78125 | 4 | class PartyAnmial:
x = 0
def __init__(self):
print('iam a contructed')
def party(self):
self.x = self.x + 1
print('so far', self.x)
def __del__(self):
print('I am destructed', self.x)
an = PartyAnmial()
an.party()
an.party()
an = 542
print(" an contains", an)
# ano... |
9f374e547d302d2393dab54a98944525a6257f2b | dykim822/Python | /ch03/for_gugu2.py | 387 | 3.765625 | 4 | # while-for문을 혼합한 구구단 입력
while True:
print("구구단 단수를 입력하세요")
num = int(input())
if num >= 2 and num < 10:
print(f"구구단 {num}단")
for i in range(1, 10):
print(f"{num} * {i} = {num * i}")
elif num == 0:
break
else:
print("다시 입력해주세요")
print("프로그램 종료") |
5f74bafce610eb36657cd775a1038d9edb8cfac7 | hewenjerry/python-demo | /GroupDict.py | 1,163 | 3.65625 | 4 | import os
from collections import defaultdict
class Person(object):
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
def __repr__(self):
return "{first name :" + self.first_name \
+ " ; last name :" + self.last_name + "}"
a1 ... |
914517de052849732eda167d48859fb4ac4e5f50 | xiaolinzi-xl/python_imooc | /twl/c8.py | 702 | 3.5 | 4 | import time
def decorator(func):
def wrapper(*args,**kw):
print(time.time())
func(*args,**kw)
return wrapper
@decorator
def f1(func_name):
print('this is a function' + func_name)
@decorator
def f2(func_name1,func_name2):
print('haha ' + func_name1 + ' ' + func_name2)
@decorator
def f... |
1cf33f7de27fbe732b35bae1546c82d8556928a0 | rebeccasmile1/algorithm | /homework1/test2.py | 3,409 | 3.546875 | 4 | def MaxmalRectangle(matrix):
h = []
matrix2 = []
for i in range(0, len(matrix[0])): # 列
h.append(0)
m = len(matrix) # 行数
n = len(matrix[0]) # 列数
print(m, n)
max = 0
for i in range(0, m):
h = []
for j in range(0, n):
if i == 0:
h.appe... |
4029ede2f9ba348ba326dbe89d0eb540d5063ac9 | oaldri/comp110-21f-workspace | /sandbox/3.py | 295 | 3.921875 | 4 | """Exercise 3 part 1."""
__author__ = "730383481"
choice: int = int(input("Choose a number: "))
if (choice % 2 == 0 and choice % 7 == 0):
print("TAR HEELS")
else:
if choice % 2 == 0:
print("TAR")
if choice % 7 == 0:
print("Heels")
else:
print("CAROLINA") |
ad0de680c95d52e443f6e3dc452ded14dc8821b7 | Anjaneyavarma/Python | /Numpy files/Numpy14.py | 276 | 3.828125 | 4 | #Numpy14.py
# diagonal matrix
from numpy import array
from numpy import diag
# define square matrix
M = array([
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
print(M)
# extract diagonal vector
d = diag(M)
print(d)
# create diagonal matrix from vector
D = diag(d)
print(D)
|
681d8ee37a7529afc46adb49be5ef74f2c9a3098 | rbUUbr/python-chillout | /nester/build/lib/nester.py | 441 | 4.0625 | 4 | """This is nester.py module. It provides function print_list_items to print elements of list. Also works for nested lists"""
def print_list_items(items_list):
# """This function takes a positional argument called items_list, which should be any of lists types.
# Function works rercursively."""
for item in... |
a4828ba5269fd7ee41020b3b10175df8ff0b1e77 | TRoyer86/DoingMathWithPython | /Mean.py | 562 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 28 21:01:00 2017
@author: tater
"""
from scipy import *
from matplotlib import pyplot as plt
'''
Calculate the mean
'''
def calculate_mean(numbers):
total = sum(numbers)
count = len(numbers)
mean = total/count
return mean
if _... |
96271f9a001641a098a045c23eb9d0ce620fe702 | trevordo/movies | /favourite/media.py | 1,175 | 3.59375 | 4 | import webbrowser
class Movie():
# triple quotes allows for setting class variable __doc__
""" This class provides a way to store movie related information
Attributes:
movie title (str): Specify the title of the movie
movie storyline (str): Movie description or plot
... |
e489a099444f7008e8da8cf57a3afabde03d6947 | philwilliammee/python-starter | /database/my_postgres.py | 2,443 | 3.6875 | 4 | """Connects to a Postgres DB
Returns:
obj -- an example of a postrges db conection for testing.
"""
import psycopg2
class Postgress():
"""simple connection
Returns:
init -- interface for connection adapter
"""
def __init__(self, database, user, password, host, port, LOGGER):
self.... |
5a2d8e746f59c16949eb22e10f58d9e8dd7aeeda | rookie-LeeMC/Data_Structure_and_Algorithm | /leetcode/第K个/最小的k个数.py | 2,223 | 3.515625 | 4 | # -*- coding:UTF-8 -*-
'''
https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
解题方法:
利用快排,不
https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/solution/3chong-jie-fa-miao-sha-topkkuai-pai-dui-er-cha-sou/#%E4%B8%89%E3%80%81%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B9%9F%E5%8F%AF%E4%BB%A5-%E8%A7%A3%... |
8ebe898f86bab89f8525ea4b183884556e7219bc | damianarielm/lcc | /4 Ano/Ingenieria del Software II/Codigo/Abstract Factory/abstractfactory.py | 693 | 3.6875 | 4 | from abc import ABC, abstractmethod
class Idioma(ABC): # FabricaAbstracta
@abstractmethod
def CrearCartaBlanca(self): # CrearProductoA
pass
@abstractmethod
def CrearCartaNegra(self): # CrearProductoB
pass
class CartaBlanca(ABC): # ProductoAbstractoA
def Texto(self):
return... |
ad478c57d9ddda3287521b6911481f4897c44860 | zhangchizju2012/LeetCode | /628.py | 336 | 3.71875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 24 19:29:19 2017
@author: zhangchi
"""
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return max(nums[-1]*nums[-2]*nums[-3],nums[0]*n... |
5672ee0809766275e4b7c0ad1d4736142afb1885 | noorulameenkm/DataStructuresAlgorithms | /LeetCode/30-day-challenge/May/May 8th - May 14th/floodfill.py | 996 | 3.515625 | 4 | class Solution:
def floodFill(self, image, sr, sc, newColor):
if image == []:
return []
color = image[sr][sc]
row, col = len(image), len(image[0])
visited = [[False for i in range(col)] for j in range(row)]
fill(image, sr, sc, row, col, color, ne... |
eb3cd07cbbac0eacccfa7183e365e918a99780d9 | Diksha4111/python | /sum of digits of random no.py | 195 | 4.0625 | 4 | #to calculate the sum of all the digits of any three digit random no.
import random
x=random.random()*900+100
x=int(x)
print(x)
sum=0
a=x//100
b=(x//10)%10
c=x%10
sum=a+b+c
print(sum)
|
e53721762c29c25df32d640187303ee602d04267 | yuanmejia01/Calculadora-de-matrices | /matrices.py | 7,800 | 3.796875 | 4 | import numpy as np
class Matriz:
def __init__(self):
pass
@staticmethod
def matrices(cantidad):
lista = []
for i in range(cantidad):
a = int(input("Ingrese el numero filas de la matriz #{0}: ".format(i+1)))
b = int(input("Ingrese el numero columnas ... |
b65c318c17cfe6454b3f1f63ce890dcc76642461 | MKarimi21/University-of-Bojnurd | /Combinatorial-Optimization/M-Karimi/Exe01/Combinatrial-Optimazing-Mostafa-Karimi-Part01.py | 5,765 | 3.984375 | 4 | #+++++++++++++++++++++++++++++++++++++++++++++++++++
#
# --------------------------------------------------
#| Combinatrial-Optimazing-Mostafa-Karimi-Part01 |
#| Python Library for this Class |
#| Version: 1.0.1 |
# --------------------------------------------------
... |
c5798c01ae9ec3140d6ea2a842ae7c0389e16bcd | gianluca191198/LectorWeb | /src/arbolb.py | 2,916 | 3.84375 | 4 |
class NodoArbolB(object):
"""Nodo base de un arbol B.
Argumentos:
orden -- La cantidad de hijos que un nodo puede tener
tipo -- El tipo de objeto a almacenar. Note requiere la clase en si, es decir,
el retorno de la funcion type().
Por ejemplo, para crear un nodo que almacene enteros con capacidad para 4:
B... |
d62df0f3840142c57f2c57d4abd48909aba99539 | s0medude/lumu-devops-test | /script.py | 4,152 | 3.953125 | 4 | import os
import re
import operator
from os.path import join, getsize
# Search for the given path and returned it if exists or return False if it is not present
def is_directory(path):
if os.path.isdir(path) and os.path.exists(path):
print('The {} is an existing directory!'.format(path))
return... |
b6ee6a4be8f35279e7f1a930be404f118c7c0e21 | rasithasreeraj/python | /Logging Basics/logging_2.py | 381 | 3.71875 | 4 | # This program shows how to get the "debug" infor to be printed in the console
import logging
logging.basicConfig(level=logging.DEBUG) # debug is actually int 10 in background
def multiply(a,b):
# "Multiplication"
return a * b
a = 10
b = 20
m1 = multiply(a, b)
logging.debug("Multiply:{} by {} gives {}".forma... |
36d9d9f28b606df1c076939412d125bd46237cfe | sunilnandihalli/leetcode | /editor/en/[567]Permutation in String.py | 1,117 | 3.703125 | 4 | # Given two strings s1 and s2, write a function to return true if s2 contains th
# e permutation of s1. In other words, one of the first string's permutations is t
# he substring of the second string.
#
#
#
# Example 1:
#
#
# Input: s1 = "ab" s2 = "eidbaooo"
# Output: True
# Explanation: s2 contains one permu... |
bbf84a0d3650e0ad598bc2195ab7cd8609c86144 | hastysun/Python | /Lessons/U5L4.py | 790 | 3.734375 | 4 | ## Unit 5 Lesson 4 - Button Canvas Interaction
## Computer Programming II - Gavin Weiss
# This program displays the letter being pressed
# on the canvas.
## Libraries
import time
import random
import simpleguitk as simplegui
## Define Global Variables
message = ("Long Live Pierce")
MessageOn = 0
## Define Hel... |
63076ec4bd95f437e42ca0dd8c97d768cb428ba3 | reb33/-algorithms_2021 | /Урок 8. Практическое задание/Урок 8. Пример практического задания/task_1/task_1.2.py | 2,995 | 3.828125 | 4 | class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return f'Node [{str(self.value)}]'
class Tree:
def __init__(self):
self.root = None
# функция для добавления узла в дерево... |
dc93aed1a4d7f2bfa5cf8bea0f63f87ca93373ee | taraewilliams/WordCounter | /word_graphs.py | 1,513 | 3.71875 | 4 | import matplotlib.pyplot as plt
def create_pie_chart_words(words: list, colors: list = [], grouped: bool = False):
"""
Create a pie chart for words in a list.
Parameters
----------
words: list[[str, int]] (ungrouped) OR list[ { words: list[str], count: int } ] (grouped)
The list of words ... |
e62de82a013c289b8ab9030fc8dff303a1dd83e6 | vyahello/python-ood | /patterns/structural/bridge.py | 1,685 | 4.15625 | 4 | from abc import ABC, abstractmethod
class DrawApi(ABC):
"""Provides draw interface."""
@abstractmethod
def draw_circle(self, x: int, y: int, radius: int) -> None:
pass
class Circle(ABC):
"""Provides circle shape interface."""
@abstractmethod
def draw(self) -> None:
pass
... |
73f534c1a16c98721816f13e1a4bbf9f0e6b3dbe | shwesinhtay111/Python-Study-Step1 | /numbers.py | 476 | 4.3125 | 4 |
# Addition
print(2 + 1)
# Substraction
print(2 - 1)
# Multiplication
print(2 * 2)
# Division
print(3 / 2)
# Floor Division
print( 7 // 4)
# Modulo
print(7 % 4)
# Powers
print(2 ** 3)
# Can also do roots this way
print(4 ** 0.5)
# Order of Operations followed in Python
print(2 + 10 * 10 + 3)
# Can use parentheses to sp... |
49b8b3a362aa723b7ba36cc5d35c57b9de383da7 | TanishaProgramer/Python | /stack.py | 392 | 4 | 4 | stack=[]
while True:
print("stack:")
print("1. add")
print("2. pop")
print("3. traverse")
print("4. Exit..")
choice = int(input("enter your choice"))
if(choice==1):
num = input("enter number")
stack.append(num)
if(choice==2):
stack.pop()
if(choice==3):
... |
a835a7f80dcddfc159b606a7d9ba18899c163790 | AlexanderWeismannn/Pierian-Data-Python-Course | /Iterators and Generators Homework/rand_num.py | 221 | 3.84375 | 4 | #GENERATOR THAT YIELDS (N) RANDOM NUMBERS BETWEEN (LOW/HIGH)
import random
def rand_num(low, high, n):
for i in range(n):
yield(random.randint(low,high))
for num in rand_num(1,10,2):
print(num)
|
3fbe02f6284b59e5d97180a6d058bab16a511372 | AninditaBasu/iPythonBluemixWatsonTone | /watson_get_tweets.py | 3,489 | 3.703125 | 4 | import json
from twitter import TwitterStream, OAuth
#
# Authenticate yourself with Twitter
#
CONSUMER_KEY = raw_input('Enter the Twitter consumer key: ')
CONSUMER_SECRET = raw_input('Enter the Twitter consumer key secret: ')
ACCESS_TOKEN = raw_input('Enter the Twitter access token: ')
ACCESS_SECRET = raw_inp... |
857a40280552f8567d83aafff800b4aff5560273 | addyj4922/python-programs | /makes_twenty.py | 189 | 3.921875 | 4 | def makes_twenty(a,b):
if a==20 or b==20 or (a+b)==20:
return True
else:
return False
print(makes_twenty(int(input("Enter 1st no.")),(int(input("Enter 1st no.")))))
|
f634d75b6b8eefe5642f53344aa62967383344d7 | Aries0331/CMPUT391 | /assignment2/q0.py | 1,292 | 3.5625 | 4 |
#!/usr/bin/python
import sqlite3
# one degree in lon/lat equals to how many meters
LATSCALE = 111191
LONSCALE = 74539
# one unit in cartesian coordinates in meters: unitLatmeter * unitLonMeter
unitLatMeter = LATSCALE*(48.24900-48.06000)/1000
unitLonMeter = LONSCALE*(11.72400-11.35800)/1000
# 21m*27m
def convertLat... |
8f83f011b10ac975085d8903d06e7d8a47f618c2 | AndreeaParlica/Codewars-Python-Fundamentals-Kata-Solutions | /stopgninnips my.py | 962 | 4.125 | 4 | # Write a function that takes in a string of one or more words, and returns the same string,
# but with all five or more letter words reversed (like the name of this kata).
#
# Strings passed in will consist of only letters and spaces.
# Spaces will be included only when more than one word is present.
# Examples:
#
# s... |
f33ac48a8ff3826f05b211efe861847a582d4d6c | Simo0o08/DataScience_Assignment | /Ass-5/2.py | 177 | 3.8125 | 4 | import numpy as np
a1=np.array([1,2,3,4,0])
print(a1)
check=a1.all()
if check:
print("No element is zero")
else:
print("there is a element zero in array")
|
fc8a72adf70039ae760c486853b0c7f203722d14 | Michael-James-Scott/NumPy | /pandasdataframes.py | 1,512 | 4.09375 | 4 | import pandas as pd
grades_dict ={'Wally':[87, 96, 70 ], 'Eva':[100, 87, 90], 'Sam':[94,77,90], 'Katie' :[100,81,82], 'Bob':[83,65,85]}
grades = pd.DataFrame(grades_dict)
grades.index = ['Test1', 'Test2', 'Test3']
print(grades)
#print(grades[grades>=90])
#print test1 and test3 grades
#iloc will return a datafra... |
548f47acd75e2f8707c417e2b62fd9dfb566b820 | KoderDojo/codewars | /python/kyu-7-sorted-yes-no-how.py | 1,506 | 4.3125 | 4 | def is_sorted_and_how(arr):
"""
Determines if an array of integers is sorted or not.
If sorted, also determines if ascending or descending.
A easy solution would be to just compare the array to
versions that were sorted ascending and descending.
However, that would run in O(nlogn) assuming a gr... |
cce3e9aafb39ff33e6d7ff7975b3f2983cef0004 | bouteill/krextown | /python/stemvoc.py | 2,155 | 3.921875 | 4 | #!/usr/bin/env python
#
# stemvoc.py
#
# Stemming using vocal and consonant patterns in Bahasa Indonesia.
# Anung B. Ariwibowo
# May 2012.
#
# Outline ide
# Ada berapa jenis prefix dalam bahasa Indonesia? Masing-masing prefix
# itu diawali dengan huruf-huruf apa saja?
# Menurut situs wikipedia Indonesia
# http://id.w... |
5ead52128101198aeeea1f8f3c3c36e25929a549 | jia80H/python-learning-experience | /09 文件/08 with与上下文管理器.py | 1,356 | 4.03125 | 4 | """ with关键字的使用 """
try:
file = open('xxx.text', 'r')
except FileNotFoundError:
print('文件不存在')
else:
try:
file.read()
finally:
file.close()
# 使用with
try:
with open('xxxx.txt', 'r') as file:
file.read() # 不需要手动的关闭文件
# with关键字会帮助我们关闭文件
except FileNotFoundError:
pri... |
341a39801846f4248a2ad8cd126627a8bd82c20a | XPRIZE/glexp-data-standardization | /team-CHIMPLE/storybooks/extract_storybook_assets_from_json.py | 2,849 | 3.546875 | 4 | # Extracts storybooks from titles.json (copied from https://github.com/XPRIZE/GLEXP-Team-Chimple-goa/blob/master/goa/Resources/res/story/swa/titles.json),
# and stores them in a standardized format.
#
# Example usage:
# cd storybooks
# python3 extract_storybook_assets_from_json.py titles.json
#
# The extracted ... |
30b0aed6833e758ae61c5feae94ff40fa401ffd3 | hrf1007/leetcode | /14字典的使用.py | 256 | 3.515625 | 4 | dcountry={"中国":"北京","美国":"华盛顿","法国":"巴黎"}
dcountry.keys()
list(dcountry.values())
dcountry.items()
'中国' in dcountry
dcountry.get('美国','悉尼')
dcountry.get('澳大利亚','悉尼')
for key in dcountry:
print(key)
|
148c0f42078301f28fbce02dc545ac7b7995ef73 | feecoding/Python | /Classes/Program 8.py | 448 | 3.609375 | 4 | ##created by feecoding
class etudient:
pass
t=list()
n=int(input("Enter Size For Your Liste:"))
for i in range(n):
t.append(etudient())
t[i].nom=input("Enter Name:")
t[i].age=int(input("Enter Age:"))
t[i].moyenscolair=float(input("Enter Your Mean school:"))
s=0
for i in range(n):
s=s+t[i].age
... |
68ff64a2b2ea51f316b5e212710bc4fc17b986db | sooriyan1994/New_intersting_work | /try.py | 4,667 | 3.65625 | 4 | import numpy
import matplotlib.pyplot as plt
import time
'''Creates a regularly spaced hexagonal package of circles. The hexagonal array is disturbed by first crisscrossing them.
Then locally disturb them by finding the maximum movable distance by calculating the distance of the nearest
neighbour. '''
... |
4010ec971be88a94cb49cdef2bda534c71223ab7 | BramvdnHeuvel/Batteryboys | /classes/battery.py | 1,149 | 4.0625 | 4 | class Battery(object):
"""
Representation of a Battery containing the battery id, its x and y coordinate, and its current capacity
"""
def __init__(self, id, x, y, capacity):
self.id = id
self.x = x
self.y = y
self.capacity = float(capacity)
self.power = float(cap... |
76700503d94654e22132ceaecc20278a0db2910e | geovanemelo/exercicios-py | /78.py | 358 | 3.90625 | 4 | listinha=[]
for c in (range (1,6)):
listinha.append(int(input(f"Digite o {c}º valor da lista: ")))
print(max(listinha))
print(f'O maior valor da lista é {max(listinha)}',end=' ')
print(f'na posição {listinha.index(max(listinha))+1}')
print(f'O menor valor da lista é {min(listinha)}',end=' ')
print(f'na posição {lis... |
763cdcffa776949f2873815cbad76a8dfe8d3772 | PriyankaKhire/ProgrammingPracticePython | /Blind 75/Programs/Two Sum.py | 1,458 | 3.828125 | 4 | # Two Sum
# https://leetcode.com/problems/two-sum/
class Solution(object):
def addToHashTable(self, nums):
hashTable = {}
for i in range(len(nums)):
if (nums[i] not in hashTable):
hashTable[nums[i]] = []
hashTable[nums[i]].append(i)
return hashTable
... |
9231b9f05be350cc0b9eb96d08154539c7d8eeac | teckMUk/setsgame | /setgame/main.py | 2,041 | 3.5 | 4 | import argparse
FUNCTION_MAP = {"setsgame":set_finder , "drawcards": draw_12_card}
def set_prase() -> ArgumentParser:
parser = argparse.ArgumentParser(description="This file runs the game called sets game")
parser.add_argument("-s", "--setgame", dest="func", choices=FUNCTION_MAP.keys())
parser. add_argu... |
635551a8c0e0ba49afa274611536783500b1a8d0 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4173/codes/1679_1102.py | 1,231 | 3.71875 | 4 | # Teste todas as possibilidades de entradas 'H', 'h' e 'x'
# Se seu programa funciona para apenas um caso de tese, isso não quer dizer que ele vai funcionar para todos os outros
# Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigi... |
158a9549d47bdbe53f921ccdf64a58d352794149 | LauraQuillo/FibonacciNumbers | /fibonacci.py | 394 | 4.28125 | 4 | def Fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
print("The fibonacci sequence is determined by the function \"f(n) = f(n-1) + f(n-2)\", where \"f(0) = 0\" and \"f(1) = 1\"\nThis program return the value of f(n) in the function f(n) = f(n-1) + f(n-2)")
x ... |
1e8180b9cf489ab50417e9c32f27b3b1071a175f | jeong-yerim4898/algorithm | /Algorithm_study/B1036_36진수v2.py | 1,075 | 3.5625 | 4 | '''
5
GOOD
LUCK
AND
HAVE
FUN
7
'''
def threesix_to_decimal(c):
num = ord(c)
if 48 <= num <= 57: # num은 숫자이다.
return num - 48
elif 65 <= num <= 90:
return num - 65 + 10 # 16진법으로 10이상 하기 때문
def decimal_to_36(n):
S = ''
if n == 0:
S='0'
else:
while n>0:
a,b =divmod(n,36)
if 0<=b<... |
95944b981128bf6859c0a10812a56709b15961bf | here0009/LeetCode | /Books/CrackingtheCodingInterview/0810_ColorFillLCCI.py | 2,314 | 4.1875 | 4 | """
编写函数,实现许多图片编辑软件都支持的「颜色填充」功能。
待填充的图像用二维数组 image 表示,元素为初始颜色值。初始坐标点的行坐标为 sr 列坐标为 sc。需要填充的新颜色为 newColor 。
「周围区域」是指颜色相同且在上、下、左、右四个方向上存在相连情况的若干元素。
请用新颜色填充初始坐标点的周围区域,并返回填充后的图像。
示例:
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出:[[2,2,2],[2,2,0],[2,0,1]]
解释:
初始坐标点位于图像的正中间,坐标 (sr,sc)=(1,1) 。... |
d462b0fde81d5ace46cebdac7204b864951e0715 | amolsawant844/SEM-4 | /Python-basic-programs/Functions/Decorators.py | 206 | 3.90625 | 4 | #a decorator to increase the value of a function by 2
def decor(fun):
def inner():
value=fun()
return value+2
return inner
def num():
return 10
res=decor(num)
print(res())
|
9281d8509cdc29ed1585bdbc5ffa6c4a445d2423 | gistable/gistable | /all-gists/5406598/snippet.py | 702 | 3.765625 | 4 | # Make a function that does a half and half image.
def halfsies(left,right):
result = left
# crop the right image to be just the right side.
crop = right.crop(right.width/2.0,0,right.width/2.0,right.height)
# now paste the crop on the left image.
result = result.blit(crop,(left.width/2,0))
# ... |
b59e022410490a27d2244dff9d534f71ff3887ea | safwanc/python-sandbox | /algorithms/dijkstra.py | 845 | 3.765625 | 4 |
from collections import defaultdict
import heapq
edges = [
('A', 'B', 7),
('A', 'D', 5),
('B', 'C', 8),
('B', 'D', 9),
('B', 'E', 7),
('C', 'E', 5),
('D', 'E', 15),
('D', 'F', 6),
('E', 'F', 8),
('E', 'G', 9),
('F', 'G', 11)
]
def dijkstras(edges, node):
graph = defaul... |
4cee8377f987576e7d14026476af33f50294d4a6 | trangttt/PythonPractice | /sum_multiples.py | 537 | 4.125 | 4 | import sys
def find_multiples(n):
'''Find sum of all multiples of or and 5
'''
set = range(n)
set = filter(lambda x: not x%3 or not x%5, set)
return set
def main(n):
import ipdb; ipdb.set_trace()
ret = find_multiples(n)
print ret
import ipdb; ipdb.set_trace()
print sum(ret)
if... |
80e551f4cbdee51c33c46c831925bdb60793cafa | antoinech2/ISN-exercices-Python-Ann-e-1 | /partie 1/ex8,1).py | 216 | 3.84375 | 4 | chaine=input("Entrez une phrase ou un mot.")
long=len(chaine)
a=long-1
char_inverse=""
while(a>=0):
char_inverse=char_inverse+chaine[a]
a=a-1
print("Voici votre phrase/mot inversé(e):",char_inverse)
|
292ccb715032c9de14d53b0d8e25d118c5878b45 | kaylasommer/bin2dec | /intro.py | 754 | 3.8125 | 4 | age = 20
gender = 'female'
if age >= 21 and (gender == 'female' or gender == 'male'):
print('go have a drink')
else:
print('go have your parents buy you a drink')
for x in range(20, -50, -5):
print("{0} to the {1} power is {2}".format(x, 2, x**2))
evens = []
for x in range(0, 20, 2):
for y in range(3... |
bf77a0b6c5978a349d9e1db63d007d97a94a1f3d | snail15/CodingDojo | /Python/week3/Checkboard/checkboard.py | 251 | 3.78125 | 4 | def drawCheckboard(row):
for i in range(1, row+1):
if i % 2 != 0:
print("* * * *")
else:
print(" * * * *")
drawCheckboard(8)
print("-------------")
drawCheckboard(1)
print("-------------")
drawCheckboard(3) |
10f99b6b3b0a70cc1e0eb6310300865e6e462351 | langseth1/DragonLore | /CmdGame.py | 1,817 | 4.15625 | 4 | #DragonLore A Game Created By Fury. PS: This Application Will Not Send Your Name
print("Enter a name.")
name = input()
if name != "":
print("Thank you for entering a name")
else:
print("You Did Not Enter A Name")
print("DragonLore a Game by Fury")
myName = input("if you want to start the game press[... |
faba4201d1712cff38c36137ce60b588da190950 | ritikbadiya/Algorithmic-Toolbox-assignment-solution | /week3/covering_segments.py | 737 | 3.71875 | 4 | # Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
segments=sorted(segments,key=lambda x:x[0])
no=[segments[-1][0]]
for i in segments[::-1]:
f=False
for j in no:
if(i[0]<=j and i[1]>=j):
... |
1fa79b15b8a1bde9511cb5c7121f98ebe21b5732 | tharang/my_experiments | /python_experiments/09_exp_mod_intDiv.py | 217 | 4.34375 | 4 | # -*- coding: utf-8 -*-
__author__ = 'vishy'
a = 10
b = 3
print("integer division in python, 10//3 = {}".format(a//b))
print("remainder when dividing, 10/3 = {}".format(a%b))
print("10 power 3 = {}".format(a ** 3))
|
c61285989ac3681469dc9296828002f341388d80 | chenjiegd/Python_exercises | /第一章例题/圆面积计算.py | 84 | 3.703125 | 4 | radius = 25
area = 4.1415 * radius * radius
print(area)
print("{:.2f}".format(area)) |
f8bc614232cda95dcb108a6f906abec09d630b4b | Samih754/randomstuff | /Python/Part1/wage.py | 387 | 4.0625 | 4 | time = input("How much time did you spend working?:")
rph = input('what is your rate per hour.')
time = float(time)
rph = float(rph)
if time <= 36.0 :
pay = time * rph
print('Your revenue is:', pay)
else:
time = 36
timeplus = time - 36
pay = (time * rph) + (rph * 2.5) * timeplus
prin... |
28a8accba14327a0e1e9316bfca8c796d5f54de7 | hareeshkmurali/Python | /class1.py | 189 | 3.65625 | 4 | number=input("enter the values")
class Nun:
def __init__(self,number):
self.number=number
def printNumber(self):
print("the Number is%s"%(self.number))
a=Nun(number)
a.printNumber()
|
52602899c842c44b1200d33dc70fa23984661b62 | fnnntc/leetcode | /search/First Bad Version.py | 739 | 3.515625 | 4 | n=3
bad=2
def isBadVersion(x):
if x==2:
return(True)
"""
l,r=1,n
versions = {}
if len(nums)==0:
return (-1)
while l<r:
m = (l+r)//2
isBad = isBadVersion(m)
if not isBad and m+1 in versions:
if versions[m+1]==True:
print(m+1)
elif isBad and l==n:
print(l)
... |
a430e9bb28ae56dfe1309b2debbfff29b73a41b8 | milincjoshi/Python_100 | /95.py | 217 | 4.40625 | 4 | '''
Question:
Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
'''
import itertools
l = [1,2,3]
print tuple(itertools.permutations(l)) |
d0fa5df91792fa0600bdf2d671450951302cf5ee | attojeon/python_datastructures | /mines_1.py | 1,565 | 3.984375 | 4 | ##################################################
# 지뢰찾기 게임 작성 1
# - 랜덤하게 matrix에 지뢰 심기
# - 지뢰의 위치를 알려주는 힌트 연산하기
# matrix 출력하기
###################################################
import random
import sys
import os
import pygame as pg
from time import sleep
matrix = []
mines = 20
rows = 0
cols = 0
mine_flag = 9
de... |
fb849e4f4a32caa76f5cdfcbc4953b297752c8db | chanshik/codewars | /functional_addition.py | 356 | 3.9375 | 4 | """
Create a function add(n) which returns a function that always adds n to any number
addOne = add(1)
addOne(3) # 4
addThree = add(3)
addThree(3) # 6
"""
def add(n):
return lambda x: x + n
from unittest import TestCase
class TestAdd(TestCase):
def test_add(self):
self.assertEqual(4, add(1)(3))
... |
f219f4636dba5cad0653d026e4e907c0211a33bd | PCA1610/Smartninja | /Uebung07/numberGuess.py | 558 | 3.984375 | 4 | import random
def main():
rant_value = random.randint(1, 100)
for x in range(0, 7):
guess = int(raw_input("Guess the secret number (between 1 and 100): "))
if guess == rant_value:
print "You guessed it - congratulations! It's number %d :)" % (rant_value)
break
... |
7ffeddf503ddecf88b1aeea7e7419cff2442dc3a | EternallyMissed/practicas-python | /suma.py | 153 | 3.671875 | 4 | a = input("ingrese un numero")
b = input("ingrese otro numero")
a = int (a)
b = int (b)
c= a + b
print("la suma de los numeros ingresados es", c)
|
2507cc570a44ac860b0f9f06c0a768dd7bccba92 | MrSyee/algorithm_practice | /string/merge_strings_alternately.py | 1,517 | 4.03125 | 4 | """
1768. Merge Strings Alternately (Easy)
https://leetcode.com/problems/merge-strings-alternately/
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.