blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
648b192b27e90e5ba6683af9a51ed20e8126cf02 | maelstrom9/DS-and-Algorithms | /EPI/BinaryTrees/9.16 set level next field in a perfect binary tree.py | 1,146 | 3.84375 | 4 |
class Tree:
def __init__(self,v,l_next=None):
self.val = v
self.left = None
self.right = None
self.l_next = l_next
def set_level_next_perfect_binary_tree(root):
queue = [root]
while queue:
temp = []
for idx in range(len(queue)):
if queue[idx... |
2adaf7455fa225b63444e6e668aef9f314ce55fc | andrefdavid/exerciciosImersaoPython | /basicos/ex01.py | 755 | 3.984375 | 4 | #Para um ano de nascimento fornecido pelo usuário, informe a idade que ele terá no dia 31 de dezembro de 2021.
#é preciso, inicialmente, solicitar ao usuário seu ano de nascimento através do input, converter para número inteiro e armazenar em uma variável
nascimento = int(input("Por favor, informe seu ano de nasciment... |
c25436ccf392b683aea8aef49b0db7209bf58855 | chowsychoch/Programming-1- | /p13/p13p1.py | 326 | 4.25 | 4 | # Program to print out the smallest of two numbers entered by the user
# Uses a function min
# if argument one is greater than two
#return argument 2
#else
#return argument one
def min(a,b)
"""Function that return the smallest of its two argument"""
if a > b:
return b
else:
ret... |
315190a4fe13ee3a78b7adf3ca516f294a82d086 | mrkickling/pythonkurs | /tillfalle1/solutions/uppg4-2.py | 659 | 4 | 4 | # Uppgift 5: Skapa ett program (vowel.py) som tar en bokstav som indata och printar
# Ja! Om bokstaven är en vokal och Nej! Om bokstaven är en konsonant
# Lösningsförslag 2
# Skapar en lista med alla vokaler och lägger i variabeln vokaler
vokaler = "aeiouyåäö"
# Hämtar indata i form av en bokstav och gör den till små... |
8d8420326ff43e244a2ef033fd629026a95c89c3 | betty29/code-1 | /recipes/Python/578222_Pythdecorator_that_reexecutes/recipe-578222.py | 1,256 | 3.734375 | 4 | def conditional_retry(func=None, exceptions=Exception,
action=None, callback_args=(), timeout=2):
'''
This decorator is able to be called with arguments.
:keyword exceptions: exceptions in a tuple that will be
tested in the try/except
:keyword action: a callable to be called... |
a181170a1b9005860d97c379ee6e3d09298a574d | Dilan/interviewproblems | /path-sum-tree-II.py | 2,109 | 3.71875 | 4 | """
https://leetcode.com/problems/path-sum-ii/
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Given the below binary tree and sum = 22,
[5]
/ \
[4] [8]
/ / \
[11] 13 [4]
/ \ / \
7 [2] [5] ... |
12e763f79a34abd12a455a50417c3cd98c31da02 | MurradA/pythontraining | /Challenges/P042.py | 213 | 3.921875 | 4 | total = 0
for i in range(0, 5):
q = int(input("Enter a number: ").strip())
n = input("Do you want that number included? (y/n): ").strip()
if n.lower() == "y":
total = total + q
print(total) |
6219592f03f5cea708dde821430897ce82166159 | aswinrprasad/Python-Code | /Decision Making/Ex2.py | 546 | 4.03125 | 4 | #The rules for winning the prize have got stricter. The first name must now have more than 5
#characters (as well as end in the letter a). Modify the program in Exercise 1.
name=raw_input("Enter your first name :")
size=len(name)
if size >= 5:
if name[size-1] == 'a':
print "Congrats!! Your name ends with the letter... |
c8b8a876118f9efcc571b0a725a884b0cc333839 | ARAVINDGOGULA1488/DSP | /sine_phase.py | 479 | 3.5 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 5 04:19:47 2019
@author: rgukt
"""
import numpy as np
import matplotlib.pyplot as plt
f=input('enter the frequency')
phi=input('enter the phase angle')
m=np.linspace(0,100,1000)
x=np.sin(2*np.pi*(float(f))*m)
y=np.sin((2*np.pi*(float(f))*m)+phi)
f... |
83db4681047d4a501dc9df00f7912822660999ab | jjauzion/evolve | /src/system/Move.py | 1,381 | 3.90625 | 4 | class Move:
def __init__(self, screen_size):
"""
Move entity in the universe.
The universe is round: When one entity goes beyond the window size it appears back at the side
of the window.
:param screen_size: [tuple of int] (x, y) -> size of the window,
... |
cc3420f085c07720da5da5f9026aeac16d130906 | mikaevnikita/ml_labs_travelling_salesman_problem | /annealing_2.py | 2,292 | 3.640625 | 4 | import random
import math
from citiesReader import readCities
city_solve = 'A'
N = 30000
def get_random_initial_state(initial_city, cities):
cities.remove(initial_city)
return [initial_city] + random.sample(cities, len(cities)) + [initial_city]
def get_random_next_state(initial_city, current_state):
curr... |
2c3c08653450026edb36f5511cbcb8cd8751812d | kotori233/LeetCode | /[0275]_H-Index_II/H-Index_II.py | 505 | 3.546875 | 4 | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
left, right = 0, n - 1
while left <= right:
middle = (left + right) // 2
if n - middle == citations[middle]:
... |
81d264e7a956e78b2b20013ca73675412263c932 | Aniaaaaa/Szyfrator | /python/main.py | 10,635 | 3.71875 | 4 | import math
special_signs = {",", " ", ".", "?", "!"}
alphabet ="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
def get_alphabet():
return alphabet
def get_alphabet_length():
return len(alphabet)
def caesar_code(message, key):
key = int(key)
message = str(message)
message_li... |
1a9032ea9a1be531e77197f456675a53be4c0427 | paulsatish/IGCSECS | /16May-Task2-parcel.py | 1,222 | 4.03125 | 4 | TotalNotAccepted=0
TotalAccepted=0
TotalWeight=0
continue1="yes"
while continue1=="yes":
print("Please enter the parcel dimensions")
height=float(input("Please enter the height of the parcel in cm: "))
width=float(input("Please enter the width of the parcel in cm: "))
length=float(input("Please enter th... |
6f1a5284efa2adbdab7135daf9e8afbfb819a288 | RaphaelZH/Raspberry_Pi_4_Progrmas_EN | /1_Mini_Programs_for_Practice/7_one_LED_with_one_PIR_sensor/one_LED_with_one_PIR_sensor.py | 667 | 3.640625 | 4 | import RPi.GPIO as GPIO
import time
LED_PIN = 17
PIR_PIN = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.output(LED_PIN, GPIO.LOW)
# avoid the warning message when executing this program again
try:
while True:
# be able to read 100 ti... |
1f19fd7004c4debfa63c29b70d7ddfc1984b9aca | thaheer-uzamaki/assignment-9 | /dupplies.py | 344 | 3.796875 | 4 | from itertools import zip_longest
a = []
n=int(input("Enter the length of list: - "))
for i in range(n):
a.append(int(input()))
res = [i for i, j in zip_longest(a, a[1:])
if i != j]
# printing result
print ("List after removing consecutive dupl... |
aef9c34c5d2fc2a3f54f81d889c71856bede79a9 | CornelRemer/dijkstra | /transformer.py | 3,448 | 4 | 4 | """Convert a PIL image into a graph, suitable for the dijkstra algorithm
"""
import numpy as np
import math
from dijkstra import Node
class RasterNodes():
"""Graph of nodes created from an image like a Digital Terrain Model (DTM)
The __init__ takes two arguments:
image (obj): Image object from the P... |
fabb296f928e6ec05929526d4d67c6d10bf9f000 | bishal8/github | /classobject.py | 167 | 3.703125 | 4 | class Test:
def sum(self, a, b):
s=a+b
return s
a= int(input("enter a number:"))
b=int(input("enter a number:"))
obj=Test()
s=obj.sum(a,b)
print(s) |
4010a4c9e624383fa5c0045c2e3373c7ffe035b2 | knishant09/LearnPythonWorks_2 | /Practise/19.py | 131 | 4.28125 | 4 | import os
str = raw_input("Enter the value of string:")
print str
if str[:2] == "Is":
print str
else:
print 'Is' + str
|
2de646411122b45e46ae21e8ff2bd10521175d05 | ravikantchauhan/python | /escape_sequence_asnormaltext.py | 148 | 3.71875 | 4 | # this is for print to escape sequence as normal taxt
# for example i want to print hellow word in \n new line
print ("hellow word in \\n new line") |
a5077ef1fbf1614feda122ca996902d914b48643 | lvraikkonen/GoodCode | /leetcode/204_count_primes.py | 459 | 3.828125 | 4 | import math
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
is_prime = [True for _ in range(n)]
is_prime[0], is_prime[1] = False, False
for i in range(2, int(math.sqrt(n))+1):
... |
9950abcb66b829471ff5a5e95905d0d086dcebe6 | aakriti-27/Internity_DataScienceWithPython | /day5/data_handling.py | 1,268 | 4.59375 | 5 | #Pandas is a Python library.
#Pandas is used for working with data sets and analyzing it.
#Pandas Series is a one-dimensional array holding data of any type(like a column in a table)
import pandas as pd #creating an alias while importing
a = [1, 2, 3]
myvar = pd.Series(a)
print(myvar[0]) #values are labeled wi... |
a5f037a18f21c9eba6cbe2f39ab5e79932e235f6 | WondwosenTsige/data-structures-and-algorithms | /python/code_challenges/graph_breadth_first/graph_breadth_first.py | 487 | 3.90625 | 4 | from code_challenges.stacks_and_queue.queue import Queue
def graph_breadth_first(vertex):
nodes = []
breadth = Queue()
visited = set()
breadth.enqueue(vertex)
visited.add(vertex)
while not breadth.isEmpty():
front = breadth.dequeue()
nodes.append(front)
for neighbor ... |
b8bf327aae2f5f0636ebef12f34a2a82c30d6017 | lope512q09/Python | /Chapter_10/Lopez_TIY10.11.py | 573 | 3.71875 | 4 | import json
fav_num = None
def fav_num_input():
"""Prompts user for their favorite number."""
active = True
while active:
try:
global fav_num
fav_num = int(input("Please enter your favorite number: "))
except ValueError:
print("Please enter numbers only... |
9e2452f970de343b21a5a3be1c6bc1f2912779c4 | johndemlon/mail-circle | /generator.py | 600 | 3.640625 | 4 | import string
import random
ltrs = string.ascii_letters
cntr = 1
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
text_file = open("emails.txt", "w")
nmml = input("How many emails do you want ? ")
nmcr = input("How many charecters do you want ? ")
for i in range(0,int(nmml))... |
2e2ec5a5bfb8e1389191adf0ce56523ed34029a8 | jordan336/battleship | /src/Grid.py | 7,081 | 3.921875 | 4 | from Position import Position
"""
Grid class
The Grid class represents one Agent's game board.
The Grid contains the dimensions of the board and
the state of each square, whether it was a hit, miss, or
has not been explored.
"""
class Grid:
def __init__(self, width, height):
self.width = width
s... |
55313bd54e80488c2147740de16d1053e97a5c32 | Tatenda-Ndambakuwa/autocomplete.py | /lexicologicalOrder.py | 2,087 | 3.703125 | 4 | # code to get the first five words
def extract(query):
# initializing
nextString = "a"
words=[]
recentWord=str()
database= []
count =0
keepGoing = True
# begin while
while ( keepGoing):
count +=1
words= query(nextString)
#print (words)
#print (len (words))... |
23e3a5849777355818231d6a497f242c36309308 | keerat21/Graph-Search-DFS-and-BFS | /BFSandDFS.py | 1,875 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 22 21:26:22 2020
@author: Hp User
"""
close = []
opened = []
def getchild(b):
print('Enter child of {0} , type 00 if no more child'.format(b))
return input()
#####################################PART A###################################
def dfs_ge... |
4d253738150432d06f88350c1bd4f77e0e7c69a7 | LukasKodym/py-tests | /strings.py | 369 | 3.75 | 4 | # %%
##
s = 'Witaj nasze 0'
print('b' not in s)
# to jest komentarz
# %%
##
x = input('Wprowadź swoej imię: ')
print('Twoje imię to: ' + x)
# %%
##
a = float(input('Wprowadź liczbę: '))
a += 1
print(a)
# %%
##
pcs = 12
# s = 'W magazynie jest ' + str(pcs) + ' sztuk.'
s = 'W magazynie jest {} sztuk.'.format(pcs)
prin... |
a21548b70211c4521cd225edf43feec62f71766e | guti7/Data-Structures | /source/finder.py | 2,835 | 4.15625 | 4 | #!python
def find(string, pattern):
"""return true if string contains the entire pattern, false otherwise."""
# implement find_iterative and find_recursive
# assert isinstance(string, str)
return find_iterative(string, pattern)
# return find_recursive(string, pattern)
def find_iterative(string, ... |
f3516b0ec5c89e9de69c1e8d161eaedc6c9cb7a7 | klmsathish/PythonBasics | /ErrorHandling5.py | 418 | 4.09375 | 4 | def ask_for_int():
while True:
try:
age = int(input("enter your age = "))
except(ValueError):
print("Entered input is not a number")
continue
else:
if(age >= 18):
print("eligible to vote")
break
... |
b3a7550a14e971ac040aa22eb1773f54b6e5a4a6 | harryoh99/IE343_ML | /Final_Project_20180396/students/task1/App/logistic_regressor.py | 3,633 | 3.84375 | 4 | import numpy as np
import pandas as pd
import math
class LogisticRegressor():
#INITIALIZATION OF THE MODEL
def __init__(self,w=None):
#First initialize the weight to a none value
self.w = w
def fit(self, X, y,lr,epoch_num):
"""
TRAINING
X dimension is (623,11)
... |
5799573ff22a3b7875e557af56df9f0770f48457 | iragomez68/Python-Lessons | /pie_store.py | 1,085 | 3.890625 | 4 | import string
pie_list = ["Pecan", "Apple Crisp", "Bean", "Banoffe", "Black Bun", "Buko", "Blueberry","Burek", "Tamale","Steak"]
basket = []
for i in range(len(pie_list)):
print(f"({i}) {pie_list[i]}")
while True:
pie = int(input("Which pie would you like to bring home? "))
selection = pie
basket.appen... |
6a3b247835d4560bf8e251fce5bd098fb7615da4 | megumik/coursera_bioinformatics1 | /1_1_frequent_words.py | 843 | 3.53125 | 4 | # 2020/5/20 megumik
# coding: utf-8
def PatternCount(Text, Pattern):
count = 0
for i in range(len(Text) - len(Pattern) + 1):
if Text[i:i+len(Pattern)] == Pattern:
count += 1
return count
def FrequentWords(Text, k):
frequent_patterns = set()
count = []
for i i... |
dc03903ae6f72040514bd97e31c6def22886895b | lse30/Sudoku-Solver | /sodoku.py | 8,005 | 3.796875 | 4 | from tkinter import *
from tkinter.ttk import *
class SudokuGui:
"""Sudoku Gui for sudoku solver"""
def __init__(self, window):
"""sets up the window"""
self.title = Label(window, text="Sudoku Solver")
self.title.grid(row=0, column=1, pady=10, columnspan = 9)
self.left_ed... |
396c8754559c3956d8ba206e4fde6533fba7a58c | DedS3t/mllib | /mllib/helpers/train_test_split.py | 1,047 | 3.515625 | 4 | import math
def train_test_split(X, y, test_size = 0.2):
if len(X) != len(y):
raise RuntimeError # TODO change errors
X_train = []
y_train = []
X_test = []
y_test = []
for i in range(math.floor(len(X) * test_size)):
# training
X_train.append(X[i])
y_train.append... |
4333f290cc3336fca513732cf0aade3ea39fa55b | CodingDojoOnline-Nov2016/DarrilGibson | /PythonAssignments/bubblesort.py | 371 | 3.78125 | 4 | # bubble sort low to high
# base case [3,1,5,9,7]
# set int_num1 to be first number
# set int_num2 to be second number
# if intnum1 > intnum2, swap
# repeat
a = [3,1,5,9,7]
for count in range (0, len(a)-1 ):
int_num1 = a[count]
int_num2 = a[count+1]
if a[count] > a[count+1]:
a[count] = ... |
5f9b361bfffe8c40d3549660d625d6842cc7b739 | romanannaev/python | /STEPIK/complete_task/tandem.py | 710 | 3.765625 | 4 | # Вам дана последовательность строк.
# Выведите строки, содержащие слово, состоящее из двух одинаковых частей (тандемный повтор).
# Sample Input:
# blabla is a tandem repetition
# 123123 is good too
# go go
# aaa
# Sample Output:
# blabla is a tandem repetition
# 123123 is good too
import sys
import re
pattern = r'\... |
c789d97d4556d0f1691eeebcc713aa1a34044f3f | coolsnake/JupyterNotebook | /new_algs/Graph+algorithms/Coloring+algorithm/Searches.py | 10,927 | 3.640625 | 4 | '''
Created on Aug 22, 2018
@author: swagatam
'''
from Node import Node
from test.test_typing import Founder
def bfs(initial,goal):
#print(goal)
start_node=Node(initial,None,None)
visited=[]
fringe=[]
#visited.append(start_node.state)
current_node=None
fringe.append(start_no... |
03ce9e936175fe0427d01c60080ad126efeaa848 | yeli7289/Algorithms | /sort/mergesort.py | 737 | 3.734375 | 4 | class Solution:
def mergesort(self, nums):
self.helper(nums, 0, len(nums)-1)
def helper(self, nums, left, right):
mid = (left+right)/2
if left < right:
self.helper(nums, left, mid)
self.helper(nums, mid+1, right)
self.merge(nums, left, mid, right)
def merge(self, nums, left, mid, right):
hl, hr = l... |
7ed744f9f185ddb2314674569ca9bbed1e9dfe96 | vikashvishnu1508/algo | /Revision/Arrays/TwoNumberSum.py | 764 | 3.984375 | 4 | def twoNumberSumMethod1(array, target):
lastSeen = {}
for i in array:
expectedValue = target - i
if expectedValue not in lastSeen:
lastSeen[i] = True
else:
return [i, expectedValue]
return [-1, -1]
def twoNumberSumMethod2(array, target):
array.sort()
... |
41e918af7e5bee7b5c068f67dea27bb6063f1f1d | MikkelOerberg/PracticalWeek5 | /Color Names.py | 962 | 4.375 | 4 | """
Based on the state name example program above,
create a program that allows you to look up hexadecimal colour codes
like those at http://www.color-hex.com/color-names.html
Use a constant dictionary of about 10 names and write a program that allows a user
to enter a name and get the code, e.g. entering AliceBlue sho... |
ea40d57eb627de1d74a30dbfa26e95d66f1490e1 | davidhuangdw/leetcode | /python/482_LicenseKeyFormatting.py | 509 | 3.75 | 4 | from unittest import TestCase
# https://leetcode.com/problems/license-key-formatting
class LicenseKeyFormatting(TestCase):
def licenseKeyFormatting(self, S: 'str', K: 'int') -> 'str':
s = S.replace('-', '').upper()[::-1]
return '-'.join(s[i:i+K] for i in range(0, len(s), K))[::-1]
def test1(s... |
b4faa37eb7a8b8715f1952d4928790b7b056020c | arvind-mocha/Login-page_Kivy | /String_validation.py | 592 | 3.5625 | 4 | import re
regex_mail = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
regex_name = '^[a-zA-z0-9_-]{3,15}$'
regex_password = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
#STRING CONDTION WHILE INPUT
def checkemail(email):
if(re.search(regex_mail,email)):
return 'valid'
else:
... |
6e726805ffae3cf62089c939e417d865362c5aec | BjaouiAya/Cours-Python | /Course/Book/Programmer_avec_Python3/13-ClasseEtInterfacesGraphiques/cercleScaling.py | 4,328 | 3.78125 | 4 | #! /usr/bin/env python
# -*- coding:Utf8 -*-
"""PROGRAMME PERMETTANT DE FAIRE VARIER LA TAILLE D'UN DISQUE"""
"EXERCICE 13.20"
###########################################
#### Importation fonction et modules : ####
###########################################
from tkinter import *
################################... |
732716d5b85856142fe6ab2f3f52a49e6943f76b | gschen/sctu-ds-2020 | /1906101002-夏先苗/20200219.py | 534 | 4.03125 | 4 | #连接
a="hi"
b="s"
print(a+b)
#重复字符
c="hi"
print(c*3)
#切片
str1="abcde"
print(str1[0])
print(str1[-1])
print(str1[0:4])
a="bcde"
print("e" in a)
print("f" not in a)
#格式化输出
print("我叫%s"%("夏先苗"))
print("我今年%s"%(19))
#列表
list1=[1,2,3,[4,5,6]]
print(len(list1))
for x in [1,2,3]:
print(x)
list1 =[1,2,3,[4,5,6]]
list... |
4ca49b6f764211862710c18aef17c5dad37bb3a7 | CaptainSherry49/Python-Beginner-Advance-One-Video | /My Practice Of Beginner Video/Chapter 11/06_Property_Decrator.py | 207 | 3.578125 | 4 | class Employee:
company = "Amazon"
Salary = 30000
SalaryBonus = 1500
@property
def TotalSalary(self):
return self.Salary + self.SalaryBonus
E = Employee()
print(E.TotalSalary)
|
587c93eaa92d1a39a8dbaeb20a2d6862e2ceed01 | laksh10-stan/DSA-Python- | /6.21_BST_search_rec.py | 490 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 02:07:56 2019
@author: laksh
"""
def find( root, data):
currentNode = root
while currentNode is not None and data != currentNode.getData():
if data> currentNode.getData():
currentNode = currentNode.getRight()
else:
curre... |
bab01f75f2806616d3cb61f3ae59fa6457085b5b | kaimhall/basic-python2 | /koodi.py | 230 | 3.5625 | 4 | print("Laskin")
luku1 = input("Anna ensimmäinen luku: ")# voi tehdä myös int(input())
luku2 = input("Anna toinen luku: ")#kokonaisluvuille.
tulos = int(luku1) + int(luku2)#integer muunnos.
print("Tulos on:", tulos)
|
4e15cfc4d9d0fade7b56558616c3ce609b278908 | Ryandalion/Python | /Files and Exceptions/Average of Numbers/Average of Numbers/Average_of_Numbers.py | 859 | 4.40625 | 4 | # Program will calculate the average of all the numbers inside the text file
def main():
dataFile = open('numbers.txt', 'r'); # Open the text file that holds the numbers
number = dataFile.readline(); # Assign the first line to number
count = 0; # Variable to hold the number of elements inside the text file... |
21159f3651f61a7cf0d9be78b9c1b7d3209a1cb1 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_186/cap7_iteracao/pares_impares.py | 448 | 3.875 | 4 | def programa():
numero = int(input('Número: '))
contador_pares = 0
contador_impares = 0
while numero != 0:
if numero % 2 == 0:
contador_pares = contador_pares + 1
else:
contador_impares = contador_impares + 1
numero = int(input('Número: '))
print(f'... |
458c0c4693f77cd8fb874c558330077f52b2c3a9 | zzh730/LeetCode | /Bit Manipulation/sqrt().py | 667 | 3.65625 | 4 | __author__ = 'drzzh'
'''
二分查找的题,注意的是如果是分数,返回时的条件是: mid*mid <= x and (mid+1)*(mid+1) > x
Time: O(logn)
'''
class Solution:
# @param x, an integer
# @return an integer
def sqrt(self, x):
if x < 0:
return -1
if not x:
return 0
if x ==1:
return 1
... |
6bc79e97829b741324ce92dd7152dd7fe459c9e4 | Danang691/Euler.Py | /euler/solutions/euler15.py | 1,007 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from euler.util import factorial
'''
research
This is a combinations problem. on a 20x20 grid to get from top-left to
bottom-right there are 40 moves (20 down and 20 right). The problem can be
solved by applying the formula for the central binomial coeff... |
1be8c44c886ffde5d98b8c18cc80d30cb4b149f8 | weizt/python_studying | /面向对象/23-多态的使用.py | 2,000 | 4.09375 | 4 | # 概念:多态是基于继承,对它进行子类重写父类的方法,
# 达到不同的子类对象调用相同的父类方法,得到不同的结果
# 作用:提高代码的灵活度
# 需求:
'''
1.多种不同类型的狗
2.一个类型的人
3.同一个人与多种类型的狗做不同的工作
'''
# 思路
'''
1. 创建一个Dog类的父类
2. 定义不同Dog类的子类
3. 重写Dog类父类的方法
4. 人调用相同的方法名,实现不同的功能
5. Dog类定义不同的方法
6. Person类定义唯一的方法,此方法将调用不同的dog类的方法
'''
# 先定义一个Person
class Person(object):
def __init__(self,... |
428d8389f56f9307be688c25ee317a1b62c5ce61 | VishnuGopireddy/leetcode | /21. Merge Two Sorted Lists.py | 1,424 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"... |
372f0ca7e16456ee967d427b285048f6bbf72998 | SJHH-Nguyen-D/data-driven-web-apps-with-flask | /app/ch05_jinja_templates/starter/app.py | 1,645 | 3.515625 | 4 | """
VIEW METHODS are defined in the app.py script and they direct us to the appropriate html template windows (views).
Each view method typically is associated with directing us in the browser to the appropriate window, which is identified by a specific
pattern in the URL. Each route view method and route should have a... |
9db01501d733a045843bb8e1650450ff4c4bd2f7 | stanilevitch/python_06102018 | /zjazd_1/snippet.py | 1,929 | 3.953125 | 4 | x = int(input("Podaj pozycję X "))
y = int(input("Podaj pozycję Y "))
if x>100 or y > 100 or x < 0 or y <0:
print("Wypadłeś z planszy")
elif x>90 and y > 90:
print("Jesteś w prawym górnym rogu")
elif x > 90 and y <10:
print("jestes w prawym dolnym rogu")
elif x < 100 and y <10:
print("jestes w prawym d... |
504b67d380ecf8d1f5f7c7faf5dd731125a10ea8 | kattachandipriya1214/priyaguvi | /42.py | 234 | 3.9375 | 4 | string1=input().split()
if(len(string1[0])>len(string1[1])):
print(string1[0])
elif(len(string1[1])>len(string1[0])):
print(string1[1])
elif(len(string1[0])==len(string1[1])):
print(string1[1])
else:
print(string1[0])
|
7825fa432d5bf5f5520d27b36a5c53bf69a0229d | endrijsss/EDIBO | /Python/scripts/milzigs_skaitlis.py | 1,033 | 3.796875 | 4 | #! /usr/bin/python3.6
print("Ievadiet Skaitli")
# a =2**200000
#te ir tris darbibas - vertibas sagaidīšana, vertibas parveidosana, pieskirs$
#argument = input()
#int(argumnet)
#a = int(argument)
#pildot int(input()) "bez izmeginajuma" programma var vienkarsi izlidot...
#tapec, lai "nelidotu", mes izmantosim try ...... |
86a20b9e336c8a5af9aab4d77a4389d491ac2fdd | kaizen0890/Machine-Learning-Project | /basic-algorithm/linear-regression.py | 840 | 3.671875 | 4 |
import os
import math
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[147, 150, 153, 158, 163, 165, 168, 170, 173, 175, 178, 180, 183]]).T
Y = np.array([49, 50, 51, 54, 58, 59, 60, 62, 63, 64, 66, 67, 68])
#Building Xbar
one = np.ones((X.shape[0], 1))
Xbar = np.concatenate((one, X), axis = 1)
... |
158d7d76f43a7e588e2149ed43cf99f818583d5e | Gaazedo/Portfolio | /Codes/python/py1/exs (4)/ex6.py | 256 | 3.84375 | 4 | def conta(vetor):
n=len(vetor)
count=0
for i in range (n):
if vetor[i]>vetor[i-1] or vetor[i]<vetor[i-1]:
count+=1
return count
def lervetor(vetor):
n=len(vetor)
for i in range (n):
vetor[i]=int(input("Digite um número: "))
|
a90d3052ada40a3cc4a63639ad51c1e6fb69e834 | IvanPerez9/Programming-Paradigms | /Python/Numpy.py | 2,287 | 4.1875 | 4 | import numpy as np
"""
Create a 4X2 integer array and Prints its attributes
"""
array = np.arange(8).reshape(4,2)
print(array)
print(array.shape)
print(array.ndim)
print(array.itemsize)
"""
Create a 5X2 integer array from a range between 100 to 200 such that the difference between each element is 10
"""
array2 = np... |
34c6214023a3329e43f990d4fdd0d9311d36e8b8 | JokerTongTong/Numpy_learn | /3.12计算阶乘.py | 284 | 3.5625 | 4 | # 3.12计算阶乘
import numpy as np
'''
prod() cumprod()
函数1:prod() 计算一个数的阶乘
函数2:cumprod() 计算一组数的阶乘
'''
a = np.arange(1,11)
print('a',a)
a_res = a.prod()
print('10!',a_res)
a_res1_10 = a.cumprod()
print('1~10阶乘:',a_res1_10)
|
13242cfb6e6b66bf30bf76106aa94fdb8095eff5 | dpassen/project_euler | /python_project_euler/Euler12.py | 416 | 3.53125 | 4 | #!/usr/bin/env python
from math import sqrt, ceil
from itertools import count
def triangle_number(num):
return (num * (num + 1)) // 2
def get_factors(num):
for i in range(1, int(ceil(sqrt(num)))):
if not num % i:
yield i
yield num // i
print(
next(
t
fo... |
18dc4f2637fee7edadcf95ebf9d717aae1dbfd6d | Nityam79/pythonPractice | /prac5/numuni.py | 256 | 3.828125 | 4 | import numpy as np
array1 = np.array([0, 11, 21, 41, 61, 91])
print("Array1: ",array1)
array2 = [5, 31, 9, 51, 71]
print("Array2: ",array2)
print("Unique sorted array of values that are in either of the two input arrays:")
print(np.union1d(array1, array2)) |
8ff224b169653b297ee85c1898525a65d20845f6 | Alexandra-Sontu/cele-15-probleme | /problema8 IF.py | 531 | 3.875 | 4 | """Să se afişeze cel mai mare număr par dintre doua numere introduse în calculator. Exemple : Date de intrare 23 45 Date de
ieşire nu exista numar par ; Date de intrare 28 14 Date de ieşire 28 ; Date de intrare 77 4 Date de ieşire 4."""
a=int(input("primului numar"))
b=int(input("al doilea numar"))
if ((a%2==0)and(... |
8925c1f4bc4702b05b48c1a0c653b1d05fd41fc4 | c3ypt1c/Lucky-Name-Numbers | /engine.py | 2,271 | 3.625 | 4 | # WJEC Controlled Asessment
# Luck Name Numbers 2016
# Python 3.3.2/3.5.2
import time
def adder(a): #Defines function adder
while len(str(a)) != 1: #Loops while the size of the string of the number a isn't 1
b = 0
for x in str(a): b += int ( x ) #Adds every current "a" value.
a = int(b) #Set... |
5dc9ce1430ade9b7aebe04423f643552b938b495 | ppitu/Python | /Studia/Cwiczenia/Zestaw6/Zad5/fracs.py | 1,366 | 3.578125 | 4 | import math
def nwd(x, y):
zmienna = math.gcd(x, y)
return Frac(x/zmienna, y/zmienna)
class Frac:
"""Klasa reprezentujaca ulamek."""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
if self.y == 1:
return "{}".format(self.x)
else:
return "{}/{}".format(self.x, self.y)
... |
7019e2cb4fcf23193a692bd89075c1745e7dabf5 | JordanHolmes/cp1404practicals | /prac_03/Extension & Practice work/word_generator.py | 1,124 | 4.125 | 4 | """
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
MENU = """Pick the format of the word
(C) for constants
... |
049e0a057caa1c5e641f848ee02d096828d928c6 | janellecueto/HackerRank | /Python/Collections/CollectionsCounter.py | 420 | 3.640625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter
X = int(input())
shoes = Counter(list(input().split()))
N = int(input())
money = 0
for i in range(N):
#add price to money if shoe still exists
size, price = input().split()
if size in shoes.elements():
... |
1669f0cd9a6fcfed515b02817127e43f8410e9cf | soumya9988/Python_Machine_Learning_Basics | /Python_Basic/6_Strings/dna_assignment.py | 2,891 | 4.28125 | 4 |
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequenc... |
1adcfc66e6657219a72c7ff0b7897ddb3586a6cd | Rolodophone/various-python-programs | /Completed/Search Day Robot Wars Game/Search Day Robot Wars Game.py | 7,794 | 3.734375 | 4 | import random
PAGE_SPLIT = "\n" * 60
robotList = None
players = None
NUM_OF_PLAYERS = None
MAX_NAME_LENGTH = 50
WINNING_SCORE = 5
def main():
loadRobots()
loadSettings()
endGame(cardGame2(NUM_OF_PLAYERS))
def loadRobots():
global robotList
#rea... |
f44096f61a4c4d271f7644305480461b01703975 | hemanthmalik/dsa | /sorting/quick_sort.py | 472 | 3.578125 | 4 | def quick_sort(arr, l, r): # T(n)=O(n) S(n)=O(1)
if r-l <= 1:
return arr
yellow = green = l+1
while green < r:
if arr[green] <= arr[l]:
arr[yellow], arr[green] = arr[green], arr[yellow]
yellow += 1
green += 1
arr[l], arr[yellow-1] = arr[yellow-1], arr... |
6ff1149d3ccd604406fae2f58c1118d0db2b3076 | ani03sha/Python-Language | /15_numpy/05_zeros_and_ones.py | 385 | 4.09375 | 4 | # You are given the shape of the array in the form of space-separated integers, each integer representing the size of
# different dimensions, your task is to print an array of the given shape and integer type using the tools
# numpy.zeros and numpy.ones.
import numpy
n = tuple(map(int, input().split()))
print(numpy.... |
1f8e043ada99a61c73f2184a4b7ebc99fac3ec74 | vai-agr/MonteCarloSim-Laplace-Poisson | /poisson_solution.py | 1,818 | 3.734375 | 4 | import random_walk as rw #imported random_walk.py for using the randomWalk1D function
import matplotlib.pyplot as plt #for graphing functions
number_of_walks = 200 #Number of random walks for each point
step_size = 1 #Distance between each point = 1cm i.e. 10 divisions
length = 20 #Distance between the... |
94c5e004150a0b33813066c72644c3a1514d6871 | miyazi777/learn_python | /dictionary.py | 579 | 3.5 | 4 | dic = {'item1': 100, 'item2': 200, 'item3': 300}
# access
print(dic['item1']) # 100
# add
dic['item4'] = 400
print(dic) # item1:100, item2:200, item3:300, item4:400
# update
dic['item1'] = 120
print(dic['item1']) # 120
# delete
del dic['item4']
print(dic) # item1:100, item2:200, item3:300
# key check
print('item... |
3c110838842360d524a4254424f28b6af5a012f2 | Tanmay53/cohort_3 | /submissions/sm_009_chinmay/week_13/day_4/part_2/count_unique.py | 144 | 3.84375 | 4 | # Given a list of items find the unique no of present (HINT: Use Sets)
list = ['a','a','a','b', 'c', 'a' ]
unique = set(list)
print(len(unique)) |
0cd9b1664799e380cbb7dfa3fd982f00fd4a016f | elena-off/sssp-loihiemulator | /RandomGraphGenerator.py | 3,998 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import random
import time
import networkx, random
import math
# random seed from current time
random.seed(time.time())
#generate a random graph dictionary given number of nodes, probability of connection between the nodes and maximal cost
def random_gr... |
2f76a05c4f8d9286453f0713cad7edf1b982f8a8 | BrandMeredith/exam_builder | /submenu.py | 1,955 | 3.71875 | 4 | import sys
class Submenu:
'''Display a menu and respond to choices when run.'''
def __init__(self,menu):
self.sections = list(menu.full_problem_list.chapter_section_list) #copy list
self.uncovered_sections = list(menu.uncovered_sections) #copy list
self.covered_sections = list(menu.cove... |
8eb1d7ceec45461930294acccf2ed5d3c2f5d4ab | guodafeng/pythondev | /algorithm/qsort.py | 701 | 3.796875 | 4 | def qsort(s,left,right):
if left >= right:
return s
l = left
r = right
k = s[l]
flag = True # True means minus r
while l < r:
if flag:
if s[r] < k:
s[l] = s[r]
flag = False
else:
r -= 1
else:
... |
2dfc76cc8779631c4de7b5a5ca885208e80e45d8 | doroshenkoam/android_vs_covid | /player.py | 2,259 | 3.5 | 4 | import pygame
import config as c
import auxiliary as a
# player - класс основного персонажа
class player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, font_health):
pygame.sprite.Sprite.__init__(self)
self.image = a.load_image("player.png").convert_alpha()
self.rect = self... |
bb0f7a0e59fc30032433c0742202386778cc65cf | avvarga/Lab206 | /Python/OOP/car.py | 725 | 3.859375 | 4 | class car(object):
def __init__ (self,price,speed,fuel,mileage):
self.price=price
self.speed=speed
self.fuel=fuel
self.mileage=mileage
if price>10000:
self.tax= 0.15
else:
self.tax= 0.12
print self.display_all()
def display_all(self... |
4b2d09bc63f7ac5fdfd4b34b3c4a41fa7fc0a9ee | sad786/Python-Practice-Programs | /Python/Operator.py | 1,067 | 4.09375 | 4 | class Employee:
def __init__(self,salary,name,city):
self.salary = salary
self.name = name
self.city = city
def __add__(self,other):
self.salary = self.salary+other.salary
def __lt__(self,other):
return self.salary<other.salary
def __gt__(self,other):
return self.salary>other.salary
def ... |
20a1d086c7aa021e72b123094a026f08bd09b9b0 | doubledouLiu/python | /pythnonStudy/com/doubledou/study/use_python_study_python/test.py | 946 | 3.53125 | 4 | def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
def __sub__(self, r):
return Rational(self.p * ... |
22bbc4de252960bebeb3d10c9afb30dd29e2d106 | jmbosley/EulerProject | /Euler Project 56.py | 227 | 3.734375 | 4 | answer = 0
for a in range(100):
for b in range(100):
num = str(a**b)
temp = 0
for i in num:
temp = temp + int(i)
if temp > answer:
answer = temp
print(answer) |
ce287f60aa83213094bfda84fff4088d970feda7 | skavhaug/rasbeery | /raspberry.pi/rasbeery/mash.py | 2,082 | 3.546875 | 4 | from typing import List, Optional
import numpy as np
import matplotlib.pyplot as plt
from .water import WaterAdjustment
class MashStep:
def __init__(self, duration: int, temperature: float) -> None:
self.duration = duration
self.temperature = temperature
class Mash:
def __init__(self,
... |
7c4855f151941740e2f72d9a0175601e291ec2ef | Maomaobadmonkey/Hangman-Game | /Hangman/task/hangman/hangman.py | 467 | 3.734375 | 4 | import random
print("H A N G M A N") # Write your code here
random.seed()
guess_words = ['python', 'java', 'kotlin', 'javascript']
picker = random.choice(guess_words)
guess_p = picker.replace('hon', '--')
guess_j = guess_p.rstrip('a') + '-'
guess_k = guess_j.replace('lin', '--')
guess_ja = guess_k.replace('ascript',... |
95ea079fa38cdd6de70049f7eaba5da307a930fd | adi-varshney/TicTacToe | /TicTacToe_Version1.0.py | 3,528 | 3.984375 | 4 | from SimpleUserInteraction import position_choice
from Player import Player
playerList = []
def get_player_names():
count = 1
while count < 3:
name = input('Enter player ' + str(count) + ' name: ')
age = input('Enter player ' + str(count) + ' age: ')
playerList.append(Player(name,... |
4181e50f79ad0969f0e905d1c01374563ddfd0e8 | kaushik-42/Data_Science_Projects | /Project_2/data/process_data.py | 3,515 | 3.578125 | 4 | import sys
import pandas as pd
from sqlalchemy import *
def load_data(messages_filepath, categories_filepath):
'''All the loading steps including merging is in the next 3 lines'''
"""
args:
messages_filepath is the the messages dataframe present in the csv format
categories_file... |
6a91ce4f20234ff1d24fd341c2e9945799529eda | davidhawkes11/PythonStdioGames | /src/gamesbyexample/sierpinskisquare.py | 2,313 | 4.1875 | 4 | """Sierpinski Square, by Al Sweigart al@inventwithpython.com
Draws the Sierpinski Square (also called Carpet) with turtle graphics.
More info at: https://en.wikipedia.org/wiki/Sierpinski_carpet"""
__version__ = 1
import turtle
turtle.tracer(100, 0) # Make the turtle draw faster.
# Setup the colors:
LIGHT_ORANGE = '#... |
25f8023f9c118dd50689b412b1bd1843b82e8801 | JefVerschuere/TikTakToe | /4Times4.py | 2,249 | 3.640625 | 4 | import random
import sys
from CheckIfSomeoneWon import *
def createBoard() :
board = []
for a in range (7) :
tabCollumn = []
for b in range(7) :
tabCollumn.append(" ")
board.append(tabCollumn)
return board
def insertInCollumn(numCollumn, board, car):
numCollumn = numCollumn - 1
for a in range(7) ... |
62aba30ffd5ca65695ff7e069b85d716cbb5ff81 | jrez7/semester-1-exam- | /main.py | 837 | 3.78125 | 4 | #### Describe each datatype below:(4 marks)
## 4 =
## 5.7 =
## True =
## Good Luck =
#### Which datatype would be useful for storing someone's height? (1 mark)
## Answer
#### Which datatype would be useful for storing someone's hair colour?(1 mark)
## Answer
####Create a variable tha will store ... |
6cc16056bd79060a9a16dccf297f8b6436f376a7 | joerocca-evolve/PyScriptPractice | /fruit_basket.py | 365 | 3.9375 | 4 | def guess_fruit(basket):
fruit_guess = input("Guess a fruit! Enter your guess below\n")
while fruit_guess not in basket:
fruit_guess = input("That fruit isn't in the basket. Try again!\n")
print("\nYou guessed correctly!")
def main():
fruit_basket = ["apple", "orange", "pear", "grape", "strawbe... |
cdf99f8a53c0d8df01b65865bc0392da2c176303 | Niccolum/intrst_algrms | /unpacking_flatten_lists/funcs.py | 4,339 | 3.859375 | 4 | """
Examples of python realization of solution for unpacking lists with indefinite depth
"""
from typing import Iterator, Iterable, List
from iteration_utilities import deepflatten
from more_itertools import collapse
# @profile
def outer_flatten_1(array: Iterable) -> List:
"""
Based on C realization of this... |
37e5ffffe6565e845e4bd7e536d78b0431c3b9f0 | JaspreetSAujla/Rock_Paper_Scissors | /Python/RockPaperScissors.py | 4,021 | 4.0625 | 4 | import random
import time
import sys
class RockPaperScissors:
"""
A class which stores the code for a game of rock paper scissors.
The game is ran for as long as the user wants to play.
Class Variables:
OPTION_LIST = Stores a list of possible options the computer
can pic... |
a64dc468ef0891df157993e38f28ad4afd8ee185 | jmery24/python | /ippython/funciones_minmax_310.py | 667 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 30 04:45:54 2013
@author: daniel
"""
#programa: funciones_minmax_310.py
#funcion que devuelve valores multiples mediante una lista
#funcion <minmax> devuelve valor minimo y maximo de una lista
#ejercicio 310
#definir funcion <minmax>
def minmax(listado):
minimo = mi... |
86725885dd69ae89a16fed4f245edd31415c0422 | popovale/python-stepic | /kurs2/Zadanie1_6_9.py | 351 | 3.609375 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(Loggable, list):
def append(self, arg):
super(LoggableList, self).append(arg) # 1 способ
#list.append(self,arg) # 2 способ
self.log(arg)
x=LoggableList([1,3,4])
x.appe... |
e20e23f7affd442a47a7a304056bf2f1c8133052 | 138818/test | /python2/day1/railway.py | 299 | 3.609375 | 4 | import time
def railway(length, speek):
print('#' * length, end='')
n = 0
while True:
time.sleep(speek)
print('\r%s>%s' % ('#' * n, '#' * (length-1 - n)), end='')
n += 1
if n == length:
n = 0
if __name__ == '__main__':
railway(30, 0.5)
|
f5398a3b9763da3b25e814144a8aa3a55c31015f | jianhui-ben/leetcode_python | /1109. Corporate Flight Bookings.py | 866 | 3.53125 | 4 | # 1109. Corporate Flight Bookings
# There are n flights that are labeled from 1 to n.
#
# You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.
#
# Return ... |
2132d96f16254b6669064da1fa6d62a6fd969d86 | acmduzhuo/python | /Python_homework_2019-10-12/test/7.py | 181 | 3.703125 | 4 | result = []
for x in [1, 2, 3]:#寻找x
for y in [3, 1, 4]:#寻找y
if x == 1:#限制x
if x != y:#限制y
result.append((x, y))
print(result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.