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 |
|---|---|---|---|---|---|---|
8f3001cb6ea5b492b87303711c31c0f0e64a9eae | wykzhang/mais-202-coding-challenge | /script.py | 1,377 | 3.8125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
#Use split apply combine
#Read the csv file using panda
df = pd.read_csv("data.csv")
#Take only the two columns that interest us, purpose and interest rate
temp = df[['purpose', 'int_rate']]
#Group them by purpose into another dataframe, take the average inter... |
2ee4b555fc2c4ba68086ade0f02116d956274ed3 | gzy0718/vip10test | /继承.py | 2,871 | 3.65625 | 4 | #
# # 单继承
# class shifu():
# def __init__(self):
# self.peifang="五香味配方"
# def jishu(self):
# print(f"通过{self.peifang}制作煎饼果子")
#
# #多继承
# class school():
# def __init__(self):
# self.peifang="香辣味煎饼果子配方"
# def jishu(self):
# print(f"通过{self.peifang}制作煎饼果子")
#
# class tudi(s... |
149d489a17aebd2d34273c582f0318797a992d83 | rawda95/CITC-Task | /Task/exam/create_exam.py | 2,029 | 3.625 | 4 | import random
def init(question_num, difficulty, objective, chapters):
chapters_num = len(chapters)
difficulty_ber_chapter = [i // chapters_num for i in difficulty]
objective_ber_chapter = [i // chapters_num for i in objective]
print(difficulty_ber_chapter)
print(objective_ber_chapter)
def diffc... |
b8158e3f4451cb4c1866cfe0853be94e4ba7c8f8 | bluenote10/SimpleLanguageBenchmarks | /bench_suite/benchmarks/fibonacci.py | 2,296 | 3.578125 | 4 | #!/usr/bin/env python
from __future__ import division, print_function
import textwrap
from ..base import Sizes, default_runtime_extractor
class Fibonacci(object):
title = "Fibonacci"
description = textwrap.dedent("""\
Compute the N-th Fibonacci using three different, popular implementations:
- *... |
ef025e26dc65d046c6fc2594037f787bab37c2be | phizaz/chula_rl | /chula_rl/alphazero/santorini/players.py | 972 | 3.53125 | 4 | import numpy as np
class RandomPlayer:
"""a random player for the game of santorini"""
def __init__(self, game):
self.game = game
def play(self, board):
a = np.random.randint(self.game.getActionSize())
valids = self.game.getValidMoves(board, 1)
while valids[a] != 1:
... |
b2772608ccf9cfbad2352e949acb0b081db10e46 | aandr26/Learning_Python | /Coursera/Week5/Week5a/Exercises/mouse_echo.py | 581 | 3.921875 | 4 | # Echo mouse click in console
###################################################
# Student should enter code below
import simplegui
def click(pos):
print(str(pos[0]), (str(pos[1])))
frame = simplegui.create_frame("Mouse Echo", 200, 200)
frame.set_mouseclick_handler(click)
frame.start()
########################... |
56bfcf0cd7d2ffcca129085aa597ec7d19ca1b22 | aandr26/Learning_Python | /Coursera/Week3/Week3b/Projects/format.py | 1,239 | 4.21875 | 4 | # Testing template for format function in "Stopwatch - The game"
###################################################
# Student should add code for the format function here
def format(t):
''' A = minutes, B = tens of seconds, C = seconds > tens of seconds
D = remaining tens of seconds.
A:BC:D
'''... |
5e2a8b44e6b0a76fb9ba56768453d4f931b999ea | aandr26/Learning_Python | /Coursera/Week1/Week1a/Exercises/rectangle_area.py | 195 | 3.859375 | 4 | # Calculate the area of a rectangle
def rectangle_area(width,height):
area = width * height
return area
print(rectangle_area(4,7))
print(rectangle_area(7,4))
print(rectangle_area(10,10)) |
17d94e1629032102c39f52aef0f951114b792cda | aandr26/Learning_Python | /Coursera/Week1/Week1b/Exercises/is_lunchtime.py | 200 | 3.9375 | 4 | def is_lunchtime(hour,is_am):
""" Takes the perameter 'hour' and checks if it is am or pm
to determine if it is lunch time"""
return (hour == 11 and is_am) or (hour == 12 and not is_am)
|
80d3ea990b71c1175cf424f6e06d60def5338779 | aandr26/Learning_Python | /Coursera/Week1/Week1a/Exercises/point_distance.py | 331 | 3.6875 | 4 | import math
# Calculate the distance between two points
# taking four parameters and using the math.sqrt module
def point_distance(x0,y0,x1,y1):
total_distance = math.sqrt((x0 - x1)**2 + (y0 - y1)**2)
print (total_distance)
return total_distance
point_distance(2,2,5,6)
point_distance(1,1,2,2)
point_distan... |
20b6edc6c257810f00377bc18c4fb0c4d5fe7d3a | aandr26/Learning_Python | /Coursera/Week3/Week3b/Exercises/expanding_cricle.py | 865 | 4.125 | 4 | # Expanding circle by timer
###################################################
# Student should add code where relevant to the following.
import simplegui
WIDTH = 200
HEIGHT = 200
radius = 1
# Timer handler
def tick():
global radius
global WIDTH
radius += 2
# Draw handler
def draw(canvas):
... |
1b1fc9b0c11d3b2f5fa65d9a45942316ea81620d | brk9009/superchargedPython | /chapter2/search.py | 569 | 3.859375 | 4 | frank_str = 'doo be doo be doo...'
n = frank_str.count('doo')
print(n)
# Starts at the 2nd char and counts # of 'doo'
print(frank_str.count('doo', 1))
# Starts at the 2nd char and goes to 9th position
print(frank_str.count('doo', 1, 10))
# Uses find to find where all 'doo' starts at.
frank_str = 'doo be doo be doo..... |
c4dd7f3bd254ba563996f95569b17b9f890987c6 | aytida23/Machine-Learning-Training | /2 - Regression/3 - Polynomial Regression/Regression Template for Non Linear Model/regression_template.py | 2,200 | 3.625 | 4 | """
Here in this regression template we get to know how to make a regression template for fitting all
other non linear regression models. It will help efficiently to make some regression models for our
truth or bluff problem with the position, and salary.
"""
# Regression Template
# Importing the libraries
import nu... |
37d5b5db138850f50282f8bd6ab410284d02c14b | ophiolite/python_practice | /morse_code.py | 1,050 | 3.890625 | 4 | def morse_converter(string):
'''Takes in string of morse code and return number based on
morse coding.
1 .---- 2 ..--- 3 ...-- 4 ....- 5 ..... 6 -.... 7 --... 8 ---.. 9 ----. 0 -----'''
n = 5
number_lst = []
morse_lst = [string[i:i+n] for i in range(0, len(string), n)]
for each in morse_lst:... |
1a3ddac44205b6b06167a319e711e1126748a2ae | Nick3366/deeptest | /第一期/北京-Windy/sample8.py | 650 | 3.875 | 4 | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
#
# class Sample8:
# '''实现x*y乘法表'''
#
# def __init__(self,cow,col):
# self.cow = cow
# self.col = col
#
# def mu(self):
# # self.col, self.cow=int(input())
# for self.cow in range(self.col,self.cow):
# print
# ... |
123de54c6eb2e151d1a3a5429b1ecfaaeaa3a0c6 | abbottn/IntelliJDemo | /crypto/helpers.py | 874 | 3.90625 | 4 | def alphabet_position(letter):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
letter = letter.lower()
return alphabet.index(letter)
def rotate_character(char, rot):
alphabet = ... |
0d1853ecb06a11c99dd74d4e399a6c872dcc1662 | walirt/Python-Design-Patterns | /行为型模式/strategy.py | 1,714 | 3.703125 | 4 | '''
策略模式 通常用在我们希望对同一个问题透明地使用多种方案时
如果并不存在针对所有情况的完美算法,那么我们可以使用策略模式,动态地决定在每种情况下应使用哪种算法
'''
import time
SLOW = 3 # 单位妙 减缓算法速度
LIMIT = 5 #字符数
WARING = 'too bad, you picked the slow algorithm :('
def pairs(seq):
n = len(seq)
for i in range(n):
yield (seq[i], seq[(i+1)%n]) if i != n-1 else (seq[i], None)
d... |
7ad56e11503763f4d3ad3e6b7fce6d03b0cf9f56 | rlworkgroup/garage | /src/garage/tf/models/parameter.py | 3,651 | 4.125 | 4 | """Parameter layer in TensorFlow."""
import tensorflow as tf
def parameter(input_var,
length,
initializer=tf.zeros_initializer(),
dtype=tf.float32,
trainable=True,
name='parameter'):
"""Parameter layer.
Used as layer that could be broadca... |
200aa19f6b9bae3b6249d3514c8c555c12b5b377 | rlworkgroup/garage | /src/garage/torch/value_functions/gaussian_mlp_value_function.py | 4,301 | 3.546875 | 4 | """A value function based on a GaussianMLP model."""
import torch
from torch import nn
from garage.torch.modules import GaussianMLPModule
from garage.torch.value_functions.value_function import ValueFunction
class GaussianMLPValueFunction(ValueFunction):
"""Gaussian MLP Value Function with Model.
It fits th... |
d84c8aee96348eba57778c389ce9a91ce1ab07ec | rlworkgroup/garage | /src/garage/torch/modules/cnn_module.py | 10,685 | 3.59375 | 4 | """CNN Module."""
import warnings
import akro
import numpy as np
import torch
from torch import nn
from garage import InOutSpec
from garage.torch import (expand_var, NonLinearity, output_height_2d,
output_width_2d)
# pytorch v1.6 issue, see https://github.com/pytorch/pytorch/issues/42305
#... |
1da99068500ac43445324a856ac14ff1f7e1c626 | rebel47/PythonInOneVideoByCodeWithHarry | /chapter2solutions.py | 886 | 4.28125 | 4 | # To add two numbers
# a = int(input("Enter the first number: \n"))
# b = int(input("Enter the second number: \n"))
# print("Sum of first and second number is:",a+b)
# To find the remainder
# a = int(input("Enter the number whose remainder you want to know: \n"))
# print("The reaminder of the given number is:", a%2)
... |
a608c36a28981eb16358dfb74e1414d1b028aacb | rebel47/PythonInOneVideoByCodeWithHarry | /chapter3solutions.py | 829 | 4.40625 | 4 | # # Print user name with Good afternoon message
# name = input("Enter your name:\n")
# print("Good afternoon", name)
# #Print the given name by adding user name
# name = input("Enter the Candidate Name:\n")
# date = input("Enter the Date:\n")
# letter = '''Dear <|NAME|>,
# You are selected!!
# Date: <|DATE|>'''
# le... |
1fbda9e7546a8299483c8c1ec55ba5d80113cd7c | thelondonsimon/citelearn | /modelserver/app/citationdetector.py | 2,068 | 3.515625 | 4 | """
A series of regular expressions which attempt to detect (APA style) in-text citations within sentences
"""
import re
def detectCitation(text: str) -> str:
if type(text) != str:
raise TypeError('citationdetector.detectCitation(text) expects text as str')
detected = False
# author/year, e.g.:
... |
b5d60b4bccfe4a3d02147a229d3927d6592af1da | JBCar1/HI2 | /Handin_Exercises/HI1_DiscretePathPlanning/python/misc.py | 951 | 3.875 | 4 | """Miscellaneous helper functions."""
import time
import math
class Timer:
"""Simple timer."""
t0 = 0.0
def tic(self):
"""Start timer."""
self.t0 = time.time()
def toc(self):
"""Stop timer."""
return time.time() - self.t0
def latlong_distance(p1, p2):
"""Comput... |
deff3aabfe16a8466420450b0231cf81bc06192c | sauravbarua02/Saurav-IDLE | /work212.py | 857 | 3.765625 | 4 | #Program Import data from Excel and plot in python used IDLE Python 3.7
#-import excel raw data to pandas data frame using pandas module
#-split columns
#- matplotlib module for scatter plot
#Before running the program in python shell, it is required to install pandas, xlrd and matplotlib module in Anaconda prompt.... |
f2c8c7200c4b936bca437502c8193d425d8622f8 | talaaz/Program-for-grading-students | /plot.py | 2,309 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 18:40:56 2019
@author: tala1
"""
import numpy as np # Import NumPy
import matplotlib.pyplot as plt # Import the matplotlib.pyplot module
def dataPlot(data):
#define the differnet types of bactaries
SalmonellaEnterica = data[data[:,2]==1]
Ba... |
078f0b6bf22a2af914b69d9e4b86959433f93015 | rohaneden10/luminar_programs | /functions/sumofnnos.py | 133 | 3.8125 | 4 | def nnumbers():
num=int(input("enter a range"))
sum=0
for i in range(0,num+1):
sum+=i
print(sum)
nnumbers()
|
96e382a8dfc19d24ff9c143eef09679fd3a93d21 | rohaneden10/luminar_programs | /regular expressions/quantifiers/q2.py | 233 | 3.875 | 4 | import re
x="a*"#count including where a and where theree is no a ie considers all position and prints all postioons
r="asfdsfsdfdsfds"
matcher=re.finditer(x,r)
for match in matcher:
print(match.start())
print(match.group()) |
bc5d56ec90d672d2585b3cf5eddf8d4c2f312738 | rohaneden10/luminar_programs | /COLLECTIONS/DICTIONARY/wordcount program.py | 299 | 3.875 | 4 | line="hai ,,,,,,hello hai hai hello hai hello hai hai hai man"
#split function is used to split line by line data to word by word data
print(line)
words=line.split((" "))
print(words)
#dic={}
#for i in words:
# if((i in dic)==False):
# dic[i]=1
# else:
# dic[i]+=1
#print(dic)
|
ba7f8e96bd44225214eb70e6e87ad81cb8c7d1a3 | rohaneden10/luminar_programs | /flow controls/decision/project1.py | 154 | 3.609375 | 4 | a=int(input("enter salary"))
b=int(input("enter years of service"))
c=5
if(b>=5):
c=.05*a
print("increment is ",c)
else:
print("no increment") |
180b8b9095a312b156733430bd2b204feea3cbf1 | rohaneden10/luminar_programs | /flow controls/looping/even_betwwen_lower_and_upper.py | 132 | 3.84375 | 4 | ul=int(input("enterthe upperlimi"))
ll=int(input("enterthe lowerlimit"))
while(ll<=ul):
if(ll%2==0):
print(ll)
ll+=1 |
eaa2d985b1037f28e57b6b7aef250f0c1fdd5476 | rohaneden10/luminar_programs | /functions/calculator.py | 434 | 3.953125 | 4 | def calculator():
print("1:add")
print("2:sub")
print("3:mul")
print("4:div")
a=int(input("enter 1st no"))
b=int(input("enter 2nd no"))
c=int(input("enter the choice"))
if(c==1):
print("addition",a+b)
elif(c==2):
print("difference",a-b)
elif(c==3):
print("... |
8740406b37ea56951ac4057fa5f69c3322fc4d24 | Cynamal/Python-algorithm-excercise | /SumPrimeNumbers/sum_prime_numbers.py | 765 | 4.03125 | 4 | # Task
# https://github.com/daftcode/python_levelup_2018/blob/master/zadania_rekrutacyjne/Zadanie_2/Zadanie_2_polecenie.md
def find_prime_number():
primes = {}
number = 2
while True:
if number not in primes:
yield number
primes[number*number] = [number]
else:
... |
b1d6343aa49e50aa7a3f102877edcb5577a40d4c | irem-kolen/GlobalAIHubPythonHomework | /HW-2.py | 369 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
while True :
a=input("first name:")
b=input("last name:")
c=int(input("age:"))
d=int(input("date of birth:"))
if c < 18 :
print("You can't go out because it's too dangerous")
elif c > 18 :
print("You can go out t... |
7093e951b025f223d38660093d10358a8a94fa6a | elDavidGarcia/CSUSM_CS436 | /WebServer.py | 1,788 | 3.53125 | 4 | #Echo server program
import socket
import sys
HOST = ''
PORT = 6666
#Create the socket
server_Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket was created.'
#Bind the socket
try:
server_Socket.bind((HOST, PORT))
except socket.error, msg:
print 'Falied to bind. \nError Code: ' + str(m... |
cd2c6edb6c48bccb6f2cd244c6bb30e4bd188237 | PeppyHare/fenicsbook | /ch2/demo_poisson.py | 7,874 | 4.34375 | 4 | #!/usr/bin/env python
r'''
Introduction to the finite element variational method!
The "hello world" of the finite element methods for PDEs is the Poisson equation, which consists of the following boundary value problem:
.. math::
- \nabla ^2 u(x) = f(x) : \quad x \text{ in } \Omega \\
u(x) = u_D(x) : \quad ... |
592fb804fff60c2a59106fcfd4d9a3b2783ba93e | Bmartinm1/holbertonschool-higher_level_programming | /0x00-python-hello_world/3-last_digit.py | 378 | 3.921875 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
n = number
if n < 0:
n *= -1
n = n % 10
if number < 0:
n *= -1
if (n > 5):
print("Last digit of", number, "is", n, "and is greater than 5")
elif (n == 0):
print("Last digit of", number, "is", n, "and is 0")
else:
print("Last di... |
52deb61b876f65ec65d06c4285f7e34db66ccdec | arushss/Python_Task | /Task01.py | 2,516 | 4.5 | 4 | # Create three variables in a single line and assign different values to them and make sure their data types are different.
# Like one is int, another one is float and the last one is a string.
x, y, z = 10, 20.5, "Consultadd"
print ("x is: ", x)
print ("y is: ", y)
print ("z is: ", z)
# Create a variable of value ty... |
ae74bbac5907cac877b61e90c45cd714553b1bae | damarisgch/Funciones | /dospalabras.py | 557 | 3.984375 | 4 | # Escriba un programa que pida al usuario dos palabras y que indique cuál de ellas es la más larga y por cuántas lo es.
palabra1 = input('Ingresa una palabra:')
palabra2 = input('Ingresa otra palabra:')
conteo1 = len(palabra1)
conteo2 = len(palabra2)
diferencia = abs(conteo1 - conteo2)
if conteo1 > conteo2:
print(... |
d993dcf0a72d7cbd9b43fb0e2543f3f46ebd89f8 | Guirdin/PythonB1 | /TrianglesDivers.py | 7,084 | 3.59375 | 4 | import tkinter
from tkinter import *
def T_D():
# ------------------------------------------------PROGRAMME PRINCIPAL---------------------------------------------------
# Création et paramétrage de l'espace déssin et de l'interface Tkinter
TD = Tk()
Dessin = Canvas(TD, width=625, height=600, bg='whit... |
e3e6007db1a89060f7122b8a61eab3d973ddbcff | George-Spanos/HashcodePractice | /entities/team.py | 792 | 3.78125 | 4 | class Team:
def __init__(self, members):
self.members = members
self.pizzas = []
self.delivered = False
def append_pizza(self, pizza):
if not self.delivered:
self.pizzas.append(pizza)
if len(self.pizzas) == self.members:
self.delivered = T... |
1d3c9a4e39caa8f6e6f238793d028e9abb45fdb7 | annaleoprok/fourlessonpi | /3_2.py | 487 | 3.65625 | 4 | def month_to_season(month):
season_ranges = {
(12, 1, 2): 'Winter',
(3, 4, 5): 'Spring',
(6, 7, 8): 'Summer',
(9, 10, 11): 'Autumn'
}
season = None
for key, value in season_ranges.items():
if month in key:
season = value
break
return... |
6d0c6b74424066c6c18ebe6ce21cc1abc7ebc707 | The-Ineffable-Alias/ProgrammingDigitalHumanitiesBook | /Ch7 - Dirty Hands 1/Code/7.2_searchingaterm.py | 289 | 3.640625 | 4 | # Overcommented for explanatory reasons
# Load the library that handles connecting to the internet
import requests
# Ask the user for a search term
query = input('What do you want to search?')
# Performing the search
searchres = requests.get('https://www.google.com/search?q='+ query)
|
2c813b65155ed9b55d366f21655ed2c6a930dec8 | The-Ineffable-Alias/ProgrammingDigitalHumanitiesBook | /Ch7 - Dirty Hands 1/Code/7.4_makingthesoup.py | 570 | 3.765625 | 4 | # Overcommented for explanatory reasons
# Load the library that handles connecting to the internet
import requests
from bs4 import BeautifulSoup as bs
# Ask the user for a the search term
query = input('What do you want to search?')
# Performing the search
searchres = requests.get('https://www.google.com/search?q='... |
d7911e0c90ce7e74a00be432556860772454b08f | sam123sonu/opencv_beginner | /helloworld/num_draw.py | 517 | 3.578125 | 4 | import numpy as np
import cv2
img=np.zeros((600,600,3),np.uint8) #here we are creating screen(black array )using numpy library
print(img)
img=cv2.line(img,(0,0),(200,200),(0,255,0),6)
img=cv2.arrowedLine(img,(0,200),(200,200),(255,0,0),8)
img=cv2.rectangle(img,(510,0),(300,200),(0,0,255),10)
img=cv2.circle(img,(405,1... |
c3587953bd8b317479f5b73e5fe59ded39bf9da8 | Mamo123-git/Library-Management-System | /Library_system.py | 1,125 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 15:23:29 2020
@author: Rajesh_Raj
"""
import Membership
import Book_Database
import Borrow
def main():
done=False
while done==False:
print(""" ======LIBRARY MENU=======
1. Membership
2. Maintain ... |
871b714dd09397b92298f6fa67d0d102d391ed50 | BoLindJensen/Reminder | /Python_Code/Snippets/Iterations/Generator_Function/generator_function_using_yield.py | 716 | 3.953125 | 4 | '''
Generator functions have at lease one yeild in then, they are used when Lazy evaluation is needed.
Eg sensors, very large data sets, etc
'''
names = []
def read_file(): # Normal function using custom generator function.
try:
f = open("names.txt" , "r")
# instead of using the build in generator .... |
2f60538072b1e817495b6a4df3036e4a06c72713 | BoLindJensen/Reminder | /Python_Code/Snippets/Files/MoreFiles/Open.py | 1,513 | 4.125 | 4 | '''
The function open() opens a file.
file: path to file (required)
mode: read/write/append, binary/text
encoding: text encoding eg. utf-8. It is a good idea to always specify this, as you never know what other file systems use as their default
Modes:
'r' Read
'w' Write
'x' eXclusive creation, fails if the file alre... |
ec4d7456fbfaa7bef8bbe1244174b7c984ffd999 | BoLindJensen/Reminder | /Python_Code/Snippets/Lists/List_Comprehension.py | 225 | 4.59375 | 5 |
# https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
# L3 returns all elements of L1 not in L2.
L1 = [1,2,6,8]
L2 = [2,3,5,8]
L3 = [x for x in L1 if x not in L2]
print(L3) #L3 will contain [1, 6].
|
4fd37c497514a2352aeb9c39d1784b2fc46773bb | BoLindJensen/Reminder | /Python_Code/Snippets/__Name__/foo.py | 480 | 3.5 | 4 | '''
Start this script to see bar.py being imported, and the function(s) within bar.py being executed.
Then see this main() being executed.
'''
import bar
def main():
print(__name__)
if __name__ == '__main__':
main()
print("foo.py is running as __main__ and called: ", __name__)
# --- Dead Code Star... |
570d466855d3abeb761c3bb07e1f53628b2df264 | BoLindJensen/Reminder | /Python_Code/Snippets/Lists/List_Comprehension2.py | 950 | 4.34375 | 4 | '''
Python Comprehension works on list[], set{}, dictionaries{key:value}
List Comprehension style is Declarative and Functional
it is readable, expressive, and effective.
[ expr(item) for item in items ]
[ expr(item) for item in iterable ]
[ expr(item) for item in iterable if predicate(item) ]
'''
words = "What is ... |
ec6b1f4863dd6a0f4fecd1f42a3abdc2f6225ff9 | pigwejq/python | /Zadanie3zajecia2.py | 1,059 | 3.90625 | 4 | #Utwórz grę, w której komputer wybiera losowo słowo, które gracz musi
#odgadnąć. Komputer informuje gracza, ile liter znajduje się w wybranym
#słowie. Następnie gracz otrzymuje pięć szans na zadanie pytania, czy jakaś litera
#jest zawarta w tym słowie. Komputer może odpowiedzieć tylko „tak” lub „nie”.
#Potem gracz musi... |
39e08683651d6f6c4bf7c47530cd590b9a51e37f | dianaparr/holberton-system_engineering-devops | /0x16-api_advanced/1-top_ten.py | 689 | 3.609375 | 4 | #!/usr/bin/python3
""" Module called 1-top_ten """
import requests
def top_ten(subreddit):
""" This function queries the Reddit API and and prints the titles of
the first 10 hot posts listed for a given subreddit.
"""
# Identify the API version with the user Agent request header
HEADERS = {'U... |
2d4fc7fc2e100e47d1d893484dd343ef909b6a2b | 8faces/CSE | /notes/brad yang- guess game.py | 435 | 4.03125 | 4 | import random
guesses = 5
random_number = random.randint(0, 10)
playing = True
while guesses > 0 and playing:
guess = input("Guess a number from 0-10")
if int(guess) == int(random_number):
print("You Win!")
playing = False
else:
print("Try again")
guesses -= 1
if int(gue... |
007edd32013a137d5e4f46f40ffef5dfe6d7984d | jimwaldo/allstonTransport | /build_transition_d.py | 1,450 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Friday, Jan 4 2019
@author waldo
Using a dictionary of student schedules, builds a dictionary that allows calculation of the transitions from Cambridge
to Allston and back for each student. The key to the dictionary is the student HUID; the value is a tran... |
580f0b4e622feee15f5350770ad40fc01030ca26 | jimwaldo/allstonTransport | /build_no_lunch_d.py | 3,063 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sunday, March 17 2019
@author chong
Using a dictionary of student schedules, counts how many students do not have at least 30 minutes for lunch
between 11am and 2pm.
"""
import make_name_dicts as md
import class_time as ct
import sys
def build_no_lunch_d... |
eecdaae374ec74fcde7b48eb4670760f709b63ca | macbeth-byui/FamilyFavorites_Postgresql | /family_favorites.py | 8,340 | 4.25 | 4 | import psycopg2
"""
This program uses postgre sql to manage a list of favorite family meals. To use this program, you
need to do the following:
1) Install Postgre SQL. When you install, you will prompted for a password. You will need this
password when you run the SQL Shell and when you the code below.
2) Install... |
41ea7082612295670eb1d01e401f9205fdaa192a | fzchriha/felician-summercode | /python/semi-week2/benaventes_coffeemachine.py | 3,986 | 4.09375 | 4 | import sys #import sys module for exit
#updated coffeemachine code
class CoffeeMachine:
def __init__(self, water, milk, beans, cups, money):
self.water = water
self.milk = milk
self.beans = beans
self.cups = cups
self.money = money
def main(self): #main functio... |
75f9c292acae8fa96ab751efff72bcff35467ace | aphexer/sewer | /sewer/dns_providers/common.py | 4,091 | 3.65625 | 4 | from hashlib import sha256
from sewer.auth import BaseAuthProvider
from sewer.lib import safe_base64
def dns_challenge(key_auth: str) -> str:
"return safe-base64 of hash of key_auth; used for dns response"
return safe_base64(sha256(key_auth.encode("utf8")).digest())
class BaseDns(BaseAuthProvider):
de... |
cbf441034155917915332a6323df036be5b2f1da | mdmasrurhossain/Learning_Python_Zulu | /quiz_1/Q5.py | 567 | 4.375 | 4 | ### Q5: Write a list of of all the datatypes in pythons
myList = [16, 'Icecream', [4, "hello"], (5, 10), {'age': 3}]
print(myList)
print("Number Datatype: ", myList[0])
print("String Datatype: ", myList[1])
print("List Datatype: ", myList[2])
print("Tuple Datatype: ", myList[3])
print("Dictionary Datatype: ... |
5b9344089f074aba5f284612f8235fd2457b107a | inoray/python_study | /01.pythonBasic/20170312_01_gugu.py | 979 | 3.65625 | 4 | """
print("- 구구단")
def gugu(n):
for i in range(10):
print("%d x %d = %d" % (n, i, (n*i)))
print("출력하고자 하는 단을 입력하세요: ")
nn = input()
gugu(int(nn))
"""
print("- 1000 미만의 자연수에서 3의 배수와 5의 배수의 총합을 구하라")
def getBeasu(r, n):
result = []
for i in r:
if divmod(i, n)[1] == 0:
result.a... |
ef5e6b5fdb0665b7cc99f5b3a054a47a5fe15df2 | asymmetry/leetcode | /0065_valid_number/solution_1.py | 1,472 | 3.71875 | 4 | #!/usr/bin/env python3
# deterministic finite automaton
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
signs = {'+', '-'}
s = s.strip()
dfa = []
dfa.ap... |
53542f02f361110dbeeb4a6564d8a414861b1a6b | asymmetry/leetcode | /0198_house_robber/solution_1.py | 693 | 3.546875 | 4 | #!/usr/bin/env python3
# dynamic programming
class Solution:
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
l_n = len(nums)
if l_n == 1:
return nums[0]
if l_n == 2:
retur... |
e3e0f9d2f3ba129fcfa091a158ecd079f1a2e1fb | asymmetry/leetcode | /0201_bitwise_and_of_numbers_range/solution_1.py | 471 | 3.546875 | 4 | #!/usr/bin/env python3
class Solution:
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
diff = n - m
power = 0
while diff > 0:
diff = diff // 2
power += 1
mask = 2147483647 - (2**power ... |
2c2cabbe6a63b0baed5489d874009dba549eae78 | asymmetry/leetcode | /0154_find_minimum_in_rotated_sorted_array_2/solution_1.py | 417 | 3.890625 | 4 | #!/usr/bin/env python3
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return None
min_ = float('inf')
for num in nums:
min_ = min(num, min_)
return min_
if __name__ == '__... |
f184ec8532346eedc0cad01893789c4b9b92e332 | asymmetry/leetcode | /0079_word_search/solution_1.py | 1,577 | 3.640625 | 4 | #!/usr/bin/env python3
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
move = [(1, 0), (0, 1), (-1, 0), (0, -1)]
lr = len(board)
lc = len(board[0])
test_list = []
fo... |
f890c3fe7507b8f88a96bf84ddad34a60886fd4d | asymmetry/leetcode | /0009_palindrome_number/solution_1.py | 608 | 3.9375 | 4 | #!/usr/bin/env python3
# O(log(x)/2)
# revert half of the number
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x == 0:
return True
if x < 0 or x % 10 == 0:
return False
r = 0
while x > r:... |
1b788079e22bfb89917b77e69a52b9660975b60e | asymmetry/leetcode | /0074_search_a_2d_matrix/solution_1.py | 1,160 | 3.84375 | 4 | #!/usr/bin/env python3
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
start, end = 0, len(matrix)
while start < ... |
f1b4e42fe69eab54f9c2019d6bec7ef185f61174 | asymmetry/leetcode | /C094/0874_walking_robot_simulation/solution_1.py | 1,156 | 3.71875 | 4 | #!/usr/bin/env python3
class Solution:
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
obstacles_set = set(map(tuple, obstacles))
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
... |
0ac82ef9e462bcd249752369fe9e4b0ccfce6bc7 | asymmetry/leetcode | /0143_reorder_list/solution_1.py | 1,553 | 4.09375 | 4 | #!/usr/bin/env python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
p = self
result = f'{p.val}'
while p.next is not None:
p = p.next
result += f' -> {p.val}'
... |
9d52671325bddf9066bff4f60bbf65072a0a0faf | asymmetry/leetcode | /0078_subsets/solution_1.py | 637 | 3.734375 | 4 | #!/usr/bin/env python3
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = [[]]
for i in range(1, len(nums) + 1):
result += self._subsets(nums, i)
return result
def _subsets(self, nums,... |
fb40c06e74fd249e870651e9ae25d9b453daf9cf | asymmetry/leetcode | /0046_permutations/solution_2.py | 362 | 3.953125 | 4 | #!/usr/bin/env python3
# itertools has permutation and combination generators
import itertools
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
return list(map(list, itertools.permutations(nums)))
if __name__ == '__main__':... |
99fd2010f4e05f9f7070080256d4ae052cfa899a | asymmetry/leetcode | /0146_lru_cache/solution_1.py | 1,755 | 3.65625 | 4 | #!/usr/bin/env python3
# O(n)
# did not pass leetcode test
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.store = []
def get(self, key):
"""
:type key: int
:rtype: int
"""
... |
b2e60b633063a5f4be0e5883f348f5ea256f12d0 | asymmetry/leetcode | /0045_jump_game_2/solution_2.py | 602 | 3.5625 | 4 | #!/usr/bin/env python3
# O(n)
# greedy algorithm
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
result = 0
max_pos = 0
last_max_pos = 0
for index, num in enumerate(nums[:-1]):
if index <= max_pos:
... |
6b68fcd5e6a18c87680c41a066448b0de0a6ac6c | asymmetry/leetcode | /0015_3sum/solution_1.py | 994 | 3.640625 | 4 | #!/usr/bin/env python3
# O(n^2)
# did not pass leetcode test
import timeit
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
len_nums = len(nums)
nums = sorted(nums)
results = {}
table = {}
... |
d19e1c5c17ef493129829ab0e62623c03b4ab8f1 | asymmetry/leetcode | /0054_spiral_matrix/solution_1.py | 1,267 | 3.625 | 4 | #!/usr/bin/env python3
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
len_row = len(matrix)
if len_row == 0:
return result
len_col = len(matrix[0])
row, col... |
0f2ef133179dee5ccfb7aa49fa552cf35277356a | asymmetry/leetcode | /0047_permutations_2/solution_1.py | 877 | 3.609375 | 4 | #!/usr/bin/env python3
import collections
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
counter = collections.Counter(nums)
return self._permuteUnique([[key, val] for key, val in sorted(counter.items())])
... |
748e76a47e1cce749276b1090f99341180e4d4f4 | asymmetry/leetcode | /C116/0961_n_repeated_element_in_size_2n_array/solution_1.py | 330 | 3.78125 | 4 | #!/usr/bin/env python3
from collections import Counter
class Solution:
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
count = Counter(A)
return count.most_common(1)[0][0]
if __name__ == '__main__':
print(Solution().repeatedNTimes([1, 2... |
d7b94c572417695c5125f6ffdcf03c325c620f1f | asymmetry/leetcode | /0048_rotate_image/solution_1.py | 824 | 3.671875 | 4 | #!/usr/bin/env python3
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
size = len(matrix)
for i in range(size // 2):
for j in range(i, size - 1 - i):
... |
4843867d49d91191d10436c76c4da0e0c98a293d | asymmetry/leetcode | /0013_roman_to_integer/solution_1.py | 809 | 3.6875 | 4 | #!/usr/bin/env python3
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman_int_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
len_s = len(s)
last_digit = 0
result = 0
for i in range(le... |
aebbd08d16337f924611cfff5b5257a1b3383d7b | asymmetry/leetcode | /0086_partition_list/solution_1.py | 1,225 | 4.0625 | 4 | #!/usr/bin/env python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
p = self
result = f'{p.val}'
while p.next is not None:
p = p.next
result += f' -> {p.val}'
... |
1de12ccbc4d8ac63b055b737498b7c63bc897cfb | asymmetry/leetcode | /0071_simplify_path/solution_1.py | 678 | 3.984375 | 4 | #!/usr/bin/env python3
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
paths = path.split('/')
result = []
for d in paths:
if d in ('', '.'):
continue
if d == '..':
... |
26ba72512011320507145f37103f49309e99a624 | asymmetry/leetcode | /0084_largest_rectangle_in_histogram/solution_1.py | 942 | 3.875 | 4 | #!/usr/bin/env python3
class Solution:
def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
if not heights:
return 0
l_heights = len(heights)
stack = []
result = 0
i = 0
while i < l_he... |
ddd0dd594654d7006376736e74edc5bd11023479 | asymmetry/leetcode | /0096_unique_binary_search_trees/solution_2.py | 337 | 4 | 4 | #!/usr/bin/env python3
# mathematical solution
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
C = 1
for i in range(0, n):
C = C * 2 * (2 * i + 1) / (i + 2)
return int(C)
if __name__ == '__main__':
print(Solutio... |
2e99f1e771f4205e6e1458a25348b0df48d97e1b | asymmetry/leetcode | /0031_next_permutation/solution_1.py | 957 | 3.71875 | 4 | #!/usr/bin/env python3
#O(n)
class Solution:
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
len_nums = len(nums)
if len_nums == 0:
return
p = len_nums - 1
... |
f19f89c4272fa363af6bb8efc77ce4e1cfa4abf9 | asymmetry/leetcode | /0136_single_number/solution_1.py | 476 | 3.625 | 4 | #!/usr/bin/env python3
from collections import Counter
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = Counter()
for num in nums:
count[num] += 1
for num in count:
if count[num] == 1... |
3d42ce38903344786ee068a898e5e34ed4cca022 | asymmetry/leetcode | /0066_plus_one/solution_1.py | 646 | 3.625 | 4 | #!/usr/bin/env python3
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = []
carry = 0
for index, digit in enumerate(reversed(digits)):
pone = digit + carry + 1 if index == 0 else digit + carry... |
d37f8302b43f700b4528d129613b6b7f04ce6469 | gauravk268/FullStack_Django_Practice-Templates | /Python/codeBreaker.py | 1,050 | 3.859375 | 4 | import random
def generateRandom():
digits = [str(num) for num in range(10)]
random.shuffle(digits)
solution = digits[:3]
print(solution)
return solution
def getUserGuess():
userValue = input("What's your guess: ")
return userValue
def checkUserGuess(userGuess, gameCode):
... |
dd428f0b5d9ab2b2a47a7882f75840f9d0dfcfde | jeyaprakash1/List_String_programs | /list_test.py | 889 | 4.375 | 4 | # append function to add element
l=[10,20,30,10]
l2=l.index(30)
print(l2)
# insert function to insert a element
l1=['a','b','c']
l1.insert(3,'d')
print(l1)
# Extend one list to another list
s1=["one","two","three"]
print(len(s1))
s2=[4,5]
s1.extend(s2)
print(s1)
print(len(s1))
# Remove function to remove particul... |
9b165148c23b4eb100d71ffa8df7d214f37184e5 | hongphuc218/HelloWorld | /Python/session 7/Bài tập/7.py | 158 | 3.625 | 4 | favorite = ['LOL', 'sport', 'BTS', 'Game']
print(favorite)
newfav = input("new favorite")
favorite.append(newfav)
print(favorite)
print(*favorite, sep=' | ' ) |
9e3a4f7d5912d94e0467aa081425ea0ca962e7d9 | hongphuc218/HelloWorld | /Python/Session 5/randomwether.py | 142 | 3.578125 | 4 | from random import *
n = (randint(0,100))
if n < 30:
print("Rainy")
elif 30 <= n < 60:
print("Cloudy")
elif 60 < n:
print("Sunny") |
a1e0dc1fea7d6179c2aa86fc123e1ad46fefd7ff | hongphuc218/HelloWorld | /Python/Session 11/16.py | 238 | 3.640625 | 4 | computer = {
'HP':20,
'DELL':50,
'MACBOOK':12,
'ASUS':30,
}
computer['FUJITSU']=15
computer['ALIENWARE']=5
export = input('computer name ?')
num = int(input('Number of computers'))
i = computer[export]-num
print(i)
print(computer) |
cf59069769eb01b678927aeca4265c2a1a665689 | hongphuc218/HelloWorld | /Python/session 7/for_list.py | 181 | 3.8125 | 4 | items = ['com', 'pho', 'chao', 'com rang']
l = len(items)
for i in range(l):
print(items[i])
for item in items:
print(item)
for i, item1 in enumerate(items):
print(i, item) |
bc498a66fa05c34730c082b54870643570f6b767 | hongphuc218/HelloWorld | /Python/Session 12/1c.py | 117 | 3.921875 | 4 | print('x * '*9)
for i in range(10):
if i%2 == 0:
print('x',end=' ')
else:
print('*',end=' ')
|
6155865871fde90ef2d03e77bdd3a9cc79a0dbb8 | TheNarcissisticArsonist/3322_LED_Matrix | /convertPictureToCode.py | 1,596 | 3.640625 | 4 | #!/usr/bin/python
"""
This program converts an image into a C string that can be read by Picture_To_Matrix.ino
Command line arguments:
python convertPictureToCode.py ARG1 ARG2
Where ARG1 is the filepath to the picture, and ARG2 is the name of the variable for the array you get.
Just copy and paste the output into yo... |
82bd9da85d32a3a0e34251a60bb51084814245fa | naurissilkans/RTR105 | /dialogs.py | 451 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
a=input("Cien. liet., lūdzu, ievadi skaitli: ")
# 3. python vide visi input rezultāti ir ar str datu tipu
# tāpec ievadītā lieluma datu tips vēlāk ir jāparveido
a = int(a)
# python valoda balstās uz C valodas => print strādā līdzīgi printf
#http://www.cplus.com/reference/cstd... |
85bc1ca7494d06b84012c6984b1831c24d449b14 | lukeschwenke/CSCI-141 | /GoFunction.py | 1,355 | 3.609375 | 4 | #Question 1
def perfect(n):
total=0
for x in range(1, n):
if(n%x == 0):
total = total + x
if (total == n):
return True
else:
return False
n = int(input('Please enter a number '))
print (perfect(n))
#__________________________________________________________________________________
#Questio... |
3964d8e3c1bdbfa73f72e0782b9dbf840ebbc628 | 3vk/ud120-projects | /datasets_questions/explore_enron_data.py | 1,175 | 3.5 | 4 | #!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... |
d31d9c60357120583f0fb35784016b5d561aef81 | sgttwld/tensorflow-2-simple-examples | /1b_gradientdescent_gradient.py | 831 | 4.15625 | 4 | """
Example of gradient descent to find the minimum of a function using tensorflow 2.1
with explicit gradient calculation that allows further processing
Author: Sebastian Gottwald
Project: https://github.com/sgttwld/tensorflow-2.0-simple-examples
"""
import tensorflow as tf
import numpy as np
import os
os.environ['TF... |
7d29c578f58fe3c64a8ffb7c7c5ea9a8c6dd26ae | JiYou/LaGouAlgo | /02.Queue/01.2.TreeLevelOrder.py | 1,312 | 3.875 | 4 | # 本题的测试平台链接:
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.