blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
666c5cbb97457b30df45afc0afe5080038a0adf7 | crampete/full_stack_course | /python/01_basic_python/03_control_statements/02_for/02.py | 82 | 3.671875 | 4 | total = 0
for number in range(1, 21):
total += number * number
print(total)
|
59fc631daf4121f03b773adde1bce56ed662f035 | salmonmoose/problems | /euler/python/p002.py | 187 | 3.5625 | 4 | previous = 1
current = 1
count = 0
while current < 4000000:
if (current % 2) == 0:
count = count + current
temp = current
current = previous + current
previous = temp
print(count) |
06940045e971682e0c5f30e17bb137d7b82d119b | tuanpn93/tuanpham | /HW01/Exercise03.py | 335 | 4.03125 | 4 | s = 'Hi John, welcome to python programming for beginner!'
print('a. Check if "python" exists in s : ', "python" in s)
position = s.find("John")
s1 = s[position:position + 4]
print('b. Extract the word "John" from s : ', s1)
print('c. Count character "o" in s : ', s.count("o"))
print('d. Count how many word s : ', ... |
332e334a29b961a5f6d1e9b47a08d486a22b7a48 | ihyf/exercise | /python_test/2017/02/test_0216.py | 418 | 3.5625 | 4 | # coding:utf-8
import operator
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student('Luna', 10)
s2 = Student('Spe', 13)
s3 = Student('Lina', 16)
list_student = [s1, s2, s3]
cmp_ful = operator.attrgetter('age') # 以此属性排序
print(cmp_ful)
list_student.s... |
3e9e40877f5f27b02e8d1d8f5cdeb0b833656b0c | jmbjorndalen/SimpleTS | /SimpleTS_Test.py | 661 | 3.53125 | 4 | """
Test program for SimpleTS.
Author : John Markus Bjorndalen <johnm@cs.uit.no>
Version: 1.1
"""
import SimpleTS
import threading
import time
TSNAME = "tst"
SimpleTS.provideTS(TSNAME)
time.sleep(1)
def test():
print "**** test function, 'computing' for a while"
time.sleep(3)
print "**** ... |
5b186308a91d4b390d5883fba8ae1e701c2d6049 | Sonjongkook/Algorithm-Practice | /TrophyDisplay(bj1668)/Solution.py | 346 | 4.0625 | 4 | n = int(input())
num_list = []
for i in range(n):
num = int(input())
num_list.append(num)
def findCount(array):
tallest = array[0]
count = 1
for n in range(1, len(array)):
if tallest < array[n]:
tallest = array[n]
count += 1
return count
print(findCount(num_list))
num_list.reverse()
p... |
a387aac29d2d36ed011ed2d154d550e46c5e6715 | Tokyo113/leetcode_python | /code_05_binarySearch.py | 661 | 4 | 4 | #coding:utf-8
'''
@Time: 2019/10/10 19:50
@author: Tokyo
@file: code_05_binarySearch.py
@desc: 二分查找
'''
def binary_search(arr, item):
"""
递归实现二分查找
:param arr:
:param item:
"""
if len(arr) >= 1:
mid = len(arr) >> 1
if (item > arr[mid]):
# 注意一定要加return,否则返回mid后顺序往下执行,最... |
66b574dd0708e7f8f08aa851739d0382010e7fde | tanzim721/Python | /2-bubble sort.py | 803 | 4 | 4 | """
Name : Tanzimul Islam
Roll : 180636
Session : 2017-18
E-mail : tanzimulislam799@gmail.com
Blog : https://tanzim36.blogspot.com/
Dept.of ICE, Pabna University of Science and Technology
"""
#Problem-2: Write a program to sort a linear array using the bubble sort algorithm
from array import *
def bubbleSort(... |
dc16ad4f9f15740359f17eeb3ff7c1690c794e16 | jfangmeyerjr/EnergyGDPScience | /HW3.py | 31,193 | 3.734375 | 4 |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.5** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._
#
... |
63f3baa2347adf2e45d712a40565041639bea771 | EoinStankard/pands-problem-set | /ProblemTwo-begins-with-t.py | 757 | 4.5 | 4 | #Name: Eoin Stankard
#Date: 13/03/2019
#Problem Two:Write a program that outputs whether or not today is a day that begins with the
#letter T. An example of running this program on a Thursday is as follows.
#References: https://docs.python.org/3/library/datatypes.html
import datetime
weekdays = ["Monday","Tuesday","We... |
3664d971dd0319ae6e551e8fa7085de7a75b1cf5 | lytvyn139/udemy-complete-python3-bootcamp | /OOP-classes/OOP.py | 3,105 | 4.125 | 4 | mylist = [1,2,3]
myset = set()
type(mylist) #list
type(myset) #set
#class name can be without () if it's not inheriting
class Dog():
# CLASS OBJ ATTRIBUTE
# SAME FOR ANY INSTANCE OF A CLASS
species = 'mammal'
def __init__(self, breed, name, spots="NO SPOTS"):
self.my_attribute = breed
... |
bda72e6a20198b7feb6ae807cc58e34c9c7b5b3f | bb04265/PythonStudy | /solving/chap03/chap03_01_03.py | 109 | 3.671875 | 4 | weight = int(input("짐 : "))
if weight >= 20 :
print("넘무거웡")
else :
print("수수료없엉") |
ad01a59877bd6590705889e5d255ef73c49a2be7 | kajal8512/python | /reverse.py | 161 | 3.640625 | 4 | places=["delhi", "gujrat", "rajasthan", "punjab", "kerala"]
i=0
list_p=[]
while i<len(places):
a=places[-i-1]
list_p.append(a)
i=i+1
print(list_p)
|
36c068291c650174c4d4f72729d87b5760a0f0bc | swastia/Python | /LamdaPrac.py | 288 | 3.8125 | 4 | #square
my_list = [5,4,3]
squared_list = list(map(lambda num : num**2, my_list))
print(squared_list)
#sortList
a = [(10,-1), (5,2), (8,5), (0,1)]
#sorting based on first value
a.sort()
print(a)
#sorting based on second value in the list
a.sort(key= lambda item : item[1])
print(a)
|
839e934c546104e0ef6f60b35bb0ad2e9482c987 | Tanokri/Lockdown-Mental-Disease | /Sasta_Starbucks.py | 3,620 | 4.1875 | 4 | # This program helps create a customised Boba tea for a customer based on their budget and preferences
print("""Welcome to Cha Literally Means Tea! We strive to provide you with the best
boba cha in the entire plaza located on Figueroa where Yoshinoya is!\n""")
budget = float(input("What's your budget for the order ... |
f40eb83430ad57547ae9ce7c5ae88be503fc91d7 | supraja-powerofn/Python | /question2.py | 1,886 | 4.15625 | 4 | import random
options = ['rock','paper','scissor']
user_sc , comp_sc = int(0),int(0)
while (user_sc != 5 or comp_sc != 5):
comp_ch = random.choice(options)
user_ch = input(str('Enter your choice: rock,paper or scissor ')).lower()
if(user_ch == 'rock'):
if(comp_ch == 'scissor'):
print(... |
8f1c2904ed817995995246e26f29b3b746e90fd8 | rizniyarasheed/python | /Flowcontrolls/looping/NumReverse.py | 443 | 4.0625 | 4 |
#num=int(input("enter the number :"))
#while(num>0):
# digit=num%10
# print(digit,end=" ")
# num=num//10
#palindrom
#multiply with10+digit
num=int(input("enter the number :"))
res=0
while(num>0):
digit=num%10
res=res*10+digit
num = num // 10
print("res=", res)
#string
#num=int(input("enter ... |
2d4ca116f93580c85d33ebdacfcf2ee9c5d24f8e | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc067/A/4746890.py | 313 | 3.609375 | 4 | from math import*
n=factorial(int(input()))
def dv(n):
if n==1:
return 1
divisorsNum=1
i=2
while i*i<=n:
cnt=1
while n%i==0:
cnt+=1
n//=i
divisorsNum*=cnt
i+=1
return divisorsNum*2
mod=(10**9+7)
print(dv(n)%mod) |
9caa21a98474a33eef0df910e834ef5050a7bc90 | lastmayday/Euler | /37.py | 935 | 3.953125 | 4 | #-*- coding:utf-8 -*-
"""
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that ... |
d03fff2f8c832f594b7e74f3ff2da0021df2722f | henryZe/code | /python_study/basic/dict.py | 401 | 3.90625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#dictionary
d = {'Mike': 95, 'Bob': 75, 'Tracy': 90}
print(d['Mike'])
print('Henry' in d)
print(d.get('Bob'))
d.pop('Bob')
print(d)
#set
s1 = set([1, 2, 3, 1, 2])
s1.add(4)
s1.remove(1)
s2 = set([4, 5, 6, 7])
print('s1 =', s1)
print('s2 =', s2)
print('s1 & s2 =', s1 & s2)
pr... |
bb9e1fae2d5d49d435e310ebf153000769a7b478 | matthew-d-ng/SecureCloudStorage | /encrypt_util.py | 1,027 | 3.578125 | 4 | from cryptography.fernet import Fernet
import sys
import os
def encrypt_file(folder, filename, key):
f = Fernet(key)
plainfile = open(folder+filename, "rb")
plaintext = plainfile.read()
plainfile.close()
ciphertext = f.encrypt(plaintext)
cipherfile = open(folder + ".encrypted/" + filename+ ".... |
f23ab4f5483cd1835c9e744650947b25ea1ffaea | granluo/P4-Streetmap-Data-Wrangling | /test.py | 966 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# content = u'\xe5\xb1\x82\xe5\x8f\xa0\xe6\xa0\xb7\xe5\xbc\x8f\xe8\xa1\xa8'
# print content.encode('latin1').decode('utf8')
# print 'San Jos\xe9'.encode("latin1").decode("utf-8")
# import re
utfbytes = "\xc2\xa9 \xc2\xae \xe2\x84\xa2 \xe9"
print utfbytes, len(utfbytes)
san... |
298613a5ecebea8c5d02abfaddd6ae03862e99af | l82as/test_py | /test_file/Казак/task_4.py | 342 | 3.828125 | 4 | S=int(input())
N=int(input())
m1=0 #Масса вещей в рюкзаке
m2=0 #Масса вещей в чемодане
for i in range(1, N+1):
m=int(input()) #Масса вещи
if m<=S and m1+m<S:
m1+=m
elif m>S or m1+m>S:
m2+=m
print( m1)
print( m2)
|
88fd2bf674a6545ff3578e3db1438373c20535b0 | shepardo/geeksforgeeks | /graphs/dfs/dfs2.py | 1,498 | 4.375 | 4 | # Python3 program to print DFS traversal
# from a given given graph
from collections import defaultdict
# This class represents a directed graph using
# adjacency list representation
class Graph:
# Constructor
def __init__(self, n):
self.n = n
# default dictionary to store graph
self.graph = defaultdict(list... |
c996073f54ec26129769b1c92f51072f485b8016 | datormx/PensamientoComputacionalPython | /dictionario_iteracion.py | 281 | 4.15625 | 4 | my_dict = {'Miguel': 25, 'David': 35, 'Juan': 40,}
for llave in my_dict.keys():
print(f'Llave: {llave}')
for valor in my_dict.values():
print(f'Valor: {valor}')
for llave, valor in my_dict.items():
print(f'Llave: {llave}, Valor: {valor}')
print('David' in my_dict)
|
1ce90fd7299bcdfafe6443497b348203e1d4e690 | kmurphy/coderdojo | /04-Some_More_Turtle_Graphics/code/Color_Square_Spiral_2.py | 244 | 3.71875 | 4 | # draw a square spiral
import turtle
bob = turtle.Turtle()
window = turtle.Screen()
window.bgcolor("black")
colors = ["red", "yellow", "blue", "green"]
for x in range(200):
bob.color(colors[x%4])
bob.forward(2*x)
bob.left(91)
|
5f8033da429c8684fe1220c04be4a97c78133a4c | Jerinca/Heuristieken | /AmstelHaege/code/random_distribution.py | 4,210 | 3.578125 | 4 | # Hoi, hier moet nog een greedy komen die niet selecteerd op grootste afstand
# maar op de hoogste score op moment van beslissing
# Project: Amstelhaege
# Name: Team Blauw
# Time: 12:48
#
# This program applies the greedy algorithm to
# the optimalization problem AmstelHaege.
import csv
import pandas as pd
import nump... |
bbea3d21e0eb21e414a1fa2f57b9494d4165256c | jimmykobe1171/leetcode | /depth_first_search/symmetric_tree.py | 1,272 | 4.4375 | 4 | """
**Problem description:**
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric::
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not::
1
/ ... |
9ff2f9d88680f288ff19075e477a4c4e3ceeaaca | gyurel/SoftUni-Basics-and-Fundamentals | /First_steps_March_Excercise/Books_to_read.py | 477 | 4.03125 | 4 | #1. Брой страници в текущата книга – цяло число;
#2. Страници, които може да прочита за 1 час – цяло число;
#3. Броя на дните, за които трябва да прочете книгата – цяло число;
pages = int(input())
pages_per_hpour = int(input())
days_to_read = int(input())
hours_a_day_to_read = (pages / days_to_read)/pages_per_hpour
... |
04d2aeee3862ad0a0556815fc7b441db5736711a | Threeboys33/designers | /generate_class/factory/Factory.py | 3,377 | 3.640625 | 4 | from enum import Enum
class Commodity(Enum): # 商品类别分类枚举
shoe = 1
clothing = 2
appliance = 3
class Goods(object): # 工厂模式 产品抽象类 abstract product
def __init__(self, category, name, size):
self._category = category
self._name = name
self._size = size
@property # 将实例的私有变量公... |
9d3aaedc73ac71fef553629a8a2f74b462d31e89 | brianmickel/set-game-set-finder | /set_check.py | 4,267 | 3.671875 | 4 | import math
from itertools import combinations
#input a board of cards
#output whether or not a set exists
"""
representing cards
four digit number where
+-------+-------+--------+------+
| color | shape | number | fill |
+-------+-------+--------+------+
Color:
1 - Green
2 - Purple
3 -... |
0ce901e92365403191250bd74759bc611b5c6385 | ujin2021/AlgorithmForEveryone | /code/q8/q8_practice.py | 332 | 3.71875 | 4 | # 선택정렬을 이용하여 내림차순 정렬 해보기
def sort_desc(a) :
n = len(a)
for i in range(0, n - 1) :
max_idx = i
for j in range(i + 1, n) :
if(a[max_idx] < a[j]) :
max_idx = j
a[i], a[max_idx] = a[max_idx], a[i]
d = [2, 4, 5, 1, 3]
sort_desc(d)
print(d) |
f75559ffc57e46d0b16b5901845742baa27504f9 | fmowl10/kmucs_swp2_class_2_Team_5 | /assn7/20181598.py | 884 | 3.65625 | 4 | class Guess:
def __init__(self, word):
self.secretWord = word
self.guessedChars = []
self.numTries = 0
self.answerBlank = []
for j in range(len(self.secretWord)):
self.answerBlank.append('_')
def display(self):
print('Current: ', ''.join(self.answer... |
513dc5e574dbf95cc6db7882ab85aadbbae1096f | EricSchles/dp | /dp_examples.py | 266 | 3.671875 | 4 | def get_fib(n):
fib = [1,1]
if n >= 2:
for i in xrange(2,n):
fib.append(fib[i-1] + fib[i-2])
return fib
print get_fib(15)[14]
def r_fib(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return r_fib(n-1) + r_fib(n-2)
print r_fib(15)
|
b12d5f3bf41755919f6c31a176ff81b6860f0cd4 | patryk-siewiera/exercises | /Python_CodeWars/Moderate (6 5 4)/Detect Pangram.py | 882 | 4.03125 | 4 | # 6 kyu
# A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence
# "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is
# irrelevant). Given a string, detect whether or not it is a pangram. Return ... |
b37b2a187afcd0cd4f2af145af768e7b92712322 | Aujasvi-Moudgil/Classification-and-Representation-Learning | /Autonomous Work/AutonomousWork_2/Aujasvi_AW2/Question1-2.py | 664 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 4 22:20:24 2017
@author: Aujasvi
"""
from numpy import*
import matplotlib.pyplot as plt
#Load the dataset
data = loadtxt('polynome.data')
#Seprate the input from the output
X = data[:, 0]
Y = data[:, 1]
N = len (X)
def visualize (w): #Plot the data
plt.plot(X,Y,'r.... |
838c06ebd1ba1fae2819507c17a8e5288b9006a9 | student-work-agu-gis2021/lesson9-geopandas-Miwa-Yamamori | /Exercise_9_problem_2.py | 2,031 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Problem 2: Points to map
#
# In this problem we continue to learn how to turn latitude and longitude coordinates in to geometries.
#
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
# YOUR CODE HERE 1 to read data
# Read the CSV file
data = ... |
a4169130f443a51e5dadfe6b02ee3846140f25d1 | PriyankaKhire/ProgrammingPracticePython | /Maximum Subarray pt2.py | 828 | 3.5 | 4 | #Maximum Subarray
#https://leetcode.com/problems/maximum-subarray/
class Solution(object):
def fillMatrix(self, nums, matrix):
maxSum = nums[0]
row = 0
col = 0
while(row < len(nums)):
if(row == col):
matrix[row][col] = nums[row]
else:... |
2b79d3cbb19f4baf5e91a5cfec4ba1d8ce766be5 | armyrunner/CS2420_IntroAlgorithims | /Graphs/main.py | 774 | 3.59375 | 4 | from graphs import Graphs
from stack import Stack
def main():
fin = open("input.txt","r")
numVert = int(fin.readline())
numEdges = int(fin.readline())
g = Graphs(numVert)
for i in range(numEdges):
pair = fin.readline()
numbers = pair.split()
V0 = int(numbers[0])... |
c946759e4de4e581f7eb367fc43bf659706cb206 | gschen/sctu-ds-2020 | /1906101026-邓静/20200229.py/03.py | 192 | 4 | 4 | #3. (使用def函数完成)找出传入函数的列表或元组的奇数位对应的元素,并返回一个新的列表
list=[1,2,3,4,5,6,7]
def h(x):
return list[::2]
print(h(list))
|
34d1d3f1ec058275dd6e42d926f739244b7a10c3 | Bar-BelliedCuckooshrike/EstudosPython | /Filter.py | 1,139 | 3.78125 | 4 | """
Filter:
Serve para filtrar dados de uma determinada coleção.
"""
#Biblioteca para trabalhar com dados estatísticos:
import statistics
#Dados coletados de algum sensor:
dados =[1.3, 2.7, 0.8, 4.1, 4.3, -0.1]
#Calculando a média dos dados utilizando a função mean():
media = statistics.mean(dados)
print(f'Média: {m... |
2064beeb50bb8a26f7d70813f89ee2dde00c4b27 | hsuoamra/CSC-120-Computer-Fundamentals | /file1.py | 341 | 3.703125 | 4 | import random
def create_list():
my_list = []
MAX_LEN = 50
for i in range(MAX_LEN):
my_list.append(random.randint(1,99))
sorted_list = sorted(my_list)
min_num = sorted_list[0]
#print(my_list)
#print(sorted_list)
print("The minimum number in the list is: ", min_num)
#return my_list
#Calling the fu... |
5005ef9e158307262ffad5495b9e3c923cdc952e | JeromeRocheEnsta/Genetic-Algorithm | /algo.py | 3,066 | 3.84375 | 4 | #coding=utf-8
from main import Individual, Population
import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def main(input_array, pop_size, selection_method, renew_rate, win_rate, MAX_GEN=1000):
"""
Main algorithm to seek the solution: the longest zero-sum sub... |
4d01eeecd4c5a87e84166d956b4caf0d944a81dc | sguha-work/PythonTraining | /Adv_Python_Training/Day3/ex8.py | 547 | 3.890625 | 4 | print('==============================================================')
class MyClass:
memberVariable1 = None
def __init__(self):
self.memberVariable1 = 'basic value'
def display(self, userGivenValue=None):
if userGivenValue != None:
self.memberVariable1 = userGivenValue
... |
811476845e18e5562ca9f564e7e9c211e43a0d29 | harshitsilly/Basics | /1 - Variables/Additional Exercises/additional_exercise17.py | 622 | 4.5 | 4 | #16-01-2012
#additional exercise 12
#sample solution
import math
print("Distance Climbed")
print("This program calculates how much height is gained when travelling a")
print("given distance and an incline angle")
print()
distanceTravelled = float(input("Please enter the distance travelled: "))
inclineAngle = float(in... |
f8c996b42a2093ce343b68950a7161ca77d5cd28 | sbasak3/Map-Reduce | /Part3/query.py | 2,593 | 3.9375 | 4 | import sys
import re
import csv
class Movie:
def searcher(self):
print "Enter the Query to be searched either as : <word> or <word1> <operator> <word2>"
print "Enter any digit(0-9) to exit"
phrase = raw_input();
pattern = re.compile('[0-9]+')
if (pattern.matc... |
5272611ee2d924b3dcdac677b6f349e7864fa370 | alhursalman/shaziscool | /harryiscool.py | 84 | 3.890625 | 4 | g = ("You are ")
d =("a wixard ")
n =input("What's your name? ")
print (g + d + n+"!") |
e82edc666d271c4a79bc8d3e8af4c53ebea29950 | Soluspero/coding_practice | /techgig_solutions/data_structure/arrays/onedArray/count_specific_element.py | 429 | 3.703125 | 4 | ''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
import sys
def main():
# Write code here
n = int(input().strip())
alist = [int(x) for x in input().strip().split()]
ll=[]
for i in alist:
if i%3==0 or i%5==0:
... |
fd97074a847003660dd5b3d8833a7a3384b8f53b | SahilMund/A_ML_Cheatsheets | /Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 39 - Artificial Neural Networks (ANN)/ArtificialNeuralNetworks.py | 2,097 | 3.6875 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
#categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#creatin... |
65827b9125a8df7de9166f21c79f8a48061ffb33 | maguas01/hackerRank | /pStuff/RepeatedString.py | 662 | 3.75 | 4 | #!/bin/python
'''
Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.
Given an integer, n, find and print the number of letter a's in the first n letters of Lilah's infinite string.
'''
import sys
def solve(s, n) :
count = 0
for c in s :
if c == 'a' :
... |
c54dd03c2b100ba934d3d31d9cefb0aea88cd006 | ChrisCodesNow/wb | /03_greedy_recursion_dynamic/03_sorting/03_intervals.py | 1,973 | 3.921875 | 4 | '''
Approach 1:
Sort intervals by start value
Merge overlaping intervals (inclusive)
Edge case: No intervals => Stop
Runtime: O(n)
Space Complexity: O(1)
'''
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
re... |
bf2012fc6c39c0c2f76a60b7a3b74efc76dd82f4 | jakewhlr/cs457 | /pa2/jesql_commands.py | 11,131 | 3.65625 | 4 | """Does stuff"""
import os
import sys
import shutil
import re
import operator
def create():
pass
def drop():
pass
def create_db(name):
"""Creates database as directory"""
database_dir = os.path.join(sys.path[0], "databases")
if not os.path.exists(database_dir): # if databases dir doesn't exist
... |
b7311773e6ee89c985ee32c9a927bd5fc608c0b1 | stgstg27/Titanic | /Kaggletitanic.py | 4,248 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 05 12:20:29 2017
@author: Saurabh
"""
from __future__ import print_function
import csv
import pandas as pd
from math import ceil
import numpy as np
from sklearn import tree
def max_three( a , b, c):
if(a>b and a>c):
return a
elif(b>a... |
e06227af5edd3a4da7fbc03ca7bc310c367fe017 | Gamez0/LeetCode-Solutions | /Python/496_nextgreaterelement.py | 365 | 3.5 | 4 | class Solution:
def check(self, number, nums1, nums2):
index = nums2.index(number)
for _ in range(index, len(nums2)):
if(nums2[_]>number):
return nums2[_]
return -1
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
return ... |
dd2c14d01fd2545510d5f1143263bb98bf794e5d | JIceberg/TicTacToe | /src/main.py | 3,310 | 3.671875 | 4 | from tkinter import *
from enum import Enum
import numpy as np # the lord and savior
class Tile(Enum):
TOP_LEFT = (0, 0)
TOP_MID = (0, 1)
TOP_RIGHT = (0, 2)
MID_LEFT = (1, 0)
MID_MID = (1, 1)
MID_RIGHT = (1, 2)
BOTTOM_LEFT = (2, 0)
BOTTOM_MID = (2, 1)
BOTTOM_RIGHT = (2, 2)
'''
Use... |
dc1b46711a4798b817ddc079fd58cdabe5cc673f | bazhenov4job/client_server | /lesson_01/homework/task_4.py | 993 | 3.8125 | 4 | """
4. Преобразовать слова «разработка», «администрирование», «protocol»,
«standard» из строкового представления в байтовое и выполнить
обратное преобразование (используя методы encode и decode).
Подсказки:
--- используйте списки и циклы, не дублируйте функции
"""
WORDS = ['разработка', 'администрирование', 'protoco... |
b0730815184762a3e568aba42e8a085abf424a3f | Silentsoul04/FTSP_2020 | /W3_2020_School/Python_Variables.py | 5,326 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 17:24:59 2020
@author: Rajesh
"""
'''
Python Variables :-
----------------
'''
Variables are containers for storing data values.
Unlike other programming languages, Python has no command for declaring a variable.
A variable is created the moment you first assign a v... |
bc2427ae37b9e6c3414d1e416863afca6ad9d2d3 | chenxu0602/LeetCode | /110.balanced-binary-tree.py | 2,598 | 3.875 | 4 | #
# @lc app=leetcode id=110 lang=python3
#
# [110] Balanced Binary Tree
#
# https://leetcode.com/problems/balanced-binary-tree/description/
#
# algorithms
# Easy (41.51%)
# Likes: 1498
# Dislikes: 136
# Total Accepted: 364.1K
# Total Submissions: 869.1K
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# Given a b... |
c700a0b94da718fe88ccb635fa7f36bdc911dfc0 | Shubha737/100-days-code-challenge | /regex_match.py | 285 | 3.515625 | 4 | # Day 35 code 2
# regex_match
urls = ''' https://www.google.com
https://coreyms.com
https://www.youtube.com
https://www.nasa.gov/ '''
import re
Pattern = re.compile(r'(https)://[a-z]+\.[a-z]*(\.*)(com|gov*)')
matches = Pattern.finditer(urls)
for match in matches :
print(match) |
f96258b1d9a53c47d31c841a862e47b8552239d9 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4308/codes/1590_1016.py | 352 | 3.796875 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
from math import*
a = float(input("a"))
b = float(input("b"))
c = float(input("c"))
s = ( a + b + c) / 2
Area = sqrt(s * (s - a) * (s - b)... |
0343b99efc353adf3f376e84c3d26a5117e6ded1 | dineshKumar777/Python-Excercies | /question15.py | 503 | 3.984375 | 4 | '''
Question 15
Level 2
Question:
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
Hints:
In case of input data being supplied to the question, it should be assumed to be a console... |
8e453eb6c6760750169876e769db854101be7c28 | zhanzhewan/app2 | /04-多任务-进程/代码/06-多进程之间通过Queue来实现数据共享.py | 1,148 | 3.640625 | 4 | import multiprocessing
"""
一个进程向Queue中写入数据,另外一个进程从Queue中获取数据,
通过Queue完成了 多个需要配合的进程间的数据共享,从而能够 起到 解耦的作用
"""
def download_from_web(q):
"""下载数据"""
# 模拟从网上下载的数据
data = [11, 22, 33, 44]
# 向队列中写入数据
for temp in data:
q.put(temp)
print("---下载器已经下载完了数据并且存入到队列中----")
def analysis_data(q):
... |
7712059e8e561b17386c72cbde5d885cbdee3da1 | greenkarson/python | /PythonStudy/inchi.py | 310 | 3.71875 | 4 | """
英制转换公制
version: 0.1
author: karson
"""
value = float(input("请输入长度"))
unit = input("请输入单位")
if unit == "in":
print("转换为厘米是%.1f" % (value*2.54))
elif unit == "cm":
print("转换为英寸是%.1f" % (value * 0.3937))
else:
print("请输入正确单位") |
a3f0c9084a8aef6874e3980a56fae3c7e04a4fe8 | dwagon/pydominion | /dominion/cards/KnightCard_Sirvander.py | 1,696 | 3.609375 | 4 | #!/usr/bin/env python
import unittest
from dominion import Game, Piles
from dominion import Card
from dominion.cards.Card_Knight import KnightCard
###############################################################################
class Card_Sirvander(KnightCard):
def __init__(self):
KnightCard.__init__(self... |
01267e14ead927edd50a851ca1d12aee4a70eb2c | gideondev/Machine-Learning-CSE-574 | /Handwritten Digits Classification using Neural Networks/facennScript.py | 8,714 | 3.515625 | 4 | '''
Comparing single layer MLP with deep MLP (using TensorFlow)
'''
import numpy as np
from scipy.optimize import minimize
import pickle
from math import sqrt
import time
def one_heater(label):
heat = np.zeros((2,))
heat[label] = 1
return heat
def sigmoid(z):
"""# Notice that z can be a scalar, a vec... |
56decf6aaafdb85d449b7c2dc0598994ed3ecd45 | kingstarfly/CZ2101 | /Lab 2/dijkstra2.py | 6,388 | 3.96875 | 4 | """
Suppose the input graph G = (V, E) is stored in an array of adjacency lists and
we use a minimizing heap for the priority queue. Implement the Dijkstra’s
algorithm using this setting and analyze its time complexity with respect to |V|
and |E| both theoretically and empirically.
"""
import math
from collections i... |
3dd1730f60758e04672a481a1b8963609f80cb1c | i5ar/eccrypt | /bin/eccrypt | 1,398 | 3.8125 | 4 | #!/usr/bin/env python
"""Easy encryption and decryption."""
import argparse
from eccrypt.encrypt import encrypt
from eccrypt.decrypt import decrypt
parser = argparse.ArgumentParser(description='AES encryption and decryption.')
parser.add_argument('crypt', choices=['encrypt', 'decrypt'],
help='Cry... |
ffc6fc06c9a9d36be5c31b25bb0e5e622afdc64f | ABenxj/leetcode | /59 generateMatrix.py | 1,304 | 3.84375 | 4 | #!/usr/bin/env pyhton
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 , Inc. All Rights Reserved
#
"""
Authors: jufei
Date: 2021/4/20 1:45 PM
"""
from typing import List
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
"""
按模拟的顺利遍历即可
:param n:
:return:
... |
9c6b0fab4a3e52fc401544a6b6ca965ad73a384b | JustinStephan/Algorithms | /Large Factorial.py | 612 | 4.09375 | 4 | def factorial(n):
calculated = [1]
if n == 1 or n == 0:
return 1
else:
for i in range(1,n):
#print(i)
calculated.append(i * calculated[i-1])
return n *calculated[n-1]
def numCount(num):
count=0
while num > 0:
num //= 10
... |
2f2b62752a914d8b4c069f08d72b9964e050f78d | beidou9313/deeptest | /第一期/杭州-张月萍/area of circle.py | 227 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# __author__ = 'Carina'
# 计算圆的面积
import math
banjing = int(input("Enter banjing:"))
a = 2
area = math.pi * banjing ** a
print("半径为{} 的圆的面积是{:.10f}".format(banjing,area))
|
c1201fa96374ee24761c06fd7c933585c5566271 | SebastianoF/calie | /calie/aux/grid_generator.py | 651 | 3.8125 | 4 | import numpy as np
def grid_generator(x_size=101,
y_size=101,
x_step=10,
y_step=10,
line_thickness=1):
"""
Creates a grid image (3d numpy array) after specified input.
:param x_size:
:param y_size:
:param x_step:
:para... |
caccc8db1fadaeeb0bf06ba620779aafd4e6065d | AYehia0/codingame | /compete/fastest/leap_years_inbetween.py | 348 | 3.53125 | 4 | """
count the number of leep years in between 2 years
"""
a = int(input())
b = int(input())
count = 0
for i in range(a,b+1):
if (i % 4) == 0:
if (i % 100) == 0:
if (i % 400) == 0:
count += 1
else:
pass
else:
count += 1
else... |
bd89f052f5c0f045a851782981101ea0e94a2b8f | rjshekar90/udemy-DS | /L60.py | 587 | 3.953125 | 4 | # Reverse the words in a list
def rev_words(s):
words = []
length = len(s)
spaces = [" "]
i = 0
while i < length:
if s[i] not in spaces:
wordstart = i
while i < length and s[i] not in spaces:
i += 1
words.append(s[wordstart:i])
... |
85e79776fd60d3c265093dd4b29d3e7fb592850c | ratchfordt/cmpt120Ratchford | /fibonacci.py | 454 | 4.40625 | 4 | # Fibonacci.py
# This program computes the nth number in the Fibonacci sequence
def main():
print("Fibonacci Calculator (Positive numbers only please)")
n = eval(input("Input a number to calculate using the Fibonacci sequence: "))
ans = fibonacci(n)
print(ans)
def fibonacci(i):
i = abs(i)
if... |
99cba8dfb17e33d45b0a70da345f3e6d46b1c606 | alfonso-torres/TDD_with_python | /simple_calc.py | 393 | 3.75 | 4 | class SimpleCalc:
#pass
def add(self, value1, value2):
return value1 + value2
# this function adds the values for value1 and value2 and return the result
def subtract(self, value1, value2):
return value1 - value2
def multiply(self, value1, value2):
return value1 * valu... |
b4dd334076c02cf0d0aa07d2dfea14da9b9e997b | Th3Lourde/l33tcode | /problemSets/300/practice/227.py | 1,656 | 3.625 | 4 | import math
'''
12-3*4
'''
class Solution:
def calculate(self, s):
s = s.replace(" ", "")
ops = set({"*", "/", "+", "-"})
ans = []
tmp = ""
i = 0
while i < len(s):
symbol = s[i]
if symbol in ops:
ans.append(tmp)
... |
b316f2863de2031e3e4a7467d206a3daf36d9abb | EomSunYoung/pyworks | /Day19/scorepass.py | 835 | 3.734375 | 4 | # 학생의 시험 점수 합격 판단
# 조건이 60점 이상이면 '합격', 아니면 '불합격'
score = [90, 45, 67, 59, 85]
idx = 0
print("for ~ in 리스트 반복문")
for i in score:
idx += 1
if i >= 60:
print(str(idx) + "번 학생은 합격입니다.")
else:
print(str(idx) + "번 학생은 불합격입니다.")
# print(i)
print()
print("for ~ in range 반복문")
n = len(score)
f... |
da8ddd7f42c1a47027e20f731875ce2fefcd454b | nrhint/GitGames | /Breakout/ball.py | 2,278 | 3.546875 | 4 | ##Nathan Hinton
##This is the file for the ball
import pygame
from random import randint#For the start
from math import sin, cos
#from time import sleep#This is for slowing down the program
def radians(x):
return x*3.14/180
class Ball:
def __init__(self, screen, speed = 3):
self.screen = screen
... |
562e6695d62da72fe18c6bc06df2bb6a702b98eb | pawangeek/Python-codes | /Maths/Sieve_eratosthenes.py | 265 | 3.703125 | 4 | # Working : first we iterate through all numbers to n, and one by one exclude non-prime numbers by storing them in a list
t = int(input())
d=[]
for i in range(2,t+1):
if i not in d:
print(i)
for j in range(i*i,t+1,i):
d.append(j) |
2e53d8cb3ffea789c523501acbb06a0ac5352291 | JamyangLotus/Web-scraping-in-Python | /Web_scrap.py | 533 | 3.609375 | 4 | import requests
from bs4 import BeautifulSoup
//Creating an instances of a requests.
result = requests.get("https://www.google.com/");
//Accessing the status_code attribute and it will return 200 for OK.
print(result.status_code)
//prints a long list of headers
print(result.headers)
//Scraping the content of a... |
c85c4b302ec41f330d134f69719affa35ad5a202 | ajakaiye33/pythonic_daily_capsules | /value_c.py | 677 | 3.953125 | 4 |
a = 10
b = 3
c = 7
def test_score(b):
a = 11
return a + b + c
c = + c + test_score(5)
print(c)
customer = {
"UT": [{
"name": "Mary",
"age": 28
}, {
"name": "John",
"age": 31
}],
"NY": [{
"name": "Linda",
"age": 71
}]
}
def num_of_cust_p... |
b970349eb8544590e95d995fd7e8e4687b459530 | abhishekpshenoy/Python | /Operaters/Special.py | 152 | 3.78125 | 4 | a1 = 'Abhishek'
b1 = 'Lets leaen '
# Identity operator
print(a1 is not b1)
print(a1 is b1)
# Membership operator
print("abhi" in a1)
print("N" not in b1) |
6b95777dd1ee6c63d74013622bc3bb5c7277a7e5 | Mumulhy/LeetCode | /646-最长数对链/FindLongestChain.py | 571 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# LeetCode 646-最长数对链
"""
Created on Sat Sept 3 10:58 2022
@author: _Mumu
Environment: py38
"""
from typing import List
class Solution:
def findLongestChain(self, pairs: List[List[int]]) -> int:
curr, ans = float('-inf'), 0
for x, y in sorted(pairs, key=lambda p: p[1]):
... |
106a731058e7da4bc8d397bc805b2e52c35448e9 | brancherbruno/ExerciciosPythonCursoEmVideo | /ex039.py | 897 | 3.53125 | 4 | from time import sleep
from datetime import date
print('\033[1;35m<==>\033[m' * 35)
nome = str(input('Olá, qual seu nome?')).capitalize().strip()
ano = int(input('\033[1;31m{}\033[m por favor digite o ano de seu nascimento (ex: 9999):'.format(nome)))
hoje = date.today().year
idd = hoje-ano
print('\033[1;31m{}\033[m \03... |
874ab19428c4b16de735727a3ca93281b7456580 | spezifisch/leetcode-problems | /maximum-binary-tree/one.py | 726 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not len(nums):
return
root = TreeNode... |
cace12cc371e66e9ff8348318d8c03254937d9a1 | Xvozt/pirple_python | /lists.py | 616 | 3.890625 | 4 | myUniqueList = []
myLeftLovers = []
print("My unique list before = " + str(myUniqueList))
print("Left Lovers list before = " + str(myLeftLovers))
def addToListIfNotExist(toAdd):
if toAdd not in myUniqueList:
myUniqueList.append(toAdd)
return True
else:
return False
def main(listMembe... |
0502b02ff6e53301509bd15458a2c9aac8b8894d | ursu1964/algorithms_datastructures_system_design | /Divide_and_Conquer/maximum_subarray/main.py | 1,347 | 3.640625 | 4 | #!python
'''
Step1: Randomly generate 10 samples of inputs with increasing number of change elements in a specific range
Step2: Run both "recursive" and "non-recursive" algorithm on the 10 samples and calculate the average amount of time.
Step3: Plot the average amount of time for the algorithms and find the crosso... |
99358dbbfe7a71967122bd79a18676829ac0e6e3 | jayeshjawale95/PythonProgramming | /while_loops.py | 419 | 4.09375 | 4 | x = 0
while x < 10:
print 'x is currently: ',x
x += 1
print "============"
x = 0
while x < 10:
print 'x is currently: ', x
x += 1
else:
print 'all done!'
print "============"
# break, continue and pass
x = 0
while x < 10:
print 'x is currently: ',x
print 'x is still less than 10, adding 1 to x'
x +=... |
60e4d80db34c28d846435c4f6270e490216871b4 | raotnameh/middle_square_algo | /main.py | 693 | 3.78125 | 4 | #python 2.7.15+ tested
# -*- coding: utf-8 -*-
"""
Code to reproduce middle square algorithm and plot to see the results if the numbers are randomly producing and all of them between 0 to 1.
"""
r=int(input("Enter number:\n"))
l=len(str(r))
list = []
# list.append(r)
while len(list) == len(set(list)) :
x=str(r*r)
... |
cfa348f74ccd1aeddf8176a8ab979e2c6d280dd8 | margaridav27/feup-fpro | /Plays/Play07/lost_element.py | 364 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 08:37:03 2019
@author: Margarida Viera
"""
def lost_element(s1, s2):
if len(s1) > len(s2):
for n in s1:
if n not in s2:
return n
if len(s2) > len(s1):
for n in s2:
if n not in s1:
return n... |
566f884a0d5db977f9de7fc7fc6b4a1a14852aba | josh81233/repo | /check.py | 184 | 3.9375 | 4 |
import re
regex = r"^[a-zA-Z0-9]+ [a-zA-Z0-9_-]$"
reegex = r"^[A-Z][A-Za-z0-9 _-]+(<[a-zA-Z0-9_].+>)?$"
name = input()
if re.match(regex, name):
print("t")
else:
print("f")
|
bbdf07ef64278134203a8ce649538bc09cd62cfc | Kimundi/heroes-of-hammerwatch-puzzle-solver | /main.py | 1,664 | 3.84375 | 4 | #!/usr/bin/env python3
from collections import deque
def get(puzzle, x, y):
return puzzle[x + y * 3]
def toggle(puzzle, x, y):
r = list(puzzle)
r[x + y * 3] = 1 - r[x + y * 3]
return tuple(r)
def walk_on(puzzle, x, y):
puzzle = toggle(puzzle, x, y)
if x > 0:
puzzle = toggle(puzzle, ... |
0de23f24e49528471924b6acc71ec0a84e843340 | pgenev/Programming101-Tasks-Completion | /Week1/3.The-Final-Round/is_an_bn.py | 383 | 3.921875 | 4 | def is_an_bn(word):
number_of_a = word.count('a')
number_of_b = word.count('b')
if number_of_a != number_of_b:
return False
return ("a" * number_of_a + "b" * number_of_b) == word
print(is_an_bn(""))
print(is_an_bn("rado"))
print(is_an_bn("aaabb"))
print(is_an_bn("aaabbb"))
print(is_an_bn("aabb... |
36025cbed1a400aac17d3299ba522814f72698ae | hhsu15/advanced_python | /async_2.py | 2,874 | 4 | 4 | import asyncio
from codetiming import Timer
import aiohttp
"""
Anything with the "async" prefix is a "coroutine" (Cooperative sub-routine function) which is an awatable.
Other awaitales are like "task" which is created when you use asyncio.create_task() and "future" object.
You will be then able to use the "await" key... |
de7905f41066ff23f641268a53d7c6d917d12d91 | rahulrpatil/coding-interview-bootcamp | /python/reversestring/index.py | 463 | 4.25 | 4 | def reverse_string_method_1(string: str) -> str:
return string[::-1]
print(reverse_string_method_1("Hello"))
def reverse_string_method_2(string: str) -> str:
reversed_string = ""
for char in string:
reversed_string = char + reversed_string
return reversed_string
print(reverse_string_method_2(... |
aa4625dcbf879ca9ea555d7591322c91406f460b | mzijlstra/Math-Probs | /prob028/prob28.py | 816 | 3.765625 | 4 | # Project Euler
# Problem 28
# Michael Zijlstra
# 05/26/2103
size = 1001
a = [[0 for x in range(size)] for y in range(size)]
direction = 0
steps = 1
x = size / 2
y = size / 2
a[x][y] = 1
count = 2
def printGrid(a):
for l in a:
for i in l:
print i,
print
print
def doStep():
global x;
global y;
if directio... |
41b93c74fde7e52247bf531489a1d0b9d4f1a739 | TheHitchhikersThumb/pill-prototype | /PillInterface.py | 6,026 | 4.0625 | 4 | def setup():
global position
global hour1
global hour2
global min1
global min2
global pill
global period
global calibration
position = 1
hour1 = 0
hour2 = 0
min1 = 0
min2 = 0
period = 1
calibration = 7
opening_interface()
def opening_int... |
e1fc589150828d3740ed0bc51ac7ece380120b3c | BScheihing/02Tarea | /relajacion.py | 1,170 | 3.65625 | 4 | '''
Este script define una funcion que permite
estudiar la convergencia de v'_n a medida que
el sistema va relajando.
'''
import numpy as np
import matplotlib.pyplot as plt
from bote import outnchoque
def Nrelax(w,eta):
'''
Esta funcion recibe como parametros la
frecuencia de oscilacion del suelo y el
... |
a29805c9b26a87482f81c8c777c8f24f3f530329 | Qwerky7835/adventofcode2020 | /day3/trees.py | 149 | 3.875 | 4 | i = 0
counter = 0
with open("input.txt") as file:
for line in file:
index = i%31
if line[index]=="#":
counter+=1
i = i+3
print(counter)
|
a3f7d8777fb1997c8582478d35cb3b76d1636ae6 | dsimatos/Python3 | /older_progs/test.py | 240 | 3.984375 | 4 | import time
print("What is your name; ")
name = input()
hour = time.localtime().tm_hour
if hour < 14:
print("Good morning", name)
else:
print("Good afternoon", name)
wait = 3
time.sleep(wait)
answer = 42
print("The Answer is...", answer)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.