blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cd7a36be18ac724e1b833670c3be396b28c6bca7 | rcv-legado/sci-libs | /pie_chart_simple.py | 329 | 3.6875 | 4 | # Ejemplo casi trivial de como hacer un Pie plot
import matplotlib.pyplot as plt
valores = [10, 25, 40, 80]
colores = ['b', 'r', 'g', 'w']
etiquetas = ['A', 'B', 'C', 'D']
fig = plt.figure("Ejemplo de Pie plot")
sp1 = fig.add_subplot(111, title='Valores')
pie = sp1.pie(valores, colors=colores, labels=etiquetas)
p... |
4f7744ef6c19094163d9d7346d7c23a99f9e3aa3 | arisu-chan/Algoritmos_CC_UCB | /Algoritmos_em_Python/loja_tintas.py | 325 | 3.75 | 4 |
area = int(input("Digite a area:"))
litros = area // 6
if area % 6 > 0:
litros = litros + 1
latas = litros // 18
if area % 18 > 0:
latas = latas + 1
galao = litros // 4
if litros % 4 > 0:
galao = galao + 1
precoLatas = latas*80
precoGalao = galao*25
print(precoLatas)
print(precoGalao)
... |
846d07ee0e31a600f9e56994892392182bbdcc5f | nerohuang/LeetCode | /Array/922. Sort Array By Parity II(Easy).py | 667 | 3.515625 | 4 | class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
result = [0 for i in range(len(A))];
eveni = 0;
oddi = 1;
for num in A:
if num % 2 ==0:
result[eveni] = num;
eveni += 2;
else:
result[oddi... |
fca8fc32ffcd393fcc76a83a20c90d2d6ac4dc48 | catern/rsyscall | /python/wish/__init__.py | 7,080 | 3.546875 | 4 | """A typed API for generically prompting the user for a typed value, typically by dropping to a REPL
The metaphor we use is "wishing" for a value of some type, and then getting back a value
of that type. We use the wish function and the Wish class to do this. We follow many
patterns of exception handling, so `wish` ca... |
d44ae853b1b856781b38ccbfcc02d751c3acfcbf | xiaohuixianone/py-patterns | /State/state2.py | 2,242 | 3.625 | 4 | # class Connection:
# """普通方案,好多个判断语句,效率低下~~"""
#
# def __init__(self):
# self.state = 'CLOSED'
#
# def read(self):
# if self.state != 'OPEN':
# raise RuntimeError('Not open')
# print('reading')
#
# def write(self, data):
# if self.state != 'OPEN':
# ... |
8583e4fe12204f227f1731b36513c04c4aa4fedb | LKlemens/university | /python/6zestaw/frac/Frac.py | 1,496 | 3.578125 | 4 | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
class InvalidValueInDenominator:
pass
class Frac:
"""Klasa reprezentująca ułamek."""
def __init__(self, x=0, y=1):
self.x = x
self.y = y
if y == 0:
raise InvalidValueInDenominator("Invalid value in denominator!")
def... |
3855b0476668ea47d46bfcaeba63b8b64de5049a | HoangTuan110/Juliet | /main.py | 3,526 | 4.34375 | 4 | # Import re for Regex support
import re
# List of operators
operator_list = ["+", "-", "*", "/", "^"]
# Operators for integer
class IntOperator:
def Plus(first, second):
print(int(first) + int(second))
def Minus(first, second):
print(int(first) - int(second))
def Multiply(first, second):... |
52d6a1d4ef94a17eed3f42843327f05a84f822b9 | rbk1234567/python_basics | /secondapp.py | 3,580 | 4.375 | 4 | #example of variables declaration, type based on syntax used
number1 = 10
number2 = 20
float1 = 3.1415
string1 = "the PI value: "
separatorline = "------------------------------------------------------------"
#example of printing string in quotes -----------------------------------------------------------------------... |
deeee8fbae71e680b4fe5e7a073755396a20ee5a | mirianfsilva/data-structures | /queue.py | 348 | 3.859375 | 4 | #using a Python list as a queue
class Queue(object):
"""docstring for Queue"""
def __init__(self, args):
#super(Queue, self).__init__()
self._args = []
def enqueue(self):
self._args.insert(0, arg)
def dequeue(self):
return self._args.pop()
def is_empty(self):
return self._args == []
def size(self... |
9da834b1168e8d7e4dadba7b3c7af506ab690aa3 | marsxat/ev3 | /test.py | 1,175 | 3.84375 | 4 | #!/usr/bin/python3
# Parallel Parking Program
# Parallel Parking means the truck will park in a spot next to it's current place by going forward, then
# reversing into the parking spot.
#
# 1: The truck will go forward 3 rotations, then stop.
# 2: The truck's front wheels will turn left (maximum)
# 3: Reverses 1 rotat... |
51235dc97bc9138b22b4477895d4ebcfc7d9fc4b | daniel-bogdoll/unknown_objects_roads | /mseg_semantic/mseg-api/mseg/utils/tsv_utils.py | 2,669 | 3.625 | 4 | #!/usr/bin/python3
import csv
import os
from typing import List, Mapping, Union
"""
Set of utilities for working with tab-separated values (tsv) files.
The tsv format is a convenient way to store a mapping, e.g. a
mapping between taxonomies.
"""
def download_tsv(tsv_fpath, spreadsheet_url) -> None:
"""Use a sy... |
67652712e4b9f9b07c6905e6ca3908d26107a478 | poschi3/AdventOfCode2015 | /day07/day07.py | 1,599 | 3.5625 | 4 | import re
leftright = re.compile("^(.*)\s->\s(.*)$")
instructions = dict()
results = dict()
def get_value(var):
if var.isdigit():
return int(var)
if var in results:
return results[var]
value = evaluate(var)
results[var] = value
return int(value)
def evaluate_three(s... |
b28801269d5ff9c2b86bad91d3c873a87593ae6d | GGMagenta/exerciciosMundo123 | /ex086.py | 454 | 4.15625 | 4 | # Crie um matriz 3x3 com valores lidos do teclado, e mostre na formatação correta
matriz = []
# matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
linha = []
for c in range(0, 3):
n = int(input(f'Digite um número para [{l}, {c}]: '))
linha.append(n)
matriz.append(linha[... |
d84cd65b3b2f545be3ece354741ace1ae1f68242 | JuzerShakir/Python-Programs | /Mini_Programs(Intermediate)/Num_week_days.py | 961 | 4.1875 | 4 | """ Author : Juzer Shakir || Created on 10 Nov 2017 || Last modified on 18 Dec 2017 1:15pm
Topic : Calculating no. of week and days"""
"""----------------------------------------------------------------------------------------------------------------------------------------------------------"""
# defining fu... |
b99c012708daa5f42aac037af69769fe53ee0d07 | JooPoo/talen | /scripts/quickstart.py | 2,844 | 3.515625 | 4 | #!/usr/bin/python
import os
# First we write to users.
print("First we create users...")
users = {}
if os.path.exists("config/users.txt"):
print("FYI: config/users.txt exists, this will append to it")
while True:
uname = input("username (empty to continue) >>\n")
if len(uname.strip()) == 0:
break... |
89947488512c91562541ad0ffddd75a80007e496 | svrishi/paracron | /src/paracron/models/db.py | 4,473 | 3.5625 | 4 | import numbers
import datetime
from validators.slug import slug
class Project:
"""
Project defines the 'project' tasks configuration with recurring
scheduling time defined as interval*count. For example, to run
a project's tasks every 5 minutes then set interval to minutes
and count to 5. Tasks li... |
5a4e1a53cfca4216371fc136af986680fab52cb2 | Aasthaengg/IBMdataset | /Python_codes/p02833/s381605790.py | 173 | 3.53125 | 4 | N = int(input())
if N%2==1:
print(0)
else:
ans = 0
judge = 10
while True:
if judge > N:
break
else:
ans += N//judge
judge *= 5
print(ans) |
b8e4c539253013d499cfc9a0037987a42e752ff0 | mikehung/competitive-programming | /leetcode/python-sol/693.Binary_Number_with_Alternating_Bits.py | 391 | 3.546875 | 4 | class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
prev_char = None
for char in format(n, 'b'):
if prev_char and prev_char == char:
return False
prev_char = char
return True
for _ in ran... |
ddc162129a721a44bcdcacb31ec6fbb7c554560b | jullynobre/research-and-ordering | /counting-sort/counting-sort.py | 351 | 3.640625 | 4 | def counting_sort(array, maxval):
m = maxval + 1
count = [0] * m
for a in array:
count[a] += 1
i = 0
for a in range(m):
for _ in range(count[a]):
array[i] = a
i += 1
return array
print(counting_sort( [1, 4, 7, 2, 1... |
33f87885c428888e7b5f627177b8eb5166c2ea74 | ag8/Cloofia | /player.py | 2,123 | 3.5 | 4 | from roles import *
"""
Class for player/user
"""
class Player:
def __init__(self, user, roles):
self.user = user
self.roles = roles
self.life = [True, True]
self.is_assassin = False
self._once_an_assassin()
# assign player to each Role"
for role in self... |
19abb0e8494a5371c0732d3e6d0ca16e22544365 | jamiekiim/ICS4U1c-2018-19 | /Working/practice_rectangle.py | 735 | 4.375 | 4 | '''
1. Define a class Rectangle that has attributes width and height defaulted to 0.
'''
class Rectangle():
'''
A class modelling wight and height
'''
def __init__(self):
self.width = 0
self.height = 0
def get_area(rec):
"""
calculate the area of the rectangle
@param widt... |
bf8a99fbd856b318ee0ed86f17d5b8010905bc49 | sh-tatsuno/python-algorithm | /structure/tree/bfs.py | 4,108 | 4.1875 | 4 | # implementation of breadth first search tree
class Node(object):
def __init__(self,value = None):
self.value = value
self.left = None
self.right = None
def set_value(self,value):
self.value = value
def get_value(self):
return self.value
... |
4169b4dee592981747247fd179bd32ee90fbe7e5 | Gackle/leetcode_practice | /945.py | 3,036 | 3.5625 | 4 | # coding: utf-8
""" 945. 使数组唯一的最小增量
给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1。
返回使 A 中的每个值都是唯一的最少操作次数。
示例 1:
输入:[1,2,2]
输出:1
解释:经过一次 move 操作,数组将变为 [1, 2, 3]。
示例 2:
输入:[3,2,1,2,1,7]
输出:6
解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。
可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。
提示:
0 <= A.length <= 40000
0 <= A[i] < 40000
思路:
1.... |
9000956887f8e14157735b666aa2121fb03b7aa5 | zedaster/ImaevIntensive | /25_2/25_10.py | 1,724 | 3.953125 | 4 | import functools
@functools.lru_cache()
def is_prime(n):
if n == 1:
return False
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
# Выводит массив из пар различных простых чисел, произведенеие которые даст n
@functools.lru_cache()
def get_two... |
b0f14cbbc905f7aa4525d37d6439196ef9a3d13c | asd3258/yzu_python_20210411 | /day05/1_list串列.py | 532 | 3.953125 | 4 | # 數組:list(元素可重複) set(元素不可重複) dict(key/value)
scores = [100, 90, 80] # list
scores.append(70)
print(scores)
print(scores[1]) # 取得維度1
print(len(scores)) # 取得元素個數
print(scores.index(80)) # 取得某個元素的維度值
print(max(scores)) # 取得元素最大值
print(min(scores)) # 取得元素最小值
print(max(scores), min(scores))
# 走訪每一個元素I
for x in scores:... |
3ec56a3009d3835bae3a11e5c1529fc1aed49498 | Ajat98/LC-Solutions | /reverseWordsInString3.py | 712 | 4.21875 | 4 | """
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not b... |
67b8922d7fa56c3c4f03fb5dbb4e7c76d238868a | ppysjp93/Effective-Computation-in-Physics | /NumpyArrays/slicingAndViews.py | 2,160 | 4.59375 | 5 | import numpy as np
# Numpy arrays have the same slicing sematics as Python lists when it comes to
# accessing elements or subarrays.
print("\nSlicing and Views of Arrays\n")
a = np.arange(8)
print("a = " + str(a))
print("a[::-1] = " + str(a[::-1]))
print("a[2:6] = " + str(a[2:6]))
print("a[1::3] = " + str(a[1::3]))... |
16d2fa375d7a711e52700fadf14b65514285540f | kapitsa2811/leetcode-algos-python | /leetcode/621_taskScheduler.py | 2,622 | 3.90625 | 4 | """
You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be... |
a1c780497305cbbdc8fb43a4646635c4bebbedd1 | DuvanDu/ProgramacionI | /Parciales/punto3.py | 242 | 3.625 | 4 | listaC = [36,37,38,35,36,38,37.5,38.2,41,37.4,38.6,39.1,40.3,33]
mensajeMayor = 'La temperatura maxima ingresado es -->'
mensajeMenor = 'La temperatura minima ingresado es -->'
print(mensajeMayor, max(listaC))
print(mensajeMenor, min(listaC)) |
4ae65747a9713faea7da3b9fbc99ff50443ea6c9 | akshayrana30/Data-Structures-and-Algorithms | /#1 LeetCode/125. Valid Palindrome.py | 1,330 | 3.875 | 4 | import string
class Solution:
def isPalindrome(self, s: str) -> bool:
# This is 2*O(n) runtime and O(n) memory
# stack = []
# for val in s:
# if val.lower() not in string.punctuation and val!=" ":
# stack.append(val.lower())
# for val in s:
... |
b6e8af01824413d029bc8b3154c8b0e786de77fd | MineRobber9000/TF2-SpyBindMaker | /code/menus.py | 273 | 3.59375 | 4 | def parenMenu(choices,prompt="> "):
i = 0
for item in choices:
i += 1
print("{!s}) {!s}".format(i,item))
while True:
try:
choice = int(raw_input(prompt))
choice -= 1
if choice in [x for x in range(0,len(choices))]:
return choice
except:
continue
|
8ba2d7f42e3d2097f381b8d013f7f38ff6581cdd | jackpickus/tbased-game | /people.py | 244 | 3.6875 | 4 | from PrintOut import print_words
class Person:
def __init__(self, name, saying):
self.name = name
self.saying = saying
def speak(self):
print_words('My name is ' + self.name)
print_words(self.saying)
|
b9f2d8a4df884ecd7f11983a97c8219655b130b8 | mattsteinpreis/hr | /Domains/Regex/hackerrank_tweets.py | 751 | 3.984375 | 4 | import re
def case_insensitive_pattern(s):
p = ''
for ch in s:
p = p + '(' + ch + '|' + ch.upper() + ')'
return p
def contains(s, p):
m = re.findall(p, s)
return bool(m)
def test():
word = 'hackerrank'
pattern = case_insensitive_pattern(word)
a = 'I just scored 27 points in... |
43764459fc9afdf76b4b727258abfc075b6fac04 | scarletstudio/transithealth | /api/metrics/Covid_cdd_metric.py | 2,251 | 3.578125 | 4 | from api.utils.database import rows_to_dicts
class Covid_CDD_Metric:
"""
Metrics for community area data.
"""
def __init__(self, con):
self.con = con
def cases_for_given_age(self, givenAge):
"""
Returns the number of cases week by week from March 2020 - July 2021 given
... |
0d6d452b9dc1de0ef1907770f50e9f25ff1a0e29 | Jesselml/DataStructure | /Data structure/Stack_structure/main.py | 317 | 3.546875 | 4 | from stack import Stack
stack = Stack()
#检测是否为空
print (stack.isEmpty())
#添加元素
for i in range(10):
stack.push(str(i))
print (stack.showStack())
#删除栈顶元素
stack.pop()
print (stack.showStack())
#检测是否为空
print (stack.isEmpty())
#反馈栈的大小
print (stack.getSize()) |
540216f1c817cfc3c3bcf2197ae6f4b30f7beeb9 | vega832/tr06_vega_cristina | /vega/doble_02.py | 461 | 3.578125 | 4 | #ejercicio 02
import os
#delclarion de variables
trabajador,renumeracion_mensual="",0
#INPUT VIA OS
trabajador=os.sys.argv[1]
renumeracion_mensual=int(os.sys.argv[2])
#PROCESSING
#si el la renumeracion mensual es mayor 100
#mostrar tiene renumeracion anual
#caso contrario se muestra "no tiene renumeracion anual"
if (r... |
acfc0da063ac7021901b3a177fe6594803dca92a | Divisekara/Python-Codes-First-sem | /PA2/PA2 ANSWERS 2015/10/Asitha/pa2-10-2015.py | 991 | 3.578125 | 4 | def getText():
try:
fo=open("FileIn.txt","r")
L=fo.read().split()
fo.close()
except IOError:
print "File not found"
pass
else:
if len(L)<1000:
for i in L:
if len(i)<20 and i.isalpha()==True:
continue
... |
0052a8a31472c73153e8b2daabab0d79cb595ce1 | jaikrgupta/topgear_python1x | /EvenOdd.py | 101 | 4.15625 | 4 | num = int(input("Enter a number: "))
if num % 2:
print "Odd Number"
else:
print"Even number" |
75e1875d123f37227aecd398b895d01ecd8a53ac | SlawomirMiszkurka/Zadania-2 | /Zad 14.py | 329 | 4.53125 | 5 | #####
# Calculation of the area and circumference of a circle
##
# determine radius and PI
radius= 5
PI= 3.14
# calculate area
area=PI*radius**2
# calculate circumference
circumference= PI*radius*2
# display results
print(f'"When radius is {radius} area equals {area} and circumference equals {circumfere... |
d6e4b0e71afc2b6e88e43c40f9813571708b54d0 | benkrichman/geocontour | /geocontour/masksearch.py | 14,461 | 3.59375 | 4 | """
Functions for finding a mask on a lat/lon grid from an input boundary
=====================================================================
"""
import warnings
import numpy as np
import shapely as sh
import matplotlib.path as mplp
import geocontour.grid as gcg
import geocontour.maskutil as gcmu
def center(latitude... |
20eebc469dec4f8c152a61f7ea5c04b53092e976 | sashakrasnov/datacamp | /24-data-types-for-data-science/4-handling-dates-and-times/03-pieces-of-time.py | 1,804 | 4.25 | 4 | '''
Pieces of Time
When working with datetime objects, you'll often want to group them by some component of the datetime such as the month, year, day, etc. Each of these are available as attributes on an instance of a datetime object.
You're going to work with the summary of the CTA's daily ridership. It contains the... |
caa751b7b83175d619d1563abbe88d2fbe99c527 | bhavnavarshney/Algorithms-and-Data-Structures | /Python/Binary-Insertion-Sort.py | 228 | 4.25 | 4 | print('****** Binary Insertion Sort **********')
# Used to reduced the number of comparison in Insertion Sort O(log n) but shifting the elements after insertion takes O(n)
# Complexity : O(nlogn)-> Comparisons and O(n*n) swaps
|
0509c0238fc33547e5b2ab3a3e79742d439cd248 | rocharayani/chatroom | /Client.py | 1,380 | 3.5625 | 4 | import socket
import sys
import time
s = socket.socket()
cliente = input(str("Digite seu nome: "))
host = input(str("Por favor, inclua o hostname do servidor: ")) #Pede o nome do host, para realizar a conexão do servidor, tbm poderia pedir o Ip, tanto faz.
port = 8080 #especifica a porta que ja consta no servidor par... |
039bcc834d3ac4f77cf4245289c97709bfd56d46 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4004/codes/1636_2730.py | 190 | 4.0625 | 4 | # Ao testar sua solução, não se limite ao caso de exemplo.
x = float(input("coordenada x: "))
y = float(input("coordenada y: "))
if y < 0:
print("Inferiores")
else:
print("Superiores") |
643e3f3da3791d85d6c551d5d747a675278bbcbf | bantic/jupyter-notebooks | /code-forces/contest-1367/c.py | 976 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[13]:
#!/usr/bin/env python
# coding: utf-8
# In[30]:
# In[31]:
def solve(s, k):
s = '1'+'0'*k + s + '0'*k + '1'
blocks = s.split('1')
# print(blocks)
total = 0
for block in blocks:
size = len(block)
if size == 0:
continue... |
8a0e59f85e8e5a04f3ce440feadde4aaa36a76d6 | hyu-likelion/NESI | /week1/조민주/one.py | 170 | 3.59375 | 4 | A,B=input().split()
A= int(A)
B= int(B)
def bigyo (x,y):
if (x>y):
print ('>')
elif (x<y):
print ('<')
else:
print ('==')
bigyo(A,B) |
4eb23bbc5e61bcb61b967a8009c45500444a2191 | lirixiang123/algorithm | /src/剑指offer/58-isSymmetrical.py | 912 | 3.53125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/7/17 15:48
# @Author : lirixiang
# @Email : 565539277@qq.com
# @File : 58-isSymmetrical.py
"""
请实现一个函数,用来判断一棵二叉树是不是对称的。
注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
"""
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# ... |
4d9d75ac57f3372e5eb3edb6fbd32dd4026d01cf | yschoi9930/PythonStudy | /ch3/제어문/반복문/for/3의 배수 출력.py | 140 | 3.984375 | 4 | # 3의 배수 출력
# 1에서 20 수 중에서 3의 배수만 출력
for x in range(1,21) :
if x % 3 == 0 :
print(x, end=" ") |
fab508288f412d51918036704c6d8e66ec786177 | msk20msk20/Python | /20190918_28.py | 172 | 3.90625 | 4 | a = 1
b = 1
c = 12
if(a+b<c):
print ("false")
elif(b+c<a):
print ("false")
elif(a+c<b):
print ("false")
else:
print ("true")
|
cfde2a9567ab04457e6074a01ed623f1e44093c4 | brian-yu/advent | /2016/4/room.py | 925 | 3.515625 | 4 |
def freqDict(letters):
freq = {}
for letter in letters:
if letter not in freq:
freq[letter] = 1
else:
freq[letter] += 1
return freq
def decrypt(wordList, ID):
alpha = [chr(i) for i in range(97, 123)]
words = []
for word in wordList:
s = ""
for letter in word:
s += alpha[(alpha.index(letter) +... |
b255c8b2f9145cd6da48145f096d8455ca4151f8 | YijinLinHere/100DaysPythonChallenge2021 | /Day022/main.py | 893 | 4.15625 | 4 | # 196. Set up the Main Screen
# 197. Create a Paddle that responds to Key Presses
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width = 800, height = 600)
screen.bgcolor("black")
screen.title("Pong")
# set tracer == 0
# wait for we drawing the canvas and show the final screen only
# it should put... |
ef086871dc6a35789b61c564d2775a662e75c566 | da-ferreira/uri-online-judge | /uri/2879.py | 164 | 3.71875 | 4 |
quantidade = int(input())
jogos = ''
for i in range(quantidade):
a = input()
jogos += a
jogos = jogos.replace('1', '')
print(len(jogos))
|
9a91e38383c5739c1fef69e85323cea2df82c7a5 | clarkngo/python-projects | /unit-test-sample/02-find-the-diff.py | 498 | 3.609375 | 4 | class Solution:
def palindrome(self, string):
from re import sub
s = sub('[/W_]', '',string.lower())
return s == s[::-1]
import unittest
a = Solution()
class Test(unittest.TestCase):
def test(self):
self.assertEqual(a.palindrome('tacocat'), True)
def test2(self):
s... |
450f96892e75e623383b22f1fdf4d06ecb20f44e | Nicobossio42/Exercises3004 | /Ex4.py | 224 | 4 | 4 | x = float(input("Introduzca el primer numero: "))
y = float(input("Introduzca el segundo numero: "))
print("La suma es: ", x + y)
print("La resta es: ", x - y)
print("El producto es: ", x * y)
print("El residuo es: ", x / y) |
e2c9ff737e77f277636ee5c7550ffe77b0a30603 | PrarthiVyas/Employee_Mini_Project | /empApp1.py | 4,907 | 4.0625 | 4 |
emp_final=[]
flag=False
emp_name=""
def addemp():
print("Add employee")
emp=[]
id2=input("ID: ")
name=input("Name: ")
designation=input("Designation: ")
salary=int(input("Salary: "))
status=input("Status: ")
emp.append(id2)
emp.append(name)
emp.append(d... |
46718dec2f32dcee0e273d2828ff97858774601e | weizt/python_studying | /函数/25-装饰器的练习.py | 1,516 | 3.53125 | 4 | # 需求:权限验证
# 权限值相加,得到的值就是用户所拥有的权限 ,如6=4+2,则拥有读写权限
# 用二进制来判断用户的权限关系
# 计算方式:用户权限 & 权限因子 做按位与运算,全为零则无权限
user_permission = 7 # 用户权限 0110
# 下列称之为权限因子
READ_PERMISSION = 4 # 读取权限 0100 从右起第三位有1表示read权限 0100 & 0110 ==> 0100
WRITE_PERMISSION = 2 # 写入权限 0010 从右起第二位有1表示write权限 0010 & 0110 ==> 0010
EXE_PERMISSION = 1 # 执... |
66467ece8bb14cd94ac9190550f73c0cd69f00a3 | EthAlenazi/python_learning | /week10th/python_64.py | 965 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 22:00:14 2019
@author: ETH
"""
try:
print(A)
except NameError:
print("Error type :")
print("not defined !! ")
except :
print("Error type :")
print("it has another Error ")
print("================================")
try:
print... |
c5b0ed8e5f493028892ac304cf3c6a74a4eb0caa | yseakshay77/Udacity-data-structures-and-algorithms-nanodegree | /Assignment 3/Problem 7.py | 2,475 | 3.6875 | 4 | class RouteTrie:
def __init__(self):
self.root = RouteTrieNode()
def insert(self, path):
route_list = split_path(path)
current_node = self.root
for route in route_list:
if route not in current_node.children:
current_node.insert(route)
... |
759c71632f3d991061988c44d5479350f979187f | SriCharan220800/RomanReigns | /nested loops.py | 502 | 3.59375 | 4 | if __name__ == '__main__':
n=int(input())
scores=[]
names=[]
for i in range(n):
x=[]
name = input()
score = float(input())
names.append(name)
scores.append(score)
mini=min(scores)
l=[]
for i in range(n):
if scores[i]>mini:
... |
c44a954d979eb9cdb49461815a19355cb9dde9d0 | sagunji/100DaysOfCode | /python/01/summing.py | 305 | 3.6875 | 4 | def sum_numbers(numbers=None):
sum = 0
if (
isinstance(numbers, list)
or isinstance(numbers, range)
or isinstance(numbers, tuple)
):
for i in numbers:
sum = sum + i
else:
for j in range(1, 101):
sum = sum + j
return sum
|
2f5948dd0b2a791b13f91cf306d2c57941dc8cd2 | Aasthaengg/IBMdataset | /Python_codes/p02860/s984022710.py | 91 | 3.53125 | 4 | n = int(input())
s = input()
t = s[0:n//2]
if s == t+t:
print("Yes")
else:
print("No")
|
23593e1754be4db91ac9425c15b7c029a88677f7 | YYN117/Demo | /qianfeng/day17/3.线程/2.多线程.py | 702 | 3.71875 | 4 | import threading,time
a = 10
def run(num):
print('子线程(%s)开始'% (threading.current_thread().name))
time.sleep(2)
#实现线程功能
print('打印',num)
print('子线程(%s)结束'% (threading.current_thread().name))
if __name__ == '__main__':
#任何进程默认启动一个线程,称为主线程,主线程可以启动新的子线程
# current_thread():返回当前线程的实例
print... |
925e3b532140f6715e023eee192ab2ce60b35185 | Firasnafti67/problemSolving | /617A.py | 202 | 3.75 | 4 | x = int(input())
n = 0
while x:
if(x>=5):
x = x-5
n+=1
elif(x==4):
x = x-4
n+=1
elif (x==3):
x = x-3
n+=1
elif (x==2):
x = x-2
n+=1
else:
x = x-1
n+=1
print(n) |
8c54f7fd9e20edaf592455b2eac89055fca485a1 | luigim1998/Questoes_URI_Luigi_Muller | /URI 1537 - Fila do Banco.py | 224 | 3.65625 | 4 | def fatorial(n):
if n == 0 or n == 1:
return 1
else:
return n*fatorial(n-1)
N = int(input())
while N != 0:
casos = fatorial(N)/fatorial(3)
print(int(casos))
N = int(input())
|
e37e61d617c6c9fa568448af368ba99150a77a1e | prasadchaitu766/Django | /16-02-2019/python/generator2.py | 116 | 3.640625 | 4 | no= int(input("enter anumnber"))
x=(y*no for y in range(1,11))
for e in x:
print(next(x))
# print(next(x)) |
242fff470b474ada97b8ae23f8b09e106baf3428 | mgjeffries/python-learning | /helloWorldWithStars.py | 696 | 4.40625 | 4 | # For learning purposesWe need a function to be used for decoration
def decorateWithStars(f):
# The decorator needs to return a function
def is_returned():
# The returned function can take actions, and alter the original,
# Or it can leave the function un-changed
print("*****")
#... |
d900bcee5eb58c17470d593e403f50d576b9e154 | sheffieldjordan/D02 | /HW02/HW02_ch03_ex03.py | 1,975 | 4.59375 | 5 | #!/usr/bin/env python
# HW02_ch03_ex03
# This exercise can be done using only the statements and other features we
# have learned so far.
# (1) Write a function that draws a grid like the following:
# + - - - - + - - - - +
# | | |
# | | |
# | | |
# | | ... |
32197ad898d8a38b6960577dda563e5a8291822f | usfbelhadj/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 187 | 3.71875 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
mat = []
for i in my_list:
if i not in mat:
mat.append(i)
s = 0
for j in mat:
s += j
return s
|
ae91c153e78c026020c6ad7219d8007be7612507 | billygarrison/practice | /python/tkinter/forget_grid.py | 1,081 | 3.921875 | 4 | """https://www.youtube.com/watch?v=XuNKxXS3Sdc&list=
PLCC34OHNcOtoC6GglhF3ncJ5rLwQrLGnV&index=38
"""
import tkinter as tk
def click_button():
global lbl
lbl.destroy()
hello = "Hello " + e.get()
lbl = tk.Label(root, text=hello)
lbl.grid(row=3, column=0, pady=10)
e.delete(0, "end")
# btn_... |
153c6e71ccdad826319540ef831d772298b739b0 | saurabhpati/python.beginner | /OOP/manager-operations.py | 385 | 3.984375 | 4 | # This explains the method overriding
from manager import Manager;
from base_employee import BaseEmployee;
# initializing the manager class.
mgr = Manager('Saurabh');
mgr.id = 2;
mgr.printEmployee(); # calls the method of the child class.
# initializing the base class.
emp = BaseEmployee(2, 'Greater Noida');
emp.name... |
f68517189f0a51bc51412ddd0a90db0ace9e5c07 | pengjinfu/Python3 | /Python02/05-Variables.py | 441 | 3.515625 | 4 |
a = 10 # 整型
b = True # Boolxoi型
c = 7.5 # 浮点型
d = 3 + 2j # 复数
e = "123" # 字符串
# type()函数:用于显示变量类型
print(type(a),type(b),type(c),type(d),type(e))
first_name = "三"
last_name = "张"
name = first_name + last_name
print(name)
new_name = name * 10
print(new_name)
# 注意,两个小数相加时,注意精度
print((0.1 * 10 + 0.2 * 10) / ... |
74f2845416d09a407a3b6577211c3fb2da8a8bdd | andrewmilo/DataScience | /GradientDescent/GradientDescent.py | 1,141 | 3.765625 | 4 | # Gradient Descent
from __future__ import division
import random
from math import sqrt
def step_fn(v, direction, step_size):
"""
Moves step_size in a direction from v
Parameters:
v - a position vector
direction - a direction vector
step_size - size of the steps we take from v to (v+... |
e311e7f0d8cca51837e441610c914056f0c94d5d | adam-diwani/ICS3U-Unit3-08 | /Leap year | 864 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Adam Diwani
# Created on: December 13, 2020
# This program tells users if a year is a leap year or not
def main():
# Input
leap_year_string = input("Enter a year: ")
# Process
try:
leap_year = int(leap_year_string)
if leap_year % 4 == 0:
... |
da4066317e56cc4e571a3426245d725cba49b10d | abespitalny/CodingPuzzles | /Leetcode/combination_sum.py | 1,710 | 3.640625 | 4 | '''
Given an array of distinct integers candidates and a target integer target,
return a list of all unique combinations of candidates where the chosen numbers sum to target.
You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times.
Two combinations are u... |
d27e00979a49af165bf317b35383a3d16aef8615 | qmnguyenw/python_py4e | /geeksforgeeks/python/medium/19_20.py | 4,032 | 3.765625 | 4 | Python | Plotting an Excel chart with pattern fills in column using XlsxWriter
module
**Prerequisite:** Create and Write on an excel sheet
**XlsxWriter** is a Python library using which one can perform multiple
operations on excel files like creating, writing, arithmetic operations and
plotting graphs. L... |
b27142967223546acc3b8127162273f097e66b39 | blessedby-clt/python_basic | /인프런_데이터과학을위한파이썬/basic_linear_algebra.py | 6,226 | 3.796875 | 4 | def vector_size_check(*vector_variables):
# return len(set([len(vector) for vector in vector_variables])) == 1
# 아래는 for loop문으로 수정.
temp = []
for i in vector_variables :
temp.append(len(i))
return len(set(temp)) == 1
def vector_addition(*vector_variables):
# if vector_size_check(*vecto... |
b64f024bdcbc8ccf81f8c6b460a865d9cf911de9 | wanglikun7342/Leetcode-Python | /leetcode_python/str_exercise.py | 491 | 3.96875 | 4 | if __name__ == '__main__':
name = ' aleX'
print(name.strip())
# name = name.strip()
if name.startswith('al'):
print('yes')
if name.endswith('X'):
print('yes')
print(name.replace('l', 'p'))
# name = name.replace('l', 'p')
print(name.split('l'))
print(type(name.split('e... |
c99a00e6e4b9d6ff3400a7681777fb9ea60d309e | aldotele/the_python_workbook | /lists/ex116.py | 365 | 3.546875 | 4 | # exercise 116: Perfect Numbers
from lists.ex115 import proper_divisors
def isPerfect(n):
return n == sum(proper_divisors(n))
# the program looks for all perfect numbers between 1 and 10000 (4 in total)
def main():
print(isPerfect(28))
for i in range(1, 10000):
if isPerfect(i):
prin... |
8cc5ecb9de081478cd8222f9f14578fb0d05d448 | FlaminCat/flamin | /homework01/caesar.py | 1,432 | 4.15625 | 4 | def encrypt_caesar(plaintext):
"""
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("")
''
>>> encrypt_caesar("123+,-")
'123+,-'
"""
ciphertext = ""
for i in range(0, len(plainte... |
cfb8deeb087124c34afdc1e3bd8877a04a0ec2e2 | wulfebw/algorithms | /scripts/recursion/decode_string.py | 1,106 | 3.53125 | 4 |
def can_parse_int(f):
try:
int(f)
except:
return False
return True
def find_matching_parens(string, start):
onstack = 1
for i, char in enumerate(string[start+1:]):
if char == ']':
onstack -= 1
elif char == '[':
onstack += 1
if onsta... |
d118432f15a288589f6ced6b2c011b64f90d76ba | herczy/codega | /codega/scope.py | 6,554 | 3.703125 | 4 | '''
:Date: 2011-09-06
:Version: 1
:Authors:
- Viktor Hercinger <hercinger.viktor@gmail.com>
Implementation for keeping track of scopes. Scopes contain information about named objects
reachable from a point during generation.
'''
import copy
class Scope(object):
'''
Scope object to keep track of named obje... |
47da0c88caf0a23b650df07b23ea5f6980aa4a9a | blacklighter07/HackerRank | /Mini max sum.py | 463 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'miniMaxSum' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def miniMaxSum(arr):
# Write your code here
jam = arr.copy()
arr.sort()
jam.sort()
arr.pop()
k=sum(arr)
jam.pop(... |
d2beccdd98626d2204ff5d16faf61153c8a4631e | shubhiparakh/python.py | /break and continue.py | 1,128 | 4.0625 | 4 | '''n=18
no_of_guesses = 1
print("number of guesses is limited to 9 times only")
while(no_of_guesses<=9):
guess_number= int(input("guess a number"))
if guess_number<18:
print("enter a number greater")
elif guess_number>18:
print("enter a lesser number")
else:
print("you guessed th... |
cab7d817a0137cda2bb81290949ecca4f39eed88 | Aasthaengg/IBMdataset | /Python_codes/p03544/s984782816.py | 184 | 3.59375 | 4 | n = int(input())
if n == 0:
print('2')
elif n == 1:
print('1')
else:
L = [2,1]
for i in range(n-1):
tmp = L[i] + L[i+1]
L.append(tmp)
print(max(L)) |
005f57862edb68a87f5446fb1ed8f3c185cf40ab | Udhaya19/python-beginner | /hackerrank_solved_problem/mars_exploration.py | 1,149 | 4.125 | 4 | def mars_exploration(string):
count = 0
length_string = []
list_string = list(map(str, str(string)))
print(list_string)
length = len(list_string)//3
start = 0
end = 3
for i in range(length):
length_string.append(list_string[start:end])
start = start + 3
end = end ... |
8254dff2a3cad72d9929e35842b11b8d36d7c362 | yuliya-sidorenko/Geek_Python_Base | /lesson03/HW03/Task01.py | 725 | 4.09375 | 4 | # 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def func_del():
try:
num1 = int(input("Первое число - >"))
num2 = int(input("Второе число - >"))
except ValueE... |
204cd8a4f9b496e50e817b72eec343b4be3c7592 | stevey1/try-python | /algorithms/graph/find-euler-path.py | 1,677 | 3.796875 | 4 | #Euler path: only 1 or 2 vertex has odd number edges
#Euler circuit: all vertex has even number edges
def findpath(graph):
n = len(graph)
numOfEdges=[]
minEdges=1000000000000000000000000000000000000000000
# Find out how many vertex has odd number edges
numOfOdd = 0
for i in range(n):
... |
2cae7986ac519b50128aa0c84429e388ad84b838 | ashmitmittal/Linked-list | /Binary Tree.py | 2,266 | 3.9375 | 4 | class Node():
def __init__(self,val):
self.info = val
self.lchild = None
self.rchild = None
class Binary_Search_Tree():
def __init__(self):
self.root = None
def insert(self,value):
if self.root == None:
self.root = Node(value)
else:... |
9516e00325fdc53365849d22ed2cf56e5eba086f | Vrancean/liste | /lista.py | 466 | 3.53125 | 4 | with open('input.txt','r') as f:
x=list(eval(f.readline()))
print("iniatial: ",x)
y=sorted(x)
print("sortare in ordine crescatoare: ",x)
y.sort(reverse=True)
print("sortare in ordine descrescatoare: ",y)
print("numărul de elemente: ",len(x))
print("elementul maxim: ",max(x))
print("elementul minim:",min(x))
print("... |
7b8f0e41d1e7a3eb7103d61a674acf69e0376aa0 | gaopenghigh/algorithm | /algorithm/graph/mst_kruskal.py | 2,145 | 3.8125 | 4 | # 最小生成树的 Kruskal 算法
# 使用邻接表实现图
import sys
class Graph:
def __init__(self) -> None:
self.graph = {}
def add_edge(self, e: tuple):
# edge is tuple: (src, dst, weight)
# 无向图,所以实际上需要添加 2 条边
src, dst, weight = e
if src in self.graph:
self.graph[src].append(e... |
441b82fd58c58001ef935673fd219fe71fa9acd3 | ankmraobade/DevOps-Journey-Preps | /python_learn_exercises/chapter_5/counting_n_summing_loops.py | 779 | 4.0625 | 4 | #!/usr/local/bin/python3
#########################################################################################################
# Counting and Summing Loops #
##############################################################################... |
2eb4e05eed3441ec4f0c07cc845aa729d9dee0f9 | roy-love/Onshore_Battle_2018 | /bc18-scaffold/OnshoreBattlebot2018/Controllers/StrategyController.py | 1,399 | 3.90625 | 4 | from enum import Enum
# Uses all known information from various controllers to determine the current strategy
# Stores the values from enums, for easy access
# Start by simply returning {"Default"} until we get the basics finished.
class StrategyController:
"""This is the strategy controller"""
def __init__(se... |
7529bd29bc81241ccba253eaff6b90be8fc0122b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2389/60619/241259.py | 281 | 3.734375 | 4 | t = int(input())
for index in range(t):
length = int(input())
numbers = input().split(" ")
for i in range(0, length, 2):
if i+1 > length-1:
print(numbers[i], end=" ")
else:
print(numbers[i+1]+" "+numbers[i], end=" ")
print()
|
d53fbc33d3589d364deb9c486dda59ee4af273ae | Sreehari78/Turtle-Crossing | /cars.py | 935 | 4.0625 | 4 | from turtle import Turtle
from random import randint, choice
COLORS = ["red", "orange", "yellow", "green", "blue", "violet"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class Cars:
def __init__(self):
self.all_cars = []
self.car_speed = STARTING_MOVE_DISTANCE
def create_car... |
a10efbd5656e29dac1fd262af0ed476eb827ce25 | sferbrb/LaserSLAM | /新人培训/陈俊威/答案/text6.py | 736 | 4.21875 | 4 | #题目6:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
if __name__=='__main__':
letter=input('please input first letter:')
if letter=='M':
print('Monday')
elif letter=='T':
print('pleasr input second letter:')
letter=input()
if letter=='u':
print('Tuesday')
elif letter=='h':
print('Thursday')
... |
118c070f7ac00b5da504fe9ef76c854ef81ba8d3 | OmarGP/Python | /Modulo1/Contraseña.py | 173 | 3.640625 | 4 | key = "contraseña"
password = input("Introduce la contraseña: ")
if (key == password):
print("La contaseña coincide")
else:
print("La contraseña no coincide") |
051a3fe755bd8e9e96c8bb76d8d42df7ea3afbf7 | kriskirla/AllProjects | /Games/Number_Hunter/NumberHunter.py | 3,867 | 4.125 | 4 | import random
def NumberHunter():
''' () -> None
Runs the game of Number Hunter
'''
print("===== Welcome to Number Hunter! =====")
status = 1
mode = intro()
while (status):
if (mode == '0'):
answer = difficulty()
game(answer)
mode = end_game()
... |
9b9be48d35c8186cce5a94831f14ac2299db3c78 | shovelingpig/first-ai-math-with-python | /chap5-differential-equation/ordinary_differential_equation.py | 382 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def my_func(x):
return -2*x**2 + x + 3
def my_func_diff(x):
return -4*x + 1
x = np.linspace(-3, 3)
y = my_func(x)
a = 1
y_t = my_func_diff(a)*x + my_func(a) - my_func_diff(a)*a
plt.plot(x, y, label='y')
plt.plot(x, y_t, label='y_t')
plt.xlabel('x', size=1... |
7ad0d378a1af97a4edd54471c05206c3d480ad3c | ncturoger/LeetCodePractice | /Array_and_String/Reverse_String.py | 424 | 3.71875 | 4 | class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
s = list(s)
s_len = len(s)
for i in range(0, int(s_len/2)):
self.swap(i, s_len-1-i, s)
return "".join(s)
def swap(self, i, j, arr):
... |
e6ab576cdee231e2305bee2ca6167f112b604b37 | CapaFenLisesi/PHY315 | /Chapter06/reflectiongaussi.py | 2,817 | 3.734375 | 4 | # Author: Richard Fitzpatrick
# Adapted from http://firsttimeprogrammer.blogspot.com/2014/12/basic-physics-and-python-simple.html
# Requires numpy, matplotlib, and animation
"""
Animation to illustrate reflection and transmission of Gaussian traveling wave
pulse at boundary. Plots wave amplitude.
Pauses on mouse clic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.