blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
65da695db59bf7a48511ebc2612f24118f98adce | ericmuzz/itc110 | /ITC110/assignment8.py | 687 | 3.9375 | 4 | # Create a Student class definition using the specifications.
class Student:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.grades = []
def name(self):
return self.first_name + " " + self.last_name
def addGrade(self,... |
73d79b4805ae8fa4b486bd01f3c3f3458804bac9 | nlpet/hackerrank | /Tutorials/Statistics/central_limit_theorem.py | 640 | 3.828125 | 4 | from math import sqrt, erf
# Central Limit Theorem
# The central limit theorem (CLT) states that, for a large enough sample (n)
# the distribution of the sample mean will approach normal distribution.
# This holds for a sample of independent random variables from any distribution
# with a finite standard deviation.
# ... |
df2ebd6ee235badf1dc531e829b1c9f95eacc5c6 | moheed/python | /languageFeatures/OOPS/OOPS1.py | 492 | 3.859375 | 4 | #A module to demonstrate class and inheritance
class Parent():
def __init__():
self.name=name
self.nchild=nchild
self.country=country
self.state=state
def __str__(self):
print(self.name,self.country,self.state,self.nchild)
def __repr__(self):
print(self.name,self.country,self.state,self.nchild)
def add... |
76f022879fb5c1cd5294e157729787fb10abd79b | abaah17/Programming1-examples | /w11s1_translator.py | 3,595 | 4.34375 | 4 | # This class will be a demo of a Translator class, which knows how to translate
# between 2 languages.
class Translator:
def __init__(self, language1, language2):
self.language1 = language1
self.language2 = language2
self.lang1_to_lang2 = {}
self.lang2_to_lang1 = {}
# Returns tr... |
b07821531349be36f7fae29f09f6f5feaa535a78 | MarcusRashford10/pyth03-20 | /tic_tac_toc_no_graphic.py | 2,983 | 3.609375 | 4 | import random #random 사용 암시
#중복체크 /
make_board = [] #틱택톡 보드판 만들기
def tic():
for i in range(9):
make_board.append('*')
def board():
print(make_board[0] +" | "+ make_board[1] +" | "+ make_board[2])
print("---------")
print(make_board[3] +" | "+ make_board[4] +" | "+ make_board[5])... |
1fd7b60ce9ea9f0b251ecf9329cdfbff5f4a504a | ayatullah34/Python | /20-Veri Görselleştirme Matplotlib/basics.py | 1,193 | 3.765625 | 4 | import matplotlib.pyplot as plt
import numpy as np
""" x = [1,2,3,4]
y = [1,4,9,16]
# plt.plot(x,y, color ='red' , linewidth = '5' )
# plt.plot(x,y, '--g')
plt.plot(x,y, 'o--r')
plt.axis([0,6,0,20])
plt.title("Grafik Başlığı")
plt.xlabel("x label")
plt.ylabel('y label')
"""
"""
x = np.linspace(0,2,100)
plt.plo... |
1e027e3eef780a50808da3b232257041e87690cc | An-ling-TS/LeetCode | /寻找旋转排序数组中的最小值2.py | 847 | 3.953125 | 4 | '''
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
注意数组中可能存在重复的元素。
示例 1:
输入: [1,3,5]
输出: 1
示例 2:
输入: [2,2,2,0,1]
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object... |
fad0f3159059b1956fd62cd3e34a0de5939d3f42 | KRiteshchowdary/myfiles | /practice.py | 217 | 3.734375 | 4 | input1 = list(raw_input("list_1 :- "))
input2 = list(raw_input("list_2 :- "))
n = raw_input("clockwise shift by ")
if(input1[0] == input2[int(n)]):
print("lists similar")
else:
print("lists diferent")
|
4acc431c15f2528d3c4064e8a080d7d9475f0a92 | Tripouille/D02 | /ex00/ft_reduce.py | 440 | 3.625 | 4 | from functools import reduce
def ft_reduce(function_to_apply, list_of_inputs):
result = list_of_inputs[0]
for el in list_of_inputs[1::]:
result = function_to_apply(result, el)
return result
def do_sum(x1, x2): return x1 + x2
print(reduce(do_sum, [1, 2, 3, 4]))
print(ft_reduce(do_sum, [1, 2, 3,... |
e8d7e464d8868e082bfa0cbcf904aefee0fd4dc9 | DowlutZuhayr/hello-world | /listremovedup.py | 311 | 3.75 | 4 | a = [5, 5, 10, 10, 15, 20, 25]
def list_dup(x):
z = []
for i in x:
if i not in z:
z.append(i)
return z
# using set automatically removes the duplicates from the list
def list_dup2(b):
return list(set(b))
print(list_dup(a))
print(list_dup2(a))
|
630d61b4730a0ba25693ffa27142926bb34f4c03 | morita657/Algorithms | /Leetcode_solutions/Strobogrammatic Number.py | 466 | 3.515625 | 4 | class Solution:
def isStrobogrammatic(self, num: str) -> bool:
hashtable = {"6": "9", "9": "6", "8": "8"}
original = num
copy = ["" for _ in num]
for n in range(len(num)):
if num[n] in hashtable.keys():
print('hi')
copy[n] = hashtable[num[n... |
37affb20e4cadf0667dd7bfc21081f0615e2f992 | jtizon001/currency_exchange | /dates.py | 5,826 | 3.578125 | 4 | import sqlite3
import datetime
import foreXchange
#script to create table of Dates to find exchange rate for any 2 currencies at some date
#USED FOR GRAPH
#in memory database, make a file
#conn = sqlite3.connect(":memory:")
conn = sqlite3.connect("currencies.db")
cursor = conn.cursor()
#__________________________... |
d73788abd425ae66a5b4ba33d733a989cd3ec945 | juanpiz96/introduccion_python | /contar_cadenas.py | 170 | 3.546875 | 4 | texto='esta lloviendo'
resultado={}
for letra in texto:
if resultado.get(letra):
resultado[letra]+= 1
else:
resultado[letra] = 1
print(resultado) |
d0bd5e2b0f6f3ae6854c9ac8ea642e3b8eab41e1 | karthikkashyap98/interview-prep | /day3_CountingValleys.py | 415 | 3.765625 | 4 | #!/bin/python3
# Complete the countingValleys function below.
def countingValleys(n, s):
sea=0
ans=0
for i in s:
if i == 'U':
sea=sea+1
if i == 'D':
sea=sea-1
if sea == 0 and i=='U':
ans = ans+1
return ans
if __name__ == '__main__':
... |
c33e568057a8e53777a325db712cb8144916a233 | Aniketgupta2007/prepinsta-top100-codes-python | /21.BinToDecimal.py | 210 | 3.75 | 4 | def binToDec(bin):
decimal = 0
base = 1
while bin:
res = bin % 10
decimal = decimal + base * res
bin //= 10
base *= 2
return decimal
print(binToDec(10101001))
|
89e2f181448a37aac2846ced768deb08403b4ba3 | rodriguezmatirp/Lab-Main | /Sem 4/Py_Lab/Lab_test1/19pw22.py | 2,705 | 3.75 | 4 | class Budget():
transactions = dict()
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.update_transactions(balance)
print("Added new Category", name)
def update_transactions(self, balance):
if self.name not in self.transactions:
... |
49d10f77b18bc7b321473e3f717cf7270d99d925 | yangyuxiang1996/leetcode | /剑指 Offer 48. 最长不含重复字符的子字符串.py | 2,055 | 3.578125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-21 23:07:38
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-21 23:42:45
FilePath: /leetcode/剑指 Offer 48. 最长不含重复字符的子字符串.py
Description:
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
'''
class Solution(object):
def lengthOfLongestSubstring1(self, ... |
021155af773288b4702f8a61839c244621379d97 | VasAtanasov/SoftUni-Python-Fundamentals-January-2019 | /l_03_functions/ex_06_math_power.py | 134 | 3.921875 | 4 | def math_power(number, exponent):
return number ** exponent
num = float(input())
ex = float(input())
print(math_power(num, ex))
|
772b751f8394d16a31bc9d8f0c5d0f4b39a11fac | secretdsy/programmers | /level2/practice/12953.py | 302 | 3.75 | 4 | def gcd(a, b):
r = a%b
while r > 0:
a = b
b = r
r = a%b
return b
def lcm(a, b):
return a*b//gcd(a, b)
def solution(arr):
arr.sort()
k = lcm(arr[0], arr[1])
i = 2
while (i < len(arr)):
k = lcm(k, arr[i])
i+=1
return k
|
de533be3154441007a451775aab72645531c5b16 | danial1021/python-study | /py_file/class/inheritance2.py | 583 | 3.96875 | 4 | class Person():
def __init__(self,name):
self.name = name
class MDPerson(Person):
def __init__(self,name):
self.name = "Doctor" + name
class JDPerson(Person):
def __init__(self,name):
self.name = name + ", Esquire"
class EmailPerson(Person):
def __init__(self,name,email):
... |
3edc2c572e87766a7d5659f95e33d6bf73df0ce0 | wolturz/Python_traineeship | /Python behave/features/steps/tttplay.xpy | 2,595 | 3.828125 | 4 | from tictactoe import EMPTY_BOARD, play, play_best_move
from behave import *
# board = EMPTY_BOARD # clear the 3 x 3 tictactoe board
# winner = None # set winner to none
# board, winner = play(board, 'X', 1,1) # take middle position
# board, winner = play_best_move(board, 'O')
# if board[6] == None:
# ... |
392d0ebb5c99d1bc436d81d8c8240bdba063a311 | yangreal1991/my_leetcode_solutions | /0066.plus-one/plus-one.py | 786 | 3.796875 | 4 | import numpy as np
class Solution:
def __init__(self):
pass
def plusOne(self, digits):
"""Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
Args:
digits: List[int] -- a non-empty array
Returns:
result: Lis... |
3f86a02b7c385eb0cd09b59883f53d5277b7f25e | ldandrade/cps844-computationalintelligence-202101 | /nonlineartransformation.py | 4,211 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import common
#Question 10
def linear_regression_w_noise_experiment(runs, X, y):
E_in_total = 0
for run in range(runs):
#"(...) Carry out Linear Regression without transformation, i.e., with feature vector \( (1,x_1,x_2) \) to find the weight \(w\) (.... |
9ae427da5367379ae191e498ac615cc7e2b4e0ca | geetha1997/python4 | /geetha.task.py | 923 | 3.859375 | 4 |
'''name=input("enter a name:")
m1=int(input("enter a marks1: "))
m2=int(input("enter a marks2: "))
print("%s has secured %d marks " %(name,m1+m2))'''
'''n1=int(input("enter a number 1: "))
n2=int(input("enter a number 2: "))
print(n1+n2)'''
'''tech="python and machine learning"
print("z" in tech )'''
'''num="54"
... |
d2735ead9edb2cb56586e7693e32201413719cfd | celeste16/gwc-2017 | /sc.py | 230 | 3.984375 | 4 | 5=["30","20","40","40","25","55","10","45","85","95,"85","40","35","15"]
3=["nike","sandals","Gucci","adidas","FENDI"]
def onlist(5):
for item in 5:
print(item)
onlist(5)
onlist(shoes)
print(5)
print(3)
|
98740904d3799b473267b63ffd8cef7625265a64 | shreesha-bhat/Python | /matrixaddition3.py | 349 | 3.625 | 4 | import numpy as np
val = [[1, 2, 3, 4],
[5, 6, 7, 0],
[8, 9, 0, 0],
[10, 0, 0, 0]]
arr = np.array([[1, 2, 3, 4],[5, 6, 7, 0],[8, 9, 0, 0],[10, 0, 0, 0]])
print("Smallest element in the matrix : ",arr.min())
print("Biggest element in the matrix : ",arr.max())
print("Sum of the elements of ... |
0f4b8bcda103af92e37a555f300b58a59fc76a23 | Shilpa25453/codeigniterproject | /python/if.py | 696 | 4.21875 | 4 | '''if('python'in['java','python','c']):
print("true")'''
'''num=5
if(num>10):
print("num >10")
else:
print("number less than 10")'''
'''a=6
if(a>20):
print("num >20")
elif(a<20):
print("num <20")
else:
print("else")'''
'''x=7
y=10
if(x>y):
print("x >y")
if(x<y):
print("x <y")
else:
pr... |
f83d4dbfaa462b3204bcffe67a0e2f0aaac47b6c | ljia2/leetcode.py | /solutions/bfs/199.Binary.Tree.Right.Side.View.py | 4,121 | 4.375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BFSSolution:
def rightSideView(self, root):
"""
Given a binary tree, imagine yourself standing on the right side of it,
return the v... |
8d927a28404b29b5c448617ea59cb8c567e4087d | kmtheobald/project_euler | /60-69/63.py | 372 | 3.96875 | 4 | # How many n-digit positive integers exist which are also an nth power?
n, i = 1, 1
nth_power_integers = []
while (True):
if (len(str(i**n)) == n):
nth_power_integers.append(i**n)
i += 1
if (len(str(i**n)) > n):
n += 1
i = 1
if (i == 9 and len(str(i**n)) < n):
brea... |
4c0d47f68ceb9f194a7abe5613f2f4b23f7c13c9 | bthowe/data_science | /python_crash_course/calvin/basics/functions.py | 3,567 | 4.25 | 4 | #
#
# def display_message():
# print("I am learning about functions!")
# display_message()
#
#
# def favorite_book(book):
# print(f"\n{book} is one of my favorite books.")
# favorite_book('The Hunger Games')
#
#
# def make_shirt(size='small', message="Storm King's Thunder"):
# print(f"The size of shirt is {... |
7d22a64f4c42f5a23b185046a33a5a6b51737688 | voyagerw/exercise | /myScripts/剑指offer20.表示数值的字符串.py | 1,778 | 3.65625 | 4 | # 代码在某些测试用例出现错误
class Solution:
def isNumber(self, s: str) -> bool:
stack = []
flag = True
def isOperator(x):
if x == '+' or x == '-':
return True
def isExp(x):
if x == 'e' or x == 'E':
return True
def isPoint(x):
... |
f521a05207da322a99d8104cc619c87465f8eac0 | dionchu/shogun | /shogun/instruments/country_info.py | 870 | 3.875 | 4 | class CountryInfo(object):
"""
Parameters
----------
name : str or None
The full name of the country, for example 'United States' or
'China'.
country_id : str
The ISO 3166 alpha-2 country code where the exchange is located.
country_id3 : str
The ISO 3166 alpha-3 c... |
854f867946b1c5e1ec68d3b1705207e25902e8a4 | ai-kmu/etc | /algorithm/2020/0414/JaeBin.py | 2,337 | 3.78125 | 4 | # 16. 프로그래머스 - 무지의 먹방 라이브
# 이진 트리기반 최소 힙 자료구조 사용, 우선순위 큐
import heapq as hq
def solution(food_times, k):
# 음식 순서값 저장
answer = 0
# food_times redefine(food, food`s position)
food_times = [(food, pos) for pos, food in enumerate(food_times, 1)]
# print('Redefine food_times : ', food_times... |
ddbe4624ba0e38b9ce3637aa17f48ba27519cf0c | Hoeuuun/algorithms | /code_fights/Array_Change.py | 672 | 3.84375 | 4 | """
CF.17
You are given an array of integers. On each move you are allowed to
increase exactly one of its element by one. Find the minimal number of moves
required to obtain a strictly increasing sequence from the input.
Example
For inputArray = [1, 1, 1], the output should be
arrayChange(inputArray) = 3.
"""
input... |
04395e5455bdc2e09df00f50cf3f17b9a3abec09 | jagadeshwarrao/programming | /boyvswarrior.py | 681 | 3.90625 | 4 | class Warrior:
def __init__(self,name,attack):
self.name=name
self.attack=attack
def myEnemy(self,obj):
print(f"My name is [{self.name}] and my enemy is [{obj.name}]")
## your code above this line ##
class Boy:
def __init__(self,name):
self.name = nam... |
adfc230aa148264678d4438e41893b266ce8ecb5 | rangerkevin/algorithms-sedgewick-wayne | /src/chapter_2/section_2/insertionSort.py | 758 | 3.84375 | 4 | import random
import time
class Insertion:
def __init__(self):
print("Insertion sorting: ")
def sort(self, alist, start, end):
n = end - start + 1
for i in range(start, end + 1):
j = i
while j > start:
if self.less(alist[j], alist[j - 1]):
... |
fe3ca394317b22b0bebf50ff22fb4c944908d512 | srikanthpragada/PYTHON_29_OCT_2020 | /demo/welcome.py | 87 | 3.578125 | 4 | # Welcome program
name = input("Enter your name :")
print(name, ", Welcome to Python") |
ea0acdc1da1d2c9a3a43d17869511b100a4c1e91 | panpan-wu/ASRCourse | /originals/04-HMM/hmm.py | 2,069 | 3.515625 | 4 | # Author: Kaituo Xu, Fan Yu
def forward_algorithm(O, HMM_model):
"""HMM Forward Algorithm.
Args:
O: (o1, o2, ..., oT), observations
HMM_model: (pi, A, B), (init state prob, transition prob, emitting prob)
Return:
prob: the probability of HMM_model generating O.
"""
pi, A, B ... |
eac53b546b39831f6e7c5a6f6222293944f96068 | omertasgithub/data-structures-and-algorithms | /leet code/Array/#1464. Maximum Product of Two Elements in an Array.py | 505 | 4.09375 | 4 |
#1464. Maximum Product of Two Elements in an Array
nums = [3,4,5,2]
nums2 = [1,5,4,5]
nums3 = [3,7]
#first solution
def maxProduct(nums):
nums.sort(reverse=True)
return (nums[0]-1) * (nums[1]-1)
print(maxProduct(nums))
print(maxProduct(nums2))
print(maxProduct(nums3))
#second solution
def maxProduct2(n... |
8d77cbd894cb82bc5991e6ec6fe36f7c636f61c5 | kbagnato/5-Crowns---Python | /Assembler.py | 12,429 | 3.5625 | 4 | import Card
import copy
class Assembler:
""" constructor """
def __init__(self , inRemainingCards = [], inAssemblies = []):
self.__assemblies = copy.deepcopy(inAssemblies)
self.__remainingCards = copy.deepcopy(inRemainingCards)
################################
########### accessors ##########
####... |
3e3f6d5663e939a05f89c020a755bf5f2ea4e03f | Manohar-Gunturu/AI-Game | /Nodes.py | 1,117 | 3.578125 | 4 | """
Track keeps row position
default track of root node is 12,12,12,12,12,12,12,12
so we can efficiently generates different states
_Note_: number of levels = number of moves, so maximum levels = 60
"""
class Node:
def __init__(self, state, parent):
self.state = state
self.parent = pa... |
d69f6da03585e20e2e4a84f8c89e240d331b245e | Larissa-D-Gomes/CursoPython | /introducao/exercicio012.py | 440 | 3.8125 | 4 | """
EXERCÍCIO 012: Calculando Descontos
Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
"""
def main():
preco = input('Digite o preco do produto: ')
preco = preco.replace(",",".")
try:
print(f'O preco do produto com 5% de desconto eh: {float(pr... |
b71a0b1e8f176501def8c71a9fcd6376cb2bcac0 | ssafarov/iss-talker | /src/service.py | 158 | 3.625 | 4 |
""" Helper function to convert input argument into float """
def to_float(s):
try:
return float(s)
except ValueError:
return False
|
26df072088c32d3ca8b8fd59cb93d74a332ad454 | kkjang/algorithms | /BFS_ShortestReach.py | 1,150 | 3.734375 | 4 | def BFS(graph_dict, root):
if root not in graph_dict:
return {}
current = [root]
visited = {root}
levels = {root:0}
while current:
frontier = []
for node in current:
for edge in graph_dict[node]:
if edge not in visited:
visited.... |
47b0d9d5d7c21c820dd5dcf18e00f7434949ca54 | harjotaujla/jash | /librarian.py | 2,890 | 3.671875 | 4 | from tkinter import*
from PIL import ImageTk#======pillow library it is used for add jpg image
from tkinter import messagebox
import sqlite3
class lib:
def __init__(self,root):
self.root=root
self.root.geometry("1350x700+0+0")
self.root.title("Library Management")
#bg image
s... |
efdfd7c375ad07fc1d04d0bc78fc6bbd51b7019c | tacslouai/python | /python-dev/a131_artistic_expression_lh/main.py | 1,780 | 3.6875 | 4 | import turtle
line = turtle.Turtle()
wn = turtle.Screen()
wn.setup(700, 700)
circles = []
slots = []
temp_scores = []
pressed = False
num_circles = 5
def press_button():
global pressed
pressed = True
def calculate_score(circles, slots):
for i in range(0, num_circles):
temp_score = 100 - abs(circl... |
ec870e2f05d148ecc200e148695d9fc3c8690056 | shandygunawan/N-ything | /Algorithms/BoardHandler.py | 8,392 | 3.640625 | 4 | from random import randint
from IO import Parser
# Create chessboard from pieces list
def createChessboard():
# create a chessboard
chessBoard = []
size = 8
for i in range(size):
col = []
for j in range(size):
col.append(('.', "."))
chessBoard.append(col)
# rea... |
48347b0e83d3769151d40ac0ace0049024edfbec | whutaihejin/EndeavorTime | /python/chpater2/c2.13.py | 600 | 4.28125 | 4 | print 'I like to use the Internet for:'
for item in ['email', 'netsurfing', 'homework', 'chat']:
print item
print
for item in ['email', 'netsurfing', 'homework', 'chat']:
print item,
print
who = 'knights'
what = 'Ni!'
print 'We are the', who, 'who say', what, what, what, what
print 'We are the %s who say %s' ... |
a65a90d7c20e4c920696524da6c58b3652f63088 | wuyuanpei/BayesNet | /node.py | 486 | 3.578125 | 4 | class Node():
""" A node in the BN"""
def __init__(self, name, values, parents, children):
""" name: string the name of the random variable
values: list possible outcomes of the random variable
parents: list of Node parents of the node
childre... |
8cce0b77bed308b4504f94c5de46286f9e1ee4f4 | boymennd/100-day | /intermediate(day 15 - day 57)/day 20 + 21/score_board.py | 827 | 3.6875 | 4 | from turtle import Turtle
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.scores = 0
with open("high_score.txt") as file:
self.high_score = int(file.read())
self.penup()
self.hideturtle()
self.pencolor("white")
self.goto(0,25... |
34a125cc4566c3653aba615410ec632dd70f260c | group8BSE1/BSE-2021 | /src/Chapter5/exercise2.py | 464 | 4.09375 | 4 | #finding minimum and maximum number
numberList = []
while True:
number = 0.0
input_number = input('Enter a number: ')
if input_number == 'done':
break
try:
number = float(input_number)
numberList.append(input_number)
except ValueError:
print('... |
6baa51f95a982278cf0357a4b5231cb9bd80bd8f | AdamSierzan/Learn-to-code-in-Python-3-basics | /2. Python_data_types/6.1 Excersice_data_types_number_done.py | 356 | 4.53125 | 5 | import math
print("Hi, this programme will let you calculate the area and circumference of a circle")
r = float(input("Plase type the radius: "))
area = 3.14 * r ** 2
circumference = 2 * 3.14 * r
print("The area of the circle with radius:", r, "is", round(area,3),)
print(", the circumference of a circle with this r... |
f3bfae81729ce1a18dd02a69dca0d96b177642a3 | whitefly/leetcode_python | /树/297_serialize_and_deserialize_binary_tree.py | 1,364 | 3.734375 | 4 | # Definition for a binary tree node.
from collections import deque
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
null_tag = "null"
split_tag = " "
def serialize(self, root):
"""Encodes a tree to a single s... |
131e8913245c7ec3c4a1a66a6bcdc787b22a1432 | iaingblack/Python_ABSWP | /Chapter-04/p1-commacode.py | 1,287 | 4.34375 | 4 | # Write a function that takes a list value as an argument and returns
# a string with all the items separated by a comma and a space, with and
# inserted before the last item. For example, passing the previous spam list to
# the function would return 'apples, bananas, tofu, and cats'. But your function
# should be able... |
35b4ce9e5080f569b7a37de39ee3052a02c1bf80 | 824zzy/Leetcode | /I_Searching/Graph/L1_752_Open_the_Lock.py | 745 | 3.78125 | 4 | """ https://leetcode.com/problems/open-the-lock/
1. Consider the problem as a graph problem, the goal is to find shortest way between two nodes.
2. Use bfs to find the shortest path.
"""
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
if '0000' in deadends: return -1
... |
668c4e0b7f4baede1e389ab87317a3bc07a3eefc | DanielLimasP/leetcode-solutions | /1-100/13-roman-to-int.py | 663 | 3.578125 | 4 | # We are lacking some terms in our dict...
def roman2int(s):
symbols_dict = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV"... |
ddf76ea451ac697a6933c6cc227a90d29e11eb9d | prashantxtim/PythonQuestions | /week2.1/area_of_a_triangle.py | 352 | 4.25 | 4 | #Write a program that reads the length of the base and the height of a right angled triangle and prints the area
#Every number is given in a separate line
base = int(input("enter the base of the triangle: "))
height = int (input("enter the height of the triangle: "))
area = (base * height)/2
print(f"The area of the r... |
427b5dfaef11981f31221702bc0394012ebbd54a | FeminaAnsar/luminarpython | /flow_controls/DecisionMaking/workshop/pattern_add.py | 154 | 4.0625 | 4 | num1=input("Enter a number:")
data=""
res=0
for i in range(1,(int(num1)+1)):
data=num1*i
print(data)
res=res+int(data)
print("Result=",res)
|
05a3a36cccae9a6b51a4a466ded2d0c2c684cd86 | emanmacario/diamond-square-py | /diamond_square.py | 3,917 | 3.921875 | 4 | # Import useful libraries
from statistics import mean
from math import isclose
def terrain():
# Initialise corner values
set_corners(height_map)
diamond_square(size-1)
def set_corners(height_map):
size = len(height_map)
height_map[0][0] = 5.0
height_map[0][size-1] = 5.0... |
6dda87ee7849313f35791315767add3b1882c69e | EOSand/Academic-Projects | /svm.py | 5,354 | 3.765625 | 4 | import numpy as np
from scipy.optimize import minimize
def linear_kernel(X1, X2):
""" Matrix multiplication.
Given two matrices, A (m X n) and B (n X p), multiply: AB = C (m X p).
Recall from hw 1. Is there a more optimal way to implement using numpy?
:param X1: Matrix A
type np.array()... |
f5bee2d743a82e8b84c915ab619495777d72d1a6 | vutran25/Checker_AI | /checkers-python/StudentAI.py | 5,236 | 3.625 | 4 | from random import randint
from BoardClasses import Move
from BoardClasses import Board
import copy
import math
MINIMAX_DEPTH = 10
INFINITY = 10000
#The following part should be completed by students.
#Students can modify anything except the class name and exisiting functions and varibles.
class StudentAI():
def... |
f28f020b9fdb5170a18e41fa614a8090321a08e5 | shantanu609/Array-8 | /Minimum_word_distance_iii.py | 943 | 3.84375 | 4 | # Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
class Solution:
def shortestWordDistance(self, words: List[str], word1: str, word2: str) -> int:
... |
940883beaced044f46465634f4f9da8383518ce5 | skilstak/code-dot-org-python | /stage07-artist2/s1level45.py | 610 | 3.53125 | 4 | """Stage 7: Puzzle 11 of 11
Try changing the numbers in the turn function calls and repeat (for) loops
to make different patterns. Or, experiment changing the rest of the code
to draw anything you want.
"""
import sys
sys.path.append('..')
import codestudio
artist = codestudio.load('s1level45')
artist.speed = 'faste... |
8cbc7d87ce5d16338450970010eab1af8271450a | Prudhvik-1996/Competitive-Programming | /Week-3/Day-2/two_eggs.py | 367 | 3.703125 | 4 | import math
def minAttempts(eggs,floors):
t1 = floors * 2
t2 = math.sqrt((1^2) + (4*1*t1))
t3 = (-1 + t2)/2
t4 = (-1 - t2)/2
# print(t3,t4)
return int(math.ceil(max(t3,t4)))
floors = 100
eggs = 2
print(str(minAttempts(eggs,floors)) + " are minimum attempts to know whether egg breaks or not when dropped from\n"+... |
d7631029bf215a5745181a4d6ffbc5ec2758d4e4 | littletreeeeeee/PythonCourse | /demo32_module.py | 433 | 3.640625 | 4 | # encoding=utf-8
def foo(x, y):
return "[foo]:result=%s" % str(x + y)
def bar(x, y):
return "[bar]:result=%s" % str(x * y)
def Dinner(meat, veg):
return "Meat :%s Vegetable : %s" % (meat, veg)
# 在此FILE中才會執行,若為Import的話不會執行這段
if __name__ == '__main__':
print foo(1, 2)
print bar(3, 4)
print D... |
5aae2821fad565e5bde6a179089cdb154962ff0d | selinvvyandexru/python_algoritms | /HomeWork01/Задача №9.py | 531 | 4.375 | 4 | # Вводятся три разных числа.
# Найти, какое из них является средним (больше одного, но меньше другого).
print('Введите три разных числа:')
a = float(input())
b = float(input())
c = float(input())
if b > a > c or c > a > b:
print('Среднее число: ' + str(a))
elif a > b > c or c > b > a:
print('Среднее число: ' + ... |
3a6c6b12cd4553fa6820311a6b004e3b64a55981 | shriaas2898/python_codes | /n_grams.py | 910 | 3.78125 | 4 | #!/usr/bin/python3
'''
Author: Aastha Shrivastava
PRN: 19030142001
Date modified: 14th August 2019: Added exception handling
Description: Program reads the contents of file 'tempfile.txt', takes user input for number of grams and print the ngrams for the filr
'''
try:
inp_file = open("tempfile.txt")
n = int(... |
565a2becbd98bc9e660e38168e922ecd14db8a74 | Jason9789/Python_Study | /week1/input.py | 217 | 3.96875 | 4 | # 입력을 받습니다.
string = input("입력 > ")
# 출력을 합니다.
print("자료 : ", string)
print("자료형 : ", type(string))
name = input("이름 > ")
print("나의 이름은 " + name + "입니다.")
|
f68303d7d1d771d5899a7496588dc5b99a820932 | jiez1812/py_Exercise | /prod.py | 425 | 3.75 | 4 | #Practice 2
from functools import reduce
def prod(L):
def miniProd(x,y):
return x*y
return reduce(miniProd,L)
L1 = []
int_n = 0
str_n = ''
while str_n != '':
str_n = input('Please insert num : ')
if str_n = '':
pass
else:
int_n = int(str_n)
L1.append(int_n)
L2 = prod(L1)
print(L1)... |
51420cb7b56701b7fb6e22669091b983ceba5a13 | ci2692-sd2019/laboratorio-1-inojosasalazar | /insertion.py | 204 | 3.984375 | 4 | #
def insertion_sort(array:[int]):
N = len(array)
for i in range(1, N):
current = array[i]
j = i-1
while(j >= 0 and current < array[j]):
array[j+1] = array[j]
j -= 1
array[j+1] = current
|
0d28cfce0369346d3287a2f7ae6239c5825d0594 | rayjustinhuang/BitesofPy | /flux.py | 856 | 3.53125 | 4 | XYZ = "https://bites-data.s3.us-east-2.amazonaws.com/xyz.csv"
THRESHOLDS = (5000, 0.05)
import pandas as pd
def calculate_flux(XYZ: str) -> list:
"""Read the data in from xyz.csv
add two new columns, one to calculate dollar flux,
and the other to calculate percentage flux
return as a list of tuples
... |
9e3b571303a5e93564d22305db77a3b6d88feba6 | devecis/learning | /testicles.py | 403 | 4.28125 | 4 | # Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
# num = 100
# isdiv = []
# for i in range(1, num):
# # isdivisible = []
# i... |
e549061e42a60de77aea418838ca9b5af9a9636a | Leshens/Pytong | /15.py | 123 | 3.546875 | 4 | y = float(input("podaj liczbę"))
if 1 <= y <= 10:
print("jest w przedziale")
else:
print("nie jest w przedziale")
|
4726e8fccf03597878d0ea1e366c463ba03efb9b | akiran1234/referencedocs | /Python/05_Dictionary&Set_DataType.py | 3,830 | 4.1875 | 4 | #################################################################################################################
# d1={'name':'python','age':23,'salary':10000.45}
# Dictionary Datatype items are represented with curly braces in key-value fashion. Key and Value separated with colon (:) and enclosed in single quotes.
... |
24d5b0da2f551b5dbb3819dac6e5d7cc060b68df | DillonWard/Python-problem-sheet-one | /largest-and-smallest.py | 656 | 4.375 | 4 | # returns the largest and smallest elements in a list
# Author: Dillon Ward (Dillonward2017@gmail.com)
# Date: 22/09/2017
# initializes a blank list to be populated
nums = []
# user input takes in the size of the list
# the input is made into an int
listLength = int(input("Enter length of list: "))
# loops based of... |
aa76a140a20e9e5a98a28cf83545040f1b6f4084 | xander1010/python | /duoxiancheng.py | 1,055 | 4.0625 | 4 | import time,threading
#新线程执行的代码
def loop():
print('thread %s is running..'%threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>%s'%(threading.current_thread().name,n))
time.sleep(1)
print('thread %s ended.'%threading.current_thread().name)
print('thread %s is running..'%threadi... |
148c90ee83121be6d765bf3fc2564a1f2d3fcfa7 | arbiben/cracking_the_coding_interview | /trees_and_graphs/build_order.py | 2,377 | 3.625 | 4 | # given a list of projects and dependencies determine
# what is the order of projects to be built.
# if there is a loop return Error!
from collections import deque
from Node import Node
# BFS
def build_order(project_list, dependencies):
if len(project_list) < 2:
return project_list
projects = {... |
487bd3f84cd41f4f3274eba0422b6ad75a2c821b | T2O3M5/sinc | /py_testing.py | 596 | 3.6875 | 4 | deltax=12.5
deltay=255
ratio= 255/12.5
result = []
rad = 0
number=25
print("hello")
for i in range(1,number):
result.append(float(number-i**2.00/number))
print(result)
#radius plus next radius faster in the middle 25**2 will be the largest value
#largest radius squared will give a range of numbers 1 to 625
#each o... |
401f0622003f72695c9862ec0b0ec344c7d96c5c | Govrie/Govrie.github.io | /HW3-1.py | 802 | 3.625 | 4 | #!/usr/bin/env python3 -tt
"""File: hello.py """
def lru_cache(function):
cache = {}
def wrapper(*args, **kwargs):
key = list(args)
key.append(tuple(zip(kwargs.keys(), kwargs.values())))
key = tuple(key)
if key in cache.keys():
return cache[key]
value = funct... |
aeb89d644c6d0ecc47c376b7f6fc0eee54163a54 | quamejnr/Python | /Algo & DS/Algorithms/breadth first search.py | 1,897 | 4.15625 | 4 | # Breadth-first search algorithm with Graph Data Structure
from collections import deque
graph = {'you': ['alice', 'bob', 'claire'], 'bob': ['anuj', 'peggy'], 'alice': ['peggy'], 'claire': ['thom', 'jonny'],
'anuj': [], 'peggy': [], 'thom': [], 'jonny': []}
def mango_seller(name):
return name[-1] == 'm'... |
ad8b1c689ddbabbcc0a52aeaa655c7c14a34ace6 | mauro37ar/programacion2 | /Practicas_unidad_2/ejercicio_5.py | 160 | 3.9375 | 4 | #!/usr/bin/python
a=int(input("ingresa anio\n"))
if((a % 4 == 0) and (a % 100 != 0) or (a % 400 == 0)):
print "ES bisiesto"
else:
print "no es bisiesto"
|
0ad368d80c84b7c89928cd810950e53de1fba53b | ImGabreuw/digital-innovation-one | /introducao-a-linguagem-com-python/lidando-com-modulos-importacoes-de-classes-metodos-e-construcao-de-funcoes-anonimas/projeto/modulos-importacoes-lambdas/contador_de_letras.py | 290 | 3.53125 | 4 | def contador_de_letras(lista_de_palavras):
contador = []
for palavra in lista_de_palavras:
quantidade = len(palavra)
contador.append(quantidade)
return contador
if __name__ == '__main__':
lista = ["cachorro", "gato"]
print(contador_de_letras(lista))
|
b25386afa6f3d2da0e432f1fc25c673d541eee45 | Zahidsqldba07/coding-exercises | /Python3/exercism/reverse-string/reverse_string.py | 82 | 3.921875 | 4 | def reverse(text):
"""This function reverses a string"""
return text[::-1] |
1427d5327bbbe03519397e70f76c83f9fdfef6c1 | Hanlen520/Daxiang | /book/chapter4/4-13.py | 245 | 3.78125 | 4 | foods = ('鸡', '鸭', '鱼', '肉', '蛋')
# 打印
for food in foods:
print(food)
# 尝试修改鸡
# foods[0] = '哈哈'
# 调整菜单,修改其中两种菜品
foods = ('a', 'b', '鱼', '肉', '蛋')
for food in foods:
print(food)
|
63256008c632834adc7e41215980801fd414219f | HayesCapers/python-basics | /dictionary_practice/dictionaries_1.py | 2,920 | 4.375 | 4 | # Write code to do the following:
# 1.Print Elizabeth's phone number.
# 2.Add a entry to the dictionary: Kareem's number is 938-489-1234.
# 3.Delete Alice's phone entry.
# 4.Change Bob's phone number to '968-345-2345'.
# 5.Print all the phone entries.
phonebook_dict = {
'Alice': '703-493-1834',
'Bob': '857-384-12... |
33f1b25e490904636ebda487645eb0c3de2478a0 | pyh3887/Tensorflow | /py_tensorflow/pack/tf3/케라스14_동물타입예측.py | 2,184 | 3.640625 | 4 | # softmax 로 다항분류 - 동물 type 분류
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
xy= np.loadtxt('https://raw.githubusercontent.com/pykwon/python/master/testdata_utf8/zoo.csv',delimiter=',')
print(xy[0],xy.sh... |
f49c3a36dd5f708762f5cb91fb72ad7c480c4e5a | sieczkah/Codewars_KATA | /6 kyu/Adding ordinal indicator suffixes to numbers.py | 337 | 3.78125 | 4 | """https://www.codewars.com/kata/52dca71390c32d8fb900002b"""
def number_to_ordinal(n):
suf = {'1': 'st', '2':'nd', '3': 'rd'}
s = str(n)
if n == 0:
return s
else:
if n > 10 and s[-2:] in ['11','12','13']:
return s + 'th'
else:
return s + suf.g... |
b25574c6043b8b3951aa9388233ba0509c034b09 | daidaifan/leetcode-problem-solver | /python/l0198.py | 1,363 | 3.625 | 4 | """
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken int... |
08fd4a89562d04cf16bbb991f15ce1e2f40f01ab | liuw/project-euler | /p42.py | 711 | 3.5 | 4 | #!/usr/bin/python
# encoding: utf-8
import time
import math
def char_to_ord(c):
return ord(c.upper()) - ord('A') + 1
def str_sum(s):
return sum(map(char_to_ord, s))
def is_triangle_number(num):
ttn = 2 * num
n = int(math.sqrt(ttn))
if n * (n+1) / 2 == num:
return True
return False
d... |
a18510587889bdafd7168ff740455a618d72bef6 | varmaprudhvi7/Data-science | /textmining_assignment1.py | 3,439 | 3.546875 | 4 | import requests # Importing requests to extract content from a url
from bs4 import BeautifulSoup as bs # Beautifulsoup is for web scrapping...used to scrap specific content
import re
macbook_reviews=[]
for i in range(1,30):
mac=[]
url="https://www.flipkart.com/apple-macbook-air-core-i5-5th-gen-8-gb-128-gb-ss... |
9a26a974bc10c1bd85351c67184fd1069ea34142 | Helldragon666/curso-de-python | /07-bloque-de-ejercicios-1/ejercicio-10.py | 595 | 4 | 4 |
'''
Ejercicio 10.
- Pedir al usuario la calificacion de
15 alumnos
- Mostrar en pantalla cuantos aprobaron
y cuantos reprobaron
'''
aprobados = 0
reprobados = 0
alumnos = int(input('Ingrese el numero de alumnos: '))
for i in range(1, alumnos + 1):
nota = int(input(f'Ingrese la calificaci... |
8d17684506f4e1cc36db0f29ba52e7c25244dd67 | DevelopGadget/Basico-Python | /Recursos Profe/ArraysManagement.py | 1,223 | 4.0625 | 4 | import os
def desplegarmenu():
os.system('cls')
print(' MENU')
print('0. salir')
print('1. Llenar nueva Lista(ingresar un dato al final)')
print('2. Agregar dato en posicion')
print('3. Borrar dato en posicion')
print('4. Consultar posicion')
print('5. Mostrar Lista actual')
print('6. Invertir posicion')
pri... |
7352e83bd112cf749760b2d26b1565d172c5ea3a | AntonKoziavin/PythonProjectEuler | /15.py | 302 | 3.640625 | 4 | import math
string = 20
strings = [0] * string
tab = [strings] * string
for item in tab:
print(item, end="\n")
print("Использование биноминального коэффициента")
print(int(math.factorial(string*2)/(math.factorial(string)*math.factorial(string))))
|
3d0d70a2fca26de6e438478d5933674a085363ab | twtrubiks/leetcode-python | /Merge_Intervals_056.py | 799 | 4.15625 | 4 |
'''
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
'''
class Solut... |
b550ca1a01845da47b823ea2b283130b9844331f | Jemmy-Hong/myPython | /alien_invasion/cn/jemmy/game/setting.py | 1,680 | 3.671875 | 4 | class Settings():
"""存储《外星人入侵》的所有设置的类"""
def __init__(self):
"""初始化游戏的静态设置"""
# 屏幕设置
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
# 飞船的设置
self.ship_speed_factor = 3
self.ship_limit = 3
# 子弹设置
... |
b50419dc4de67c5c95168e19bf2d63d0f84b7615 | mtle/solvedProblems | /python/reverseBits.py | 681 | 3.703125 | 4 | #!/usr/bin/python -tt
import sys
CHAR_BIT = 8
def swapBits(x,lo,hi):
int('{:08b}'.format(x)[::-1], 2)
mask = ((x>>lo)&1) ^ ((x>>hi)&1)
if mask==1: x = x ^ ((mask<<lo)|(mask<<hi))
return x
def reverseBits(x,j):
int('{:08b}'.format(x)[::-1], 2)
i = 0
cnt = j / 2
print(j,cnt)
'''whil... |
5cff33421a0d40816ef4b46092d307adb3d0fea8 | Janddda/RaspberryPiQuadcopter | /tests/testSingleBrushlessMotorInteractively.py | 1,043 | 3.59375 | 4 | #!/usr/bin/python
# Adapted from: http://withr.me/let-rpi-drive-brushless-motor/
import sys
from RPIO import PWM
if 2 != len(sys.argv):
print "Please supply one argument: the pin number of the motor."
exit(0)
SERVO_PIN = int(sys.argv[1])
print "Testing motor on pin:", SERVO_PIN
FULL_THROTTLE = 1860
ZERO_THRO... |
5aa20a029894ebff378b548963d8441073ea638f | wtewalt/bellhops-supply | /drive_time_functions.py | 3,306 | 3.984375 | 4 | """Functions used to compute round-trip distances and durations
Used in compute_drive_times.py
"""
import pandas as pd
import requests
import numpy as np
def make_url(origin, destination):
"""Create URLs from 2 lat/long pairs."""
base_url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=... |
93eb542b471110dc0a7cd96dd5c296b949eb89ec | Eightbitpixel/Random-Projects | /Timer/timer.py | 475 | 3.734375 | 4 | import time
import os
print("Welcome to the Timer Program")
Amount = input("Please enter the amount of minutes you want the timer to run for \n")
print("Alright so the timer is set to " + Amount + " Minutes Correct? \n")
Amount = int(Amount)
Verify = input("yes or no\n")
if Verify == "yes":
print("timer count... |
5381f1b5cb9e662b22a85f3c02f3765bf8559ff8 | jdrich1289/mycode | /countWhile.py | 294 | 4.1875 | 4 | from typing import Counter
beginning = int(input("Enter a start point: "))
ending = int(input("Enter an end point: "))
arigato = beginning
while ending >= arigato:
print(arigato, end=" ")
arigato += 1
if beginning > ending:
print("Beginning value is greater than ending value.") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.