blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
aa48d363e35894f3ff0479b8f04188f98e06c898 | sururuu/TIL | /Baekjoon_Algorithm/14496_그대,그머가 되어.py | 648 | 3.8125 | 4 | import heapq
INF = float('inf')
def dijkstra(a,b):
distance = [INF] * (n+1)
distance[a] = 0
q = []
heapq.heappush(q,[0,a])
while q:
dis,idx = heapq.heappop(q)
if idx == b:
return distance[b]
for k in graph[idx]:
if dis + 1 < distance[k]:
... |
5539d7df9d444008e030b596dc0668a513425ae5 | AlexanderOnbysh/edu | /bachelor/generators.py | 3,744 | 3.765625 | 4 | # yield and yield from difference
# yield
def bottom():
return (yield 42)
def middle():
return (yield bottom())
def top():
return (yield middle())
>> gen = top()
>> next(gen)
<generator object middle at 0x10478cb48>
# ----------------------
# yield from
# is roughly equivalent to
# ***
# for x in iter... |
f1fd2535b2414f329f57dc856b2cb89621e07b5f | terrence85561/leetcode | /python/Array/LC238_productExceptSelf.py | 1,074 | 3.65625 | 4 | def productExceptSelf(self, nums: List[int]) -> List[int]:
# imagine when looping from left to right, in a certain view, we can only know the product of the values on the left
# in order to knnow the product of values on the right from this view, just loop from right to left again
#... |
1cdf33060a02674b34fcfa37c133f44c8fceb115 | samuelluo/practice | /recursive_staircase/recursive_staircase.py | 709 | 3.6875 | 4 | def num_ways_1(N):
if N == 1: return 1 # 1 way: [1]
if N == 2: return 2 # 2 ways: [1+1, 2]
return num_ways_1(N-1) + num_ways_1(N-2) # take one step from N-1, or 2 steps from N-2
def num_ways_2(N):
if N in [0, 1]: return 1
ways = [1, 1]
for i in range(2, N+1):
ways.append(ways[i-1]... |
17c66e0b79d2b9be178fbfbb08a88b2014f0f96e | AlexandrSech/Z49-TMS | /students/Volodzko/Task_4/task_4_1.py | 499 | 4.25 | 4 | """
Дан список целых чисел.Создать новый список,
каждый элемент которого равен исходному элементу умноженному на -2
"""
# Способ 1
my_list = [2, 5, 3, 8, 7, 9]
my_list2 = list()
i = 0
while i < len(my_list):
my_list2.append(my_list[i]*(-2))
i+=1
print(my_list2)
# Способ 2
my_list3 = [2, 5, 3, 8, 7, 9]
my_list4... |
8d8f833866058a6e5a9461adf96f9c61e374af35 | hanameee/Algorithm | /Leetcode/파이썬 알고리즘 인터뷰/6_문자열조작/src/most-common-word.py | 689 | 3.515625 | 4 | from collections import Counter
def solution(paragraph, banned):
paragraph = paragraph.lower()
filtered_paragraph = ""
buf = ""
for char in paragraph:
if char.isalpha():
filtered_paragraph += char
continue
filtered_paragraph += " "
arr = list(map(lambda x: x... |
e2bc2e2be278d14ce48392a61e172b0b629476a9 | tuestudy/ipsc | /2011/A/haru.py | 527 | 3.765625 | 4 |
game_table = {
'scissors': ['Spock', 'rock'],
'paper': ['scissors', 'lizard'],
'rock': ['paper', 'Spock'],
'lizard': ['rock', 'scissors'],
'Spock': ['lizard', 'paper']
};
def main():
t = input()
result = []
for _ in range(t):
x = raw_input()
if len(result) > 0 and resu... |
fc4d16b3f454905c3773d52c059ed190f86528af | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/Functions/lab/2_calculations.py | 395 | 4.15625 | 4 | def calculation(operator, n1, n2):
if operator == 'multiply':
result = n1 * n2
elif operator == "divide":
result = n1 // n2
elif operator == "add":
result = n1 + n2
elif operator == "subtract":
result = n1 - n2
return result
command = input()
num1 = int... |
3fddd6c9c907b25ddc50b0f7ab15fee756a39e46 | ikhwan1366/Datacamp | /Data Engineer with Python Track/13. Building Data Engineering Pipelines in Python/Chapter/01. Ingesting Data/07-Communicating with an API.py | 3,921 | 4.40625 | 4 | '''
Communicating with an API
Before diving into this third lesson’s concepts, make sure you remember how URLs are constructed and how to interact with web APIs, from the prerequisite course Importing Data in Python, Part 2.
The marketing team you are collaborating with has been scraping several websites for custome... |
86087bacc41b3926b4de98e25b0f687436a54c9f | sumitvarun/pythonprograms | /inheritance baseclass.py | 210 | 3.609375 | 4 | class Rectangle():
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
|
43f5c68c8a9adfc9b590557baabc15843e390dfb | renebentes/Python4Zumbis | /Exercícios/Lista I/questao08.py | 117 | 3.875 | 4 | f = int(input('Informe a temperatura em Fahrenheit: '))
print('Temperatura em Celsius: %5.2f' % ((f - 32) * 5 / 9))
|
ec22cf8fcd82e0f0e62bb3b4c9e78af01f99a352 | enordlund/CS325 | /Homework 3/h3q4d.py | 4,362 | 3.5625 | 4 | #!/usr/bin/python
from collections import namedtuple
import numpy as np
# item type for code clarity
Item = namedtuple("Item", "weight value")
def constructItemArrayBottomUp():
# opening data file
f = open("data.txt")
# initializing empty array for items
itemArray = [Item(0,0)]
for line in f.readlines(... |
1e3298652853c8aa9aace93ffb3862e680e57041 | mmveres/pythonProject18_09_2021 | /lesson02/cycle/task_cycle.py | 465 | 3.65625 | 4 | def print_inc_value(start=0, end=100, delta=1):
i = start
while i < end:
print(i)
i = i + delta
def print_dec_value(start, end, delta):
i = start
while i >= end:
print(i)
i = i - delta
def print_power_value(x = 2,n = 10):
i = 0
xn = 1;
while i < n:
... |
5837be02bf4ec3da8e84480cf1f0abdce6dbc5b3 | NeelShah18/googletensorflow | /operation.py | 1,559 | 4.28125 | 4 | import tensorflow as tf
#Defining constant using tensorflow object
a = tf.constant(2)
b = tf.constant(3)
'''
Open tensorflow session and perform the task, Here we use "with" open the tensorflow because with will close the session automatically so we dont need to remember to close
each sessiona fter starting it. We c... |
4ebcd7c1b2489942f7c533b821ce7654d09163ff | Natebeta/Tannenbaum | /Tannenbaum.py | 795 | 3.53125 | 4 | # Autor: Aman
# Tannenbaum
#Version 1
#Variablen
l = int(input("Eingabe: "))
sterne = "**"
stern = "*"
sterne_anzahl = 0
loop = 0
out = "*"
var1 = l
FILLER1 = ""
FILLER = ' '
def stamm():
var2 = l//4
countFILLER = len(FILLER1)
for loop in range(0, var2):
print(str(... |
9b74583fc3edbc72b8cf0ab7fab9000626a3d6c3 | oneMoreTime1357/selfteaching-python-camp | /19100101/Shawn/mymodule/stats_word.py | 1,001 | 3.578125 | 4 | #d9 excercise
import collections
import re
#英文字频统计
def stats_text_en(text_en,count):
if type(text_en) == str:
entext = re.sub("[^A-Za-z]", " ", text_en.strip())
enList = entext.split()
return collections.Counter(enList).most_common(count)
else:
... |
271694984dbdf95ef138b363e511e06405505618 | Raragyay/Snake | /snake/solver/path.py | 8,473 | 3.734375 | 4 | # coding=utf-8
"""
Definitions for PathSolver class, which is the path-finder for Greedy and Hamilton..
Exported methods in PathSolver are longest path to tail and shortest path to food.
"""
import random
import sys
from collections import deque
from snake.map import PointType, Direc
from snake.solver.base import Base... |
de9562fe2357209d34bcec2a78619162b6f146c7 | songaiwen/information_29_01 | /7.爬虫/day3/4.re方法2.py | 567 | 3.609375 | 4 | """
正则表达式:
"""
import re
if __name__ == '__main__':
str_one = 'abc123'
str_two = '456'
pattern = re.compile('^\d+$')
# 1.match 从头开始 匹配一次
result = pattern.match(str_one)
print(result)
# 2.search 从任意位置
result = pattern.search(str_one)
print(result)
#3.findall 返回list
str_t... |
71d43d633f889b07ecb97317cef581abbba59273 | xizhang77/LeetCode | /Math/357-count-numbers-with-unique-digits.py | 642 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
excluding 11,22,33,44,55,66,77,88,99
'''
class Solution(object):
de... |
8a7f5a0c4362f69e5289170081277f6d0433f8e3 | dcheung15/Python | /ecs102/Hw/KGtoPound.py | 929 | 3.625 | 4 | #Doung Lan Cheung
#KGtoPound.py
#kilograms to pounds
from graphics import *
def main():
win=GraphWin("Kilograms to Pounds Converter",400,600)
win.setBackground("light blue")
win.setCoords(0,0,4,6)
#make fake button for conversion
button=Rectangle(Point(1,1.5),Point(3,.5))
button.setFill("g... |
ac63da86a9d8fe6a81ecc0e70a5d1240c425acae | suecharo/ToudaiInshi | /2014_summer/question_3.py | 341 | 3.859375 | 4 | # coding: utf-8
import math
def question_3():
ans = 0
s_0 = 25 * math.sqrt(3)
for i in range(3):
if i == 0:
ans += s_0
else:
tri_num = 3 * (4 ** (i - 1))
s_i = s_0 * ((1 / 9) ** i)
ans += s_i * tri_num
print(ans)
if __name__ == "__main_... |
480259fdfe4386648ebd370f07554924b7afeb50 | vkumar62/practice | /leetcode/229_majority_element.py | 762 | 3.734375 | 4 | from collections import defaultdict
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
counts = defaultdict(int)
for n in nums:
counts[n] += 1
if len(counts) == 3:
for c in ... |
24d0475a05be00049fa4d88053b4398307a94281 | josepmg/trabalhoRedes1 | /model/tabuleiro.py | 3,582 | 3.65625 | 4 | import random
import sys
from main.utils import Utils
class Tabuleiro:
#construtor da classe Tabuleiro que ja cria um tabuleiro novo
def __init__(self, dim):
#dimensoes do tabuleiro
self.dimension = dim
#numero de pecas
self.nPieces = dim**2
# numero de pares
sel... |
8379ebe3e66656e4b7e0484543ba4af27ef7f559 | LiangZZZ123/algorithm_python | /2/02_linked_list.py | 876 | 3.890625 | 4 | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __repr__(self):
return '<Node: value: {}, next={}>'.format(self.value, self.next)
class LinkedList():
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.r... |
702f77c704b9bbef0168fa956aa906d2a017472c | solareenlo/python_practice | /03_制御フローとコード構造/none.py | 763 | 4.15625 | 4 | """This is a test program."""
is_empty: object = None
print(is_empty) # None と表示
if is_empty == None:
print('None!') # None! と表示
if is_empty is None:
print('None!') # None! と表示
if is_empty is not None:
print('None!') # 何も表示されない
print(1 == True) # True と表示 objectとしてTrueかどうかを判定
print(1 is True) # False と表示 ... |
7f544e07dc56f4ee89de2d780cf029d5846b2f0c | arthurPignet/privacy-preserving-titanic-challenge | /src/features/build_features.py | 3,766 | 3.65625 | 4 | import logging
import pandas as pd
from sklearn.preprocessing import LabelEncoder
DATA_PATH = "../../data/raw/"
WRITE_PATH = "../../data/processed/"
def data_import(path=DATA_PATH):
""""
This function import the raw data from .csv files to pandas. It aims for 2 files, named train.csv and test.csv
Para... |
9aa6a675e4cf57571729a07154a7124ca4489734 | zhangambit/486finalproject | /commentCompile.py | 3,390 | 3.6875 | 4 | import json
import os
""" This module defines methods and a class to take a Reddit archive and create a representation of who replied to whom."""
class Person:
def __init__(self, ID):
self.ID = ID
self.replies = dict() # The number of replies & to whom this person has made.
self.parents... |
74a78ec1bd536ca71138ef203d2cb244b4ff5ee4 | abhishekreddy1206/spoj | /nextpali.py | 904 | 3.53125 | 4 | output = []
cases = input()
def next_higher(K):
if all(digit == '9' for digit in K):
return int(K) + 2
L = len(K)
left = K[:L/2]
center = L % 2 and K[L/2] or ""
right = left[::-1]
P = left + center + right
if P > K:
return P
if center and center != '9':
center = ... |
b0c65894f67a4ee168f84e472fd3f8bf1afe0ad7 | Wormandrade/Trabajo02 | /eje_p1_06.py | 448 | 4.28125 | 4 | #Utilizando la función range() y la conversión a listas genera las siguientes listas dinámicamente:
print("========================")
print("\tEJERCICIO 06")
print("========================")
print("\nListas dinamicas\n")
def listas(inicio, fin, salto):
num_lista = []
for num in range(inicio, fin+1,salto):
... |
24e028b3eb783c36f9f165d13dc5dcb2f69fe80a | kubos777/cursoSemestralPython | /Tareas/SolucionesTarea3/tarea3P5.py | 391 | 4.46875 | 4 | #################################################################################################
# Tarea 3 , Problema 1
# Escriba un programa de Python que acepta una palabra del usuario y la invierte.
#################################################################################################
palabra=input("Es... |
1f8544b2fb33c90483c87d84492e9493abca7281 | WilliamSampaio/ExerciciosPython | /exerc26/26.py | 235 | 4.03125 | 4 | import os
num1 = float(input('digite o numero 1: '))
num2 = float(input('digite o numero 2: '))
num3 = float(input('digite o numero 3: '))
num=[num1,num2,num3]
print(*sorted(num,reverse=True), sep=', ')
os.system('pause') |
6b3c8e282e6881deab73a5912304c843df4f1558 | jorgemauricio/INIFAP_Course | /ejercicios/ej_26_groupDataFrames.py | 1,412 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
"""
# librerias
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
# crear un dataframe
dframe = DataFrame({'k1':['X','X','Y','Y','Z'],
'k2':['alpha','beta','alph... |
b900505abbd54b33687bd1af9c58d8e00443d541 | chintu0019/DCU-CA146-2021 | /CA146-test/markers/line-plot.py/line-plot.py | 1,218 | 4.09375 | 4 | #!/usr/bin/env python
import sys
n = 20
x1 = float(sys.argv[1])
y1 = float(sys.argv[2])
x2 = float(sys.argv[3])
y2 = float(sys.argv[4])
m = (y2 - y1) / (x2 - x1)
c = y1 - m * x1
def should_plot(x, y):
if x < x1 and x < x2: # Too far left.
return False
if x1 < x and x2 < x: # Too far right.
retur... |
175d4fa4a648aa25846e0deb97033d1d7aac617a | MHM18/hm18 | /hmpro/zhangxiyang/homework/greatestcommondivisor.py | 367 | 3.953125 | 4 | a = input("输入第一个数字")
b = input("输入第二个数字")
a = int(a)
b = int(b)
def greatestcommondivisor(a, b):
if a > b:
smaller = b
else:
smaller = a
for i in range(1,smaller+1):
if((a % i == 0) and (b % i == 0)):
greatestcommondivisor = i
return greatestcommondivisor
print(greatestc... |
1e930f51d398c6692fe6fa8f3a8cb45695e3e274 | EOT123/AllEOT123Projects | /All Python Files Directory/Year2Tutorials/2018_08_21_screen_events001.py | 633 | 3.625 | 4 | import turtle # imports the turtle library
import random # imports the rankdom library
scr = turtle.Screen() # goes into turtle library and calls screen function
trt = turtle.Turtle() # creates turtle
def little_draw():
scr.tracer(10, 0)
myx = random.randrange(-360, 360)
myy = random.randrange(-360, ... |
4596c63bccd721402e76b45a41eeb9622803bc51 | sodaWar/MyPythonProject | /PycharmProjects/testPython/test_transmit_data.py | 822 | 3.78125 | 4 | # -*- coding:utf-8 -*-
a = 1
def changeInteger(a):
a = a+1
return a
print(changeInteger(a))
print(a)
b = [1,2,3]
def changeList(b):
b[1] = b[1] + 1
return b
print(changeList(b))
print(b)
# 第一个函数传的变量是整数变量,函数对变量进行操作,但是不会影响原来的变量,因为
# 对于基本数据类型的变量,变量传递给函数后,函数会在内存中复制一个新的变量,从而不影响原来的变量。(我们称此为值传递)
# 第二个函数传的变量是表,函数对表进行... |
8ab2cd8ddbc86f6b1d5e1b261d69c6e82c5fab13 | panthercoding/Summer_Lecture6 | /flatEarth.py | 1,843 | 4.21875 | 4 | import numpy as np
""" helper function to calculate arc cosine given radians """
def arccosine(theta):
return np.arccos(theta)
class Point3D():
def __init__(self,x,y,z):
""" delete the below and finish the constructor method """
pass
def EuclideanDistance(self,other):
""" calculate the Euclidean ... |
9225c73be056d7922353e44c38e64011be1e02e2 | MaryamNajafian/Tea_TF2.0 | /rnn_shapes.py | 2,701 | 3.625 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input, Dense, Flatten, SimpleRNN
from tensorflow.keras.optimizers import SGD, Adam
from tensorflow.keras.models import Model
"""
RNN for Time series prediction:
It did not perform as autoregressive linear mod... |
fcadee1c22eb8f77971a8c35320976f142918e2a | LiXiang02140105/Python_code | /8_returnfunc_bibao.py | 1,075 | 3.84375 | 4 | '''
返回函数
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
闭包的知识
也就是直接早
实际上,是因为在Python中,函数名 f 只是一个变量,相当于C中的指针,指向的是函数 f() 的存储位置
而,之后通过 是使用 f 还是 f()来知道是得到函数的地址还是函数计算之后的值
strip()
'''
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
print("f : ",f,f())
fs.append(f)
... |
c61b9df745407de1b3dd840e5aac9d32aa71cd06 | anishverma2/MyLearning | /MyLearning/Files/json_imports.py | 852 | 4.28125 | 4 | import json
'''
json data is very much like a dictionary
the json library help us to convert the json data to a dictionary easily
'''
file = open('friends_json.txt', 'r')
file_contents = json.load(file) #read files and turns it to a dictionary
file.close()
print(file_contents)
print(file_contents['friends'][0])... |
544a636c28ce4f336313bfb80a95c2a66000d472 | freekdh/advent-of-code-2020 | /advent_of_code_2020/day9/solve.py | 1,704 | 3.828125 | 4 | import re
from itertools import combinations
def get_input_data(path_to_input_data):
with open(path_to_input_data) as input_file:
return list(map(int, input_file.read().splitlines()))
def is_the_sum_of_two_of_the_n_numbers(focal_number, n_numbers):
return any(
number1 + number2 == focal_numb... |
20249785b5439cba743d03f3c34f89b480bce47b | egorkravchenko13/python_homework | /Lab1/1.py | 788 | 3.734375 | 4 | import re
re_integer = re.compile("^\d*$")
def validator_1(pattern, promt):
a_value = input(promt)
while not bool(pattern.match(a_value)):
a_value = input(promt)
return a_value
def validator_2(prompt):
number = float(validator_1(re_integer, prompt))
return number
import math
num1 = vali... |
116a700351d64f09dceb06c125cf969c806ea72d | KARABERNOUmohamedislem/First-Python-experience | /printing.py | 78 | 3.625 | 4 | print ("winter is coming")
age=input("hhfisod ")
age=int(age)*4
print (age) |
df27b442a9ecdfcb57a57ddf0341382743baad83 | iFission/Linear-Algebra | /rref.py | 1,616 | 4 | 4 | # finds the rref form of a matrix
from pprint import pprint # to print matrix row by row
# initialise a mxn matrix with 0s
def initialise(m,n):
zero_matrix = [[0 for x in range(n)] for y in range(m)]
return zero_matrix
def assign_matrix(matrix): # len(matrix) = row, len(matrix[0])= column
for x in range(len(m... |
de4e74ee1086c2afd01139bd6976e6163d4556f7 | salvadb23/SPD1.2 | /superheroes.py | 4,704 | 3.765625 | 4 | class Hero:
def __init__(self, name, starting_health=100):
self.name = name
self.starting_health = starting_health
self.current_health = starting_health
self.abilities = list()
self.armors = list()
self.deaths = 0
self.kills = 0
... |
1a76675c23c150918b8657926d3ef00af9483e2b | daem-uni/dagdim-lab-informatica | /lab3/e3.py | 522 | 4.21875 | 4 | s = input("Inserire una stringa: ")
if s.isalpha():
print("La stringa contiene solo lettere.")
if s.isupper():
print("La stringa contiene solo lettere maiuscole.")
if s.islower():
print("La stringa contiene solo lettere minuscole.")
if s.isdigit():
print("La stringa contiene solo numeri.")
if s.isalnum... |
2ac30b1f7b133b60482faba41b5cb69529872515 | suhassrivats/Data-Structures-And-Algorithms-Implementation | /Problems/Leetcode/733_FloodFill.py | 1,764 | 3.703125 | 4 | class Solution:
def floodFill(self, image: List[List[int]], sr: int,
sc: int, newColor: int) -> List[List[int]]:
"""
Time Complexity:
=> O(M x N) // length of (rows * col) (OR)
=> O(n) // n is the number of pixels in the image
Space Complexity:
... |
8be81da05fb147528a6829c154b8e3e078b2cf3b | paranoidandryd/pyyyy | /ex14.py | 795 | 3.78125 | 4 | from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s! So good to see you." % user_name
print "How are you doing, %s? Are you doing well or poorly?" % user_name
status = raw_input(prompt)
if(status == "well"):
print "I'm so glad to hear that %s." % user_name
elif(status == "poorly"):
print "I'm... |
a2ac5c856a1a5661a1d61202f4aa3140197e48cf | betaBison/learn-to-care | /covid.py | 2,568 | 3.9375 | 4 | ########################################################################
# Author(s): D. Knowles
# Date: 26 Jul 2021
# Desc: working with COVID-19 dataset
########################################################################
# import python modules that will be used in the code
import pandas as p... |
8c3009e149d0786bc1c690185c23229df1bde0ad | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4058/codes/1602_842.py | 121 | 3.765625 | 4 | a=int(input("Digite um numero:"))
b=a//1000
b1= a%1000
c=b1//100
c1=b1%100
d=c1//10
d1=c1%10
e=d1//1
x=b+c+d+e
print(x)
|
9b7d6db0790265c9987c27de5693fd51ce57353c | ShramanJain/Computer-Society | /Basic/Check if A String is Palindrome or Not/SolutionByShraman.py | 188 | 3.609375 | 4 | def palin(str):
l = len(str)
n = int(l/2)
for i in range(1, n):
if str[i] != str[l - i - 1]:
return 'No'
return 'Yes'
str = input()
print(palin(str))
|
c96d84ed695de83fa9c4ce7bf9b41789ef335499 | joshualan/Notes | /python_notes/modules.py | 2,456 | 3.703125 | 4 | # Modules are one of the best and most natural ways to structure your code.
# They are an abstraction layer, which means we can separate code into parts
# that have related functionality or data. They're pretty easy to grasp, which
# means that it's also really easy to screw up.
# Here's some things that we should ... |
6a0e5c1b2d83ec7a9691f601d9d792231254b1cd | jadeliu/interview_prep | /epi4.11_zip_single_list.py | 1,139 | 3.84375 | 4 | __author__ = 'qiong'
# epi 4.11
# start time 8:55 pm
# initial trial end time 10:15 pm
# initial trial time complexity O(n^2)
# space complexity O(1)? recursive O(n)?
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def zip_list(head):
if not head:
return None
... |
2b649ae8084d2266f8d55f18ec1b8aba0b58c303 | ccsreenidhin/Practice_Anand_Python_Problems | /Learning_python_AnandPython/Module/problem7.py | 564 | 4.09375 | 4 | #Problem 7: Write a function make_slug that takes a name converts it into a slug. A slug is a string where spaces and special characters are replaced by a hyphen, typically used to create blog post URL from post title. It should also make sure there are no more than one hyphen in any place and there are no hyphens at t... |
06861a40e95ba77314c85f9b11fc66af889b41e4 | vijaymaddukuri/python_repo | /training/time_conversion.py | 413 | 3.84375 | 4 | def timeConversion(time):
if time[-2:] == "AM" and int(time[0:2]) < 12:
convTime = time[:-2]
elif time[-2:] == "AM" and int(time[0:2])==12:
convTime = '00' + time[2:8]
elif time[-2:] == "PM" and int(time[0:2])==12:
convTime = time[:-2]
else:
convTime = str(int(time[:2]) +... |
3cf083705d272ace6fa7e53109253cccb1170761 | ineed-coffee/PS_source_code | /LeetCode/17. Letter Combinations of a Phone Number(Medium).py | 713 | 3.53125 | 4 | class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dig2ch = {
"2":["a","b","c"],
"3":["d","e","f"],
"4":["g","h","i"],
"5":["j","k","l"],
"6":["m","n","o"],
"7":["p","q","r","s"],
"8":["t","u","v"],
... |
06193a95d64778b5d61cb5a48d57898fb86f190e | rimzimt/Trees-2 | /44_post_inorder.py | 1,290 | 3.828125 | 4 | # S30 Big N Problem #44 {Medium}
# LC pproblem - 106
# Recursive approach
# Construct Binary Tree from Inorder and Postorder Traversal
# Time Complexity : O(nlogn) n=no. of nodes in the tree
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
... |
7d59f1e6e06f9ef56d9a917db3612624ccd00693 | valvesss/ratata-crypto | /ratata.py | 2,247 | 3.8125 | 4 | class Ratata(object):
def __init__(self, desc, owner, amount):
self.desc = desc
self.owner = owner
self.amount = amount
self.payers = []
print("#1 Ratata created. Owner: {0} | Description: {1} | Amount: $ {2}".format(owner.name,desc,amount))
def assignLeader(self, leader... |
2726ac64e3386ff62ce007e8ddda3dcf82fc947f | phamhung3589/LearnPython | /sorting/insertion_sort.py | 391 | 4.25 | 4 | def insertion(arr):
n = len(arr)
for i in range(1, n):
tmp = arr[i]
j = i-1
while j >= 0 and arr[j] > tmp:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = tmp
if __name__ == "__main__":
arr = [4, 3, 2, 10, 12, 1, 5, 6]
print("the array before sorting: \n",... |
9c6dde5286c9d240ed926332c7c9fcca796128ad | Alexanderklau/Algorithm | /Everyday_alg/2021/01/2021_01_11/find-minimum-in-rotated-sorted-array-ii.py | 630 | 3.640625 | 4 | # coding: utf-8
__author__ = 'Yemilice_lau'
"""
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
注意数组中可能存在重复的元素。
示例 1:
输入: [1,3,5]
输出: 1
示例 2:
输入: [2,2,2,0,1]
输出: 0
"""
nums = [1,3,5]
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
... |
8cf765d877bb5d7655550639418a963529c87340 | romf90/python-3-tasks | /python task1.py | 435 | 3.6875 | 4 | import numpy as np
def task1():
print ("Task 1:")
a=np.array([[2,2],[1,1],[3,2]])
b=np.array([[1,2,2],[2,1,2]])
c=np.zeros((a.shape[0],b.shape[1]), dtype=int)
size=c.shape
for row in range(size[0]):
for column in range(size[1]):
for mul in range(a.shape[1]):
... |
f7e4bad89403e4012e198214f81daa8a0a6c646a | Farhad16/Python | /Data Structure/List/zip.py | 268 | 4.25 | 4 | list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
# combine a list into a one list with a single tuple
x = list(zip(list1, list2))
print(x)
# zip can also add single character with the list as it takes a string which is iterable
y = list(zip("abcd", list1, list2))
print(y)
|
f71bed373178d0353a97ee6ce54b494798732369 | youngkey89/MDASO1 | /HW3/HW3A1.py | 2,077 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Define function
def f(x):
return np.exp(x)
x0 = 1
h_value = np.logspace(-15, 1, 17)
# Analytical Result
def df1_ana(x):
"first derivative"
return np.exp(x)
def df2_ana(x):
"second derivative"
return np.exp(x)
def df1_ff(x... |
ac304ad1ae256b1e3ba1de3fc2ac672cedde5e32 | Samothrace-Shaddam/expense_tracker | /help_page.py | 920 | 3.59375 | 4 | '''
Contains help files for the program, if you're looking for the README,
go to the README.
'''
def main_help():
help_text = '''
Press the keys shown on the menu and hit enter to control different parts
of the program. Selections are not case sensitive. (Entering 'E' or 'e'
will both take you to the Enter menu.)
... |
5a9a74cb5f1e05caa878d0e2ceef29aee20af5f7 | devitasari/intro-python | /string.py | 729 | 4.09375 | 4 | #Let's Form a Sentence
word = "JavaScript"
second = "is"
third = "awesome"
fourth = "and"
fifth = "I"
sixth = "love"
seventh = "it!"
print word,second,third,fourth,fifth,sixth,seventh
#Index Accessing -1 by 1
word = 'wow JavaScript is so cool'
exampleFirstWord = word[0:3]
secondWord = word[4:14]
thirdWord = word[15:... |
0b0c3359f60549ce08245d9f9131a1917b6573d0 | Bigpig4396/Multi-Agent-Reinforcement-Learning-Environment | /env_Rescue/Python2/maze.py | 15,084 | 3.78125 | 4 | #! /usr/bin/env python3
'''
Random Maze Generator
Makes use of a radomized version of Kruskal's Minimum Spanning Tree (MST)
algorithm to generate a randomized mazes!
@author: Paul Miller (github.com/138paulmiller)
'''
import numpy as np
import os, sys, random, time, threading
# defined in disjointSet.py
import disjo... |
473d274ac4afc18690d37c1a01402a284305fe4d | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/M_Sunday/lesson08/circle.py | 2,110 | 3.875 | 4 | #!/usr/bin/python
from math import pi
class Circle(object):
@staticmethod
def entry_check(the__radius):
if isinstance(the__radius, (str, list, tuple, dict)):
raise TypeError("Radius/Diameter entry must be a single, positive, and "
"non-string value")
el... |
04eeedfceeeac5d24380d683751509b495df5109 | TorpidCoder/Python | /PythonCourse/DataStructure/stacksBasics.py | 682 | 3.875 | 4 | __author__ = "ResearchInMotion"
class Stacks:
def __init__(self):
self.stack =[]
# pushing the element
def push(self,data):
return self.stack.insert(0,data)
# check if emepty
def isempty(self):
return self.stack == []
# pop the data
def pop(self):
if ... |
b71992fd3ffdc65a812bd5f440e01efc36602706 | v-profits/python_lessons | /1.9.py | 627 | 3.875 | 4 | s = 'C:\d\new'
print(s)
s = 'C:\d\\new'
print(s)
s = r'C:\d\new'
print(s)
s = 'Ry''thon'
print(s)
s = 'Ry'+'thon'
print(s)
s1 = 'Hello, '
s2 = 'world!'
s = s1 + s2
print(s)
name = 'John'
age = 20
print('My name is ' + name + " I'm " + str(age))
print("hi "*5)
s = 'Hello world!'
print(s[0]) # H
print(s[-1]) # ... |
b4ec35a2c62bbdb036cff0e06bd29714cf3d8a9b | josesandino/Python-con-JS-2021-Polotic-Misiones | /Clase 3/Ejercicios/ejercicio2.py | 300 | 4 | 4 | #Escribe un programa Python que acepte 5 números decimales del usuario.
a = float(input("Escribe un número: "))
b = float(input("Escribe un número: "))
c = float(input("Escribe un número: "))
d = float(input("Escribe un número: "))
e = float(input("Escribe un número: "))
print(a, b, c, d, e) |
44a0a8c90a6ac14b092ff4c946e4c663beb87d46 | alulec/CYPAlexisCC | /libro/programa1_10.py | 259 | 3.734375 | 4 | # programa que calcula la base y superficie de un rectangulo
bas= int(input("cuanto mide la base: "))
alt= int(input("cuanto mide la altura: "))
sup= alt * bas
per= (2* alt) + (2* bas)
print("la superficies es de {} y su perimetro es de {}".format(sup,per))
|
e9ce77c99c7f142632513b50f8b9467c22f3dd14 | Dyndyn/python | /lab12.1.py | 1,646 | 4 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import math
class Point:
def __new__(cls, x=0, y=0):
inst = object.__new__(Point)
inst.x = x
inst.y = y
return inst
def __str__(self) -> str:
return "Point(x = {}, y = {})".format(self.x, self.y)
def diff_length(self, point... |
aaf4f8e342468f48551fe8b86d404c0f0fa7bccd | mayartmal/puche | /range_loop.py | 181 | 3.8125 | 4 | friends = ['kot', 'bot', 'mot']
congrats = 'Happy NY, '
for friend in friends:
print(congrats + friend)
print()
for i in range(len(friends)):
print(congrats + friends[i])
|
55c6739feb85462395d553cddb44a43304143cd2 | shreyasabharwal/Data-Structures-and-Algorithms | /Sorting/10.3SearchInRotatedArray.py | 1,870 | 4.1875 | 4 | '''10.3 Search in Rotated Array: Given a sorted array of n integers that has been rotated an unknown
number of times, write code to find an element in the array. You may assume that the array was
originally sorted in increasing order.
EXAMPLE
Input: find 5 in [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]
Output: 8 (the i... |
c681600100cb54002bc05b4aeac6fadc6258197f | lxyshuai/leetcode | /82. Remove Duplicates from Sorted List II.py | 1,052 | 3.78125 | 4 | """
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init_... |
9f1eae7fa7ca133c710468cd572b1c5252489824 | palenic/Automata | /my_fsa.py | 8,318 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""Finite state automata
Provides the Fsa class to configure and run finite state automata (FSA)
and a parser function to parse .txt files into a Fsa object.
"""
class Fsa:
"""
Create and use a finite state automata object.
Attributes
----------
states : list of string... |
e4522cf8b50b4061e52798a4114df4e39896a8bb | chuckinator0/Projects | /scripts/BST_value.py | 2,715 | 4.125 | 4 | '''
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
For example,
Given the tree:
4
/ \
2 7
/ \
... |
b2e73437f39016dde1abbe8e3a1beb2ecb18a1e7 | SerhiiD/sudoku | /sudoku.py | 5,998 | 3.765625 | 4 | import random
class Board:
def __init__(self, size):
self.__size = size
self.__backstep_count = 0
self.__pointer = [0, 0]
self.__board = []
for rowi in range(self.__size ** 2):
self.__board.append([])
for columni in range(self.__size ** 2):
... |
7e189e936e27cf000597125a7eec80284f27f949 | EllyChanYiLing/github | /password entry.py | 233 | 3.984375 | 4 | password = 'a123456'
i = 3
while True:
pwd = input('Please input password:')
if pwd == password:
print('Correct Assess!')
break
else:
i = i - 1
print('Wrong Password! You still have ', i, 'chances')
if i ==0:
break |
72ab5f3c18b55166d12c235791d046b7b8b490a8 | doudou1234/MachineLearningAlgorithm | /python/Clustering/KMeansClustering.py | 6,506 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2017-02-13 09:03:42
# @Last Modified by: WuLC
# @Last Modified time: 2017-02-15 20:54:58
# Clustering with KMeans algorithm
import random
from math import sqrt
from PIL import Image,ImageDraw
from GetData import read_data
def pearson(v1,v2):
"""use pearson co... |
5683495e9a591b9701b392d2a701c40a738c79e4 | asavpatel92/algorithms | /sorting/MergeSort.py | 1,879 | 3.890625 | 4 | #===============================================================================
# implementation of mergesort
#===============================================================================
from math import floor
import random
#===============================================================================
# Takes i... |
301a042f0f35cc7c0561027a66fca5e7b71624b7 | asmitrofanov74/Final-python-project-with-GUI | /Database.py | 2,273 | 3.5 | 4 | import sqlite3
from tkinter.messagebox import _show
def submit(*get_data):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
c.execute("""INSERT INTO Users (User_name , Password , First_name , Last_name , Age , Address, City , Gender )
VALUES(?,?,?,?,?,?,?,?);""",
*g... |
bd551b1735ba0376dcd71a0b4f1413835c93c8b1 | ElleSowulewski/CIT228 | /Chapter10/learning_python.py | 537 | 4.0625 | 4 | filename = "Chapter10/learning_python.txt"
with open(filename) as textFile:
myText = textFile.read()
# From read()
print(myText)
# From for loop
with open(filename) as textFile:
for line in textFile:
print(line)
# From readlines() as list
with open(filename) as textFile:
myText = ... |
728911b303a41e4d0ef3f56ae47c954fbee40c34 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/CCSt130/lesson01/front_back.py | 688 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 2019
@author: Chuck Stevens :: CCSt130
"""
test_string = "Watermelon"
def front_back(str):
# Find length of the string and assign it to a variable
index = (len(test_string)-1)
print("\nWe're going to swap the first and last characters of our str... |
3ec8dba014d8ef19ec057a7855168eaf233bf5f3 | learnMyHobby/func-dict-while-for-python | /for/pattern.py | 344 | 3.984375 | 4 |
# F
# F F F
# F F F F F
# F F F F F F
# F F F F F F F F F
# F F F F F F F F F F F
current = "f"
stop = 2
rows = 6 # Number of rows to print numbers
for i in range(rows):
for j in range(1, stop):
print(current , end=' ')
p... |
cbbf8a818af7b40a6219fe7c451f626bcb45b086 | aluisq/Python | /estrutura_repeticao/ex7.py | 143 | 3.953125 | 4 | x = 1
soma = 0
while x <= 10:
y = abs(float(input("Digite um número: ")))
soma += y # soma = soma + y
x += 1
print((soma / 10))
|
26e9a4bae35ef522d8bdcc84244a5d4f2a0b8d43 | rczwisler/wispChallenge | /wisp_api/special_math.py | 2,218 | 3.921875 | 4 | '''
Module to computer special math:
f(n) = n + f(n-1) + f(n-2)
and provide a Blueprint for a Flask app with endpoint(s):
/specialMath/<int>
Functions:
special_math_get(str)
special_math_memoize(int)
special_math_iterative(int)
'''
from flask import Blueprint
bp = Blueprint("specialMath", __name__... |
1c23baa3d4f2bc44e50c5ce1afbefc5dfa90e5e5 | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 3/Exercicio 3a/Algoritmo130_se41.py | 338 | 3.8125 | 4 | # Programa: Algoritmo130_se41.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 25/03/2020 - 12:06
# Updated:
value = float(input("Enter with the value: "))
if value > 0:
if value<=20:
tax = 45
else:
tax = 30
else:
tax = 0
print("What fuck is this?!")
discount = value + ((va... |
773f3b389a7163d46c81503d44a8be6d530cc346 | betty29/code-1 | /recipes/Python/65445_Decorate_output_stream_printlike/recipe-65445.py | 801 | 3.953125 | 4 | class PrintDecorator:
"""Add print-like methods to any file-like object."""
def __init__(self, stream):
"""Store away the stream for later use."""
self.stream = stream
def Print(self, *args, **kw):
""" Print all arguments as strings, separated by spaces.
Take an option... |
ad788169bd7cc707689f188dfd852f720ce4cf90 | Hrishikesh-3459/leetCode | /prob_20_0.py | 311 | 3.6875 | 4 | def isValid(s):
x = []
ope = ['{', '(', '[']
clos = ['}', ')', ']']
if(s[-1] in ope):
return(False)
if(len(s) == 0):
return(True)
for i in s:
if(i in ope):
x.append(i)
# diff = list(set(s)^set(x))
# print(diff)
print(x)
isValid("()[]")
|
be37c8273bdbe38abf2738a8a9cba388af53ba3d | T0biasLJ/Mis_practicas | /math_clases.py | 1,960 | 4.03125 | 4 | import math
class Operacion:
def __init__(self,numero):
self.__numero=numero
def floor(self):
a=math.floor(self.__numero)
return f"{a}"
def ceil(self):
b=math.ceil(self.__numero)
return f"{b}"
def raiz(self):
c=math.sqrt(self.__numero)
... |
4c42580f825c09327c011acd3d555194fe9ac632 | Freshield/LEARNING_PYTHON | /30_chp7_3_filter.py | 757 | 3.609375 | 4 | #30/123
def is_odd(n):
return n%2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10])))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty,['a','','b',None,'c',''])))
def _odd_iter():
n = 1
while True:
n = n+ 1
yield n
def _not_divisible(n):
... |
7a6e896703416bd81019052c229852022840f356 | Enigmamemory/submissions | /7/intro-proj1/jstrauss_lakabas/original_files/analysis01.py | 4,821 | 3.640625 | 4 | #!/usr/bin/python
print "Content-Type: text/html\n"
heading = "Justin Strauss and James Xu (Team Dream) <br>"
heading += "IntroCS2 pd 6 <br>"
heading += "HW26 <br>"
heading += "2013-04-22"
intro = "<h3> Background: </h3>"
intro += "We chose basketball because the playoffs of the NBA just started. <br>"
intro += "We t... |
78eac952952cf186c3a2416109e325642e653006 | hengdii/practice | /src/main/python/excelBatchInsert.py | 2,366 | 3.515625 | 4 | import pymysql
import xlrd
'''
连接数据库
args:db_name(数据库名称)
returns:db
'''
def mysql_link(de_name):
try:
db = pymysql.connect("localhost",
"root",
"1q2w3e4r",
de_name)
return db
except:
pr... |
296dd75cbc77a834515929bc0820794909fb9e54 | sdaless/pyfiles | /CSI127/shift_left.py | 414 | 4.3125 | 4 | #Name: Sara D'Alessandro
#Date: September 12, 2018
#This program prompts the user to enter a word and then prints the word with each letter shifted left by 1.
word = input("Enter a lowercase word: ")
codedWord = ""
for ch in word:
offset = ord(ch) - ord('a') - 1
wrap = offset % 26
newChar = chr(ord('a... |
efbbca18d032dde58d8b9e14c1003628c7babeee | roidelapluie/hiera-sorter | /hiera_sorter.py | 658 | 3.5 | 4 | #!/usr/bin/python
import sys
import os.path
# Check if at least one argument is passed
if len(sys.argv) <= 1:
print "File argument needed";
sys.exit(0);
# Loop over arguments ignoring first one (is filename of script)
for arg in sys.argv[1:]:
# Check if file passed actually exists
if not os.path.isfile(arg):
p... |
16870618af92301f5d494b836c65dc148005ab0e | ozbek94/blackjackoyunu | /KaraAlperen/2KaraAlperen1.py | 2,963 | 3.6875 | 4 | import random
kartlar = [2,3,4,5,6,7,8,9,10,11]
bakiye = 100
print("---------------------------------------")
print (" ***KARA ALPEREN***")
print("---------------------------------------")
print("\n")
while True:
acik_Kart = random.choices(kartlar, k=2)
rakip_Kart = random.choices(kartlar, k=2)
... |
231e2d77328f66cd8e68d1f6b214a80b98d7d0af | eschenfeldt/h1b_data_processing | /src/input_format.py | 3,299 | 3.734375 | 4 | """
Generate and store information about the structure of an input file, primarily
the locations of columns of interest.
"""
import re
class InputError(Exception):
pass
class Concept:
"""Constants representing the types of data we need for this problem."""
STATUS = 'status'
WORK_STATE = 'state'
... |
f1270d64cfc5d3fd60f802dd3718654f4a0bf201 | HinataHinata/SimpleTensorflow | /Slides/slides_01.py | 1,972 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
' simple tensorflow demo '
__author__ = 'zhuchao'
import tensorflow as tf
# first tensorflow program
hello = tf.constant('Hello,Tensorflow')
sess = tf.Session()
result = sess.run(hello)
print(result) # result b'Hello,Tensorflow'
print(result.decode('utf-8')) # Hello,Te... |
11ec986377e6f971c4128759dc06874ef6c22d04 | Mplaban/MNIST-Train | /main.py | 2,878 | 3.78125 | 4 |
# Homecoming (eYRC-2018): Task 1A
# Build a Fully Connected 2-Layer Neural Network to Classify Digits
# NOTE: You can only use Tensor API of PyTorch
from nnet import model
# TODO: import torch and torchvision libraries
# We will use torchvision's transforms and datasets
import torch
import torchvision
from torchvi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.