blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a1e03be21e7c110cfee36d88b7a00432b13813fa | RadescuIoana/Producer-Consumer | /producer.py | 1,879 | 4.03125 | 4 | """
This module represents the Producer.
Computer Systems Architecture Course
Assignment 1
March 2020
"""
from threading import Thread
import time
class Producer(Thread):
"""
Class that represents a producer.
"""
def __init__(self, products, marketplace, republish_wait_time, **kwargs):
"""... |
e5acfea30b66123e154e5e73b1d7e48c0fb0a29a | vanexcel777/erreur | /chechsum.py | 427 | 4 | 4 | #!/usr/bin/env python3
def somme_de_controle(string):
words = string.split(' ')
res = {}
for word in words:
currentSum = sum(map(ord,word))
res[word] =currentSum
totalSum = 0
sumAscii = [res[word] for word in words]
print("Checksum: ")
print(' '.join(map(str,sumAscii)))
print("Somme des Cheksum -> ",sum(... |
4b994b72c5772b89ece9d1bb3366f31b47554f48 | iSreeman/Python-practice | /datatype(Strings).py | 1,042 | 4.125 | 4 | # Immutable data types - (Numbers, Strings, Tuples)
# Mutable Data types - (Lists, Dictionaries, Sets)
#Numeric datatypes - Int, Float, complex, Boolean#
#Strings
a = "Hello Python"
b = "Hi"
print(a," ",b)
#multi-line strings
text = """This is a multi line text where we can add paragraphs"""
prin... |
016ce400f7ac98794f19ebecd01ef0608f175ec9 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 4.08 - Fonctions_Eq-Second-Degre.py | 2,221 | 3.953125 | 4 | """ Auteur = Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Écrire une fonction rac_eq_2nd_deg(a, b, c) qui reçoit trois paramètres de type float correspondant aux trois coefficients
de l’équation du second degré ax^2 + bx + c = 0, et qui renvoie la ou ... |
28c04bc096b39cd0c18b78f77aa45d54ed3875ad | Nmazil-Dev/PythonCrashCoursePractice | /8-10.py | 373 | 3.96875 | 4 | #Great MAGICIANS
magicians = ['Bob', 'magic mike', 'abracadabra']
over = []
def show_magicians(list, empty):
while magicians:
for magician in list:
print (magician.title() + ' is a magician!')
empty.append('the Great ' + magician)
list.pop()
show_ma... |
ed8630771b34f4f49bbe2983c482c47da9d7f5fb | ShannonTully/neuralknight | /prep_features.py | 4,659 | 3.578125 | 4 | # import adam's module up here
from random import randint
from numpy import array as ndarray
def prep_feature_matrix(board, num_leaves):
'''Creates a matrix of input features for predictor algorithm
Inputs:
board: current board state as 2D list from row 1-8, column A-H
num_leaves: the numb... |
ed46b1526ec191f1f9dfb88efbeb2f4e58773d98 | Aasthaengg/IBMdataset | /Python_codes/p02722/s439672872.py | 394 | 3.5 | 4 | import numpy as np
N = int(input())
def divisor(N):
x = np.arange(1, int(N**(1/2))+1, dtype=np.int64)
div = set(x[N % x == 0])
return div | set(N // x for x in div)
cand = divisor(N) | divisor(N - 1)
def test(N, K):
if K == 1:
return False
while N % K == 0:
N //= K
... |
c9f1264408104c017bb01e9f588df4bdbeeb84f1 | ivarthor/for3 | /timaverk_3.py | 1,181 | 3.6875 | 4 | import random
def random_tolur(byrja,enda,tala): # Fall sem býr til random lista
listi = []
for i in range(tala):
listi.append(random.randint(byrja,enda))
return listi
def snua(x,y):# Fall fyrir lið 1
x = x[::-1]
y = y[::-1]
sv = int(x) + int(y)
return sv
def lista_b... |
27eb2236cc7f43d9a05d93b2c3dfc45be5f3505e | dennisliuu/Coding-365 | /103/001.py | 933 | 3.9375 | 4 | A = []
B = []
while 1:
mov = int(input())
if mov == 0:
break
elif mov == 1:
A = []
print('A:%s B:%s' % (A, B))
elif mov == 2:
B = []
print('A:%s B:%s' % (A, B))
elif mov == 3:
insert = int(input())
A.append(insert)
print('A:%s B:%s' % (... |
266e07a7be2e111fb6fdf0084040b882bd08a5e8 | kinshukjuneja/Information-Retrieval | /Assignment 2/CreateIndex.py | 3,951 | 3.671875 | 4 | import os
# Initializing empty dictionaries that will be used for mapping term, document and inverted list
term_termid = {}
dict_termid = {}
dict_documentid = {}
dict_inverted_list = {}
def build_dict():
"""
Build the above dictionary structures for term, document and inverted list
"""
term_id_counter... |
61d6eae1701669ca27f1b4433cb03493c8eecf39 | chenkeyu1997/python | /simple/fib.py | 147 | 3.8125 | 4 | def fib(n):
if n < 2:
return 1
else:
return fib(n-1)+fib(n-2)
if __name__ == '__main__': #调用函数
print(fib(5)) |
ae5686cee52fb0a3db5dbda8a98f0058272dc8f5 | fagan2888/rosemary | /rosemary/algebra/polynomials/algorithms.py | 6,005 | 4.125 | 4 | # Algorithms on polynomials
def mul_classical(M, N):
"""
Returns the product of M and N.
Given lists M and N of numbers, this returns the coefficients of the product
f(x) * g(x), where f(x) = M[0] + M[1]*x + ... + M[k - 1]*x^{k - 1} and g(x)
= N[0] + N[1]*x + ... + N[l - 1]*x^{l - 1}.
Input:... |
8466f97575444b3cf8421b79dc63642ec72563d6 | SamantaMarry/Aulas-Python | /projeto1/lista.py | 509 | 4.125 | 4 | nome = 'Samanta' #STRING
idade = 28 #VALOR
minha_lista = ['azul', 'amarelo', 'vermelho', 'rosa', 'cinza', 'verde'] # LISTA DE CORES
minha_lista[1] = 'branco' #SUBSTITUIR UM ELEMNTO DA LISTA, NESTE CASO O 1 (AZUL)
minha_lista.append('roxo') #ADICIONA ITENS NA LISTA
minha_lista.remove('azul') #REMOVE ITENS DA LISTA
fo... |
ccd7b5bdd1425a43b8463a4a0e784a4b91585535 | jaycer95/holbertonschool-machine_learning | /supervised_learning/0x01-classification/7-neuron.py | 3,213 | 4.125 | 4 | #!/usr/bin/env python3
""" Neuron Class """
import numpy as np
import matplotlib.pyplot as plt
class Neuron:
""" Define a single neuron performing binary classification """
def __init__(self, nx):
""" Instantination """
if not isinstance(nx, int):
raise TypeError("nx must be an ... |
0efdef49f94c80bf3640237ecc91c65c3b6e0749 | vic012/Alura-python-intro-oo | /teste.py | 414 | 3.8125 | 4 | #A função que cria contas bancárias
def cria_conta(numero, titular, saldo, limite):
conta = {
'numero': numero,
'titular': titular,
'saldo': saldo,
'limite': limite
}
return conta
def deposita(conta, valor):
conta['saldo'] += valor
def saca(conta, valor):
conta['saldo'] -= valor
def extrat... |
9f0d1c76e8067793b0f43d1af09184d666d6a231 | tanvirstreet/Tweets_Sentiment_Check | /src/tweets_sentiment.py | 3,328 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
import tweepy #https://github.com/tweepy/tweepy
import pandas as pd
import csv
from textblob import TextBlob
#Twitter API credentials
access_key = "695651038150266881-2iHmfIpodOhBCaxYndeFmQIucLouFRX"
access_secret = "SnZDYgPygKGdb8lqhPDgnIAhAIFpCUkZaSGtms7G8h1tP"
consumer_key =... |
d3e3dc8325509f285943c96a3d10739581496f2d | chezbob/chezbob-legacy | /pybob/logwatcher/gs1_validator.py | 526 | 3.671875 | 4 | """Barcode validation."""
import math
# http://www.gs1.org/how-calculate-check-digit-manually
def validate_gtin13(bc):
check = 0
for posn, digit in enumerate(bc[:-1]):
digit = int(digit)
mult = 3 if posn % 2 else 1
#print(digit, mult, posn)
check += mult * digit
check = m... |
09a64b8a45a803c1d23844967630a4f5ea5054dc | QAlexBall/Python_Module | /Python_lxf/Database_Operation/SQLite_Op.py | 2,172 | 3.828125 | 4 | '''
表是数据库中存放关系数据的集合, 一个数据库里面同常都包含多个表
要操作关系数据库, 首先需要连接到数据库, 一个数据库的连接称为Connection
连接到数据库后, 需要打开游标, 称之为Cursor, 通过Cursor执行SQL语句, 然后获得执行结果
Python定义了一套操作数据库的API接口, 任何数据库要连接到Python秩序提供Python标准的数据库驱动即可
由于SQLite的驱动内置在Python标准库中, 可以直接操作SQLite数据库
'''
'''
import sqlite3 # 导入SQLite驱动
conn = sqlite3.connect('test.db')# 连接到SQLite数... |
635966de0b4986b09dfe9dd4c2e2283edd9eb917 | dafu2020/Mini-Python-Projects | /lab06/tests/test_make_board.py | 915 | 3.65625 | 4 | """
Demonstrated unit tests for make_board function
"""
from unittest import TestCase
from lab06.maze import make_board
class Test(TestCase):
def test_make_empty_board(self):
argument = 0
expected = []
actual = make_board(argument)
self.assertEqual(expected, actual)
def test_m... |
d526c15a01a6b8d394576d842584085e4c94d22e | selcukakarin/python_code_samples | /UcgenVeyaDörtgenCinsiBul.py | 827 | 3.921875 | 4 |
choice=int(input("Üçgen mi bulmak istiyon kare mi? (üçgen=1,kare=2"))
if(choice==1):
a=int(input("1. kenar "))
b = int(input("2. kenar "))
c = int(input("3. kenar "))
if(a+b<c or a+c<b or b+c<a):
print("böyle bir üçgen tanımlanamaz")
else:
if(a==b or a==c or b==c):
... |
98b7b29fef7508f4d5f3b1e51d1a95b76d5bb9ac | yetihedy/py4e | /course-1-getting-started/week-6/payFunction.py | 228 | 3.78125 | 4 | hrs = input("Enter Hours: ")
h=float(hrs)
rte = input("Enter Rate: ")
r=float(rte)
def computepay(hr,rt):
if hr<=40:
return hr*rt
else:
return (40*rt)+((hr-40)*(rt*1.5))
p=computepay(h,r)
print("Pay",p)
|
bf9c22013786c1c535010ed4c9b7b0976df34a78 | silasburger/LPTHW | /ex11.py | 622 | 4.1875 | 4 | print('How old are you?')
age = input('ENTER AGE IN YEARS:') # Assigns a variable to an input that users type into command line.
print('How tall are you?')
height = input('ENTER HEIGHT IN FEET:')
print('How much do you weigh?')
weight = input('ENTER WEIGHT IN POUNDS:');
print(f'So, you\'re {age} old, {height} feet t... |
46622591c25ca1dc0b508c9d1dc0636ef93e0d68 | canglangxing/python_work | /practice_9_2.py | 746 | 3.5625 | 4 | class Restaurant(object):
"""模拟餐厅信息"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""打印餐厅类型"""
print(f"{self.restaurant_name.title()} is a restaurant specializing i... |
0c4a029b990521bf4a76726354c6b954122b54f2 | smarshy/find-on | /InbuiltHash.py | 576 | 3.65625 | 4 |
"""Modifications for using inbuilt hash table (dictionary) in python.Redefine add_to_index and lookup procedures.Taking care not to add duplicate
entries of url to keyword"""
def add_to_index(index,keyword,url):
#hash table implementation:adding keyword-url pair
if keyword in index:
... |
ca1de014b744599e7ef75b8135e2ab876527859f | LeynilsonThe1st/python | /cp/uri/Accepted/2289.py | 699 | 3.609375 | 4 | """ __author__: Leynilson José "Snake" """
# distancia hamming | accepted
# Leitura dos dados
def cin():
dados = input().split()
dados = list(map(int, dados))
dados.sort()
global a, b
(a, b) = dados
return False if a == 0 and b == 0 else True
def arrange(b1, b2):
size1, size2 = len(b1), le... |
751eb712eca3a0bc5bb23b215fd3b2d20c734193 | Octoberr/letcode | /easy/893groups_of_special_equivalent_strings.py | 1,912 | 4.3125 | 4 | """
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we ma... |
813a605e33fa0c17e2b2ff2d7944e593fd8e3855 | dayes/curso_Python | /SOLUCIONES/SOLUCIONES/intermedio II/19.Pruebas/listas_doctest.py | 789 | 3.625 | 4 | def moda(L):
# calcular la moda de una lista de enteros
"""
>>> L = [3,4,5,6,7,8,8,9,8,8,2,1,9]
>>> moda(L)
(8, 3)
"""
conteo={}
for i in L:
if i in conteo.keys():
conteo[i]+=1
... |
1344525cda0eae849e68231fd374e845a0a2729e | DennisMufasa/PythonPractice | /formattingStr.py | 1,122 | 4.40625 | 4 |
# what it would look like without specification
print('{0} | {1}'.format('Fruit', 'Quantity'))
print('{0} | {1}'.format('Apple', 3))
print('{0} | {1}'.format('Oranges', 10))
print('\n')
# format specification
# the number following the colon makes value to format at least 8 characters in length
print('{0:8} | {1:8}'... |
9bb0e0ddb96db912021f02eb465ff02bebb5afeb | chauhanvishu/bbc | /bb/CLASS 1/q4.py | 985 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 21:52:32 2018
@author: aksha
"""
class MovieDetails():
def __init__(self, Moviename, Artistname, Yearofrelease, Ratings):
self.Moviename = Moviename
self.Artistname = Artistname
self.Yearofrelease = Yearofrelease
self.Ratings = Rat... |
bf77c0d3269a2b714b9ff787a2b1edd5219480ad | Mr-Umidjon/python-tasks-sariq-dev | /20-lesson/functions.20.4.py | 553 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 08:11:48 2021
@author: WINDOWS 10
"""
def tub_sonlar_top(min, max):
"""Berilgan oraliqdagi tub sonlar ro'yxatini qaytaruvchi funksiya"""
tub_sonlar = []
for n in range(min, max+1):
tub = True
if (n == 1):
tub = False
eli... |
a7e4d694c5e7f3b5cbb3cd5cab0fdd9988900d6f | leiyang-mids/MIDS | /W261/HW2-Questions/mapper_t.py | 868 | 3.75 | 4 | #!/usr/bin/python
import sys, re, string
# define regex for punctuation removal
regex = re.compile('[%s]' % re.escape(string.punctuation))
# input comes from STDIN (standard input)
for line in sys.stdin:
line = line.strip()
# use subject and body
msg = line.split('\t', 2)
if len(msg) < 3:
contin... |
2455d65690feb8e2585a154b3dcc0d2b5bca798c | cuong1997565/tutorial_python | /oop/bai5.py | 813 | 3.640625 | 4 | class Person:
count_instance = 0
def __init__(self,first_name,last_name,age):
Person.count_instance = 1
self.first_name = first_name
self.last_name = last_name
self.age = age
@classmethod
def count_instance(cls):
return "You have created ",cls.count_instance , " ... |
e960939df6ea74fcb2010640bc70e58f9684b0ee | G00398258/myWork | /Week08/barChartCounties.py | 641 | 3.671875 | 4 | # Same as pieChartCounties except with bar chart
# Author: Gillian Kane-McLoughlin
import numpy as np
import matplotlib.pyplot as plt
# make the array of occurences
possibleCounties = ['mayo', 'Galway', 'Rosommon', 'DirtyDublin','Donegal']
# pick 100 randomly from possible counties with the frequence set in p
counti... |
0ad90f2426b6020cf2c8dfb3e491e55ce3659e20 | 294150302hxq/python_learn | /learn_with_carter/ch7_decision_making.py | 740 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
"""
@author:huang xiaoqin
@time: 2019/12/12
@desc:
"""
# 代码块:python通过缩进来指出代码块开始和结束
age = int(raw_input("how old are you?"))
if 8 < age < 12: # 介于两者之间
print "hi, my little girl!"
# 多条件判断:and、or、not(logical operator)
amount = float(raw_input("how much ?"))
if am... |
4261494e87ea58229eeebba37f7fe56cae9e17ed | ro1406/Graph-Theory | /Find Permutation Matrix To Show Isomorphism.py | 1,282 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 9 15:23:47 2021
@author: rohan
"""
# Program to find the value of P. No need any guesses.
from itertools import permutations
import numpy as np
size=int(input("Enter the value of n for an nxn matrix: "))
A1=[]
A2=[]
print("Enter the matrix A1: ")
for i in... |
114a7af826fc94cdeb7bcc041651947d5045e138 | JamesWalter/AdventOfCode | /2017/day21.py | 7,872 | 3.5625 | 4 | """ Advent of Code 2017 Day 21 Fractal Art """
# You find a program trying to generate some art. It uses a strange process
# that involves repeatedly enhancing the detail of an image through a set of
# rules.
#
# The image consists of a two-dimensional square grid of pixels that are
# either on (#) or off (.). The ... |
b7ecf0d9a1571b36740a8680a2ea17b15094f4fe | cuthai/Learning-Blackjack | /hand.py | 1,026 | 4.25 | 4 | '''
Class to define hand object
Comes with the following methods:
add_card - takes card object as a parameter and adds it to the hand
adjust_for_ace - if the value of the hand is over 21 and there is an ace, this method will reduce the ace's value from 11 to 1
'''
from card import * #import card in order to get the ca... |
e888e014484d3c2d3abea5a6ea503e9854e79226 | necoak/dev | /atcoder/abc145/abc145_a.py | 203 | 3.65625 | 4 | #!/usr/bin/env python3
# Atcoder necoak answer
# https://atcoder.jp/contests/abc145/tasks/abc145_a
circle_r_text = input()
circle_r = int(circle_r_text)
circle_area = circle_r ** 2;
print(circle_area)
|
8cda0913c1749638610dbb97f046ff8fedb634b8 | salmonofdoubt/TECH | /PROG/PY/pyintro/coding/week8_demo_files/xls/xls_reader_col.py | 508 | 4.21875 | 4 | #!/usr/bin/python2.6
"""
Shows how to read a column from an XLS file.
author: alberthwang@google.com
course: Introduction to Programming (goto/i2p)
"""
import xlrd
def main():
xls_file = xlrd.open_workbook('data.xls')
col3_data = []
# Get the specific sheet you want to work with
sheet1 = xls_file.she... |
d2c7caae69f703261f595c2d3aa3154579991577 | rajlakshmide/KMeans | /app.py | 1,754 | 3.671875 | 4 | #! /usr/bin/env python
"""app.py: Launches web app (Flask-based) to accept input and displays final cluster counts."""
# imports
import sys
import io
import csv
from flask import Flask, make_response, request
import numpy as np
from kmeans import *
# create the application instance
app = Flask(__name__)
@app.route... |
6be6a2cc75cbc04e26e731a8249dbd44a1b0ee11 | YuriBittencourt/T2-Compiladores | /utils/tree.py | 442 | 3.625 | 4 | class Tree(object):
def __init__(self, name, left=None, right=None):
self.name = name
self.left = left
self.right = right
def __str__(self):
res = str(self.name)
if self.left is not None:
res += ";" + str(self.left)
if self.right is not No... |
332b424f1bd85e1860f5ae540931f91f9472f797 | ShenTonyM/LeetCode-Learn | /Q090SubsetsII.py | 1,384 | 3.5625 | 4 | from collections import defaultdict, Counter
import copy
class Solution1:
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
m = Counter(nums)
total_result = [[]]
for k, v in m... |
3d50425c8f34a219ac904963920b074d46ce45af | aphrx/travelling-salesman | /assignment.py | 7,551 | 3.6875 | 4 | # Group 8
# Amalnnath Parameswaran - 100585138
# Zeerak Siddiqu - 100554495
# Ali Khan - 100526718
import random
import matplotlib.pyplot as plt
import math
from array import *
# Global Vars
citiesNo = 20
populationNo = 20
iterations = 10000
class city():
x = 0
y = 0
# Assign set values
def assign(self, x, y, ... |
e8a751fc8dad23817166311f52881074f0cf57c6 | tinitiate/python-pandas | /011-pandas-dataframe-group-by.py | 5,273 | 3.578125 | 4 | """ MARKDOWN
---
YamlDesc: CONTENT-ARTICLE
Title: Python Pandas Dataframe Group By
MetaDescription: Python Pandas Dataframe Group By, Min, Max, Count, Sum
MetaKeywords: Python Pandas Dataframe Group By, Min, Max, Count, Sum
Author: (c) Venkata Bhattaram / www.github.com/tinitiate
ContentName: pandas-dataframe-gr... |
bb8cf4df1310b6b4a8d5993577b4eccd0e29f479 | younggeeks/Bright-events | /database/models.py | 1,151 | 3.5 | 4 |
class User:
"""
Model class for User
"""
def __init__(self, id, full_name, email, password):
"""
constructor which will be called every time User object is instantiated
:param id:
:param full_name:
:param email:
:param password:
"""
self.i... |
fe343c2d7dd3c3a68146cfb8e0f110c0c9204df1 | thalesmg/leetcode | /fizz-buzz-multithreaded/python/sol.py | 1,421 | 3.828125 | 4 | from threading import Barrier
from typing import Callable
class FizzBuzz:
def __init__(self, n: int):
self.n = n
self.is_3 = False
self.is_5 = False
self.barrier = Barrier(4)
# printFizz() outputs "fizz"
def fizz(self, printFizz: 'Callable[[], None]') -> None:
for... |
8807b9f407e8cb6ab7b0c0321551f389160721e4 | norbertosanchezdichi/TIL | /Python3/Exercises/BuiltInModules/contains_keyword.py | 197 | 3.890625 | 4 | from keyword import iskeyword
def contains_keyword(*arg):
for string in arg:
if iskeyword(string):
return True
return False
print(contains_keyword("hello", "goodbye")) |
6e253a3bf75cc7dfe7c6ce9c5a49f5c8edf66c6f | cgsmendes/aulas | /exerc_pesoideal.py | 510 | 3.703125 | 4 | sexo = int(input("Olá seu sexo é Masculino ou Feminino? Responda 0 para Masc. ou 1 para Fem.: "))
if sexo != 0 or sexo != 1:
print("Digite somente 0 ou 1.")
if sexo == 0:
altura = float(input("Digite a sua altura: "))
pesom = (72.7 * altura) - 58
print("O peso médio ideal para homens é: ... |
8683e11ced8bf1346e8869f1a028947ca4c2e773 | HoerTech-gGmbH/doasvm-visualizer | /connect_to_webapp.py | 1,264 | 3.515625 | 4 | from collections import Sequence
import socket
def connect_to_webapp(host="localhost", port=9990):
"""Connect to the visualisation web-app
Opens a connection to the server at the specified host and port and returns
a function, with which you can send data to the visualisation TCP server,
along with a... |
2e20bde8ebd1ce124bb986dea8093cf2d49d7779 | RizkyRajitha/slrc | /BFS_approch.py | 3,600 | 3.515625 | 4 | #
from collections import deque
#
# visited = [-1] * 10
#
# def ret_bfs_stk(gpdic,start_node,end_node):
# stk_ret = []
# stk = bfs(gpdic,start_node,end_node,stk_ret)
#
#
# def bfs(gpdic,start_node,end_node,stk):
#
# parent = {}
#
# dQe = deque()
# result = deque()
#
# # dQe += gpdic[start_node]
... |
187c786b1025f4028c83826385fba52d9492c2fd | simonhuang/LeetCode | /other_algorithms/mergesort.py | 682 | 4.03125 | 4 | def mergesort(low, high, a):
if high <= low + 1:
return
middle = low + (high - low) / 2
mergesort(low, middle, a)
mergesort(middle, high, a)
merge(low, middle, high, a)
def merge(low, middle, high, a):
a_copy = list(a)
index = low
index1 = low
index2 = middle
while index1 < middle and index2 < high:
... |
3b16871675b62dcb39aa3f91601f16620785e94b | urbanskii/UdemyPythonCourse | /secao05/se05E30.py | 440 | 4.21875 | 4 | """
30 - Faça um programa que receba três números e mostre-os em ordem crescente.
"""
def main():
n1 = int(input('Informe o primeiro Numero: '))
n2 = int(input('Informe o segundo Numero: '))
n3 = int(input('Informe o terceiro Numero: '))
list_num = [n1, n2, n3]
list_num.sort()
print(f'Nume... |
a8433cdb56fe13e847d7f9f835ef5f6bf5831595 | armaan-handa/ECE-448-MPs | /template 2/transform.py | 2,442 | 3.734375 | 4 |
# transform.py
# ---------------
# Licensing Information: You are free to use or extend this projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to the University of Illinois at Urbana-Champaign
#
# Cr... |
443c3802a6e6af75619c4141a55dcd0348f25485 | PatrickAGibbs/Python | /RPG text base 2018-10-09.py | 16,065 | 3.78125 | 4 | import random
Player_level = 1
Strength = 0
Dexterity = 0
Constitution = 0
Intelligence = 0
Wisdom = 0
Charisma = 0
bombs = 5
cats = 5
med = 5
user_name = input("Welcome to the world of Arsolf, this world is full of danger, glory as well as many new ideas, but "
"first what is your name?")... |
23a9359943ecbf0177e60de07d84f312e182da2f | sushantkumar-1996/PythonDsGeeks | /Python_Arrays/Python_ArrayRotation.py | 274 | 4.28125 | 4 | """Program for rotating an array of size n by d elements----Method 1--Using a temp array----
arr[] = [1, 2, 3, 4, 5, 6, 7], n = 2, d = 2-------Store d elements in a temp array temp[] = [1,2]
Shift the rest of the arr and add the d elements arr[] = [3, 4, 5, 6, 7, 1, 2]"""
|
9a7035c67cc1092c942d59077714a443bdceada5 | doofenshmirtzInc/algo-b505 | /hw1/file.py | 659 | 3.9375 | 4 | import random
#pseudocode
#arr as input
#arrlen = len(arr)
#declare new array of size arrlen
#loop thru array w/ j
#r = rand(0, 3*arrlen) % arrlen
#while arr[r] != 0 and r
#r++
#newarr[r] = arr[j]
def reorder(arr):
arr_len = len(arr)
rand_arr = [0] * arr_len
for i in range(0, arr_len):... |
597659c3c8dac6778aaffe794a693435f18f94b8 | hankewyczz/Web-Structure-Modeling | /Obsolete/radialSW.py | 472 | 3.78125 | 4 | radNumber = int(input("Number of radial threads: "))
radRadius = input("Radius of radial threads: ")
initial = "$fa=.5; $fs=0.5; $fn=100;\n"
degreesInitial = 180 / radNumber
degreesSTR = str(degreesInitial)
j = 0
while j < radNumber:
initial += str("rotate([90,0," + degreesSTR +"])translate([0, 0, -250])linear_extr... |
c628c86236e9618386ce5cface2bf8300f67bfc5 | rafaelperazzo/programacao-web | /moodledata/vpl_data/94/usersdata/228/56045/submittedfiles/mediaLista.py | 380 | 3.859375 | 4 | # -*- coding: utf-8 -*-
n=int(input('digite um valor:'))
lista=[]
for i in range(0,n,1):
elemento=int(input('digite o elemento:'))
lista.append(elemento)
def media(a):
soma=0
for i in range(0,len(lista),1):
soma=soma+lista[i]
media=soma/len(lista)
return media
print('%2f'%lista[0])
... |
53825d862d938f63afba8694e1cb4f3cc706de9b | MrLiono21/stocal | /stocal/examples/typed_rules.py | 966 | 3.515625 | 4 | """An example on how to use typed rules
"""
import stocal
ABlock = stocal.molecular_type("ABlock")
BBlock = stocal.molecular_type("ABlock")
state = {
ABlock('x'): 100,
ABlock('y'): 100,
ABlock('z'): 100,
BBlock('u'): 100,
BBlock('v'): 100,
BBlock('w'): 100,
}
class Polymerization(stocal.Rea... |
102f103897fc2ae6d40fbc4e14655dd39f617ddd | DzianisOrpik/Python_Material | /itproger/cicle/list_2.py | 213 | 3.59375 | 4 | l = []
lis = [1, 23, 34, 45, 56, 65, 'Hello Worls', ['Hello MEN']]
print (lis)
l.append(23)
l.append(34)
b = [2, 3, 4]
l.extend(b)
l.insert(2, 222)
l.pop()
print (l.index(34))
l.count(23)
l.sort()
print (l)
|
3d557a9e22ad02f39c3baebc7ecdcff37ef869a0 | pater8715/SimulationModelSaturday | /Ejercicios/Luis Moreno/Ejercicio21.py | 76 | 3.875 | 4 | word = input("introduce una palabra: ")
for i in range(10):
print(word)
|
6815b68ebf82d0dfa1221d89acb092f4cadbb93f | vaibhav20325/school_practical | /Class11/q7.py | 167 | 3.578125 | 4 | h=int(input("Enter number of heads "))
l=int(input("Enter number of legs "))
a=int((l-2*h)/2)
b=h-a
print ("Number of rabbits is", a, "Number of chickens is", b)
|
750abb56747fe162cb6b6253ba2a202d311ee82d | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5166.py | 1,646 | 3.671875 | 4 | """
Written by blackk100 for Google Code Jam 2017 Qualifications
Problem
Tatiana likes to keep things tidy. Her toys are sorted from smallest to largest, her pencils are sorted from shortest
to longest and her computers from oldest to newest. One day, when practicing her counting skills, she noticed that some
... |
3634499a44f8344ed7be306801b68123842d832e | clementinesacre/Competences | /creation_db/utilisation_db.py | 5,072 | 3.5625 | 4 | import sqlite3
def afficher_pays_db() -> dict:
"""
Permet de récupérer les données de la table pays dans la DB tlca.db.
PRE : La table 'pays' doit exister dans la DB.
POST : Renvoie les données dans un dictionnaire.
"""
connexion = sqlite3.connect("../db/tlca.db")
sql = connexion.execute... |
61c0f2c1eec20b0291d44753fe1bd8b04d36a362 | fabatef/6.02 | /Psets/PS6/filter.py | 1,361 | 3.65625 | 4 | #!/usr/bin/python
'''Defines different filters to use in the filtering step.'''
import math
import numpy
def averaging_filter(samples, window):
'''Pass samples through an averaging filter.
Arguments:
samples -- samples to average
window -- window size to use for averaging
Returns: an array r th... |
fbd9789baabf90885671464a7c6ad5c849c8dc84 | Milan-Pro/Python | /BFS_Suuccessor.py | 1,195 | 3.96875 | 4 | '''
Problem Statement #
Given a binary tree and a node, find the level order successor of the given node in the tree. The level order successor is the node that appears right after the given node in the level order traversal.
Example 1:
Given Node: 3
Level Order Successor: 4
'''
from collections import deque
class Tr... |
ce428e903431a6380d1ed4506f078f3694d23531 | oectechcommunity/Code-Ground | /python/Area of a rectangle/anuskalenka-1821211011.py | 244 | 4.375 | 4 | #Write a program to find the area of a rectangle
#Input : lenth, breadth
#Output : Area
width = float(input("enter width of a rectangle"))
height = float(input("height of a rectangle"))
area = width*height
print("the area of rectangle is",area) |
c6f180ca7611eefd3d241bece8b85c932351ccb9 | Durell/LPTHW | /ex30.py | 991 | 4.5 | 4 | people = 30
cars = 40
buses = 15
# us an if statement to determine if value of cars is greater than people
if cars > people:
# if above is true, statement below will print out
print "We should take the cars."
# if above is false check if cars are greater than people
elif cars < people:
# print below state... |
286fcd91f283bff87126eec3462bd0f9829ee99e | logan-lach/Algos | /DP/unique_paths.py | 625 | 3.8125 | 4 | def uniquePaths(m: int, n: int) -> int:
paths = dict()
def traverse(loc, m, n):
# If we're out of bounds, return 0
if loc[0] >= m or loc[1] >= n:
return 0
# If we got a success, return 1
if loc == (m-1, n-1):
return 1
# If we've seen this path ... |
a1e417c5d52d0f2fa53a58f568661dec2dc2516a | Aasthaengg/IBMdataset | /Python_codes/p03130/s386935510.py | 250 | 3.5 | 4 | a1,b1=input().split()
a2,b2=input().split()
a3,b3=input().split()
lista=[a1,a2,a3,b1,b2,b3]
yn=0
for i in range(1,5):
if lista.count(str(i))==0 or lista.count(str(i))>2:
yn=1
break
if yn==1:
print("NO")
else:
print("YES")
|
b4653e1a4e966f687b380de58e4d6699f168246f | dregli14/Compound-interest-calculator | /interes compuesto gabo.py | 1,066 | 3.8125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[63]:
print('ingresar el monto a invertir:')
invi=input( )
print('Ingresar interes anual:')
inta = input()
invi=int(invi)
inta=float(inta)
intacor= inta/100
intm= intacor/12
ganm= invi * intm
reta=invi * intacor
rett=reta+invi
retm=(rett/12)
print('Inversion inicial: $', inv... |
0794abbb63239991da5e0bba357fdb9cd520a62d | easton57/automatatron8000 | /EasyEmail/DirectoryServices.py | 1,646 | 3.78125 | 4 | """
Class to do everything that's needed with folders and directories
by: Easton Seidel
2/23/21
"""
from os import listdir, path
from shutil import move, Error
class DirectoryServices:
"""Class to handle the directory services for EasyEmail and Easy Groups"""
# Declare Directories
delivered_dir = "deliv... |
8e6b108d074fb0979008d11e1f93ea8d244ae014 | yyogeswaran/python-scripts | /sample files - beta/sample random number.py | 955 | 3.546875 | 4 | """import random
radius = 200
rangeX = (0, 2500)
rangeY = (0, 2500)
qty = 100 # or however many points you want
# Generate a set of all points within 200 of the origin, to be used as offsets later
# There's probably a more efficient way to do this.
deltas = set()
for x in range(-radius, radius+1):
for... |
38b2a14a27217f90f12c14e616ba01eabddfc361 | chaehyeon119/Pandas | /Function/Pandas02_06_lambdaEx02_김채현.py | 325 | 3.796875 | 4 | #Pandas02_06_lambdaEx02_김채현
#함수 안에서 lambda가 있음
#lambda 활용법 lambda 매개변수: 표현식
x=lambda a:a+10
print(x(5)) #15
x=lambda a,b:a*b
print(x(5,6)) #30
def myfunc(n):
return lambda a:a*n
mydoubler=myfunc(2)
print(mydoubler(11)) #22 #11*2
mytripler=myfunc(3)
print(mytripler(11)) #33
|
644c1c618dd32fdd8ffb9cbcdfbdef00d416a021 | quangdbui9999/CS-171 | /week4Python/Week4/HighwayNumber.py | 833 | 4.40625 | 4 | highway_number = int(input())
''' Type your code here. '''
if(highway_number == 0):
print(f'{highway_number} is not a valid interstate highway number.')
if(1 <= highway_number <= 999):
if(1 <= highway_number <= 99):
if(highway_number % 2 == 0):
print(f'The {highway_number} is primary, going... |
757ca396c2263f5629d38d42006d033f9574874f | akriticg/Google_Interview_Prep | /LeetCode_06_LongestSubstring_340.py | 1,493 | 3.8125 | 4 | '''
340. Longest Substring with At Most K Distinct Characters
Given a string, find the length of the longest substring T
that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation:... |
5e36b7a0cf72e4c0d943572cc4393a1c0870c479 | sophia050506/python_study | /automate_the_boring_stuff_with_python/chapter05/arrange.py | 223 | 3.921875 | 4 | def display_inventory(item):
total = 0
for k, v in item.items():
print(v,k)
total += v
print(total)
items = {"rope":1, "torch":6, "gold coin":42, "danger":1, "arrow":12}
display_inventory(items) |
60f5e011dd400afec1a9ad396bdde45d3074d4f6 | zhangyanling1989/python_study | /day22_0106/day22.py | 1,616 | 4.03125 | 4 | # -*- coding: utf-8 -*-
s1 = 72
s2 = 85
r = s1/s2
name = 'xiaoming'
print('%s\'s score improves %.2f %%'%(name,r))
print('%2d-%2d' % (3, 1))
print('%.2f' % 3.1415926) # %.2f 意思是两个小数点,有一个period
classmates = ['Michael', 'Bob', 'Tracy']
classmates.append('Adem') #后面加element
print(classmates)
classmates.insert(1,'Jac... |
119113b0bdcc3ab63ea5b937817ecb2e8c7ec40a | franklingu/leetcode-solutions | /questions/construct-the-rectangle/Solution.py | 1,324 | 4.53125 | 5 | """
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area... |
f6c5ba44afea97bc551f7e75d99d2bfef3477324 | NicolasGomez97/Cientifico-Datos-ISPC | /Programacion-I/matematico-curioso.py | 530 | 3.78125 | 4 | from random import randint
while True:
numeros = []
numeros.insert(0, randint(20, 100))
print(numeros)
k = 0
while True:
if numeros[k] % 2 == 0:
k += 1
numeros.insert(k, numeros[k-1] // 2)
else:
if numeros[k] == 1:
break
... |
87e0ace6902aca39ce6e71a3c4b3ddb3456df7d0 | Yaseen315/pres-excercise | /yq-grace-exercise-logic1.py | 932 | 4.25 | 4 | """This is my random number generator, I have a few problems with it. The turns don't seem to be working properly- I want them to start from 1
and increase each turn. Also the print statements seem to not be coming out the way I want them. I also can't make the game finish."""
print "Random number generator"
from ran... |
235147fa9e8e6c068f0273e50d3332555c22357b | leohong1106/python_basic | /hello.py | 250 | 3.890625 | 4 | #console.log('hello')
# let greeting = 'hello'
greeting = 'hello'
name = 'markus'
print(greeting + ' ' + name)
# console.log(`${greeting} ${name}`)
print(f'{greeting} {name}')
foods = ['피자', '타코벨', '장어', '치킨']
print(foods[2])
|
1ee6d3b5de86568aa2cba0f1a27d3a137d1aab26 | wdlsvnit/SMP-2017-Python | /smp2017-Python-maulik/extra/lesson9/selectiveCopy.py | 917 | 4.375 | 4 | #! python3
#Program walks through a folder tree and searches for files with given extension-
#and copies them into a new folder
import os,shutil
def copyFile(file):
shutil.copy(file,newFolder)
def searchFile(folder,extension):
for foldername,subfolders,filenames in os.walk(folder):
for file in fi... |
347a9ca4a8826ec9826a41328ce8617eb1b09cdc | Jgmora/tinyintError_package | /validate.py | 373 | 3.671875 | 4 | def validate_tiny_int(val):
return val >= 0 and val <= 255
def validate_val(val):
try:
return isinstance(int(val),int)#aca valida si es una instancia de la clase int
#en python todo es un objeto
#se intenta convertir un string a entero con int(val... |
ca2baae38e2580ac2ec0dfcc589984e4df0cb1f1 | varsha0721/grras_varsha | /Python/projects/texteditor.py | 2,568 | 3.828125 | 4 | import os
import shutil
def Create_file():
f = input("please enter FULL and VALID path:")
if os.path.exists(f):
fp = open(f,'w')
print("type 'quit' to save file")
while True:
d = input("write ur text from here\n")
if d.lower() == 'quit'... |
303a59a2f3217dd08fb3dc2ef9886c4e35d19fc1 | egorb2008/perimetr | /perimetr.py | 691 | 3.546875 | 4 | a = []
flag1 = True
flag2 = "д"
p = 0
print("Вводите числа, если захотите закончить, то введите 'з'")
while flag2 == "д":
while flag1:
coor = input()
if coor == "з":
flag1 = False
else:
a.append(int(coor))
for i in range(len(a)):
x = a[i]
for j in ... |
bfbd5d1e13e2630463a44b25ed87c3ba96f65ec0 | hughian/OJ | /LeetCode/LeetCode/Hash.py | 1,417 | 3.765625 | 4 |
class MyHashSet_705:
# TODO 开放定址法,平方探测
def __init__(self):
"""
Initialize your data structure here.
"""
self.primes = 10007
self.hash_table = [None] * self.primes
def add(self, key: int) -> None:
idx = key % self.primes
i = 1
sign = 1
... |
66bc08d402447c7007a5007c8ced32a9663dad2b | Hamza-Rashed/Python-data-structures-and-algorithms | /data_structures_and_algorithms/challenges/multi_bracket_validation/multi_bracket_validation.py | 508 | 3.671875 | 4 |
def multi_bracket_validation(input):
open_list = ["[","{","("]
close_list = ["]","}",")"]
stack = []
for y in input:
if y in open_list:
stack.append(y)
elif y in close_list:
index_position = close_list.index(y)
if ((len(stack) > 0) and (open_list[ind... |
0f310c4e6f2866b1eaaae36ef94008655aa06281 | shawndust/Project-Euler | /003 - Largest prime factor.py | 329 | 3.78125 | 4 | bigNum = 600851475143
def isPrime(u):
for i in range(2, int(u/2)+1):
if u%i == 0:
return False
return True
for i in range(int(bigNum/3) + 1, 3, -1):
# print(i)
if bigNum%i ==0:
# print(i)
if isPrime(bigNum/i):
print(int(bigNum/i))
break
print... |
7d0041974faf00da5d88847f1eaddcd17ebb8c51 | yinzaihecode/hongongpython | /venv/chap21-30/chap231.py | 737 | 3.765625 | 4 |
# 배열에 있는 단을 전부 꺼내는걸 flating 이라고 함. 자주 사용
character = {
"name":"기사",
"level": 12,
"items": {
"sword" : "불꽃의 검",
"armor": "풀플레이트"
},
"skill": ["베기", "세개 베기", "아주 세게 베기"]
}
for key in character:
if type(character[key]) is dict: #딕셔너리에 있다면
for k in character[key]:
... |
9f8c462a47f19f61bba00a24cc9b9dc7c669e7f7 | bajakprashant1798/Fibonacci_and_positive_numbers_python | /fibonacciNumbers.py | 142 | 4.21875 | 4 | #Fibonacci numbers
number = int(input("Enter number.."))
n = 0
m = 0
temp = 1
while(n<number):
m = n + m
n = temp
temp = m
print(m)
|
cbbb9715f3486129717ec9f758deac0ee517f4d5 | dennisnderitu254/Andela-Exercises | /question15.py | 611 | 3.859375 | 4 | """ program that approximates the value of pie by summing the terms of the series:
program should prompt user for n,the number of therms to sum, and gitve tn n terms of the series
"""
from math import pi
numerator=4
denomenator=1
while True:
try:
n=int(input("Enter the number of terms for estimation:"))
br... |
7966abfbffd1cef38db3e18c2de81f71c8494d49 | NATHAN76543217/BtCp_D01 | /ex02/vector.pytest.py | 3,731 | 3.578125 | 4 | class Vector():
"""
A vector tools class
"""
def __init__(self, values):
if type(values) == list:
self._initList(values)
elif type(values) == int:
self._initInt(values)
elif type(values) == tuple:
self._initTuple(values)
else:
... |
73861bb3b6d1feded7353f563b5e4f2b0774c0a5 | 9gecdeepak/October_batch | /Anil/scripts/common/Dcitonary all Program 1.py | 1,181 | 3.90625 | 4 | # coding=utf-8
# Write a program to find all the subsets of the set x={1,2,3,4}
from __future__ import print_function
import itertools
x = {1, 2, 3, 4}
for key in range(len(x)):
for j in itertools.combinations(x, key):
print(j)
# Consider a tuple, x=(‘s’,’y’,’e’) and a dictionary, d={‘a’:’act’,’b’:’battle... |
86cef7e3f265207e6191fb269d95fceffaa344fe | onlyjackma/little_tools | /shaizi.py | 240 | 4.09375 | 4 | #!/usr/bin/env python
from random import randrange
num = input("How many dice? :")
sides = input("How many sides per dice? :")
sum = 0
for i in range(num):
pnum = randrange(sides) + 1
print pnum
sum += pnum
print 'The result is ',sum
|
ae29245717f4d629b2a862a3372619237b6e56e0 | aaroncampf/LearningPython | /LearningPython1/LearningPython1/Practice/module1.py | 821 | 3.65625 | 4 | import csv
class Contact(object):
pass
class Company(object):
"""Represents a company"""
def __new__(cls):
cls.Name = ""
cls.Address = ""
cls.City = ""
cls.State = ""
cls.Zip = ""
cls.Phone = ""
cls.Email = ""
cls.Contacts = [Contact]
... |
41c23b14496f660d5b9f784f5d3fd2cd6c735832 | jbobo/leetcode | /longest_palindromic_subsequence_dp.py | 1,156 | 3.828125 | 4 | #!/usr/bin/env python3
def longestPalindromeSubseq(input_string):
"""
"""
palindrome_length_at = [[1]*len(input_string)
for i in range(len(input_string))]
for length in range(2, len(input_string) + 1):
for left in range(len(input_string) - length + 1):
... |
b06d66beb255351b2fa362dd26546014f021536b | white-source/happy_shua_shua | /graph/Dijkstra.py | 1,816 | 4 | 4 | class City:
def __init__(self, name):
self.name = name
self.routes = {}
def add_routes(self, city, price_info):
self.routes[city] = price_info
def dijikstra(starting_city, other_cities):
routes_from_city = {}
routes_from_city[starting_city] = [0, starting_city]
for city in... |
809217b8a7c69d925265cfd53fb7434ac63dd17c | lvraikkonen/GoodCode | /leetcode/125_valid_palindrome.py | 398 | 3.765625 | 4 | # two pointer solution
def isPalindrome(self, s):
i, j = 0, len(s) - 1
while i < j:
# only char and digit left
while i < j and not (s[i].isdigit() or s[i].isalpha()):
i += 1
while i < j and not (s[j].isdigit() or s[j].isalpha()):
j -= 1
if s[i].lower() != ... |
a50f7d01eb6cfcf8e183b0e126dec676048edeee | CodesByMass/MapReduce-Introduction | /MapperMass.py | 652 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
for line in sys.stdin:
line = line.strip()
record = line.split(",")
# On récupère toutes les lignes où la ville est Paris.
#Ca veut dire que nous sommes dans le fichier users si l'enregistrement a 5 colonnes.
if len(record) == 5 :
if record[4] == "Pa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.