blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
a752737c13ff711f56f779e51d8457a6a105d69b | vasyanch/edu | /Vasiliev_book/mult_matrix.py | 1,917 | 4.46875 | 4 | '''
В данном коде реализованы три функции:
rand_matrix(n,m) - инициализирует и возвращает
матрицу n на m, представленную в виде вложенных списков.
unit_matrix(n) - возвр. единичную матрицу размера n.
mult_matrix(A1, A2) - возвр. произведение матриц A1 и A2.
sho... |
f810bd844b72f026627c3d21165ee6393bafa8b6 | vasyanch/edu | /Algo_club/informatics_mccme/Heap/heap_sort.py | 2,315 | 3.6875 | 4 | # Exercise 9(I). Задача: Сортировка массива с помощью кучи(приорететной очереди).
# Метод ООП. Решение через класс.
# не проходит по времени!!!
class Heap(object):
def __init__(self, massif, n):
self.dat = massif
self.n = n
self.size = n
def siftup(self, k)... |
643a69f8771c7152ded30953b1f764f065d37312 | vasyanch/edu | /first_my_proframm/exception_multiTry.py | 735 | 3.625 | 4 | sep = '-' *32 + '\n'
print(sep +'EXCEPTION RAISED AND CAUGHT')
try:
x = 'spam'[99]
except IndexError:
print('except run')
finally:
print('finally run')
print('after run')
print(sep + 'NO EXCEPTION RAISED')
try:
x = 'spam'[3]
except IndexError:
print('except run')
finally:
prin... |
243ee248ffb2ff7b38fede71483ab29297cf2b2f | vasyanch/edu | /Algo_club/class_queue.py | 773 | 3.953125 | 4 | # Структура данных очередь на базе массива.
class Queue:
def __init__(self, size):
self.data = [None] * size
self.start = 0
self.end = 0
self.num = 0
self.size = size
def push_back(self, a):
if self.num < self.size:
self.data[self.end] ... |
97631d437b471088872e35e794a5818e5b9d2718 | vasyanch/edu | /Algo_club/informatics_mccme/Heap/queue_heap_del.py | 1,828 | 3.78125 | 4 | # Exercise 5(E). Задача: Приорететная очередь с удалением(очередь с приорететом).
def siftup(mas, i):
while i > 0 and mas[i] > mas[(i - 1) // 2]:
mas[(i - 1) // 2], mas[i] = mas[i], mas[(i - 1) // 2]
i = (i - 1) // 2
return i
def siftdown(mas, i):
while (2 * i + 1) < len(mas)... |
85305700ca378e3cc3a6d7b9095bc25e7e663dbc | vasyanch/edu | /first_my_proframm/anti_vowel.py | 179 | 3.671875 | 4 | def anti_vowel(text):
vow = "aeiouAEIOU"
t = ''
for i in text:
if i in vow:
t = t + ''
else:
t = t + i
return t
|
2443d224cc41a2afc46fea72199404e9c1d22d5f | skyying/aoc2020 | /src/days/day9/1.py | 1,172 | 3.59375 | 4 |
def two_entries(nums, target):
seen = {}
for i in nums:
if (target - i) in seen:
return i * (target - i)
else:
seen[i] = True
return None
def get_inputs():
f = open('./in', 'r')
return [int(n) for n in f.read().strip().split("\n")]
def calc_first_number_o... |
b4aae5cdcaff71fe4ef6801646f2c586de04b88a | skyying/aoc2020 | /src/days/day1/1.py | 807 | 3.640625 | 4 |
def read_file():
f = open('in', 'r')
content = []
for x in f:
content.append(x.strip('\n'))
return content
def two_entries(nums, target):
seen = {}
for n in nums:
if (target - n) in seen:
return n * (target - n)
else:
seen[n] = True
return N... |
dc2336046775884088d7fb20bacf1aab5074084c | luwei19941010/python_09 | /三元运算.py | 271 | 3.671875 | 4 | #-*-coding:utf-8-*-
# Author:Lu Wei
#让用户输入值,如果值为整数,则转换成整数,否则赋值为None
data=input('>>>')
value=int(data) if data.isdecimal() else None
d={}
print(type(d))
a=['alex','123','18']
b=['eric','uniut','19']
a.append(b)
print(a) |
339e246de80dcae21570d157d30f194483deb84d | esun0087/SPOJ-Solution | /IWGBS.py | 127 | 3.5 | 4 | n = input()
res = [0,2,3]
if n >= 3:
for i in xrange(3,n+1):
res.append(res[-1] + res[-2])
# print res
print res[n] |
0e00bb5c4b96ae4dcf013b2f79503c36c04fa8c6 | SSITB/rl-project | /arms.py | 2,773 | 3.671875 | 4 | import random
import numpy as np
class ArmBernoulli:
''' Arm to be played in the bandit model with Bernoulli Distribution
'''
def __init__(self, p):
'''Args:
- p (float): the paramater of the Bernoulli distribution
'''
if 0 <= p <= 1:
self.p = p
else... |
9fe798c852f50e62df62b1295dbb755439dc72c6 | slykid/Python3 | /Python Deep Learning Code/ver_2022/7_Implement_CNN.py | 3,845 | 3.734375 | 4 | # 1. Shapes in CNN
# 1) Shapes in the Feature Extractors
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
print(tf.__version__)
N, n_H, n_W, n_c = 32, 28, 28, 3
n_conv_filter = 5
batch_size = 32
k_size = 3
pool_size = 2
pool_strides = 2
input = tf.random.normal(shape=(... |
74b49b93e9bd1eb71c628c7bbf7824c1037be2bd | slykid/Python3 | /CodingTest_Example/Python_Algorithm_Interview/4_Most_Common_Word.py | 758 | 3.59375 | 4 | # 문제
# 금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
# 대소문자 구분은 없으며, 구두점(마침표, 쉼표) 도 무시한다.
# [입력]
# paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
# banned = ["hit"]
# [출력]
# "ball"
def solution(paragraph: str, banned: list) -> str:
import re
input = [x for x in re.sub('[^\w]', " ", paragraph).low... |
3f68c301f8eaaa92623a99199b7df8af40dd97a0 | slykid/Python3 | /CodingTest_Example/Python_Algorithm_Interview/13_palindrome_linked_list.py | 418 | 3.5625 | 4 | # 문제. 연결 리스트가 팰린드롬 구조인지 확인하시오.
# 예시.
# 입력 1. 1 -> 2 (false)
# 입력 2. 1 -> 2 -> 2 -> 1 (true)
def solution(input):
q = []
if not input:
return True
node = input
while node is not None:
q.append(input.val)
node.next
while len(q) > 1:
if q.pop(0) != q.pop():
... |
451af1ea328f3331078e6271fb0a7dcb24e8c2fd | mentalclear/autobots-fastapi-class | /typing_playground/funcs/random_stuff.py | 485 | 4.1875 | 4 | def greeting(name: str) -> str:
""" This function expects to have argument name of type string"""
return 'Hello ' + name
print(greeting('Tester'))
# A type alias is defined by assigning the type to the alias. In this example,
# Vector and list[float] will be treated as interchangeable synonyms
Vector = lis... |
86b8952b5cf5aabf96626238aeb66b8d6ebfe5f5 | zhiqiao/text-game-engine | /my_game_room.py | 2,896 | 3.515625 | 4 | import my_game_utils
class RoomStateMapper(object):
"""Class to maintain all configured room states.
This class, when instantiated, acts like a datastore mapping between a state
ID and a description of a room, which is a list of adjectives.
"""
def __init__(self):
self._default_state = [... |
5de3a114bdaf7e1f3a0606c79f540c84786949c6 | zhiqiao/text-game-engine | /my_game_item.py | 3,334 | 3.953125 | 4 | import copy
class ItemMapper(object):
"""Class to maintain all possible game items.
This class, when instantiated, acts like a datastore mapping between a game
item name and a copy of that game item.
"""
def __init__(self):
# A default no-op item.
self._default_item = GameItem()
... |
914b29d69407348e8ae9b2187739ac9d1a1128cc | Strokov/PyRuletka | /Pysecond.py | 1,821 | 3.765625 | 4 | # coding: utf-8
import turtle
import random
import math
import ucheba
def gotoXY(x,y): # Функция переноса курсора
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
def Circle(r,color): # Функция заливки круга цветом
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(r)
turtle.... |
3f1d65391eeaac96eda46df18494aeadada0af01 | ChristyLeung/Python_Green | /Green/6-1--3 dictionary_1.py | 1,523 | 3.640625 | 4 | # 6-1
favorite_person = {
'first_name': 'athena',
'last_name': 'yeung',
'age': '23',
'city': 'donguan'
}
print(favorite_person['first_name'].title())
print(favorite_person['last_name'].title())
print(favorite_person['age'])
print(favorite_person['city'].title())
# 6-2
favorite_number... |
609b61bab4602df7434e12d207ae1ff5862534cb | ChristyLeung/Python_Green | /Green/5.3.1-2 voting.py | 487 | 4.1875 | 4 | # 5.3
# 5.3.1
if conditional_test:
do something
age = 19
if age >= 18:
print("You are old enough to vote!")
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# 5.3.2
age = 17
if age >= 18:
print("You are old enough to vote!"... |
eebbb911e2a2d0ceb57ca2c3898d511592073f8e | ChristyLeung/Python_Green | /Green/4.3.1-3 numbers.py | 161 | 3.9375 | 4 | # 4.3
# 4.3.1
for value in range(1,5):
print(value)
for value in range(1,6):
print(value)
# 4.3.2
number = list(range(1,6))
print(number)
|
1f8acbbc0af62fdf18d8408eade076fce2d59931 | KShaz/Machine-Learning-Basics | /python code/ANN 3-1 Supervised Simoid training.py | 1,725 | 4.125 | 4 | # https://iamtrask.github.io/2015/07/12/basic-python-network/
#X Input dataset matrix where each row is a training example
#y Output dataset matrix where each row is a training example
#l0 First Layer of the Network, specified by the input data
#l1 Second Layer of the Network, otherwise known as the hidden layer
#S... |
4fef689b385b06e587dff5b9ee8fddd725054680 | harris44/PythonMaterial | /02_Advanced/Hackerrank_solutions/Data Structures/balanced-brackets2.py | 1,066 | 3.953125 | 4 | #!/bin/python
"""
https://www.hackerrank.com/challenges/balanced-brackets/problem
"""
import sys
def isBalanced(s):
stack = []
for ch in s:
if ch in '})]':
if not stack:
return 'NO'
elif ch == ')':
if stack[-1] == '(':
stack.re... |
1360a02703e48c7cee0c53073e3dd650f78c742c | harris44/PythonMaterial | /00_Basic/03_Boolean_Operations/01_booleanOperations.py | 383 | 4.0625 | 4 | #!/usr/bin/python
"""
Purpose: Boolean Operations
"""
# True, False
choice = True
print 'choice = ', choice
true = 'Udhay Prakash'
choice = true
print 'choice = ', choice
choice = False
print 'choice = ', choice
print "True = ", True
print "True * 30 = ", True * 30 # True has a value of one
print "False = ", ... |
b57eb53c83c401e1f91ab64e502bfb548111d261 | harris44/PythonMaterial | /00_Basic/14_OOP/12_Linked_List_creation.py | 452 | 3.703125 | 4 | #!/usr/bin/python
"""
Purpose: linkedList creation
"""
__author__ = 'Udhay Prakash'
class LinkedList:
def __init__(self, initData):
self.data = initData
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next()
def setData(self, newDa... |
fd13ff030f12e027b7237ff1eb808eff65fd3572 | harris44/PythonMaterial | /02_Advanced/algorithms_and_data_structures/02_single_linked_list.py | 557 | 3.859375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Purpose: Implementation of Single Linked List
In a linked list, each node will store a value and address of next node
"""
__author__ = "Udhay Prakash Pethakamsetty"
###########################
# UNDER DEVELOPMENT
#############################
class Node(object):
def... |
4efffd09c623ecf7c64ef4c4e1bac18dc2ec8af5 | harris44/PythonMaterial | /02_Advanced/algorithms_and_data_structures/01_Guessing_Game_with_Stupid_search.py | 1,272 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randrange
"""
Purpose: Stupid Search.
In a list of numbers, user guesses a number.
if it is correct, all is good. Else, next time, he/she will guess among the unguessed numbers.
"""
__author__ = "Udhay Prakash Pethakamsetty"
list_of_numbers = range(10,... |
8c00d01127af04807c9a8f03678312b3d66ab9e2 | terryhu08/algorithm | /IT名企算法/二叉树问题/根据后序数组重建搜索二叉树.py | 1,226 | 3.609375 | 4 | def isPost(arr:list, start:int, end:int)->bool:
if start==end:return True
less=-1
more=end
for i in range(start,end):
#后序遍历根节点在最后,所以与根节点比划分左右子树
if arr[end]>arr[i]:
less=i
else:
more=i if more==end else more
if less==-1 or more==end:
return isPo... |
741186406a63a689c06999e232429c1cd2a6eaf5 | yavar29/python_programs | /declaring_and_printing_inbuilt_data_structures.py | 664 | 4.125 | 4 | # first method of declaring a list
l=[]
l.append("saim")
l.append("yavar")
l.append("sidra")
l.append(101)
l.append(101.99)
l.append("adil")
print(l)
# second method of directly declaring a list
l1=['saim', 'yavar', 'sidra1', 1013, 101.99, 'adil1']
print(l1)
print(l1[0]+' '+str(l1[3]))
print(type(l1))
# declaring a t... |
d3b4126ae0900d2a03f8d8a2c2e025f6162b04c1 | KaygoYM/Python-and-Tensorflow-learning | /Python_basic/matplot17.py | 1,125 | 4.03125 | 4 | import matplotlib.pyplot as plt
import numpy as np
#图中图 plot in plot
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# below are all percentage
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 #相对于整个figure的百分比
ax1 = fig.add_axes([left, bottom, width, height]) # main axes
ax1.plot(x... |
86d7ec536b38554f3c392dd1a0e3e3c680ae3186 | KaygoYM/Python-and-Tensorflow-learning | /Python_Web/threading2.py | 1,235 | 3.75 | 4 | import threading
import time
from queue import Queue
def thread_job():
print('T1 has launched\n')
for i in range(10):
time.sleep(0.1)
print('T1 has finished\n')
def T2_job(l,q):
print('T2 start\n')
for i in range(len(l)):
l[i]=l[i]**2
q.put(l)
print('T2 f... |
dfb5648c3e5db8d19cc09e99da573ee439c61840 | halapano/mympthwex | /dllist_ex14/dllist/dllist.py | 1,346 | 3.90625 | 4 | class DoubleLinkedListNode(object):
def __init__(self,value,nxt,prev):
self.value = value
self.nxt = nxt
self.prev = prev
def __repr__(self):
nval = self.nxt and self.nxt.value or None
pval = self.prev and self.prev.value or None
return f"[{self.value},{repr(n... |
0e82dd432d6fd4fc5cb42f891be48f89cfc82b2b | halapano/mympthwex | /ex5_cat.py | 251 | 3.5 | 4 | import argparse
parser = argparse.ArgumentParser(description='concatenate')
parser.add_argument("filename",type =str,nargs='*')
args = parser.parse_args()
for file in args.filename:
infile = open(file,'r')
print(infile.read(),end="")
|
854b44a67d155c0c901d010a3e7ed5fc3735761a | liboyue/BOOM | /examples/BioASQ/extra_modules/bioasq/Tiler.py | 671 | 4.3125 | 4 | import abc
from abc import abstractmethod
'''
@Author: Khyathi Raghavi Chandu
@Date: October 17 2017
This code contains the abstract class for Tiler.
'''
'''
This is an Abstract class that serves as a template for implementations for tiling sentences.
Currently there is only one technique implemented which is simpl... |
072d3061955eb283fd9c3f831703d4ede2aba196 | MrPinkPigg/cisc108 | /Python Labs/week11LearningStuff.py | 1,653 | 4.03125 | 4 | message = "hello world" #concatenation
message = message + "!"
print(message)
print(message[5:])
print(message[1:]) #substring
print(message[-5:])
my_list = [10, 30, 50] #lists
print(my_list)
my_list.append(70) #adding to lists
print(my_list)
print(my_list[0]) #calling indecies
class book: #classes
'''
Att... |
5d22bc101799a9759b44e9078f16c2a62df39b13 | DimitriosStergiou/-python | /12.ascii.py | 342 | 3.703125 | 4 |
def readIn():
file=str(input("Give a name of file:"))
try:
fn=open(file,'r')
except IOError:
print("Error: File does not appear to exist.")
return 0
return fn.read()
s=readIn()
myList=[]
for c in s:
k=128-ord(c)
myList.append(chr(k))
print(myList)
for i in range(len(myList)):
print(myList[len(myList)-i-... |
84b647de1f0cae44891d95bb393681bb04bfb49a | wstivenarango/Banda_Flask | /Banda-py-master/Banda-py-master/Instrumentos.py | 2,249 | 3.78125 | 4 | from abc import ABC, abstractmethod
class Instrumento(ABC):
@abstractmethod
def tocar(self):
pass
@abstractmethod
def preparar(self):
pass
class Guitarra(Instrumento):
nombre = 'Guitarra'
imagen = "/static/Guitarra.png"
def tocar(self):
return("tocand... |
9c86c21e8546fd8bde9a8b41187fd54e6c25b538 | BumShubham/assignments-AcadView | /assignment8.py | 1,591 | 4.46875 | 4 | #Q1
#What is time tuple
'''
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −
Index Field Domain of Values
0 Year (4 digits) Ex.- 1995
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61 (60/61 are leap seconds)
6 Day of Week 0 to 6 (Monday to Sunday)
7 Day... |
98c7bff2305aa5628e982db72d255800dd3cf860 | BumShubham/assignments-AcadView | /assignment13.py | 2,925 | 4.09375 | 4 | #Q1 Name and handle the exception occurred in the following program:
try:
a = 3
if a < 4:
a = a / (a - 3)
except (ZeroDivisionError, IndentationError):
print("The answer is 0.")
else:
print(a)
"""answer 1: The error that has occurred is IndentationError : unexpected indent and
also ZeroDivisi... |
bf44a078ad05d797e2dbd1d48e621fb58ecde9f3 | zyx20180209/pie-game | /piegame/pie1.py | 606 | 3.71875 | 4 | import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 500))
myfont = pygame.font.Font(None, 60)
white = 255,255,255
blue = 0,0,255
textImage = myfont.render("Hello Pygame", True, white)
pygame.display.set_caption("Drawing Circle")
while True:
for event in... |
ce12861ff7869727cad0eecc19de0d3437e6138c | olyapetryshyn/Ciphers | /AffineCipher/affineCipher.py | 5,202 | 3.5 | 4 | import os
import sys
upperCased = list(map(chr, range(ord('A'), ord('Z')+1))) # A, B, C, ..., Z
lowerCased = list(map(chr, range(ord('a'), ord('z')+1))) # a, b, c, ..., z
probil = list(' ')
#otherSymbols = [' ', '?', '!', '.', ':', '-', '_', '(', ')']
alphabet = upperCased + lowerCased + probil
letterFreq = {'E': 1... |
8bf2fb89b65f3b410869a4f22384ecb1bc258ff3 | R2D34/Algorithms-Practice | /Staircase/Staircase.py | 803 | 3.90625 | 4 | import numpy as np
def staircase(height, strides):
#0 is our ground condition
#if we have no stairs there is only 1 way to go
if height == 0:
return 1
# numpy array for higher efficiency: no rellocation of memory
ways = np.zeros(height + 1)
ways[0] = 1
for currStep in range (1,... |
fc4e042d22a93e94989da4e7db7f25e1b736f918 | JoyOfTech/Playtime_Projects | /Repositories/PBJLoop.py | 1,907 | 3.890625 | 4 | # Lesson 2: PBJ Loop
# Goal #1: Write a new version of the PB&J program that uses a while loop.
"""
total = 1 #I have no idea how anyone found this out. add variable "total", make it equal 1, then add 1 each time.
bread = 83
peanutbutter = 23
jelly = 18
sandwich = min(bread / 2, peanutbutter, jelly)
while sandwic... |
edc1d6157f5af87fdb2ab16c6cc4a5a7b5a2c240 | saeidp/Udacity-Artificial-Intelligence-for-Robotics | /Warehouse.py | 9,445 | 4.0625 | 4 | import os
__author__ = 'Ibis'
from operator import itemgetter
# -------------------
# Background Information
#
# In this problem, you will build a planner that helps a robot
# find the shortest way in a warehouse filled with boxes
# that he has to pick up and deliver to a drop zone.
#
# For example:
#
# warehouse = ... |
ca16ffc73758ca373461b366cc66299d1337b099 | BenGilbert98/OOP_Task_5 | /list.py | 722 | 3.546875 | 4 | import random # importing the random module
class List:
def __init__(self):
self.dataset = [] # Blank dataset list
def random_dna_sequence(self):
# for every value in the range 1 - 1000 a number between 1 and 4 is generated
for i in range(1, 1000):
dna_value = random.rand... |
f2824fc0ab161275fd19ca8a9f64f0a3e6bb0f47 | lolajay2022/MyPythonCourse | /Labs/Ch02-vscode/which_is_cheaper.py | 913 | 4.09375 | 4 | import math
product1_price=input("What is the price of product1?")
price1= float(product1_price)
print('the type is', type(product1_price))
print('product1_price is:', price1))
print('product 1 is an integer:' ,price1.is_integer())
weight1 = float(input("How many ounces is product 1? "))
price2 = float(input("What is t... |
bff94ecd69ccf5487b8dbad8e2596755ce58b4cf | BBBB00/workshop2 | /lists/change value.py | 124 | 3.875 | 4 | thislist = ["apple","banana","cherry"]
thislist[1] = "watermalon"
print(thislist) #output ['apple', 'watermalon', 'cherry'] |
c8fe388671d0870c7b85a55df5ab9b0fcb3807e5 | Kevin-Grgd/TP_Outils_Info | /tp3/ex2/add.py | 164 | 3.875 | 4 | entree=input("Entrez le plus et la limite : ")
s = 0
nb = entree.split(" ")
plus = int(nb[0])
limite = int(nb[1])
while s <= limite:
print(s)
s = s + plus
|
75b29e188be5d3366f2605ab6ac5749d85f77fa0 | Kevin-Grgd/TP_Outils_Info | /tp2/ex3/moyenne.py | 131 | 3.90625 | 4 | nombre=int(input("Entrez un nombre : "))
acc = 0
for n in range(1,nombre+1):
acc = acc + n
moy = acc / nombre
print(moy)
|
37c0a5e7954d0d30b8a179450577c240977b5d8c | lirt15/leetcode | /55_Jump_Game/code.py | 319 | 3.5 | 4 | class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums)<2:return True
start,end=0,0
while end < len(nums)-1:
start,end=end+1,max([nums[i]+i for i in range(start,end+1)])
if end < start:
return False
return True
tp=Solution()
print(tp.canJump([2,0,0])) |
8d52f7aa6b563040ef5529fd9b291b2cf0dabd21 | teocrono/scripts | /sped_correcao/helper.py | 2,718 | 3.625 | 4 | ## funções para auxilio
def soma2strfloat(num1,num2):
num1 = float(num1.replace(",","."))
num2 = float(num2.replace(",","."))
return str(round(num1 + num2,2)).replace(".",",")
def mult2strfloat(num1,num2):
num1 = float(num1.replace(",","."))
num2 = float(num2.replace(",","."))
return str(round... |
08d88a8909d01428901208e29b08240944144e29 | jiejie168/hash_leetcodes | /BinaryTreePostorderTraversal.py | 2,132 | 3.65625 | 4 | __author__ = 'Jie'
"""
145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
# Definition for a binary tree node... |
600e729b6fb974e71df0dd515c0652292ca4a410 | jiejie168/hash_leetcodes | /SudokuSolver_gui.py | 6,326 | 3.625 | 4 | __author__ = 'Jie'
#GUI.py
"""
GUI display for the game of sudoku
"""
import pygame
from SudokuSolver import Solution
import time
pygame.init()
class Grid:
board=[[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0... |
6e5ec1c9c0b3926e94b861a6e895a5d5cea8add4 | cbrown1234/hangman | /hangman.py | 1,817 | 3.890625 | 4 | import random
words = [
'some',
'words',
'which',
'test',
'the',
'game',
]
class Game:
max_misses = 8
def __init__(self, word: str):
self.word = word.lower()
self.known_letters = '_'*len(self.word)
self.guess = '?'
self.misses = []
@property
d... |
6eb241ca4eef5abbf4af8e218c00b1ee6ef7df7b | tomguy04/FlaskFormToCommandLine | /whatsMyName.py | 1,265 | 3.875 | 4 | # Assignment: What's My Name?
# Create a project that allows users to submit a form.
# "/": renders a landing page with a form.
# "/process": the route your form should submit to.
# In your process function,
# print the user's name and redirect to root.
from flask import Flask, render_template, request, r... |
1def46681e7b6fd5dd17ed7040cd83786501e505 | GRSEB9S/linconfig | /qgis/qgis2/python/plugins/qProf/geosurf/utils.py | 2,657 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def is_number(s):
"""
Check if string can be converted to number.
@param s: parameter to check.
@type s: string
@return: boolean, whether string can be converted to a number (float).
"""
try:
float(s)
... |
0b6d5d5fd7798b269baa49c8b4acba3eedd2a097 | mikalstill/codeclub | /2015/network_battleship/stage2_guichat.py | 3,988 | 3.515625 | 4 | #!/usr/bin/python
import datetime
import select
import socket
import sys
import tkinter
PORT = 5005
client_address = None
listen_socket = None
client_socket = None
class ServerOrClientDialog:
def __init__(self, parent):
self.top = tkinter.Toplevel(parent)
tkinter.Label(
self.to... |
51a196d38bc3800a8edc7730a419349b6266e043 | adamnemecek/christophesaintjean.github.io | /Python/py/Factorial numeration and permutations.py | 1,727 | 3.78125 | 4 |
# coding: utf-8
# # Factorial numeration and permutations
#
# Implementation of article:
#
# Laisant, Charles-Ange (1888), "Sur la numération factorielle, application aux permutations", Bulletin de la Société Mathématique de France (in French) 16: 176–183.
#
# http://archive.numdam.org/ARCHIVE/BSMF/BSMF_1888__16... |
1d759eaf1cf8ac98c7fe4397d074d6b35579fcc0 | ShahrukhSharif/Applied_AI_Course | /Data_Visualization/Plotting/EDA1.py | 2,337 | 3.90625 | 4 | # Ploting of Exploretary Data Analysis
'''
1. Understanding of Features And Target Variable
2. Scatter Plot --- Visualize in 2 Dimensions
3. Pair Plot --- If you have 4d,5d and 6d then visualize your data
4. Histogramme --- Analysis one Feature (How Many Datapoints we have in a interval)
5. PDF --- Probablity Distrib... |
8dfe63e954810cead138b81ef4c5fdf813cf224e | ShahrukhSharif/Applied_AI_Course | /Fundamental of Programming/python Intro/Prime_Number_Prg.py | 364 | 4.125 | 4 | # Wap to find Prime Number
'''
num = 10
10/2,3,4,5 ---> Number is not pN OW PN
'''
num = int(input("Input the Number"))
is_devisible = False
for i in range(2,num):
if(num%i==0):
is_devisible = True
break
if is_devisible is True:
print("Number is Not Prime {}".format(num))
else:
pri... |
65db1b94418435c55be5ed1053bb7a73200f6f64 | ericlurton/ERIC_LURTON_M1RES | /TD3 - Corrigé avec explications.py | 5,608 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
# Exercice 1
n = input("Entrer un nombre: ") #Demande un nombre
for i in range(1,11): #Tant que i est inclus entre 1 et 11 --> on affiche n*i, donc n*1 à 10
print(n*i)
print("# *** 1 *** #")
n = input("Entrer un nombre: ")
for i in range(1,11):
print(n*i, en... |
13f0fdca6ee78c55b8b00907292b130a7ce7dadf | sp4c38/kniffel | /src/kniffelGame/lib/utils.py | 3,062 | 3.640625 | 4 | import sys
def get_font_by_size(pygame, box_size, text, list_length, settings):
# This finds the font size which is needed to make a text fit into a specific width and height / returns font_size
# box_size are the width and the height of the window section the text shall fit in (as tuple)
# list_length is... |
a4179cf1b3447abc02a0dfc30c1c3ecda16ee7f7 | andrewlin0/MachineLearningBeginnings | /MNIST.py | 1,973 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 16:14:00 2020
@author: andrewlin
"""
import pandas as pd
import numpy as np
from keras.datasets import mnist
from keras.layers import Conv2D,MaxPooling2D,Flatten, Dense, Dropout
from keras.models import Sequential
from keras.utils import to_categ... |
135912db78ce69952677da13d6e9d0ce06dff1de | hasham7861/BumbleBuddy | /bumbleAI.py | 2,027 | 3.671875 | 4 | # '''
# Author: Hasham Alam
# Features: swipe right based on your user type, and then message them
# How does this AI know when to swipe right
# steps: given an image of person you like, then based on that swipe right
# before swiping right, crop images to just detect the face. - face_recognizt... |
6936912c2055502665c895e2558f087df6deea9f | binxxx/Coursera-Algorithms | /3-Greedy Algorithms, Minimum Spanning Tree, and Dynamic Programming/2-Dynamic Programming/2-Weighted Interval Scheduling Problem/weighted_interval_scheduling.py | 4,919 | 4.03125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Weighted Interval Scheduling Problem:
-Many jobs to do, each job has an importance/weight w_j, a starting time s_i and
an ending time e_i.
Find a maximum-weight subset of the jobs with no overlapping.
Algorithm: (Dynamic programming)
Denote S to be the optimal solut... |
8b48790c6fee4ef35cef892b5e5c4443b8b296b6 | binxxx/Coursera-Algorithms | /3-Greedy Algorithms, Minimum Spanning Tree, and Dynamic Programming/2-Dynamic Programming/3-Knapsack Problem/Knapsack Problem Variations/1-Knapsack Problem with Exact Size/knapsack_with_exact_size.py | 2,810 | 3.78125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Similar to the knapsack problem, but need to subject to sum(w) = W.
Algorithm: Same as the ordinary knapsack problem.
"""
__author__ = 'Ziang Lu'
from typing import List, Set
def knapsack_with_exact_size(vals: List[float], weights: List[int], cap: int) -> \
... |
2f806f47e29acd7b2c7dd83ca41319864e9cdfda | binxxx/Coursera-Algorithms | /1-Divide and Conquer, Sorting and Searching, and Randomized Algorithms/3-Closest Pair/closest_pair.py | 5,810 | 4.125 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given an array of points, find the closest pair.
Naive implementation: O(n^2)
"""
__author__ = 'Ziang Lu'
import copy
import math
from typing import List
def find_closest_pair_1d(points: List[float]) -> List[float]:
"""
Finds the closest pair in the given ... |
b9f0c1e65841bd0ea4c061add08943a701981a8b | binxxx/Coursera-Algorithms | /3-Greedy Algorithms, Minimum Spanning Tree, and Dynamic Programming/1-Greedy Algorithm/4-Data Structure-Union Find/Python/lazy_union.py | 5,866 | 4.0625 | 4 | #!bin/usr/env python3
# -*- coding: utf-8 -*-
"""
Lazy Union implementation of Union-Find data structure.
Lazy Union: Only update a single pointer in each union() operation
When two groups merge, make one group's leader (i.e., root of the tree) point to
the other leader (to be a child of the root of the other tree).
... |
ce5a819e77e94e19d65b152fa222c7db43d436bb | honggom/Study_Note | /data_structure/Stack/stack.py | 682 | 4.09375 | 4 | class Stack():
# 초기화
def __init__(self):
self.stack = []
# 데이터 삽입
def push(self, item):
self.stack.append(item)
# 맨 위(마지막) 데이터 리턴 및 삭제
def pop(self):
if self.isEmpty():
return 'empty..'
return self.stack.pop()
# 맨 위(마지막) 데이터 리턴
def peek(sel... |
3076299707623edad0d0013eddb8affdd8ff323d | JoeBigToe/advent_of_code_2017 | /day19.py | 1,617 | 3.53125 | 4 | import re
global letters, matrix
def getDirection(location, direction):
if direction in ["down", "up"]:
if matrix[location[0]][location[1]-1] != " ":
return "left"
if matrix[location[0]][location[1]+1] != " ":
return "right"
if direction in ["left", "right"]:
i... |
49eb928578248832617071b605653173097344f2 | atifkarim/problem_solving | /python_practise/class_python_1.py | 335 | 3.671875 | 4 | class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')
# Output: 10
print(MyClass.a)
# Output: <function MyClass.func at 0x0000000003079BF8>
print(MyClass.func)
obj = MyClass()
print("a: ",obj.a)
print(obj.func())
# print("func: ",obj.func())
# Output: 'This is my second class'
# print(M... |
8fae00f286dbdacb65109ba40a50b0cec6a705d8 | atifkarim/problem_solving | /python_practise/py_function_return.py | 199 | 3.9375 | 4 | def check(num):
if num!=1 and num!=2:
num=int(raw_input())
check(num)
print "pressed num is: ",num
return num
a = int(raw_input())
d = check(a)
print "finally pressed NUMMMM is: ",d
|
3f21a5021db24233a1a208d63ffa19119779792b | knightstempler/intro-project3-udacity | /app.py | 2,535 | 3.9375 | 4 | import time
from random import randint
pause = 2
def printPause(something, sec):
print(something)
time.sleep(sec)
def takeInputChecker(frm, to):
print('PLease enter a number from: ', frm, 'to', to)
while True:
choice = int(input())
if ((choice < frm) or (choice > to)):
p... |
86c9d3291752b1501400e7de5c780aff0d605128 | dilimanlabs/Pitstop | /utils/fancy_utils.py | 2,296 | 3.65625 | 4 | import random
num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \
19... |
22f9f3941a1163dd5581e514282530a1e398dd2c | niangu/Python_machine_learning | /逻辑回归-信用卡欺诈.py | 10,149 | 3.6875 | 4 | #信用卡欺诈检测
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv("creditcard.csv")
print(data.head())
count_classes = pd.value_counts(data['Class'], sort=True).sort_index()
print(count_classes)
#value_counts统计Class列的属性值0,1各有多少个
count_classes.plot(kind='bar') #条形图,可以用pandas直接画
plt.tit... |
612ace04b4af232ecc5408a2c92f06620e75a17b | kitsuyui/dict_zip | /dict_zip/__init__.py | 2,086 | 4.375 | 4 | """dict_zip
This module provides a function that concatenates dictionaries.
Like the zip function for lists, it concatenates dictionaries.
Example:
>>> from dict_zip import dict_zip
>>> dict_zip({'a': 1, 'b': 2}, {'a': 3, 'b': 4})
{'a': (1, 3), 'b': (2, 4)}
>>> from dict_zip import dict_zip_longest
... |
efc0e87feb62b0dfd3aa203cb99a2cb3aafde10c | yayapy/Hands-on-python | /exception.py | 469 | 3.765625 | 4 | #!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
#print KelvinToFahrenheit(279)
#print int(KelvinToFahrenheit(600.78))
#print KelvinToFahrenheit(-5)
try:
fh = open("testfile", "w")
fh.write("This is my test file for exc... |
709fafac6bbcfbee03859e251c88cee0d14dcdb4 | yangulo/Data-Structures-Algorithms-Nanodegree-Project | /Project_2/problem_3/BinaryTree.py | 806 | 3.96875 | 4 | from Project_2.problem_3.TreeNode import TreeNode
class BinaryTree:
def __init__(self, root=None):
self.__root = root
self.__size = 0
def get_root(self):
return self.__root
def insert(self, value):
if value is None:
return False
self.__root = self.inse... |
bd72fe2a81a1c9fad22af16de6c5299ddbcd5b2e | yangulo/Data-Structures-Algorithms-Nanodegree-Project | /Project_2/problem_2/problem_2.py | 536 | 3.59375 | 4 | import os
def find_files(suffix, path):
if len(path) == 0:
return -1
return find_files_recursive(suffix, path, list())
def find_files_recursive(suffix, path, new_arr):
arr = os.listdir(path)
for element in arr:
new_path = path + "/" + element
if os.path.isfile(new_path):
... |
c1058f961aaccdf0815c8037c72db7159816645a | yangulo/Data-Structures-Algorithms-Nanodegree-Project | /Project_3/problem_3/problem_3.py | 624 | 3.5625 | 4 | import copy
from Project_3.helpers.Merge_Sort import merge_sort
def rearrange_digits(input_list):
if len(input_list) == 1 or len(input_list) == 0 or input_list is None:
return None
sorted_array = merge_sort(input_list)
copy_sorted = copy.deepcopy(sorted_array)
string_1 = ""
string_2 = ""
... |
5afd548624578e174b04bec5374c778e1bbed79f | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom04/a_module.py | 1,048 | 4.15625 | 4 | """
How to mock function in a module.
In a unit test we dont want to actually read a file so we will mock
the read_file_content() function. But still test get_number_of_line_in_file().
"""
def get_number_of_line_in_file():
"""
Return how many lines exist in a file
"""
content = read_file_content()
n... |
b0933cd099c1f235fdd0cc00bf40a9a4bf8269ba | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom02/src/account.py | 1,793 | 3.90625 | 4 | #!/usr/bin/env python3
"""
Account class
"""
import random
class Account:
interest = 1.12
def __init__(self, amount, name, owner):
self._balance = amount
self.name = name
self.owner = owner
self.number = random.randint(1000000, 20000000)
def withdraw(self, amount):
... |
7bc58f3621d6e04206543d4b556929e56b1c3b0f | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom03/get_post_ok/src/guess_game.py | 1,766 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Main class for the guessing game
"""
import random
from src.guess import Guess
class GuessGame:
"""
Holds info for playing a guessing game
"""
def __init__(self, correct_value=None, guesses=None):
if correct_value is not None:
self._correct_value = correct... |
1c7fff9785c0b6be2abe9313696c42f622dbce11 | Gangadhar454/hackerrank-solutions-python | /sqrt.py | 389 | 4.03125 | 4 | def sqroot(x):
if (x==0 or x==1):
return x
else:
start=1
end=x
while(start <=end):
mid=(start+end)//2
if(mid*mid == x):
return mid
elif(mid*mid < x):
start=mid+1
ans=mid
e... |
8e2fb19c70fe196a2c8812139d7794b657b45e99 | Shnatta/Banner-around-word | /banner-around-word.py | 195 | 3.765625 | 4 | def banner(xy):
x = ""
for i in range(len(xy)+4):
x+= "*"
return x + "\n* " + xy + " * \n" + x
vy = input("Please enter a word you would've like to be bannered around # ")
print(banner(vy)) |
87d80ec70e3daf58920d1985e97a1dd0904f0e94 | borisigal/my_ds_course | /04 flow control barry sigal.py | 4,101 | 4.1875 | 4 | flow control|
------------|
flow control ex 1
-----------------
sentence = 'hello i am python'
char_to_search='m'
counter=0
for char in sentence:
counter+=1 if char==char_to_search else 0
print(counter)
flow control ex 2
-----------------
sentence = 'hello i am python'
lower_sentence=sentence.lower()
unique_... |
b0213aa5c83731bc061145bf29d7b5ec6510c231 | Shokey123/edyoda-python-django | /Python_Revision.py | 8,098 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
Mutable datatypes:
list
dict
set
Immutable:
int
float
tuple
str
# In[ ]:
Mutable :change at same memory location
Immutable : change at same memory location is not possible
# In[ ]:
id() => Memory location
# In[ ]:
type() => data t... |
7ecfde7ce24ea4b37661e1d32bec510566dcee87 | cfoust/leetcode-solutions | /problems/add-digits/solution.py | 1,322 | 4.0625 | 4 | # Explanation:
# Your first instinct is probably just to iterate (or recurse) and sum the
# digits until the number converges. That is a fine approach as (though I
# haven't proven this) doing so should converge quickly.
#
# That's a swell approach, but there's a better one. The prompt hints at
# this. It implies... |
e429913f8f61e9acf8791170d0d47c1b5ae569bc | amulya-devops/spark_python_course | /session_12/analyse_twiki_log.py | 2,371 | 3.671875 | 4 | import sys
import os
# Read the File
def get_lines_list (log_file):
log_lines = []
with open (log_file, 'r') as f:
for line in f.readlines():
log_lines.append(line)
return log_lines
def get_username( line ):
# line = '| 2017-01-01 - 07:54:57 | BenazirBhutto | edit | Fullgc.WebHome ... |
bf24bb8ef55a9969233357450cc435f57e2651fd | marydCodes/jetbrains_coinverter | /stage2.py | 175 | 3.53125 | 4 | conicount = int(input())
dollars = conicount * 100
print(f"I have {conicount} conicoins.")
print(f"{conicount} conicoins cost {dollars} dollars.")
print("I am rich! Yippee!") |
95ca5df62d32f9252ec9fcaef0f8ebf91c8b146d | wdwoodee/LearningPython | /ClassTest/parentAndSon.py | 966 | 3.796875 | 4 | __author__ = 'dwang'
class Person():
def __init__(self,
name = None,
age = 1,
sex = "men"):
self.name = name
self.age = age
self.sex = sex
def displayInfo(self):
print ("name:%-20s" % self.name)
print ("age:%-20d" % sel... |
f5687e8702eae22364fedad8485f3fadd1f41d81 | yyyuaaaan/python7th | /Leat/Binary Tree Level Order Traversal.py | 2,220 | 3.578125 | 4 | """
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution: 1. Use queue. In order to sepe... |
68e3da3377b4b67080f3edeaf13e79927bf4311c | yyyuaaaan/python7th | /crk/18.2h.dp.py | 2,843 | 4.09375 | 4 | """__author__ = 'anyu'
11.7 A circus is designing a tower routine consisting of people standing atop one another's shoulders.
For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her.
Given the heights and weights of each person in the circus, write a method to ... |
db5ed7697cd0c6a41d9290f1c8b7785cc892b9ec | yyyuaaaan/python7th | /Leat/Edit DistanceH.py | 1,760 | 3.5625 | 4 | """__author__ = 'anyu'
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Solution: Dynamic Programming.... |
0a9e8b7d73802491fca57d0dd1965186239b9137 | yyyuaaaan/python7th | /crk/1.6.py | 1,109 | 3.859375 | 4 | def rotatematrix(m):
"""
__author__ = 'anyu'
Given an image represented by an NxN matrix, where each pixel in
the image is 4 bytes, write a method to rotate the image by 90 degrees.
Can you do this in place?
0(N2)
#diagonal mirror
for i in range(len(m)):
for j in range(i):
m[i][j],m[j]... |
cff94325526549f4f0673cbcd0867cc4922c26d3 | yyyuaaaan/python7th | /crk/2.4.py | 2,682 | 4.03125 | 4 | """
__author__ = 'anyu'
Write code to partition a linked list around a value x,
such that all nodes less than x come before alt nodes
greater than or equal to x.
If this were an array, we would need to be careful about how
we shifted elements. Array shifts are very expensive.
However, in a linked list, the situatio... |
9902a96d8649184b27bafe7835742d13bcec0f07 | yyyuaaaan/python7th | /crk/8.4subsets.py | 1,655 | 4.25 | 4 | """__author__ = 'anyu'
9.4 Write a method to return all subsets of a set.
gives us 2" subsets.We will therefore not be able to do better than 0(2") in time or space complexity.
The subsets of {a^ a2, ..., an} are also called the powerset, P({aj, a2, ..., an}),or just P(n).
This solution will be 0(2n) in time and space,... |
f61e3cfa368cc0ed4e02d1c306b2127c8d5ade72 | yyyuaaaan/python7th | /Leat/Remove Duplicates from Sorted Array.py | 783 | 3.875 | 4 | """
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now ... |
c2ffda55f905b9d0bc11dd1cff64761490722eb0 | yyyuaaaan/python7th | /crk/4.4.py | 1,547 | 4.125 | 4 | """__author__ = 'anyu'
Implement a function to check if a tree is balanced.
For the purposes of this question, a balanced tree is defined
to be a tree such that the heights of the two subtrees of any # this is so called AVL-tree
node never differ by more than one.
"""
class Node(object):
def __init__(self):
... |
e52a2bcad9d4f52f109ef8e78a796d1126175099 | yyyuaaaan/python7th | /Leat/Generate Parentheses.py | 1,171 | 3.625 | 4 | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution: Place n left '(' and n right ')'.
Cannot place ')' if there are no enough matching '('.
*/
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.