blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
eeb053ac1dfe12aaa104ab430f00a63f8e0b42b9 | Therealchainman/LeetCode | /problems/cousins_in_binary_tree/solution.py | 1,118 | 4.09375 | 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
from collections import deque
from collections import defaultdict
class Solution:
def isCousins(self, root: TreeNode,... |
76401d79a49833bdc55c5d6f28b8c555f8cf889a | jlehenbauer/CS106A | /moonweight.py | 971 | 4.4375 | 4 | # Constants are a good way to always have things you need on hand!
# They are also great for code readability.
# The weight of something on the moon is 16.5% of it's weight on earth.
EARTH_TO_MOON_RATIO = 0.165
def earth_to_moon_weight():
# To find out how much someone weighs on the moon,
# we need to know their ter... |
97ede2827bca7afb0762b69b4c0edc34c6c0ffaa | syurskyi/100DaysOfCode_i_Python | /01-03-datetimes/datetime_timedelta.py | 656 | 3.703125 | 4 | #!python3
from datetime import datetime
from datetime import timedelta
t = timedelta(days=4, hours=10)
print(t.days)
# 4
print(t.seconds)
# 36000
# print(t.hours)
# Traceback (most recent call last):
#File "<pyshell#119>", line 1, in <module> t.hours
# AttributeError: 'datetime.timedelta' object has no attribu... |
73f52e9780fd697ebd1e5a086433e4020ffcf055 | Gerrydh/MPP-Recursion | /counter.py | 429 | 3.65625 | 4 | class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high: #Stop condition of iteration
raise StopIteration #Stop condition of iteration
el... |
72efbe9b5fdf04b702b66d4141d8f72c72660be2 | aminkhalaj73/OOP | /Bank account/Bankaccount.py | 1,660 | 3.75 | 4 | import datetime
import pytz
class Account(object):
#simple account class with balance
@staticmethod
def _current_time():
utc_time = datetime.datetime.utcnow()
return pytz.utc.localize(utc_time)
def __init__(self , name , balance):
self.__name = name
self.... |
de4c15e14a32135c0f6bba9be2fa60531abeee38 | Aaron-Nazareth/ChocolateMinds-Python-beginner-course | /Functions...functions...functions.py | 1,161 | 4.25 | 4 | # 1. Write a function which has the following requirements:
# - takes in name of the person;
# - expects a four or more characteristics about him/her
def person_characteristics(name, *characteristics):
print(f"Hello {name}, you have the following characteristics: {characteristics}")
person_characteristic... |
49583a9eeea58799c98ddb7f885a4ee24b6f2d3d | lilyfofa/python-exercises | /exercicio14.py | 178 | 3.8125 | 4 | print('---'*15+'\nConversor de temperaturas\n'+'---'*15)
c = float(input('Qual a temperatura em °C? '.replace(",",".")))
print(f'{c}°C equivalem a {c*1.8+32}°F.\n'+'---'*15)
|
dc33ede235ce98ec68eef676f265a974b966ab8b | ZhiCheng0326/LeetCode-Practices | /solutions/130.Surrounded Regions.py | 1,252 | 3.703125 | 4 | """
1) Start dfs from boundaries with letter "O"
2) Mark all "O" connecting with boundaries to "#", as it is not surrounded by "X"
3) dfs completed
4) loop through each grid, change "O" to "X" and "#" to "O"
"""
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anyth... |
c827fea3806da2a2bfd48585e82799981d00f256 | ccyit/learning-python3 | /chapter-7循环/parrot.py | 145 | 3.8125 | 4 | # message = input("请输入你的名字:")
# print("Hello, " + message + "!")
age = input("How old are you?")
age = int(age)
print(age > 11)
|
32cc564b42b987c7e5a207c2d1c1de2267f10b82 | xujackie1993/TheAlgorithms | /BinarySearch/binary_search.py | 1,677 | 3.828125 | 4 | """
当 while (left < right) 时,对应的更新式是 left = middle + 1 , right = middle
当 while (left <= right) 时,对应的更新式是 left = middle + 1,right = middle - 1
"""
class Solution(object):
def binary_search(self, A, target):
left = 0
right = len(A) if A else 0
if not A:
return -1
while... |
f298c73853c6d97637a6719d28616ecdcc388666 | arafuls/Python-367 | /Python-367/Periodic-Table/elements.py | 3,439 | 3.890625 | 4 | def build_periodic_table(filename="periodic_table.txt"):
input_file = open(filename, 'r')
table = dict()
for element in input_file:
tokens = element.split()
table[tokens[2]] = (tokens[1], int(tokens[0]), float(tokens[3]))
return table
def menu_options():
print('1) Search by sy... |
7035d7da815ffc9664d118c3112c14d96bbf71cb | melbinmathew425/Core_Python | /collections/dictionary/word_count.py | 203 | 3.859375 | 4 | line="hai hello hai hello hai"
word=line.split(" ")#split function used to split a sentence into words
dic={}
for i in word:
if (i not in dic):
dic[i]=1
else:
dic[i]+=1
print(dic) |
b1c08daa27168fcf95083accda80f172fae474a7 | bethsecor/python-exercisms | /pangram/pangram.py | 222 | 3.875 | 4 | def is_pangram(string):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
string = string.lower()
letter_count = 0
for letter in alphabet:
if letter in string: letter_count += 1
return letter_count == 26
|
2dd27fde04827b9a8c8379ce8935d145d76007d5 | jayprakashprasad/Python-Practice | /def.py | 921 | 3.734375 | 4 | class myclass():
def __str__(self):
return "4"
print(myclass())
def my_function(fname,lname):
print(fname + lname+" Refsnes")
my_function("Emil","ee")
my_function("Emiel","ee")
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias"... |
e5a2c6eb01929294008f61b4e6c50697be1c7ee3 | lonewolfcub/Python-Crash-Course | /Part-I/Chapter 10 - Files and Exceptions/c10e12_favourite_number_remembered.py | 1,171 | 3.96875 | 4 | import json
# Load favourite number, if it has been stored previously.
# Otherwise, prompt for favourite number and store it.
def get_stored_favourite_number():
"""Get stored favourite_number if available"""
filename = 'favourite_number.json'
try:
with open(filename) as f_obj:
favourit... |
f78a17ac7abb55ebd806be28ac805768ff6fd36d | astory/cs4740_4 | /packer.py | 1,125 | 3.859375 | 4 | #!/usr/bin/env python
# Tools to fit answers into fixed-byte data.
def pack(data, length, pack=False):
"""
Pack data (a sorted list of (score, candidate) into length bytes.
If pack = True, will continue to look for smaller words to fit in until
there is no space or no more words. If pack = False, stops at the fi... |
fb1b73ab4470162673b5b27d475cbc6148cc401b | kkashii/Python-NRS568 | /Class 2/Challenge2.4.py | 186 | 3.96875 | 4 | # User input
age = int(input('What is your age?'))
if age < 65:
r_age = 65 - age
print("You can retire in {0} years.".format(r_age))
else:
print("You are retired!")
|
054d9102007fe6848f2b550ff5b045a077c90f77 | njaccardo/project-euler | /problem10.py | 839 | 3.890625 | 4 | # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
import pdb
import numpy as np
# First find all the prime numbers less than 2 million
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n % i == 0:
return False
return True
# loop to find all primes
p... |
d14f72b19bbb109b56675fe346661f4be15846fd | Jun0414/Algorithm | /Algorithm_theory/Chapter_08.py | 4,315 | 3.515625 | 4 |
# 예제 8-1 (피보나치 함수 p.210)
# 일반 재귀적 구현
def fibo(x):
if x == 1 or x == 2:
return 1
return fibo(x - 1) + fibo(x - 2)
print(fibo(4))
# 다이나믹 프로그래밍(탑다운) 재귀적 구현
# 한번 계산된 결과를 메모이제이션하기 위한 리스트 초기화
d = [0] * 100
def d_fibo(x):
# 호출함수 확인
print('f(' + str(x) + ')', end=' ')
# 종료 조건
if x == 1 ... |
60d52326958b77b73b7244b8bd8546ee282051b6 | enitink/prj | /generic/codes/prData/pythonCode/arc.py | 598 | 3.90625 | 4 | from TurtleWorld import *
import math
def Arc(t, radius, deg):
t.delay = 0.01
circumference = 2 * math.pi * radius
n = circumference / 2
d = 360 / n
temp = 360 / deg
n = int(n / temp)
print n
for i in range(n):
fd(t, n)
lt(t, d)
def arc(t, r, angle):
arc_length = 2 ... |
2ca87d11f7da30db5c8be6d7b703d783c8da1a38 | udhay18/My-Captain-Python-Tasks | /PYT4.py | 111 | 3.859375 | 4 | #Upper_Lower
n=input("Enter a Word:");
print("Upper Case : ",n.upper());
print("Lower Case : ",n.lower());
|
ca1df296e9c246878e369afa6fe639cdfc959ed5 | thecodearrow/Algorithms | /Data Stuctures/Trees/TopView.py | 945 | 4.09375 | 4 | #https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1
#Combines Level Order Traversal + Vertical Order Traversal
def verticalOrder(root):
queue=[root]
hd_given_ele={root.data:0} #horizontal distance
while queue:
ele=queue.pop(0)
if(ele.left):
l=ele.left.data
... |
d92b597ab8e48c1687560271dd690ea80bce1300 | jaewilson07/course-material | /exercices/070/solution.py | 197 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 22 17:24:00 2014
@author: Catherine
"""
for i in range(97, 123):
for j in range(97, 123):
if i != j:
print(chr(i) + chr(j))
|
8d9df43d7e4fd9042c9e127104dd3e2ac9b15643 | icccee/excersise | /d15.py | 382 | 3.921875 | 4 | #:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
def Grade(score=0):
if score >= 90:
return "A"
elif score > 60:
return 'B'
else:
return 'C'
def main():
print(Grade(100))
print(Grade(89))
print(Grade(60))
print(Grade(70))
if __name__ == "__main__":
main() |
b556e19b2ff574b2ba8d1529dc161ab3bc5132ce | JDChiang/sc-project | /stanCode_Projects 2/break_out_game/breakoutext.py | 1,599 | 3.578125 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao.
Name: Jo-Di(Frank), Chiang
"""
from campy.gui.events.timer import pause
from breakoutgraphicsext import BreakoutGraphics
FRAME_RATE = 1000 / 100 # 100 frames per second
NUM_LI... |
c4f34fd43078d6762cac51b34e8005ba9de24bbd | aduV24/python_tasks | /Task 21/list_types.py | 227 | 4.125 | 4 | # In this program we are just working with lists
friends_names = ["Dirk", "Vuyo", "Cameron"]
print(friends_names[0])
print(friends_names[2])
print(f"The length of the list is {len(friends_names)}")
friends_ages = [18, 19, 22]
|
8ed3361b629eadd7bde43b05fbac101df8f645c9 | kishanp519/CS100 | /Homework/Dog.py | 640 | 3.828125 | 4 | """
Kishan Patel
CS 100 - Section 019, Fall 2019
HW 11 - December 2nd, 2019
"""
class Dog:
"""Declaration of Dog Class"""
species = "canis familiaris"
def __init__(self, dogName, dogBreed):
self.name = dogName
self.breed = dogBreed
self.tricks = []
def teach(self, trick):
... |
650957cb81f39861e4801e03706df9486e8b5de1 | klin0816/leetcode | /343.py | 733 | 3.59375 | 4 | '''
343. Integer Break
https://leetcode.com/problems/integer-break/submissions/
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
note: 2 <= n <= 58
'''
# def function():
def integerBreak(n):
if n == 2: return 1
result = 0
for i in range(2... |
4801815060666081a75b69070de397256fb35c27 | hubbardgary/AdventOfCode | /day10.py | 1,829 | 4.21875 | 4 | # --- Day 10: Elves Look, Elves Say ---
#
# Today, the Elves are playing a game called look-and-say. They take turns making sequences by reading aloud the
# previous sequence and using that reading as the next sequence. For example, 211 is read as "one two, two ones",
# which becomes 1221 (1 2, 2 1s).
#
# Look-and-say ... |
c56e4341d2e76244a61838adf8b548f14e7c3c16 | Shane-Frost/zooapp | /zooapp.py | 2,393 | 3.734375 | 4 |
#importing flask, cause you need flask to host the web server thingy.
# see https://flask.palletsprojects.com/en/2.0.x/quickstart/
from flask import Flask, request,Response
import json
app = Flask(__name__)
#Placeholder for a temporary database until we're learned how to do it.
zoo_animals = {
"1": {"Animal": "L... |
99d46fd4b88e19fbfdb0d51e188bba1e8ad1fd15 | AK-Vitae/Python-Practice | /basics/user_input/greeter.py | 592 | 4.28125 | 4 | name = input("Please enter your name: ")
print(f'\nHello, {name}!')
prompt = "If you tell us who you are, we can personalize the messages you see."
print("\n")
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f'\nHello, {name}!')
print("\n")
age = input("How old are you? ")
age = int(age)
greeter_ag... |
bfe553596ad3ae99515de893cd841668ab840512 | tonerqq/math | /area.py | 3,991 | 4.15625 | 4 | # AREA CALCULATOR
# @author tonerqq
# @date 16 Jan 2021
# rectangle & square
# various triangles
# circle
# import math lib & sys
import math
import sys
# print shape choices ASCII
print ""
print(" AREA CALCULATOR : SELECT SHAPE NUMBER")
print(" . +-----+ x x")
print(" /\ | /| | ... |
8c85a9473f5f806d6f1eebc27fd15d9193be2dd7 | fanmaoxueyuan/web0910 | /tools/datahandler.py | 1,589 | 3.515625 | 4 | """
主要存放数据出路的方法
"""
import os
from openpyxl import load_workbook,Workbook
from openpyxl.worksheet.worksheet import Worksheet
import csv
class FileHanlder:
def __init__(self):
self.root_dir = os.path.join(os.path.dirname(__file__),'../')
def write_excel(self,filepath,sheetname, row,col,value):
... |
daec2092043b67d43881df2457e3db0806deb43d | gmdzy2010/leetcode_cn_record | /leetcode_150.py | 578 | 3.84375 | 4 | def eval_reverse_polish_notation(tokens):
operation_map = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: int(x / y),
}
stack = []
for token in tokens:
if token in operation_map:
y, x = stack.pop(), stack.... |
f8fdc55934f1c51c16470e4f030964fde8c4ecc7 | KhAoS182/Programacion | /Primer trimestre/P4/pruebas.py | 141 | 3.78125 | 4 | a = int(input("Ingresa un numero: "))
b = True;
for i in range (2,a-1):
if a%i!=0:
x = 1
else:
b=False
print("ha entrado")
print(b)
|
d1e074172237db44c67bd07bd37b924ce9054274 | JoseALermaIII/python-tutorials | /pythontutorials/books/AutomateTheBoringStuff/Ch15/P6_multithreading.py | 350 | 3.734375 | 4 | """Multithreading
This program demonstrates :class:`threading.Thread` on :func:`print`.
"""
def main():
import threading
# Passing Arguments to the Thread's Target Function
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'], kwargs={'sep': ' & '})
threadObj.start()
if __nam... |
30c8fcc920627d518ff6f1a78ef16a2a6debd093 | guozhaoxin/leetcode | /num101_200/num171_180/num172.py | 1,111 | 4.125 | 4 | #encoding:utf8
__author__ = 'gold'
'''
Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic ... |
e43afb549a18c82b4b4f4d94e05a965299b3c94b | RenanGouveia/LingProg | /2018 10 02/ativ08.py | 341 | 3.9375 | 4 | #8 Defna a função junta que recebe como argumentos duas listas de números
#inteiros w1 e w2 e devolve a concatenação de w1 com w2 .
#Ex: junta([1,2,3],[4,5,6]) = [1, 2, 3, 4, 5, 6]
#Ex: junta([],[4,5,6]) = [4, 5, 6]
#Ex: junta([1,2,3],[]) = [1, 2, 3]
def juncao(lista1,lista2):
return lista1+lista2
print(juncao([... |
4f21a4315dc21d89e826259a46320a3c07a50264 | joshuadams/Marvel-Heroes | /main.py | 774 | 3.9375 | 4 | People ={
'AAA' : 'John',
'ABA' : 'Matthew',
'ABB' : 'Joesph',
}
quit = 'Y'
while quit == 'Y':
q1 = input('Do you like Minecraft? \nA) Yes \nB) No \n')
q2 = input('Favorite Sport? \nA) Soccer \nB) Baseball \n')
q3 = input('Favorite Movie? \nA) Harry Potter and the Goblet of Fire \nB) Avengers: Endgame \n... |
6465869d74fb5aadacab922950019e5db41098f4 | lukaszklusek/AIiR_1115_komiwojazer | /TSP_MPI/Path.py | 602 | 3.546875 | 4 | __author__ = 'Wiktor'
class Path(object):
def __init__(self,numCities):
self.length = 0
self.visited = 1
self.city = []
for i in range(0,numCities):
self.city.append(i)
def set(self,len,city,visited):
self.length = len
self.city = city
self.v... |
88c50f0284c3a32b2957cfd97d8a3c6e393de748 | KakTyc74/CardStone | /allclasses.py | 1,027 | 3.734375 | 4 | class Card(object):
'''Base class for one card'''
def __init__(self, name, mana, atk, hp):
self.name = name
self.mana = mana
self.hp = int(hp)
self.atk = atk
def attack(self, enemy):
enemy_hp = int(enemy.hp)
enemy_hp -= int(self.atk)
self.hp -= int(ene... |
ba8ab6155ae6a2d8f426f5bc66f56e2c5ca230ec | claywong/ud120-projects | /naive_bayes/nb_author_id.py | 1,712 | 3.53125 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email... |
9821bd7a14119dae7a18e9702d42645bab500a56 | da-ferreira/uri-online-judge | /uri/2373.py | 206 | 3.609375 | 4 |
bandejas = int(input())
copos_quebrados = 0
for i in range(bandejas):
latas, copos = map(int, input().split())
if latas > copos:
copos_quebrados += copos
print(copos_quebrados)
|
5e94ed0ab84ea83676f59723555e03f3b01150ab | mh70cz/py_old | /challenges/coderbyte/ChessboardTraveling.py | 1,864 | 4.78125 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
https://coderbyte.com/editor/Chessboard%20Traveling:Python
Using the Python language, have the function ChessboardTraveling(str)
read str which will be a string consisting of the location of
a space on a standard 8x8 chess board with no pieces on the board
along ... |
8ff0679b711db2e5f2df73b0030bf66292a097f0 | josemariacastillo/ejercicio_xml | /ejercicio3.py | 604 | 3.75 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
#Pedir una cadena por teclado y mostrar todos los Festivales
#cuyo nombre empieza por dicha cadena, junto con su URL donde su ubica el festival.
from lxml import etree
datos=etree.parse("festivales.xml")
cad=raw_input("Introduce un festival: ")
festivales=datos.xpath(... |
802ea116c3681110bbdd18c01fc0547c2b1ffef3 | afcarl/WordRepresentableGraphs | /3uniformwordcount.py | 2,330 | 3.625 | 4 | '''
To count the number of 3-uniform words representing the cycle graphs.
It is known that this number is >= 4n.
Author: Ameya Daigavane
'''
n = 4
counts = [0] + [3 for i in range(1, n + 1)]
string_array = [0] * (3 * n)
wordcount = 0
validwordcount = 0
# prints string_array as a string
def print_string... |
5b9846c57baffed7f5a0d67eeba9a0c37bc9bcda | layueyu/flask-base | /base/commons/page.py | 1,471 | 3.6875 | 4 | """
分页
"""
from flask import current_app
class Page:
"""
分页
"""
def __init__(self):
self.__page = 1 # 当前页
self.__limit = 10 # 每页大小
self.__total_page = 10 # 总页数
self.__total_count = 0 # 总记录数
self.__list = []
@property
def page(self):
return... |
b70dbecfcefb146957c5ddd57c2113af1fa1d012 | ZhengLiangliang1996/Leetcode_ML_Daily | /Tree/778_SwimInRisingWater.py | 1,643 | 3.640625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 liangliang <liangliang@Liangliangs-Air>
#
# Distributed under terms of the MIT license.
class Solution(object):
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
... |
2bbfc014f69a7fc1f71d73a861d95b838b7e6247 | poojagmahajan/python_exercises | /ds_and_algo_educative/Singly_Link_List/Reverse_String_stack.py | 615 | 4.15625 | 4 |
### logic --- push all input)string characters in stack...then pop them from stack as a reverse string
from stack import Stack
def reverse_string(stack, input_str):
for i in range(len(input_str)): ## push string on a stack
stack.push(input_str[i])
rev_str = "" ## create empty ... |
6e22ca35c8b77d5d61a99ec9d67344b5ec9d31f5 | shankar7791/MI-10-DevOps | /Personel/Chandrakar/Python/12march/pro_02.py | 287 | 4.09375 | 4 | def convert(x):
return list1[0]+list1[1]+list1[2]+list1[3]+list1[4]+list1[5]+list1[6]+list1[7]+list1[8]+list1[9]+list1[10]
list1 = (['p','r','o','g','r','a','m','m','i','n','g'])
print(f"Before the convert list is : {list1} ")
print(f"after the convert list is : " ,convert(list1)) |
4fb6c4ea0fd01ae81a31e9af0e0b1574e929d121 | hi0t/Outtalent | /Leetcode/151. Reverse Words in a String/solution1.py | 192 | 3.6875 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
result = []
for word in s.split(' ')[::-1]:
if word: result.append(word)
return ' '.join(result)
|
34b80505a693e49bc8c9958be23a9b83fce8904d | harshchoudhary1998/Pytthon | /gettersetter.py | 330 | 3.59375 | 4 | class oops:
def setName(self,name):
self.name=name
def getName(self):
return self.name
def setMarks(self,marks):
self.marks=marks
def getMarks(self):
return self.marks
s=oops()
s.setName(input("enter the name."))
s.setMarks(int(input("enter the marks")))
print("{} and {}".format(s.getName(),s.ge... |
ae1e1307cb3f6e4e7fe981de582a68bf459caf3e | Shiv2157k/leet_code | /goldman_sachs/reorganize_string.py | 1,068 | 3.78125 | 4 | import heapq
class String:
def re_organize(self, S: str) -> str:
"""
Approach: Heap
Time Complexity: O(N log A)
N - length of string
A - size of alphabet
Space Complexity: O(A)
:param S:
:return:
"""
reorganized_string = ""
... |
691db098ed5c25f882afd33d6b6ffb6b9233019d | shreyadharmadhikari/AI-ML-honours | /Shreya_Assignment1.py | 6,583 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# <h2>Assignment No : 1</h2>
# In[10]:
# Name : Shreya Dharmadhikari
# Roll No : 31014
# Batch : T1 Batch Computer
# Title : Calculate Mean, Variance, Standard Deviation, Covariance, Correlation and Standard Error.
# Problem Statement : Compute Estimators of the main statistica... |
2ea46c2110373d7818e4fe02e3a01ab4025ea531 | Raj-kar/Python | /Build-in Python functions/sorted.py | 2,564 | 4.5 | 4 | # sorted can use for sort list,tuple,dict .
# it's return a sorted copy of the input, not change the original list/tuple or dict !
# yoh ! let's see ~
nums = [55, 4, 1, 9, 65] # list
print(sorted(nums)) # [1, 4, 9, 55, 65]
print(sorted(nums, reverse=True)) # [65, 55, 9, 4, 1]
# <-----------------------------... |
cfed757e4409452bab50a72a2d60fd06f75f5792 | eric496/leetcode.py | /union_find/721.accounts_merge.py | 2,633 | 4.5 | 4 | """
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email tha... |
4b09c65f9d5c4ccf5e3b80a277e88e263c85ed99 | jezhang2014/2code | /leetcode/LengthofLastWord/solution.py | 241 | 3.515625 | 4 | # -*- coding:utf-8 -*-
class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
w_list = filter(None, s.split())
if not w_list:
return 0
return len(w_list[-1])
|
b967b956ae64ecbe651a19966f56a29b92e39c06 | ManavParmar1609/OpenOctober | /Miscellaneouos/Python/InventoryManagementApp/database.py | 2,817 | 3.796875 | 4 | # by: Imakshat47
import sqlite3
import config as cfg
# DB Interactions
class Database:
# Connect to DB
def conn(self):
print("Database: conenction method called")
con = sqlite3.connect(cfg.db_name)
cur = con.cursor()
query = "create table if not exists " + cfg.table_name + \
... |
d6e0df097331b2a9540d1d45dbc1c0c67d8d85fa | SensenLiu123/LeetCode | /Rotate Array.py | 572 | 3.578125 | 4 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
self.reverse(nums, 0, len(nums) -1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) -1)
... |
7d0e6c228fd5de571ace0495bb962a6c0ea2c407 | ash/amazing_python3 | /130-finally.py | 298 | 3.6875 | 4 | # Demonstrating the "finally" keyword
def f():
try:
print(1/0)
except:
print('Exception')
return 0
finally:
print('Finally')
# The finally block will work
print('Return') # will not be printed
return 1
print('Start')
f()
print('Finish') |
77e5d7f95735a2f230b1c906c9c5ff8c53098a91 | ixuhan/PythonStudy | /SortAlgor.py | 3,190 | 3.796875 | 4 | # 选择排序
def chooseSort(a):
for i, val in enumerate(a):
min = i
for j in range(i + 1, len(a)):
if a[min] > a[j]: # 找到最小位置的下标
min = j
a[i], a[min] = a[min], a[i] # 交换首位和最小位
# 插入排序
def insertSort(a):
for i, val in enumerate(a):
for j in range(i, 0, -1)... |
988f32a2c9adc5c3e066a32e1fd456fa44a83a07 | DariaMikhailovna/Algorithms | /Graphs/dijkstra_algorithm.py | 1,609 | 3.765625 | 4 |
class Dijkstra:
inf = float('inf')
def __init__(self, adjacency_vector, start_vertex):
self.adjacency_vector = adjacency_vector
self.start_vertex = start_vertex
self.vertex_count = len(adjacency_vector)
self.weight = [self.inf] * self.vertex_count
self.used = [False] * ... |
c9f695ee02cafe171a6a252b5dd5a96f2c50fdf7 | Keerthanavikraman/Luminarpythonworks | /pythonprgm/bankaccount2.py | 191 | 3.75 | 4 | fixed_amount= 10000
a=int(input("enter the amount to withdraw"))
print("ac balance",fixed_amount-a)
if a<fixed_amount:
print(" sufficient balance")
else:
print("insufficient balance") |
7e4caf6cbd9f93a401f1e8060f5c8f61080d1327 | MakrisHuang/LeetCode | /python/684_redundant_connection.py | 985 | 3.671875 | 4 | class Solution:
# Time Complexity: O(N)
# Space Complexity: O(N)
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
# apply union find
def find(parent, curr):
if parent[curr] != curr:
parent[curr] = find(parent, parent[curr])
retur... |
d67b680114c051e38a009e0062df6f517bfff269 | hpapucha/Python-Programs | /StudentsUnitTests/student.py | 791 | 3.734375 | 4 |
import unittest
class Student:
#__init__ method
def __init__(self, username, last, first, phone, yr):
self.username = username
self.last = last
self.first = first
self.phone = phone
self.yr = yr
if self.yr < 1:
self.yr == 1
elif sel... |
220d24e004bdf046beadc4cf63ca5def9216cf4f | hans0517/hans | /week3/ImplementQueueusingStacks.py | 1,116 | 4.25 | 4 | class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.write = []
self.read = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.write.ap... |
b52c0aff68e957fb6cc22a55893ae39c391ebbb7 | NodirMN/python_dars | /Dars/dars_1.py | 583 | 3.546875 | 4 | print('hello world')
print('hello world')
print("hello'\"' world")
print("hello'\\' world")
print('hello"\\" world')
print(2+3)
print("Hello,"+ "Nodir") #bir xil rezultat
print("Hello,", "Nodir")
print("Hello,", "Nodir", "and Xumora")
print("Hello,", "-Nodir", "-and Xumora")
print("Hello,", "Nodir", "and Xumora", sep... |
e0aab4888b1c2faef4b5d0f70d4d58d551d1b420 | seniroberts/Expressions | /Python/MiniProjects/Rewards/Rewards.py | 1,052 | 3.875 | 4 |
# A function to extract contents from a txt file into an array
def readTextFile(fileName):
an_array = []
with open(fileName, "r") as the_file:
the_file = the_file.readlines()
for value in the_file:
an_array.append(value.rstrip("\r\n"))
return an_array
# Main program starts here
def ... |
edd925b64183e785ff58fef1c4a31619d008367f | rbutt15/python-scripts | /snap!.py | 286 | 3.9375 | 4 | one=int(input("Please enter number 1:"))
two=int(input("Please enter number 2:"))
three=int(input("Please enter number 3:"))
if (one==two) :
if (two==three) :
print("SNAP!")
else:
print("They do not all match")
else:
print("They do not all match")
|
4b84239bd55909cb074ad61be9a9cd71344d0347 | robinsxdgi/Machine-Learning | /Gaussian-Mixture-Model-with-EM-Algorithm/gmm_est.py | 5,685 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# EECS 349 Machine Learning
# Ding Xiang
from __future__ import division
import numpy as np
import sys
import scipy.stats
import math
import matplotlib.pyplot as plt
def main():
"""
This function runs your code for problem 2.
You can also use this to test you... |
dcd2f2327b4d45ce88cc5116a12d86d31f5bc7a8 | lnminh58/All_Work_Space | /python/core/index.py | 1,923 | 4.1875 | 4 | # len(), print()
# a = [3, 4]
# b = len(a)
# print(a)
# print(b)
# input()
# print('what is your name');
# myName = input()
# greeting = 'It is good to meet you, {}'
# print(greeting.format(myName))
"""
is , is not
"""
# print(42 == 42.0, True == True)
# print(42 is 42.0)
# a = True
# if a is True:
# print('hi')... |
cf1e3aa630ec34233b352168bd4b0818565883cb | sofianguy/skills-dictionaries | /test-find-common-items.py | 1,040 | 4.5 | 4 | def find_common_items(list1, list2):
"""Produce the set of common items in two lists.
Given two lists, return a list of the common items shared between
the lists.
IMPORTANT: you may not not 'if ___ in ___' or the method 'index'.
For example:
>>> sorted(find_common_items([1, 2, 3, 4], [1,... |
6992bd915313f42ad9f727ec7cbdd757327bd2eb | yemao616/summer18 | /Google/2. medium/474. Ones and Zeroes.py | 3,027 | 3.859375 | 4 | # In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
# For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
# Now your task is to find the maximum number of... |
c17c955dfa4d23ad066245aa8ad7c29407bc001c | jcasarru/coding-challenges | /python/9.py | 1,589 | 4.375 | 4 | '''
Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise)
Extras:
Keep the game going until the user types “exit”
Keep... |
631d198be35f1eedc3720a5a22b1a0fcd333f5fc | vvbaliga/PythonCourse | /MitX-python/fortest.py | 191 | 3.734375 | 4 | n=0
for n in range(5):
print(n)
mysum=0
for n in range(7, 10):
mysum += n
print(mysum)
mytest=0
for n in range(5,11,2):
mytest += n
if(n==7):
break
print(mytest)
|
2d5536ecbfb2c910c35edf3a5d08fd5ba610a49f | EthanTaft/PythonLearning | /AdvancedTopics.py | 4,646 | 4.625 | 5 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 23 18:30:50 2017
@author: Ethan
"""
# ADVANCED TOPICS IN PYTHON----------------------------------------------------
# Dictionaries ----------------------------------------------------------------
# In Dictionaries, there are Items, Keys, and values. Each item contains ... |
5bfac5da8a826c516f645d8abc00bd9c9e3309d2 | shubh101295/IITK-Bucks-assignments | /Assignment3/headers.py | 3,900 | 3.5625 | 4 |
class Input:
def __init__(self, transactionID ,index, sign,len_sign= None):
self.transactionID = transactionID
self.index = index
self.sign = sign
self.len_sign = len_sign==None and len(sign) or len_sign
def show(self):
print("TransactionID: " + self.transactionID)
print("Index: " + str(self.index))
p... |
ed7d5869e93e79b7e8f9ca081de1adfd4e81981e | alma18-meet/meet201617YL1cs-mod6 | /dictionary_practice.py | 1,065 | 4.5625 | 5 | #Module 6, Part 5: Practice with dictionaries here
my_phonebook={"Statue of Liberty":2125555555, "Ghostbusters":2125551234}
###
#Assign the value of the Statue of Liberty's phone number to the variable, num
###
num= my_phonebook["Statue of Liberty"]
###
#Print the variable, num
###
print(num)
###
#Change the value o... |
c047d442e047e86281402b74dd5d00ec30ea25af | anterra/learning-python | /string_format.py | 904 | 4.125 | 4 | age = 24
name = "Anterra"
print("{0} was {1} years old when she learned python".format(name,age))
name + " is " + str(age) + " years old"
#can also concatenate strings as so but it is ugly and error prone
#also conversion of age to string in first way is automatic via format, this needs explicit coversion
#same outp... |
4d7c07d7f7cfbddfc154615342fc27595735dc0e | scottwedge/python_one_liners | /15_Function.py | 280 | 3.578125 | 4 | #!/usr/bin/env python3
# Function format is 'def' '<NAME>' '(var1, var2):'
def power_of(x, power):
return x ** power
def square(y):
return y ** 2
def combo (a, b, c):
return power_of(a,b)/square(c)
print(power_of(10,2))
print(square(9))
print(combo(8,9,100))
|
97c3051e71a83cab2cfc73f2931c2051f86a088a | zhuny/Codejam | /solution/C/CO/DiverseSubarray/__main__.py | 1,925 | 3.515625 | 4 | import collections
def get_int():
return int(input())
def get_line():
return input().strip()
def get_ints():
return [
int(i)
for i in input().split()
]
class Queue:
def __init__(self):
self.body = []
self.tail_index = 0
def size(self):
return len(... |
ef25badf445ab980ec74a440e2e38169442190ea | dexterchan/DailyChallenge | /FEB2020/PalindromeIntegers.py | 1,096 | 3.953125 | 4 |
#Given an integer, check if that integer is a palindrome. For this problem do not convert the integer to a string to check if it is a palindrome.
#Analysis
#find the max number of digit
#numOfDigits=floor(log10(number))
#Go into loop
#head , tail
#init: head=numOfDigits , tail = 0
#loop until head<=tail
# check if h... |
41b77c4ab03cb366a1b60612c266b24321baf13a | mathwer/pythonCurso | /23-Crossing_Turtle/carros.py | 744 | 3.8125 | 4 | from turtle import Turtle
from random import choice, randint
VELOCIDADE = 5
CORES = ['blue', 'red', 'yellow', 'green', 'black', 'orange', 'purple']
class Carros():
def __init__(self):
self.carros = []
self.spawn()
def spawn(self):
self.chance = randint(1, 6)
if self.chance ==... |
9a62b8a8fa5666395bc696636dedc29310f6eb66 | sandeepa97/nextGen-py | /20210207/VehicleClass.py | 548 | 3.6875 | 4 | class Vehicle:
def __init__(self, model, year):
self.model = model
self.year = year
def accelerate(self):
print("The car is accelerating")
print("Car Model :" + self.model)
print("Car Year :" + self.year)
def brake(self):
print("Brake is applied")
... |
3eac01a4ebcead37e17241680ed487a81fedf910 | annkon22/chapter5 | /ex2.py | 1,571 | 4.0625 | 4 | #Implement the binary search using recursion without the slice operator.
# Recall that you will need to pass the list along with the starting and ending
# index values for the sublist. Generate a random, ordered list of integers and do a benchmark analysis
import random, time
def binary_search_recurive(a_list... |
bee9de05bcf32986836925f490942ae6235f57fc | Alexk-9/project | /dz_1_3.py | 564 | 3.96875 | 4 | number = int(input('Введите колличество процентов от 0 до 20'))
if number == 1:
print(number, 'процент')
elif 1 < number < 5:
print(number, 'процента')
else:
print(number, 'процентов')
# output of all declensions for verification
print('-------Вывод всех склонений для проверки-------')
for i in range(0, ... |
3e96f808b077972642e9f4dea2fd1d1b66c98817 | ephraim888sun/Finance | /Stock_Portfolio/Portfolio.py | 1,370 | 3.765625 | 4 | # Description: This program visualizes your stock portfolio
# Import Modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
# Load data
# Store data
df = pd.read_csv('')
# Show the data
print(df)
# Get total invested amount of money in portfolio
total_amount = sum(df['Amount']... |
49138be910a508c51ea2cebe8bd2239e6b546f49 | gchacaltana/python-funciones-derivadas | /ejercicio_aplicacion_24.py | 3,911 | 3.6875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Gonzalo Chacaltana"
__version__ = 1.0
import sympy as sp
from sympy.plotting import plot
import console
class Application(object):
def __init__(self):
self.x = sp.Symbol('x')
self.equation_i = (28*self.x**2)+36000*self.x
self.eq... |
c383601ebe5ca21c5a6d26153b35084dea3ef9db | uasanbekov/test2 | /test2.py | 128 | 3.515625 | 4 | import re
pattern = r"\d+"
text = "12 ай, 12 жыл, 12 уй, 12 киши"
res = re.findall(pattern, text)
if res:
print(res) |
aae1793482bc98870517133d77843f8de603f935 | andreiaacs/lotofacil-generator | /gerador.py | 3,608 | 3.5 | 4 | import pandas as pd
import numpy as np
def geraJogo():
i = 1
jogo = []
while(i <= 15):
num = np.random.randint(1, 25)
if num not in jogo:
jogo.append(num)
i = i + 1
jogo.sort()
return jogo
def readJogos():
df = pd.read_excel("resultados.xlsx", hea... |
307d372d18634e19309dc05c33ff492e36fa62bf | heyongman/python3 | /other/lottery_forecast/test1.py | 236 | 3.796875 | 4 | import pandas as pd
import numpy as np
res = map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])
print(list(range(1, 12)))
df = pd.DataFrame(np.arange(1, 10))
df['a'] = 1
df['b'] = 3
# df.pop('a')
print(df)
for x in range(1,3):
print(x)
|
52b1aecd82af5572b4cb2516e126710de15f28af | Nanoparty/ProjectEuler | /7. 10001st Prime Number/main.py | 328 | 3.765625 | 4 | def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def nthPrime(n):
primeCount = 0
index = 2
while primeCount < n:
if isPrime(index):
primeCount+=1
index+=1
return index-1
print("100th Prime:", nthPrime(... |
20d1db3b40db2633af09a741d502480abd3f76d8 | raghvendru/MY-PROGRAMS | /python/opp2com.py | 150 | 3.546875 | 4 | """
opp1
"""
def opp1():
a=int(input())
b=int(input())
sum= a+b
sub= a-b
p=a*b
d=a/b
m=a%b
print(sum,sub,p,d,m)
opp1() |
769b1bb8912a2ca7e368c2be22d48c7757c9d0a3 | contactshadab/data-structure-algo-python | /programs/leetcode/973_K_closest_point_to_origin.py | 3,590 | 4.03125 | 4 | '''
https://leetcode.com/problems/k-closest-points-to-origin/
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for... |
06870649a0fed0f1f55834d87013cf9831da2aee | Jason101616/LeetCode_Solution | /Dynamic Programming/95. Unique Binary Search Trees II.py | 1,689 | 4 | 4 | # Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
# For example,
# Given n = 3, your program should return all 5 unique BST's shown below.
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# /... |
6b568496ba945107317158d11d4d4e6de822518b | facebookresearch/CompilerGym | /compiler_gym/util/timer.py | 2,316 | 3.515625 | 4 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from time import time
from typing import Callable, Optional
from absl.logging import skip_log_prefix
def humanize_duration(seconds: float) -... |
320230f91a22b1fd6af58136962824f17b5b740d | Ana-Morales/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,397 | 4.28125 | 4 | #!/usr/bin/python3
"""
Module 2-matrix_divided.py
This module defines a function that divides all elementes of a matrix
"""
def matrix_divided(matrix, div):
"""Returns the division of all elementes in matrix by a given number
matrix must be a list of lists of ints or floats
Each row of the matrix must be... |
ee35c609f2e7068a10b00fddb5262de46d8e56da | mhq1065/respose | /homework_2_py/3-2(2).py | 315 | 3.703125 | 4 | def gys(a,b):
while a!=b:
if a>b:
a=a-b
else:
b=b-a
return a
print("这是一个计算最大公因数的程序")
while True:
a=int(input("请输入一个正整数:"))
b=int(input("请输入令一个正整数:"))
print("最大公因数为:",gys(a,b)) |
5cc9976fecffb9cef7e236e47416c1ef9ff306fe | samwar/python-class | /lab00_ipython_orientation.py | 539 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
:mod:`lab00_ipython_orientation` -- IPython Interpreter Basics
===========================================================================
Start ipython and read the verbiage.
If ipython does not start without error, please see instructor
How do you do you ent... |
89fca9c007c4e5b4efd8b7cb820bfa2ec1501f91 | salihenesbayhan/BUS232-Test-2-submission | /Test 2.py | 1,720 | 4.0625 | 4 | # function for taking input having list empty as list as a parameter
def inp(l):
# take input until the user enters 0
while True:
n=int(input("Please enter the number of shares: "))
l.append(n)
if n==0:
break
# function for total shares
# using sum
def shares(lst):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.