blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2d983e95c9e2cf1e657803ff6e27ffe32709f224 | harshkavdikar1/Data-Structures-and-Algorithms-with-Python-and-Java | /Linked List/quick_partition_linkedlist.py | 1,127 | 3.578125 | 4 | '''
Created on 14-Dec-2019
@author: Harsh
'''
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
root = head
left = right = None
if head and head.next:
if head.val >= x:
... |
3b50411f53871e26cec88f80e7cd8b1a49d5ffb2 | AbramicK16/Ra-1 | /dvojisko_drevo/DvojiskoDrevoRisi.py | 8,847 | 3.53125 | 4 | from tkinter import*
from math import*
from random import*
from time import*
class DvojiskoDrevo:
'''Implementacija razreda DvojiskoDrevo.'''
def __init__(self, podatek = None, levo = None, desno = None):
''' Konstruktor. '''
self._levoPoddrevo = levo
self... |
01ed4cca3a882cac91adea8c3c1fca042c0f77a3 | Prakhar-Saxena/CollegeAssignments | /CS481 - Advanced Artificial Intelligence/assn3/assn3.py | 434 | 3.53125 | 4 |
cardValues = [1, 2, 3, 4]
# hand is a list
hand1 = []
hand2 = []
def whoWon(hand1, hand2):
if sum(hand1) > 4 and sum(hand2) > 4:
return None
if sum(hand1) > 4 and sum(hand2) <= 4:
return 2
if sum(hand1) <= 4 and sum(hand2) > 4:
return 1
if sum(hand2) < sum(hand1) <= 4:
... |
1a2958056a7ae06d1ee90069f39bd0996df3f6e8 | ShaneOBhriain/machine_learning_dhs | /The SUM data set (without noise) - Classification.py | 2,641 | 3.578125 | 4 | # coding: utf-8
import pandas as pd
import numpy as np
# specify data set path
file ='Data Sets/The SUM dataset/without noise/The SUM dataset, without noise.csv'
# read CSV file directly from path and save the results
data = pd.read_csv(file, sep=';', index_col = 0) # 'sep' specifies separator used in the CSV file
#... |
1f647e7f226d2108b534ed1c7f14746c9e771217 | Ahyoh1/Loan-Prediction | /classFunc.py | 3,115 | 3.515625 | 4 | class modelCompile:
def __init__(self, pred_var, targ_var, scaled):
'''
Class initializes self with predictor features and target variable
pred_var contains dataframe of independent/predictor features
targ_var is the target variable
scaled: Takes in boolean value. Scales th... |
57e441c58e87cdc4b65e28bf7f8bb1f24fb88016 | justinminsk/Python_Files | /Intro_To_Python/Lec17/walk_through7.py | 1,115 | 3.890625 | 4 | whalecounts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
def find_two_smallest(L):
# Examine each value in the list in order
# Keep track of the indices of the two smallest values found so far
# Update these values when a new smaller value is found
# Return the two indices
#...or
# Set ... |
28a6f903e33696e572b3da388588d8b34871a2b9 | cal-poly-csc530-2174/tiny-lc-compiler-danielt105 | /lambdaPython.py | 4,191 | 3.984375 | 4 | #!/usr/bin/env python
import sys
import argparse
#parses a string input
def parseInput(userInput):
if userInput.startswith("(") and userInput.endswith(")"):
#remove parens
userInput = userInput[1: -1]
#lambda
if userInput.startswith("lambda") or userInput.startswith("λ"):
return parseLambda(userInput)
... |
779f484531c4dd9ea3e8e0130489b632cdaa97c3 | godfreytech/Python | /multi_re_find(2).py | 325 | 3.84375 | 4 | import re
def multi_re_find(patterns,phrase):
for pat in patterns:
print("Searching for pattern {}".format(pat))
print(re.findall(pat,phrase))
print('\n')
test_phrase = 'This is a string!'#NOW I WANT TO REMOVE THE CAPITAL LETTER T
test_patterns = ['[a-z]+']
multi_re_find(test_patterns,test_ph... |
fc95bb2fe422d3597e113b659bc8372d395fc4a1 | Healingl/Leetcode-Python-Algorithm | /Tree/19_generateTrees.py | 619 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# @Project: Leetcode-Python-Algorithm
# @IDE: PyCharm
# @File: 20_generateTrees.py
# @Author: ZhuangYuZhou
# @E-mail: 605540375@qq.com
# @Time: 2020/5/26
# @Desc:
# # # # # # # # # # # # # # # # # # # # # # ... |
1aaffc1f9ead9b53f24d96ef13c7b8e1bdcc4d3a | leonarita/Python | /Complemento/Orientação a Objetos/Banco/conta.py | 1,089 | 3.671875 | 4 | class Conta:
def __init__(self, nome, saldo, senha):
self.nome = nome
self.saldo = saldo
self.senha = senha
def consulta(self):
print("\n\t\t Seu saldo é ", self.saldo)
def deposito(self, valor):
self.saldo += valor
print("\n\t\t Seu saldo é ", self.saldo)
... |
02afd334423a75ded908d179bcb2b310e2d1ffcd | garvinipkiss/News-HIghlight | /app/tests/test_article.py | 750 | 3.78125 | 4 | import unittest
from app.models import Articles
class TestArticle(unittest.TestCase):
'''
Test Class to test the behaviour of the Article class
'''
def setUp(self):
'''
Set up that will run before every Test
'''
self.new_article = Articles("Palestinians evacuate the body of Palestinian journalist... |
a6f3ed9d095fd67e2329ceb079e5a06a4735ce1c | NajusAnaxi/UNet-based-for-Brain-Tumor-Segmentation | /bts/loss.py | 2,919 | 3.515625 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
class DiceLoss(nn.Module):
"""Sørensen–Dice coefficient loss to calculate
the mean loss over a batch of data.This loss mainly
calculates the similarity between two samples.
To know more about this loss check this link:
ht... |
4712faa3b843f6bf08da93182da28411d3b5102a | dubeyji10/PythonCoursera | /startPython.py | 639 | 3.59375 | 4 | def hello():
print("Hello, world!")
hello()
#---------------------------------------
#%%
def myname():
print("My name is Bill")
myname()
#-----------------------------------------
#%%
def ourschool():
print("Coursera is our school")
ourschool()
#-----------------------------------------
""" This w... |
6d4aa85140e26da3c277f4835851e21a849e6a41 | AtulCoder01/Programming-Notes | /Python/__str__&__repr__.py | 259 | 3.671875 | 4 | # __str__ & __repr__
class A:
def __init__(self):
self.val=10
def __str__(self):
return 'class A: __self__'
#def __repr__(self):
# return 'class A : __repr__'
__repr__=__str__#memeber function assign
a=A()
print (a)
print (repr(a))#builtin function
|
0d8f56ad72bd87d9aff9131f48108dfad077bbe5 | mzhao3/CS-HW-2017 | /02.10.2017hw.py | 596 | 4.125 | 4 | """
def sumOfPowers(n):
power = 1
sumpower= 0
while 2**power <= n:
sumpower = sumpower + 2 ** power
power = power + 1
return sumpower
print sumOfPowers(0)
print sumOfPowers(10)
print sumOfPowers(2)
"""
def sumAtoB(a,b):
sumab = 0
while a <= b:
sumab = sumab +... |
dab53475695d017d9f7e9886ab1f8397e8491b2c | Moeen-Farshbaf/assignment1-_- | /Scores.py | 413 | 4.03125 | 4 | name = input('Student name: ')
family = input('Student Family: ')
score1 = float(input('Enter 1st score'))
score2 = float(input('Enter 2nd score'))
score3 = float(input('Enter 3rd score'))
average = score3+score2+score1
average = average/3
print (name +" "+family+' is:')
if average < 12:
print('fail')
i... |
c053c7fbb1dac5047fc8a69e1b20d1c1f799c1f3 | tesstanya/Intro-to-Python | /Ch 4/ThreeDigitPalindrome.py | 282 | 4.3125 | 4 | # This program checks if the user
# input for a three digit integer
# is a palindrome
num = eval(input("Enter a three-digit integer: "))
# get the hundreths digit and the ones digit
if num // 100 == num % 10:
print(num, "is a palindrome")
else:
print(num, "is not a palindrome") |
810f199243a79c1f15abf590bb958bda5eb3f6d8 | imsilence/actual_05_homework_mage | /01/chaojie.gu/work2.py | 1,377 | 4.03125 | 4 | #encoding: utf-8
'''
猜数字游戏
随机生成一个0~100之间的数字,提示用户在控制台上输入一个数字
当用户输入的数字大于随机数,则打印猜大了
当用户输入的数字小于随机数,则打印猜小了
当用户输入的数字等于随机数,则打印猜对了
用户一共可以猜5次,如果5次都错误,则打印"太笨了,下次再来"
提示:生成随机数的方法
import random
random_num=random.randint(0,100)
'''
import random
random_num=random.randint(0,100)
count=5
user_input=input('请猜一个1到100之间的数:')
while count... |
96530a8eaff8c260020375d30853f58676fe1666 | courtney-sims/lunas-delivery-service | /archive/traffic.py | 892 | 3.53125 | 4 | from scene import Scene
class Traffic(Scene):
def __init__(self):
self.scenario = """
Luna begins the delivery route with great speed and efficiency.
Halfway through the route, she encounters a traffic jam.
"""
self.choices = [
{
"choice"... |
06448333e68cbadcaef859ad7c66c07304ffe972 | Sun-Zhen/leetcode | /0101-0150/0111-MinimumDepthOfBinaryTree/MinimumDepthOfBinaryTree.py | 1,298 | 3.765625 | 4 | # -*- coding:utf-8 -*-
"""
@author: Alden
@email: sunzhenhy@gmail.com
@date: 2018/4/6
@version: 1.0.0.0
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root:... |
927e7f03354eb0692b68fc17e24aeb9805f5c847 | kogansheina/euler | /p1_30/p11.py | 6,672 | 3.671875 | 4 | #!/usr/bin/env python
import os
"""
the greatest product of 4 adjacent numbers in one direction
"""
def right(row,column):
prod = 1
if column > len(row)-4:
return -1
try:
for j in range(column,column+4):
prod *= row[j]
except IndexError:
print "IndexError rig... |
13a9ba16bf9cd24d84a9c3a647c568edb65d67b7 | yosef8234/test | /pfadsai/10-mock-interviews/social-network-company/phone-screen.py | 1,923 | 3.9375 | 4 | # Phone Screen - SOLUTION
# Problem
# Remove duplicate characters in a given string keeping only the first occurrences. For example, if the input is ‘tree traversal’ the output will be ‘tre avsl’.
# Requirements
# Complete this problem on a text editor that does not have syntax highlighting, such as a goolge doc!
# ... |
8f388a15928d37b6581a43e9ae41e2945b814d0c | wfdoran/python-notes | /examples/ex1.py | 165 | 3.59375 | 4 | import matplotlib.pyplot as plt
x = [1,2,3,4,6]
y = [i*i - 5 * i for i in x]
plt.plot(x,y,"r*-")
plt.xlabel("foo")
plt.ylabel("bar")
plt.title("title")
plt.show()
|
22efb8b4ee092d5d9b78fa0c6769d4549cf08864 | Lebron-Kun/thoughtworks | /fib_test.py | 863 | 3.796875 | 4 | def fib(n):
if n <= 0 :
return None
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1,1]
for i in range(2, n):
fibs.append(fibs[i - 1] + fibs[i - 2])
return fibs
import unittest
class FibTest(unittest.TestCase):
def test_generate_5_fibs(s... |
f45eb498c0088ee757ea6c2a05d682f300f35100 | CristhianCastillo/introduction-computational-thinking-python | /edades_usuarios.py | 551 | 3.875 | 4 | def run ():
user_name_1 = input("USUARIO_1: Ingresa tu nombre: ")
user_age_1 = int(input("USUARIO_1: Ingresa tu edad: "))
user_name_2 = input("USUARIO_2: Ingresa tu nombre: ")
user_age_2 = int(input("USUARIO_2: Ingresa tu edad: "))
if(user_age_1 > user_age_2):
print(f'{user_name_1} es mayo... |
e7ecd5ec71e7fbf6477a8564af1a97d44650b2d7 | MiguelKorn/advent-of-code-2020 | /day_5/part_2.py | 339 | 3.578125 | 4 | input = open('input.txt', 'r')
input_list = input.read().split('\n')
highest = 0
seats = [int(p.replace('B', '1').replace('R', '1').replace('F', '0').replace('L', '0'), 2) for p in input_list]
seats.sort()
print(seats[-1])
for x in range(seats[0], seats[-1]):
if x not in seats and x + 1 in seats and x - 1 in seat... |
d7ffd7fbaced54657c9b89c119547ba71d0a3fed | anu-ka/coding-problems | /Python/common_characters.py | 1,405 | 3.859375 | 4 | # https://leetcode.com/problems/find-common-characters/
# Given a string array words, return an array of all characters that show up in
# all strings within the words (including duplicates). You may return the answer in any order.
import pytest
class Solution:
def commonChars(self, words: list[str]) -> list[str]... |
1284db079870a4a5006d962416c860215976e39d | LordGhostX/ML-Logistic-regression-algorithm-challenge | /Esenyi_Solomon/logisticregression.py | 1,638 | 3.65625 | 4 | import pandas as pd
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, accuracy_score
class LogisticRegression:
"""
Logistic regression implementation in Python
fit(X, y) - data to fit to the model... |
356dfcec6448b4b8dfae1d6ae94c498883d0fd48 | darshdmb/pyscript | /ex3.py | 455 | 4.46875 | 4 | print("chickens are:")
print("hens:", 25 + 30 / 6) #"," is very very very crucial
print("roosters:", 100-25+3%4) #"%" is for remaining in the division, in this case =3
print("now counting eggs")
print(3+2+1-5+4%2-1/4+6)
print("is this true that 3+2<5-7:", 3+2<5-7)
print("what's 3+2", 3+2)
print("what's 5-7", 5-7)
... |
7b1c68911e02a7baa5649282f0b56485e2b90ab7 | sahasatvik/assignments | /CS2201/assignment06/Q1.py | 464 | 3.84375 | 4 | #!/usr/bin/env python3
# Store data
years = [2009, 2010, 2011, 2012, 2013, 2015]
rainfall = [166.6, 473.2, 426.7, 318.3, 389.5, 458.5]
target = 2014
interp = 0.0
# Perform Lagrangian interpolation
for i, y_i in enumerate(years):
term = rainfall[i]
for j, y_j in enumerate(years):
if i == j:
... |
afc51a0a5cc26d50e92871ea265021e790ea80fc | Ocnarf2070/DataStructure | /MainHeap.py | 540 | 3.78125 | 4 | from Heap import *
print("BinaryHeap")
m = BinaryHeap([95, 3, 21])
m.push(10)
print(m)
print(m.pop())
print(m.peek())
print(m)
print(m.is_heap())
print('\n')
print("MaxHeap")
ma = MaxHeap([95, 3, 21])
ma.push(10)
print(ma)
print(ma.pop())
print(ma.peek())
print(ma)
print('\n')
print("WBLHeap")
wblh = WBLHeap()
for e... |
900a4a38f0b703f790f8c676a7110025e58d641c | akb46mayu/Data-Structures-and-Algorithms | /LintcodePartII/li81_dataStreamMedian.py | 1,569 | 3.703125 | 4 | """
Numbers keep coming, return the median of numbers at every time a new number added.
Have you met this question in a real interview? Yes
Clarification
What's the definition of Median?
- Median is the number that in the middle of a sorted array.
If there are n numbers in a sorted array A, the median is A[(n - 1) / ... |
79b2d67497f18c5dfc2a5f4dbf2224db10cbb018 | tlima1011/python3-curso-em-video | /ex058vs1.py | 566 | 3.578125 | 4 | from random import randint
from time import sleep
vezes = 0
num_cpu1 = 1
num_cpu = 0
print('\033[1;32m-=-\033[m' * 40)
while num_cpu1 != num_cpu:
num_cpu1 = randint(0, 10)
num_cpu = randint(0, 10)
print('\033[1;32mProcessando...\033[m')
sleep(1)
if num_cpu != num_cpu1:
print(f'\0... |
2298cd58a4d2b001fdeedf62b0c492af7601c758 | cvva/Clases-Python | /2_Ejemplos_Variables/ejem05.py | 128 | 3.703125 | 4 | #Operadores aritmeticos
x=100
print(repr(x)+" - "+repr(x+5)+" - "+repr(x-5))
print(repr(x*5)+" - "+repr(x/5)+" - "+repr(x%5)) |
f5d3c837414ec76b610c2b8cf0cd73728cac1102 | RIT-2015/CPS | /Homework_2/drawImage.py | 1,213 | 3.765625 | 4 | __author__ = 'Pratik'
import turtle
import math
TOTAL_WOOD = 550
'''
xcor = right wall of house
ycor = height of tree + 30 + 30
height of tree = max trunk length + head
'''
def draw_star(xcor, ycor):
turtle.up()
turtle.setposition(xcor, ycor+40)
turtle.down()
for x in range(0, 8):
... |
f2cb2f643553709e407a9f756eb8c33b6ab3ab14 | Jasonandy/Python-X | /cn/study/days100/days08/02定义类.py | 1,131 | 4.34375 | 4 | """
定义类对象
"""
# 定义student 对象
class Student(object):
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
# self 有点类似java的this? init 类似Java构造函数?
def __init__(self, name, age):
self.name = name
self.age = age
# study 学习这个动作
def study(self, course_name):
print... |
9b4299412239ff3029e03d9e3fd3dc1974a1e0cb | wjknihao/study | /wjktest,2.py | 171 | 3.96875 | 4 | sum =score=0
count=-1
while score!=-1:
score=int(input('请输入分数'))
sum+=score
count+=1
average=sum/count
print('共',count,'科','总分',sum,'平均',average)
|
e9acf4cf48c485d140717d8dc5d1b7aad2da1acf | sameerms/Hobbyprosjekter | /inf3331/src/py/examples/copytypes.py | 1,441 | 4.0625 | 4 | #!/usr/bin/env python
import copy
# number objects:
a = -99
b = a # b becomes a copy of a
a = 999
print b # b is still -99
# strings:
a = '-99'
b = a # b becomes a copy of a
a = '999'
print b # b is still '-99'
# user-defined objects:
class A:
def __init__(self, value=None):
self.value = value
... |
7657d8530421950fd450e09b2871c066a48ae315 | prajwalacharya016/CrackingCodingInterviewSolutions | /quest3.4.py | 737 | 3.703125 | 4 | class Tower:
def __init__(self, index):
self.stack = []
self.index = index
def get_index(self):
return self.index
def add(self, d):
self.stack.append(d)
def moveTopTo(self,t):
top=self.stack.pop()
t.add(top)
print "Move disks {0} from {1} to {2}... |
091b78f8f776b9b82a4701241e3110b420af653d | ZTatman/Daily-Programming-Problems | /Day 8/problem8.py | 1,869 | 3.875 | 4 | # Author: Zachariah Tatman
# Date: 6/4/2021
'''
'''
import sys
class Node:
'''Node class'''
def __init__(self, data):
self.data = data
self.right = None
self.left = None
# class Tree:
# '''Tree class'''
# def __init__(self):
# self.root = None
# def add(self, val):
#... |
8b06e098d7fe9caa1cd383d7cf577f49f8f24f76 | Gagan-453/Python-Practicals | /GUI/Canvas/Creating arcs.py | 1,269 | 4.3125 | 4 | #Creating arcs using Canvas
from tkinter import *
#Create a root window
root = Tk()
# var c is Canvas class object
# root is the name of the parent window, bg is background colour, height is the height of the window and width is the breadth of window, cursor represents the shape of the cursor in the canvas
c = Canvas(... |
5ede6d469e335aa67438e846744e05f42a4f65c3 | gaTarr/PythonasaurusRex | /Module11/student.py | 1,815 | 3.59375 | 4 | """CIS189 Python
Author: Greg Tarr
Created: 11/04/2019"""
from person import Person
class Student(Person):
"""Student class"""
def __init__(self, student_id, last_name, first_name, major='Computer Science', gpa=0.0):
valid_characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567... |
eba6d18e6598c2c7f3ae941aecf8caa2340a6421 | Ishanth-Studios/convertion_python | /convertion.py | 974 | 4.5625 | 5 | # Welcome back to python tutorial, In this
# video we are going to see how to make a convertion program
# for fahrenheit and celsius
# Inputs
number = float(input("Enter the number: "))
convertion_symbol = input("Enter the convertion symbol: ")
# convertion process
def convert (num,symbol):
if symbol.u... |
47f9bec67353ce2b5555845bbd29acfae168caab | simrankaursoin/NYU_CS1134 | /hw2/sks684_hw2_q4.py | 421 | 3.671875 | 4 | '''
Simran Soin
CS UY 1134
22 February 2019
Homework 2 Question 4
'''
def e_approx(n):
sum_approx = 1
prev_factorial = 1
for i in range(1,n+1):
prev_factorial*=i
sum_approx += ((1)/(prev_factorial))
return sum_approx
def main():
for n in range(15):
curr_approx = e_approx(n)
... |
dc97b73f112a79feade5950b5a28597651e30fee | njakstudio/FizzBuzz-Pytest-Test | /fizzbuzz_test.py | 1,425 | 3.9375 | 4 | # Importing the function fizzbuzz() from the file fizzbuzz.py
from fizzbuzz import fizzbuzz
class TestFizzBuzz:
# When I fizzbuzz number 1, I get back a string representing it
def test_answerFor1(self):
assert fizzbuzz(1) == 1
# When I fizzbuzz number 2, I get back a string representing it
def test_answerFor... |
661b3389ce174d320a21c0ef6bced7906e7c14fa | robsoncezrio/python-django | /orientacao_objetos_SI/prog2.py | 550 | 3.921875 | 4 | #w3school é a referência para Python
class Pessoa:
#construtor
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def sono(self):
return self.idade / 3
class Aluno(Pessoa):
#construtor
def __init__(self, matricula, nome, idade):
self.matricula = ... |
215ffe619760567117d0bd2b349f62448e10ef41 | aafshar17/mission_to_mars | /mars_scraper.py | 4,019 | 3.5625 | 4 |
# coding: utf-8
# In[13]:
# Import BeautifulSoup for parsing and splinter for site navigation
import pandas as pd
import time
from bs4 import BeautifulSoup
from splinter import Browser
def init_browser():
executable_path = {"executable_path": "chromedriver.exe"}
return Browser("chrome", **executable_path,... |
9766ed23a35c8373c231d8be6b339e215d18daee | stsewd/TheRoomPartyProblem | /room_party.py | 2,939 | 3.96875 | 4 | """ The room party problem
Problema de sincronización obtenido de: The Little Book of Semaphores. Allen B Downey
Autor: Santos Gallegos
"""
import threading
import time
class Decano:
def __init__(self):
self.dentro = False
def __entrar(self):
print("Decano entrando")
self.dentro = T... |
5d6e47a3c22c10f2ea0e7163312349ac7adcfced | kvalluru-srk/pdsnd_github | /bikeshare.py | 9,706 | 4.25 | 4 | # Main program function is at the end of the code 6 functions
# Display function was added after inital submission
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'Chicago': 'chicago.csv',
'New York': 'new_york_city.csv',
'Washington': 'washington.csv' }
def get_filters():... |
b51d9424e22ea44515d83b8bfe1e8368e3b87fd9 | people-lover/NLP-pipeline-using-Spacy | /facts.py | 763 | 3.75 | 4 | # Extracting facts
import spacy
import textacy.extract
# Load the large English NLP model
nlp = spacy.load('en_core_web_lg')
# The text we want to examine
text = """London is the capital and most populous city of England and the United Kingdom.
Standing on the River Thames in the south east of the island of Great... |
393c18e0dded7c77a1440224bc95554a7c9f50b4 | Kriegersan/Project-Euler | /3x5.py | 281 | 3.6875 | 4 | #!/bin/env python
def byThreeFive(a):
if(a % 3 == 0 or a % 5 == 0):
return a
def main():
total = []
stuff = range(1000)
for things in stuff:
total.append(byThreeFive(things))
st = [x for x in total if x is not None]
print sum(st)
if __name__ == '__main__':
main()
|
91f64840c3a1768e4302feb691890033615cbcde | KrisWu618/Algorithm-Practice | /SortLettes.py | 309 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 29 18:00:05 2017
@author: kubla
"""
import re
def sortSegments(s):
string_list = re.split(r'(\d+)',s)
for i in range(0,len(string_list)):
string_list[i] = ''.join(sorted(string_list[i]))
merge = ''.join(string_list)
return(merge)
|
ae9edaa2fff0148010ed642f3a469a93a6cb0786 | noootown/algorithm | /leetcode/binary search/436.py | 599 | 3.671875 | 4 | # https://leetcode.com/problems/find-right-interval/description/
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
import bisect
class Solution:
def findRightInterval(self, intervals):
"""
:type intervals: List[Inter... |
4e410ac42c2108be2fb0b955632f17f04e0a3da3 | AhmetTuncel/CodeKata | /CodeKata/8_Rank/Sum_without_highest_and_lowest_number_Kata.py | 373 | 4 | 4 | """
Sum all the numbers of the array except the highest and the lowest element (the value, not the index!).
(The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!)
"""
def sum_array(arr):
if not arr or len(arr) <= 2:
return 0
e... |
39051dba7022832846c7ad8b5becb2a7f7ac1b3e | danielnavarro831/Battleship_Remade | /Player.py | 6,093 | 3.671875 | 4 | from Ship import Ship
from Grid import Grid
import random
class Player:
def __init__(self, Name, Player_Number):
self.Name = Name.title()
if Player_Number > 0 and Player_Number < 3:
self.Player_Num = Player_Number
else:
raise Exception("Invalid Player Numbe... |
fa9ec94cdbf28401998d08bf470481f9aad1313e | lion30/forum | /tempory.py | 1,825 | 4.09375 | 4 | import math
lists = [69, 65, 90, 37, 92, 6, 28, 54]
print(lists)
'''insert_sort'''
# 将待排序元素与列表中在它序号后面的元素进行比较,并递增这一过程
#print(insert_sort(lists))
#print(insert_sort(lists))
'''shell_sort'''
# 将待排序列表中元素进行分组,然后比较
#print(shell_sort(lists))
#print(shell_sort_1(lists))
'''bubble_sort'''
#将待排序元素两两比较
#print(bubble... |
2a2e6167c4bdb57b9ce8aebe062843aa955ab23c | ayangacann/hicheel4 | /Dasgaluud/8.py | 211 | 3.625 | 4 | # 8. 4оронтой тооны зуутын орны тоо тэгш бол true үгүй бол false гэж хэвлэ.
n = int(input())
if ((n // 100 % 10) % 2 == 0):
print(True)
else:
print(False)
|
537a8bcfc030851f0e5ce3bb1a923abdc6cd0b3a | JBMATANDA/Algorithm-Test | /Algorithm/InsertionSort.py | 524 | 3.921875 | 4 |
def sort(a_list):
global count
count = 0
insertion_sort(a_list)
return count
def insertion_sort(a_list):
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index
while increment_count() and position > 0 and a_list[position - 1] > current_value:... |
550f2c48ea563485017bccc3cd7573e7d711cb49 | CodeSik/2021_Algorithm | /Greedy/1541.py | 794 | 3.59375 | 4 | def main():
input_arr = list(input().split("-"))
result = 0
if "+" in input_arr[0]:
sub_arr = input_arr[0].split("+")
sub_result = 0
for sub_num in sub_arr:
sub_result += int(sub_num)
result += sub_result
elif "+" not in input_arr[0]:
result += int(in... |
b12175f8ff97f34cffa8c93efce1cf004cf71e92 | nathanzhu144/coding | /coding_exercises/array/basics/window_sliding.py | 648 | 4.09375 | 4 | # https://www.geeksforgeeks.org/window-sliding-technique/
# Nathan Zhu
# 9:20 pm Saturday October 6th, 2018
#
# Window sliding is a key concept for reducing runtime
def find_max_sum_of_subarray(arr, window):
window_sum = sum(arr[0:window])
max = window_sum
for i in range(1, len(arr) - window):
... |
70172b3e6364c5196b3d944bcb48233edb00d7b8 | alcivar-inca/SegundoBimestre | /semana 9/ejercicio3.py | 205 | 3.546875 | 4 | # PROGRAMA QUE DIBUJA UN CUADRADO DE LADO 150
import turtle
t=turtle.Pen()
t.forward(150)
t.left(90)
t.forward(150)
t.left(90)
t.forward(150)
t.left(90)
t.forward(150)
turtle.getscreen()._root.mainloop() |
a7789f8e533afca9dc919c7733673d0e97101a55 | valleyceo/code_journal | /1. Problems/h. Sort & Search/Template/c. Merge Sort Inplace.py | 1,124 | 3.6875 | 4 | # Mergesort in-place
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
self.mergeSort(0, len(nums)-1, nums)
return nums
def mergeSort(self, l: int, r: int, nums: List[int]):
if l < r:
m = l + (r-l)//2
self.mergeSort(l, m... |
1bc2422c279c4e6e50e58392fb21980af128b9b6 | annProg/learn | /interview/baidu.py | 585 | 3.6875 | 4 | #!/usr/bin/env python2.6
# -*- coding:utf-8 -*-
#-----------------------------------------------------------
# Usage: use python2
# $Id: baidu.py i@annhe.net 2015-08-03 17:56:10 $
#-----------------------------------------------------------
#输出如下形式的数字
# 0
# 0 1
# 0 1 2
# ...
# 现场使用Python2
def func1(x):
for i in ... |
252e0a99564d77e3ec8e0fe65dacac1f364e11e0 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Summation/24_sum_of_all_leaf_nodes.py | 736 | 3.875 | 4 | ''' Sum of all leaf nodes '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def sum_leaf_nodes_util(node, leaf_sum):
if not node:
return 0
if not node.left and not node.right:
leaf_sum[0] += node.val
su... |
60933c9e240127d15cadb95396665d3d721a253a | ibadullaevn/webdev2020 | /lab7/codingBat/Warmup-1/front_back.py | 141 | 3.75 | 4 | def front_back(str):
if len(str) <= 1:
return str
str = str[-1] + str[1:-1] + str[0]
return str
print(front_back("a"))
|
dd1bdf8747158fb5459803b3869f822df3d70988 | NeilCarvalho/LetsupgradeAssignments | /Print X to the power of Y.py | 162 | 3.921875 | 4 | a = int(input("Please enter a number(the base numeral):"))
b = int(input("Please enter a number(the exponent):"))
print(a, "to the power", b, "is", a ** b) |
45c25a249e9bf30ba8a6560ebe66cc6a279e3227 | krastin/pp-cs3.0 | /chapter-10/exercise04.py | 1,757 | 3.671875 | 4 | from typing import TextIO
from io import StringIO
def skip_header(reader: TextIO) -> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
... |
d2b761383c2656c244c8ff8f3cdc76ff5b9f7a85 | etcadinfinitum/advent | /2021/01/solution.py | 557 | 3.515625 | 4 | def first():
count = last = -1
with open('data.txt', 'r') as f:
for line in [int(x.strip()) for x in f.readlines()]:
if line > last:
count += 1
last = line
return count
def second():
count = last = -1
with open('data.txt', 'r') as f:
lines = [... |
9f55eceb5aaf64ff61db325fefc14a6fc581c075 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2315/60812/290647.py | 509 | 3.671875 | 4 | def height(tree, node):
temp = tree[node]
lh = rh = 0
n = len(temp)
if n == 2:
rh = height(tree, temp[1])
if n > 0:
lh = height(tree, temp[0])
return 1+max(lh, rh)
n = int(input())
tree = {i: [] for i in range(n)}
retree = {i: -1 for i in range(n)}
for i in range(n-1):
f, s... |
fc4ad84c8126dfeb8d733a56d7207796af321fb4 | RyanSept/Andela-Programming-Logic | /programming_logic.py | 1,484 | 4.28125 | 4 | #this generates prime numbers up to given parameter 'end'
#it returns a list
def prime_generator(end):
if type(end)!=type(1):
raise ValueError
if end<=1:
return []
#empty list for storing generated numbers
l = [2,]
#we loop
for n in range(0,end+1):
if is_prime(n):
... |
97d5295fc35d925ac34aea43ca654a5ecf48311c | udhayprakash/PythonMaterial | /python3/13_OOP/f_Advanced/11_Memento_pattern.py | 997 | 4.09375 | 4 | #!/usr/bin/python
"""
Purpose: Memento Design Pattern example
https://en.wikipedia.org/wiki/Memento_pattern
"""
class Memento(object):
def __init__(self, state):
self._state = state
def get_saved_state(self):
return self._state
class Originator(object):
_state = ""
def set(self... |
61af3e8647c853146abc3c9bec138ba44aae1093 | Elmo33/e-olymp | /0000-0999/924.py | 119 | 3.5625 | 4 | from math import pi, sqrt
s, r1 = map(float, input().split())
print(format(round(sqrt(r1 ** 2 - s / pi), 2), '.2f'))
|
9bc1060541d5ac97af9e078789d40b9f50febd6f | lakshmanboddoju/Deep_Learning_Prerequisites_The_Numpy_Stack_in_Python | /2/4-Lists_vs_numpy_arrays.py | 923 | 4.15625 | 4 | import numpy as np
L = [1, 2, 3]
A = np.array([1, 2, 3])
for e in L:
print(e)
for e in A:
print(e)
# Works
L.append(4)
# Doesn't work
try:
A.append(4)
except:
print("Can't append to numpy array.")
# Works
L = L + [5, 6]
# Dosn't work
try:
A = A + [4, 5, 6]
except:
print("Can't append list... |
53bac241ed50c3ff59cb552a5e90b07470abfff0 | ChiakiChiaki/leetcode | /Array/34. Search for a Range.py | 1,754 | 4.09375 | 4 | #Author:Sun Jian
'''
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target ... |
8f94ef4c4e0c013cd46ca538b59a91687bfaabf4 | AJLightfoot/hello-world | /CH6-Dictionary-Alien0.py | 1,789 | 4.375 | 4 | alien_0 = {'color': 'green', 'points': 5} #dictionary stores key value pairs - key:value indicated by the {} braces
print(alien_0['color'])
print(alien_0['points'])
#you can add to and change dictionaries
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position... |
95cea6da07f7dd1f3dcbff8fac85ffedff0690a8 | i35186513/270201057 | /Lab2/example5.py | 125 | 3.9375 | 4 | a= int(input("One side lenght:"))
b = int(input("The other side lenght:"))
hypotenuse = ((a**2 +b**2)**0.5)
print(hypotenuse) |
ecdc4cfe2b759a4aa0c26aee0addb0dd6afd7e38 | iamrishap/PythonBits | /InterviewBits/tree/root-to-leaf-path-with-sum.py | 1,276 | 4.03125 | 4 | """
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
... |
352a40cd0059270c5447214654577f2ea9e3c923 | heenbo/my_python_test | /001_hello/main2.py | 232 | 3.75 | 4 | #!/usr/bin/python2
print("Hello Python")
#print('hahahaha', '111', '222', '333', sep='>>', end='', files=sys.stdout,
# flush=False)
a = input("input num a:")
b = input("input num b:")
a += b
print(a)
print("hahahaha")
|
33421ce7f89b65d4fe6e5d7755b60a15ba95adb5 | elkorb/self-py-solutions | /722.py | 195 | 3.6875 | 4 | def numbers_letters_count(my_str):
digits = 0
letters = 0
for item in my_str:
letters+=1
if item.isdigit():
digits += 1
return [digits,letters-digits] |
401acc727cf468a13b9e89973112d5f2d5998ba4 | tianqing617/PythonStudy | /advancedUsage/sliceDemo.py | 272 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# 切片的几种用法
L = list(range(20))
print(L[0:3])
print(L[:3])
print(L[-3:])
print(L[:10:2])
print(L[:])
print('-----------------------------------------------')
# 字符串也可以使用切片
print('ABCDEFG'[:3])
print('ABCDEFG'[::2]) |
bc02344761b09b57042bfdaebe0c050501696775 | kritikadusad/HackerRank | /max_array_sum.py | 1,030 | 4.3125 | 4 | """
Given an array of integers, find the subset of non-adjacent elements
with the maximum sum. Calculate the sum of that subset.
Example:
>>> max_subset_sum([-2, 1, 3,-4,5])
8
>>> max_subset_sum([3, 7, 4, 6, 5])
13
>>> max_subset_sum([2,1,5,8,4])
11
>>> max_subset_sum([3, 5, -7, 8, 10])
15
"""
def max_subset_sum(ar... |
e8b911c8572b1e3c8a9fcc2347ea519945eb63f4 | Beck-Haywood/Recursion_And_Search | /search.py | 2,688 | 4.3125 | 4 | def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_iterative(array, item)
#... |
2aa63d019f42772bee994bdb4baee637d6ce370c | Edward11235/AutoZoomRecorder | /database.py | 1,921 | 3.5 | 4 | class DataBase:
def __init__(self, filename):
self.filename = filename
if filename == "info.txt":
self.btnlist = None
self.file = None
self.load()
else:
self.userlist = None
self.userfile = None
self.zoomid = "zoom id (... |
3323296d4868d5957817a0322b9b1bccdb2ff683 | akansh028/6-Weeks-to-Interview-Ready | /quickstart_guides/bit_manipulation/python/set_nth_bit.py | 868 | 4.0625 | 4 | """
Title: Set n^th bit
Problem:
Write a program that takes an integer and
sets the n-th bit in the binary representation of
that integer
For instance, the binary representation of 6 is:
110
The least significant bit is the bit on the far right
of the binary representation and the mos... |
73c5f9f2c1e2f5a7499b3ade6886280a62f4f3ab | dudengjin/python.two | /python假期作业/第六章/字典.py | 836 | 3.703125 | 4 | message = {'first_name':'dengjin','last_name':'du','city':'taiyuan'}
print(message['first_name'])
print(message['last_name'])
print(message['city'])
print("---------------------------------------")
for k,v in message.items():
print(k,v)
print("---------------------------------------")
number = {'du':'2','li':'3','... |
b91247673fc0dc62ba12abfc52a7cbfa9c541e24 | M-Murad-Ahmed/AVATAR | /ImageCorrection.py | 834 | 3.640625 | 4 | import cv2
class ImageCorrection:
"""
returns a grayscale image of the image passed in its argument
@frame is the opencv image passed
"""
def get_gray(self, frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return self.apply_filter(gray)
'''
applies bilateral filter ... |
eef96557c25c5b26913f3aa951f0285bf31ac049 | jd3johns/dsa | /python/trees/tree.py | 659 | 3.796875 | 4 | class BinaryTree:
def __init__(self, root_data=None):
self.root_data = root_data
self.left_tree = None
self.right_tree = None
def append(self, data):
if self.root_data is None:
self.root_data = data
elif data < self.root_data:
if self.left_tree is... |
128d0f4217ede4b94043027c0b9f1b3d0d4cb542 | JunLei-MI/PythonX | /ToolsX/leetcode/0112/0112.py | 689 | 3.640625 | 4 | from leetcode import TreeNode
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
"""
减去 root,然后继续判断 child
"""
if not root:
# return sum == 0
return False
dif = sum - root.val
if dif == 0:
if not root.left and ... |
e913200efc6c4e742a14d90d6eff73116af22cbb | MuhammadNaqi03/Movie-Recommender-Using-REST-API | /Movie Recommender.py | 4,401 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 12:46:39 2020
@author: Nobody
"""
import json
import requests
def get_movie_recommendations(ls):
'''
Takes a list of movie(s) as input and upon getting related movies and their infos
from get_related_movies() and get_data_from_OMDB() respec... |
1782d5649d926879a13edcf3ee458d2cbff19f59 | 2flcastro/python-exercises | /solutions/2flcastro/beginner/factorializeNumber.py | 2,299 | 4.3125 | 4 | # ----------------------------------
# Facorialize A Number
# ----------------------------------
# Return a factorial of the provided ineger.
# If the integer is represented with the letter "n", a
# factorial is the product of all positive integers less
# than or equal to n.
#
# Factorials are often represented with th... |
40ef7c9f690ad2f0d4ff352cb59032bf08b71926 | arsamigullin/problem_solving_python | /leet/facebook/trees_and_graphs/binary_tree_maximum_path_sum.py | 2,045 | 3.890625 | 4 |
# this algo uses PostOrder traversal
# at the root node we check if current sum of tree (made of current node being a root and its left and right children)
# has maximum value by updating global max_sum variable
# But since we look for path we must return node.val + max(node.left.val, node.right.val)
# let's consider ... |
c1313d85049ba1d45fd7e2bb8018e15e7b92fb2a | MaxIakovliev/algorithms | /old/Session002/Arrays/RevealCardsInIncreasingOrder.py | 544 | 3.78125 | 4 | class Solution:
"""
https://leetcode.com/problems/reveal-cards-in-increasing-order/
answer: https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/257891/Python-(easy-to-understand)-solution
"""
def deckRevealedIncreasing(self, deck: 'List[int]') -> 'List[int]':
sd= sorted(de... |
62a3e0306d82ddce02ba9f471c7b0d1f3ffa9199 | wangtao666666/Data-structure-Algorithm | /Sort/2-sort.py | 492 | 3.546875 | 4 | #encoding='utf-8'
"""
短冒泡排序
"""
def shortBubbleSort(alist):
exchanges = True
item = len(alist) - 1
while item > 0 and exchanges:
exchanges = False
for i in range(item):
if alist[i] > alist[i+1]:
exchanges = True
temp = alist[i]
... |
5386c3ee00da7024fc0a3e08ef12f13324df9029 | AWangHe/Python-basis | /13.tkinter与银行系统实战/thinker/3.Button控件.py | 561 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import tkinter
def func():
print("sunck is a good man")
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("魔兽世界")
#设置大小和位置 大小400x400 距离左侧400,距离上侧100
win.geometry("400x400+400+100")
#创建按钮
button1 = tkinter.Button(win, text="按钮", command=func, width=10, height=5)
button1.pack()
#使用匿名函数
button2... |
9438c3c16e1ea6f8bf95974775a9bec30160254f | RoopaBorkar/AI_Machine_Learning | /pyspark_restapi_dataframe_creation.py | 1,221 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Fetching the data from REST API
# In[1]:
import requests
# In[2]:
response=requests.get('https://api.covid19api.com/summary').text
# In[3]:
response
# # Json data is loaded as Dictionary
# In[4]:
import json
# In[5]:
response_info=json.loads(response)
# ... |
5940ee5f8eec90b644245c72bfb219364a9d3628 | nthnjustice/FletcherPythonWorkshop | /Round1/Classes.py | 1,153 | 4.21875 | 4 | class Apple:
typeof = "Food"
def __init__(self, kcal, col):
self.calories = kcal
self.color = col
class Pizza:
typeof = "Food"
def __init__(self, kcal):
self.calories = kcal
class Soda:
typeof = "Drink"
def __init__(self, kcal):
self.calories = kcal
myApple = Apple(70, 'red') #Declares ... |
2533ad2e8c6499083391be5efbe182899ca029ab | Dennis-coder/sudoku_solver | /sudoku_solver_backend/main.py | 578 | 3.5 | 4 | import math
import time
from sudoku import Sudoku
start = time.perf_counter()
sudokuStr = open("sudoku.txt").read()
sudoku = Sudoku(sudokuStr)
sudoku.solve()
end = time.perf_counter()
print("time:", (end - start))
sudoku.print()
print(sudoku.correct())
# print("Rows:")
# for row in sudoku.rows:
# print(row)
# ... |
a423cd77496d1e0f8e7b266d901d5e57a3d29665 | krstoilo/SoftUni-Fundamentals | /Python-Fundamentals/Homeworks-and-labs/functions/calculations.py | 452 | 4.125 | 4 | operator = input()
int1 = int(input())
int2 = int(input())
def calculate(int1, int2, oper):
result = None
if oper == 'multiply':
result = int1 * int2
elif oper == 'divide':
if int2 is not 0:
result = int(int1 / int2)
else:
print("WRONG")
elif oper == 'ad... |
7760844630b8d3562a51d96bac23fd74632bb691 | allanlealluz/Python-First-tests | /ex068.py | 539 | 3.71875 | 4 | import random
palpite = 'null'
c= 0
while True:
numrand = random.randint(1,100)
palpite = input('par ou impar? ')
n = int(input('escolha um numero de 1 a 100'))
result = numrand + n
if result % 2 == 0 and palpite.upper() == 'PAR':
print('você ganhou')
c += 1
elif result % 2 != 0 ... |
bc8875dfcb63f9a7d5932c4a2800bb3a4742187e | sang2770/Python | /Learn Basic/Set.py | 715 | 3.859375 | 4 | ##Create
mySet={1,2,3};
print(mySet);
mySet=set([4,2,2,3]);
print(mySet);
##add
mySet.add(5); ##One element
print(mySet);
mySet.update([1,7,8]); ##many element
print(mySet);
##Delete
mySet.discard(8);
print(mySet);
##Show err if element no exits
##mySet.remove(10);
mySet.remove(1);
print(mySet);
##phép hợp
mySet1={... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.