blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9ef6772a19ba0c1aa6c66b3902a7628dd095aba6 | Inatigerdream/CTEW | /zMisc_Code/DATA_VISUALIZATION/doublebarplot.py | 1,782 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def doublebarplot(list1, list2, n=20, title='', label1='l1', label2='l2', xlabel=[], color1='turquoise', color2='dodgerblue', save='', barval=True):
""" Plot a double barplot of two lists. specify length with n """
if len(xlabel) == 0:
xlabel = list1.... |
363f9856c42906fdf8850d02c7ac7c0752f4184a | noanner/PBC_group92 | /table_V1.py | 862 | 3.609375 | 4 | from tkinter import *
from tkinter import ttk
root = Tk() # 初始框的声明
columns = ("品項", "成本", "售價")
treeview = ttk.Treeview(root, height = 18, show = "headings", columns = columns) # 表格
treeview.column("品項", width = 200, anchor = 'center', )
treeview.column("成本", width = 100, anchor = 'center')
treeview.column("售價", wi... |
8f3d41c81ad3c0e92b1e4f2bac6e9d1f873dfc17 | ZhukovOleksandr/HW | /HW2/practic_task2.py | 125 | 3.765625 | 4 |
for number in range(0, 1001, 1):
if (number % 2 != 0) and (number % 3 == 0) and (number % 5 == 0):
print(number) |
266bda9d905488860f9123256ecbc3ab8048e475 | helq/optimization-aspirants-locations | /greedy.py | 5,442 | 3.5625 | 4 | #!/usr/env/python3
from math import sqrt
# Evaluating average distance (between aspirants and locations)
# type :: ( [[float]], [int] ) -> float
def averageDistance(M, assignment):
return sum([ M[i][ assignment[i] ] for i in range(len(assignment)) ]) / len(assignment)
# Defining distance between two points in sp... |
05e24f84b681d556bb1953f866957b67322421c3 | ootz0rz/tinkering-and-hacking | /2021/LeetCode/FB/linked-lists/merge two sorted lists.py | 2,655 | 3.65625 | 4 | from listnode import ListNode
from typing import *
debug = False
class Solution:
# O(nm)
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
global debug
a = l1
b = l2
if debug: print(f'\n------\nmergeTwoLists l1<{l1}> l2<{l2}>')
... |
0f95d1044cec1f3b8510db23c823cf9758b5b2e6 | benjaminleon/EulerProject | /04_Largest_palindrome_product.py | 572 | 3.78125 | 4 | largest_palindrome = 0
for i in range(100,1000):
for j in range(i,1000): # Don't try 2*3 and 3*2
number = str(i * j)
failure = False
for idx in range(3):
if number[idx] != number[-(idx+1)]:
failure = True
break
... |
eb0432a8b10147af1950b177b9fb5bad4c93e3a1 | pyElena21/FileManipulationTools | /FileUnzipping.py | 628 | 3.5 | 4 | '''
Created on 14 Dec 2017
@author: Elena Koumpli
See more in https://stackoverflow.com/questions/30887979/i-want-to-create-a-script-for-unzip-tar-gz-file-via-python
'''
import tarfile
import os
def unzip_tarfiles(path_to_tarfiles, unzip_where_folder):
'''
Fast unzipper for csv.tar.gz f... |
a8bff6ad3880f48dee989afc77066d48787a4b35 | topherCantrell/computerarcheology | /holdAndDelete/cpu/cpu_common.py | 7,979 | 3.59375 | 4 |
'''
p - memory address (one byte)
q - memory address (one byte) used for opcodes with multiple Ps
t - memory address (two bytes)
b - constant (one byte)
w - constant (two byte)
r - memory branch relative offset (one byte)
s - memory branch relative offset (two byte)
The "bus" field shows how a... |
cd7c24b137ddbbed76f50c2db5e6e0895e071e75 | TekNoir08/weather | /Weather.py | 2,178 | 3.6875 | 4 | '''
Created on 21 Nov 2012
@author: Michael Kemp
'''
import urllib2
import os
from bs4 import BeautifulSoup
page = urllib2.urlopen("http://www.metoffice.gov.uk/weather/uk/observations/")
soup = BeautifulSoup(page)
## This need to be changed to allow the print and write to be separate. Too much dup... |
a74b3e1b5130042204a5bb7d9a1735302be91b63 | taghavi/EricssonTestTask | /Server/server6.py | 592 | 3.5625 | 4 | from pynput import keyboard
from pynput.keyboard import Key
def on_press(key):
if isinstance(key ,Key):
if key == keyboard.Key.esc:
# Stop listener and exit
keyboard.Listener.stop
return False
elif Key.space == key:
... |
cdb14277df766adf58610782eb588fba65c2a2bc | FelixZFB/Python_advanced_learning | /02_Python_advanced_grammar_supplement/004_设计模式/001_工厂模式.py | 1,082 | 3.859375 | 4 | # -*- coding:utf-8 -*-
# project_xxx\venv\Scripts python
'''
Author: Felix
Email: xiashubai@gmail.com
Blog: https://blog.csdn.net/u011318077
Date: 2019/12/9 12:21
Desc:
'''
# 工厂模式是一个在软件开发中用来创建对象的设计模式。
# 当程序运行输入一个“类型”的时候,需要创建于此相应的对象。
# 这就用到了工厂模式。在如此情形中,实现代码基于工厂模式,
# 可以达到可扩展,可维护的代码。
# 当增加一个新的类型,不在需要修改已存在的类,只增加能够产生新类型的子类... |
7cc60a6dbfcd2bf8818d3bf11983039ef0b87b7c | sunjoopark/python-algorithm | /python_exercise/ex_037.py | 350 | 3.796875 | 4 | N = 12
def combi(n, r):
p = 1
for i in range(1,r) :
p = p*(n - i + 1) // i
return p
if __name__ == "__main__":
for n in range(N+1) :
t = 0
while t < (N - n) * 3 :
print(" ",end="")
t = t + 1
for r in range(n + 1) :
print("%3d "%(combi(... |
3c0a9d6571c80782071beccff76827ea4e07b1a6 | Rkhwong/RHK_PYTHON_LEARNING | /PythonExercices/Semana_Python_Ocean_Marco_2021-main/Exercicios_Python_PauloSalvatore/Exercicio_13.py | 1,195 | 4.25 | 4 | """
Exercício 13
Nome: Convertendo Celsius/Farenheit
Objetivo: Escrever duas funções de conversão, uma de graus celsius em farenheit e a outra que faça o contrário.
Dificuldade: Principiante
1 - Crie um aplicativo de conversão entre as temperaturas Celsius e Farenheit.
2 - Primeiro o usuário deve escolher se vai entrar... |
76d2b48fa2a1fc5ede96030f2c34a8508f3830f6 | SanyaBoroda4/Hillel_Homeworks | /LESSON_06(LISTS, TUPLES)/Lesson 06_10.py | 144 | 3.625 | 4 | """Expression comprehension"""
list = [1, 3, 5, 8, 12]
my_expr = sum(i for i in list if i % 2 == 0) # only works for 1 TIME!!!
print(my_expr)
|
091626ca8cf2c7002c5d265b2f795bbcaa06bf21 | timemaster5/BodyPos | /MediaPipe/HandPos/hands01DisplayHandLandmarks.py | 1,819 | 3.546875 | 4 | # this is a full tutorial
# how to detect and display hands using live camera
# first pip install media pipe
#https://google.github.io/mediapipe/getting_started/install.html
import mediapipe as mp
import cv2
mp_drawing = mp.solutions.drawing_utils #helps to render the landmarks
mp_hands = mp.solutions.hands
cap ... |
f8fb1fe5d5ea5bfc13ae45785ff5056f62ef11be | g-yuqing/leetcode | /110_BalancedBinaryTree.py | 900 | 3.890625 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root:
... |
d297ebdd6b0bd0cff9f655f14e8de4e3ebc5eb73 | gagm04/Resolver-los-prerequisitos | /Laboratorio5/online_retail.py | 1,431 | 3.609375 | 4 | #import necessary libraries
import pandas as pd
import numpy as np
import sklearn as skl
import matplotlib as plt
# Read in iris data set
iris = pd.read_csv("/home/sheynnie/Escritorio/online_retail_price1")
# Add column names, features as indepent variables
iris.columns = ['Quantity','Price','StockCode']
# Split data... |
af364441be52f06890e21fa6f84a5a1d8a41b66b | mola1129/atcoder | /contest/abc142/D.py | 593 | 3.671875 | 4 | import math
import fractions
a, b = map(int, input().split())
def make_divisors(n):
divisors = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n // i)
divisors.sort()
return divisors
def is_pr... |
f7e7a34ea40111b0b26dd16720d36377cac96c93 | fallerd/CS2050 | /Assignment04.py | 7,716 | 3.640625 | 4 | from __future__ import print_function
from sys import stdin
import unittest
'''
Description: Assignment 04 - Family Tree
Author: David Faller
Version: 02
Help received from:
Help provided to:
'''
class FamilyTree(object):
def __init__(self, name, parent=None):
self.name = name
self.... |
d85c53775aa0a720b7b8099063ad24267b34ae5d | Davidxswang/leetcode | /easy/1446-Consecutive Characters.py | 1,098 | 3.859375 | 4 | """
https://leetcode.com/problems/consecutive-characters/
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with... |
f66d64323f7d63191373e1e7af264000112c8a69 | namratarane20/MachineLearning | /ML Basics/Create module in python for reusability.py | 968 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
def function():
print('welcome to jypyter notebook')
# In[6]:
def add():
num1 = int(input('Enter the first number '))
num2 = int(input('Enter the second number'))
print('addition of an Entered numbers is ', num1 +num2)
# In[7]:
def sub():
... |
cbfb595f2e2ac70e40c00eba08f7ac719816bf5f | harisahmed11/FintechPy | /playground/python_lang_playground.py | 183 | 3.65625 | 4 | list_of_tuples = [
(1, 'Adnan', 39.6),
(2, 'Naveen', 35.5),
(3, 'Sabah', 13.1),
]
for index, (id, name, age) in enumerate(list_of_tuples):
print(index, id, name, age) |
cd7a934dcc2bfb05ab400866cfccebd0efd60888 | sppenna/cs415a1 | /Sieve.py | 377 | 3.84375 | 4 | '''
Finds Prime Numbers 2 - n and stores them in a list
'''
def sievePrimes(n, count):
"""
"""
count = 0
primeList = []
for h in range(1, n):
primeList.append(h)
for i in range(2, n):
for j in range(i, n):
count+=1
k = i * j
if k in primeLi... |
017212ac196114317e88f0a42b60c51e5a2d72a0 | ffabut/kreap1 | /4/ukol2.py | 520 | 3.890625 | 4 | def multipleHello(jmeno, x=1):
pozdrav = "Hello " + jmeno + "!" # pozdrav vytvorime zde, at to pocitac nemusi vypocitavat pri kazdem novem pozdravu
while x > 0:
print(pozdrav)
x = x - 1 # po pozdraveni zmensime x o 1 a cyklus se pote zepta, zda je cislo stale vetsi nez 0, tj. jestli mame jeste j... |
7731c443ecc49348fe5c962a3e5af7a0196f58c0 | sivakrishnarajarapu/code_signal-challenges | /Desktop/Desktop/Code_signals_challenge/test_28.py | 200 | 3.578125 | 4 | # m=chr(ord("s")+1)
# print(m)
def fun(s):
n=''
for i in s:
if i=='z':
n+='a'
else:
k=chr(ord(i)+1)
n+=k
return n
print(fun("crazy"))
|
9b6fc3d43d5c790807825a2d29f9fd5cdcccc76e | hao310rui140326/my_verilog | /PCIE-TLP-DEMO/tb/test.py | 752 | 3.765625 | 4 | #def foo():
# print("starting...")
# while True:
# res = yield 4
# print("res:",res)
#
#g = foo()
#print(next(g))
#print("*"*20)
#print(next(g))
#def fun_inner():
# i = 0
# while True:
# i = yield i
#
#def fun_outer():
# a = 0
# b = 1
# inner = fun_inner()
# inner.send(None... |
164d072f1edcb96e208e8c6193e1ccec6afef610 | USTH-Coders-Club/API-training | /callapi.py | 527 | 3.8125 | 4 | #import the library to make http request
import requests
#URL of the API
URL = "https://ssd-api.jpl.nasa.gov/cad.api"
distmax = input("set the maximum distance: ")
vinfmax = input("set the maximum speed: ")
#Params
param = {
'dist-max': distmax,
'v-inf-max': vinfmax
}
#Make an API request and store date t... |
4eae8f0722c2b3deadc57599dddbe26e7cc15f0e | Cecilia520/algorithmic-learning-leetcode | /cecilia-python/others/CalMaxPathNum.py | 2,287 | 3.53125 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : CalMaxPathNum.py
@Contact : 70904372cecilia@gmail.com
@License : (C)Copyright 2019-2020
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2020/9/15 18:59 cecilia 1.0 米兔吃胡萝卜,计算最大胡萝卜... |
9064fb62cc947b47b05a1809c99cd37ea3a74cd9 | Oussema3/OneMonth | /formatters.py | 698 | 3.578125 | 4 | #!/usr/bin/python3
#strings are texts surronded by quotes singles '' or double "" or triple """
kanye_quote = "My greatest pain in life is that i will never be able to see my self perform live"
print(kanye_quote)
print()
print("Now splited")
print()
kanye_splited_quote = """My greatest pain in life
is that i will never... |
22f0790136f45572012603570cd1bb2d69ae8afa | rscorrea1/youtube | /python_from_scratch/13_dictionaries/dictionaries.py | 712 | 4.5625 | 5 | #############################################
# Let's learn about Dictionaries in Python! #
#############################################
## how to initialize a dictionary
menu = {}
## how to add element to a dictionary
menu["Cappuccino"] = 2.5
menu["Tea"] = 1.5
menu["Water"] = 1.0
menu["Juice"] = 2.0
# print(menu)
#... |
95ad0d6eff5f4bdbd20ac5e7b4b5e01ec32ed0a4 | tgfbikes/python | /CS-1410/Drills/drill18.py | 799 | 3.71875 | 4 | import random
class MathProblem:
def __init__(self):
self.num1 = random.randrange(1, 10)
self.num2 = random.randrange(1, 10)
def get_first_operand(self):
return self.num1
def get_second_operand(self):
return self.num2
def get_answer(self):
return None
def... |
10f8a06fd1f918ccbb3bb89dbbf108b1a424437e | shailchokshi/ClientServer | /client.py | 1,601 | 3.96875 | 4 | from socket import *
import sys
import urllib.request
#The socket module forms the basis of all network communication
#Firstline specifies the address of the server. it can be an IP or servername.
#e.g. "128.138.32.126" or "yourserver.eng.uci.edu"
#second line shows which port your server will be working on(usually ... |
44bfdc6ed86805cefef1c88b86f283571e0db5a4 | WilliamslifeWayne/python_practice | /python_new/collatz.py | 3,550 | 4.15625 | 4 | #例题:
"""
考拉兹猜想(Collatz Conjecture),也叫奇偶归一猜想、3n + 1猜想、冰雹猜想、角骨猜想、哈塞猜想、乌拉姆猜想、叙拉古猜想
算法介绍:
1.对于每一个正整数,如果他是奇数,就对他乘以3,再加1,如果是偶数则对他除以2,最终都能得到1.
"""
# def collatz_conjecture(number):
# while number != 1:
# if number % 2 == 0:
# # 偶数
# number /= 2
# print(number)
# elif num... |
d3c34edd9cd84056bd5469d6bd3676e3cd0009ec | dmitrie43/PythonLabs | /Lab3-6/functions/Helper.py | 3,001 | 3.53125 | 4 | import os
import csv
class Helper:
"""
Класс для требований к программе. Лаб 3
Дополнительный функционал
"""
@staticmethod
def get_count_in_dir(path) -> list:
"""
Возвращает кол-во файлов в директории
:param str path:
:return list:
"""
return o... |
1920acc95446b7a068217a998ed9233435e67517 | Aasthaengg/IBMdataset | /Python_codes/p02400/s581321955.py | 81 | 3.65625 | 4 | import math
r = float(input())
print("%.10f %.10f"%(r**2*math.pi,2.0*math.pi*r))
|
be77e30a49b7c5d371f78a524e7eac1f25f3c742 | greyhere/data-structures-and-algorithms-in-python | /ch04/R-4.3.py | 886 | 4.0625 | 4 | ''' R-4.3
Draw the recursion trace for the computation of power(2,18), using the
repeated squaring algorithm, as implemented in Code Fragment 4.12.
'''
def power(x, n):
'''Compute the value x**n for integer n.'''
if n == 0:
return 1
else:
partial = power(x, n // 2)
result = partial... |
4643d368a020f067358e6dfa6919eb6f0031e05b | luisnarvaez19/Proyectos_Python | /edu/cursoLN/funciones/funciones4.py | 960 | 4.25 | 4 | '''
Created on Agosto 18, 2019
Imprime un rango de valores y *args como argumento
@author: luis.
'''
print(list(range(3, 6))) # normal call with separate arguments
args = [3, 6]
print(list(range(*args))) # call with arguments unpacked from a list
var_global = "cualquiera"
# Hacer multiplicaci... |
413b5fdcc7874962a7ecd2b53e8454bcb6b0be5e | JZY11/mypro01 | /myoop13.py | 435 | 3.671875 | 4 | # 测试 mro() 方法(查看类的目录结构)
class A:
pass
class B(A):
pass
class C(B):
pass
print(C.mro())
# 重写 object的 __str__()
class Person:
def __init__(self,name):
self.name = name
def __str__(self):
return "名字是:{0}".format(self.name)
p = Person("小二")
# print(p) # 不重写object的 __str__()时打印结果... |
c9ad96870251f452c54ce5746f789137899b6998 | shaikshareef99/Email-Spam-Filter | /classifier.py | 978 | 3.984375 | 4 | from collections import defaultdict
#Classifier object declaration
class classifier(object):
"""Classifier feature initialization"""
def __init__(self):
self.label_word_count = defaultdict(int)
self.feature_count = defaultdict(lambda: defaultdict(int))
self.total_word_count = 0
... |
b54da8ff96609263451631f3d326a39ee53dc63d | DOCgould/MessagePassing | /Shafi/Calibrated_Control.py | 2,358 | 3.578125 | 4 | import pygame
import numpy as np
def set_thruster_value(input_matrix):
'''
Parameters: Matrix of xbox inputs
Returns: the dot product of the xbox input along with this mathematically
predetermined map by me, not by Christian at all. Why do you ask?
'''
thruster_matrix = np.matrix(\
'1 0 0 0... |
3def7b80a5a0f048754372f9ff9de5f40ced665e | rfm110/Tower_of_Hanoi | /recursive_tower_of_hanoi.py | 1,844 | 4.15625 | 4 | def recursive_tower_of_hanoi(pin_1=[4,3,2,1], pin_2=[], pin_3=[], number_of_disks=4):
# change parameter names so they are more general? like source, target, and intermediate
if pin_3 == [4, 3, 2, 1]:
print "Game Completed"
return pin_1, pin_2, pin_3
# let pin_1 be the source, pin_2 be the ... |
e83ae221fd2ffee37cc5ee7842f8766a26c2c9ae | sling1678/python | /hacker_rank/src/day1_prob.py | 1,221 | 3.65625 | 4 | import math
N_int = int(input().strip())
if not (10 <= N_int <= 2500):
raise AssertionError (" N must be integer between 10 <= N <= 2500 ")
x = list(map(int, input().split()))
# check right number of data points
if not(N_int == len(x)):
raise ValueError (" Number of elements of x mus t equal N")
for num in x:
... |
f8ffea9374c11fe71f9dcd945efaf1bb28f35c2f | Ye0l/python | /inputTest.py | 122 | 3.53125 | 4 | a = input("a 값을 입력하세요.")
b = input("b 값을 입력하세요.")
c = int(a) + int(b)
print(a, "+", b, "=", c) |
bbac88a7a57f3445153d1df85ecddc235e53c4f7 | denis-trofimov/challenges | /leetcode/contest 156/Unique Number of Occurrences.py | 461 | 3.5 | 4 | from collections import Counter
class Solution:
def uniqueOccurrences(self, arr) -> bool:
c = Counter(arr)
l = list(c.values())
c2 = Counter(l)
for i in c2.values():
if i > 1:
return False
return True
if __name__ == "__main__":
sol = Solution... |
31acd0b2f7c52ed3ef971048e9e28634341300e6 | IsraelCavalcante58/Python | /Aprendendo Python/exercicios/ex012.py | 301 | 3.59375 | 4 | #Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto.
preco = int(input('Qual o valor do produto?'))
novo = preco - (preco * 5 / 100)
print(f'O preço do produto sem desconto é: R${preco:.2f}')
print(f'O valor com os 5% de desconto ficará: R${novo:.2f}') |
da933451e22bea77b47d37ae16980b0385e5de03 | DUanalytics/pyAnalytics | /88-TS/88B2_dt_intro2.py | 1,432 | 3.71875 | 4 | #Date Time - Operations & Arithmetic
#-----------------------------
#%
from datetime import datetime as dt
#to date from integer values
new_date = dt(2019,7,4)
new_date
equinoxDate = dt(2019,6,23)
equinoxDate
#%%
d1 = dt(2010,6,10)
d2 = dt(2019,7,28)
d2 + d1 #error
diff=d2 - d1 #number of days
diff
diff/365 #this... |
c51026745e1c90a494d97e176d12b7037aa62dc8 | djrgit/coursework | /udemy/python-video-workbook/my_progress/086.py | 259 | 3.515625 | 4 | # Exercise 86 - Data Checker
checklist = ["Portugal", "Germany", "Munster", "Spain"]
with open('countries_clean.txt', 'r') as f:
countries = [l.strip('\n') for l in f.readlines()]
filtered = [c for c in checklist if c in countries]
print(sorted(filtered)) |
2c7c0243cfb250654e578ff575bbb68053d0f7be | DimejiAre/code-challenges | /python/equalize_array.py | 311 | 3.703125 | 4 | """
https://www.hackerrank.com/challenges/equality-in-a-array/problem
"""
def equalizeArray(arr):
count = {}
largest = 0
for i in arr:
if i in count:
count[i] += 1
else:
count[i] = 1
largest = max(count[i], largest)
return (len(arr) - largest)
|
f511e32735963d72e1a2bec216f8c8333afd3a2c | bartkowiaktomasz/algorithmic-challenges | /LeetCode - Top Interview Questions/BinaryTreeLevelOrderTraversal.py | 1,067 | 3.921875 | 4 | from collections import deque
from typing import List
# 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:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
... |
fa4751dca2d7f80cdbea0f586c408e5bb6011265 | mbermudez00/Tutorials | /Python/examples.py | 488 | 3.890625 | 4 |
#x = "ejemplo"
kilometer = [39.2, 36.5, 37.3, 37.8]
try:
#x = "Caballo" if x=="ejemplol" else x
#feet = [3280.8399*x for x in kilometer]
feet = map(lambda x: float(3280.8399)*x, kilometer)
print(list(feet))
except:
print("esto paso el try")
# num = input("ingresa el numero maximo menor a 200: ... |
f6342d6bd0db6fa911141a7dc0b4343a03ba6540 | benjazor/leetcode | /Solutions/sortedArrayToBST.py | 825 | 3.6875 | 4 | # NAME : Convert Sorted Array to Binary Search Tree
# LINK : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
# DATE : 29/04/2021
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
#... |
9bd373b912c9b2cc41c51627afded4e22655830c | manuelemacchia/algorithms | /data/stack.py | 920 | 3.9375 | 4 | class Stack:
def __init__(self, n):
self.n = n # maximum length of stack
self.pos = -1 # current position inside stack (-1 is empty)
self.stack = [None] * n
def __repr__(self):
return str(self.stack[:self.pos+1])
def _stack_empty(self):
if self.pos == ... |
eea8f453814c55a0854005e8f8a2b1afefec891a | nils-frank/moodle_fragen_importer | /jquiz_import.py | 2,601 | 3.65625 | 4 | #!/usr/local/bin/python
import csv
from sys import argv
def read_csv(filename, fms):
with open(filename, 'rb') as csvfile:
csv_file = csv.reader(csvfile, delimiter=',', quotechar='|')
next(csv_file, None)
for row in csv_file:
each_q = format_to_xml(fms, row)
write_t... |
130b479f29c854dee0f2848c8fe2f4e30fec509a | sellenth/algorithms | /stack.py | 765 | 3.71875 | 4 | import ll as linked
class Stack:
top = None;
cap = 0;
def __init__(self, v):
if v == None:
self.top = linked.ll(None);
else:
self.top = linked.ll([v]);
self.cap = 1;
def peek(self, v):
return self.top.root.get_val();
def is_empty(self):... |
136b60238aec5c8f20f424b2e303a129a6196f3a | hensingh/FinalProject_SI206 | /spotify_csv.py | 1,244 | 3.796875 | 4 | import os
import sys
import json
from json.decoder import JSONDecodeError
import sqlite3
import csv
def spotify_csv():
print("Beginning process")
conn = sqlite3.connect('spotify.sqlite')
cur = conn.cursor()
cur.execute("SELECT album, AVG(Popularity) FROM Spotify_Top_Songs GROUP BY album ORDE... |
b251fdf99671f78bf1aa7c652e93730601ee1188 | RobAkopov/IntroToPython | /Week5/Practical/Problem2.py | 136 | 3.53125 | 4 | l1 = [1,2,3,4,5,6,7,8,10,11,45,68,61,18]
def even_func(l1):
e = [i for i in l1 if i % 2 == 0]
return e
print(len(even_func(l1))) |
332c27b5bacacdb21d9867ec0685ca4dd7b6759b | radhikari54/FirstAlgorithmsThenCode | /chapter_03_the_tournament/tournament.py | 1,502 | 3.9375 | 4 | # Program TOURNAMENT in Python
# Figure 3.4 from the book "Computational Thinking: First Algorithms, Then Code"
# Authors: Paolo Ferragina and Fabrizio Luccio
# Published by Springer
# loads mathematical functions
import math
def tournament(set):
"""
Search the maximum in a table with n = 2^k partecipants.
... |
921733801eb645d39f781e301a8a89cca66051ac | Timothy-S-Fang/bookShelf | /Book.py | 657 | 3.546875 | 4 | class Book():
def __init__(self, title, author, rating, num_ratings):
self.title = title
self.author = author
self.rating = rating # bookFinder.getRating()
self.num_ratings = num_ratings
# self.cover = cover # bookFinder.getBookCover(title)
def __lt__(self, other):
... |
f711d7daae458d64992372c3be42dfcb87adbda4 | JonSeijo/project-euler | /problems 30-39/problem_38.py | 1,342 | 4.34375 | 4 | # Pandigital multiples
# Problem 38
"""
Take the number 192 and multiply it by each of 1, 2, and 3:
192 * 1 = 192
192 * 2 = 384
192 * 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved... |
7f398f65810e21dd3290a18af7ef270156af4282 | swingninja/AlgoPython | /check_palindrome_number.py | 540 | 3.96875 | 4 | def check_palindrome(num):
if num is None:
return False
# Single digit is a palindrome
if num/10 == 0:
return True
# Extract digits and push onto stack
stack = []
num_copy = num
while num_copy != 0:
stack.append(num_copy % 10)
num_copy = num_copy / 10
... |
d9b00aa406e5337fab1627b225e6ae9bdd09bddf | AnumaThakuri/pythonassignment | /assignment 6/question 7.py | 159 | 4.0625 | 4 | string=input("Enter your string :")
def length(string):
if string=='':
return 0
else:
return 1+length(string[1:])
print(length(string)) |
2292cae2865f29f0237aa4338c5e33df1069246e | 600tomatos/exponea_challenge | /src/interfaces/validator.py | 996 | 3.703125 | 4 | from abc import ABC, abstractmethod
class ValidatorInf(ABC):
"""Base class for validators"""
@classmethod
def check(cls, value):
"""Helper method that takes out the logic of creating a validator outside view.
It is understood that validation begins with the perform_validate method.
... |
45dbce74f0570b98078a6df52a499898cc227c8c | rohitkyadav/Codechef | /BOOKCHEF.py | 2,217 | 3.546875 | 4 | """
Chef Watson uses a social network called ChefBook, which has a new feed consisting of posts by his
friends. Each post can be characterized by f - the identifier of the friend who created the post,
p - the popularity of the post(which is pre-calculated by ChefBook platform using some machine
learning algorithm) a... |
67496daf3685cb7908806e9cea0ec7d1287d2829 | kaushik2000/python_programs | /ex_14/json1.py | 347 | 3.59375 | 4 | # Using json library in python
import json
data = '''{
"name" : "Kaushik",
"phone" : {
"type" : "int1",
"number" : "+1 234 567 890"
},
"email" : {
"hide" : "yes"
}
}'''
info = json.loads(data)
print("Name:", info["name"])
print("Phone:", info["phone"]["number"])
print("Hide... |
b25edd005fb0985d224d12c39d9a972e39bc9901 | weiranfu/cs61a | /functions/Exception/safe_newton_method.py | 3,107 | 4.4375 | 4 | """
Now we need to get the zero point of the objective function: f(x) = 2*x^2 + sqrt(x) using Newton method.
"""
from math import sqrt
def objective_f(x):
return 2*x*x + sqrt(x)
def objective_df(x):
return 4*x + 1/(2*sqrt(x))
############### Something changes:
def find_zero(f, df):
def near_zero... |
400e3324e945cbd3e5b3bdf56494de1c97f77fe4 | Rasgacode/codecool_tasks | /unit_task/4/test_poker_hand.py | 681 | 3.59375 | 4 | import unittest
import poker_hand
class poker_hand_test(unittest.TestCase):
def test_poker_hand(self):
self.assertEqual(poker_hand.hand_score([1, 1, 1, 1, 1]), "five")
self.assertEqual(poker_hand.hand_score([1, 1, 1, 1, 2]), "four")
self.assertEqual(poker_hand.hand_score([1, 1, 1, 2, 3]),... |
f7d3b1bd374558bba5ac8e4a56bd42d2985b2eac | shivam-singh-au17/morning_boostup | /may05/my.py | 978 | 3.78125 | 4 |
# 1
N = 5
for i in range(1, N + 1):
res = "";
for j in range(1, i+1):
res += "*" + " "
print(res)
print()
# 2
N = 5
for i in range(1, N + 1):
res = ""
for j in range(1, N + 1):
if (i == 1 or i == N or j == N):
res += "*" + " "
else:
... |
dc2ad886a925e85a395a092284dfbcb194dff53a | javierdiaz13/CS-115 | /hw6.py | 5,058 | 3.921875 | 4 | '''
Created on: October 17, 2018
@author: Javier Diaz
Pledge: "I pledge my honor that I have abided by the Stevens Honor System"
CS115 - Hw 6
Got help from CS115 tutor!
'''
# Number of bits for data in the run-length encoding format.
# The assignment refers to this as k.
COMPRESSED_BLOCK_SIZE = 5
... |
4b6eca3b1599f8e722c0e45ff2bcd761a58061a3 | cce-bigdataintro-1160/winter2020-code | /3-python-notebook/9-functions.py | 696 | 3.671875 | 4 | #!/usr/bin/env python3
import os
def pretty_print(a):
return f"My value is: {a}"
def sum_one(a):
return a + 1
def sum(a, b):
return a + b
def prefix_string_with(prefix, string):
return f'{prefix}{string}'
def check(prefix, string):
return f'{prefix}{string}'
def reverse(s):
return s... |
c982d69679ac842fe9c1f02450c268d2a2aab4a9 | Pumacens/Competitive-Programming-Solutions | /CodeWars-excercises/Python/7_kyu/files/1. Remove duplicate words.py | 287 | 3.734375 | 4 | from collections import OrderedDict
def remove_duplicate_words(s):
return ' '.join(OrderedDict.fromkeys(s.split()).keys())
# Funciona a partir de python 3.6 porque los diccionaros ahora son ordenados
# def remove_duplicate_words(s):
# return ' '.join(dict.fromkeys(s.split())) |
699f0685c3e12389225ef7ec9a60d8683e69c99b | SaleemShahdi/Extended-Project | /quadrat/get_user_input.py | 998 | 3.546875 | 4 | from re import fullmatch
class Input:
@staticmethod
def read_double(text):
try:
x = input(text)
x = float(x)
return x
except ValueError:
return Input.read_double("That is not a number. Enter again: ")
@staticmethod
def get_decision(text):... |
e4afc36b9d8363092d8ef00c0a786c7e4480ffb9 | s1092877/ipfit5 | /Inladenimage.py | 4,296 | 3.53125 | 4 | # Importeer TKinter voor GUI
import tkinter as tk
from tkinter import *
from tkinter import filedialog
opdracht1 = "IP-adressen"
opdracht2 = "Mailadressen"
opdracht3 = "Entiteiten"
root = tk.Tk()
def main():
global var
var = IntVar()
# Toon welkom bericht
welkomLabel = tk.Label(roo... |
0cf72584ef95a40fa94fbd43b53552c23f8a0d3d | chybot/crawler | /CommonLib/DataParse.py | 1,508 | 4.0625 | 4 | # -*- coding: utf-8 -*-
import string
def listToCoupleList(lst):
"""
change list to a list with couple element in a touple
such as [1,2,3,4]=>[(1,2),(3,4)]
:param lst:
:return:
"""
return zip(lst[::2],lst[1::2])
def listToDict(lst):
return dict(zip(lst[::2],lst[1::2]))
def doubleListT... |
69cb8d5089dfd07e0965d81dd5057e928b4b6607 | Jeronimo-MZ/Math-And-PEMDAS | /MathGame.py | 527 | 3.734375 | 4 | from MyPythonClass import MathGame
from time import sleep
print('='*50)
print("Arithmetics game".center(50))
print("="*50)
starter = MathGame()
starter.Iniciar()
while True:
question = input("Do you want to see your Score?[Y/N]").upper()
if question == "Y":
starter.show_score()
break
elif q... |
f9f12d683fb245fac62d6c98cf1c6502ad930c89 | hihello-jy/portfolio | /2034연습문제8-운동에너지.py | 257 | 3.765625 | 4 | mass=float(input("물체의 무게를 입력하시오(킬로그램): "))
velocity=float(input("물체의 속도를 입력하시오(미터/초): "))
energy= 0.5*mass*velocity**2
print("물체는 "+str(energy)+"(줄)의 에너지를 가지고 있다.")
|
c47a62b1a08e261370975c60ae95c45406d30aaf | victorbrossa/curso_python | /exercicios2/exer2.py | 271 | 4 | 4 | '''Escreva um programa que abra um arquivo digitado pelo usuário
e imprima seu conteúdo na tela. '''
nome = input('Digite o nome do arquivo que voce deseja abrir: ')
arquivo = open(nome)
linhas = arquivo.readlines()
for linha in linhas:
print (linha.strip())
|
b759ace487a7b4c417c661f504d9ec41b79bf006 | eserebry/holbertonschool-higher_level_programming | /0x0B-python-input_output/14-pascal_triangle.py | 458 | 3.9375 | 4 | #!/usr/bin/python3
def pascal_triangle(n):
"""returns a list of lists of integers representing
the Pascal’s triangle of n
Args:
n - size of triangle
"""
outer = []
for i in range(n):
inner = []
for j in range(i + 1):
if j == 0 or j == i:
inner... |
7faa8b7639db9efc93bae988ad6bad83f60bec02 | varsha131/assignment1 | /6.py | 391 | 3.625 | 4 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #stars
num=int(input("enter the rows"))
for i in range(1,num+1):
for j in range(1,i+1):
... |
9f825661d8ea4317d8b13faa5596b23edd1b7497 | Cristinamulas/algorithms-for-big-data | /Quick_sort.py | 2,039 | 3.78125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 16:52:35 2019
@author: cristinamulas
"""
import numpy as np
import random
import time
def create_array (x,y):
randon_sample = random.sample(range(x), y)# creat an list of ramdon mumbers
array = np.array(randon_sample) # convert a list i... |
69a2005b0c91b87016f4b285e497cd334bec7bf0 | PilarPinto/holbertonschool-machine_learning | /math/0x00-linear_algebra/101-the_whole_barn.py | 1,308 | 3.609375 | 4 | #!/usr/bin/env python3
'''Adds two matrices'''
def matrix_shape(matrix):
'''Matrix shape function'''
shape_m = []
shape_m.append(len(matrix))
if type(matrix[0]) == list:
while type(matrix[0]) != int:
shape_m.append(len(matrix[0]))
matrix = matrix[0]
return shape_m
... |
de326a7b4f8959e50f39b9cc5278b00854d3529f | korowood/algorithm-and-data-structures | /1 - Сортировки и O-нотация/D. Количество инверсий.py | 775 | 3.578125 | 4 | """
input:
4
1 2 4 5
output:
0
"""
def merge_list(left, right):
ans = list()
i, j = 0, 0
count = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
ans.append(left[i])
i += 1
else:
ans.append(right[j])
j += 1
c... |
fec491fb51394beba56a1729ba21e7961f49b2fd | lorranapereira/exer_python | /exercicios/exercicio7.py | 2,316 | 3.78125 | 4 | #import datetime
#def func(year,month,day,aux):
# x = datetime.datetime(year,month,day)
# if aux==1:
# print(x.strftime('%Y')+','+x.strftime('%d')+' of '+x.strftime('%B'))
# if aux==2:
# print(x.strftime('%d')+'/'+x.strftime('%m')+'/'+x.strftime('%Y'))
#func(2000,9,8,1)
#func(2000,9,8,2)
#-----... |
77df4581317d5f632678eccb52ab312005e79de3 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/vgyric001/question1.py | 605 | 3.921875 | 4 | # Assignment 7
# Question 1
# Richard van Gysen
# 29 April 2014
# Enter strings
strings = input("Enter strings (end with DONE):\n")
lis = []
# Add strings
if strings!='DONE':
lis.append(strings)
# Terminate list when DONE is entered
while strings!='DONE':
strings = input()
if strings =='DONE':
... |
02afec53e27d3309dfce37ad347222c216c7339b | Graziele-Rodrigues/100-exercicios-resolvidos-em-python | /62_ProgressaoV2.py | 551 | 3.890625 | 4 | # Leia o primeiro termo e a razão de uma PA e mostre os 1 termos usando a estrutura while #
print('Gerador de PA')
print('-='*10)
primeiro = int(input('Primeiro termo: ' ))
razao = int(input('Razão da PA: '))
termo = primeiro
n = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while n <= total:
... |
fa0e7b118ab45e6aaa1cb00c91aa1ac8edd9af5d | richa92/Jenkin_Regression_Testing | /robo4.2/fusion/FusionLibrary/libs/utils/keyword.py | 356 | 3.640625 | 4 | import types
def convert_bool(s):
if isinstance(s, types.BooleanType):
return s
elif isinstance(s, types.StringType) or isinstance(s, types.UnicodeType):
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
raise Exception('Invalid val... |
d733b9facac06947a7f996532fc16083eea20bfb | Khushi2324/Python | /linked_list/merge_two_sorted_list.py | 665 | 4.03125 | 4 | class Node:
def __init__(self,data,next):
self.data=data
self.next=next
def merge(L1,L2):
L3=Node(None,None) #Create Empty List
prev=L3
while (L1!=None and L2!=None):
if L1.data<L2.data:
prev.next=L1
L1=L1.next
else:
prev.next=L2
... |
1b6fdf7141a4ed6ab1fef1a1787a707776c5c878 | msaio/pythonstuff | /get_ExchangeRate.py | 783 | 3.71875 | 4 | import requests
def get_currency_rates():
# Where USD is the base currency you want to use
url = 'https://api.exchangerate-api.com/v4/latest/USD'
# Making our request
response = requests.get(url)
data = response.json()
# Your JSON object
f = open("ExchangeRate.txt", "w")
#... |
698fe0d59bb083a6cad4454d44a1e12d0fe27877 | Microstrong0305/coding_interviews | /33.二叉搜索树的后序遍历序列/33.二叉搜索树的后序遍历序列.py | 596 | 3.6875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence) == 0:
return False
return self.check(sequence,0,len(sequence)-1)
def check(self,arr,start,end):
if start>=end:
return True
root = arr[... |
faff568661729dd13bdb94e1da75950cb78d364a | dhjnvytyjub/SpecialistPython2_v2 | /Module9/examples/02_collections_deque.py | 1,566 | 4.0625 | 4 | import collections
queue = collections.deque()
print(queue) # deque([]) - пустая очередь
queue.append("read book") # Добавляет элмент в очередь
queue.append("sleep") # Добавляет элмент в очередь
print(queue) # deque(['read book', 'sleep'])
queue.popleft() # Удаляет первый(левый) элемент очереди
print(queue) #... |
171f5c54fa923b55a9503e3af471d026685119e0 | Caimingzhu/Managing_Your_Biological_Data_with_Python_3 | /11-classes/11.4.3_subclasses.py | 769 | 3.84375 | 4 | '''
Classes can inherit from other classes
and extend their functionality.
-----------------------------------------------------------
(c) 2013 Allegra Via and Kristian Rother
Licensed under the conditions of the Python License
This code appears in section 11.4.3 of the book
"Managing Biological Data wit... |
ba908d07e25a6492ffa7e7641e0126e3f5ffcb4d | tundecmd/holbertonschool-interview | /0x1C-island_perimeter/0-island_perimeter.py | 561 | 3.78125 | 4 | #!/usr/bin/python3
"""Module perimeter"""
def island_perimeter(grid):
"""length of the perimeter"""
i = 0
for y, row in enumerate(grid):
for x, cell in enumerate(row):
if cell == 1:
if y == 0 or grid[y - 1][x] == 0:
i += 1
if y == len... |
5a554a8257b8a24d6f5958cad8a4ca18eb4852f2 | devender15/CoronaVirus_Updates_Checker | /main.py | 3,592 | 3.515625 | 4 | from bs4 import BeautifulSoup
import requests
from discord_webhooks import DiscordWebhooks
import datetime
def get_website(url):
r = requests.get(url)
return r.text
def updates():
my_data = get_website("https://www.worldometers.info/coronavirus/")
# creating soup instance for extracting data
soup = BeautifulSo... |
9fb1c08f046b7ae13d2fe420f299df1060fd4d91 | cooldoggy/Python-Projects | /BookExamples/Is it dark.py | 210 | 4.03125 | 4 | is_dark = input('Is it dark outside? (y/n)')
if is_dark == 'y':
print("O.K.! Goodnight! Zzzzzzzzzzzzzzzz......")
elif is_dark == 'n':
print("O.K! Staying On!")
else:
print("Invalid Input, please try again.") |
b15a3693699d361eea8a7b2b782e61e2b9071772 | therochaexperience/coursera-algorithmic-toolbox | /max_pairwise_product.py | 2,250 | 4.03125 | 4 | # Maximum pairwise prodcut
# Python 3.4.3
# Date: 11/5/2016
# Author: harryjrocha@gmail.com
# Finds two integers in a sequence that will give the largest product
# Assumes all integers are positive
import random
def maximum_pairwise_product(a):
# Goes through every possible pair of integers in a list; N... |
bdaa0e5c68b8408c729c9da8181defbc89fefa4c | mistryharsh28/A-December-of-Algorithms-2019 | /December-06/python_mistryharsh28_fibonacciPrimeNumberGeneration.py | 530 | 3.90625 | 4 |
def fibonacci_prime_numbers(n):
result = []
second_prev = 0
prev = 1
i = 0
while(i<n):
next_fibo = prev + second_prev
# check if next_fibo is prime
for j in range(2, next_fibo//2):
if next_fibo % j == 0:
break
else:
if(next... |
e2abc9a3b5f54cd6699b37968bd9ebd06907ff56 | siuols/Python-Basics | /strings.py | 2,216 | 4.21875 | 4 | def init():
input_string = input("Enter a string: ")
count = 0
upper_string(input_string)
lower_string(input_string)
count_string(input_string)
convertion_to_list(input_string)
indexing(input_string)
count_string(input_string)
reverse(input_string)
slicing(input_string)
start... |
126dd15cb721a5d913d3ee02f98214276c7e539d | ebby-s/ALevelCS | /Python Challenges/ebbyA206.py | 2,456 | 3.8125 | 4 | import random
class Card:
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
ranks = ["","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"]
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank
def __str__(self):
return (self.ranks[self.rank] + " of... |
851e9dfde3ec8fb771a90e9f87e4b77a292c7972 | aironm13/Python_Project_git | /Modules_learn/functools_Modules/functools_total_ordering.py | 349 | 3.65625 | 4 | from functools import total_ordering
@total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __gt__(self, other):
return self.age > other.age
def __lt__(self, other):
... |
4e39eb65f44e423d9695653291c6c15b95920df2 | rocket7/python | /S8_udemy_Sets.py | 695 | 4.1875 | 4 | ###############
# SETS - UNORDERED AND CONTAINS NO DUPLICATES
###############
# MUST BE IMMUTABLE
# CAN USE UNION AND INTERSECTION OPERATIONS
# CAN BE USED TO CLEAN UP DATA
animals = {"dog", "cat", "lion", "elephant", "tiger", "kangaroo"}
print(animals)
birds = set(["eagle", "falcon", "pigeon", "bluejay", "flaming... |
fcffc923213aecbe1ae7e9873f0f3739fe0dfe68 | manikandanmass-007/manikandanmass | /Python Programs/program to find a num is prime number or not.py | 276 | 4.21875 | 4 | #program to find a num is prime number or not
i=2
num=(int(input("enter the number...")))
while (i<=num-1):
if(num%i==0):
print("the given number is not a prime number")
break
i=i+1
if(i==num):
print("the given number is a prime number") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.