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 |
|---|---|---|---|---|---|---|
d69969bf670cfc2cb1bc53a91de8e5af6254d981 | davvid/skeletor | /skeletor/db/decorators.py | 5,571 | 3.5625 | 4 | """Decorators to simplify database access
skeletor database decorators makes it easy to provide access to a common
schema or other database resource. These are referred to as contexts.
Contexts manage a sqlalchemy session and provide it to their decorated
functions through their `context` keyword argument.
Contexts... |
21ac16945548caf5c51dea80b1f117c305abe198 | JerrySmithLu/Disaster-Responses-Analysis | /data/process_data.py | 3,050 | 3.734375 | 4 | #prepare dataset from csv file
import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
"""
#load messages and categories dataset and then merge them into on dataframe by column”id”
messages_filepath: it's messages dataset file path
... |
c2aecac1241c301730a4180b798032aa822b4bd5 | surya-malleswar-chinta/Python-BlackJack | /BlackJack.py | 7,345 | 3.765625 | 4 | import random
class Card():
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[self.rank]
def __str__(self):
return self.rank + ' of ' + self.suit
class Deck():
def __init__(self):
self.cards = []
for suit in suits:
... |
fab7c2797bc0f767059887d3baf7a022c1a38a79 | ioanalucaci/Auction_Combinations_Simulator | /agents_factory.py | 3,053 | 3.640625 | 4 | """
Class in charge of creating agents. Here, the risk, base rate and utility can be updated.
"""
import random
class AgentsFactory:
"""Class in charge of creating the bidders and auctions."""
def __init__(self, parameters, bidder_types):
"""
The initialising function.
:param paramete... |
a14b8c610cee7e492118d621310af95dc775e05d | eirikmorken/introAI | /Assignment3_deliver/multiAgents.py | 4,427 | 3.828125 | 4 | from math import log
import sys
#from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman G... |
e6c85b4d7c25a0e5e8629ed5f123ce53a22291f6 | 0x0539/eulerproblems | /0025/solution.py | 216 | 3.5 | 4 | def digits(i):
d = 0
while i > 0:
i /= 10
d += 1
return d
def fib():
index = 2
i = 1
j = 1
while digits(j) < 1000:
k = i + j
i = j
j = k
index += 1
return index
print(fib())
|
d1d051a33cc4da4eeec7a394394b976926ea51d8 | jenny-liang/uw_python | /week05/screen_scrape_downloader.py | 2,061 | 4.3125 | 4 | """
Assignment: choose one or both or all three. I suspect 2 is a lot harder, but
then you would have learned a lot about the GitHub API and JSON.
1. File downloader using screen scraping: write a script that scrapes
our Python Winter 2012 course page for the URLs of all the Python
source files, then downloads them a... |
246dbf8049ab2ef3ea5ec3b0fbb850115f333821 | priyankasingh/CF-Python-2017 | /Codes/cel_to_fahr.py | 252 | 3.84375 | 4 | #Conversion of temps from celsius to fahrenheit
def cel_to_fahr(celsius):
"""Conversion of temperatures from celsius
to fahrenheit.
It takes one parameter which is in degree celsius.
"""
fahr=(celsius * 9/5) + 32
return fahr
|
087cae35399e4bde7589d19a423b83aba2d186b7 | Misha91908/Laboratory_Works | /Python/1 course/Lab2/test4.py | 209 | 3.734375 | 4 | a = int(input())
if a == 1: # проверяется,какой символ введен
print("Vi vveli \"1\" ")
elif a == 2:
print("Vi vveli \"2\" ")
else:
print("Vi vveli ni \"1\", ni \"2\" ")
|
d6285a3a42857039d4f44de958ab69e176ec1a0b | Misha91908/Laboratory_Works | /Semestr_works/Python/Sqrt/src.py | 323 | 3.921875 | 4 | digit = float(input("Введите число: "))
iterator = 0
x_value = digit
while x_value*x_value != digit:
x_value = 0.5 * (x_value + (digit / x_value))
iterator += 1
if iterator > 150:
break
print("Квадратный корень из введенного числа равен ", x_value)
|
763238abfb63cff25933e7d13429e8e0af6bef34 | Bio-designer/bioinfo-scripts | /gene_id_conversion.py | 1,697 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
@author: Min Dai
@created on 03,Apr, 2018
@ide: PyCharm Community Edition
"""
import mygene
import sys
##This script mainly used MyGeneInfo to convert gene symbols to gene Entrez IDs.
##Returns only gene symbols and their corresponding IDs if thier Entrez IDs are available.
##If there ... |
e21c6240a9efbdd3dd04017e502c0ec837a2995e | jochman/CompetitionProgramming | /Lessons/SortingProblem.py | 563 | 3.78125 | 4 | class Entry:
def __init__(self, name, id_number, priority):
self.name = name
self.id_number= id_number
self.priority = priority
def __repr__(self):
return f"{self.id_number}-{self.name}-{self.priority}"
lst = [
Entry("first", 4, 2),
Entry("second", 2, 5),
Entry("th... |
ce3791c2041e663e31446101cdf694c22badfb11 | jochman/CompetitionProgramming | /IEEE/Aeneascryptographicdisc/Aeneascryptographicdisc.py | 1,458 | 4.0625 | 4 | import math
def to_polar(r, theta):
"""Gets radian of the spin
:param r: radius
:param theta:
:return: angle in radians
"""
return r * math.cos(theta), r * math.sin(theta)
def calculate_distance(args):
"""Gets distance from (x1, y1) to (x2, y2)
:param args:
:return: distance
... |
33eb2439581e937701e90db74f8692b665337b10 | n40r1s/Simple-Binary-Crypt-Decrypt | /crypt.py | 432 | 4.09375 | 4 | def crypt():
a_string = input("Enter the string you want to crypt\n")
a_byte_array = bytearray(a_string, "utf 8") #Create bytearray
byte_list = []
for byte in a_byte_array:
binary_representation = bin(byte) #Convert to binary
byte_list.append(binary_representation) #Add to list
for i in range(0,len(b... |
7258b2c13a69571603a80612f8d8131b0c271e19 | lodgify/recruitment-exercises | /fib.py | 571 | 4 | 4 | from typing import Callable, Iterator
# iterative
def fib_iter() -> Iterator[int]:
""" Generates an infinite sequence of Fibonacci """
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# recursive
def fib_rec(n: int) -> int:
""" Returns Fibonacci number at n position """
if n == 0:
... |
e19fdaef235afb2afb9587344404e7786ed2439d | timbrahm/Artificial-Intelligence | /Project 1/parseMap.py | 1,333 | 3.5625 | 4 | from location import Location
from road import Road
def parse_map(filename):
# initialize location dictionary {ID -> Location} and road dictionary {ID -> list[Road]}
locationDict = {}
roadDict = {}
# parse file
with open(filename, "r") as file:
for line in file:
# remove \n and... |
91f74def1a8ed5245f8fd8d489f874c9b02eb4f0 | dariothornhill/data-structures-and-algorithms | /python/challenges/array_shift/array_shift.py | 239 | 3.8125 | 4 | # Worst case time O(n)
# Worst case space O(n)
def insert_shift_array(arr: list, value: int) -> list:
for i in range(len(arr)):
if arr[i] > value:
newArray = arr[:i] + [value] + arr[i::]
return newArray
|
0bc204ec75fb503fb8883e8f2932a2adbdc06053 | juan-g-bonilla/Algorithms-Project | /problem_5.py | 2,029 | 3.640625 | 4 | class TrieNode(object):
def __init__(self):
self.is_word = False
self.children = {}
def suffixes(self, suffix = ''):
"""
Return a list with all possible word endings for this node
"""
sol = [suffix] if self.is_word else []
for i, j in self.children.items... |
fd40f927926fc4f7eac6f72c9c7c798fbc24bb29 | emiliano-f/ia-uncuyo-2021 | /tp2-agentes-racionales/code/environment.py | 2,344 | 3.6875 | 4 | import random
class Environment:
""" Environment definition """
def __init__(self,
_sizeX: int, _sizeY: int,
_posX: int, _posY: int,
_dirt_rate: float):
def create() -> list:
""" Initialization of floor: clean """
floor: list = []
... |
f57cdd7a75a2c77960081500b6ece437e3805523 | emiliano-f/ia-uncuyo-2021 | /tp3-busquedas-no-informadas/code/breadth_first_search.py | 1,564 | 3.625 | 4 | from agent import Agent
from environment import Environment
from dque import Queue
from graph import Graph, Node
class BreadthSearchAgent(Agent):
def __init__(self,
_environ: Environment,
_graph: Graph):
Agent.__init__(self, _environ)
self.graph = _graph.graph
... |
7a8f6dff62463a67db3ce7e6f102a2750b453853 | emiliano-f/ia-uncuyo-2021 | /tp5-busquedas-locales/code/board.py | 3,634 | 3.609375 | 4 | from random import randint
class Board:
def __init__(self, _size: int):
self.board = [randint(0, _size-1) for _ in range(_size)]
self.table = [[30 for _ in range(_size)] for _ in range(_size)]
self.__temp = [0 for _ in range(_size)]
self.__fn_obj = self.update_fn() # Not working!
... |
6351ceee575965f6d7b3b071e34b0d52d7b7c303 | mwytock0812/osm_dc | /mapparser.py | 807 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import pprint
def count_tags(filename):
"""Return a dictionary of top-level tags and their counts.
Dictionary Format: {tag_name : count}
"""
# Initialize ouput dict. Build and root the tree.
tags = {}
tree = ET.par... |
9905ffde6ba123aceb1653aa00c110ac4f7e2977 | LeiHan-CA/DataAnalysisPanda | /pandabasics.py | 1,461 | 3.984375 | 4 | # import pandas library
import pandas as pd
import numpy as np
# Import pandas library
import pandas as pd
# Read the online file by the URL provides above, and assign it to variable "df"
other_path = "source/auto.csv"
# no header for this dataset
df = pd.read_csv(other_path, header=None)
# df.head() df.tail()
# c... |
ac3e5ad37b8697a6f31481ee0ec2224818f91641 | inimitabletim/iii | /Numpy/5_arange_set_array.py | 137 | 3.703125 | 4 | # --- 從數值範圍建立陣列 page.44
import numpy as np
a = np.arange(12)
print(a)
a = np.arange(12).reshape(4, 3)
print(a) |
ead0d989fc780cb3a237b09967d676a8fd2fe378 | inimitabletim/iii | /Numpy/4_change_array_shape.py | 290 | 4.1875 | 4 | # --- 變換陣列的形狀排列與維度 page.44
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
a_2d = a.reshape(3, 4)
print(a_2d)
print('\n')
a_3d = a.reshape(3, 2, 2)
print(a_3d)
print('\n')
a_2d_col = a.reshape(3, 4, order='F')
print(a_2d_col) |
55c4abb41c52130cf8c451550d1782ca42b8f9e4 | inimitabletim/iii | /Numpy/10_shapes_index.py | 416 | 3.609375 | 4 |
# --- 多維陣列的索引 page.47
import numpy as np
a = np.arange(16).reshape(2, 2, 4)
print(a)
print('')
# 切片擷取
print(a[0])
print('')
print(a[0, :, 1:3])
print('')
print(a[0, 1, :-1])
print('')
# 陣列索引
print(a[0, 1])
print('')
# 切片擷取
print(a[0][1])
print('')
# 陣列索引
print(a[0, 1, 2])
print('')... |
b456aa44b458be393f38710d4e2697bcce9c099d | gwccu/day10-Tallulahwalz | /problemSetDay10.py | 901 | 3.875 | 4 | # File name: problemSetDay9.py
import random
wordList = ["whatup", "bird", "pink", "orange","england", "park"]
randomword = wordList[random.randint(0,4)]
characters= list(randomword)
display = list()
displaylength = len(characters)
for i in range (0, len(characters)):
display.append("_")
print(display)
tracker = ... |
340f3842c543fd471eca527ceb74b4999e0b08e1 | Iftee360/syntax-library | /Programming Languages/python/14-exception-handling.py | 351 | 3.890625 | 4 | ### Exception Handling
userInp = int(input("Enter Num"))
# try:
# answer = 10 / userInp
# except:
# print("Error")
try:
answer = 10 / userInp
except ZeroDivisionError as e:
print(e)
except ValueError as v:
print(v)
except:
print("Sorry, some Error Occured😓") #HIGHLY Un-recommended (do... |
52d875c26549bfee522212e31e68a1c8a3c0bdd5 | Iftee360/syntax-library | /Programming Languages/python/2-variables-&-data-types.py | 497 | 3.96875 | 4 |
### VARIABLES and DATA TYPES
'''
Names are case-sensitive and may begin with:
letters, $, _
After, may include
letters, numbers, $, _
Convention says
Start with a lowercase word, then additional words are separated
by underscores
ex. my_first_variable
'''
name = "Iftee" # Strings
age = 30 ... |
3264a434e5f410dd1165fb59d8360ccef7e23c86 | IMabuza/factorial | /factorial.py | 430 | 4.03125 | 4 | class Factorial:
def __init__(self, n):
self.n = n
def fac(self):
if type(self.n) != int or self.n < 0:
return "Please enter an int greater or equals 0"
elif self.n == 0:
return 1
multiple, prod = self.n - 1, 1
while multiple >= 1:
pro... |
7cdab00e7ec6d5866c28d7996625eb4b51c36501 | Symbo1/wsltools | /wsltools/utils/faker/providers/address/en_PH/__init__.py | 32,074 | 3.703125 | 4 | # -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from collections import OrderedDict
from string import ascii_uppercase
from .. import Provider as AddressProvider
class Provider(AddressProvider):
"""
Provider for addresses for en_PH locale
Like many things in the Philippines, even addres... |
8e2fa93b471ea7b39d26ee5e82734a1cfc35e3eb | byunwonju/2020_programming | /0523/selc04.py | 122 | 3.578125 | 4 | num = int(input("정수 입력:"))
if num%2 ==0:
print("짝수입니다.")
else:
print("홀수입니다.")
|
60dff7df0fcad7496a9fad1c32f40c5633361947 | byunwonju/2020_programming | /0606/func06.py | 181 | 3.671875 | 4 | def print19(start,end):
for i in range(start, end+1):
print(i,end=" ")
print("")
s= int(input("시작:"))
e= int(input("끝:"))
if s < e:
print19(s,e)
|
691e6507ae6008713eabbceaad91f9363c0adc6a | byunwonju/2020_programming | /prob101.py~ prob130.py/prob 116.py | 161 | 3.8125 | 4 | time= str(input("현재 시간을 입력하세요:"))
a= ("02:00")
if (time ==a):
print("정각입니다.")
else:
print("정각이 아닙니다.")
|
86528dd845be83a71b90850b26a7880f85a0f758 | mk346/Python-class-Projects | /Guess_Game.py | 492 | 4.25 | 4 | secret_word ="trouser"
guess= ""
count=0
guess_limit = 3
out_of_guesses= False
print("HINT: I have two legs but i cant walk")
while guess!= secret_word and not(out_of_guesses):
if count<guess_limit:
guess = input("Enter Your Guess: ")
count+=1
else:
out_of_guesses= True
i... |
284c6ae73ecae77019ed55d9d1974bd5ea55c898 | ghotiv/PyCon-Talk-Intro-to-Brython | /Brython1.4/site/tests/test_strings.py | 2,585 | 3.765625 | 4 | # strings
log('spam eggs')
log('doesn\'t')
log("doesn't")
log('"Yes," he said.')
log("\"Yes,\" he said.")
log('"Isn\'t," she said.')
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
log(hello)... |
e51cac7191f29351e37768a30cf857b6c4be3216 | deepgautam77/Basic_Python_Tutorial_Class | /Day 7/python_PEP_rule.py | 592 | 3.859375 | 4 | menu = {
'momo':19,
'chowmein':16,
'pasta':14,
'Thupka':10,
'chicken_chilli':20,
'sausage':18
}
def __init__(self):
self.order = str
self.menu = str
def customer_order(self,order_list):
order_list=[]
order=input("enter your order followed by comma: ")
order_list.append(order... |
a8a4f8ecc948c07a6c8f96173bb2b6e32ee550aa | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 2/for_loop.py | 253 | 4.15625 | 4 | #for i in range(10):
# print("This is fun..")
#range() function
#print odd number from 0-100
for i in range(1,100,2):
print(i, end=' ')
#WAP to print even numbers from 2000-2500
#WAP to print odd numbers starting from 5200 and ending at 4800
|
d49cedb5535e851045d759e51e9a37f833f6c460 | deepgautam77/Basic_Python_Tutorial_Class | /Day 5/homework_1.py | 659 | 4.34375 | 4 |
#Create a phone directory with name, phone and email. (at least 5)
#WAP to find out all the users whose phone number ends with an 8.
#all the users who doesn't have email address. --done
d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'},
{'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'},
{'... |
76bf8b924eb07939bf038f367b6c24f6a338c146 | deepgautam77/Basic_Python_Tutorial_Class | /OpenCV/test_1.py | 650 | 3.75 | 4 | import cv2
img = cv2.imread('messi5.jpg',-1)
print(img)
cv2.imshow('image',img) #show image when running program
k = cv2.waitKey(0) #decides how long to preview shown image in terms of millisecond
if k==27: #27 is code for ESC key.
cv2.destroyAllWindows() ... |
b96ecd405a97dbf123aa17a569545de5ace8edd0 | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 4/list_1.py | 389 | 3.765625 | 4 | from random import randint, sample, shuffle, choice
list_int = [1,2,3,4,5]
list_1 = []
list_1 = list_int[:]
print(list_1)
del(list_int[3])
print(list_int)
#insert
list_int.insert(1,8)
print(list_int)
#WAP that generates 50 random numbers between 1 and 100 and print that number.
L = [randint(1,100) for i in range(... |
694759e96c8e1988ff347b36ff6c50b55b113639 | deepgautam77/Basic_Python_Tutorial_Class | /Week 1/Day 2/simple_task.py | 294 | 4.3125 | 4 | # -273 degree celsius < invalid..
temp = float(input("Enter the temperature: "))
while temp<-273:
temp = eval(input(("Impossible temperature. Please enter above -273 degree celsius: ")))
print("The temperature of ",temp," Celsius in Farenheit is: ", 9/5*temp+32)
#break
#continue
#pass
|
2897cee2f66c43f322e0d6a08c528c5500ecb799 | cpe202fall2019/lab0-jgilbe14 | /planets.py | 349 | 3.859375 | 4 | def weight_on_planets():
weight_earth = float(input("What do you weigh on earth? "))
weight_mars = weight_earth * .38
weight_jupiter = weight_earth * 2.34
print("\nOn Mars you would weigh %.2f pounds.\nOn Jupiter you would weigh %.2f pounds."
% (weight_mars, weight_jupiter))
if __name__ == '__mai... |
2be4287cfdc439333a10ee252c31c3b0a88f77e0 | tungyr/skillbox-study | /Data Science/webinars/skillbox brute force/generators/bases.py | 550 | 3.515625 | 4 | states = {
# state_key: 0
}
symbols = '0123456789qwertyuiopasdfghjklzxcvbnm'
def get_next_str():
if state_key not in states:
states[state_key] = 0
password_index = states[state_key]
password = ''
index = password_index
while index > 0:
rest = index % len(symbols)
inde... |
898a0deee774aa56b193d93a47b4038aa30a6727 | tungyr/skillbox-study | /Data Science/2. Data Scientist. Аналитика. Начальный уровень/7. Основы Python - классы и объекты/7.4. Special methods of classes.py | 1,564 | 3.84375 | 4 | class Backpack():
def __init__(self, gift=None):
self.content = []
if gift is not None:
self.content.append(gift)
def add(self, item):
"""Put something to backpack"""
self.content.append(item)
print('Put to backpack: ', item)
def inspect(self):
... |
432d61c22ec968d2443021ab8fc3aace70261023 | tungyr/skillbox-study | /Data Science/2. Data Scientist. Аналитика. Начальный уровень/7. Основы Python - классы и объекты/7.8 Practice OOP 2.py | 2,516 | 3.5625 | 4 | import random
from termcolor import cprint
class Man:
def __init__(self, name):
self.name = name
self.fullness = 20
self.house = None
def __str__(self):
return 'I\'m {}, fulness {}'.format(self.name, self.fullness)
def eat(self):
if self.house.food >= 10:
... |
7e0a1a3b4e5c9df5194249a60363ec710e3dfdaf | ellinj2/Past_Projects | /CSCI1100/Simple_Spell_Check/hw7Part1.py | 6,924 | 4 | 4 | '''
This code checks a set of input words against a set of known words. If the word isn't in the dictionary, it tries
dropping each letter and checking the new word, then inserting each letter in the alphabet into each index and
checking the new words, then swapping consecutive letters and checking the new words, then ... |
0348ac14e4b5d85f8a707342faf6d513b6ca6946 | darkdefender27/ibit | /codechef/snackdown17/TEMPLELA.py | 393 | 3.625 | 4 | #!/usr/bin/env python
S = int(raw_input().strip())
for i in xrange(S):
is_valid_strip = "yes"
ni = int(raw_input().strip())
ii = map(int, raw_input().strip().split(' '))
if(ni%2==0 or ii[0]!=1 or ii[-1]!=1):
is_valid_strip = "no"
else:
j = 1
while(j < (ni/2)+1):
if(ii[j] != ii[-j-1] or ii[j] != ii[j-1]... |
eee2b799ebe8bc9fe55ea4f93a224154f45b5cf2 | darkdefender27/ibit | /codechef/snackdown17/SNAKPROC.py | 521 | 3.71875 | 4 | #!/usr/bin/env python
R = int(raw_input().strip())
for i in xrange(R):
L = int(raw_input().strip())
report = raw_input()
result = "Valid"
stack = []
for i in xrange(L):
if(report[i] == 'H'):
if(len(stack) != 0 and stack.pop() == 'H'):
result = "Invalid"
break
else:
stack.insert(0, 'H')
el... |
da2bbf05274b911e0fb924680b6f910d219ab4eb | amitbmas90/python-algorithms | /algorithms/graphs/bipartite.py | 1,315 | 3.75 | 4 | """
In the mathematical field of graph theory, a bipartite graph (or bigraph) is a graph whose vertices can be divided
into two disjoint and independent sets U and V such that every edge
connects a vertex in U to one in V. Vertex sets U and V are usually called the parts of the graph.
Equivalently, a bipartite graph... |
4abb31369eacaaa9b0812df76e4b15ea94f46bae | gregmankes/cs372-project2 | /ftclient.py | 4,735 | 3.703125 | 4 | #!/bin/python
from socket import *
import sys
def check_args():
# check to the amound of arguments
if len(sys.argv) < 5 or len(sys.argv) > 6:
print "Invalid number of args"
exit(1)
elif (sys.argv[1] != "flip1" and sys.argv[1] != "flip2" and sys.argv[1] != "flip3"):
# check to make s... |
802ac41bb0e8d2035d204bcff6f762736e66eb00 | s0513/python_basic | /answer/210616_買最多禮物_15min.py | 1,611 | 4.40625 | 4 | '''
題目:
小明和小華生完第一個孩子後非常高興,他們的兒子喜歡玩具,
所以小明想買一些玩具。他面前擺著許多不同的玩具,
上面標有它們的價格,他想用手上的錢最大程度地購買玩具。
給定玩具的價格清單和能夠花費金額,
確定他可以購買的最大禮物數量。
#註: 注意每個玩具只能購買一次。
Example:
玩具價格清單 = [ 1, 2, 3, 4 ]
手上的錢k = 7
所以預算為7個貨幣單位,他可以購買組合為[1、2、3]或[3、4],因此最多3個玩具。
限制:
1. 玩具清單n最長為10個項目
2. 玩具價格i最高100
3. 手上有的錢k最高150
'''
import random
#i = random.randin... |
87df06f291f07ca3d42adac26380e888e16a5e24 | cryptopossum/ReferenceGenome | /image.py | 3,525 | 3.71875 | 4 | #!/usr/bin/env python
import codecs
import gd
import keys
import os
import sys
import twitter
pwd = "/home/amarriner/python/genome/"
# Total number of acids
TOTAL = 248956422
# Number of acids we will process per run
max = 28419 # 28419.682876712328767123287671233
# Image size will be px * size
# px is the square ... |
206a0179cbc113f3debf05653074b4f813c788e7 | samiurrahman98/ece458-computer-security | /P1/samiur-rahman.py | 9,992 | 3.65625 | 4 | """
ECE 458 Project 1
Skeleton solution file.
You need to assign values to variables, and implement two functions as part of your answers to this project
You are not allowed to call any DSA signature package.
You are allowed to define whatever subroutines you like to structure your code.
"""
import hashlib
import bin... |
789176de8fc3a128c23ef3f9eceef0a629d310a9 | naelob/tic-tac-toe | /game.py | 3,207 | 4.0625 | 4 | import math
import time
from player import HumanPlayer, RandomComputerPlayer, SmartPlayer
class TicTacToe():
def __init__(self):
self.board = self.make_board()
self.winner = " "
@staticmethod
def make_board():
board = []
for i in range(9):
board.append(" ")
... |
63e63ec4a0340d36b1734eb6abe7abd0661abf43 | keylorch/python-101 | /5-tuples.py | 440 | 4.40625 | 4 | # Tuples
# Basic information and operations on Tuples in python
# Tuples are INmutable
myTuple = (1,2,3,4)
print("myTuple: ", myTuple)
print("min(myTuple): ", min(myTuple))
print("max(myTuple): ", max(myTuple))
print("sum(myTuple): ", sum(myTuple))
print("len(myTuple): ", len(myTuple))
print("1 in myTuple: ", 1 in m... |
fabd8954b3f651d5df4a7bda4b6c45268e21b928 | sridevishanmugam/sri | /holiday.py | 143 | 4.125 | 4 | s=input()
if(s=="Monday" or s=="Tuesday" or s=="Wednesday" or s=="Thursday" or s=="Friday"):
print("no")
else:
print("yes")
|
d66319a3e8fd7c47b973fcfb4baf3b9489b23e4f | sridevishanmugam/sri | /countprime.py | 224 | 3.59375 | 4 | def prime(n1):
i=2
while(i<n1):
if n1%i==0:
return False
i=i+1
return(True)
n1=input()
n1=n1.split()
i=int(n1[0])
j=int(n1[1])
count=0
while(i<=j):
if(prime(i)):
count+=1
i=i+1
print(count)
|
6448d6558262935be6a409bfa47878d58db9fbf2 | san-smith/patterns_template | /factory_method/script.py | 1,110 | 4.125 | 4 | #coding: utf-8
"""
Типы строя
"""
class Culture:
"""
Культура
"""
def __repr__(self):
return self.__str__()
class Democracy(Culture):
def __str__(self):
return 'Democracy'
class Dictatorship(Culture):
def __str__(self):
return 'Dictatorship'
"""
Само правительство
"""
... |
1d9270f40c2b8c4d7bbb647978d5f922b19ab197 | DrShiz/stepik_tkinter | /les8.py | 282 | 3.734375 | 4 | from tkinter import *
def hello(event):
text1.config(bg='green')
def bye(event):
text1.config(bg='red')
window = Tk()
text1 = Label(window, width=30, height=30, text='', bg='red')
text1.pack()
text1.bind('<Right>', hello)
text1.bind('<Left>', bye)
window.mainloop()
|
dc2ba7f32e4478a8d35c633209d018e182c12547 | SummerBigData/SurenRepo | /Coursera.EX3/neuralNet.py | 4,725 | 4.09375 | 4 | # Written by: Suren Gourapura
# Written on: May 22, 2018
# Purpose: To solve exercise 3 on Multi-class Classification and Neural Networks in Coursera
# Goal: To use the given theta matrices to see the classification power of a neural network
# Import the modules
import numpy as np
from numpy import genfromtxt
impo... |
3896ee999184f745da5cdfd7e1ad7b0f6dd0634b | SummerBigData/SurenRepo | /Coursera.EX3/numGrapher.py | 1,654 | 4.0625 | 4 | # Written by: Suren Gourapura
# Written on: May 22, 2018
# Purpose: To solve exercise 3 on Multi-class Classification and Neural Networks in Coursera
# Goal: Take the provided data and plot the numbers
# Import the modules
import numpy as np
from numpy import genfromtxt
import matplotlib.pyplot as plt
import matpl... |
01295096e7ab2e89fd0cf9655a1a47773d6db5a7 | SummerBigData/SurenRepo | /OpenClassroom.ML.EX2/sol2.py | 1,626 | 3.96875 | 4 | # Import the modules
import numpy as np
import matplotlib.pyplot as plt
import math
def hypothesis(theta, x):
xArr = np.array([[1]*len(x), x])
thetaArr = np.asarray(theta)
hypo = [0 for j in range(len(x))]
hypo = np.matmul(xArr.transpose(), thetaArr.transpose())
return hypo
# Obtain the x and y data values a... |
f63ebc054df6a8f2c78ffab79a4f58f69707fd15 | steven-snelling/PR301-Assignment_3 | /source/model/data_validation/data_validator_tests.py | 1,856 | 3.671875 | 4 | import unittest
from data_validator import *
class DataValidatorTests(unittest.TestCase):
# By Steven Snelling
@classmethod
def setUpClass(cls):
cls.dataValidator = DataValidator()
def setUp(self):
# be executed before each test
print("set up")
self.data_1 = [['H001',... |
b23cd19aac4a66c70ab74ed5ae45d22c5acac8c0 | iclementine/leetcode | /problem4.py | 3,912 | 4.125 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
num... |
3dd3d2eefcce0aece534d10cc9da543f4bf3fca5 | Mohit9486/computer-graphics | /circle/circle.py | 788 | 3.890625 | 4 | import turtle as t
x1 = int(input("X coordinate of center: "))
y1 = int(input("y coordinate of center: "))
r = float(input("Radius: "))
screen = t.Screen()
p = t.Turtle()
p.speed("fastest")
p.penup()
p.goto(x1, y1)
p.dot()
p.pendown()
p.pencolor("red")
p.write("center")
p.penup()
x = 0
y = round(r)
D = 5 / 4 - r
w... |
8ff8d9dc2babe38737206c32085bfcd84dff55e7 | torreaopt/NBprocessing | /NBprocessing/categorical/__init__.py | 2,667 | 4.03125 | 4 | """
Generic functions to manipulate categorical features in pandas data frame.
This library include the functions:
1. remove_categories(database, column_name, categories_to_drop):
Remove all indexes in the database that contain the categories from the categories_to_drop.
Before removing the indexes... |
502c92447b734fcbafb423b7d1b666fb5e49bd22 | stellanechi/Class-Assignment-SheCodeAfrica- | /classes.py | 1,189 | 3.78125 | 4 | # Examples on Class. A way of grouping functions and other statements
"""class Student_Record:
pass
std_1 = Student_Record()
std_2 = Student_Record()
std_1.surname = 'Eneh'
std_1.firstname= 'Stella'
std_1.others= 'Nkechi'
std_1.program = 'SheCodeAfrica'
std_1.hort = 3
std_1.username = 'Nechi'
std_1.duration= 'Thr... |
00af72c64e08a9f15b7f869ed9745e3130e676e7 | markap/PythonPlayground | /language_features/decorator.py | 535 | 4.375 | 4 | """
a decorator example to multiply to numbers before executing the decorated function
"""
def multiply(n, m):
def _mydecorator(function):
def __mydecorator(*args, **kw):
# do some stuff before the real
# function gets called
res = function(args[0] * n, args[1] *... |
4e0f1e661c01efed7fc16eaa341256752583aaa8 | anuraagkonda/macbuddy_app | /dropboxapi file encryption/test.py | 1,793 | 3.59375 | 4 | """Name: Anuraag Konda
Enrollment_number: 1001051814
Subject: Cloud computing(6331)
Programming assignment 1"""
# Include the Dropbox SDK
import dropbox
import gnupg
import time
# Get your app key and secret from the Dropbox developer website
app_key = '2ufi6uo6w2nsnlf'
app_secret = 'uvbq0hm2uc5mnm5'
gpg... |
cc0c63e8f2bff0f622c7bee6265c76ffc81f0240 | siyam04/python_problems_solutions | /Siyam Solved/Problem Set -1/Solutions - 1/5.py | 173 | 4.15625 | 4 | print('Enter any String:')
a = str(input())
for c in a:
if(c == 'w'):
print(a.replace('w', '#'))
elif(c == 'W'):
print(a.replace('W', '#'))
|
48edaabea194596e6914515801cbeead798456dc | siyam04/python_problems_solutions | /Siyam Solved/Problem Set -1/Solutions - 1/7.py | 125 | 4 | 4 | print("Enter String:")
a = str(input())
print("Enter How many Times:")
b = int(input())
for i in range(0, b):
print(a)
|
7de5e63b39afa2e8fc593bae2b62d61e25714ba2 | siyam04/python_problems_solutions | /Siyam Solved/Problem Set -2/Solutions- 2/11.py | 321 | 3.9375 | 4 | start = int(input('Enter Starting Year: '))
end = int(input('Enter Starting Year: '))
print("Leap Years Between", start, "and", end, "is:")
while (start <= end):
if (start % 4 == 0 and start % 100 != 0):
print(start)
if (start % 100 == 0 and start % 400 == 0):
print (start)
start = start + 1... |
8c763d12a5708eaf31d2da130d47304f4414bd6b | sean-blessing/20210424-python-1-day | /ch07/classes/main.py | 640 | 4.1875 | 4 | from circle import Circle
class Rectangle:
"""Rectangle class holds length and width attributes"""
# above doctring is optional
area_formula = "area = length * width"
def __init__(self, length, width):
pass
self.length = length
self.width = width
def area(self):
""... |
b8387b9ee340e02727a089494ef37a9d80ed5de5 | sean-blessing/20210424-python-1-day | /ch01/rectangle-calculator/main.py | 352 | 4.15625 | 4 | print("Welcome to the area and perimeter calculator!")
choice = "y"
while choice == "y":
length = int(input("enter length:\t"))
width = int(input("enter width:\t"))
perimeter = 2*length + 2*width
area = length * width
print(f"Area:\t\t{area}")
print(f"Perimeter\t{perimeter}")
choice = in... |
17d6e9ac7ffad9093310f0437fb27ce0fffd4367 | thompsonf/md-crypto | /PS5/jrh_rsa_sig_forger.py | 1,980 | 3.546875 | 4 | # How to solve:
#
# if m 63-digit hex number,
# M = 0x00 m 0x00 m
# implies
# M = m*2^512 + m
# M = m(1 + 2^512)
#
# M^d = m^d * (1 + 2^512)^d mod N
#
# suppose a, b are any two factors of m
# then
# M^d = (ab)^d * (1 + 2^512)^d mod N
#
# let A = 0x00 a 0x00 a, B = 0x00 b 0x00 b s.t.
# A^d = a^d * (1 + 2^512)^d mod N
#... |
7629fd5b532921754914a2652b905b8865e2667f | avichai/euler_project | /euler_15.py | 1,470 | 4 | 4 | # Lattice path
# Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,
# there are exactly 6 routes to the bottom right corner.
#
#
# How many such routes are there through a 20×20 grid?
# Avichai Ben David
from pprint import pprint
import math
ROWS = 20
COLS = 20
BEGIN_... |
3f175826b1ea6bf71b8d975ce5fe44215992405c | avichai/euler_project | /euler_24.py | 946 | 3.84375 | 4 | # Lexicographic permutations
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits
# 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are:
#
# 0... |
d9546aeab930b32aa543a6206f081480b466f6fc | avichai/euler_project | /euler_21.py | 2,128 | 3.515625 | 4 | # Amicable numbers
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are
# called amicable numbers.
#
# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 1... |
4db701b8d7af4c5fc243bc02ecd0e64fd1f8548d | agentle/Book-Index | /main.py | 7,986 | 3.828125 | 4 | def for_grandpa():
"""
Future Additions:
1. Mulitple page #s per entry ---------------- DONE -----
2. Last name then first name ----------------- DONE -----
3. Corrections to the index (remove data) ---- DONE -----
4. Saving an index as a file (.txt?) --------- DONE -----
5. Naming each... |
ddacc2fcfafe334bd3240362792759b4e4fdeece | enmodoflow/sorteololo | /src/modulos/logica.py | 1,959 | 3.625 | 4 | from datetime import date, datetime
def transformarHora(fecha):
año = fecha.year
mes = fecha.month
dia = fecha.day
hora = fecha.hour
minutos = fecha.minute
segundos = fecha.second
fecha_hoy = datetime.now()
dia_hoy = fecha_hoy.day
fecha_x = datetime(año, mes, dia, hora, minutos, seg... |
cc301f60fd5de04d71885228bec672d0d177e76b | puspita-sahoo/python_program | /for_loop.py | 7,244 | 4.3125 | 4 | # 1.
# Print all elements of a list using for loop.
# ====================================
# l = list(map(int, input("Enter a list: ").split(",")))
# print(l)
# for i in l:
# print(i)
# ==================================================================================================================
# 2.
# Tak... |
b1ebc075281f1d5784d3acb2956676a3a240c521 | pyfun/msf | /stat/util.py | 2,067 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def summaryone(x):
"""Summary of the time series.
include mean, std, max, min and range
"""
print 'mean and std are ',np.mean(x), np.std(x)
print 'max and min are ',np.max(x), np.min(x)
print 'the range is ',np.max(x)-np.min(x)
def... |
789c2eb20dfaeaa72e1ee96f16c065e2f07f13b0 | guam68/class_iguana | /Code/nathan/pythawn/optional_arbitrary_precision_math.py | 428 | 3.796875 | 4 | def long_divide(number_list, divided_by):
new_list = []
for i in range(len(number_list)):
i /= divided_by
new_list.append(i)
return new_list
number = '656565'
number_list = []
for i in number:
number_list.append(i)
number_list = int(number_list)
print(number_list)
divided_by = in... |
0734e72eed28afa8c6bfa637f46fc3a59a5a8afd | guam68/class_iguana | /Code/nathan/pythawn/lab_05_emoticongen.py | 559 | 3.859375 | 4 | import random
#allows program to know what random is
start = input('PRESS ENTER TO CREATE AN EMOTICON AT RANDOM')
#pointless intro text to allow user to know what program is going to do
mouths = ['D', ')', '(', 'p', '/']
noses = ['^', 'c', '<', '*']
eyes = [':', 'X', ';', 'B']
#list of emoticon face pieces
outstring = ... |
5377f4e69a75d5004a5857c93a3ee0f7b7d62217 | guam68/class_iguana | /Code/Scott/Python/lab_10_average_numbers_v3.py | 1,144 | 4.0625 | 4 | #median
# def find_median(numbers):
# numbers.sort()
# for i in numbers:
nums = []
while True:
new_num = input('Please enter a number, or type \'done\': ')
if new_num == 'done':
break
nums.append(int(new_num))
nums.sort()
# print(nums[2:3])
# len is 4
# 0 1 2 3
# [a, b, c, d]
if len... |
6726b05dfc6576f5e64d65f86d2db85b6e580cb4 | guam68/class_iguana | /Code/Josh/python/lab17_palindrome_anagram.py | 813 | 4.125 | 4 | def check_palindrome():
word = input('Check and see if your word is a palindrome, give me a word\n>>').lower()
word_list = []
for i in word:
word_list.append(i)
reversed_word_list = word_list[::-1]
if reversed_word_list == word_list:
return True
else:
return False
# prin... |
7271907dba835c8f2aca679466abfb4d414259ba | guam68/class_iguana | /Code/Josh/python/lab07_rock_paper_sicissors.py | 891 | 4 | 4 | import random
print('let\'s play Rock, Paper, Scissors')
pick = input('What\'s your choice Rock type "r", Paper type "p" or Scissors type "s"\n')
z = ['Rock', 'Paper', 'Scissors']
pc = random.choice(z)
print(f'computer picks {pc}')
if pick == 'r' and pc == 'Rock':
print('it\'s a tie')
elif pick == 'p' and pc == 'Pa... |
0b8558ac770fd1417df15131365b044ea4e9e05b | guam68/class_iguana | /Code/Richard/python/lab19-blackjack.py | 2,771 | 3.71875 | 4 | """
author: Richard Sherman
2018-12-06
lab19-blackjack.py, advises to hit or stay given a blackjack hand
"""
import random
print('I\'ll deal you a blackjack hand. Then you can decide to hit or stay. But I\'ll help by giving you advice.')
print('To make it interesting, I\'ll play too. I won\'t look at my hand until you... |
a2939f9834efd995dce131b47835070982058687 | guam68/class_iguana | /Code/Richard/python/lab-road-trip_3.py | 1,609 | 4.21875 | 4 | """
author: Richard Sherman
2018-12-21
lab-road-trip.py, an exercise in sets and dictionaries,
finds the cities from an origin that are accessible by taking n 'hops'
"""
# this is the dictionary of sets of cities that can be reached from a given origin
# a pair are added to the original lab to facilitate testing
city_t... |
1e30a99c62bcb5aa44be58891d8210b608794cfd | guam68/class_iguana | /Code/Richard/python/lab18-peaks-valleys.py | 1,508 | 3.90625 | 4 | """
author: Richard Sherman
2018-12-06
lab10-peaks-valleys.py, takes a list of ints and identifies elements greater than their immediate neighbors ('peaks')
and elements less than their immediate neighbors ('valleys'). Tries to extend this logic beyond immediate neighbors to find
the 'volume' of 'valleys' and the 'heig... |
de513e18abf270601e74fc0e738dc4f6ef7c5c1a | guam68/class_iguana | /Code/Richard/python/lab25-atm.py | 1,914 | 4.34375 | 4 | """
author: Richard Sherman
2018-12-16
lab25-atm.py, an ATM simulator, an exercise in classes and functions
"""
import datetime
class ATM():
def __init__(self, balance = 100, rate = 0.01):
self.balance = balance
self.rate = rate
self.transactions = []
def check_withdrawal(self, amount)... |
164ff47a83bd250d278c32f37ecb28a1cb13e1b9 | guam68/class_iguana | /Code/nathan/pythawn/lab_03_grading.py | 1,016 | 4.15625 | 4 | #ask user for input needing a number between 50 and 100
grade = input('what was your grade? \n>')
#turn user input (string) into an integer
grade = int(grade)
#
# if grade >= 96:
# print('A+')
# elif grade == 95:
# print('A')
# elif grade >= 90:
# print('A-')
#
#lots of ifs and elifs to determine what to... |
bdf4fabb89d8d1d17131a525549a45e8ec38a334 | guam68/class_iguana | /Code/nathan/pythawn/lab_13_rot13.py | 1,050 | 4.3125 | 4 | #making rot13 function attached to dictionary
def rot13(user_string):
rot_dict = {'a': 'n',
'b': 'o',
'c': 'p',
'd': 'q',
'e': 'r',
'f': 's',
'g': 't',
'h': 'u',
'i': 'v',
... |
587a422070acb602320273d7f8ac555dbb5a6939 | guam68/class_iguana | /Code/nathan/pythawn/lab_19_blackjackv2.py | 1,208 | 4.09375 | 4 | #dictionary of cards with each card tied to an integer value
card_list = {'a': 1, 'aa': 11, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'j': 10, 'q': 10, 'k': 10}
#asking user what their card is
first_card = input('what is your first card?')
print(card_list[first_card])
#asigns user input ... |
827347e991156b09594e7c4cf27d5d87e1b94627 | guam68/class_iguana | /Code/Scott/Python/Lab_20_Credit_Card_Validation.py | 1,667 | 4.0625 | 4 | #Lab_20_Credit_Card_Validation
# Convert the input string into a list of ints
# Slice off the last digit. That is the check digit.
# Reverse the digits.
# Double every other element in the reversed list.
# Subtract nine from numbers over nine.
# Sum all values.
# Take the second digit of that sum.
# If that matches th... |
6a8ccd4bc43590afc4d759f5ba159a24f44587a8 | guam68/class_iguana | /Code/Scott/Python/Lab_23_Contact_List.py | 545 | 3.625 | 4 |
with open('contact_list.csv', 'r') as file:
lines = file.read().split('\n')
# print(lines)
#list of dictionaries
#Name : Gordon Jefferson, Favorite Fruit : Pineapple ...each person their own dictionary
data_list = []
for line in lines:
line = line.split(',')
data_list.append(line)
indexes = data_lis... |
7a9349976447f50f8a54c6999aa1419e5e382f2e | guam68/class_iguana | /Code/Scott/Python/lab_11_simple_calculator_version2.py | 898 | 4.28125 | 4 | #lab_11_simple_calculator_version2.py
#lab_11_simple_calculator_lvl_1
#operator_dict = {'+': +,}
operator = input("What type of calculation would you like to do? Please enter '+', '-', '**', or '/' :")
operand_a = input('Please enter the first number:')
operand_b = input('Please enter the second number:')
operand_a... |
fd0dd8b52a26df3303763b2c2da839a42c00ab31 | guam68/class_iguana | /Code/Josh/python/lab12_guess_the _number.py | 1,709 | 3.765625 | 4 | import random
x = random.randint(1,100) #generating the random number for the computer
#print(x)
guess = 0 #setting guess (the counter) to 0
while True: #start of first user's guess while loop
guess_left = abs(guess - 8)
if guess == 1:
break
user_num = int(input(f'Guess my number from 1 to 100 \n{gu... |
2eba7e9bccb0005fdf14007ee56046302fe2da97 | guam68/class_iguana | /Code/Scott/Python/lab6_password_generatory.py | 2,431 | 4.375 | 4 | #lab6_password_generatory.py
#1. acquire all possible characters
import random
import string
# n = input('How many characters would you like your password to have?:\n')
# n = int(n)
# character_list = list(string.ascii_lowercase) + list(string.digits) + list(string.punctuation)
# password = ''
# for c in range(0, n):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.