blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
24185bcb4295e5189877da4160ffe969a0252ebc | minhthe/practice-algorithms-and-data-structures | /Explore/September 30 days/13_insert_interval.py | 874 | 3.640625 | 4 | '''https://leetcode.com/problems/insert-interval/'''
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
rst= []
flag = True
x, y = newInterval
affect = False
if len(intervals) == 0: return [newInterval]
for i,k in ... |
7281ee96ccc8d25973560142ddcebe661e9edc99 | minhthe/practice-algorithms-and-data-structures | /Contest/176/01.py | 498 | 3.515625 | 4 | j'''
https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/
***Brute force
'''
class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
cnt = 0
m = len(grid)
if m == 0 : return 0
n = len... |
327afaa28fc5d1b4c7b89fda07a436e3961cf02e | ahungrynacho/project-in-os | /project1/sandbox.py | 1,687 | 3.921875 | 4 | class Node:
def __init__(self, value, parent):
self.parent = parent
self.value = value
self.children = []
self.leaf = True
def add_children(self, child):
child.parent = self
self.children.append(child)
self.leaf = False
return
def... |
31a875a2cf44c032c4edf1e28ea0f204474728d7 | biancagotaski/Assessment-Python | /task3.py | 2,403 | 3.921875 | 4 | # Escreva um programa em Python que:
# - gere uma estrutura que armazena o nome dos arquivos em
# um determinado diretório e a quantidade de bytes que
# eles ocupam em disco. Obtenha o nome do diretório do usuário.
# - Ordene decrescentemente esta estrutura pelo valor
# da quantidade de bytes ocupada em disco
# (pod... |
9c4491252d5103ae84c97afb2d55d569dd765193 | oxalorg/aoc | /src/day11.py | 2,160 | 3.515625 | 4 | from pprint import pprint
def find_adjacents_visible(matrix, i, j, m, n):
adjacents = []
for edge_dx in [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, -1), (-1, 1)]:
new_i = i + edge_dx[0]
new_j = j + edge_dx[1]
a = 0
while 0 <= new_i < m and 0 <= new_j < n:
a = matrix[new_i][new_j]... |
9610bdbfc5d6285b6fd186c158ee7bcdf0cd68db | wang-yikai/efficient-eater | /Efficient Eater Helper Files/Fast_Food_Database_Editor.py | 13,663 | 3.515625 | 4 | import sqlite3
import time
database_name = "Menu"
def open_database_connection(database_name):
conn = sqlite3.connect(database_name)
return conn
def open_database_cursor(conn):
c = conn.cursor()
return c
conn = open_database_connection(database_name)
c = open_database_cursor(conn... |
992956b4062697ec685708aa758e51713f4e4c9c | sbowl001/cs-module-project-recursive-sorting | /src/recursive_sorting/recursive_sorting.py | 3,151 | 4.21875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
while elements is not len(elements) - 1:
elements_combined = arrA + arrB
elements_val = elements_combined[0]
... |
851d94073eeca2f2f14092e7f81c6e8f02ab2799 | durbarroy/PyModules | /LeastSquares.py | 12,813 | 3.9375 | 4 | """
Created on Thu Jun 20 06:14:19 2013
"""
# Least Squares Fitting
"""
The following least square methods are below.
1. Polynomial fit for coefficients with LINEAR dependence
2. Gauss-Newton fit for NON-LINEAR coefficients with 2 parameters
3. Gauss-Newton fit for NON-LINEAR coefficients with 3 parameters
4. Gauss-Ne... |
c424a574d99c2c3c9c4a44ab382fa68d61494f04 | durbarroy/PyModules | /FirstDerivative.py | 1,699 | 3.765625 | 4 | """
Created on Sat Sep 21 23:44:35 2013
"""
# First Derivative Approximations
"""
The following first derivative methods are below.
1. Backward difference method
2. Forward difference method
3. Central difference method
"""
# 1
# backward difference method for first derivative approximation
#************************... |
bc2811f79153bc957016ca5cf7c856861b001ff4 | syntaxSizer/bc-9-oop | /TDD/sum/sum.py | 289 | 3.984375 | 4 | #/usr/bin/python
def my_sum(x,y):
'''
a method takes to number and return the sum
'''
if isinstance(x,int) and isinstance(y,int):
n = x+y
return n
raise TypeError
print my_sum(2,8)
if __name__ == '__main__':
print 'running'
else:
print 'imported'
|
c29a14460e0ccd435819c088a60c7a4bb336b3aa | Soares/graveyard | /django-utilities/utilities/decorators.py | 4,133 | 3.6875 | 4 | from functools import update_wrapper, partial
def with_fn(decorator):
"""
Allows a decorator to take mode arguments.
The first argument is the function to decorate, which defaults to None.
If the decorator is called without the function, it partially evaluates
itself with the keyword arguments and ... |
639ea4d85a826fb2f1869517f168ff555502e40b | Soares/graveyard | /django-utilities/utilities/itertools.py | 881 | 3.765625 | 4 | def irange(start, stop, step=1):
"""
>>> list(irange(1, 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(irange(5, 1, -1))
[5, 4, 3, 2, 1]
"""
return xrange(start, stop+step, step)
def unzip(iterable):
"""
Unzips an iterable of any bredth into multiple lists.
@iterable must be an ... |
6065b6d6ecb45e18d532a5a3bcf765851e97d1eb | iMeyerKimera/play-db | /joins.py | 929 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# joining data from multiple tables
import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
# retrieve data
c.execute("""
SELECT population.city, population.population,
regions.region FROM population, regions
WHERE population.city = r... |
6d7fc074fcd6e207ee59ed225c2e24e0a16f1279 | neelay-naman/TCP-Chat | /TCP Connection/sender.py | 2,473 | 3.59375 | 4 | """
This is a 2 device connection for sending and receiving messages.
I did it using functional programming and a lot of exception handling,
so please don't point out any mistakes. I did it after 2 months of failing to do a google search!
Also I'm a Rookie
Default size of received and sent texts is 1024 bytes or ... |
a0726dd521de08339fa610661bb8a4d2171bf88b | naeo28/bioinfo-lecture-2021-07 | /bioinfo_python/007.py | 146 | 3.703125 | 4 | #!/usr/bin/python3
for i in range(1,10,1):
if i % 2 == 0:
for j in range(1,10,1):
print(f"{i}x{j}={i*j}")
print("")
|
978ae8c5e7703f01ba88db40c838cc25d259f6c9 | michaelmdrs/Hackaton-Polemic-Knowledge | /desafio04ValidadorCPF.py | 220 | 3.84375 | 4 | #Desafio4 - Validador de CPF
print('Informe seu CPF (apenas números)')
print('=' * 32)
numero_cpf = str(input('Digite seu CPF: '))
if len(numero_cpf) == 11:
print('CPF Válido')
else:
print('CPF Inválido')
|
0aa388685486022d15a8464da9c5691f19b0202e | kmayerb/Meleagris | /meleagris/carve.py | 533 | 3.703125 | 4 | import numpy as np
def carve(a,b):
"""
carve a sum
:param a: int or float
:param b: int or float
:return: sum of a and b
:example: carve(1,3)
>4
"""
return(np.sum([a,b]))
def carve3(a,b,c):
"""
carve a sum of 3 parts
:param a: int or float
:param b: int or float
... |
e2443d45a49aa1b205649aa1eb45a59079d62d4f | svv232/Data-Structs-Algos- | /DataStructures/mta.py | 2,005 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 3 20:01:26 2016
@author: Sai Vegasena
"""
'''
Sai Vegasena
Creates a dictionary data structure from a file
of train stop information and prints it in an
organized manner based off user input
'''
def file_data_to_dict(filename): #creates the dictionary from th... |
872d3970ff41f3221a38f2c076548c01d7d7e33a | curious-username/python-crash-course | /chp4/dimensions.py | 538 | 4.03125 | 4 | #Tuple is like a list that doesn't change so a constant for lists. It uses parentheses vs square brackets.
dimensions = (200, 50)
#Attempt to modify a tuple, gives typeerror
#dimensions[0] = 250
#printing each element in the tuple
#print(dimensions[0])
#print(dimensions[1])
#loop throught tuple
print("Original dime... |
33b417a9375c733c2c19a51b5f1c05036c3c90ee | henrinehlsen/LPTHW | /Ex36/ex36.py | 6,419 | 3.890625 | 4 | import time
from sys import exit
positive=["ja", "yes", "yep", "of course", "indeed", "definitely", "absolutely"]
negative=["no", "nope", "nein", "nay", "not"]
not_understood = "I didn\'t get that, sorry"
def define_player():
print "Welcome!"
print "What is your name?"
define_player.player_name = raw_inpu... |
7496e42626f21bcd7f526a5be0c1a56698fc133c | derajo/ReLU | /src/models/logistic_regression.py | 2,228 | 3.5 | 4 | import numpy as np
from utils import train_test_split
import sys
print(sys.version)
def sigmoid(z):
"""
computes the sigmoid of z.
"""
return 1 / (1 + np.e**(-z))
def loss(X,y,theta):
"""
Loss function for logistic regression
"""
z = np.dot(X,theta)
h = sigmoid(z)
ret... |
72e9b01c4773acbedcb9f4bb01b2a40fddf01f49 | z0di4ckX/Master-python | /01-holamundo/comen.py | 312 | 3.8125 | 4 | # Esto me mostrara el texto Hello por la consola
print("Hello")
# Estas dos instrucciones muestran texto por la pantalla
print("World")
print("!!!")
"""
Esto no se mostrara:
- print("Esto no se va a mostrar por pantalla")
- print("Por que estara dentro de un comentario mutilinias")
"""
print("Adios") |
cc7b630c57d928fa96813fd26913f7e2dab8dba8 | z0di4ckX/Master-python | /07-ejercicios/ejercicio3.py | 483 | 3.96875 | 4 | """
Ejercicio 3. Escribir un programa que muestre los cuadrados
(un numero multiplicado por si mismo) de los 60 primeros numero
naturales. Resolver con "for" y "while".
"""
# WHILE
contador = 0
while contador <= 60:
cuadrado = contador*contador
print(f"El cuadrado {contador} es {cuadrado}")
contador += ... |
ad43ef67d4b737cfffec2810d846b14a6f69d65e | TheodorusF/15-puzzle | /15.py | 5,312 | 3.671875 | 4 | from tkinter import *
import random
class YouButt:
def __init__(self, x, y, btn=False, button=None):
self.x = x
self.y = y
self.b_x = x
self.b_y = y
self.count = 0
def begin(self):
if self.x == self.b_x and self.y == self.b_y:
return True
re... |
301df2b9b29cfd51f5fbc6d47e8e6ea52a8e897f | doremifasollasi/Home_workshop_python_libraries | /SQLAlchemy/run.py | 3,273 | 4.0625 | 4 | # https://docs.sqlalchemy.org/en/14/core/tutorial.html
# Using the Table objects directly
# We don't even need to map our Table-objects in order to manipulate our tables
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, text
engine = create_engine('sqli... |
1ed293becc97a9a57fd91aa0648e218a0620e250 | PriyankaJhaTheAnalyst/PythonDataStructures | /manipulating_lists.py | 731 | 3.953125 | 4 | #concatenating lists using '+'
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
#slicing lists
t = [9, 41, 12, 3, 76, 90]
t[1:3]
t[:4]
t[3:]
t[:]
#building a list from scratch
stuff = list()
stuff.append('book')
stuff.append(99)
print(stuff)
#is something in the list?
some = [9, 41, 12, 3, 76, 90]
9 in some #gives - T... |
7316ac18d32bc728f7dee373034b8cdc2e4b4ac1 | varadtupe/HackerRank | /Data Structure/Arrays/countOccur.py | 315 | 3.59375 | 4 | def countOccur(q,inpStr):
cnt = 0
for i in inputStr:
if i == q:
cnt +=1
return cnt
N = int(input())
inputStr = []
for i in range(N):
string = input()
inputStr.append(string)
Q = int(input())
for i in range(Q):
query = input()
occurs = countOccur(query, inputStr)
print(occurs) |
f8bac8a1d0f7e934c61c9aff3ad37ec7ac42d8a0 | varadtupe/HackerRank | /Cracking the Coding Interview/checkBST.py | 712 | 3.8125 | 4 | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def checkBST(root):
if root is None:
return True
def isBST(node, min, max):
if node.data <= min:
return Fa... |
2909e9da710ee8da8f33f9c67687f697c8db7385 | lorenanicole/abbreviated-intro-to-python | /exercises/guessing_game_two.py | 1,143 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
"""
ITERATION THREE: Now that you have written a simple guessing
game, add some logic in that determines if the game is over
when either:
* user has correctly guesses the number
* user has reached 5 guesses
Let's use tw... |
20a6261e6e88144b0b07674e560cbfd64b422984 | sangee9968/codekata6 | /isalnum.py | 205 | 3.890625 | 4 | s=input()
if s.isalpha() or s.isdigit():
print("No")
elif any(i.isalpha() for i in s):
if any(i.isdigit() for i in s):
print("Yes")
else:
print("No")
else:
#print result
print("No")
|
4b0e0059c99c691ad8df734fd9fb8d1107e52a35 | ant-shiv/IP | /ip_plot0.py | 204 | 3.515625 | 4 | import pandas as pd
Area=[34567,890,450,67892,34677,78902,256711,678291,637632,25723,2367,11789,345,256517]
Ser1=pd.Series(Area)
print(Ser1.sort_values().tail(3))
print(Ser1.sort_values().head(3)) |
00e5554c6102b8d68b785053d6705e5806f4b0c7 | bernardofrassy/ml-scripts-coursera | /ML_Neural_Network.py | 12,838 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 10 14:32:49 2017
@author: bernardoalencar
Machine Learning Functions
"""
import numpy as np
class Network:
"""
Network to be used as a machine learning tool.
"""
def __init__(self, train_data: 'pd.DataFrame or similar',
... |
98612ab009ae0558b9a5ab39c8afd394c467b046 | heenashree/CTCI-Solutions-1 | /Chapter17 - Hard/Q14-SmallestK.py | 571 | 3.671875 | 4 | import heapq
def k_smallest(array, k):
if k < 0 or k > len(array):
return None
if k == len(array):
return array
heap = []
for item in array:
if len(heap) < k:
heapq.heappush(heap, -item)
else:
if -item > heap[0]:
heapq.heappop(hea... |
f487fe3fff610c3d7cf85141c50d807bc76cf034 | heenashree/CTCI-Solutions-1 | /Chapter3 - Stacks and Queues/Q6-AnimalShelter.py | 2,906 | 3.875 | 4 | class Node():
def __init__(self, data):
self.data = data
self.next = None
def appendToEnd(self, data):
current = self
while current.next != None:
current = current.next
current.next = Node(data)
def __repr__(self):
resp = ""
current = self
... |
b9fa07e90b79440612fe530c82ffed4a996030c5 | heenashree/CTCI-Solutions-1 | /Chapter8 - Recursion and Dynamic Programming/Q13-StackOfBoxes.py | 1,275 | 3.734375 | 4 | class box():
def __init__(self, w,h, d):
self.w = w
self.h = h
self.d = d
def __gt__(self, box2):
return self.w > box2.w and self.h > box2.h and self.d > box2.d
def __lt__(self, box2):
return self.w < box2.w and self.h < box2.h and self.d < box2.d
def __repr__(se... |
8015890859b0b49bd8d6164b71cf213dff4e1fa6 | heenashree/CTCI-Solutions-1 | /Chapter17 - Hard/Q11-WordDistance.py | 669 | 3.765625 | 4 | def findDist(w1, w2, bookWords):
if w1 not in bookWords or w2 not in bookWords:
return -1
l1 = bookWords[w1]
l2 = bookWords[w2]
dist = float('inf')
p1 = 0
p2 = 0
while p1 < len(l1) and p2<len(l2):
dist = min(dist, abs(l1[p1] - l2[p2]))
if l1[p1] < l2[p2]:
... |
8c446d5207ab3a1873d47fb537a3a40e196a2bbf | heenashree/CTCI-Solutions-1 | /Chapter17 - Hard/Q17-MultiSearch.py | 1,130 | 3.921875 | 4 | class Trie:
def __init__(self, wordList):
self.root = {}
self.end = '_end_'
for word in wordList:
self.add(word)
def add(self, word):
node = self.root
for letter in word:
if letter not in node:
node[letter] = {}
node = ... |
4d9220283574ab05b5b4ca58d8da8d428cba9b6e | heenashree/CTCI-Solutions-1 | /Chapter16 - Moderate/Q23-Rand7FromRand5.py | 330 | 3.578125 | 4 | import random
from collections import defaultdict
def r5():
return random.randint(0, 4)
def r7():
while True:
n = 5*r5() + r5()
if n <= 21:
return n%7
def main():
frequency = defaultdict(int)
for i in range(100):
n = r7()
frequency[n]+=1
print(frequenc... |
8be447a1744b73eaf77f4fe968f17d6408e63d70 | heenashree/CTCI-Solutions-1 | /Chapter2 - Linked Lists/Q8-LoopDetection.py | 739 | 3.75 | 4 | from node import Node
def loopDetection( head):
slow = head
fast = head
colision = None
while slow != None and fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
if slow is fast:
colision = slow
break
if colision != None:
... |
706d09789a2fca4b87d767f1a99b8b6a8d22833b | heenashree/CTCI-Solutions-1 | /Chapter16 - Moderate/Q19-PondSizes.py | 860 | 3.765625 | 4 | def isValid(matrix, row, col):
if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[row]):
return False
return True
def water(matrix, row, col):
if matrix[row][col] != 0:
return 0
else:
matrix[row][col] = -1
tot = 1
for i in range(-1, 2):
... |
e6a5f67dba51030455a771afe9143c7e39d8145b | heenashree/CTCI-Solutions-1 | /Chapter16 - Moderate/Q16-SubSort.py | 628 | 3.828125 | 4 | from collections import defaultdict
def subSort(v):
left = 0
right = 0
maxSoFar = float('-inf')
for i in range(len(v)):
if v[i] < maxSoFar:
right = i
maxSoFar = max(maxSoFar, v[i])
minSoFar = float('inf')
for i in range(len(v)-1, -1 ,-1):
if v[i] > minS... |
2da4fe2f140707478495ec10db66cde97d432b13 | saris20038/programacion01 | /clases/while.py | 1,090 | 4 | 4 | #ciclo para ahorrar de a mil pesos
PreguntaPrecio = "¿Cuanto vale el celular?: "
PrehguntaAhorro = "¿Cuanta plata tengo?: "
precio = float(input(PreguntaPrecio))
ahorro = float(input(PrehguntaAhorro))
if (ahorro >= precio):
print("Tenemos la plata, a comprarlo")
while(precio > ahorro):
print("Te falta dinero,... |
884185099fd172db1c527b8533506b68581c45e8 | saris20038/programacion01 | /clases/Funciones/Operacionesmatematicas.py | 811 | 3.890625 | 4 | def sumar (value1=0, value2=0, value3= 0):
return (value1 + value2 + value3)
def restar (value1=0, value2=0, value3= 0):
return (value1 - value2 - value3)
def multiplicar (value1=0, value2=0, value3= 0):
return (value1 * value2 * value3)
def dividir (value1=0, value2=0, value3= 0):
return (value1 / v... |
be60b390e1009fc00d628c7970f27237a1ca1382 | saris20038/programacion01 | /clases/quiz.py | 2,949 | 3.828125 | 4 | #CONSTANTES
MENSAJE_NUMERO = '''INGRESE ALGUNA DE LAS OPCIONES
1- Hacer conversión de pesos a dolares o euros.
2- Agregue un valor a la lista
3- Obtenga el valor máximo, mínimo y el promedio de la lista
4- Elimine un elemento de la lista
5- Salir
'''
MENSAJE_CONVERSION = '''¿Cuál es la conversió... |
b9a599544b5dbf2e0cf855cfe9b848f3fec098eb | juliakyrychuk/python-for-beginners-resources | /final-code/oop/car.py | 777 | 4.25 | 4 | class Car:
"""Represents a car object."""
def __init__(self, colour, make, model, miles=0):
"""Set initial details of car."""
self.colour = colour
self.make = make
self.model = model
self.miles = miles
def add_miles(self, miles):
"""Increase miles by given n... |
765285565c8b82733d118bc9967a01f095e5e009 | juliakyrychuk/python-for-beginners-resources | /final-code/data_structures/nested_dict.py | 194 | 3.5 | 4 | dog = {
'name': 'Otis',
'breed': 'Pug',
'owner': {
'name': 'Mark',
'age': 31,
}
}
print(dog)
owner_name = dog['owner']['name']
print(f'Owner Name: {owner_name}') |
757b154565f1b957e93a11ce34af847727fa6243 | juliakyrychuk/python-for-beginners-resources | /final-code/functions/params_multi_line.py | 544 | 3.53125 | 4 | def output_welcome_text(first_name,
last_name,
age,
location,
returning_user=True):
"""Output welcome text with users details"""
if returning_user:
msg_start = f'Welcome back {first_name} {last_name}!'
... |
3760eeb1091c8988388b91bccaa84a580ea11aef | juliakyrychuk/python-for-beginners-resources | /final-code/http_requests/forecast.py | 1,644 | 3.640625 | 4 | """
Weather forecast app.
"""
import argparse
import requests
API_KEY = 'CHANGEME'
API_BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast'
def handle_args():
"""Handle arguments."""
parser = argparse.ArgumentParser(description='Forecast the weather.')
parser.add_argument(
'city',
... |
eba01d4aca52c054d2fdd0f34220077dc251eabe | PingMaster99/AlphaHoppers | /AlphaHoppersMain.py | 7,212 | 3.53125 | 4 | """
AlphaHoppersMain.py
Utilizes Pygame and Minimax to generate a game of Hoppers
Pablo Ruiz 18259 (PingMaster99)
Version 1.0
Updated February 9, 2020
Controls:
Click - Select initial and final square for the hopper
Space - Reset the selected coordinates
"""
i... |
70504fde426af3e446033709871f1d5219844539 | Farmerjoe12/PythonLoanLadder | /pythonLoanLadder/model/Loan.py | 1,234 | 4.1875 | 4 | import numpy
import math
class Loan:
""" A representation of a Loan from a financial institution.
Loans are comprised of three main parts, a principal
or the amount for which the loan is disbursed, an interest rate
because lending companies are crooked organizations which charge
y... |
7b1b53b6d68c11bf6ed4821601d3660428eff6a3 | LIZETHVERA/python_crash | /chapter_8_functions/person.py | 542 | 4 | 4 | def build_person (first_name , last_name):
"""Return a dictionary of infomation about a person"""
person = {"first" : first_name, "last":last_name}
return person
musician = build_person ("jimi","hendrix")
print (musician)
def build_person (first_name , last_name, age =" "):
"""Return a dictionary... |
d58b6c5d46414600c5905f55bf359ab026821166 | LIZETHVERA/python_crash | /Chapter_3_Lists/seeing_the_worl_50.py | 451 | 3.75 | 4 | world_favs = ["japon","paris","amsterdam","italia","china"]
print (world_favs)
print (sorted (world_favs))
print (world_favs) # Original list
world_favs.reverse()
print (world_favs)
world_favs.reverse()
print (world_favs)
world_favs.sort()
print (world_favs)
world_favs.sort(reverse=True)
print (world... |
e96dbb8d2f50ce761d058b3f79d708c2f2600749 | LIZETHVERA/python_crash | /chapter_7_input_while/no_pastrami.py | 561 | 3.890625 | 4 | sandwich_orders = ["chicken","pastrami","tuna","pastrami","vegetables","pastrami"]
finished_sandwiches = []
while "pastrami" in sandwich_orders:
sandwich_orders.remove("pastrami")
print ("Deli has run out of pastrami")
print ("\n")
while sandwich_orders:
finished_sandwich = sandwich_orders.pop()
... |
785903e37ee2784bb0b1f8ebe134360d62ecf9bb | LIZETHVERA/python_crash | /chapter_8_functions/pets.py | 817 | 3.53125 | 4 | def describe_pet (animal_type, pet_name):
"""Display informaction about a pet"""
print ("\nI have a " + animal_type + ".")
print ("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet ("hamster","harry")
def describe_pet (animal_type, pet_name):
"""Display informaction about a pet"... |
365202e7f1df74e13f9cdf28f4f281524d7b1e70 | LIZETHVERA/python_crash | /chapter_6_dictionaries/aliens.py | 897 | 3.9375 | 4 | alien_0 = {"color":"green","points":"5"}
alien_1 = {"color":"yellow","points":"10"}
alien_2 = {"color":"red","points":"15"}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print (alien)
print ("\n")
#make an empty lis for storing aliens.
aliens = []
#Make 30 green aliens.
aliens
for alien_number in ran... |
0a0558e50b0bd8f9f41348596aae5c06ac66c7e7 | LIZETHVERA/python_crash | /chapter_7_input_while/parrot.py | 788 | 4.3125 | 4 | message = input ("Tell me something, and i will repetar it back to you: ")
print (message)
name = input ("please enter your name: ")
print ("hello, "+ name + "!")
prompt = "If you tell us who you are, we can personalize the messages you see"
prompt += "\nWhat is your first name?"
name = input (prompt)
print ("\nHe... |
504706762139e10779a5d2b1ce73fbffcdb28eb8 | leoxie080808/BetaTesting | /HoverWithClickCheck/HoverWithClickCheck.pyde | 949 | 3.640625 | 4 | myList = [0,1,2,3]
flagOne = True
flagTwo = False
def setup():
size(900, 600)
noStroke()
def draw():
mouseHovering(flagOne, flagTwo)
if flagOne == True:
fill(120,120,120)
rect(500,500,50,50)
elif flagOne == False:
fill(230,120,0)
rect(500,500,50,... |
3b5e19472d33a08f13f9c4dea3ba9d782209ddf5 | Akshidhlavanya/pythonprogramming1 | /beginnerlevel/Beginnerset1(9)sumofdigits.py | 114 | 3.671875 | 4 | n=int(input())
k=int(input())
sum=0
for x in range(1,k+1):
number=int(input())
sum=sum+number
print(sum)
|
51a6df394570c4a24d418321c8e3c4f147937e37 | Akshidhlavanya/pythonprogramming1 | /beginnerlevel/Beginnerset7(7)printnearestmultipleof10.py | 80 | 3.765625 | 4 | num=int(input())
for x in range(num)
mul=10*num
if(mul>num):
print(mul)
|
6dc5592a90364b09411110fca5d3678e1773433d | Akshidhlavanya/pythonprogramming1 | /Player/Playerset12(4)sumofsquareofnumber.py | 122 | 3.515625 | 4 | try:
a=int(input())
sum=0
while(a>0):
x=a%10
sum+=x
a=a//10
print(sum*sum)
except:
print('Invalid')
|
fee7b06badf7041f9be4bcf9576f59cf9c0747ef | Akshidhlavanya/pythonprogramming1 | /beginnerlevel/Beginnerset7(4)sumisoddoreven.py | 89 | 3.9375 | 4 | M=int(input())
N=int(input())
sum=N+M
if(sum%2==0):
print('even')
else:
print('odd')
|
114682a88355575ff179d1385fd1067aa2f97786 | Akshidhlavanya/pythonprogramming1 | /beginnerlevel/Beginnerset9(2)areaoffarm.py | 69 | 3.5 | 4 | L=float(input())
B=float(input())
area=(L*B)
a='%.5f' %area
print(a)
|
4a7bf08d497615abc383754946e9479340ec2186 | JorgeDiazz/Competitive-Programming | /Project Euler/Problem14.py | 268 | 3.8125 | 4 | number = 0
largest_count = 0
for n in range(1, 1000000, 2):
count = 0; possible = n
while n != 1:
n = 3*n + 1 if n % 2 else n >> 1
count += 1
if count > largest_count:
largest_count = count
number = possible
print(number)
|
ac48a164c8f4f65ab0c60c7ca1204eb8c823b434 | Shorokhov-A/practical_tasks | /Shorokhov_Andreiy_dz_1/task_1_2.py | 1,299 | 3.796875 | 4 | odd_number_list = []
idx = 1
number_sum = 0
while idx < 1000:
if idx % 2 != 0:
odd_number_list.append(idx ** 3)
idx += 1
print('Cписок, состоящий из кубов нечётных чисел от 1 до 1000:')
print(odd_number_list)
for number in odd_number_list:
digits_sum = 0
idx = number
while idx > 0:
... |
4f3eab5001ad299eafa61716d4568987f81b0c8b | Shorokhov-A/practical_tasks | /Shorokhov_Andreiy_dz_2/task_2_2.py | 851 | 3.546875 | 4 | example_list = ['в', '5', 'часов', '17', 'минут', 'температура', 'воздуха',
'была', '+5', 'градусов']
list_processed = []
for element in example_list:
list_processed.append(element)
if element.isdigit():
list_processed.pop()
list_processed.extend(['"', f'{int(element):02d}', ... |
407958c6e7c5802eaf4ea7dd0f6b73b1f9e71edb | nicholas-patterson/PythonCS-Practice | /HashTable.py | 2,405 | 3.515625 | 4 | class HashTable(object):
def __init__(self, array_size):
self.array_size = array_size
self.array_bucket = [None for item in range(array_size)]
def hash_key(self, key, count_collisions=0):
char_bytes = key.encode()
hashed = sum(char_bytes)
return hashed + count_collisions... |
4911b662843dfcbfb5b1f98ed7bd1b038fd51661 | olsgaard/adventofcode2019 | /day04_solve_puzzle2.py | 1,995 | 3.875 | 4 | def is_ascending(number):
ns = str(number)
return all([ns[i] >= ns[i-1] for i in range(1, len(ns))])
assert is_ascending(123456) == True
assert is_ascending(1234444456) == True
assert is_ascending(1234566666) == True
assert is_ascending(1111234566666) == True
assert is_ascending(1234566566) == False
assert is_ascen... |
f25f1e4333a6c8a4ef1f22eb18a430ad3be862ab | olsgaard/adventofcode2019 | /day01_solve_puzzle1.py | 801 | 4.5 | 4 | """
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
For example:
For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
For a mass of 14, dividing by 3 and rounding do... |
47faab066384b5f26dc6767c263f1cce21b1efb9 | osmandi/programarcadegames | /Capítulo 4: Adivianzas con números aleatorios y bucles/numeros_aleatorios.py | 630 | 3.984375 | 4 | #No se debe guardar el archivo .py con el nombre de la librería
print ("\n")
import random
#Número aleatorio entre 0 y 49
mi_numero = random.randrange(50)
print (mi_numero)
print("")
#Número aleatorio entre 100 y 200
numero = random.randrange(100,201) #El límite no se imprime
print (numero)
print ("")
#Elegir al a... |
4ca178f0001895353568c77d443a8868015ff547 | osmandi/programarcadegames | /Capítulo 12: Introducción a los sprites/spriteConDisparos.py | 5,075 | 4.1875 | 4 | """
Nos enseña como disparar proyectiles
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Vídeo explicativo: http://youtu.be/PpdJjaiLX6A
"""
import pygame
import random
# Definimos algunos colores
NEGRO = ( 0, 0, 0)
BLANC... |
a00d0f8ef6e6f6ba51524c3c0309ebe863ab9581 | osmandi/programarcadegames | /Capítulo 4: Adivianzas con números aleatorios y bucles/ejemplos_de_while.py | 1,633 | 4.21875 | 4 | """
# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://programarcadegames.com/
# http://simpson.edu/computer-science/
"""
# Podemos emplear un bucle while allí donde, también, podríamos usar un bucle for:
i = 0
while i < 10:
print(i)
i = i + 1
# Es lo mismo que:
for i in range(10):
... |
65aa8e72d8b3b44aaf8457ba08931c23eb3c7f70 | osmandi/programarcadegames | /Capítulo 1: Crear una calculadora personal/lab_1_calculadoras_personalizadas_1.py | 310 | 3.84375 | 4 | '''
Crear un programa que le pregunte al usuario por la temperatura
en grados Celsius, y que la devuelva en grados Fahrenheit
'''
temp_grado_celsius = float(input("Ingrese temperatura en grados Celsius"))
f = temp_grado_celsius*(9/5)+32
print (temp_grado_celsius, "grados Celsius en grados Fahrenheit es:", f) |
bab473b3c1c99716eb1306788aed7a6154f8267e | osmandi/programarcadegames | /Capítulo 1: Crear una calculadora personal/Operadores_de_asignacion.py | 217 | 3.859375 | 4 | # Crea una variable x
# Almacena en ella el valor 10.
x = 10
# Esto imprime el valor almacenado en x.
print(x)
# Esto imprime la letra x pero no el valor que contiene
print("x")
# Esto imprime "x= 10"
print("x=",x) |
3aa375fbfcd085e085f189bb2633c1eed666b337 | osmandi/programarcadegames | /Capítulo 4: Adivianzas con números aleatorios y bucles/lab_4_camello.py | 3,880 | 3.84375 | 4 | #Juego de camello
#Librería para números aleatorios
import random
#Mensaje de entrada
print ("\n")
print ("¡Bienvenido al Camello!")
print ("Has robado un camello para atraversar el gran desierto del Mobi.")
print ("¡Los nativos quieren que les devuelvas su camello y salen en persecución tuya!")
print ("Tendrás que s... |
7be9c7cf55bb2065c8dfc8e643c8449e8068b93f | osmandi/programarcadegames | /Capítulo 1: Crear una calculadora personal/lab_1_calculadoras_personalizadas_3.py | 371 | 4.03125 | 4 | '''
Créate tu propio problema y mira qué variables deberá introducir
el usuario. Si no estás por la abor de hacer algo original, escoge
alguna de las ecuacones de esta lista
'''
print ("Este es un programa que determina el área de un círculo")
radio = float (input("Igrese el radio en metros"))
area = 3.1416*radio**2
pr... |
b6524d5ed308317d8ab0ecbfcfd66370990d2d51 | osmandi/programarcadegames | /Capítulo 14: Bibliotecas y módulos/grafica_senos_colores.py | 330 | 3.796875 | 4 | """
Uso de 'fill' para rellenar una gráfica
"""
import numpy
import matplotlib.pyplot as plt
x = numpy.arange(0.0, 2.0, 0.001)
y = numpy.sin(2 * numpy.pi * x)
plt.plot(x, y)
# 'b' significa azul. 'alpha' es la transparencia.
plt.fill(x, y, 'b', alpha = 0.3)
plt.ylabel('Valor del Elemento')
plt.xlabel('Elemento')
p... |
4809d74e30e4e2631a37e3fb05ebb59d9d367b6e | osmandi/programarcadegames | /Capítulo 5/ejercicio_lab5_.py | 2,457 | 3.703125 | 4 | """
- Utilizar múltiples colores.
Hacer un dibujo coherente. No me interesa el arte abstracto de formas
aleatorias.
- Utilizar múltiples tipos de funciones gráficas (por ejemplo; círculos,
rectángulos, líneas, etc.)
- Utilizar, ya sea un bucle while, o uno for, para crear un patrón repetitivo.
No vayas a dibujar lo m... |
27aaa558d6f5144dc82ebe0f4b4f73fa5840f590 | mananiac/Leetcode | /485. Max Consecutive Ones.py | 1,332 | 3.75 | 4 | '''
Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only c... |
3b1f6faae39750425c1f9afb120f8144c4683cd0 | mingruimingrui/FastTokenizer | /bindings/python/fasttokenizer/__init__.py | 1,807 | 3.578125 | 4 | """Type hint and docstrings for fasttokenizer."""
from fasttokenizer import _fasttokenizer
__all__ = ['Segmenter']
__version__ = _fasttokenizer.__version__
class Segmenter(_fasttokenizer.Segmenter):
"""A universal text segmenter that works for all languages.
Args:
protected_dash_split (bool, option... |
af03e3f346a215c620bef13d91d47aeb99a0aea8 | minuso/leetcode | /0965/isUnivalTree.py | 340 | 3.8125 | 4 | def isUnivalTree(self, root: TreeNode) -> bool:
val = root.val
stack = [root.left, root.right]
while stack:
node = stack.pop()
if node:
if node.val != val:
return False
stack.extend([node.left, node.right]) # list.extend() is used to append multiple va... |
0dd3e72602c557f9d9631b5a52411062a5886804 | minuso/leetcode | /0414/thirdMax.py | 366 | 3.796875 | 4 | def thirdMax(self, nums: List[int]) -> int:
nums = list(set(nums))
if len(nums) < 3: return max(nums)
[r3, r2, r1] = sorted(nums[:3])
for n in nums[3:]:
if n < r3:
continue
if n < r2:
r3 = n
elif n < r1:
r3, r2 = r2, n
else:
... |
c0dc5228b05713c482982a1641013cf8b98e0ca1 | minuso/leetcode | /0459/repeatedSubstringPattern.py | 297 | 3.578125 | 4 | def repeatedSubstringPattern(self, s: str) -> bool:
# If True, s has as least 2 repeated substrings
# S = s*2 # has at least 4 repeated substrings
# S[1:-1] remove the first and the last substring,
# which has at least 2 repeated substrings (contains s)
return s in (s*2)[1:-1] |
15dd480644b1c5d46dd6ee841f20d465c315d6c4 | minuso/leetcode | /0461/hammingDistance.py | 209 | 3.703125 | 4 | def hammingDistance(self, x: int, y: int) -> int:
x = x ^ y # do xor (and then count '1's)
y = 0
while x:
y += 1
x &= (x - 1) # useful tip for removing the last '1' bit
return y |
2cba66790095bb94c217ec72f3d91fb79e73c2ed | minuso/leetcode | /0572/isSubtree.py | 686 | 3.734375 | 4 | def isSameTree(self, t1, t2):
if not t1 and not t2: return True
if not t1 or not t2: return False
if t1.val != t2.val: return False
return self.isSameTree(t1.left, t2.left) and self.isSameTree(t1.right, t2.right)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
# recursive
if self... |
ca6e1c5ea90c8a7cef0eff28b7f9bcac180cfc21 | minuso/leetcode | /0896/isMonotonic.py | 229 | 3.703125 | 4 | def isMonotonic(self, A: List[int]) -> bool:
if len(A) < 3: return True
d = 1 if A[-1] - A[0] > 0 else -1
for i in range(len(A) - 1):
if (A[i+1] - A[i])*d < 0:
return False
return True |
b2aeb422bb1e6940d681c3a48146d5137c5fa182 | Haris-Siddiqi/Python-Excercises | /Ex20_functions_files.py | 820 | 3.953125 | 4 | # Ex 20
# Functions and Files
# Get file from command line
from sys import argv
script, input_file = argv
# Print entire file
def print_all(f):
print(f.read())
# Go to beginning of file
def rewind(f):
f.seek(0)
# Prints a specific line
def print_a_line(line_count, f):
print(line_count, f.readline())
# ... |
0a12da07f4ed6aa879deda23a03e422fc3eaa08c | Bbooth4/python-tic-tac-toe | /test.py | 5,434 | 3.9375 | 4 | from random import shuffle, randint
print('hello world', 2 + 1, 50 % 10, 0.1+0.2-0.3, type(1))
# types - int, float, str, list, dict, tup, set, bool (True/False)
# && = and || = or
a = 'test string'
# a[start:end:skip/step]
print(a[1:8:2])
# can be used to reverse a string
print(a[::-1])
q = 'string'
q = 'name'
... |
8babb5d69af4566be9e87b2f2ab8c7f42c76f9aa | VitaliiPolishchuk/telegram_bot_truth_or_lie | /SQLither.py | 4,071 | 3.546875 | 4 | # -- coding utf-8 --
import sqlite3
from QuestionData import QuestionData
from EnrolledUserData import EnrolledUserData
from FinishedUserData import FinishedUserData
class SQLither:
def __init__(self, database):
self.connection = sqlite3.connect(database)
self.cursor = self.connection.cursor()
... |
01927132d16e028ef62e70bd99159d6a3d12aba9 | Chri5G/Sudoku-Solver | /Sudoku.py | 2,528 | 3.625 | 4 | board = [
[2,0,7,0,3,5,0,0,4],
[6,0,9,0,0,0,0,0,0],
[0,0,0,0,0,7,0,0,0],
[7,0,4,9,0,0,6,0,8],
[3,0,0,0,6,0,0,0,1],
[1,0,5,0,0,2,7,0,9],
[0,0,8,0,0,0,0,0,0],
[0,0,0,0,0,0,9,0,5],
[4,0,0,5,2,0,1,0,3]
]
def solve(board):#solving the game
#print(board)#shows step by step ... |
77da7fdefd5a5ddc68ce5652094f4ad1b627d3a3 | stefantoncu01/Pizza-project | /pizza_project.py | 2,981 | 4.125 | 4 | class Pizza:
"""
Creates a pizza with the attributes: name, size, ingredients
"""
def __init__(self, name, size):
self.name = name
self.size = size
self.ingredients = None
@property
def price(self):
"""
Calculates the price based on size and i... |
4472beaefec4bbcb6f61ddd0e7d16dcc01eb6de6 | dealant/atbs | /src/root/nested/XkcdDownloads.py | 1,576 | 3.5 | 4 | #! python3
'''
Created on May 27, 2019
@author: alansuface
Loads the XKCD home page.
Saves the comic image on that page.
Follows the Previous Comic link.
Repeats until it reaches the first comic.
'''
import requests, bs4, webbrowser, os
url = 'http://xkcd.com' # starting url
os.maked... |
5140542316b8c6a49ea31fd6c1ffcdbeed26f9a9 | dealant/atbs | /src/root/nested/pw.py | 556 | 3.875 | 4 | #! python 3
# a password organizer
password = {'1' : ' 0001',
'desktoppin' : '0202',
'worklaptop' : 'thing'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg... |
fc76ea3feea20c7868f5ff65f6cb94b21359eb0f | namanM003/PortScanner | /database_view.py | 520 | 3.78125 | 4 | import sqlite3
conn = sqlite3.connect('portdb')
cursor = conn.execute("SELECT * from IPINFO ORDER BY TIME DESC")
for roe in cursor:
print roe
print " See till here "
cursor = conn.execute("SELECT * from PORTDATA")
for row in cursor:
print 'x'
print "Printing the whole table"
cursor = conn.execute("SELECT * from IPD... |
0b72b2021312926e8025b837c544ee3dfc1baeeb | yotsuba4/BaiTapChuoiPython | /BaiTapChuoi/bai2.py | 759 | 3.59375 | 4 | #chuoi=input("Nhap vao mot chuoi: ")
#a=input("Nhap vao ky tu: ")
#print(chuoi.count(a))
#print(chuoi.find(a))
#for i in range(len(chuoi)):
# print(str(chuoi[i])+":"+str(chuoi.count(chuoi[i])))
#tu=input("Nhap vao mot tu: ")
#print(chuoi.find(tu))
xaukitu=input("Nhap vao 1 xau bat ki: ")
kitu = input("Nhap vao 1 ky... |
36ba2447ff3e9f95fc77d25b7f922419d3304c7c | jemgodden/Sorting-Algorithms | /sortAlgs.py | 11,619 | 4.1875 | 4 | import time
'''
This file contains the implementation of eight separate sorting algorithms, whose names can be seen below in
sortingAlgNames. It also contains some utility functions for looking at lists.
'''
sortingAlgNames = ["Bubble Sort", "Comb Sort", "Insertion Sort", "Selection Sort", "Quick Sort", "Merge Sort... |
c515933f3effedddecffe7bdb0009e3ed99e9e45 | EdwardHarriss/C-Compiler-and-C-to-Python-Translator | /Python_Translator/translator_tests/tests/f11.py | 221 | 3.65625 | 4 | def geo(n):
acc = 0
t = n
while (t < n):
acc = (acc + t)
t = (t + 1)
return acc
def main():
return ((geo(3) + geo(2)) + geo(1))
if __name__ == '__main__':
import sys
ret = main()
sys.exit(ret)
|
2f1329ece2381138cb605b5ae4d74f878273ffd8 | EdwardHarriss/C-Compiler-and-C-to-Python-Translator | /Python_Translator/tmp/formative/f17-got.py | 263 | 3.5625 | 4 | def main():
xx = 0
y = 0
acc = 2
xx = 0
y = 0
while (xx < 6):
y = 0
while (y != xx):
acc = (acc + y)
y = (y + 1)
xx = (xx + 2)
return ((acc - xx) - y)
if __name__ == '__main__':
import sys
ret = main()
sys.exit(ret)
|
1aa27e717e986adbbc8253465e5aa2690a2c7c20 | Tomas-Balciunas/pythonExercises | /exercise/exercise3.py | 169 | 3.828125 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
enter = int(input("Enter a number: "))
for i in range(len(a)):
if a[i] < enter:
b.append(a[i])
print(b)
|
13afaad7a2d91740136cdbbb218d299072d87cf0 | Tomas-Balciunas/pythonExercises | /exercise/exercise11.py | 103 | 4.0625 | 4 | num = int(input())
if num % 2 == 0 or num % 3 == 0:
print("not a prime")
else:
print("prime")
|
55e419ca7d0f36d95e5a805f924a296ec5c0ecd2 | kim-dong-yeob/dataStructure | /shell_sort.py | 390 | 3.734375 | 4 | def shell_sort(data):
h = 4
while h >= 1:
for i in range(h, len(data)):
j = i
while j >= h and data[j] < data[j - h]:
data[j], data[j - h] = data[j - h], data[j]
j -= h
h //= 3
return data
if __name__=="__main__":
data = [9, 4, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.