blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0ed15c33933445128cfe2c330e8ad9a1ae0e6fe3 | leosbarai/pythonbrasil | /estruturaseq/2_numero.py | 302 | 3.8125 | 4 |
def numero():
print("*********************************")
print(" Imprimindo o número!")
print("*********************************")
print("Digite um número: ")
numero = input()
print("O número escolhido foi {}".format(numero))
if __name__ == "__main__":
numero() |
95a64e622daa3f46c429bbd268df376265d33d95 | wiput1999/PrePro60-Python | /Onsite/Week1/string_format.py | 174 | 4 | 4 | """ String Format """
def main():
""" Print formatted string """
num = float(input())
print("%.1f" %num)
print("%.3f" %num)
print("%05.1f" %num)
main()
|
a09b471535042743dc6a67bd423616c3303377ba | halmanza/pythonClass | /paintEstimator.py | 487 | 3.921875 | 4 | # Anthony Almanza
# Chapter 3
import math
gallon_paint= 350.00
height_wall= (int(input('Enter wall height(feet):\n')))
width_wall= (int(input('Enter wall width(feet):\n')))
wall_area= height_wall * width_wall
paint_needed= wall_area / gallon_paint
final_amount= math.ceil(paint_needed)
print('Wall area: {wall:.... |
1898faecc974befd7ec09b836662cb82b8ed7d32 | impacevanend/unalPython | /algoritmosOrdenamiento/ordenamientoRapido.py | 1,009 | 4.09375 | 4 | #Algoritmo de ordenamiento rápido - quicksort
'''
-De los más rápidos y usados (hasta hace poco)
-Utiliza la estrategia de: Divide y vencerás
(Se implementa de forma recursiva)
-Complejidad de tiempo media: n log n
(En el peor caso puede llegar hasta n^2)
-Complejidad de espacio constante(in-place)
(la versión simp... |
888a725345e69590f28cf990f638ba7f75ec02b8 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/multiply-n-with-unit-digit.py | 484 | 4.3125 | 4 | Multiply N with Unit Digit
The program must accept a positive integer N and print the value of N multiplied with it's unit digit.
Boundary Condition(s):
1 <= N <= 9999
Input Format:
The first line contains N.
Output Format:
The first line contains the value of N multiplied with it's unit digit.
Example Input/Output 1:... |
024899bdb975fff5c0bf9f793b525a306a35def6 | Qais17/PYTEST | /ExoPython/DListes&DTuples.py/blackList.py | 203 | 3.5625 | 4 | #!/usr/bin/python3.5
# -*-coding:Utf-8 -
black_list = ['toujours actif','au rendez vous', 'inactif','au commissariat']
for i, elt in enumerate(black_list):
print("la cible {} est {}.".format(i, elt))
|
f3e43bc23f16a2adfd30089baf1d75662c89b234 | JamesPagani/holbertonschool-higher_level_programming | /0x0B-python-input_output/13-student.py | 1,782 | 4.0625 | 4 | #!/usr/bin/python3
"""Student to JSON.
A Student class with the folowing attributes:
FIELDS:
+ first_name (Instance, Public)
+ last_name (Instance, Public)
+ age (Instance, Public)
METHODS:
+ __init__(self, first_name, last_name, age): Init method
+ to_json(self, attrs=No... |
e60287e32e4c29b59e2cb8a064b91d659726aa71 | rusantsovsv/CookBook | /3_num_date_time/3.8_calcfrac.py | 1,595 | 4.5 | 4 | """
Вы вошли в машину времени и внезапно обнаружили себя делающим домашку по
математике с задачками про дроби. Или же вы просто пишете код, который будет
обсчитывать измерения, сделанные в вашей столярной мастерской...
Модуль fractions может быть использован для выполнения математических опе-
раций с дробями. Например... |
74507d49e9f13df6b34c717ff698f8273567bd76 | emezzt/CheckiO | /x-o-referee.py | 1,416 | 3.5625 | 4 | ##------------------------------------------------------------------------------
# CheckiO: Xs and Ox Referee
# http://www.checkio.org/mission/x-o-referee/
##------------------------------------------------------------------------------
def checkio(game_result):
# Constants for each possible way to win in a Tic-Ta... |
1a9135504152120acad7067c565d9cc0dfcee9cb | Antiquated-Messaging/All-Code-Together | /main.py | 990 | 3.53125 | 4 | from cipher import cipher
from saver import saver
from translate import Numcode
from morse import morse
# import all the classes
print('What type of message would you like to send?')
print('Morse Code')
print('Cipher')
print('Numeric')
print('')
messageType=input().lower() #which translation should be used
while messag... |
be6c1d06a84c99bbdfac1296558951c91ab8ed9c | sabrupu/comp151 | /Loops/Examples.py | 462 | 4.1875 | 4 | def main():
# i = 0
# j = 10
#
# while i < j:
# print('i = ', i)
# i += 1
# () tells you if something is a function
# for is used for a set number
# while is used when we don't know how many times the user will input numbers
# Returns a list of numbers
# 'i' gets se... |
7a20200803987bb1cd7f733fd590ba07059f6e78 | naoyasugiyama/algorithm | /python/sort/sort.py | 604 | 4.09375 | 4 | import random
import sys
# バブル
def BubbleSort(ary):
max_idx = len(ary)
for i in range(max_idx):
for j in range( i + 1, max_idx):
if ary[i] > ary[j]:
ary[i],ary[j] = ary[j], ary[i]
return ary
def BubbleSort2(ary):
change = True
while change:
change = False
for i in ra... |
bddf393024629ae013635443e4d9c1d942ad4ff7 | rafaelperazzo/programacao-web | /moodledata/vpl_data/1/usersdata/74/173/submittedfiles/formula.py | 232 | 3.75 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
p = input('Digite o primeiro valor')
i = input('Digite o segundo valor')
n = input('Digite o terceiro valor')
a = ((1+n)**n)-1
b = a/n
v = p*b
print('O valor v e: %.2f'% v)
|
7f2f15f80f924566cb8c55283bd9c868fd58f47d | hjm0702/MPCS-51042-Python | /spring-2018-hw4-hjm0702-master/spring-2018-hw4-hjm0702-master/problem1.py | 1,662 | 3.5 | 4 | class ESArrary(list):
def __init__(self, *lst):
self.lst = lst
self.length = len(self.lst)
self.flattened = []
def join(self, s):
if self.length == 1:
oneitem = self.lst[0]
middlelist = [str(oneitem[i])+str(s) for i in range(len(oneitem)-1)]
... |
03059d73720cb383e5e9d6936ea2463aff80eb93 | hoonest/PythonStudy | /src/chap05/05_return.py | 970 | 3.90625 | 4 | # 호출자에게 반환하기
def multiply(a,b):
return a*b # return -> 1. 함수를 즉시 종료, 2. 호출자에게 결과 전달
result = multiply(3, 4)
print( 'multiply(3, 4) result = ', result)
# 한 함수 안에 여러개의 return 배치 가능
def my_abs1(arg):
if(arg<0):
return arg * -1
else:
return arg
print(my_abs1(-1), "====", my_a... |
076866b9fc799ef4ca5391d9792d8a85be88e0df | RandBetween/checkio | /Alice_In_Wonderland/multiplicationTable.py | 1,037 | 3.609375 | 4 | from operator import xor
def checkio(first, second):
x1 = format(first, 'b')
y1 = format(second, 'b')
sum = 0
sum += and_table(first, second, x1, y1)
sum += or_table(first, second, x1, y1)
sum += xor_table(first, second, x1, y1)
return sum
def and_table(first, second, x1, y1):
dec = []
for i in range(l... |
0ba1110740438872d33b0d2cd829d432e8fa16ba | billykim618/Python | /Chapter 2 - Elementary Prog./Triangle.py | 380 | 3.984375 | 4 | x1, y1, x2, y2, x3, y3 = eval(input("Enter three points for a triangle separated by commas: "))
side1 = ((((x2 - x1) ** 2) + ((y2 - y1)) ** 2) ** 0.5)
side2 = ((((x3 - x1) ** 2) + ((y3 - y1) ** 2)) ** 0.5)
side3 = ((((x3 - x2) ** 2) + ((y3 - y2) ** 2)) ** 0.5)
s = (side1 + side2 + side3) / 2
area = ((s * (s - side1) *... |
47166322e4a6bbd7baf1500a1ea4fe5bf5c84b7d | terence4wilbert/Programs | /Python/remove_dups.py | 2,130 | 3.609375 | 4 |
class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class SingleList(object):
head = None
tail = None
def show(self):
x =self.head
while x is not None:
print(x.data,end='')
print(" -> ", end='')
... |
168ac6ce68127ed175db73034c6159c52b1d9217 | rrehacek/Tetris_neural_network | /NN_v2.0/test_new_net.py | 773 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 31 16:52:42 2020
@author: radekrehacek
"""
from neural_network import Layer, NeuralNetwork
grid = [[(255,0,0) for n in range(10)] for i in range(20)]
net = NeuralNetwork()
net.read_inputs(grid)
#Layer(inputs, neurons)
layer1 = Layer(210, 10)
l... |
771e59e5440cbab1c9ac2a2b4626e659b9fa55e0 | HankPym/PymTool | /python/plot2.py | 289 | 3.5 | 4 | import matplotlib, matplotlib.pyplot as pyplot
import numpy
import types
import math
def simple():
for x in range(100):
y = math.sqrt(x)
pyplot.scatter(x, y, lw=2)
axes = pyplot.gca()
axes.set_xlabel('x')
axes.set_ylabel('y')
pyplot.show()
simple() |
5ac79ff8e4c78488a57599680a0e36c8e8d4ea09 | guzmonne/coral | /coral/core.py | 9,515 | 4.09375 | 4 | from __future__ import annotations
from dataclasses import dataclass
from typing import List, Literal, Union, Callable
@dataclass
class Order:
"""
Represents an order entered by a user. It specifies the number of
shares that have to be bought/sold and its maximum/minimum prices.
Attributes
------... |
9216634e654902139e8ae6b63ebfeb74b3e3a9bb | johnnylecy/Target-Offer-python | /替换空格.py | 324 | 3.59375 | 4 | '''
题目
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
'''
#coding:utf-8
def method(string):
l = list(string)
for i, elm in enumerate(list):
if elm == "":
l[i] = "%20"
|
1b91fc53b4ba2762f3e0c7b93a68ebdca2017a29 | olaruandreea/LeetCodeProblems | /uncommon-words-from-two-sentences.py | 845 | 4.15625 | 4 | """
We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Return a list of all uncommon words.
You may return the list in... |
0408e9d2dd02f3dc72746f2725803766ad37a11f | Pranay0302/basicPy | /basic/basic.py | 166 | 3.515625 | 4 | import os
import sys
def yes():
print("yes")
def no():
print("NO")
yes()
checking = True
if checking is False:
print("false eh")
else:
pass
no()
|
5bf60d512dd26e02b0a3a2e60c7f0d91e22a746f | bitsapien/anuvaad | /public/phase-2-20160620022203/PYTHON/palindrome-game.py | 206 | 3.65625 | 4 | #!/usr/bin/python
# Name : Palindrome game
# input:
# str : input
str = raw_input().strip()
# write your code here
# store your results in `winner`
# output
# Dummy Data
winner = "First"
print(winner)
|
1e6045f0d2d9427eef8d7a8e356687a27e4d7da3 | Dudashvili-Vladislav/Algorithms | /search/Breadth-first-search.py | 3,100 | 3.625 | 4 | from collections import deque
#-------------------------------------------------
# Поиск в ширину
#-------------------------------------------------
""" Реализация графов """
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jo... |
9324a07fbd5334ffd1ecfb64f022d8d6603bafa5 | Anupriya-Inumella/CourseWork | /Python_Pi-trie/assign12.py | 1,087 | 3.59375 | 4 | class Node():
def __init__(self,string):
self.string=string
self.dict={}
def getString(self):
return self.string
def setNext(self,char,aNode):
self.dict[char]=aNode
def getNext(self,char):
if (char in self.dict):
return self.dict[char]
class Trie():
def... |
95aad43b38b2ab975686cd15b4017e90c89a87c0 | MuhamedAbdalla/Automatic-Audio-Book-Based-On-Emotion-Detection | /backend/microservices/auth/core/entities/exception/phone.py | 605 | 3.8125 | 4 | class PhoneException(Exception):
"""Exception raised for non phones string's"""
def __init__(self, message):
super().__init__(message)
def __str__(self):
return 'there is something wrong with the phone.'
class PhoneNotValid(PhoneException):
"""Exception raised for non phon... |
7434f8e3def80bf007ad0641fcf225a68d10db0d | pecata83/soft-uni-python-solutions | /Programing Basics Python/Exam Preparations/07.py | 1,401 | 4.03125 | 4 | movie_name = input()
free_seats = int(input())
ticket_type = input()
# total_tickets =
student_tickets = 0
standard_tickets = 0
kids_tickets = 0
current_movie_tickets = 0
while ticket_type != "Finish":
if current_movie_tickets > free_seats:
print(f"{movie_name} - {100 / free_seats * current_movie_ticke... |
8a97e66e5ae8b3b913bed77419f42e9086c2c2b9 | eshkil/Python_Prometheus_Courses | /Lesson4.3.py | 291 | 3.546875 | 4 | import sys
result = 0
znaki = str(sys.argv[1])
if znaki != '' and znaki[0] != ')':
for i in znaki:
if i == '(': result = result + 1
else: result = result - 1
else:
if znaki[0] == ')': result = -1
else: result = 0
if result == 0: print('YES')
else: print('NO') |
f4e29afd19d1dec7a7dc5e082390dd31cb5da116 | dennis2030/leetcodeStudyGroup | /147-insertion-sort-list/dennis/147.py | 1,620 | 4.03125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def printList(self, head):
current = head
tmp_str = ''
while current != None:
tmp_str += str(current.val)
... |
eaefd382d9e543a0dd6020cbef373489ec6715c8 | UpCode-Academy/Python-Bootcamp-October | /08 - functions.py | 739 | 3.96875 | 4 | # functions are important!!!
def add(a, b):
print("Adding %d + %d" % (a, b))
return a + b
def subtract(a, b):
print("Subtracting %d - %d" % (a, b))
return a - b
def multiply(a, b):
print("Muliplying %d * %d" % (a, b))
return a * b
def divide(a, b):
print("Dividing %d / %d" % (... |
bb2387f41b33e7156d3b21bd8521b1a8113a6e07 | pubudu08/algorithms | /structures/binary_search_tree.py | 6,820 | 4.25 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class BinarySearchTree(object):
"""
TODO: Add detailed description about binary search tree operations
O(logN) time complexity for search, remove and insertion
It i... |
b150ed50192c4b426b94122067f77b3e5ed1516e | kliklis/CodeJam_Pancakes | /Pancakes.py | 1,716 | 3.734375 | 4 | def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
#opens the f file
f = open('C:\\Users\\Kostas\\Downloads\\A-small-practice.in', 'r')
str = f.read()
#initialisation... |
e57e7155bea94531a84c817083cc71a59c202a4d | PRitmeijer/TicTacToe | /main.py | 3,382 | 4.0625 | 4 | # Tic Tac Toe
board = [' ' for x in range(9)]
def insertLetter(letter, pos):
board[pos] = letter
def spaceIsFree(pos):
return board[pos] == ' '
def printBoard():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(b... |
565a4fa04bebd90ed037c9c2dcdd155831619b24 | EvgeniyBudaev/python_learn | /base/nested_list/nested_list.py | 544 | 4.375 | 4 | # Вложенные списки
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(len(nested_list)) # длинна 3
print(len(nested_list[0])) # длинна первого списка равна 3
for inner_list in nested_list:
print(inner_list)
for inner_list in nested_list:
for number in inner_list:
print(number) # получили все элементы
resu... |
ec1c7501aec5309a42754cc42a76f2c4a090b73a | Mcdonoughd/CS480x | /Assignments/HW2/Code/Python/bokeh_example.py | 1,120 | 3.5 | 4 | import pandas as pd
import numpy as np
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, output_file, show
def Main():
car_data = pd.read_csv('cars-sample.csv')
# clean data
car_data = car_data[np.all(car_data != "NA", axis=1)]
# Data preparation
y = car_data.loc[: , ... |
d68833537d5e872ccb305d5e991780bbbefe3348 | dciupei/Python | /assignment#6.py | 2,005 | 3.75 | 4 | #David Ciupei
#CS121
#assignment #6
from bmp import *
def inMSet(c,n):
z = 0
for x in range(0, n):
z = z**2 + c
if abs(z) > 2:
return False
return True
def testImage():
""" a function to demonstrate how
to create and save a bitmap image
"""
width = 200
h... |
ac80e13b92b172ab91c592cd604cce6c55dddd89 | VadimVolynkin/learning_python3 | /multiprocessing/04_queue.py | 11,208 | 3.609375 | 4 | import multiprocessing
# Очереди позволяют обмениваться данными между процессами.
# В multiprocessing существует 3 вида очередей, построенных на основе обычной многопоточной очереди FIFO queue.Queue
# Все 3 вида очередей могут иметь несколько производителей и потребителей.
# ==========================================... |
190767e0a66e113889bd4859543f80a8f3d54add | shourya192007/A-dance-of-python | /Basics/13. Classes Part 1.py | 1,018 | 3.859375 | 4 | class Song:
def __init__(self, name, genre, duration):
self.name = name
self.genre = genre
self.duration = duration
def showSong(self):
return "Name: "+self.name+"\nGenre: "+self.genre+"\nDuration: "+self.duration
def showParticularGenre(self, genre):
... |
d3cb3b999db2fd48d1bfefa76a247980b315776e | chenglinguang/python_algorithm | /ListNode/listnode.py | 417 | 3.703125 | 4 | #!/usr/bin/env python3
#!-*-encoding:utf-8-*-
#定义一个节点类与应用
class LNode:
def __init__(self,elem,_next=None):
self.elem=elem
#_next避免与python标准函数重名
self.next=_next
llist1=LNode(1)
p=llist1
for i in range(2,11):
p.next=LNode(i)
p=p.next
#相当于p又指向了head
p=llist1
while p is not None... |
9a73d34d0b7d3409651a9ccf77e0ecde51350def | Ashwini114/tic_tac_toe_python | /tic_tac_toe.py | 2,929 | 3.9375 | 4 | positionArray = [1,2,3,4,5,6,7,8,9] # initial array
current = 'X'
win = 0
# setting board display
def setBoard():
print("\t\t|\t\t|\t\t\n\t{}\t|\t{}\t|\t{}\t".format(positionArray[0],positionArray[1],positionArray[2]))
print("----------------------------------------------------")
print("\t\t|\t... |
2dd915de606c1dcdbe1eb68f14341512b40102f1 | Zabdielsoto/Curso-Profesional-Python | /4.- Unidad/Ejemplo1.py | 574 | 3.96875 | 4 | ''' Ejemplo 1: Funciones
Funciones con argumentos variables
'''
def suma(*args):
num = 0
for n in args:
num += n
return num
def multiplicacion(*args):
num = 1
for n in args:
num *= n
return num
OPERACIONES = {
"suma" : suma,
"multiplicacion" : multiplicacion,
}
def operacion(*args,... |
60c6ed333a2c5db766c3938b8e7e330c5929108f | susoooo/IFCT06092019IS | /Repo_M_Lorenzo/Python/Ej11.py | 406 | 3.828125 | 4 | a_actual=input()
a_destino=input()
a_actual=int(a_actual)
a_destino=int(a_destino)
if a_actual==a_destino:
print("Es el mismo año")
else:
if (a_actual>a_destino):
if ((a_actual-a_destino)==1):
print("Ha pasado 1 año")
else:
print("Han pasado",a_actual-a_destino," años")
else:
if ((a_destino-a_actual)==1... |
62944a5348842b5517b6dcecd7de66103d9b132c | NohaAShehab/ITP_PythonMansQ01 | /Day03/dealingwithfiles.py | 803 | 3.609375 | 4 | # deal with of file
# open file
myfile = open("itipackage/data.txt", "r") #default r ---> reading
print(myfile)
print(type(myfile))
# do task , read, write, append
# data = myfile.read() # read content of the file into a string
# print(type(data))
# print(data)
# data = myfile.readline()
# print(data)
# data = myfi... |
a747582b7ab6010f7cadefd0a73f93e23f39a8a5 | selinsezer/pattern_recognition | /Project_1/task1.1/task1_1.py | 2,138 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import os
def plotData2D(X, filename=None):
# create a figure and its axes
fig = plt.figure()
axs = fig.add_subplot(111)
# see what happens, if you uncomment the next line
# axs.set_aspect('equal')
# plot the data
axs.plot(X[0,:], X... |
ffdfeac72712dd5933d6653b2e0dc977f3c7c8f8 | SavvaShe/GBHW | /GBHW1_2.py | 275 | 3.671875 | 4 | a=int(input('enter num: '))
if a<0:
print('error a<0')
else:
h=str(a//3600)
m=(a//60)%60
s=a%60
if m<10:
m='0'+str(m)
else:
m=str(m)
if s<10:
s='0'+str(s)
else:
s=str(s)
print(h+':'+m+':'+s)
|
c9b422ab0c10c6239774dab0c89e3b6c7327bd2e | MrTejpalSingh/Problem-Solving | /Small Practise Programs/Fundamentals Python/Module2/Assignment 5/Human_Tower.py | 660 | 3.75 | 4 | # lex_auth_01269437527007232044
def human_pyramid(no_of_people):
if no_of_people == 1:
return 50
else:
return no_of_people * 50 + human_pyramid(no_of_people - 2)
def find_maximum_people(max_weight):
no_of_people = max_weight // 50
if no_of_people % 2 == 0:
no_of_people -= 1
... |
d82fb5738b276b476f5394e80287ab020e4bdafd | heartkiIIer/HotelCritic | /project/models/Hotel.py | 889 | 3.609375 | 4 | class Hotel(object):
def __init__(self):
self.num_of_reviews = 0
self.avg_rating = {}
self.name = ''
self.price = ''
self.address = ''
# self.city = ''
# self.state = ''
self.us = 0
self.id = ''
# self.comment = []
# self.key_w... |
17f60b0316e2f0058eeb3eb700372438a1f0803b | dannyqiu/advent-of-code | /2017/day12/p2.py | 1,065 | 3.5 | 4 | #!/usr/bin/env python3
from __future__ import print_function
import sys
import re
def solve(data):
pipings = {}
for line in data.split('\n'):
pipe_regex = re.compile(r"([0-9]+) <-> ([0-9, ]+)")
match_result = re.match(pipe_regex, line)
if match_result:
start = int(match_res... |
c1545dfcae78a35f5f7ef85b86ef2b860d92c1e5 | dvns17/variables | /variableDrills.py | 982 | 4.3125 | 4 | '''
For this assignment you should read the task, then below the task do what it asks you to do.
EXAMPLE TASK:
'''
#EX) Make a variable called name and assign it to your name. And print the variable.
name = "Danica"
print(name)
'''
END OF EXAMPLE
'''
'''
START HERE
'''
'''INTEGERS'''
var1 = 5
print (var1)
var2 = 1... |
6cc924005a4ca0dda0cc4432766108a2c2c70c84 | dustinlacewell/deconf | /deconf.py | 6,364 | 3.5 | 4 | import os, imp
class RequiredParameterError(Exception): pass
class CyclicalDependencyError(Exception): pass
class ParameterTypeError(Exception): pass
class ParameterValueError(Exception): pass
def load_config(filename):
basename = os.path.basename(filename)
parts = basename.split('.')
modname = parts[0]
... |
eecd3933a2256603a042d40d33e54f7fac1efc3d | techbless/parabola-simulator | /src/run.py | 2,255 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import time
import math
from mpl_toolkits.mplot3d import Axes3D
import ball_physics as bp
def show_help():
help_message = (
" ////// ////// // ////// ",
" // // // // // // ",
" ////// ... |
e31120c98094c49c0389f7cd0b545f9774dc6258 | AFatWolf/cs_exercise | /4.1. Understanding Object Methods/assignment4-1-1.py | 134 | 3.984375 | 4 | def list_upper(xs):
result = []
for x in xs:
result.append(x.upper())
return result
xs = ['a','b','c']
print(list_upper(xs)) |
72ed97f9d2d6aebfc6a3adaa1d72cabfb9b0fc5e | jinw96/python-tutorial | /code/8. if & for.py | 1,093 | 3.921875 | 4 | # 1. Alssong Dalssong Pythong
print("\n# 1")
s = "AlsongDalsongPythong" # from this string, we want to print the right one
for c in s:
print(c, end='')
# 's' one more
if(c == "s"):
print(c, end='') # or just print("s", end='')
# blank after 'g'
if(c == "g"):
print(end=' ') # ... |
c7277827ed457df365469d7b30076efa49c13fc7 | elvirag/BudgetGraph | /sqlite_stuff.py | 1,219 | 3.859375 | 4 | import sqlite3
def connect():
conn = sqlite3.connect('expenses_db.sqlite')
cur = conn.cursor()
return conn, cur
def create_table():
conn, cur = connect()
cur.execute('pragma encoding')
cur.execute("""CREATE TABLE IF NOT EXISTS expenses (
Expense_id INTEGER PRIMARY KEY,
Date_purchase DATE NOT NULL,... |
a6e1c8ed661292bf6839b0d0183b5ee4d8c71f86 | paraujocaimi/blockChainWithPython | /entrega/MerkTree.py | 3,524 | 3.71875 | 4 | import hashlib
from hashlib import sha256 #função para fazer o hash 256
# site para verificar hash
# https://timestampgenerator.com/tools/sha256-generator
#Fazer o calculo do hash do block para gerar o Proof of work
class MerkTree:
def __init__(self, _arrayHash):
self.arrayHash = _arrayHash... |
8d60638e300ce87898a71f22f2c2d491c7f409b7 | Sakartu/suikoden | /prices.py | 1,895 | 3.734375 | 4 | #!/usr/bin/env python
from prices1 import name as name1
from prices1 import price as price1
from prices2 import name as name2
from prices2 import price as price2
from operator import itemgetter
from sys import argv
import traceback
differences = {}
abs_difs = {}
max_profit = {}
best_buy = {}
for item in price1.keys():... |
3bf97590b5438a177e473086c67ab43377c66c37 | KrishnaPrasath/CODEKATA_G | /Mathh/479.py | 1,097 | 3.703125 | 4 | # Shreya is a brilliant girl. She likes to memorize the numbers. These numbers will be shown to her. As an examiner develop an algorithm to test her memory.
# CONSTRAINTS
# 1<=Y,N,T<=1000
# Input Description:
# First line contains no. of test cases(Y). Next line contains a number N. Next line contains n space separ... |
46bd5b65c05386f54f0f7cb4ff2ce5f6f8ec65a1 | Deepanshu276/AlgorithmToolbox | /Array/practiceQuestion/maxProductOfTwoInteger.py | 283 | 3.90625 | 4 | from array import *
arr1=array("i",[1,12,3,4,5,6,7,10])
max1=0
max2=0
arr2=array("i",[])
def product(arr):
for i in range(len(arr)):
for j in range(i+1,len(arr)):
max1=arr[i]*arr[j]
arr2.append(max1)
print(max(arr2))
product(arr1)
|
3cb32e8e877f07cb24070239bbaed8a0493fa47f | chuck0523/atCoder | /python/03_b.py | 386 | 3.546875 | 4 | replace = [i for i in 'atcoder']
def isCharMatch(a, b):
if a == b:
return True
elif a == '@' and b in replace:
return True
elif a in replace and b == '@':
return True
else:
return False
print('You can win' if all(list(map(lambda a: isCharMatch(a[0], a[1]) ,list(zip([i f... |
37336809bbd688178940548b65442a5562420b54 | joshhmann/python-learnings | /#compound data structures.py | 742 | 4.25 | 4 | #compound data structures
#can include containers in other containers to create compound data structures
#dictionary that maps keys to values that are also dictionaries
elements = {"hydrogen" : {"number": 1,
"weight:" : 1.00794,
"symbol" : "H" },
"hel... |
39600eb3cafa4ed36689db61d7ab83ec91da45a4 | QT-HH/Algorithm | /SWEA/5186_이진수2/5186_이진수2.py | 469 | 3.5625 | 4 | import sys
sys.stdin = open('input.txt')
def two(num):
n = -1
res = []
while n > -14:
if num >= 2 ** n:
res.append('1')
num -= 2 ** n
if not num:
break
else:
res.append('0')
n -= 1
else:
print(res)
... |
1fb9596f114d5d7ad5d9d3567705082119577b98 | aimdarx/data-structures-and-algorithms | /solutions/Greedy Algorithms/class_photos.py | 1,825 | 4.03125 | 4 | """
Class Photos:
It's photo day at the local school, and you're the photographer assigned to take
class photos. The class that you'll be photographing has an even number of is students, and all these students are wearing red or blue shirts.
In fact, exactlyhalf of the class is wearing red shirts, and the other half ... |
7f2dadde44f742aa604f730e6ee34acba13084ef | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 7/Newton's method.py | 105 | 3.625 | 4 | def sqrt(x):
a=0.5*x
b=x
while abs(a-b)>0.001:
b=a
a=0.5*(a+x/a)
return a |
ca2a426f5279cc62d54e4233612b8abdf4be5d97 | nimiew/python-oodp | /tutorial_1_classes_and_instances.py | 562 | 4.0625 | 4 | """
Python OODP Tutorial 1: Classes and Instances
"""
class Employee:
def __init__(self, first, last, pay): # constructor
self.first = first # attribute
self.last = last
self.email = "{}.{}@company.com".format(first, last)
self.pay = pay
def fullname(self): # method; remember ... |
b839e8df2e84ffe1d1068af2636759f338c8094b | Goyatuzo/python-problems | /project_euler/062/cubic_permutations.py | 1,546 | 3.65625 | 4 |
from sys import getrecursionlimit
def lex_sort(s: int):
return ''.join(sorted(sorted(str(s))))
def permute_numbers(s: int):
s = str(s)
if len(s) == 0:
return [s]
permutations = []
for idx, char in enumerate(s):
temp_str = s[:idx] + s[idx + 1:]
rest = permute_numbers(tem... |
9bd59b97cab5bb815f5ab1d514c01e75f3f301d0 | xiaoyeren/python_high_performance | /parallel_processing/pro_pool_execu.py | 1,420 | 3.625 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2019年5月5日
@author: Zhukun Luo
Jiangxi university of finance and economics
'''
#ProcessPoolExecutor类的用法
import asyncio
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import wait,as_completed
def square(x):
return x**2
if __name__=='__ma... |
a42d7d634187a611f639597f66db94e8f5e2a968 | haiyan12345/store | /笔记本电脑面向对象.py | 1,949 | 3.984375 | 4 | '''
有笔记本电脑(屏幕大小,价格,cpu型号,内存大小,待机时长),
行为(打字,打游戏,看视频)
'''
class notebookComputer:
__username = ""
__size = 0
__price = 0
__CPUtype = ""
__Memorysize = 0
__Standbylength =""
def shownotebookComputer(self):
print("这是一台屏幕大小为:",self.__size,
"寸,价格为:",self.__pr... |
76fcbea8bfd30e3a845acb057212ab1c33453f11 | axura/shadow_alice | /demo07.py | 169 | 3.640625 | 4 | #!/usr/bin/python
#Project Euler problem 1: factors of 3 and 5
result = 0:
for i in range(1000) :
if (((i % 3) == 0) || ((i % 5) == 0)) :
result += i;
|
5536fd83638ce48beec0d43c8cdc91068d2c5bf3 | parv3213/Python-Archived | /class 12 lab file/queue.py | 1,694 | 3.875 | 4 | def cls():
print"\n"*100
def isempty(qu):
if qu==[]:
return 1
else:
return 0
def Enquene(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
def dequeue(qu):
if isempty(qu):
return"Underflow"
else:
... |
a8770f501ccb2a34b930fea0e99b2bf59c204dfb | buxizhizhoum/data_structure_and_algorithm | /graph/basic_graph/sparse_graph.py | 1,604 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
implement graph with adjacent list
it is better to implement graph with adjacent list when the graph is sparse
"""
from __future__ import print_function
class SparseGraph(object):
def __init__(self, n, directed=False):
self.n = n
self.m = 0
se... |
83cab97aff8c4fdb649e99687d1798c19190214f | fchapoton/comch | /comch/symmetric/symmetric.py | 16,180 | 3.890625 | 4 | from comch.free_module import FreeModuleElement
from itertools import product
class SymmetricGroupElement(tuple):
r"""Element in a finite symmetric group.
We refer to elements in the group of permutations of :math:`r` elements
:math:`\mathrm S_r` as symmetric group elements of arity :math:`r`. An
ele... |
0b9deb22ce017f54ee5122382a7ea213a2867980 | diegoshakan/algorithms-python | /Dic_Def_Python/calcDef.py | 900 | 4 | 4 | '''
cadastrar
remover
gerar relatório
matricula, nome e idade
'''
alunos = {2: ['diego', 33], 1: ['kassandra', 34], 3: ['Aimée', 4]}
def cadastrar(mat, nome, idade):
alunos[mat] = [nome, idade]
print('Cadastro Realizado com sucesso.')
def remover(mat):
alunos.pop(mat)
print('Removido com sucesso.')
... |
5c60b25b678adb7f601c9dc0a69699298b9631c2 | GlennPatrickMurphy/Thinkful- | /Stat_Analysis/Plotting/ProbabilityPlot.py | 302 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 15 23:05:21 2016
@author: GlennMurphy
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
mean = 0
variance =1
sigma = np.sqrt(variance)
x= np.linspace(-3,3,100)
plt.plot(x,mlab.normpdf(x,mean,sigma))
plt.show()
|
820ecbd9eab2801ecd94a61fbad2127d5cfb95cf | mc-mario/PracticePython | /PycharmProjects/PracticePython/Ex2.OddorEven.py | 360 | 3.875 | 4 | number = int(input("Introduce un número: "))
if (number % 2) == 1:
print("Impar")
else :
print("Par")
if (number % 4) == 0:
print("Múltiplo de 4!!!!")
print("Extra: Introduce dos números")
enum = int(input("Primer número: "))
enum2 = int(input("Segundo número: "))
print("{0} / {1} resulta en : {... |
bd88d10dd10ac7af432535b132c35f1e7e8fa09f | CS-for-non-CS/ThisIsCodingTest | /광훈/PART03/그리디/02_곱하기_혹은_더하기.py | 210 | 3.703125 | 4 | S = input()
result = 0
for s in S:
if result == 0:
result += int(s)
else:
if int(s) == 1:
result += int(s)
elif int(s):
result *= int(s)
print(result)
|
ad4570392d3dc97694e83d169303fdaa0f08e42a | gabriellaec/desoft-analise-exercicios | /backup/user_144/ch21_2019_08_19_13_23_29_727229.py | 155 | 3.828125 | 4 | conta = float(input("Qual o valor da conta do restaurante ? "))
conta_com_10 = conta * 1.1
print("Valor da conta com 10%: R${0:.2f}".format(conta_com_10)) |
51c728046b9fd4b0217eab90835effdf1e4ea2e4 | mlechonczak/subnetcalc | /subnetcalc.py | 6,503 | 3.796875 | 4 | from sys import exit
def ip_valid(ip):
'''This functions tests if IPv4 address is valid. If yes, it returns IPv4 address.
Function will accepts IP address from classess A, B and C except:
- 127.0.0.0/8 - uses for loopback addresses
- 169.254.0.0/16 - used for link-local addresses'''
ip_octets = ip.split(... |
dd8e3afef5ff8f8a061cad57d60411fbe5bc087a | Aasthaengg/IBMdataset | /Python_codes/p02861/s231434301.py | 311 | 3.5 | 4 | def dist(x0, y0, x1, y1):
from math import sqrt
return sqrt((x1-x0)**2 + (y1-y0)**2)
from itertools import permutations
N = int(input())
points = [tuple(map(int, input().split())) for _ in range(N)] #; print(points)
dsum = 0
for i, j in permutations(points, 2):
dsum += dist(*i, *j)
print(dsum/N) |
4b328b3137c7524358c12c7e838d38608c09d078 | ebrahimsalehi1/frontend_projects | /Python/PrintSquare.py | 309 | 3.828125 | 4 |
n = int(input(''))
star=""
for i in range(n):
for j in range(n):
if i==0 or i==n-1:
star = star+"*"
else:
if j==0 or j==n-1:
star = star+"*"
else:
star = star+" "
star = star+"\n"
print(star)
|
82648212a8357ef54841f6923466a693959c7eeb | Nihilnia/reset | /Day 16 -exampleModule.py | 240 | 3.65625 | 4 | # example Module
itsAVarible = "Nihil"
sayHi = lambda x : print("Hello dear", x)
def h2so4(*arg):
"""
Toplama islemi yapar.
"""
result = 0
for number in arg:
result += number
return result |
4505e1e3a67e5219f88b3e542bc28bde38fa18a6 | bjaus/tdd-book | /py/bank.py | 621 | 3.75 | 4 | from money import Money
class Bank:
def __init__(self):
self.__rates = {}
@staticmethod
def __make_key(from_, to):
return f"{from_}->{to}"
def add_exchange_rate(self, from_, to, rate):
key = self.__make_key(from_, to)
self.__rates[key] = rate
def convert(self, mo... |
ae93480ff78b28d97fb26208ca722708e033fc1e | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/095_Unique_Binary_Search_Trees_II.py | 932 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
c_ Solution o..
___ generateTrees n
"""
:type n: int
:rtype: List[TreeNode]
"""
__ n __ 0:
r... |
3437adc87332c59aaec2dcc412e485ac2ff707c1 | gertsfert/ds_from_scratch | /src/linear.py | 1,741 | 4 | 4 | from typing import List
from math import sqrt
Vector = List[float]
class VectorSizesDifferentError(Exception):
""" Error raised when the input vectors are of different
sizes (for elementwise operations)
"""
pass
def vector_sum(vectors: List[Vector]) -> Vector:
"""Adds corresponding elements"""
... |
d1b44c4c602a55e1e609c8196ff10338b166a60a | milan-ex3labs/rocketRL | /data_classes.py | 1,301 | 3.75 | 4 | from dataclasses import dataclass
@dataclass
class Rocket:
height: float = 50 # height of the rocket in meters
fin_offset: float = 3 # how far below the nose are the fins
fuel_height_prop: float = .5 # What proportion of the rocket is the fuel tank
fin_drag: float ... |
77fd2df6bdf55c025734fc627951b73873e3e6dd | bmoretz/Daily-Coding-Problem | /py/dcp/problems/stack_queue/stack.py | 397 | 3.90625 | 4 | """
Stack.
push, pop, peek, is_empty.
"""
class Stack():
def __init__(self):
self.data = []
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop() if len(self.data) > 0 else None
def peek(self):
return self.data[-1] if len(self.da... |
bf8400102ddfb4ddf11b74138c0e088f698fa2e1 | chriswill88/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 656 | 3.828125 | 4 | #!/usr/bin/python3
"""
The island_perimeter Fuction
looks at a 2 dimensional array
and finds the perimeter of the 1's
that define land
"""
def island_perimeter(grid):
per = 0
for i in range(len(grid)):
for x in range(len(grid[i])):
if grid[i][x] == 1:
if x =... |
5c8c45318b72e14766f0133e2c9f357d9e5ce75b | nwtgck/python-type-hints-prac | /callable_prac.py | 523 | 3.59375 | 4 | import typing
def f1(callable: typing.Callable[[int], str]) -> str:
return callable(1)
# def f2(callable: typing.Callable[[int], str]) -> str:
# return callable("hello") # mypy error(GOOD!): error: Argument 1 has incompatible type "str"; expected "int"
print(f1(lambda i: "hello"))
# print(f1(lambda i: 1.3)... |
341e775a45cc8ad245fb831a83ff158ca9b32b38 | BennyW23/AdventOfCode | /aoc2018/day2_p1.py | 1,174 | 3.578125 | 4 | def read_input(inp):
f = open("day2.txt", "r")
l = f.readlines()
for i in range(len(l)):
l[i] = l[i].strip("\n")
return l
l = read_input("day2.txt")
# l = ["abcdef", "bababc", "abbcde", "abcccd","aabcdd", "abcdee", "ababab"]
def count_n_occurences(n, inp):
# finds the amount of phrases i... |
b729424c0582179afe46651921920f9b2e821f2e | AlexReva27/car_numbers | /car_numbers2.py | 1,001 | 3.6875 | 4 | import os, keyboard
file = open("base.txt").read().split()
def inp():
guess = input("Введите номер автомобиля или часть номера: ").strip()
if len(guess) != 0:
return guess
else:
print("Вы ничего не ввели")
ex()
def search(guess):
return [word for word in file ... |
a6cd99553a3803a1035746b01609204512a14f1b | karthikk/projecteuler-python | /problem7.py | 533 | 3.90625 | 4 | #!/usr/bin/python
import time
def primegen():
primelist = []
current = 3
yield 2
while 1:
isprime = 1
for i in primelist:
if current % i == 0:
isprime = 0
break
if isprime:
primelist.append(current)
yield curre... |
c9fc1301acc25b7b305937781f1d128ae9520800 | chetho/python-learning | /hackerrank/Interview Preparation Kit/Warm-up Challenges/4.py | 450 | 3.953125 | 4 | #!/bin/python3
# Repeated String
import math
import os
import random
import re
import sys
import pdb
# Complete the repeatedString function below.
def repeatedString(s, n):
i,j = n // len(s), n % len(s)
if len(s) == 1:
return s.count("a") * n
else:
return s.count("a") * i + s[:j].count("a"... |
3b22aef337f19a0681174a47287d8fddd73d7c27 | jacgit18/Python-sorts---search | /binary_search.py | 732 | 3.75 | 4 | # Shift crtl b to run in atom script plugin
position = -1
def binary_search(numbers, n):
lower = 0 # lower bound
upper = len(numbers) - 1 # upper bound
while lower <= upper:
mid = (lower+upper) // 2
if numbers[mid] == n:
globals()['position'] = mid
... |
38bcf6e13f49c5a3054fe66f8080a42dc1fa25b7 | cavid-aliyev/HackerRank | /Setunion.py | 238 | 3.859375 | 4 | # Set.union() -> https://www.hackerrank.com/challenges/py-set-union/problem
n = int(input())
set1 = set(map(int, input().split()))
b = int(input())
set2 = set(map(int, input().split()))
set3 = set1.union(set2)
print(len(set3))
|
5a949998f5190e1e9d270e132bcfe104bcbbd045 | MarcusQuigley/Princeton-Algos-P2 | /weeks/week2/bellman_ford.py | 1,637 | 3.78125 | 4 | import sys
class BellmanFord(object):
def __init__(self, n, graph):
self.n = n
self.graph = graph
def compute_shortestpath(self):
distances = [sys.maxsize] * self.n
distances[0] = 0
counter=0
for i in range(self.n-1):
for v1 in range(se... |
408bc37983334b3e5f576f764f21ec4873ed816d | HSx3/TIL | /algorithm/day01/day1_answer/1. List1/BubbleSort.py | 246 | 3.875 | 4 | def BubbleSort(a):
for i in range(len(a)-1, 0, -1): # 범위의 끝 위치
for j in range(0, i):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j] #swap
data = [55, 7, 78, 12, 42]
BubbleSort(data)
print(data)
|
75aa84be9fe45fd3f5a2908a325bfb7ea1e10549 | milkshakeiii/simple_python_projects | /homework/mp3-code/part1/naive_bayes.py | 8,028 | 3.625 | 4 | import math
import numpy as np
#import matplotlib.pyplot as plt
class NaiveBayes(object):
def __init__(self,num_class,feature_dim,num_value):
"""Initialize a naive bayes model.
This function will initialize prior and likelihood, where
prior is P(class) with a dimension of (# of class,)
... |
cd604b8cd640d44220cde6f89c977949124060b5 | wshis77/leetcode | /climbing-stairs.py | 376 | 3.5 | 4 | class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
if n == 1:
return 1
if n == 2:
return 2
else :
prepre = 1
pre = 2
current = 0
for i in range(0,n-2):
current = prepre + pre
prepre = pre
pre = current
#print i, current
return current
s... |
2f8c175c2e016f5c7dec01d872d4489b42f50331 | explorerr/STCRnetM3 | /pytorch_m3/models.py | 5,457 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 14:23:37 2018
@author: zhangrui
"""
import torch
import torch.nn as nn
class Residual5_0(torch.nn.Module):
def __init__(self, xDim, H, activation="ReLU"):
"""
In this class we define a residual block
"""
su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.