blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b14f4607f923fcd1312648be297af45033a4394c | siowyisheng/python-problem-solving | /unsolved/maximum_weight_path.py | 542 | 3.859375 | 4 | You are given an array of arrays of integers, where each array corresponds to
a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]]
represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row
at a time to an adjacent va... |
623c29fea6b1a30ffaaf873784443cc04ec45188 | KremenaVasileva/HackBG | /Week3/Monday/bank_account.py | 1,935 | 3.890625 | 4 | class BankAccount():
def __init__(self, name, balance, currency):
self.name = name
self.balance = balance
self.currency = currency
self.account_history = []
self.account_history.append("Account was created")
def __str__(self):
return "Bank account for {} with ba... |
5d610bd5a8a9c301afec7384c906ecaa61e46781 | nicktog/Memory | /Memory.py | 2,249 | 3.734375 | 4 | # implementation of card game - Memory - Nick Togneri
import simplegui
import random
list1 = range(1,9)
list2 = range(1,9)
card_deck = list1 + list2
x = 0
y = 0
turns = 0
state = 0
# helper function to initialize globals
font_size = 50
font_color = "Yellow"
def new_game():
global hidden, turns, x, y
random.... |
87c011e24cb13275785d4888f8a345869992660c | vanigupta20024/Programming-Challenges | /Odd_or_Even_lengthSLL.py | 917 | 3.90625 | 4 |
def length_even_odd(head):
c = 0
while head:
c += 1
head = head.next
return 1 if c % 2 == 0 else 0
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
... |
0ee9d9ef83201bb3a19d702c86c77e5e1dbea119 | rohitx/DataSciencePrep | /PythonProblems/Codeeval/moderate/longest_lines.py | 1,037 | 4.53125 | 5 | '''
Your program should accept a path to a file as its first argument. The file contains multiple lines. The first line indicates the number of lines you should output, the other lines are of different length and are presented randomly. You may assume that the input file is formatted correctly and the number in the fir... |
3f7e6c576414354d3d213aec3b5cecb8cad762f3 | Programacion-Algoritmos-18-2/ejercicios-clases-6-1-Rennato99 | /packArchivo/file.py | 1,312 | 3.859375 | 4 | class File:
# Constructor
def __init__(self, fileName, mode="r"):
self.openFile(fileName, mode)
# Metodo para abrir el archivo
def openFile(self, fileName, mode):
self.file = open(fileName, mode)
# Metodo que retorna una lista cuyos elementos son cada line
def getLines(self):
return self.file.readlines()... |
e578e2b04f8a12fb61ea48ae4ccd60461454990d | comlounge/starflyer | /starflyer/events.py | 1,004 | 3.75 | 4 | class Events(object):
"""a container for holding event queues"""
def __init__(self):
"""initialize the event container"""
self.handlers = {} # mapping event name -> list of handlers
def register(self, name, handler):
"""register a new handler for a given event
:param name:... |
6282aab3b8d2f2ae2ac2c18cc584160a3c6b8f3d | diogenesvazmelo/Aprendizado_de_Maquina_da_Teoria_a_pratica | /Pre-exercicio/Pre-exercicio.py | 1,387 | 3.84375 | 4 | def add(a,b):
"""
Realiza a soma de dois numeros
@author: Diógenes Vaz de Melo
"""
return a+b
def maior(a,b):
"""
Verifica, entre dois números, qual é o maior
@author: Diógenes Vaz de Melo
"""
if a > b:
return a
else:
return b
def soma(lista,x=0):
"""
retorna o somatório dos valore... |
fe5e08594d24f47d4a09ba8777df6ae328b4f8eb | mr-zhouzhouzhou/LeetCodePython | /剑指 offer/链表/二叉搜索树与双向链表.py | 1,947 | 3.703125 | 4 | """
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
"""
"""
思路: 先中序遍历, 然后把节点记录下来 一个for循环
"""
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write c... |
f8cc26dec1ac8efe3c7c281bed1409b7df7d361f | elsemac/Python | /Lesson2-2/ask.py | 1,035 | 3.765625 | 4 | # def ask_user:
# while True:
# user_say = input("Как дела? ")
# if user_say == "Хорошо":
# print('И у меня хорошо!')
# break
# else:
# print('Нет, а все-таки как твои дела? ')
answers = {
"Как дела?": 'Хорошо',
"Что делаешь?": 'Пишу код',
"Как погода?": 'Сейчас солнечно... |
3bbfdb125da9aa7c00b931aec1cd6c78e1867166 | manasacharyya25/DSA | /Trees/15. Convert Tree to SumTree.py | 604 | 3.734375 | 4 | class BinaryTreeNode:
def __init__(self, k, left, right):
self.data = k
self.left = left
self.right = right
class Solution:
@staticmethod
def sum_tree(root):
if not root:
return 0
# Trick is to store curr value in temp var
curr_val = root.data
... |
18fea0782a9459853ce49b8992c887b73ba1f766 | dlsqjary/baekjoonPy | /baekjoon_py/baekjoon2748.py | 461 | 3.75 | 4 | a = int(input())
arr = [0] * (a + 1)
arr[1] = 1
for i in range(2, a+1):
arr[i] = arr[i-1] + arr[i-2]
print(arr[a])
"""
이 방법처럼 하게 되면 시간초과가 발생함.
재귀식으로 풀면 중복연산이 많이 발생하기 때문.
배열에 값을 넣으면서 계산하면 중복 연산이 발생하지 않아 문제해결 시간이 더 빠름
def fibo(n):
if n <= 1:
return n
else:
return fibo(n-1) + fibo(n-2)
""" |
eafa1a8bd6497d7b0d4e979235110b7479038c03 | NayaradeSousa/first-steps | /Beginner/JogodaVelha.py | 2,047 | 4.09375 | 4 | """
It is a game of only two players where:
The board is an array of three rows by three columns.
| |
---+---+---
| |
---+---+---
| |
Two players choose a mark each, usually a circle (O) and a cross (X).
Players play alternately, one check at a time, in a gap that is empty.
The aim is to get three ... |
611af7cac71250f0fade06fcd87baa56388ee877 | KeleiAzz/LeetCode | /Clone Graph.py | 1,073 | 3.53125 | 4 | # Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
#res = UndirectedGraphNode(node.labe... |
b684bfac3f6755acd819ad396e583a6e63a65d5f | btsmarco/cse491-drinkz | /json-rpc-client.py | 1,573 | 3.515625 | 4 | #! /usr/bin/env python
import sys
import simplejson
import urllib2
def call_remote(base, method, params, id):
# determine the URL to call
url = base + 'rpc'
# encode things in a dict that is then converted into JSON
d = dict(method=method, params=params, id=id)
encoded = simplejson.dumps(d)
#... |
64f34e208d48e715bfc681eb7b0dbd3940516d2b | AutuanLiu/Code-Storm2019 | /509_Fibonacci_Number.py | 486 | 3.75 | 4 | # 509. Fibonacci Number
# 动态规划
# Runtime: 36 ms, faster than 44.34% of Python3 online submissions for Fibonacci Number.
# Memory Usage: 13 MB, less than 5.02% of Python3 online submissions for Fibonacci Number.
class Solution:
def fib(self, N: int) -> int:
if N == 0:
return 0
if N == 1:
... |
28d4d71b5ce50fbbf8f1345bc0d19d7e1db704c2 | junwon1994/Coursera-ML | /ex3/lrCostFunction.py | 1,373 | 3.796875 | 4 | import numpy as np
from sigmoid import sigmoid
def lrCostFunction(theta, X, y, lambda_):
""" computes the cost of using
theta as the parameter for regularized logistic regression and the
gradient of the cost w.r.t. to the parameters.
"""
if X.ndim == 1:
X = X.reshape(1, -1)
i... |
d0d1956848322471a5c8acaddeabdba50dded895 | georgenecro/semweb1718a1 | /Lab 1/test2.py | 623 | 3.796875 | 4 | import csv
#s,s2=input("mera,didaskwn\n").split(',')
#s= input('dwse 1')
#s2= input('dwse 2')
# open csv file for reading
with open('programma.csv','r',newline='',encoding='utf-8') as ifp:
with open('out.csv','w',newline='') as ofp:
ir = csv.reader(ifp)
writer = csv.writer(ofp)
#create csv reader object
#r... |
77c60c71e845361edeb3cbe1fc27756d05b0fb42 | j4viermora/python | /fundamentos/06-list.py | 695 | 3.96875 | 4 | lenguajes = [ 'python', 'kotlin', 'java', 'javascript']
lenguajes.sort()
aprendiendo = f'estoy aprendiendo { lenguajes[0] }'
print( aprendiendo )
# remplazando valors de un arreglo
lenguajes[2] = 'PHP'
print( lenguajes )
# agregar valores a una lista
lenguajes.append('RUBY')
print( lenguajes )
# eliminar ... |
6fef4fcadeee2a70e9ee7a077890ee9f447924b0 | tazbingor/learning-python2.7 | /python-basics/unit10-class/py090_create_subclass.py | 749 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17/12/11 下午8:42
# @Author : Aries
# @Site :
# @File : py090_create_subclass.py
# @Software: PyCharm
'''
创建子类
'''
class MyClass(object):
# 构造函数
def __init__(self, name, age):
self.name = name
self.age = age
class MyNewClass(My... |
9407551d2fd6bea72683a890329ec86c880f4832 | rishabh2811/Must-Know-Programming-Codes | /String Functions/string_times.py | 458 | 4.09375 | 4 | """
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
string_times('Hi', 2) → 'HiHi'
string_times('Hi', 3) → 'HiHiHi'
string_times('Hi', 1) → 'Hi'
"""
def string_times(given_str, times):
print_str = ''
while( times > 0 ):
print_str += given_str
... |
fb5f2e125d69735ad8a69b0de9cf6f1209970940 | kjoheyjo/PythonDS | /getHeight.py | 286 | 3.65625 | 4 | def getHeight(self,root):
if root is None:
return 0
elif root.right is None and root.left is None:
return 0
else:
height = 1 + max(self.getHeight(root.left), self.getHeight(root.right))
return height |
ef076847da3d9ce562bfe318ddf001563b47917f | Mannizhang/learn | /趣学python/第五章/条件.py | 132 | 3.765625 | 4 | money = 2000
if money > 1000:
print("I'm rich!")
# 注意有冒号!!
age = 10
if age == 10:
print('you are stupid')
|
284dba7d49da7c34b03d207ad037850c744075ee | PClark344/Demos-Learning | /AbstractFac.py | 2,076 | 3.53125 | 4 | import abc
# abstract classes
class Toy(metaclass = abc.ABCMeta):
@abc.abstractmethod
def show(self):
pass
class color(metaclass = abc.ABCMeta):
@abc.abstractmethod
def show_color(self):
pass
# concrete classes
class Car(Toy):
def show(self):
print('Remote ... |
f6e7a17384abf60f503e1bf9c710cec00597b871 | taariksiers/udemy-complete-python-bootcamp | /Project01_TicTacToe/ProjectOne_TicTacToe_2018.py | 2,329 | 3.96875 | 4 | # inputs & capture
# number position mapping
# print new spacer
# print board
# print detect 3 in a row as winner
# from iPython.display import clear_output()
# record turn based
print('Welcome to Tic Tac Toe.')
while True:
player1 = input('Please pick a marker X or O: ').upper()
if player1 in ('X','O'):
... |
69d368cf3d3937593a9bda0fde0d5d83d16021e4 | juhyun0/python_SQLite | /insert_record.py | 434 | 3.75 | 4 | # -*- coding: utf-8 -*-
import sqlite3
conn=sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute("""
INSERT INTO PHONEBOOK(NAME,PHONE,EMAIL)
VALUES(?,?,?)
""", ('aaa', '021-322-1542', 'shinhye@park.com'))
id=cursor.lastrowid
print(id)
cursor.execute("""
INSERT INTO PHONEBOOK(NAME,PHONE,EMAIL)
VALUES(?,... |
80a5579be2963eaf2907059b6b45e2c8ae939093 | JancisWang/leetcode_python | /118. Pascal's Triangle.py | 510 | 3.9375 | 4 | '''
easy
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
'''
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
def get_k(k):
row = [1]
for i... |
a2a06c5eb85c8034cedba70bd6cd5eeb94d20bf6 | jacquerie/leetcode | /leetcode/0697_degree_of_an_array.py | 1,047 | 3.625 | 4 | # -*- coding: utf-8 -*-
from collections import namedtuple
Occurrence = namedtuple("Occurrence", ["min", "max", "count"])
class Solution:
def findShortestSubArray(self, nums):
occurrences = {}
for i, num in enumerate(nums):
if num in occurrences:
occurrence = occurren... |
d0e5c8c0dd6f90a92225b82d1896f15f24004422 | inshaal/DPSB-Lab-Practicals | /AHZ PRACTICAL PAPER/Received from QA/Q11.PY | 1,886 | 4.21875 | 4 |
def login_store():
"""This function stores 5 login names
along with corresponding passwords"""
t=() # Empty tuple (will store login name and password)
print "Enter 5 login names and password!"
for i in range(5):
ask1=raw_input("Enter Login Name:") #asks user to enter log... |
e54aeadcec383309daa66efb8e90c0f102f261a6 | AlexanderKuzmin/2015_SHAD_Python_3.4.1 | /main.py | 1,369 | 3.78125 | 4 | '''
@version: 1.0
@since: 07.04.2015
@author: Alexander Kuzmin
@return:
@note: for small tests
'''
from collections import OrderedDict
from collections import Counter
#import rbtree, RBTree, pyavl
def BinSearch(arr, predicate):
'''
Bin search by predicate.
:param arr: list - where to... |
19b78792c22a1fa7f70e8b409d9f0e2883fbec7b | CheeseC4k3/practicepython | /pythonexercise2.py | 211 | 4.15625 | 4 | #!/bin/python3
num = int(input("enter a random number"))
check = int(input("enter a divisor"))
if num%check == 0:
print("num divides evenly by check")
else:
print("num is not divided evenly by check")
|
0de4a6f8fe3fc54954339eba939309da3aec88b8 | ledbagholberton/holbertonschool-machine_learning | /unsupervised_learning/0x01-clustering/1-kmeans.py | 2,429 | 3.953125 | 4 | #!/usr/bin/env python3
"""
Write a function that performs K-means on a dataset:
X is a numpy.ndarray of shape (n, d) containing the dataset
n is the number of data points
d is the number of dimensions for each data point
k is a positive integer containing the number of clusters
iterations is a positive integer contai... |
3ad60bc59fe13a6554266b250265d4857daf0f53 | AvisekNaug/QLearning | /qlearn/flearner.py | 8,751 | 3.59375 | 4 | """
This module implements the FLearner class. It uses temporal difference learning
on a descrete state/action space to generate a function approximation value of
each state in terms of state variables.
Value(state, action) = f(state, action)
Where 'f' is of the form:
f = function(state variables, action var... |
2d8bc64ac752f3ecd0823fdf943d3c1a4e403af7 | ad780hv/Belajar-Python1 | /P14-Class hewan.py | 942 | 3.546875 | 4 | class hewan:
def __init__(self):
self.suara = 'suara'
self.bulu = 'bulu'
print(self.suara)
print(self.bulu)
class kucing(hewan):
def __init__(self):
print('==============')
print('kucing')
print('==============')
def suara(self):
self.suara = input('masukkan suara:')
d... |
f416bc248633186a6ee21c8ce91805507d20c178 | 5l1v3r1/algorithms_py | /other/addDays.py | 602 | 4.03125 | 4 | # algorithm for adding days to a specific date (DD/MM/YYYY), variable and function names are in portuguese
meses_dias = {'1': 31, '2': 28, '3': 31, '4': 30, '5': 31, '6': 30, '7': 31, '8': 31, '9': 30, '10': 31,
'11': 30, '12': 31}
def addDias(data_atual, dias):
(dia, mes, ano) = tuple([int(i) for i in data_atual... |
e33ebf8a83af5d7b1e27d5f1797096d682517be9 | Dipeoliver/python_class | /fundamentos_projetos/Class_67.py | 486 | 3.921875 | 4 | from math import pi
import sys
# função que recebe raio como parametro
def circulo(raio):
return round(pi * float(raio)**2,2)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(f'''\
É necessário informar a area do circulo
Sintaxe: {sys.argv[0]} <area>''')
else :
... |
94bd112d9f2fce0fa4afbeff3fc76cd94ba21d22 | Saptarshidas131/NPTEL | /Data Structure and Algorithms using Python/search_value4.py | 368 | 3.796875 | 4 | # search a value in list, a more better approach with else
def findpos(l,v):
for i in range(len(l)):
if l[i] == v:
# Exit and report position of x
pos = i
break
# else pos is -1
else:
pos = -1
return(pos)
l = [5,20,9,8,43,72]
v = int(input("En... |
a88346540e213cad4f58aff5db69cf9c08dc3314 | AooRobot/Learning-Python-refresher- | /internetdatezip.py | 1,461 | 3.578125 | 4 | # accessing the internet and processing internet protocols
# urllib.request for retriveving data from 'URLs' and 'smtplib'
# for sending mail
'''
from urllib.request import urlopen
with urlopen('https://translate.google.com/') as response:
counter = 0
for line in response:
line = line.decode('ut... |
51092863412d211467cc250cee6db26b1b135770 | AlyssaYelle/python_practice | /numpy/numpy.py | 2,973 | 4.15625 | 4 | '''
learning how to use numpy
'''
import numpy as np
data = [[5.5,6,7],[1,5,8],[10,0,5],[12,12,7]]
print 'Row 1 is:', data[0]
x = np.array(data)
print 'Row 1 in numpy is:', x[0]
print 'Type Row 1, Col 1. Python', data[0][0], 'Numpy', x[0,0]
print 'First two rows:', x[0:2]
print 'First two cols:', x[:,0:2]
print... |
d96f6860eb0816cafc7ae15eee83c013fcd7d454 | HanHyunsoo/Baekjoon_Algorithm | /Python/11656.py | 126 | 3.9375 | 4 | word = input()
result = []
for i in range(len(word)):
result.append(word[i:])
result.sort()
for j in result:
print(j)
|
0b94de523da459cecdc1be7de0fb76e4401bf648 | alfoquial/algoritmos | /dequelist.py | 628 | 3.65625 | 4 | class Cola:
def __init__(self):
self.items = []
def isempty(self):
return len(self.items) == 0
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def hot_potato(vueltas, ... |
420f3917ee0838ec7817fb1523d03e33cf15d418 | dushyantss/ctci-python | /ch02_linked_lists/q03_delete_middle_node.py | 925 | 3.984375 | 4 | """
Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
EXAMPLE
lnput:the node c from the linked list a->b->c->d->e->f
Result: nothing is returned, but the new li... |
0da16b2ae7c15f01a8039bca6a21880c0197e823 | Saransh-kalra/Python-Labs | /Python/conversion_2.py | 403 | 4.53125 | 5 | #introduce the program
print("welcome to the farheneit to celcius conversion program")
#ask the use for a farheneit temperature
degree_f=float(input("please enter a farheneit temperature: "))
#convert the user's input to celciuys by dividing it by 1.8 and subtracting 32
degree_c=float((degree_f - 32)/1.8)
#print out th... |
be80b6d705ac8d5bfc59242fd5d94ba1b112e560 | manojnayakkuna/leetcode_easy | /problems/leetcode_121_bestTimeToBuyStock.py | 856 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 7 02:04:44 2020
@author: manoj
"""
def maxProfit(prices):
if len(prices) < 2:
return 0
if len(prices) == 2:
if prices[0] < prices[1]:
return prices[1] - prices[0]
else:
return 0
curr_max_profit = 0
cu... |
2bd9b179e54bb35c92d06158ab967fdfaeb78f2a | haiyugerald/Python | /day3/装饰器/2 函数嵌套.py | 448 | 3.546875 | 4 | #!/usr/bin/python
#-*- coding:utf-8 –*-
#1、函数的嵌套调用
# def my_max(x,y):
# if x >= y:
# return x
# else:
# return y
#
# def my_max4(a,b,c,d):
# res1=my_max(a,b)
# res2=my_max(res1,c)
# res3=my_max(res2,d)
# return res3
#2、函数的嵌套定义
def f1():
def f2():
print('from f2')
... |
30377d4cc03caa1de962f946f652460e11009063 | Sjerrul/Advent-Of-Code-2018 | /day9/day9.py | 2,718 | 3.890625 | 4 | class Node:
def __init__(self, data: int):
self.data = data
self.next = None
self.prev = None
class CircularLinkedList:
def __init__(self, initial: int):
self.head = Node(initial)
self.head.next = self.head
self.head.prev = self.head
def remove(self):
... |
8974f33d54c723f689c368eb2197fadab89e6e30 | yonoel/Python | /OpenCVModule/CoreOperations/BasicOperations/AccessAndModifyPixelValues.py | 971 | 3.859375 | 4 | import numpy as np
import cv2 as cv
img = cv.imread("roi.jpg", 0)
# You can access a pixel value by its row and column coordinates.
# For BGR image, it returns an array of Blue, Green, Red values.
# For grayscale image, just corresponding intensity is returned.
px = img[100, 100]
print("img's px---->", px)
# accessing... |
c60c773a49eff1fb54c33f2bc505a737fdf5a266 | VolodymyrFilSG/Code | /Python/Hackerrank/basic data types/Finding the percentage.py | 233 | 3.640625 | 4 | lenght = int(input())
a = []
for i in range(lenght):
a.append(input().split(' '))
name = input()
for i in range(lenght):
if a[i][0] == name:
print('%.2f' % ((float(a[i][1]) + float(a[i][2]) + float(a[i][3])) / 3))
|
f6b9e2a317a4d315d96d5a64cf00129e5fd4b3b9 | FancyYan123/LeetcodeExercises | /4_findMedianSortedArray.py | 2,225 | 4.03125 | 4 | """
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
进阶:你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗?
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
示例 3:
输入:nums1 = [0,0], nums2 = [0,0]
输出:0.0... |
ed1a7f1190a68d8322d9855d0dbe464f41516b0c | mmyumu/advent-of-code | /03.py | 1,660 | 3.625 | 4 | import sys
class Triangle:
def __init__(self, a, b , c):
self.a = int(a)
self.b = int(b)
self.c = int(c)
def isValid(self):
return (self.a + self.b > self.c) and (self.a + self.c > self.b) and (self.b + self.c > self.a)
class TriangleParser:
def __init__(self, datas):
self.datas = datas
def getTriangl... |
d58b21af054d8c35e02af8b0786770f4a9b77f80 | xyp8023/LeetCode_Python | /657_JudgeRouteCircle.py | 873 | 3.5625 | 4 | class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
if len(moves) < 2:
return False
if moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D'):
return True
else:
return ... |
6dcef2d50687fef1eceafb9a725c64c29680d921 | moodycam/MARS-5470-4470 | /Ramsden/Ramsden_6_Feb_2019_Class_notes.py | 3,092 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import matplotlib
# In[2]:
import numpy as np
# In[3]:
import matplotlib.pyplot as plt
# In[4]:
get_ipython().run_line_magic('matplotlib', 'inline')
# In[5]:
#Setting up the plot
# In[7]:
plt.subplots(figsize = (2,2))
# In[8]:
#1.3.2
# In[9]:
... |
e7b5bc8728132f3afd8685121c74deb55691540f | rupol/Computer-Architecture-Lecture | /01_basics/example_cpu.py | 2,108 | 4.21875 | 4 | import sys
# operation (OP) codes
# things our computer can do
# our computer is 8 bit, so we can only write 256 OP codes
PRINT_HELLO_WORLD = 1 # 0b00000001
HALT = 2 # 0b00000010
PRINT_NUM = 3 # 0b00000011
SAVE_REG = 4 # 0b00000100
PRINT_REG = 5 # 0b00000101
ADD = 6 # 0b00000110
memory = [
# hard co... |
be2c183f6964229a70b72e18febc376081040c6f | diegojuan2104/flask_course | /1_python_feedback/22_first_class_fuctions.py | 211 | 3.59375 | 4 | def sum(*values):
total = 0
for i in values:
total += i
return total
def calculate(*values,operator):
return operator(*values)
result = calculate(32,34, operator = sum)
print(result)
|
84d2041c885444197fc499e43527d37061170e83 | venkatbalaji221/CompilerDesignLab | /2asgn/la.py | 5,935 | 3.59375 | 4 | import string
value = 1
while 1:
if value == '0':
break
exp = input("\nInput Expression: ")
# p-pointer
p = 0
flag = 0
operators = ["<", ">", "<=", ">=", "=", "<>"]
alphabet = list(string.ascii_letters)
identifier = ""
# checks operator
def checkop(j):
if exp[j:... |
fad4f472551ecbc53298f3357fd2334e478775c4 | tursunbek/task1 | /task1.6.py | 171 | 3.515625 | 4 | x='добро пожаловать'
# print(x[2])
# print(x[-2])
# print(x[0:5])
# print(x[0:-2])
# print(x[::2])
print(x[1::2])
print(x[::-1])
print(x[::-2])
print(x)
|
41d62e045de80556b841be6693157c36c93dbb2f | Washington-bezerra/Python-Execicios | /Exercicio 098.py | 1,041 | 3.875 | 4 | #Faca um programa que tenha uma função chamada contador(). Que recebe tres parâmetros: inicio, fim e passo e realize a contagem. A) de 1 até 10, de 1 em 1 -- B)de 10 até 0, de 2 em 2 C)uma contagem personalizada
def contador(inicio, fim, passo):
print('-=' * 17)
if inicio < fim:
if passo == 0:
... |
934ba2d306257246d690beeb350cf0f56f743df5 | LK/advent-of-code | /2016/03-1.py | 191 | 3.65625 | 4 | line = raw_input()
count = 0
while line != '':
nums = [int(num) for num in line.split(' ') if num != '']
if 2 * max(nums) - sum(nums) < 0:
count += 1
line = raw_input()
print str(count) |
53467c007eb0234710d857909d1888738a27d0d1 | adityatanwar800/FSDP2019 | /Day17/uni_admin.py | 1,298 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 16:00:27 2019
@author: Aditya Tanwar
"""
import numpy as np
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('University_data.csv')
#check for none value
dataset.isnull().any(axis=0)
#features and label
features = dataset.iloc[:, :-1].values
labels... |
c61b8e8a9efe5e6d7f23e4e79f1585a1879cc519 | Dhakad9/Python | /sorts/double_sort.py | 1,558 | 4.46875 | 4 | def double_sort(lst):
"""this sorting algorithm sorts an array using the principle of bubble sort ,
but does it both from left to right and right to left ,
hence i decided to call it "double sort"
:param collection: mutable ordered sequence of elements
:return: the same collection in ascendi... |
9c80f9de31c4c714e692d2ebb8831e2258e66bc8 | x4v13r1120/WoWCompabilityTest | /main.py | 3,585 | 4.1875 | 4 |
from string import ascii_uppercase
import alliance
import horde
def main():
# Xavier Naranjo 09/12/2019
# Description of program
print("Welcome to, World of Warcraft Character Compatibility test!\n")
print(
"This is where you will pick\nYour true embodiment of a WoW character\nBased off a f... |
d10ab9ec48a2a18fa2ae0bfafd895161762e7813 | mayank-iisc/Udemy-Python | /Tic Tac Toe.py | 4,281 | 4 | 4 | #Function to Display a board
def display_board(board):
print('\n'*100)
print(board[0] + ' | ' + board[1] + ' | ' + board[2])
print('---------')
print(board[3] + ' | ' + board[4] + ' | ' + board[5])
print('---------')
print(board[6] + ' | ' + board[7] + ' | ' + board[8])
#Function to t... |
9a5a3273d4d800397d38f8b0d7d713ada0d9b5db | jedzej/tietopythontraining-basic | /students/olszewski_bartosz/lesson_06_dictionaries/cities_and_countires.py | 370 | 3.65625 | 4 | number_of_countries = int(input())
cities = dict()
ACTION = 0
ACTION_2 = 1
for city in range(number_of_countries):
entry = input().split(' ')
cities[entry[ACTION]] = entry[ACTION_2:]
number_of_checks = int(input())
for checks in range(number_of_checks):
city = str(input())
for key, val in cities.items(... |
c67eb902216ce5bfbe6dbbd7babcfc7428dc01b7 | TusharKanjariya/python-practicles | /9.py | 163 | 4 | 4 | # Iterative Way
str1 = input("Enter String")
char1 = input("Enter Character")
count = 0
for x in str1:
if char1 == x:
count = count + 1
print(count)
|
ca221de9e078b3ab844dac87256d1d2d04790eb8 | leoncheng57/graphics-0-picmaker | /8.py | 1,160 | 3.890625 | 4 | #TODO: Make recursive, fractal circles
#if <r then do this first
#else, call recursive function, set enter to w/4, h/4
#also set r to r/4
import math
width = 400
height = 400
maxcolor= 256
code = "P3\n"
code+= "%d %d %d\n"%(width, height, maxcolor)
def inRange(h, k, radius):
return math.sqrt((x-h)**2+(y-k)**2)<r... |
10e29625736d7955ac9b80b5a9e1ad9efd9203ae | rowlowles/BISDAC | /Release_procedure.py | 2,612 | 3.734375 | 4 | import webbrowser
from tkinter import *
from tkinter import messagebox
import os
#TODO: For someone to fill with the appropriate Release code
def guiPump(user_Command, button_name):
"""
Basic premise for the GUI is that the user will "Pump" the software. When the script reaches a point that requires
user i... |
47774e68b3d370b7c34c3e887eed4baf026e509b | Maha244/Tip_Calculater | /main.py | 412 | 4.15625 | 4 |
print("Welcome to the tip calculator.")
bill = input("What was the total bill? ")
tip_percent = input("What percentage tip would you like to give ? 10, 12, or 15 ? ")
tip_person = input("How many people to split the bill ? ")
tip = float(bill) * (int(tip_percent)/100)
total_bill = float(bill) + tip
each_person_bill... |
1a0711c4d9bda459b98c4f6f002bc4cdeaf739dd | tahajalili/Python-Fundamentals | /Math-problems/circle_area_calc_OOP.py | 556 | 4.09375 | 4 |
class Circle:
def __init__(self,radius):
self.radius = radius
def area(self):
pi = 3.14
area_value = pi*(self.radius**2)
print('Area of a circle with r='+str(self.radius),'is',area_value)
def perimeter(self):
pi = 3.14
perimeter_value = pi*(self.radius... |
4d1ce2a31c24215c400e0f93edbd925a37e8ccf9 | NeilVeira/ProjectEuler | /42.py | 479 | 3.96875 | 4 | import math
def is_tri(t):
root = int(math.sqrt(1+8*t))
if (root+1)*(root+1) == 1+8*t:
root += 1
if root*root != 1+8*t:
return False
n = (-1+root)/2.0
return abs(n-int(n)) < 1e-6
def convert(word):
t = 0
for char in word:
t += ord(char)-ord('A')+1
return t
an... |
b39e70b256bf506c8e36ccccfb02413db4a2c0d4 | edu-athensoft/stem1401python_student | /sj200917_python2m6/day07_201029/exception_9.py | 405 | 4.21875 | 4 | """
raise an error
throw
throws
raise
keyword: raise
1. we can raise an error as we want to (when, where and what)
2. we can add a message when raising an error
logical error / exception
"""
# input a positive integer
try:
num = int(input("Enter a positive integer: "))
if num <= 0:
raise ValueErr... |
3eb388b5ec1813bcfc60b7a6df601857a5b6c1a9 | sebastianwaleka/CV | /GoldPrices/goldgui.py | 1,140 | 3.578125 | 4 | import tkinter
from PIL import Image, ImageTk
from GoldPrices import goldprices
def last(days):
goldprices.GoldPrices().draw_graph(goldprices.GoldPrices().goldprice_last_days, days)
image = Image.open('graph.jpg')
graph_img = ImageTk.PhotoImage(image)
display = tkinter.Label(image=graph_img)
displa... |
db061013aa05c8b11ef601a7c055f0cf86845fb6 | krrajkumar/GUVI | /LEO.py | 317 | 4.125 | 4 | even=[]
odd=[]
n=int(input("Enter the number of digits:"))
for i in range(0,n):
num=int(input())
if (num%2==0):
even.append(num)
else:
odd.append(num)
print("Even number list" ,even)
print("odd number list",odd)
print("Sum of Even numbers",sum(even))
print("Sum of Odd numbers",sum(odd))
|
d9ce05b03f458c155cc9586573ccbebd2e219549 | MarKuchar/intro_to_algorithms | /2_Strings/string_operations.py | 918 | 4.21875 | 4 | # String (str) : A sequence of characters "" or ''
# + Concatenation : combining two strings
print("hello " + "world")
# * multiplication : repeat strings
print("hello" * 5)
# String indexing (index == position)
singer = "Lady Gaga"
# index 0123456789
# index always starts from "0"
print(singer[0]) # "L"
print(singer... |
0f761069d781a53176773bceab426af8f32cadfa | jeongmin14/algorithm | /python_pr/def.py | 451 | 4.03125 | 4 | def add(a, b):
c=a+b
print(c)
add(3, 2)
def add(a,b):
c=a+b
return c #값을 리턴하고 함수를 종료함
x=add(3,2)
print(x)
def add(a,b):
c=a+b
d=a-b
return c, d
print(add(3,2)) #튜플형태로 출력
# 소수인지 아닌지 판별
def isPrime(x):
for i in range(2, x):
if x%i==0:
return False
return True
... |
f8fbd14a33d4ad5c1b047dc4a9a508c5798bf20d | Gendo90/topCoder | /0-300 pts/topcoderCultureShock.py | 1,088 | 4.21875 | 4 | # Problem Statement
#
# Bob and Doug have recently moved from Canada to the United States, and they are confused by this strange letter, "ZEE". They need your assistance. Given a string text, replace every occurrence of the word, "ZEE", with the word, "ZED", and return the result. Note that if "ZEE" is just part of a ... |
262d6c87c8958da72cba60544ffeb270e6beeab7 | sleepypower/Arquitectura-de-software | /Quiz 1/Trabajo_en_Clase_1/main.py | 746 | 3.796875 | 4 | from abc import ABC, abstractmethod
"""
Invoker: Bot
Commands:
"""
class Command(ABC):
@abstractmethod
def execute(self) -> None:
pass
class EncenderCommand(Command):
def __init__(self):
pass
def execute(self) -> None:
print("Encendiendo!")
class ApagarCommand(Command):
... |
6937b4b1fdb4d6c69ecd4bd707407c00adb0785d | baothais/Practice_Python | /handle_file.py | 6,733 | 4.15625 | 4 | # """
# "r" - Read - Default value. Opens a file for reading, error if the file does not exist
#
# "a" - Append - Opens a file for appending, creates the file if it does not exist
#
# "w" - Write - Opens a file for writing, creates the file if it does not exist
#
# "x" - Create - Creates the specified file, returns an ... |
82925326ceb4899e92d6b091aa5962370b92c8b0 | alex-coch/OpenEDG-Python-Institute-PCEP-Entry-Level-Python | /2.1.4.7 Variables/main.py | 185 | 3.703125 | 4 | john = 3
mary = 5
adam = 6
print(john, mary, adam)
totalApples = john + mary + adam
print("Total number of apples:", totalApples)
print(john + mary - adam / john * mary // john **mary)
|
20653fc367e201222a6dd55bdccd51f9163c8dce | d4v3y/pythonScripts | /indexLines.py | 557 | 3.8125 | 4 | import re
# Ask user for input file
filename = input("Enter text filename: ")
# Open requested file
file = open(filename, 'r')
line = file.readline()
count = 1
while line :
# Check if line begins with a digiti
if line[0].isdigit() :
print(re.sub(r"^\d+ ", "", line), end="")
else :
if co... |
ce44bff1120e7606b4f76dc48a1d59434f59acf1 | sunyihuan326/analysis | /leetcode/threeSumClosest.py | 654 | 3.59375 | 4 | # coding:utf-8
'''
created on 2019/1/17
@author:sunyihuan
'''
def threeSumClosest(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res = sum(nums[:3])
for i in range(len(nums)):
l, r = i + 1, len(nums) - 1
while l < r:
... |
8eb9dd0ba0e086ff8e9876dfa45678de1a7bb161 | heshiqiufenzuoan/practice | /python基础代码/test1.py | 116 | 3.5 | 4 | x = 16
y = 20
for i in range(1, 16):
if ((x % i == 0) and (y % i == 0)):
hcf = i
print(hcf) |
6af737f328d382f768cd90ae28d8b54d4fbba6ca | npcastro/pyRF | /Viejo/graf.py | 4,704 | 3.734375 | 4 | # Guardo los metodos basicos para graficar y mantener el codigo dry
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
import pandas as pd
import tree
def draw_points( ax, df, x_name, y_name, colors):
"""Toma un dataframe y grafica dos variables como puntos con distintos colores
ax: objeto axis... |
ffa8f32aead1ec5cd0ee5240051118e684ee6313 | alex-i-blair/codeguild_bootcamp | /Guess_a_number2.py | 267 | 3.671875 | 4 | import random
def get_number():
t = raw_input("Guess a # between 1 and 100: ")
t = int(t)
return t
x = random.randint(1, 100)
while t != x:
if t < x:
print "Too low"
if t > x:
print "Too high"
t = get_number()
if t == x:
print "You got it!"
|
b56fedeba1a48759a91e98b33a0b64782febb331 | vaibhavkumar1517/Coding-in-Python | /01knaprecursive.py | 344 | 3.546875 | 4 | wt = [1,3,4,5]
val = [1,4,5,7]
w = 7
def knapsack(wt,val,w,n):
if n==0 or w==0:
return 0
if wt[n-1] <= w :
return max(val[n-1]+knapsack(wt,val,w-wt[n-1],n-1) , knapsack(wt,val,w,n-1))
elif wt[n-1]>w:
return knapsack(wt,val,w,n-1)
print("Max Profit is : ",knapsack(wt,val,w,... |
4f0ad41ab6e5864c548dc6875481c038f31103e7 | FFloresM/trabajos | /python/ejemplo.py | 229 | 3.9375 | 4 | ## esto es un comentario
#a = "perro"
b = "mundo"
a = b
c = 6.4
d = 12
#print(a,b,c,d)
if a == 'hola':
print("a es igual a hola")
elif a == "perro":
print("a es igual a perro")
else:
print("a no es igual a hola ni perro")
|
19a277ec8156a69bf97593d6ba2ff1c0148e5214 | IshmaelHeathcliff/python-assignments | /simple-exercise/最大公因式.py | 186 | 3.53125 | 4 | def gcd(x, y):#最大公因数
m = x if x >= y else y
n = x if x <= y else y
if m % n == 0:
return n
else:
return gcd(n, m % n)
print(gcd(18, 60))
|
fd3da2c29d658910089cffa36895ec5d35e9cdb2 | yang7988/python-foundation | /format/original_string.py | 356 | 3.5625 | 4 | # r或者R开头的字符串为原始字符串,即使遇到转义字符也原样展示并不会真的的转义
# 在处理正则表达式时应全程使用原始字符串。否则,将会有大量 Backwhacking 需要处理
def format_row_str():
str = r"Newlines are indicated by \n"
print(str)
if __name__ == '__main__':
format_row_str()
|
63b5cb4584085523b4e4577a7ecfcfabfc9cb6df | Gaya3balu0509/program | /repeat.py | 86 | 3.6875 | 4 | str1,num1=list(input().split())
for i in range(0,int(num1)):
print(str1,end="\n")
|
2dce860bc036407b0e174927b4f9f95310b188cd | dalcow3/CS-Python | /FileEditorGUI.py | 8,333 | 3.59375 | 4 | """
File: cs1520pgmProj4.py
Author: Christopher Bruns
Description: A GUI program that allows a user to input a file name to be used or
created. The file is then turned into a list in which the user is able to determine
the number of lines, view, edit, replace, delete, or insert new lines into the file.
"""
from Tkin... |
abc6939f627dc7d3bac5b2989ee292afdfab618c | dacl010811/cursopython2021 | /Unidad9/ejemplo.py | 660 | 3.84375 | 4 |
#
def tarea1():
lista = []
numero_emcontrado = 8
while True:
numero = input("Ingrese el numero de 0/9")
lista.append(numero)
for numero in lista:
if numero == numero_emcontrado:
print("Encontrado")
break
def tarea7():
lista1 = [1,2... |
b59dace6d2db42c49a19b46d86f75212059661b9 | laukikpanse/Python-Practice-Examples | /Practice9.py | 333 | 4.34375 | 4 | #Write a Python program to get a new string
#from a given string where "Is" has been
#added to the front. If the given string
#already begins with "Is" then return the string unchanged.
my_string = input("Please enter a string: ")
if (my_string[0] == "I" and my_string[1] == "s"):
print(my_string)
else:
print("I... |
bc89ba489cfb865ec125c5542781abcc3d8e17a2 | douradodev/Uri | /Uri/1116_v2.py | 210 | 3.71875 | 4 | def divisoes_simples(testes):
while testes:
x, y = map(int, input().split())
if y == 0:
print('divisao impossivel')
else:
print('{:.1f}'.format(x/y))
testes -= 1
divisoes_simples(int(input()))
|
ca7b89adae567d739697542e712ca323c0f1e8e7 | sydneyhoward/15-112 | /Week 3/wk3_practice.py | 13,274 | 3.78125 | 4 | #################################################
# Week3 Practice
#################################################
import cs112_s17_linter
import math, string
#################################################
# Helper functions
#################################################
def almostEqual(d1, d2, epsilon=10**-... |
ccaf59ade11422296dc3d6729547d6e9a9794b11 | Mr-Helpful/Improved-Vernam | /Encoder/encoder.py | 2,532 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
The concept:
A vernam cipher is mathematically a perfect way of transmitting a message, but
it requires a pre-transmission decided pad, which has to be the length of the
message encoded.
If a transformation to perform on the key is encoded along with the message,
then the initial pad can be... |
ca2f41587e5ab5b717e5f06b80ac182c15469f94 | cloi1994/amazon | /code/127.py | 1,372 | 3.59375 | 4 | class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if endWord not in wordList:
return 0
if not wordList:
... |
0b3886189181a7f5e62c2c18c25475b92a060de8 | arittrosaha/CS_and_Algorithms | /fight_club_2019/0p_facts.py | 646 | 3.734375 | 4 | # Python is strongly typed like Ruby and unlike JavaScript
# strongly typed means type coersion does not happen much
# js: 4 == "4" => true
# py/rb 4 == "4" => False/false
# Concatination in python and ruby returns a new array
# copy of list or string using slicing [start:end:step] (+)step is left to righ... |
19c52fbc009797cc615227b75b9a025883ec8c84 | liuspencersjtu/MyLeetCode | /4-Median-of-Two-Sorted-Arrays.py | 2,714 | 3.578125 | 4 | class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
def median(array):
l = len(array)
if l%2 == 1:
return array[l//2]
... |
083020acbb3deb7fea9f8ff4c9c00fa713a13972 | tanuj-maheshwari/RISC-V_Simulator | /helper_functions/ALU_utility_functions.py | 3,966 | 3.5625 | 4 | from helper_functions import basic_functions
def bin_add(bin_num1, bin_num2, signed=True):
bin_num1 = basic_functions.extend_to_32_bits(bin_num1, signed)
bin_num2 = basic_functions.extend_to_32_bits(bin_num2, signed)
result = ''
carry = 0
for i in range(31, -1, -1):
digit_1 = int(bin_num1[... |
0951bd0b8c45daeb5a4546827a27da3bfd71d392 | conancheng/pyGreat | /tools/Pandaspd/t05saveload.py | 1,303 | 3.53125 | 4 | import pandas as pd #加载模块
import numpy as np
# 生成测试数据2
df = pd.DataFrame({'col1':[11,12,13], 'col2':[21,22,23]})
df.to_csv('data/savecsv.csv')
# 从.csv文件读取读取DataFrame对象
df_csv = pd.read_csv(r'data/savecsv.csv', sep=',', header=0, index_col=0)
# 这里的sep是分隔符,当为‘,’时,可以在excel中方便的查看;为‘\t’时,反而在excel不能很好的显示了
# header # 索引行... |
6f3c8ce9d34948aa034f8605ac60ea5a9f7cea57 | skrjha20/01-Machine-Learning-Assignment | /01-Linear Regression/ex11.py | 912 | 3.53125 | 4 | from __future__ import division
import pandas as pd
import numpy as np
def gradient_descent(X,y,theta,alpha):
J1 = 0
m = len(y)
converged = False
while not converged:
J2 = np.sum(np.power((X.dot(theta.T)-y),2))/(2*m)
if abs(J1-J2) > 0.0000001:
J1 = J2
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.