blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
6c1f21f06a5ce2bbbe03ab9a7a468628673ee29b | senbagaraman04/pythonfordatascience | /listlab.py | 698 | 3.703125 | 4 | print ("\n\nAuthor: Senbagaraman")
print ("Lines printed with # are actual coding line, which will provide the desired result beneath it")
print ("*************************************")
L=["Michael Jackson" , 10.1,1982]
#print('the same element using negative and positive indexing:\n Postive:',L[0],'\n Negative:' , ... |
a66a874e71d7fcd94befa52b0f881864421b4419 | Ayush181005/Intermediate-and-Advance-Python | /lambda function.py | 285 | 3.625 | 4 | # Syntax - lambda argument : manipulate the argument, it is a single line function
# def add(a, b):
# return a+b
# print(add(4, 6))
add = lambda x,y : x+y
print(add(4, 6))
add = lambda x,y:x>y
print(add(4, 6))
a = [(1, 2), (4, 5), (555, 34)]
a.sort(key=lambda x:x[1])
print(a)
|
05b95c929104fdecd3dc1ec64d062c42445cbc25 | Huako7/ProgramacionEstructurada | /Unidad 2-Estructuras de Control/Ejercicio 41.py | 1,649 | 4 | 4 | <<<<<<< HEAD
#Ejercicio 41 -
#Autor: Jorge Limón
#Entrada: Cantidad de números por evaluarse y los números en sí
#Salida: El número mayor y el menor de los números dados
n = int(input("¿Cuántos Números va a usar?"))
#N números
for x in range (0, n):
numero = int(input("Ingrese un número:"))
#Se verifica cual... |
00103bb0d6182794e8b78ebfada6fe2884edfc7c | Huako7/ProgramacionEstructurada | /Unidad 2-Estructuras de Control/Ejercicio43.py | 1,194 | 3.78125 | 4 | #Ejercicio #43
# Programa que lea N valores y que cuente cuantos de ellos son positivos y cuantos
# son negativos (0 es condici'on de fin de lectura)
# Audny D. Correa Ceballos (Equipo 'about:blank')
#ENTRADAS:
#Cuantos valores va a ingresar
lengLista = int(input())
listaNumeros = []
#Asignar los numeros que... |
8c32515f31e32f713ae7dfc09e0234d1b89485da | J4Jeffort/Jeffort | /coffee_machine_data.py | 2,579 | 4.09375 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"c... |
d6e3afe057f97951d4f8499f2cc7d958e8861f2a | anobil/pytimecop | /timecop/__init__.py | 2,731 | 3.953125 | 4 | import time
import datetime
class fake_datetime(datetime.datetime):
"""Like datetime.datetime, but always defer to time.time()
These implementations of now and utcnow are lifted straight from
the standard library documentation, which states that they are
"equivalent" to these expressions, but may prov... |
cf21267f0f65593c910953cce92db9e08096d36b | jackandsnow/BasicProject | /data_struct/queue.py | 3,026 | 4.40625 | 4 | class Queue:
"""
Sequential Queue implement
"""
def __init__(self):
"""
initialize an empty Queue, __queue means it's a private member
"""
self.__queue = []
def first(self):
"""
get the first element of Queue
:return: if Queue is empty return... |
3d9bc6f7ede7eda2420a82ce6019f690b8605347 | clarasdfgh/Curso_python | /Condicionales/Evaluacion/pertenece.py | 193 | 4.1875 | 4 | #No modifiques esto para que podamos evaluarte
numero = int(input("Numero: "))
if numero > -3 and numero < 0 :
print("Pertenece")
elif numero >= 3 and numero < 6 :
print("Pertenece")
|
2f8a9df2c2a7df6b9b2e927750bad8d2a0fa9747 | mscandizzo/CorpFinBook | /FinanceApp/finratiosFull.py | 14,232 | 3.84375 | 4 | import pandas as pd
import numpy as np
class FinRatios(object):
"""
This class contains all the financial ratios which contain 2 input variables.
A dictionary (variables2V) has been created where each financial ratio (key)
has a tuple value with the input variables name as well as the formula to calcul... |
a865462f32bdc2ee0b4a3efe27c458cc1e308a93 | The-One-And-Only-H/TREP | /Alphabetgenerator.py | 905 | 3.71875 | 4 | #!/usr/bin/env python
# For every letter: write the body into body then for every letter: save the body
alphabet = list(map(chr, range(ord('a'), ord('z')+1))) # Not using import string string.ascii_lowercase as I want to be able to include/exclude letters manually
def main():
for c in alphabet:
# Rea... |
f3adfc660b4c7c83e8d45f08773195514518d413 | luxiya01/CodeU_Assignments | /assignment1/string_permutation.py | 608 | 4.03125 | 4 | import string
import collections
def string_permutation(str1, str2):
"""Checks whether str1 and str2 are permutations of
each other. Note that the function is case insensitive. """
if not ((str.isalpha(str1) or str1 == "")
and (str.isalpha(str2) or str2 == "")):
raise ValueError("The... |
9354234b81db69e37096e66c37f68b14acdbf142 | arkiz/py | /lab1-5.py | 713 | 3.8125 | 4 | year01 = input("Enter the number of 1st year")
wins01 = input("Enter the number of wins in 1st year")
year02 = input("Enter the number of 2nd year")
wins02 = input("Enter the number of wins in 2nd year")
year03 = input("Enter the number of 3rd year")
wins03 = input("Enter the number of wins in 3rd year")
year04 =... |
abdff8d3bf6c1e1cc39a24519587e5760294bdc6 | arkiz/py | /lab1-4.py | 413 | 4.125 | 4 | studentName = raw_input('Enter student name.')
creditsDegree = input('Enter credits required for degree.')
creditsTaken = input('Enter credits taken so far.')
degreeName = raw_input('Enter degree name.')
creditsLeft = (creditsDegree - creditsTaken)
print 'The student\'s name is', studentName, ' and the degree name... |
a0eb11daa6aa1f642541eea86601d0c4ebe29a6b | insoo67park/bigdata | /d2/word_count/.ipynb_checkpoints/reducer-checkpoint.py | 961 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
prev_word = None
counts = 0
# (keyword, count)하나의 pair가 입력 됨
# 같은 keyword가 묶여서 연속으로 입력 됨
# ex) (백신, 1) (백신, 1) (코로나, 1) (거리두기, 1)
for word_count in sys.stdin:
word, count = word_count.split("\\") # map에서 보낸 "key$value"를 $로 나눠서 저장
count = int(count) # s... |
79b163e645ae2030938f3accadcd502d2cb4610a | jocelyneterrazas/socialnetwork | /socialnetwork.py | 3,056 | 3.5 | 4 | ## Made by: Jocelyne Terrazas
## My Social Network
class User:
def __init__(self, username):
self.username = username
self.firstName = ""
self.lastName = ""
self.bio = ""
##self.userID = userID
self.friendsList = []
self.posts = []
self.... |
d85ea99814d0f990fcb8ec6261e604dd59180902 | kyeongeun25/Python | /py_02/p001/연산자.py | 1,610 | 4.0625 | 4 | # 연산자
# 4칙연산
num1 = 40
num2 = 3
print("덧셈 : "+str(num1+num2))
print("뺄셈 : "+str(num1-num2))
print("곱셈 : "+str(num1*num2))
print("나눗셈 : "+str(num1/num2))
print("나머지 : "+str(num1%num2))
# 특별한 산수 연산자
print("나버지 버림 : "+str(num1 // num2))
print("제곱 : " + str(num1 ** 3)) # VB, C#에서는 num1^3
print("num1 : " + str(num1))... |
12fc80e09e5d6cc61b33171d30102042784dc212 | vigitia/VIGITIA-Toolkit | /VIGITIA_toolkit/utility/get_ip.py | 664 | 3.5 | 4 | from urllib import request, error
# https://stackoverflow.com/questions/2311510/getting-a-machines-external-ip-address-with-python
def get_ip_address():
# try:
# # Try to get the public IP address of the computer
# ip = request.urlopen('https://ident.me').read().decode('utf8')
# except error.UR... |
1d4071a8dbcff5752d1941863e3d6a424a61b7f5 | KiD21606/HackerRank | /python/Regex_and_Parsing/Detect_Floating_Point_Number.py | 1,391 | 3.8125 | 4 | '''
constrains:
1. Consist of numbers, "+", "-", and ".".
2. Contain at most one of "+" and "-".
3. Have exactly one "." symbol, and must have a number after ".".
4. must contain at least 1 decimal value.
'''
for _ in range(int(input())):
dot = False
number = False
string = input()
if string[0] in '01... |
65a3751044e9098230c71112828444f1d317cb76 | KiD21606/HackerRank | /python/Sets/Check_Strict_Superset.py | 186 | 3.515625 | 4 | A = set(input().split())
result = True
for _ in range(int(input())):
B = set(input().split())
if B-A != set() or A-B == set():
result = False
break
print(result)
|
d5dcfba7aaa1057e45d45a3d009c6b50b730cb8d | KiD21606/HackerRank | /python/Regex_and_Parsing/Validating_Credit_Card_Numbers.py | 269 | 3.515625 | 4 | import re
def varify(s):
if not re.match(r'^[456]\d{3}(-?\d{4}){3}$',s):
return 'Invalid'
s = s.replace('-','')
if re.search(r'(\d)\1{3}',s):
return 'Invalid'
return 'Valid'
for _ in range(int(input())):
print(varify(input()))
|
9308608e093885d0aef426e5ff2ad834c349ee94 | KiD21606/HackerRank | /python/Date_and_Time/Calendar_Module.py | 240 | 4.09375 | 4 | import calendar
day_name = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']
date = input().split()
year = int(date[2])
month = int(date[0])
day = int(date[1])
print(day_name[calendar.weekday(year,month,day)])
|
a8d1170910fa9c49eefba50a19ae0a5483d5b9f2 | KiD21606/HackerRank | /python/Python_Functionals/Map_and_Lambda_Function.py | 394 | 4.09375 | 4 | cube = lambda x: x**3
def fibonacci(n):
if n==0:
return []
fib = [1]*n
fib[0] = 0
for i in range(3,n):
fib[i] = fib[i-1] + fib[i-2]
return fib
'''
def fibonacci(n):
fib = [0,1]
for i in range(2,n):
fib.append(fib[i-1]+fib[i-2])
return fib[0:n]
'''
if __name__ == ... |
0939885322d9a139e117d9ab92e7e008fe254a1f | KiD21606/HackerRank | /python/Strings/Text_Wrap.py | 353 | 3.75 | 4 | import textwrap
def wrap(string, n):
result = ''
k = len(string)//n
for i in range(k):
result += string[n*i:n*(i+1)]+'\n'
if len(string)%n != 0:
result += string[n*k:]+'\n'
return result
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(stri... |
2abbf5f56a47bd8041b38221e33de5aa16fe5dd9 | stoneriver/AtCoder-Python | /AtCoder Beginners Selection/ABC049C.py | 1,512 | 3.5625 | 4 | # ABC049C - 白昼夢
S = input()
while True:
if S[0:5] == "dream":
if S == "dream": # この単語がdream、次の単語は存在しない
S = ""
elif S == "dreamer": # この単語がdreamer、次の単語は存在しない
S = ""
elif S[5:8] == "dre": # この単語がdream、次の単語はdreamかdreamer
S = S[5:]
elif S... |
517f231a66c9d977bc5a34eaa92b6ad986a8e340 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-2-12-Python-loops-else-The-while-loop-and-the-else-branch.py | 356 | 4.15625 | 4 | #!/usr/bin/python3
"""
Both loops, while and for, have one interesting (and rarely used) feature.
As you may have suspected, loops may have the else branch too, like ifs.
The loop's else branch is always executed once,
regardless of whether the loop has entered its body or not.
"""
i = 1
while i < 5:
print(i)
... |
6920b44453655be0855b3977c12f2ed33bdb0bc3 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-4/4-1-3-10-LAB-Converting-fuel-consumption.py | 1,432 | 4.4375 | 4 | #!/usr/bin/python3
"""
A car's fuel consumption may be expressed in many different ways. For example,
in Europe, it is shown as the amount of fuel consumed per 100 kilometers.
In the USA, it is shown as the number of miles traveled by a car using one
gallon of fuel.
Your task is to write a pair of functions convertin... |
c9bedff4032b89fbd4054b4f03093af06a3d01d0 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-2/2-1-4-10-LAB-Operators-and-expressions.py | 567 | 4.5625 | 5 | #!/usr/bin/python3
"""
Take a look at the code in the editor: it reads a float value,
puts it into a variable named x, and prints the value of a variable named y.
Your task is to complete the code in order to evaluate the following
expression:
3x3 - 2x2 + 3x - 1
The result should be assigned to y.
"""
x = 0
x = floa... |
fd86bac9750e54714b1fe65d050d336dba9399ca | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-4/4-1-3-9-LAB-Prime-numbers-how-to-find-them.py | 1,302 | 4.28125 | 4 | #!/usr/bin/python3
"""
A natural number is prime if it is greater than 1 and has no divisors other
than 1 and itself.
Complicated? Not at all. For example, 8 isn't a prime number, as you can
divide it by 2 and 4 (we can't use divisors equal to 1 and 8, as the
definition prohibits this).
On the other hand, 7 is a prim... |
a68c0ddd6f458d58084dee9810c34072a1312f71 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-6-2-Operations-on-lists-slices-Powerful-slices.py | 459 | 3.796875 | 4 | #!/usr/bin/python3
"""
Powerful slices
Fortunately, the solution is at your fingertips - its name is the slice.
A slice is an element of Python syntax that allows you to make a brand new
copy of a list, or parts of a list.
It actually copies the list's contents, not the list's name
"""
# Copyng the whole list
list1 ... |
3e7b84ff790a508534c03cdc878f6abdf2e32a53 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-6-1-Operations-on-lists-The-inner-life-of-lists.py | 1,345 | 4.375 | 4 | #!/usr/bin/python3
"""
The inner life of lists
Now we want to show you one important, and very surprising, feature of lists,
which strongly distinguishes them from ordinary variables.
We want you to memorize it - it may affect your future programs, and cause
severe problems if forgotten or overlooked.
Take a look at... |
22d49020846e8a953364049ff95f348443100a81 | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-4-12-Lists-collections-of-data-lists-and-loops-Lists-in-action.py | 261 | 4.0625 | 4 | #!/usr/bin/python3
"""
Now you can easily swap the list's elements to reverse their order:
"""
myList = [10, 1, 8, 3, 5]
print(myList)
for i in range(len(myList) // 2):
myList[i], myList[len(myList)-1-i] = myList[len(myList)-1-i], myList[i]
print(myList)
|
946ec887e106dde979717832e603732ef85a750c | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-4/4-1-2-2-How-functions-communicate-with-their-environment-Parametrized-functions.py | 1,358 | 4.375 | 4 | #!/usr/bin/python3
"""
It's legal, and possible, to have a variable named the same as a function's
parameter.
The snippet illustrates the phenomenon:
def message(number):
print("Enter a number:", number)
number = 1234
message(1)
print(number)
A situation like this activates a mechanism called shadowing:
pa... |
b6732e8d49b943a0391fe3d6521bdf29d2f840ee | rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python | /Module-3/3-1-1-11-LAB-Comparison-operators-and-conditional-execution.py | 1,014 | 4.46875 | 4 | #!/usr/bin/python3
"""
Spathiphyllum, more commonly known as a peace lily or white sail plant,
is one of the most popular indoor houseplants that filters out harmful
toxins from the air. Some of the toxins that it neutralizes include benzene,
formaldehyde, and ammonia.
Imagine that your computer program loves these pl... |
7910f459e4fa3465fa210d3b7710c2d0269e55b7 | kingsman142/Projects | /Udacity/smartcab/smartcab/smartcab/agent.py | 5,486 | 3.625 | 4 | import random
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
class LearningAgent(Agent):
"""An agent that learns to drive in the smartcab world."""
def __init__(self, env):
super(LearningAgent, self).__init__(env) # sets self.env = env, sta... |
ad07c957de435974775396e4cc0b8a793ffe4141 | michellecby/learning_python | /week7/checklist.py | 788 | 4.1875 | 4 | #!/usr/bin/env python3
# Write a program that compares two files of names to find:
# Names unique to file 1
# Names unique to file 2
# Names shared in both files
import sys
import biotools
file1 = sys.argv[1]
file2 = sys.argv[2]
def mkdictionary(filename):
names = {}
with open(filename) as fp:
for name in fp.r... |
93bb7d0991282aae1b16a4524f9428c3a6077c0d | riferman/epam_5 | /laba 5-2 GUI.py | 1,835 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
import os
__author__ = "Sergey_Matusevich"
# The program searches for files in the specified directory.
# If the directory is not specified, the search is performed on
# D: er, and the size of the required files is set to 0. That is, all files.
d... |
0939070cf0430a2d3c79d94c04ef9d7886fcf46a | kai230/mPython | /examples/thread/thread_lock.py | 749 | 3.734375 | 4 | import _thread # 导入线程模块
import time # 导入时间模块
# 创建锁
lock=_thread.allocate_lock()
# 定义线程函数,打印线程编号和运行时间
def print_time( threadName, delay):
count = 0
# 获取锁
if lock.acquire():
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s sec" % ( threadName,... |
a0c765e6fbe2c954eb0d745c2e99301461e864ab | sveetch/video-registry | /tests/utils.py | 728 | 3.5625 | 4 | """
Test utilities
"""
from pyquery import PyQuery as pq
def html_pyquery(content):
"""
Shortand to use Pyquery parsing on given content.
This is more useful to dig in advanced HTML content. PyQuery is basically a
wrapper around ``lxml.etree`` it helps with a more intuitive API (alike
Jquery) to ... |
a26660f14b5e65ecb68877a5fcc233d160e16271 | sudobum/rectangle_triangle_info | /rectangle_info.py | 1,228 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 29 19:31:22 2018
@author: IBM-Watson
"""
#this program displays information
#about a rectangle drawn by the user.
from graphics import *
import math
def main():
win = GraphWin('Rectangle Information', 400 , 400)
win.setCoords(-10, -... |
69742bf185e0c29d592e1cddd36cf5a3789be8f6 | lanhel/pyietflib | /pyietflib/iso8601/__init__.py | 2,257 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""Package that will handle `ISO 8601:2004 Representation of dates and
times <http://www.iso.org/iso/catalogue_detail?csnumber=40874>`_ parsing
and formatting.
"""
__copyright__ = """Copyright 2011 Lance Finn Helsten (helsten@acm.org)"""
from .__meta__ import (__version__, ... |
ecf9b0bf9197c735047dda97d9c88734f16471af | profjrr/ev3 | /ev3/robot/lego.py | 1,588 | 3.609375 | 4 | """ The interface class providing the way to configure an EV3 lego robot.
The robot is represented by an instance of EV3Robot class.
This is meant to be derived from and passed to EV3RobotDriver instance.
"""
class EV3RobotConfigurator(object):
drive = None
touch_sensor = None
ir_sensor = None
... |
f6510f19dc43e3374f3dfb5cb25b1ef5d6c2f2fe | profjrr/ev3 | /ev3/motor/lego.py | 12,725 | 3.96875 | 4 | """Classes for original Lego Mindstorms EV3 motors."""
from ..rawdevice import lms2012
from ..rawdevice import motordevice
import collections
MAX_SPEED_VALUE = 127
"""Class for manipulating a single instance of a motor.
Motor must be one of ev3.MOTOR_* where * is A-D."""
class EV3Motor(object):
MOVE_NONE = -1
... |
74943adb8248eee39850823f5d5bfe973937f8ad | trendscenter/coinstac-dpsvm | /scripts/common_functions.py | 337 | 3.609375 | 4 | """Common functions used in COINSTAC scripts.
"""
import numpy as np
def list_recursive(d, key):
"""Yields the value corresponding to key in a dict d."""
for k, v in d.items():
if isinstance(v, dict):
for found in list_recursive(v, key):
yield found
if k == key:
... |
027e704ab7884402dbc4c4143f0dedde532d31ce | leetuckert10/CrashCourse | /chapter_4/exercise_4-8.py | 196 | 3.765625 | 4 | # Cubes
# Make a list of the cubes of numbers 1 - 10.
cubes = []
for value in range(1, 11):
# check out this syntax for suppressing a new line.
print(value**3, " ", end="")
print("\nfinished")
|
c0c560ee4e39d1bd412a5506b4d850da12715ca1 | leetuckert10/CrashCourse | /chapter_4/exercise_4-5.py | 341 | 3.90625 | 4 | # Summing a million numbers...
# using functions min(), max(), and sum()
one_million = []
for value in range(1, 1000001):
one_million.append(value)
print(f"Mininum value is {min(one_million)}")
print(f"Maximum value is {max(one_million)}")
print(f"The sum of adding one million numbers together is {sum(one_million)}!"... |
4418ca32623c1494633e5e78ab8d4ba716b93087 | leetuckert10/CrashCourse | /chapter_9/exercise_9-14.py | 421 | 3.6875 | 4 | # Exercise 9:14: Lottery
#
# Create a list or tuple contain 10 numbers and 5 letters. Using choice(),
# randomly select 4 values to generate a lottery ticket.
from random import choice
lottery_numbers = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
'c', 'd')
ticket = ""
for x in ran... |
2f8d761707c15cef64f9e8b49aae03c733959d00 | leetuckert10/CrashCourse | /chapter_9/exercise_9-6.py | 1,668 | 4.375 | 4 | # Exercise 9-6: Ice Cream Stand
# Write a class that inherits the Restaurant class. Add and an attribute
# called flavors that stores a list of ice cream flavors. Add a method that
# displays the flavors. Call the class IceCreamStand.
from restaurant import Restaurant
class IceCreamStand(Restaurant):
def __ini... |
df70e46cceaa083c3a0545af8eb83463295b0b40 | leetuckert10/CrashCourse | /chapter_11/test_cities.py | 1,339 | 4.3125 | 4 | # Exercise 11-1: City, Country
#
# Create a file called test_city.py that tests the function you just wrote.
# Write a method called test_city_country() in the class you create for testing
# the function. Make sure it passes the test.
#
# Remember to import unittest and the function you are testing. Remember that
# the... |
b678820b88d80d9ab8c120a620e441f75d457d4c | leetuckert10/CrashCourse | /chapter_9/user.py | 3,202 | 4.125 | 4 | """A set of clases that can be used to represent users, specialized users and
privileges."""
class User:
"""The User class is a simple attempt to model a computer user."""
def __init__(self, user_id, first_name, last_name,
address_1=None,
address_2=None,
city=None,
... |
b2df32b33c07286f9bf610a570903dbd6538ddf1 | leetuckert10/CrashCourse | /DataVisualization/chapter_15/exercise_15-1.py | 836 | 4.03125 | 4 | # Exercise 15-1: Plot the first five cubic numbers and then plot the first
# 5000 cubic numbers.
import matplotlib.pyplot as plt # type: ignore
from typing import List
upper_bound: int = 5001
input_values: range = range(1, upper_bound)
cubes: List[int] = [x**3 for x in range(1, upper_bound)]
# Set the plot s... |
82779034d745269ff23f4effee830c70eae6b9b5 | leetuckert10/CrashCourse | /chapter_4/exercise_4-9.py | 269 | 3.84375 | 4 | # Cube Comprehension
# Make a list of the first 10 cubes using list comprehension.
cubes = [value**3 for value in range(1, 11)] # list comprehension
for value in cubes:
# check out this syntax for suppressing a new line.
print(value, " ", end="")
print("\nfinished") |
4b396840502cab41a8b3e75eb0e28250954546da | leetuckert10/CrashCourse | /chapter_10/exercise_10-9.py | 439 | 3.796875 | 4 | # Exercise 10-9: Silent Cats and Dogs
#
# Modify the except block in Exercise 10-8 to fail silently if either file is
# missing.
cats_file = 'cats.txt'
dogs_file = 'dogs.txt'
try:
with open(cats_file) as cats:
contents = cats.read()
except FileNotFoundError:
pass
else:
print(contents)
try:
wi... |
2114dd90d264f1ea5f77ea0f8444eb15957dd978 | leetuckert10/CrashCourse | /chapter_9/exercise_9-5.py | 775 | 3.640625 | 4 | # Exercise 9-5: Login Attempts
# This program uses the User class in user.py. Added the attribute
# login_attempts and a method for increment by one. Also added a method to
# rest to zero.
from user import User
#import user as u
u1 = User("leetuckert", "terry", "tucker")
u1.address_2 = "1690 Macedonia Church Rd."
u... |
f4f669c12f07d0320e5d9a01fec7542e249d4962 | leetuckert10/CrashCourse | /chapter_4/exercise_4-10.py | 539 | 4.5625 | 5 | # Slices
# Use list splicing to print various parts of a list.
cubes = [value**3 for value in range(1, 11)] # list comprehension
print("The entire list:")
for value in cubes:
# check out this syntax for suppressing a new line.
print(value, " ", end="")
print('\n')
# display first 3 items
print(f"The first three item... |
86b4f7e1bfe9621bd3eff200a94e0cb2cfac364c | leetuckert10/CrashCourse | /chapter_6/exercise_6-10.py | 851 | 4.03125 | 4 | # Favorite Numbers Modified
# Store the favorite number of five people in a dictionary using their
# name as the key. In this version we have added a list of numbers.
favorite_nums = {
'terry': [18, 21, 41, 60],
'carLee': [12, 16, 21, 25],
'linda': [16, 12, 44],
'rebekah': [21],
'nathan': [42, 25, ... |
1897ec6770bca8f6e0dc72abbcdcd70644e6f182 | leetuckert10/CrashCourse | /chapter_8/exercise_8-14.py | 764 | 4.3125 | 4 | # Exercise 8-13: Cars
# Define a function that creates a list of key-value pairs for all the
# arbitrary arguments. The syntax **user_info tell Python to create a
# dictionary out of the arbitrary parameters.
def make_car(manufacturer, model, **car):
""" Make a car using a couple positional parameters and and a... |
997df0520551de4bfb67665932840b09fa1a6d5a | leetuckert10/CrashCourse | /chapter_6/exercise_6-9.py | 1,229 | 4.21875 | 4 | # Favorite Places:
# Make a dictionary of favorite places with the persons name as the kep.
# Create a list as one of the items in the dictionary that contains one or
# more favorite places.
favorite_places = {
'terry': ['wild cat rock', 'mount mitchell', 'grandfather mountain'],
'carlee': ['blue ridge parkway... |
ab6b62451de82d2c52b1b994cfabab7893c4f64e | leetuckert10/CrashCourse | /chapter_8/exercise_8-3.py | 541 | 4.125 | 4 | # Exercise 8-3: T-Shirt
# Write a function called make_shirt() that accepts a size and a string for
# the text to be printed on the shirt. Call the function twice: once with
# positional arguments and once with keyword arguments.
def make_shirt(text, size):
print(f"Making a {size.title()} T-Shirt with the text ... |
6a514ad94f999c1840fbffd3ea153bf8a1b22e47 | leetuckert10/CrashCourse | /chapter_9/exercise_9-9.py | 3,738 | 4.46875 | 4 | # Exercise 9-9: Battery Upgrade
# Using the example in the text defining a Car class and a Battery class,
# create a new method that upgrades the battery from 75kWh to 100kWh.
class Car:
"""A simple attempt to model a car."""
def __init__(self, make, model, year):
self.make = make
self.model ... |
7dd4f0340dbcb616851c1872561e7c5b30ce5137 | jcorb/bookstore_dashboard | /app/main.py | 5,916 | 3.578125 | 4 |
import pandas as pd
import numpy as np
from bokeh.models import ColumnDataSource, HoverTool, Range1d, Div
from bokeh.plotting import figure, curdoc
from bokeh.layouts import column, row, widgetbox
from bokeh.models.widgets import Select, Slider
import os
"""
This code uses Bokeh and Pandas to display the top sellers... |
928d97a0023a0a64773fb1df4c1e59bc20f01123 | algorithms-21-devs/Interview_problems | /weekly_interview_questions/IQ_4/Q4_emmanuelcodev/Q4Medium_N.py | 1,840 | 4.25 | 4 | import node as n
'''
Time complexity: O(n)
Algorithm iterates through link list once only. It adds memory location as a key to a dictionary. As it iterates it checks if the
current node memory matches any in the dictionary in O(1) time. If it does a cycle must be present.
'''
def cycle(head_node):
#must be a linke... |
7248c2bc7108c4eff0f07f3171dab62000651988 | algorithms-21-devs/Interview_problems | /weekly_interview_questions/IQ_5/Q5_maguil53/Q5Medium_O(logn).py | 640 | 4.03125 | 4 | # Time Complexity: O(n)
def reverseIntArray(int_list):
if int_list is None:
raise Exception("Can't enter None")
length = len(int_list)
if length == 0:
return None
half = length // 2
for i in range(half):
temp = int_list[i]
# Swap element on left with one on the ri... |
4374c169c241a96ef6fc26f74a3c514f4cc216ed | algorithms-21-devs/Interview_problems | /weekly_interview_questions/IQ_2/Q2_Emmanuelcodev/Q2Medium_Nsquared.py | 2,634 | 4.1875 | 4 |
def unique_pairs(int_list, target_sum):
#check for None
'''
Time complexity: O(n^2).
1) This is because I have a nested for loop. I search through int_list,
and for each element in int_list I search through int_list again.
N for the outer and n^2 with the inner.
2) The... |
3c7b9f0575cd89c95c1eb4a91b6655ae84c31221 | ZaxR/100-people-in-a-circle-with-gun-puzzle | /100-people-in-a-circle-with-gun-puzzle.py | 990 | 3.5625 | 4 | """
http://quiz.geeksforgeeks.org/puzzle-100-people-in-a-circle-with-gun-puzzle/:
100 people standing in a circle in an order 1 to 100.
No. 1 has a gun.
He kills the next person (i.e. No. 2) and gives the gun to the next (i.e. No. 3).
All people do the same until only 1 survives. Which number survives at the last?
The... |
21b935d316daacdd26b6ee02b1bcf5d4b449e462 | serafdev/codewars | /merged_string_checker/code.py | 440 | 4.125 | 4 | def is_merge(s, part1, part2):
return merge(s, part1, part2) or merge(s, part2, part1)
def merge(s, part1, part2):
if (s == '' and part1 == '' and part2 == ''):
return True
elif (s != '' and part1 != '' and s[0] == part1[0]):
return is_merge(s[1:], part1[1:], part2)
elif (s != '... |
0e8601398a0c45de5e781febbc2b4f9f2d174321 | mis813/Power_system_analysis | /line_data_2_matrix.py | 2,366 | 3.5 | 4 | import pandas as pd
from pandas.io.parsers import read_csv
def line2list(data):
##this function convert row in Data to list
#Data Type is Dictionary
l = len(data['From_Bus'])
line = []
header = ['From_Bus','To_Bus','R','X','G','B','Max_Mvar','Y/2']
for i in range(1,l+1):
... |
a9052948120ec2afb1d52d3c104abd526418e92a | fantenuc/SI-206-Project-1 | /206project1.py | 5,350 | 3.59375 | 4 | import os
import filecmp
def getData(file):
#Input: file name
#Ouput: return a list of dictionary objects where
#the keys will come from the first row in the data.
#Note: The column headings will not change from the
#test cases below, but the the data itself will
#change (contents and size) in the different test
#cas... |
84ce96ecca9c72d6442f5eafe1afc7ace3dc1ba3 | deepu14d/ScriptAllTheThings | /StrongPasswordGenerator/password_generator.py | 604 | 3.8125 | 4 | """
Strong Password Generator
- Generates a secure random password
Author: Skyascii (https://github.com/savioxavier)
Date : 1/10/2021
"""
import secrets
import string
def generate_password(length=12):
"""Generates a random password
Args:
length (int, optional): Length of the generated password. ... |
8aab690e36890037d72ae050a1b967dd6afd6d86 | cnrooofx/CS2516 | /lab1/merge_sort.py | 844 | 3.78125 | 4 | from random import randint
def merge_sort(mylist):
n = len(mylist)
if n > 1:
list1 = mylist[:n//2]
list2 = mylist[n//2:]
merge_sort(list1)
merge_sort(list2)
merge(list1, list2, mylist)
def merge(list1, list2, mylist):
f1 = 0
f2 = 0
while f1 + f2 < len(mylis... |
f453f370b0e4fae667198c49361ad84564fb10fe | kathyz08/RoadTrppn | /app/gmaps_util.py | 4,164 | 3.625 | 4 | import googlemaps
import time
import json
# https://stackoverflow.com/questions/15380712/how-to-decode-polylines-from-google-maps-direction-api-in-php
def decode_polyline(polyline_str):
index, lat, lng = 0, 0, 0
coordinates = []
changes = {'latitude': 0, 'longitude': 0}
# Coordinates have variable len... |
12f8122c6fe4bca4c5d777534bbe4d87c63318d2 | judyliou/LeetCode | /python/1108. Defanging an IP Address.py | 442 | 3.53125 | 4 | def defangIPaddr(self, address):
defanged = ''
for i in address:
if i == '.':
defanged += '[.]'
else:
defanged += i
return defanged
def defangIPaddr(self, address):
return address.replace('.', '[.]')
def defangIPad... |
3e0c28d7e45a59c4911da3272e0fc85f1a9ee2f9 | judyliou/LeetCode | /python/169. Majority Element.py | 965 | 3.875 | 4 | # Solution 1: Count with dict
# Time Complexity: O(n), Space Complexity: O(n)
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = {}
for i in nums:
cnt[i] = cnt.get(i, 0) + 1
for k, v in cnt.items():
if v > len(nums) // 2:
return k
... |
7e8f873e5aa3d44ba662c4a88c28e254ba6cd1db | CTEC-121-Spring-2020/mod-2-programming-assignment-gromo2 | /Template.py | 3,276 | 4.09375 | 4 | """
CTEC 121
<Garrett>
<Mod 2 Programming Assignment>
<assignment/lab description
"""
""" IPO template
Input(s): list/description
Process: description of what function does
Output: return value and description
"""
from math import *
import math
def main():
#Assignment Statements
print()
exampleString... |
fc748f366fdae31f941ca0779b96d3a962955388 | Aloi-6/Sudoku | /a.py | 976 | 3.78125 | 4 | rows = 'ABCDEFGHI'
cols = '123456789'
def cross(A, B):
"Cross product of elements in A and elements in B."
return [i+j for i in A for j in B]
boxes = cross(rows, cols)
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC','DEF','G... |
8c586b54b079fbed0cacdd9daaec909738fe1696 | zzclynn/Swiss-Tournament-Result | /tournament.py | 4,023 | 3.671875 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the d... |
586fb03d59826b643f5aa85b73c33d838c298356 | abhising10p14/Image_processing_face_detection | /Faces/face_recognization_dlib_faces.py | 3,959 | 3.5 | 4 | import sys
import dlib
import numpy as np
import cv2 # importing opencv which is c++ library for image processing
from skimage import io # skimage is a python library for image processing
'''The histogram of oriented gradients (HOG) is a feature descriptor used in computer vision and image processing for the purpos... |
a7f39ebcb80933999133e7c52279c3dbb335a8d4 | dema501/adventofcode | /task1.py | 2,123 | 3.515625 | 4 | def calcDirection(d, s):
if d == "N" and s == "L":
return "W", "x-"
if d == "N" and s == "R":
return "E", "x+"
if d == "E" and s == "L":
return "N", "y+"
if d == "E" and s == "R":
return "S", "y-"
if d == "S" and s == "L":
return "E", "x+"
if d == "S" an... |
3f83e36343b8191b3e0bca5d61e4fc003e33ab8d | 10258392511/SI507_Final_Project | /sites_scraper.py | 4,037 | 3.6875 | 4 | # This file implements the scraper
import bs4
import requests
import re
from bs4 import BeautifulSoup
from pprint import pprint
from utilities import *
def scrape_main_page(cache_filename):
"""
Scrapes the main page for detailed pages' urls.
Parameters
----------
cache_filename: str
Cache... |
5a2cd1098175ff8bc25c43dc628c7cd737f61dca | sgouda0412/AlgoExpert_Solutions | /Hard/Hard_DynamicProgramming.py | 8,515 | 3.5 | 4 | # 1 Longest Common Subsequence
# first T: O(nm * min(n,m)) S: O(nm * min(n,m))
def longestCommonSubsequence(str1, str2):
if len(str1) == 0 or len(str2) == 0:
return []
arr = [[ [] for x in range(len(str1) + 1)]
for y in range(len(str2) + 1)]
for up in range(1, len(str2) + 1):
for down in range(1... |
c050f0759aaa4cac06b57a04ca3288c9b41642e6 | sgouda0412/AlgoExpert_Solutions | /Very_Hard/Very_Hard_BST.py | 2,691 | 3.734375 | 4 | # 1 Right Smaller Than
# two optimal solutions with T: O(n*log(n)) S: O(n)
# n - numbers smaller at insertion
# l - left subtree
# n | n l | n l | n l | n l | n l | n l
# 0 1 1 1 1 0 0 0 4 2 4 0 5 0
# 2 4 3 -1 11 5 8
# `left subtree` will be added to values
# (`.numsSmallerAtInsert`) that ... |
7a4cecca76070805c157212d87003ecf4cb36028 | sgouda0412/AlgoExpert_Solutions | /Medium/Medium_Graphs.py | 10,948 | 4 | 4 | # 1 Breadth-first search
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
def breadthFirstSearch(self, arr):
curr = self
queue = [curr]
explored = {}
explore... |
9200bb98fc0fbbf27b9202490d8dcdf3fda66a92 | sgouda0412/AlgoExpert_Solutions | /Medium/Medium_BST.py | 6,638 | 3.6875 | 4 | # 1 BST traversal
def inOrderTraverse(tree, arr):
def traverse(tree):
if tree.left:
traverse(tree.left)
arr.append(tree.value)
if tree.right:
traverse(tree.right)
traverse(tree)
return arr
def preOrderTraverse(tree, arr):
def traverse(tree):
arr.append(tree.value)
if tree.left:
traverse(t... |
dd67e60748c0c229a7ddc44539f3975938c8198b | sgouda0412/AlgoExpert_Solutions | /Medium/Medium_recursion.py | 2,892 | 3.640625 | 4 | # 1 Permutations
def getPermutations(arr):
perms = []
helper(0, arr, perms)
return perms
def helper(idx, arr, perms):
if idx == len(arr) - 1:
perms.append(arr[:])
else:
for x in range(idx, len(arr)):
swap(x, idx, arr)
helper(idx + 1, arr, perms)
swap(x, idx, arr)
def swap(idx1, idx2, arr):
arr[idx1... |
8f5f902a00bec0a2f5490cada18911936bcacf34 | Art-And/python_basics | /through_the_letters.py | 261 | 4 | 4 | def run():
# name = input("Please write your name: ")
# for letter in name:
# print(letter)
sentence = input("Please write a sentence: ")
for caracter in sentence:
print(caracter.upper())
if __name__ == '__main__':
run() |
429dc963f813e2e84c30923d0740ccc0b0036c4f | Art-And/python_basics | /conversor_inverso.py | 195 | 3.625 | 4 | dolar = input('Introduce tus dolares: ')
dolar = float(dolar)
valor_peso = 20
pesos = dolar * valor_peso
pesos = round(pesos, 2)
pesos = str(pesos)
print('Tienes $' + pesos + ' pesos mexicanos') |
4b9debc3b6e466c1ae1e86b42fde816e4a3b143e | jkim2791/UC-berkeley-CS88 | /proj/wheel/game.py | 1,181 | 4.0625 | 4 | from secret import SecretWord
from board import Board
class Game:
"""Run an entire game.
Initialization defines the player who pickers secret word and one or more guessers.
play
- picker picks the secret word from the dictionary held by all players
- guessers guess in turn looking at the sta... |
f587e8614825a2d013715057bf7cffc0ed0cf287 | Earazahc/exam2 | /derekeaton_exam2_p2.py | 1,032 | 4.25 | 4 | #!/usr/bin/env python3
"""
Python Exam Problem 5
A program that reads in two files and prints out
all words that are common to both in sorted order
"""
from __future__ import print_function
def fileset(filename):
"""
Takes the name of a file and opens it.
Read all words and add them to a set.
Args:
... |
9b646e8de6eccecff554062ff607dc63b96b003a | ramteja64/python_project | /word_game.py | 3,233 | 4.15625 | 4 | """
File: word_guess.py
-------------------
Fill in this comment.
"""
import random
LEXICON_FILE = "Lexicon.txt" # File to read word list from
INITIAL_GUESSES = 8 # Initial number of guesses player starts with
def play_game(secret_word):
"""
Add your code (remember to delete the "pass" belo... |
cbe25e58a699661cba8668b0295a9c7a848e9bb3 | chivemind/pythonbiblehomework | /loops101project2.py | 864 | 3.96875 | 4 | # Get sentence from user
original = input("Write a sentence to code! ").strip().lower()
#split sentence into words
words = original.split()
#loop through words and convert into pig latin
new_words = []
#if word starts with a vowel, add "yay"
for word in words:
if word[0] in "aeiou":
new_word = word +"yay... |
2374e05debdb31353c46e9bddca773a02232e7a4 | soyoungboy/pythonStudy | /four.py | 4,633 | 3.53125 | 4 | # #!/usr/bin/python
# # -*- coding: UTF-8 -*-
# # Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
# flag = False
# name = 'luren'
# if name == 'python': # 判断变量否为'python'
# flag = True # 条件成立时设置标志为真
# print 'welcome boss' # 并输出欢迎信息
# else:
# print name # 条件不成立时输出变量名称
# # !/usr/bin/python
# # -*- coding... |
45454a5eb68caf4713f2b0ed2aab7d8b4d3c1166 | quioxe/Trieur-Etre-Vivants | /category.py | 1,832 | 3.65625 | 4 | from sqlite3.dbapi2 import Cursor
import database
class Category:
def __init__(self, name, parent_category=None, id=None) -> None:
self.name = name
self.parent_category = parent_category
def __init__(self, id) -> None:
cursor = database.get_cursor()
cursor.execute("SELECT * FRO... |
2afdcc56807edf7ac7debe13d55eb4d7f45c645b | danieta/thunderboard | /Desktop/Algdat2/oving2.py | 1,337 | 3.828125 | 4 | #!/usr/bin/python3
from sys import stdin
from itertools import repeat
def merge(decks):
# SKRIV DIN KODE HER
mittOrd = ""
while(len(decks) != 0 ):
minsteVerdi = decks[0][0][0]
minsteVerdiIndex = 0 #i vårt tilfelle kan minsteVerdiIndex være 0,1,2,3 eller 4.
for i in range(0,len(d... |
e5a93d3de2bf9f58e15f5f9a48f359f5c1a45b70 | a13z/nd256_project3 | /problem_7.py | 6,522 | 3.921875 | 4 | # A RouteTrie will store our routes and their associated handlers
class RouteTrie:
def __init__(self, handler):
# Initialize the trie with an root node and a handler, this is the root path or home page node
self.root = RouteTrieNode(handler)
def insert(self, path, handler):
"""
... |
92572db3c9acc30301d0580bcc8355ec8a4c3c40 | AdamSierzan/Python_basics_course_2 | /Lesson_1/1.3 Formatting_the_strings_p2.py | 591 | 4.03125 | 4 | #python 2 formatting
waluta = "dolar"
us = 1
pln = 4.08234915
print("Aktualnie %r %r kosztuje %.2r zł" % (us, waluta, pln))
waluta = "dolar"
us = 1
pln = 4.08234915
print("Aktualnie %d %s kosztuje %.2f zł" % (us, waluta, pln))
# in old python version, while formating for:
# strings we use: %s
# floats: %f
# int: %d... |
58c3f5d0d23fe52ad7cbdaafcd0f7d10ea86c7e7 | yogeshvaral/PythonWithFlask | /OppsConceptDemo.py | 1,542 | 3.953125 | 4 | class Computer:
def __init__(self, model, ram):
self.model = model
self.ram = ram
def config(self):
print("i5,16gb,1TB")
print("Model and ram is", self.model, self.ram)
comp1 = Computer("AMD", 16)
comp2 = Computer("i5", 24)
comp1.config()
comp2.config()
class Person:
d... |
d3315235bd4fb593a671393c20f9783ed6e4c62b | yogeshvaral/PythonWithFlask | /PolymorphismDuckTyping.py | 578 | 3.53125 | 4 | class Pycharm:
def execute(self):
print("compiling")
print("Running")
class Eclipse:
def execute(self):
print("Checking")
print("verifying")
print("compiling")
print("running")
class Laptop:
def code(self,ide):
ide.execute()
ide = Pycharm()
ide1... |
b452707e33da8a102d2b964ba93261f4c7003108 | MaVericKWareZ/automation | /lesson1.py | 2,002 | 3.703125 | 4 | from datetime import datetime as dt
players = {}
def get_age_diff(duration_in_s):
days = divmod(duration_in_s, 86400)
hours = divmod(days[1], 3600)
minutes = divmod(hours[1], 60)
seconds = divmod(minutes[1], 1)
return [days,hours,minutes,seconds]
def get_dob_obj(dob_... |
3cffeebd9a0b35519af78d0325f7b58f55334252 | mdu74/python_greeting_kata | /test_greeting.py | 2,815 | 3.625 | 4 | import unittest
from greeting import Greeting
class TestGreeting(unittest.TestCase):
def test_Greeter_GivenSingleName_ShouldGreetSingleName(self):
singleNames = ["Bob","Mary","Tom"]
for eachName in singleNames:
# Arrange
name = eachName
# Act
result =... |
b2c24fe1f3d4f3474b70461b608a2c14e9d44e9b | viralsir/python_saket | /if_demo.py | 1,045 | 4.15625 | 4 | '''
control structure if
syntax :
if condition :
statement
else :
statement
relational operator
operator symbol
greater than >
less than <
equal to ==
not equal to !=
gr... |
0bdb3507ea776a6b421a6e8dfda6c3e47f2c38bd | viralsir/python_saket | /def_demo3.py | 354 | 4.1875 | 4 | def prime(no):
is_prime=True
for i in range(2,no):
if no % i == 0 :
is_prime=False
return is_prime
def factorial(no):
fact=1
for i in range(1,no+1):
fact=fact*i
return fact
# no=int(input("enter No:"))
#
# if prime(no):
# print(no," is a prime no")
# else :
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.