blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d3646897390d6ad0266783a7124731478d834ff6 | zhangler1/leetcodepractice | /链表/剑指 Offer 25. 合并两个排序的链表.py | 601 | 3.734375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
p=ListNode()
head=p
p1=l1
p2=l2
while(p1!=None and p2!=None):
if p1.val>=p2.val:
... |
2b578291c9c7dc15177d5d6edaa4bbc7ff2ea975 | RyLaney/userpass | /userpass/tests/test_module.py | 1,834 | 3.515625 | 4 | """Test cases for module
"""
from unittest import TestCase
import userpass.generate
class TestModule(TestCase):
"""Test Case class for module
"""
def test_alphanumeric_is_string(self):
"""generate.alphanumeric should return a string
"""
item = userpass.generate.alphanumeric(64)
... |
2d40827f1d3307b9966772ace3f48d98b8124eda | arakann/python-basics | /practice_2/vladimir_assertions.py | 1,579 | 3.546875 | 4 | '''
Created on 12.03.2014
@author: vladimirbessmertnyj
'''
def assert_equal(a, b):
if a == b:
return True
else:
raise Exception
def assert_not_equal(a, b):
if a != b:
return True
else:
raise Exception
def assert_true(x):
if x:
return True
else:
... |
ab3d832b14744e03f55203484a4d4000c0d5e93b | CamiloCastiblanco/AYED-AYPR | /AYED/Programas/mid.py | 456 | 3.734375 | 4 | import sys
def main():
x=int(input())
y=int(input())
z=int(input())
if x>y and x>z:
if y>z:
print ("Case 1:",y)
else:
print ("Case 1:",z)
if y>x and y>z:
if x>z:
print ("Case 1:",x)
else:
print ("Case 1:",z... |
6469ec80a5bbdc439a2b4d61a78e03fc3ae98478 | changbokLee/Python-in-Practice | /section07-03.py | 1,815 | 3.921875 | 4 | #파이썬 클래스 상세이해
# 상속 , 다중상속
# 예제1
# 상속기본
# 슈퍼클래스(부모) 및 서브클래스(자식) -> 모든속성 ,메소드 사용가능
# 라면 -> 속성(종류 , 회사 , 맛 , 면 종류, 이름 ): 부모클래스
# 코드의 재사용 가능
class Car:
"""Parent Class"""
def __init__(self, tp , color):
self.type = tp
self.color = color
def show(self):
return 'Car Clas "Show Meth... |
ec8af6720f602475dfe4f8cece908545371b2d30 | kongfany/python100 | /if_for/shuixianhua.py | 865 | 3.546875 | 4 | """
----------------------------------------
File Name: shuixianhua
Author: Kong
Date: 2021/7/8
Description: 寻找所有水仙花数
水仙花:三位数,个位的3次方之和为本省
关键得出数字的三位
个位:num % 10
十位:num // 10 % 10
百位:num // 100
153 370 371 407
----------------------------------------
for num in range(100,1000):
... |
c3742cdf2d9fb26c62d1cc81f0938a726b410385 | ed100miles/StructuresAndAlgorithms | /SearchTrees/bst_simple.py | 1,590 | 4.125 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BST:
"""Simple implementation of a binary search tree"""
def __init__(self):
self.root = None
def insert(self,data):
if self.root is None:
self.root ... |
184745da9d5f0ba618b3ea3e96ab18a098e7eef7 | singultek/ModelAndLanguagesForBioInformatics | /Python/List/31.lendecoding.py | 945 | 3.90625 | 4 | def repeat_value(repetition,value)-> list:
i=0
_shallow = []
while i < repetition:
_shallow.append(value)
i+=1
return _shallow
def flatten(nested_list: list) -> list:
"""
Flatten an input list which could have a hierarchical
multi nested list
:param nested_list: The ... |
cbd8645102c0622bcf874cf619045a901480e2a2 | kubbo/python-lang | /ListDemo.py | 202 | 3.75 | 4 | __author__ = 'zhu'
str="hello are you"
list=str.split()
print(list)
print(len(list))
while len(list)!=0:
print(list.pop())
list=["hello","world"]
print(" ".join(list))
print("#".join(list[0:2]))
|
58a7af593921bf5e1634f8f6bf64dff98d755e33 | geraldzm/Othello-ASM | /putPice.py | 1,341 | 3.53125 | 4 | mtz = [] # 0 = - , 1 = B, 2 = N
def putPice(fil, col, color):
global mtz
for i in range(-1, 2):
for j in range(-1, 2):
if((i,j) == (0,0)):
continue
if(mtz[fil+i][col+j] != color):
if(path(fil, col, j, i, color) == color):
mtz[... |
08e76bcbb4d4407c3f414e368f0ad1f688d54f59 | edithturn/Data-Structures-Algorithms | /valid_parentesis/valid_parentesis_01.py | 1,250 | 4.4375 | 4 | # A string of brackets is considered correctly matched if every opening bracket in the string can be paired up with a later closing bracket, and vice versa. For instance, “(())()” is correctly matched, whereas “)(“ and “((” aren’t. For instance, “((” could become correctly matched by adding two closing brackets at the ... |
97e7fac458c215ed312bb59f8bc05ec850368125 | sunnyyeti/Leetcode-solutions | /34 Find First and Last Position of Elements in Sorted Array.py | 1,330 | 3.78125 | 4 | # Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
# If target is not found in the array, return [-1, -1].
# You must write an algorithm with O(log n) runtime complexity.
# Example 1:
# Input: nums = [5,7,7,8,8,10], target = 8
# Output: [3,... |
2b6d52fec15f0c05e7730b4756212a10fb813bc9 | ekomai/Forecast_AI | /2_owm_sql_csv.py | 993 | 3.5 | 4 | # api to json
from pprint import pprint
import urllib
import urllib.request
import json
import sqlite3
import sqlite3 as sql
import os
import csv
from sqlite3 import Error
try:
conn = sqlite3.connect('sqlite/forecast.db')
cur = conn.cursor()
cur.execute('''SELECT * FROM Forecast''')
... |
96fde298fd9ef94a7ddd925d790f4b799f757763 | petro-ew/test1 | /solutions/1.py | 993 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import cmath
import math
__author__ = 'petro-ew'
#zadacha number 1
"""
#список квадратов чисел от 1 до 10
n=int(input())
print("n=",n)
l1=[]
x=0
while x < n:
x=x+1
l1.append(x)
l2 = [x ** 2 for x in l1]
print(l2)
"""
"""
#список ква... |
1bcf5e6314ee9cc3f82bd93b8ca8af892d18860c | Santigonzaq/Exercisespython | /Ejercicio.py | 3,825 | 3.578125 | 4 | from datetime import datetime as dt
from datetime import timedelta as td
from dateutil.relativedelta import relativedelta as rd
import locale
locale.setlocale(locale.LC_ALL,"Spanish_Spain.1252")
formato="%d/%m/%y - %I:%m:%p"
alterno = "%Y-%m-%d"
print("----------------CLINICA LA ESPERANZA------------------")
p... |
df0cce5e478f0fae6633b42c936601da00ff7451 | yanshengjia/algorithm | /leetcode/Breadth First Search/513. Find Bottom Left Tree Value.py | 1,027 | 3.9375 | 4 | """
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Solution:
1. DFS + Stack
2. BFS + Queue
"""
# Definition for a binary tree node.
... |
285bf181a4ded51deea18aa6a71129503f2981de | arbitre125/ChessTournament-1 | /Controllers/utils.py | 2,583 | 3.828125 | 4 | import datetime
class Util:
@staticmethod
def input_format(string_input):
"""
Format the asked input of the user
Replace caracters with accents
Delete white spaces
"""
if type(string_input) == str:
string_input = string_input.lower()
for... |
0166d1a226e16647bd2c9e281f953e163e23dd8a | Arxtage/leetcode | /zigzag-iterator/zigzag-iterator.py | 797 | 3.640625 | 4 | class ZigzagIterator:
# Create a list beforehand
def __init__(self, v1: List[int], v2: List[int]):
L, R = 0, 0
self.res = []
while L < len(v1) and R < len(v2):
self.res.append(v1[L])
L += 1
self.res.append(v2[R])
R += 1
... |
9e8a391c8911ffa73757421a939218e8202b5087 | nawaka7/Booking_System | /main.py | 31,763 | 3.53125 | 4 | # Booking System (Concert Ticket)
import pymysql.cursors
def connect_sql():
connection = pymysql.connect(
host = 'YOUR_HOST',
port = 8888,
user = 'USER_NAME',
password = 'PASSWORD',
db = 'DATABASE',
charset = 'utf8',
cursorclass = pymysql.cursors.DictCursor,
autocommit = True)
r... |
542301d4bd2e43831f702fbee5eca43f29b284cf | bhuvankaruturi/Python-Programs | /least_cost_path.py | 1,120 | 3.8125 | 4 | #Path with the least cost
inputString = input()
blocks = []
row = []
cost = ''
for value in inputString:
if value == '#':
row.append(int(cost))
blocks.append(row)
row = []
cost = ''
else:
if value == '@':
row.append(int(cost))
cost = ''
el... |
0de36cab21e7a08bd840fe93ea481ea93b6fbaa5 | dawidstefaniak/Python30DaysChallange | /22BST.py | 997 | 3.765625 | 4 | class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left... |
f8e24836094201741c4c57330b7e108ae0d78dd6 | Arvind-Bhakuni/Projects | /rock_paper_scissor/rps.py | 3,896 | 3.796875 | 4 | # importing necessary libraries
import random
import tkinter as tk
# creating objects
root = tk.Tk()
# set geometry
root.geometry('400x400')
root.resizable(0,0)
root.title('Rock Paper Scissor')
# defining global variable
user_score = 0
com_score = 0
user_choice = ''
com_choice = ''
# define a function to convert us... |
58318a02e0f738cdef8f1a61ea23faa176e7f9e3 | vijay-vj/python | /Date_Formattin.py | 580 | 4.03125 | 4 |
from datetime import datetime
def main():
x = 0
print (x)
now = datetime.now();
print (now.strftime("%Y"))
# %a/ %A -- weeday
# d/ D -- Day
# b/ B -- Month
# y/ Y -- Year
# c -- Local date and time
# x -- Local date
# X -- Local time
#
prin... |
36c38bdde076f2acffc62e1074bfce8f68737f68 | Vern01/comp_v2 | /maths.py | 252 | 3.640625 | 4 | def solve(equation):
print("Needs to solve equation.")
class Math:
def __init__(self, memory):
self.memory = memory
def calc(self, string, ignore=""):
values = self.memory.set_values(string, ignore)
return string
|
b6297410ce3040058c477ae931b0e3857015f4a4 | anyone21/Project-Euler | /gallery/Dynamic-programming/Problem-82/Problem-82.py | 1,988 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 17 18:09:44 2016
@author: Xiaotao Wang
"""
"""
Problem 82:
The minimal path sum in the 5 by 5 matrix below, by starting in any cell in
the left column and finishing in any cell in the right column, and only
moving up, down, and right, is indicated in red and bold; the s... |
4eef352068ed9bd22a8eda7c6ca688613c1abb4a | ArvindAROO/AckermannFunctionHyperOptimization | /ackermannOriginal.py | 534 | 3.9375 | 4 | def ackermann(m,n):
#the legacy code for the actual ackermann function
if m==0:
ans = n+1
elif n==0:
ans = ackermann(m-1,1)
else:
ans = ackermann(m-1,ackermann(m,n-1))
return ans
if __name__ == "__main__":
print("Be careful with the values, the function grows beyond expo... |
b47b74dee2093752a94167d0e51705c430d9b544 | YLyeliang/now_leet_code_practice | /tree/depth_binary_tree.py | 2,068 | 4.09375 | 4 | # 输入一棵二叉树的根节点,求该树的深度。
# 从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
# 树的遍历方式总分为两类:深度优先搜索(DFS)、广度优先搜素(BFS)
# 常见DFS:前序、中序、后序遍历
# 常见BFS:层序遍历
# 一、 DFS
# 后序遍历/DFS一般采用递归或栈来实现。
# 采用递归的方式进行。 树的深度由左右子树决定,其深度等于左右子树中最深的+1.
# 则可得到递归公式max(left,right)+1
# time: O(N) space:O(N)
# Definition for a binary tree node.
# class TreeNo... |
0d9fa9a2e977babc33005ffe51eeab630811cfd9 | 981377660LMT/algorithm-study | /20_杂题/骑士距离.py | 910 | 3.921875 | 4 | # 骑士距离
# 棋盘上马从(0,0)到目标点的最短路径
def knight_distance(tx: int, ty: int) -> int:
"""https://maspypy.github.io/library/other/knight_distance.hpp"""
max = lambda x, y: x if x > y else y
tx = abs(tx)
ty = abs(ty)
if tx + ty == 0:
return 0
if tx + ty == 1:
return 3
if tx... |
c7b0231ee433241fcc447c86157cbfeaea1d0dbe | SelinaBains/SEL | /Python/unique_chars.py | 2,053 | 4.46875 | 4 | def is_char_unique(x=None, case_sensitivity=True):
"""
Checks if the string has unique characters.
Example:
is_char_unique(x="abcABC")
is_char_unique(x=abcABC, case_sensitivity=False)
:param str x:
**REQUIRED** Input string.
:param bool case_sensitivity:
*O... |
1ec5f0daf6b560fc9d57293f9029e42fea7c907c | tfcampbell/startech | /testPyMongo.py | 338 | 3.515625 | 4 | import pymongo
'make db connection'
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["testDatabase"]
'a document in MongoDB same as record in SQl'
'insert a column into testDatabase'
mycol = mydb["customers"]
'add data'
mydict ={"name" : "John", "Address" : "23 London Road"}
x = mycol.... |
34708977bcc962e922c5923225e2ac5e9b65f594 | jshaw63/codeinprogress | /program4.py | 1,104 | 4.375 | 4 | # program prime physics 104
# j. shaw 3/10/17
#
# prime test and factoring program
#
# input a number:
#
print ' prime number test and factoring program:'
print ' tests for primality and factors x if not prime'
x=float(input("enter x: "))
#
# echo back to screen
#
print 'You entered:'
print 'x = ',x
#
if x%2==0:
pr... |
165572e40474e8dc1d38fcd949b39b6fa97407fd | SJTU-yys/Leetcode | /isPalindrome.py | 277 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 23:57:08 2015
@author: yys
"""
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# Get the length of the digit
if x >= 0:
return x == int(str(x)[::-1])
else:
return False |
957f1daef5c4d81b2bf644068c6186016737bc47 | ElizaLo/Practice-Python | /DataCamp/Writing Efficient Python Code/Foundations for efficiencies/enumerate.py | 454 | 3.65625 | 4 | # Rewrite the for loop to use enumerate
indexed_names = []
for i, name in enumerate(names):
index_name = (i,name)
indexed_names.append(index_name)
print(indexed_names)
# Rewrite the above for loop using list comprehension
indexed_names_comp = [(i,name) for i,name in enumerate(names)]
print(indexed_names_comp)... |
71f93fa4629e3d1926e1a7d9897e9e4d1a481c29 | chulsea/TIL | /algorithm/Python/algorithm/problems/steal_pole.py | 458 | 3.671875 | 4 | def solution(arr):
answer = 0
n = len(arr)
stack = []
for i in range(n):
if arr[i] == "(":
stack.append(arr[i])
else:
prev = arr[i-1]
stack.pop()
if prev == "(":
answer += len(stack)
elif prev == ")":
... |
8ec72a745bd6d9001f74bfd0dd8c7054e33dd762 | LRYnew/note | /015 python/code/nine/f1.py | 783 | 3.734375 | 4 | # -*- coding:utf-8 -*-
# 类的定义
class Student():
sum = 0
name = ''
age = 20
__score = 100
# 构造函数
def __init__(self, name='YJob', age=18):
self.name = name
self.age = age
self.__score = 0
# print(name) # name为传入的参数,而不是类变量
# print(age)
s... |
97f55ce4ba4c31b5576820d167e57251027b1e69 | bakunobu/exercise | /1400_basic_tasks/chap_7/main_funcs.py | 1,159 | 4.46875 | 4 | from typing import Union
def get_input(message:str, is_float:bool=True) -> Union[int, float]:
"""
Gets a number as an imput and returns it. If input is incorrect,
i.e. float instead of int or a string that can't be converted to
number prints warning and asks for another input
Works while the... |
727efdb2d34b7077afc10120a65ecefd5f4e810c | perticascatalin/1.1-Understanding-an-Image | /code/colorScales.py | 1,442 | 3.625 | 4 | # Run: python colorScales.py
# Creates image examples for 1.1 Understanding an image
# Obtained images saved under: 'blackwhite.jpg', 'grayscale.jpg', 'blue.jpg', 'green.jpg', 'red.jpg'
import cv2
import numpy as np
import sys
rows = int(sys.argv[1])
cols = 256
blackwhite = np.zeros((rows, cols), np.uint8)
for col i... |
0a71f498965749dfed415b8969a2256470399eed | agarwalmohak6/Python-codes | /primecheck.py | 172 | 3.78125 | 4 | n=int(input())
i=2
c=0
while(i<n):
if(n%i==0):
c+=1
break
else:
i+=1
if(c!=0):
print("Not prime")
else:
print("Prime")
|
d00165f352151ba859d37e321323acd8251f4ba0 | jaehyunan11/leetcode_Practice | /robotBoundedInCircle.py | 3,479 | 3.984375 | 4 | # class Solution:
# def
# if after the set of operations, the robot is still at the position (0,0) then it is bounded
# if the robot doesn't point North after the set of instuctions, it will
# return to the point (0,0) after 4 sets of instructions, pointing North, and repeat
# Therefore, if the robot doesn't point... |
e09f7bbdaa45b9d65ab904f2a8da5d979f4d1901 | 6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion | /CH12/EX12.14.py | 3,770 | 4.3125 | 4 | # 12.14 (Tkinter: Mandelbrot fractal) The Mandelbrot fractal is a well-known image
# created from a Mandelbrot set (see Figure 12.26a). A Mandelbrot set is defined
# using the following iteration:
# Z(n+1) = Z(n)^2 + c
# c is a complex number, and the starting point of the iteration is Z(0) = 0(For
# information on com... |
31fd84e2258879af1e3ccc2eba05a9ec196908bb | terrifyzhao/leetcode | /daily/1071_gcdOfStrings.py | 391 | 3.546875 | 4 | class Solution(object):
def gcdOfStrings(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
if str1 + str2 != str2 + str1:
return ''
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
return str1[0:gcd(le... |
f5eac7228672449e7a1e014a8cb16df6f6229f84 | atulpatel991928/bitcoin-maxnum | /add.py | 227 | 3.8125 | 4 | """var1= "45 "
var2= 4
var3= " 60"
print(int(var1) + int(var3))
print(10* "hwllo word\n")
"""
print("Enter firsrt number:")
n1 = input()
print("Enter second number:")
n2 = input()
print("sum of the number:", int(n1) + int(n2)) |
635e8f44f46576687f27585d7e7b296d6b5e8017 | dexterka/coursera_files | /1_Python_for_everybody/week6_functions/functions_testing.py | 373 | 3.78125 | 4 | # Conditions within functions
# Calling the function with parameters and returning the values
def greet(lang):
if lang == 'es':
return 'Hola'
elif lang == 'fr':
return 'Bonjour'
else:
return 'Hello'
print(greet('en'), 'Sally!')
print(greet('es'), 'Maria!')
print(greet(... |
2f1025ffd9e87284d4447b9e1120c46baaaca6d6 | ArthurConmy/EPQ | /A General Solution.py | 25,324 | 3.703125 | 4 | from itertools import count
from math import factorial as f
from random import randint
white='\033[1;37m'
black='\033[1;30m'
reset='\033[0m'
def print_game(horizontals, verticals, rs, cs): ##if you're in repl.it, turn this into print_game and delete the function below
for index in range(0, rs+1):
... |
f6b6db6125364f64f347e9cd435aa26839a7166e | gnenov89/BashScripting | /re_json.py | 1,773 | 3.5625 | 4 | #!/usr/bin/python
# Create class that takes a file as an argument
class Open_File():
def __init__(self, filename, mode):
self.filename= filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_t... |
867bfd831baf5ffaa5697a299979f0a32bb07177 | xiaotiankeyi/PythonBase | /exercise/base_exercise.py | 1,549 | 4.46875 | 4 | """x 的 y 次方(xy) 以下表达式"""
v = 3 ** 2
print(v)
"""3*1**3表达式输出结果"""
b = 3 * 1 ** 3 # 正确的是 3,** 拥有更高的优先级,
print(b)
"""9//2表达式输出为,取整除,返回商的整数部分"""
s = 9 // 2
print(s)
"""如果表达式的操作符有相同的优先级,则运算规则是?____从左到右"""
g = (3 + 1) * (5 + 5)
print(g)
"""以下代码输出为"""
x = True
y = False
z = False
if x or y and z: # 这里先运算and,y等于0,返回y的值F... |
3c6b3e0e225fb71a6c0d1832a68f57f825bf5085 | OlehPalka/Second_semester_labs | /labwork8/test_validator.py | 5,537 | 3.71875 | 4 | """"
This is testing module.
"""
import unittest
from validator import Validator
class TestValidator(unittest.TestCase):
"""
Class which tests function from module disc
"""
def test_validator(self):
"""
This method cheks if the functtion works correctly.
"""
valid = Va... |
f781becc20b89fa939854ad2bc1f984af7115450 | Minions1128/sorting_algorithm | /sort/select_sort.py | 253 | 3.921875 | 4 | def select_sort(array):
for i in range(len(array)):
_min = i
for j in range(i, len(array)):
if array[j] < array[_min]:
_min = j
array[_min], array[i] = array[i], array[_min]
return array |
000a81cb903328f4ae595eae436b1693e7b4bf06 | eat-toast/Algorithm | /Baek_jun/1924.py | 528 | 3.5625 | 4 | day = {6: 'SUN', 0: 'MON', 1: 'TUE', 2: 'WED', 3: 'THU', 4: 'FRI', 5: 'SAT'}
mon = {1 : 31, 2: 28, 3:31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
# 1월 1일이 Mon 이다
# 시작일로 부터 현재까지 지난일 수를 더하고 7로 나누면 현재 요일이 나온다.
x, y = map(int, input().split(' '))
after_mon = 0
for M in range(1, x, 1):
... |
bec2cb22a536528db70d1a39dd056ae6aeda0c29 | kevhunte/hackerrank_leetcode_solutions | /leetcode/python/max_depth_binary_tree.py | 1,265 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# DFS / Recursive
def maxDepth(self, root: TreeNode) -> int:
# recurse in a helper, return the n... |
97f705029cc049e46803d87020d73c2842a46c8a | kirtivr/leetcode | /Leetcode/2385.py | 7,534 | 3.953125 | 4 | from typing import List, Optional, Tuple
import math
import ast
import pdb
import time
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BST:
head: Optional[TreeNode]
def PrintT... |
64d995ba53cee507db1b0ea02993a50e7bc3a2be | Tr4shL0rd/mathScripts | /blandedeTal/blandede_tal_Brøker_minus.py | 1,318 | 3.71875 | 4 | from fractions import Fraction
try:
def fracToMixed(num,dem):
a = num // dem
b = num % dem
#print(a)
print("{} {}/{}".format(a, b, dem))
print()
main()
def gcd(a, b):
if (a == 0):
return b;
return gcd(b % a, a);
def lowest(den3, num3):
common_factor = gcd(num3, den3);
... |
b0f9eaea8c87bdb418ba016a02e982d217b7a4b4 | emersonsemidio/python | /Desafio61.py | 242 | 3.71875 | 4 | import time
a = int(input('Digite o primeiro termo: '))
b = int(input('Digite a razão: '))
cont = 0
termo = a
while cont <10:
print('{}'.format(termo),end=' > ')
termo = termo + b
cont = cont +1
time.sleep(2)
print('FIM')
|
4e87d6cb56ce9ac5f28b7c46bb646d774f2f2649 | nanapereira/python-introducao | /desafios/desafio_retangulo_circulo.py | 557 | 3.5 | 4 | from math import pi
class Retangulo:
def __init__(self, lado_x, lado_y):
self.lado_x = lado_x
self.lado_y = lado_y
def calcular_area_retangulo(self):
return self.lado_x * self.lado_y
def calcular_perimetro_retangulo(self):
return (self.lado_x * 2) + (self.lado_y * 2)
cla... |
0aea0a41da8bdb87b05d1f1e75c63d12e2851fd7 | azureleaf/utilities | /anagram/main.py | 1,608 | 3.6875 | 4 | import romkan
import itertools
src_hiragana = "あさって"
# Container of the anagrams generated
anagrams = []
# Note that only the vowels "a", "u", "o" can connect to
# these double consonants in MOFA's Hepburn Romaji
double_consonants = ["ky", "sh", "ch", "ny",
"hy", "my", "ry", "gy", "by", "py"]
... |
8542098909a2582c49c5818ff63ef8198dc0b681 | czchen1/cs164-projects | /proj2/tests/error2/D5.py | 110 | 3.5 | 4 | class A:
x = 3
def __init__(self): pass
def f(self):
if self.x > 0:
return x
|
294b15673cbb073a1c6618c3513817626ee0bfef | sat5297/AlgoExperts.io | /Easy/NthFibonacci.py | 897 | 3.8125 | 4 | #Approach 1: Recursive
def getNthFibRec(n):
if n==2:
return 1
elif n==1:
return 0
else:
return getNthFib(n-1) + getNthFib(n-2)
# Time Complexity = O(2^n)
# Space Complexity = O(n)
#############################
#Approach 2: Memoization
def getNthFibMem(n, memoize={1:0, 2:1}):
... |
c3e834eef13cf670f8c4f4a2dd1ea7ae8a1fa1bf | BommakantiHarshitha-1/O11_Cp-Python | /Module-13/CP-ELECTIVE-02-wordwrap-Python/02-wordwrap-Python/wordwrap.py | 1,078 | 4.40625 | 4 | # Write the function wordWrap(text, width) that takes a string of text (containing only lowercase letters
# or spaces) and a positive integer width, and returns a possibly-multiline string that matches the
# original string, only with line wrapping at the given width. So wordWrap("abc", 3) just returns "abc",
# but ... |
630936f5057afb03f5b057cbb458a695c90080dc | ArtemKonnov/python_stepik | /2.6.3.py | 906 | 3.90625 | 4 | # Напишите программу, которая считывает список чисел lstlst из первой строки и число xx из второй строки, которая выводит все позиции, на которых встречается число xx в переданном списке lstlst.
# Позиции нумеруются с нуля, если число xx не встречается в списке, вывести строку "Отсутствует" (без кавычек, с большой букв... |
99f22b207bebc9b65baba6da5acee2e1c24987b3 | gurupunskill/Competitive-Programming | /archive/deprecated/week-1/program-1.py | 559 | 3.703125 | 4 | #!/bin/python3
# Question: https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
# O(n)
import sys
# Attempt 1:
def getRecord(s):
highest = s[0]
lowest = s[0]
high_count = 0
low_count = 0
for i in s:
if i > highest:
high_count += 1
highest = ... |
cab162bd2b0ae715227e5400c9f93b2a69b0d650 | giurgiumatei/Graph-Algorithms | /Lab3/UI.py | 1,898 | 3.546875 | 4 | from Domain import *
from copy import deepcopy
class UI:
def __init__(self,graph):#the UI is initialised with the graph
self.graph=graph
def print_menu(self): # prints the menu
print("11.Represent the graph using the set of inbound edges: ")
print("12.Represent the graph... |
579e8d59d0c96951e955d5d40e3f3939296879f1 | takafuji23/Python | /1-2-1.py | 230 | 4.0625 | 4 |
def is_anagram(_str1, _str2 ):
if "".join(sorted(_str1)) == "".join(sorted(_str2)):
return True
else:
return False
k = False
while k == False:
_str1, _str2 = map(str, raw_input().split(" "))
k = is_anagram(_str1, _str2) |
a251cd44e5068f33509dd4902fe07f6bd298fa21 | Marcos-Valencia/practicePython | /ex8rps.py | 1,275 | 4.09375 | 4 | print("WELCOME TO RPS")
user1 = str(input("who will be player 1?"))
user2 = str(input("who will be player 2?"))
game_status = str("ongoing")
user1_trn = str(user1) + ", Paper Rock or Scissors?"
user2_trn = str(user2) + ", Paper Rock or Scissors?"
print("This is RPS(Rock Paper Scissors)\n "
"To quite Type... |
69ae4f5791b0739975a8793bd19ce100524b6b9f | rsgmon/api_retrieval | /api_retrieval/setup_api_parameters.py | 1,238 | 3.890625 | 4 | import argparse
import json
from .config import APIConfig
import sys
def parse_args(args=None):
if not args: return None
parser = argparse.ArgumentParser(description='Path to the config file.')
parser.add_argument('path', help='Specify the absolute path of the config file.')
return parser.parse_args(ar... |
a20f18fcee5574fa3b4179bfb44f56455f247da5 | robertoItSchool/homework | /ex3.py | 836 | 4.3125 | 4 | # 3. Exercises with lists
list1 = [1, 3, 45, -7, 89, 3, 1, 12, 3, 3, 1, 3]
list2 = ["a", "cd", "b", "b", "f", "oj", "Zz"]
list3 = [1, 2, "a", 34, "bgh", "#"]
# a. eliminate all elements from list3
# list3.clear()
# b. eliminate all 3s from list1
print(list1)
while 3 in list1:
list1.remove(3)
print(list1)
# c. sort... |
b500fd177e68ab68c723c885b50dc05dbe3cf044 | evanSpendlove/CompetitiveProgramming | /Kattis/qaly.py | 594 | 3.859375 | 4 | # Kattis - Quality of Life Problem - Code: qaly
# Written by Evan Spendlove
def qaly():
numPeriods = int(input())
sumQaly = 0
period = numPeriods
while(period > 0): # For each period in the given number
[quality, numYears] = input().split(" ") # Gets the quality of life for the given period
... |
ab746bd82b53f855c4f107143b3e2cf3ce2da6a0 | artificial-cassiano/yapCAD | /examples/example7.py | 3,722 | 3.578125 | 4 | ## yapCAD poly() intersecton and drawing examples
print("example7.py -- yapCAD computational geometry and DXF drawing example")
print("""
In this demo we create open and closed polyline figures and calculate
intersections with lines and arcs. We draw the elememnts so we can
visibly confirm the correctness of the inte... |
7067f7dd24150f640409c644cc1856fe4a741e3b | ykushla/TES-P | /yk/data/frame.py | 598 | 4.03125 | 4 | class Frame:
# Frame class provides a structure for abstract datasets storage and representation
def __init__(self, names, items):
self.names = names
self.items = items
def print_to_console(self):
# prints the data to console
for name in self.names:
print(str(n... |
f86ada03d5ca1220de7162504a4fca811fdb2cf8 | esvarmajor/AICamp | /EsvarabalaK/MyPet.py | 577 | 3.625 | 4 | class MyPet:
def __init__(self, name):
self.name = name
self.trust=0
def pet(self):
print("Your pet " + self.name + " seemed happy that you pet them.")
def make_noise(self):
print("Noise noise noise.")
def spend_time(self,minutes_spent):
self.trus... |
426c00aa93e86cc3d8241c37528ccc8eca70b73b | couchjanus/python-fundamental | /index.str.test.py | 1,789 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# index.str.test.py
word = 'Help' + 'A'
print(word[4])
char = "C"
print(char[0])
print(word[0:2])
print(word[2:4])
print(word[:2]) # Первые два символа
print(word[2:]) # Всё, исключая первые два символа
# В отличие от строк в C, строки Python не могут быть изменены.
# Присваивание по п... |
d53f82ebdc1ec386356052c14f35c72a84b8bd77 | amadabhu/funtime | /Vowel_remover.py | 359 | 3.59375 | 4 | class vowel_remover:
def removeVowels(self, S: str) -> str:
vowels = list('aeiou')
s_ls = list(S)
seperator = ""
new_ls = []
for letter in s_ls:
if letter not in vowels:
new_ls.append(letter)
else:
continue
S = s... |
e00dff8735ecbcfc952e3111e7baa13d1d254c1a | Markboerrigter/webapp | /python_files/tagging_from_xml_Mark.py | 6,796 | 3.59375 | 4 | #import the needed packages
#a common package to work with data in Python
import pandas as pd
#used to do stuff with regex (for recognizing the product id)
import re
#used to read data from sql database
from pymongo import MongoClient
import importlib
def retrieve_links(csv_path,col_names,split_name):
"""
Get... |
1cddb3b74519620edbfe27461dc42d1b8997c182 | opwtryl/leetcode | /746. 使用最小花费爬楼梯.py | 1,371 | 3.796875 | 4 | '''
数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
示例 1:
输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
示例 2:
输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过... |
e9d109e49e4a2bb1c9c6b4251b647a510cdc0247 | rodrigosantosti01/LingProg | /Exercicio5/atv03.py | 4,919 | 3.828125 | 4 | # 3 Jogo de Blackjack: Faça um joguinho simples em Python.
# Aqui estão os requisitos:
# - Você precisa criar um jogo de BlackJack (21) baseado em texto simples
# - O jogo precisa ter um jogador contra um croupier automatzado.
# - O jogador pode desistr ou bater.
# - O jogador deve ser capaz de escolher o seu valor de ... |
31323f96134549f8c54de472a9670d4e592e55da | yanbinkang/problem-bank | /epi/arrays/even_odd.py | 466 | 4.1875 | 4 | def even_odd(A):
"""
Your input is an array of integers, and you have to reorder its entries so that even entries appear first
"""
next_even, next_odd = 0, len(A) - 1
while next_even < next_odd:
if A[next_even] % 2 == 0:
next_even += 1
else:
A[next_even], A[... |
ee6a52d8877a8ea0848657e5a0e9ad7c13c2be52 | alicelieutier/AoC2020 | /day1/day1.py | 759 | 3.671875 | 4 | import sys
def get_lines_as_number(filename):
f = open(filename)
return [int(line.strip()) for line in f.readlines()]
def find_pair(numbers, target):
seen = set()
for number in numbers:
missing_pair = target - number
if missing_pair in seen:
return(number, missing_pair)
... |
a5a36e6d3732b14be51a11a92493c4bb4951e0d3 | ehdrn3020/Python_Ref | /sum_multiples.py | 220 | 3.828125 | 4 | n=int(input("input the number "))
k=0
Sum=0
if n<1 and n>100:
print("input only 1 to 100 number")
elif n>=1 and n<=100:
while k<100:
k=k+n
Sum=Sum+k
print(k)
print(Sum)
else:
print("wrong number")
|
1762ee81fb7446d066ba07da7e6dee163ee496b9 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/Three_Restaurants.py | 826 | 4.5 | 4 | """9-2. Three Restaurants:
Start with your class from Exercise 9-1 . Create three
different instances from the class, and call describe_restaurant() for each
instance ."""
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name.title()
self.cuisine_type = cuisine_type... |
1674c5eb6caa015a1262d727a2be31663c2785be | Bondarev2020/infa_2019_Bondarev2020 | /kontr3-4.py | 615 | 3.640625 | 4 | money = int(input())
A = input().split(' ')
coins = [0] * len(A)
for i in range(len(A)):
coins[i] = int(A[i])
def make_exchange(money, coins):
for i in range(1, len(A[1]), 2):
C.append(int(A[1][i]))
ways_of_doing_n_cents = [0] * (money + 1)
ways_of_doing_n_cents[0] = 1
for coin in ... |
8ee6e4e4ed30ce7e0d5bbdf050c646e33bed09d1 | YiyingW/Leetcode | /20-Valid-Parentheses/solution.py | 677 | 3.71875 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
match = {"(":")", "[":"]","{":"}"}
stack = []
for sambol in s:
if sambol == '(' or sambol == '[' or sambol == '{':
stack.append(sambol)
else... |
7e394af4c075b84798292a95a6834a652345b1ae | tuhiniris/Python-ShortCodes-Applications | /patterns1/alphabet pattern_5.py | 294 | 4.0625 | 4 | """
Example
Enter the number of rows: 5
E E E E E
D D D D
C C C
B B
A
"""
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,number_rows+2-row):
print(chr(65+(number_rows-row)),end=' ')
print() |
ed8b212293c95e135579f659c6fee3333bf10949 | henrikforb/TDT4113-ProgrammingProject | /Keypad/Keypad.py | 2,209 | 3.5 | 4 | """
Docstring
"""
import time
import RPi.GPIO as GPIO
class Keypad:
"""
Docstring
"""
def __init__(self):
"""
Docstring
"""
self.keypad = [['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['*', '... |
62755a204003a11a153c0c35d263ceeaa11c3ee5 | Omar-Castillo/Advanced-Data-Storage-and-Retrieval-HW | /Instructions/oc_climateapp.py | 4,910 | 3.59375 | 4 | ###
#Flask Routes for Surf's Up Homework
###
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect
# import pandas and datetime
import pandas as pd
import datetime as dt
#import flask
from flask impor... |
2e97f7502cd586551e4ec18b93a56689dad7b245 | jabbalaci/AdventOfCode2019 | /day04/python/part2.py | 1,299 | 3.59375 | 4 | #!/usr/bin/env python3
from typing import Dict, List
def explode(n: int) -> List[int]:
digits = []
while n > 0:
digits.append(n % 10)
n = n // 10
#
return digits[::-1]
def is_password(digits: List[int]) -> bool:
ascending = True
for i in range(len(digits)-1):
a = dig... |
047293fa58bd1d960637d62d67627a77598a97d4 | Sheenazz/pythonlessons | /return-largest-numbers-in-arrays/lessons.py | 490 | 4.15625 | 4 | numbers = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
arrayOfLargestNumber = []
def findingLargestNumberInArrays(arrayOfArraysOfNumbers):
for arrayOfNumbers in arrayOfArraysOfNumbers:
max = arrayOfNumbers[0]
for number in arrayOfNumbers:
if number > max:
... |
f6699e6f81a69b99d027dedf402950955da4d9f4 | pjt3591oo/exchange-crawler | /test.py | 642 | 3.515625 | 4 | '''
https://datascienceschool.net/view-notebook/c645d51f308b4047aa78e8b343a2e181/
'''
from statsmodels.tsa.statespace.kalman_filter import KalmanFilter
import numpy as np
import matplotlib.pyplot as plt
model1 = KalmanFilter(k_endog=1, k_states=1,
transition=[[1]], selection=[[1]], state_cov=[... |
6af3a6abbd058e36731b8ba1fcae987af1cf1bb7 | ShahradX/Term4 | /Insert to mysql TKINTER.py | 2,017 | 3.625 | 4 | import tkinter
from tkinter import *
import mysql.connector as sql
def connection():
cnx = sql.connect(
user = 'root',
password = 'shahrad.f.99',
host = 'localhost',
database = 'legends'
)
cursor = cnx.cursor()
return cnx, cursor
def insert(first_name, last_name, code_... |
811f4a91e75ab9d4cda3fa24c15f2c0b24e9f6cb | renarfreitas/Coursera | /imprime_retangulo_cheio.py | 170 | 4.0625 | 4 | l = int(input("digite a largura: "))
a = int(input("digite a altura: "))
while a > 0:
for i in range(l):
print('#', end = '')
print()
a -= 1
|
e23134c82d6c05e649d4f96af8036647d028bb21 | code-tamer/Library | /Business/KARIYER/PYTHON/Python_Temelleri/strings-demo.py | 1,292 | 3.953125 | 4 | website = "http://www.sadikturan.com"
course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 Saat)"
# 1- "course" karakter dizisinde kaç karakter bulunmaktadır ?
result = len(course)
lenght = len(website)
# 2- "website" içinde www karakterlerini alın.
#result = website[7:10]
# 3- "website" içinde co... |
7c9a0879f6895a9c289a88e3710be09ad1c4a2bd | mxmoca/python | /rank_choice_lab.py | 7,273 | 3.84375 | 4 | from matplotlib import pyplot as plt
from pprint import pprint
# This will read in the necessary data
# make sure avengers.csv is in the same directory
# as this python file.
# You can get the file here: https://raw.githubusercontent.com/mks22-dw/python/main/avengers.csv
# avengers.csv represents the results of ran... |
84068b82291e6980a980258d0afec505eee065a1 | lduran2/dev.array-problems.in-python | /p01A-missing-number | 2,684 | 4.28125 | 4 | #!/usr/bin/env python3
r'''
./p01A-missing-number
This program finds the missing number in a list of integers.
* by: Leomar Duran <https://github.com/lduran2>
* date: 2019-06-28T19:00ZQ
* for: https://dev.to/javinpaul/50-data-structure-and-algorithms-\
problems-from-coding-interviews-4lh2
'''
import random # fo... |
28d24a5a847d7b83235c52dda88308bca87641c9 | scottrob/palindrome | /palindrome.py | 1,023 | 4.1875 | 4 | import re
import os
def is_palindrome(sentence):
sentence = re.sub(r'[^A-Za-z]','',sentence).lower()
if len(sentence) != 0 and sentence[0] == sentence[-1]:
return is_palindrome(sentence[1:-1])
elif len(sentence) == 0:
return True
else:
return False
def its_is_palindrome(sentenc... |
5e53d20e66562ffef6d7db2317a890289b9d50e3 | kukuhyudhistiro/algpython | /readingItemList.py | 797 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 21 15:33:34 2021
@author: x220
"""
#1. Mencetak seluruh item List menggunakan Loop
namakota = ['A','B','C','D','E']
#a. While
print(" Menggunakan WHILE ------------------------------")
i = 0;
while i < len(namakota):
print(namakota[i])
i = i + 1;
... |
c6d9de92457a3e6df52f43b679d6c088d5f33128 | ProximaDas/HW07 | /HW07_ex10_02.py | 1,000 | 4.1875 | 4 | # I want to be able to call capitalize_nested from main w/ various lists
# and get returned a new nested list with all strings capitalized.
# Ex. ['apple', ['bear'], 'cat']
# Verify you've tested w/ various nestings.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass ... |
cdce163717590f63a104d181f4aa2d1ab1205225 | aatul/Python-Workspace | /068_SearchFile.py | 501 | 4.03125 | 4 | """
Serach File in Current Folder:
WAP to search '.txt' files in current folder.
We can change file type/name and path according to the requirements.
"""
import os
# Get the directory that the program is currently running in
dir_path = os.path.dirname(os.path.realpath(__file__))
for root, dirs, fil... |
377cbc5f1e647ab3882c1758dcdfe276151cbfc3 | lobsterkatie/CodeFights | /Arcade/AtTheCrossroads/metro_card.py | 2,279 | 4.75 | 5 | """
AT THE CROSSROADS / METRO CARD
You just bought a public transit card that allows you to ride the Metro for a
certain number of days.
Here is how it works: upon first receiving the card, the system allocates you a
31-day pass, which equals the number of days in January. The second time you
pay for the card, your p... |
0a6ff307ce961e107ff805f4a973527e9c0615fe | NishantSinghChandra/test-python | /test-home.py | 176 | 3.515625 | 4 | def last2(str):
count = 0
for i in xrange(len(str)-2):
print str[i:i+2], str[-2:]
if str[i:i+2] ==str[-2:]:
count+=1
return count
print last2('xaxxaxaxx')
|
2fc12dd6d7f7b2701b2e1decbea25887057d1485 | silversurfer-gr/Python | /BlinkLED.py | 1,073 | 3.875 | 4 | import RPi.GPIO as GPIO
import time
ledPin = 5 # RPI Board pin17
dauer = 5
def setup():
print("setup ist entert")
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.output(ledPin, GPIO.LOW) # Set ledPin low to off led print ('using pin%d'%ledPin)
# Numbers GPIOs by physi... |
35ca57cac32bb10115cbf44f4b1827327f4456a4 | Eric-programming/PythonTutorial | /PyBasics/0_list.py | 1,286 | 4.125 | 4 | # List items are ordered, changeable, and allow duplicate values.
# Define List
my_list = [1, 2, "3"]
my_list = list(["i1", "i2", "i3"])
my_list = [1, 2] * 10
# Access / mutate item
my_list = ["i1", "i2", "i3"]
second_item = my_list[1] # access second item
last_item = my_list[-1] # access last item
second_last_item... |
62014e241e885fb3d336ca16b97cb74af7e320fd | Strd79/Class_Work | /week_01/day_04/start_code/modules/output.py | 778 | 3.59375 | 4 | def print_task(task):
print(f'Description: { task["description"] }')
print(f'Status: { "Completed" if task["completed"] else "Incomplete"}')
print(f'Time Taken: {task["time_taken"]} mins')
def print_list(list):
for task in list:
print_task(task)
def mark_task_complete(task):
task["complete... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.