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 |
|---|---|---|---|---|---|---|
4aa52ac9d6cd5d76a2cfab2c93ce8bdfe204ef9e | dragondave/ricecooker | /ricecooker/utils/path_builder.py | 1,334 | 3.53125 | 4 |
class PathBuilder:
"""
Class for formatting paths to write to DataWriter.
"""
path = None # List of items in path
channel_name = None # Name of channel
def __init__(self, channel_name=None):
""" Args: channel_name: (str) Name of channel """
self.channel_name = ... |
64739565dd86b5b36fdbe203c3f6beeb2c78b847 | anthony-marino/ramapo | /source/courses/cmps130/exercises/pe01/pe1.py | 651 | 4.5625 | 5 | #############################################
# Programming Excercise 1
#
# Write a program that asks the user
# for 3 integers and prints the
# largest odd number. If none of the
# three numbers were odd, print a message
# indicating so.
#############################################
x = int(input("Enter x: "))
y =... |
9dbffbb4195dfe02d90e4f2bd2813cc2a7d993a6 | anthony-marino/ramapo | /source/courses/cmps130/exercises/pe10/pe10-enumeration.py | 1,047 | 4.40625 | 4 | ##############################################################################
# Programming Excercise 10
#
# Find the square root of X using exhaustive enumeration
#############################################################################
# epsilon represents our error tolerance. We'll
# accept any answer Y where... |
43cdf02e3724d53e242e9421c9be9029d6af1602 | anthony-marino/ramapo | /source/courses/cmps367/modules/module04/pitfalls.py | 285 | 4 | 4 | x = 3
while x < 5:
print ( x )
x += 1
print("===========");
#x = 2
#y = 2
#while x < 5 :
# print (x)
# y += 1
print("===========");
x = 6
while x < 6:
print (x)
x += 1
print("===========");
x = 2
y = 10
while x < 5:
print (y)
y += 1
x += 1
|
d8424f43eb8b9da019e23d963bcc110271d65805 | anthony-marino/ramapo | /source/courses/cmps367/modules/module05/scoping1.py | 216 | 3.75 | 4 | def f(x): #name x used as formal parameter
y = 1
x = x + y
print( 'x = ', x)
return x
x = 3
y = 2
z = f(x) #value of x used as actual parameter
print ('z = ', z)
print ('y = ', y)
print ('x = ', x) |
1dde3599a52ab0070490d5d68c15f9250beb7ff6 | VertAdam/PianoKeyboard | /PianoFun.py | 4,043 | 3.703125 | 4 | # Jan 16, 2021
# Adam Vert
############## IMPORTS ##############
import mido
from midi_numbers import number_to_note, note_to_number
import numpy as np
import time
############# Class ###########
"""
This is just some fun scripts I made to practice using the MIDO package
"""
class PianoFun:
def __init__(self, ... |
19340157cb8476bcb38067e8ff6bdf146ab5377b | chepkoy/python_fundamentals | /whileloop.py | 246 | 3.84375 | 4 | # Python while loops
count = 5
while count != 0:
print(count)
count -= 1 # Augmented assignment operator
while True:
print("Looping")
# Breaking Out
while True:
response = input()
if int(response) % 7 == 0:
break |
ec667dfd898237d140b31ebeef4634525d4eeb76 | chepkoy/python_fundamentals | /lists.py | 279 | 3.765625 | 4 | # Mutable sequences of objects
three_numbers = [1, 9, 8]
three_strings = ["apple", "orange", "pear"]
print(three_numbers, three_strings)
print(three_numbers[2])
three_numbers.append(1.983)
print(three_numbers)
# list constructor
construct = list("characters")
print(construct) |
9ee8dddc6393e378280525a1ee34852ab327eb93 | thiagopf/Movie-Website | /media.py | 1,574 | 3.5 | 4 | import webbrowser
class Movie:
def __init__(self, movie_title, storyline, poster_image, trailer_youtube):
"""
Store the arguments
:param movie_title: a string containing the title of the movie
:param storyline: a string containing the storyline of the movie
:para... |
93d656f81678bdaa2e636a99724fc92044b7d617 | doparko/aoc2019 | /day1_code.py | 970 | 3.71875 | 4 | # aoc 2019 day 1 code
import numpy as np
filename = 'day1_input.txt'
dataopen = open(filename)
datin = dataopen.readlines()
def massfuel(mass):
fuel = np.floor(int(mass)/3) - 2
return fuel
def fuelfuel(mass):
tempmass = int(mass)
tots = 0
while (np.floor(tempmass/3) -2) > 0:
tots = tots + (np.f... |
9a38b0a4146440f7c301091cd31997088ecddccf | shikharbhardwaj/tradegame | /src_qac/environment/environment.py | 6,929 | 3.5 | 4 | """ environment.py
Represents the trading environment providing price data, simulating trades and
generating reward signals for the agent.
"""
import numpy as np
def createTimeFeatures(time):
"""Create time features for the given timestamp
Arguments:
time {datetime} -- A datetime object for the tick... |
1e32370d9ec0836c85e17c7f3eb5d21c9203eeca | kartheek527/python_scripts | /scripts/irish_lottery_draw.py | 1,547 | 3.78125 | 4 | """Python script to get the next Irish lottery draw.
The Irish lottery draw takes place twice weekly on a Wednesday and a
Saturday at 8pm. Write a function that calculates and returns the next
valid draw date based on the current date and time and also on an
optional supplied date.
Example: If we provide 2017-4-... |
9ca0c54591b4ae5de938ee91363211a8955a593f | bluethon/leetcode | /111.minimum-depth-of-binary-tree.py | 814 | 3.75 | 4 | #
# @lc app=leetcode id=111 lang=python3
#
# [111] Minimum Depth of Binary Tree
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
# 从... |
87a0631129b875552e84f0af842a05dd4748b631 | bluethon/leetcode | /206.reverse-linked-list.py | 547 | 3.796875 | 4 | #
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 初始化
prev, cur = None, h... |
c9985c24d41005ffec41cbed9f69a77abcfc3298 | azegun/workspace_python | /python_newclass/class/class_ex3.py | 452 | 3.53125 | 4 | # static 메서드
class StringUtils:
@staticmethod
def toCamelcase(text):
words = iter(text.split("_"))
return next(words) + "".join(i.title() for i in words)
@staticmethod
def toSnakecase(text):
letters = ["_" + i.lower() if i.isupper() else i for i in text]
return "".join(l... |
cd8399779d856f85a5ce907223cde5499ee7acdf | azegun/workspace_python | /financial_pandas/arrange.py | 228 | 3.75 | 4 | data = [3, 2, 1, 5, 4]
sorted_data = sorted(data)
print(sorted_data)
data1 =[("000060", 8.25), ("000020", 5.75), ("039490", 1.3)]
print(data1)
# pbr이 낮은 순서대로 정렬
data1.sort(key=lambda x:x[1])
print(data1)
|
ae55aaa82fa270d6dc00f631c771480d269693d1 | azegun/workspace_python | /python_newclass/ex_basic/fx_1.py | 4,277 | 3.5625 | 4 | # def print_coin():
# for i in range(100):
# print("비트코인")
#
#
# print_coin()
# print()
#
#
# def message():
# print("A")
# print("B")
#
#
# message()
# print("C")
# message()
#
# print()
# print("A")
#
#
# def message1():
# print("B")
#
#
# print("C")
# message1()
# print()
def message1():
... |
ccaae0052164e8d294b1a20a08decaa8f6a75f83 | azegun/workspace_python | /python_newclass/exception/exception_div.py | 1,827 | 3.984375 | 4 | # def ten_div(x):
# x = int(input("숫자 입력: "))
# return 10 / x
#
#
# # print(ten_div(2))
# # print(ten_div(0)) # error ZeroDivisionError: division by zero
#
# try:
# x = int(input("숫자 입력: "))
# y = 10 / x
# print(y)
# except:
# print("예외가 발생")
#
# try:
# print(ten_div(x))
# except:
# pr... |
76abc5a4523cf567fa574d8809693a116f2f38b7 | azegun/workspace_python | /python_newclass/tkiner_practice/tkiner_text2.py | 688 | 3.65625 | 4 | from tkinter import *
window = Tk() # tkinter 클래스 선언해주고
# 윈도우 기본 설정
window.title("python txt") # 윈도우 타이틀
window.geometry("640x400+650+380") # 윈도우 사이즈랑, 위치(너비 x 높으 + x좌표 + y좌표)
window.resizable(False, False) # 상하, 좌우 크기 조절 여부
text = Text(window)
text.insert(INSERT, "Hello!!!")
text.insert(END, "..........")
... |
bad16cec4921b10da3d787d6e9dc7d74bb36d069 | azegun/workspace_python | /python_newclass/class/class_ex2.py | 490 | 3.515625 | 4 | class User:
def __init__(self, email, password):
self.email = email
self.password = password
@classmethod
def fromTuple(cls, tup):
return cls(tup[0], tup[1])
@classmethod
def fromDictionary(cls, dic):
return cls(dic["email"], dic["passwrod"])
new = User("test1@tes... |
e2c38b9a4035dc6c612ec6a55054f875d934e313 | azegun/workspace_python | /python_newclass/class/class_person2.py | 714 | 3.90625 | 4 | class Person:
bag = [] # 클래스 변수, 공유해서 쓰는 값
bag_class = []
def __init__(self, name):
self.name = name # 인스턴스 변수, 혼자 사용하는 값
def put_bag(self, stuff):
self.bag.append(stuff)
def bag_class(self, stuff):
Person.bag.append(stuff)
# james = Person("제임쓰~")
# james.put_bag("신의탑"... |
f9ff5d1720db79cffd5311fb804fd3ca6d1dab19 | azegun/workspace_python | /python_newclass/tkiner_practice/tkiner_entry.py | 1,512 | 3.75 | 4 | import tkinter
from math import *
window = tkinter.Tk() # tkinter 클래스 선언해주고
# 윈도우 기본 설정
window.title("python UI") # 윈도우 타이틀
window.geometry("640x400+650+380") # 윈도우 사이즈랑, 위치(너비 x 높으 + x좌표 + y좌표)
window.resizable(False, False) # 상하, 좌우 크기 조절 여부
def calc(event): # event 매개변수가 들어가야지 작동
label.config... |
8b959e7214d29ccd59143745ef5c3ba8f7715e26 | azegun/workspace_python | /python_newclass/tkiner_practice/tkiner_frame.py | 758 | 3.90625 | 4 | from tkinter import *
window = Tk() # tkinter 클래스 선언해주고
# 윈도우 기본 설정
window.title("python txt") # 윈도우 타이틀
window.geometry("640x400+650+380") # 윈도우 사이즈랑, 위치(너비 x 높으 + x좌표 + y좌표)
window.resizable(False, False) # 상하, 좌우 크기 조절 여부
frame1 = Frame(window, relief="solid", bd=2)
frame1.pack(side="left", fill="both", ... |
ffe30d498e54186069dcf521d4469037980aa840 | AndrewJamieson/FI_Module_1 | /Section7/dsc-1-07-06-object-oriented-attributes-with-functions-lab-online-ds-pt-041519/school.py | 841 | 3.625 | 4 | class School():
def __init__(self, name=None):
self.name = name
self.roster = {}
def roster(self):
return self.roster
def add_student(self, name, grade):
if grade in self.roster:
self.roster[grade].append(name)
else:
self.roster[... |
c74194ef412726b64475ee1de814336caf80c670 | sundarum/ml-challenge-expenses | /Spark_Design/Data_to_Spark_Utils.py | 1,176 | 3.859375 | 4 | # This file has utility functions to load csv files and perform the following functions
#
# 1. Load CSV files into Spark and provide SQL based data extraction capability
# 2. Helps in dropping colums from a dataset
#
# More capabilities will be added as the complexity of data proessing increases
import pyspark
# Thi... |
88f33a912f1c8a275d38eae499dfa02df2f1f2e4 | ajayrfhp/kaggle | /titanic/logistic.py | 782 | 3.578125 | 4 | import numpy as np
import pandas as pd
from numpy import *
from math import e,log
def sigmoid(y):
return 1.0 / (1.0 + np.exp(np.multiply(-1.0, y)))
######################CLEANING DATA
data=np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
n=data.shape[0]
m=data.shape[1]+1
iterations=5000
learningRate=0.15
target=np.... |
f279a594a986076b96993995f5072bcc383244d6 | singh-vijay/PythonPrograms | /PyLevel3/Py19_Sets.py | 288 | 4.15625 | 4 | '''
Sets is collection of items with no duplicates
'''
groceries = {'serial', 'milk', 'beans', 'butter', 'bananas', 'milk'}
''' Ignore items which are given twice'''
print(groceries)
if 'pizza' in groceries:
print("you already have pizza!")
else:
print("You need to add pizza!") |
3619e25b4e1ffe120534cc5b565cf1dc5d8ac7a3 | AriannaB99/MinEditDistance | /MED.py | 4,407 | 4.0625 | 4 |
'''Recursive method to compute the minimum edit distance between two words
A -> 1st word
B -> 2nd word (misspelled word)
i -> current place in word A
j -> current place in word B
returns the minimum edit distance between the two words'''
def MinDistRecursion(A, B, i, j):
'''If one of the words is longer than the o... |
96ee1777becc904a39b140c901522881b2942cee | WavingColor/LeetCode | /LeetCode:judge_route.py | 1,034 | 4.125 | 4 | # Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
# The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (d... |
6afcf0aaea0524fd08d4d7840d8bbe0ea058acbc | danishprakash/courses | /atbs/c5p2-fantasy_game_2.py | 544 | 3.953125 | 4 | def displayInventory(invent):
totalItems = 0
print('Inventory:')
for k,v in invent.items():
print(v, k)
totalItems += v
print("The total number of items:", totalItems)
def addToInventory(inventory, addedItems):
# your code goes here
for item in addedItems:
if item in inventory.keys():
inventory[item... |
5eaddedee16806b9bf2b3cde6339cda4f6b2cbbf | danishprakash/courses | /atbs/c6-pw.py | 456 | 3.96875 | 4 | #! python3
# pw.py a script for storing passwords
PASSWORDS = {'zucker': '34rly',
'email' : 'l4t3',
'luggage': '0n3'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Enter the correct format for usage')
sys.exit()
account = sys.argv[1]
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
prin... |
7c2d66fc0d548347d434c864b5970fef42d2d4a2 | danishprakash/courses | /coursera-uom/Part1/p1w6a46.py | 282 | 3.78125 | 4 | def computepay(h,r):
global hrs
if hrs > 40:
ovt = hrs - 40
hrs = hrs - ovt
gpa = hrs * rph
gpa += ovt * 1.5 * rph
return gpa
hrs = float(input("Enter Hours:"))
rph = float(input("Enter Rate per hour: "))
p = computepay(hrs,rph)
print(p) |
4aa0881d535df447bf0e5909528fd55f6f5e9a79 | danishprakash/courses | /atbs/c5-tictactoe.py | 1,199 | 3.890625 | 4 | theBoard = {'1': ' ', '2': ' ', '3': ' ', '4': ' ', '5':
' ', '6': ' ', '7': ' ', '8': ' ', '9': ' '}
def drawBoard(board):
print(board['1'] + '|' + board['2'] + '|' + board['3'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['7'] + '|' + ... |
7a2bead65dc402857dfcd36975770f2f3a787234 | danishprakash/courses | /coursera/pset1/problem1_3.py | 131 | 3.84375 | 4 | def problem1_3(n):
my_sum = 0
for num in range(n+1):
my_sum += num
print (my_sum)
#x = input()
#problem1_3(x)
|
1a5f19f97681fab7ff64c914c76380ecf10ba964 | zjq02010/LearnPython | /venv/Lib/site-packages/modis/discord_modis/modules/tableflip/api_flipcheck.py | 1,848 | 4.09375 | 4 | def flipcheck(content):
"""Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text
"""
# Prevent tampering with flip
punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─"""
tamperdict =... |
7368756255009a233449214b6636138db7f31582 | mattandersoninf/AlgorithmDesignStructures | /Trees/Python/BinarySearchTree_with_defaultdict.py | 4,168 | 4.125 | 4 | from collections import defaultdict
class BST:
def __init__(self):
# Use a defaultdict with default value [None, None] to store the BST nodes
self.tree = defaultdict(lambda: [None, None])
def insert(self, key):
if self.tree[key][0] is None:
# If the current node is empty, s... |
7d16110d7acabae6e223b512c743993475f8f2b9 | mattandersoninf/AlgorithmDesignStructures | /Graphs/Graph_w_heap_libraries.py | 2,831 | 3.8125 | 4 | from heapq import heappop, heappush
class Graph:
def __init__(self):
self.graph = {}
def add_vertex(self, vertex):
if vertex not in self.graph:
self.graph[vertex] = {}
def add_edge(self, source, destination, weight):
if source in self.graph and destination in self.grap... |
f084aa9b24edc8fe1b0d87cd20beee21288946ad | mattandersoninf/AlgorithmDesignStructures | /Points/Python/Point.py | 1,083 | 4.15625 | 4 | # python impolementation of a point
# a point in 2-D Euclidean space which should contain the following
# - x-coordinate
# - y-coordinate
# - moveTo(new_x,new_y): changes the coordinates to be equal to the new coordinates
# - distanceTo(x_val,y_val): this function returns the distance from the current point to some oth... |
46bf8bfbd8f3e32cb377bde5d46cd702f7296b43 | jnrizvi/CMPUT-355 | /assignment4/gui_minesweeper.py | 10,345 | 3.59375 | 4 | #icons from https://github.com/HaikuArchives/Minesweeper
'''
Beginner level has 5 mines
Intermediate level has 10 mines
Expert level has 40 mines
'''
from tkinter import *
from PIL import ImageTk,Image
from tkinter import ttk
import random
from tkinter import messagebox
import time
import sys
import platform
sys.setr... |
36fa9cf3660aee4033a041ec3ae81629ed4bf0c6 | Akola-Mbey-Denis/Data-Structures-and-Algorithms-in-Python | /squareroot.py | 167 | 3.65625 | 4 | import math
def squareRoot(number):
return math.pow(number,0.50)
def Power(number,n):
return number**n
if __name__ =="__main__":
print( Power(2,6))
|
d6a7edc815b5a576d712d41f697cab2821319411 | Akola-Mbey-Denis/Data-Structures-and-Algorithms-in-Python | /missingNumber.py | 627 | 3.953125 | 4 | def findMissingNumber(array):
for k in range(0,len(array)+1):
if k not in array:
return k
def reverseInteger(number):
reverse=""
if number<0:
reverse=str(abs(number))
return "-"+ reverse[::-1]
else:
return reverse[::-1]
if __name__ =="__main_... |
e1b777fbda50499e65e468f4feaa36ff656a2fb8 | Akola-Mbey-Denis/Data-Structures-and-Algorithms-in-Python | /magicGame.py | 706 | 3.796875 | 4 | import random
class DiceGame:
'''
Multi-slided die
Instance variable
current value
num_sides
'''
def __init__(self,num_slides):
self.num_slides=num_slides
self.current_value=self.roll()
def roll(self):
self.current_value=random.randrange(1,self.num_slides+1)
... |
8ad29cd9456fee2414878d84224927048ac374e2 | Akola-Mbey-Denis/Data-Structures-and-Algorithms-in-Python | /recursive.py | 541 | 4.09375 | 4 | def factorial(number):
if number ==1 or number==0:
return 1
else:
return factorial(number-1)*number
def reverseList(list_data):
if len(list_data)==1:
return list_data
else:
return [list_data[-1]] + reverseList(list_data[:-1])
def fibonnaci(number):
if numb... |
91eb26b11d3a5839b3906211e3e10a636ac0277b | Exia01/Python | /Self-Learning/testing_and_TDD/basics/assertions.py | 649 | 4.28125 | 4 | # Example1
def add_positive_numbers(x, y):
# first assert, then expression, message is optional
assert x > 0 and y > 0, "Both numbers must be positive! -> {}, {}".format(
x, y)
return x + y
# test cases
print(add_positive_numbers(1, 1)) # 2
add_positive_numbers(1, -1) # AssertionError: Both ... |
b48b6b8fb19e8ab7546a817683bebce140c2d50c | Exia01/Python | /Self-Learning/dictionaries/dictionary_comprehension.py/ASCII_dictionary_code.py | 185 | 4.125 | 4 | # Create a dictionary with the Character letters using chr() in python from numbers 65-90
start = 65
end = 91
abc_list = {num: chr(num) for num in range(start, end)}
print(abc_list)
|
dbdf00041078931bec33a443fbd330194cf60ec0 | Exia01/Python | /Self-Learning/lists/slices.py | 361 | 4.28125 | 4 | items = [1, 2, 3, 4, 5, 6, ['Hello', 'Testing']]
print(items[1:])
print(items[-1:])
print(items[::-1])# reverses the list
print(items[-3:])
stuff = items[:] # will copy the array
print(stuff is items) # share the same memory space?
print(stuff[0:7:2])
print(stuff[7:0:-2])
stuff[:3] = ["A", "B", "C"]
print(stuf... |
9c9f143fd94186c089ee4eec0d025834d6ddb7f2 | Exia01/Python | /Self-Learning/File IO/exercise/find_and_replace/exercise.py | 713 | 3.953125 | 4 | # find_and_replace
# Write a function called nd_and_replace, which takes in a file name, a word to search for, and a replacement word. Replaces all instances
# of the word in the file with the replacement word.
from pathlib import Path
data_folder = Path(
"c:/Users/sixgg/Documents/GitHub/Python/Self-Learning/File ... |
b5bfdc8e7e8907725abca48426ea1bf2627691c3 | Exia01/Python | /Self-Learning/working CSV Files and pickling/pickling/pickling-example.py | 1,305 | 3.5 | 4 | import pickle
from csv import reader, DictReader
from pathlib import Path
data_folder = Path(
r"C:\Users\sixgg\Documents\GitHub\Python\Self-Learning\working CSV Files and pickling\pickling")
filename = "pets.pickle"
file = data_folder / filename # generates an instance each time it is used
class Animal:
def... |
1019a0ef7bc404f04f393370b7ee5e3c42c5c10d | Exia01/Python | /Self-Learning/decorators/basics/higher-order.py | 320 | 3.859375 | 4 | # We can pass funcs as args to other funcs
def sum(n, func):
total = 0
for num in range(1,n+1):
total += func(num)
return total
def square(x):
return x*x
def cube(x):
return x*x*x
def half(x):
return x/2
#sum either a cube
print(sum(3,cube)) #passing cube function
print(sum(3,square))
print(sum(4,half))
|
64878d4e5e228f2c45c578ea44614fcb5dc67e1b | Exia01/Python | /Self-Learning/built-in_functions/abs_sum_round.py | 712 | 4.125 | 4 | #abs --> Returns the absolute value of a number. The argument may be an integer or a floating point number
#Example
print(abs(5)) #5
print(abs(3.5555555))
print(abs(-1324934820.39248))
import math
print(math.fabs(-3923)) #treats everything as a float
#Sum
#takes an iterable and an optional start
# returns the sum... |
9da09b39cda66f4fe2aa74badbdbc4024bdc5fcd | Exia01/Python | /Self-Learning/functions/basics_2/prefixes.py | 520 | 3.875 | 4 | #write a function called "combine_words" which accepts a single string and a prefix
#should return the word with the prefix together
def combine_words(word, **kwargs):
if 'prefix' in kwargs:
prefix = kwargs['prefix']
return f'{prefix}{word}'
elif 'suffix' in kwargs:
suffix = kwargs['suf... |
ee47c13e5b6e12c57c5d9f9e435cfd074dcacbf1 | Exia01/Python | /Self-Learning/dictionaries/excersises/state_abbreviations.py | 523 | 3.890625 | 4 | # covert two list to
abbreviations = ["CA", "NJ", "RI"]
states = ["California", "New Jersey", "Rhode Island"]
if len(abbreviations) != len(states):
raise Exception('Not the same length')
combination = {states[i]: abbreviations[i] for i in range(0, len(abbreviations))}
print(combination)
#using Zip
#https://www.... |
278dd78ed805a27e0a702bdd8c9064d3976a2f78 | Exia01/Python | /Python OOP/Vehicles.py | 2,884 | 4.21875 | 4 | # file vehicles.py
class Vehicle:
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
def drive(self, miles):
self.mileage += miles
return self
... |
9176cb03f9915895da8161e51a2de2e32ce08286 | Exia01/Python | /Self-Learning/loops/guessing_gamev0.py | 503 | 4.09375 | 4 | import random
random_number = random.randint(1,10) # numbers 1 - 10
guess = None
while guess != random_number:
guess = input("Pick a number from 1 to 10: ")
guess = int(guess)
if guess < random_number:
print("TOO LOW!")
elif guess > random_number:
print("TOO HIGH!")
else:
print("YOU WON!!!!")
print(rando... |
65a6a75a451031ae2ea619b3b8b2210a44859ca3 | Exia01/Python | /Self-Learning/Algorithm_challenges/three_odd_numbers.py | 1,607 | 4.1875 | 4 | # three_odd_numbers
# Write a function called three_odd_numbers, which accepts a list of numbers and returns True if any three consecutive numbers sum to an odd number.
def three_odd_numbers(nums_list, window_size=3):
n = window_size
results = []
temp_sum = 0
#test this check
if window_size > len... |
66ebbe4465ff1a433f5918e7b20f019c60b496ae | Exia01/Python | /Self-Learning/lambdas/basics/basics.py | 725 | 4.25 | 4 | # A regular named function
def square(num): return num * num
# An equivalent lambda, saved to a variable but has no name
square2 = lambda num: num * num
# Another lambda --> anonymous function
add = lambda a,b: a + b #automatically returns
#Executing the function
print(square(7))
# Executing the lambdas
print(square... |
fc398484bc9b09d4cb0dc055cffd79118cb481bc | Exia01/Python | /Self-Learning/testing_and_TDD/Unit testing/other_types_of_assertions/test.py | 2,053 | 3.640625 | 4 | # To run we only have to execute test.py or -v at end for comments or more info
import unittest
from activities import eat, nap, is_funny, laugh # importing the functionalities
# setting up the test
class ActivityTests(unittest.TestCase): # Can be named anything. Inherits from class
def test_no_eat(self):
... |
3fb3240d55819af7e305b6cb93da4434adf37b07 | Exia01/Python | /Self-Learning/functions/basics/return.py | 525 | 3.90625 | 4 | number = 9
def print_square_number(number):
number ** 2
#this does not return anything so nothing will be sent out
print_square_number(number)
nums = [1, 2, 3, 4]
def print_square_of_7(): #This function does not return anything
print(7**2)
print_square_of_7()
def square_of_7():
print("I AM BEFOR... |
40be281781c92fc5417724157b0eebb2aefb8160 | Exia01/Python | /Self-Learning/functions/operations.py | 1,279 | 4.21875 | 4 | # addd
def add(a, b):
return a+b
print(add(5, 6))
# divide
def divide(num1, num2): # num1 and num2 are parameters
return num1/num2
print(divide(2, 5)) # 2 and 5 are the arguments
print(divide(5, 2))
# square
def square(num): # takes in an argument
return num * num
print(square(4))
print(square(... |
44697f20d48ba5522c2b77358ad1816d6af2bb96 | Exia01/Python | /Self-Learning/built-in_functions/exercises/sum_floats.py | 611 | 4.3125 | 4 | #write a function called sum_floats
#This function should accept a variable number of arguments.
#Should return the sum of all the parameters that are floats.
# if the are no floats return 0
def sum_floats(*args):
if (any(type(val) == float for val in args)):
return sum((val for val in args if type(val)==f... |
f8b7cd07614991a3ae5580fd2bd0458c730952ee | Exia01/Python | /Self-Learning/functions/exercises/multiple_letter_count.py | 428 | 4.3125 | 4 | #Function called "multiple_letter_count"
# return dictionary with count of each letter
def multiple_letter_count(word = None):
if not word:
return None
if word:
return {letter: word.count(letter) for letter in word if letter != " "}
#Variables
test_1 = "Hello World!"
test_2 = ... |
704b448f0e2f5143331193c07c586c25bc2eb992 | Exia01/Python | /Self-Learning/timezones/testing_time_zones.py | 865 | 3.640625 | 4 | import datetime
import pytz
dt = datetime.datetime(2016, 7, 8, 11, 30, 45, tzinfo=pytz.UTC)
print(dt)
dt_now = datetime.datetime.now(tz=pytz.UTC)
print(dt_now)
#both print utc but not localized
# same as dt_now
dt_utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
print(dt_utcnow) #current utcnow but not... |
0d7c1fc412732aedff3df46f8c4750feffae0718 | Exia01/Python | /Self-Learning/dictionaries/using_with.py | 580 | 3.9375 | 4 | # does a dictionary have a key?
instructor = {
'name': 'John',
'has_pets': False,
'age': 18,
'favorite_language': 'Python',
'favorite_color': 'Purple',
'favorite_sport': 'Soccer!',
'test': [1, 2, 3, 4, 5],
}
print("name" in instructor) # True
print(1 in instructor['test']) # True
if 18 i... |
4a056b406a733461216be2cf5754f571ed88bb42 | Exia01/Python | /Self-Learning/File IO/exercise/copy_task/exercise.py | 976 | 3.796875 | 4 | # Write a function called copy, which takes in a le name and a new le name and copies the contents of the rst le to the second le.
# (Note: we've provided you with the rst chapter of Alice's Adventures in Wonderland to give you some sample text to work with. This is
# also the text used in the tests.
# 1 copy('story.tx... |
7ad9a8f7530f0636495f8b65372cccd4fe050c24 | Exia01/Python | /Self-Learning/OOP/part2/exercises/multiple_inheritance.py | 784 | 4.15625 | 4 | class Aquatic:
def __init__(self, name):
self.name = name
def swim(self):
return f'{self.name} is swimming'
def greet(self):
return f'I am {self.name} of the sea!'
class Ambulatory:
def __init__(self, name):
self.name = name
def walk(self):
return f'{self.... |
a57c5d8b32f451b26b708969a57644cd63d075af | shvnks/comp354_calculator | /src/FunctionFactorial.py | 956 | 3.53125 | 4 | from FunctionBase import FunctionBase
from CalculationErrorException import CalculationErrorException
class FunctionFactorial(FunctionBase):
'''Class used to calculate the factorial function.'''
def __init__(self, x: int) -> None:
'''Constructor.'''
super(FunctionFactorial, self).__init__()
... |
bea429f7de9a604e1d92b4506038dd17fef4c7eb | shvnks/comp354_calculator | /src/InterpreterModule/Tokens.py | 936 | 4.28125 | 4 | """Classes of all possible types that can appear in a mathematical expression."""
from dataclasses import dataclass
from enum import Enum
class TokenType(Enum):
"""Enumeration of all possible Token Types."""
"Since they are constant, and this is an easy way to allow us to know which ones we are manipulating.... |
aa7556b840c4efa4983cd344c69008a0f342f528 | shvnks/comp354_calculator | /src/functionsExponentOldAndrei.py | 2,603 | 4.21875 | 4 | # make your functions here
def exponent_function(constant, base, power):
total = base
if power % 1 == 0:
if power == 0 or power == -0:
return constant * 1
if power > 0:
counter = power - 1
while counter > 0:
total *= base
co... |
bd2ccc9f7bb13894e436b2c7ad4d89a19977d312 | shvnks/comp354_calculator | /src/Interpreter/ComputeExpression.py | 5,486 | 3.96875 | 4 | """Give the answer to the tree."""
from Nodes import AddNode, MinusNode, PositiveNode, NegativeNode, MultiplyNode, DivideNode, PowerNode, FactorialNode, TrigNode, LogNode, SquareRootNode, GammaNode, StandardDeviationNode, MADNode
import math
import sys
sys.path.insert(0, 'C:\\Users\\Nicholas\\Desktop\\COMP354\\comp354_... |
6a92d99f431a4043218bea9e20e129181ccf7b42 | csyouk/data-structure-coursera- | /week1/pa1/tree_height/tree-ver4.py | 1,114 | 3.828125 | 4 | # python3
import sys
import threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeHeight:
def read(self):
self.n = int(sys.stdin.readline())
self.parent = list(map(int, sys.stdin.readline().split()))
... |
8face047d25661db2f4a5ed4faccf7036977c899 | y0m0/MIT.6.00.1x | /Lecture5/L5_P8_isIn.py | 854 | 4.28125 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Base case: If aStr is empty, we did not find the char.
if aStr == '':
return False
# Base case: if aStr is of length 1, just see if t... |
5146ede0491d3046a242ff44f3cf4ea4dec55386 | y0m0/MIT.6.00.1x | /ProblemSet/ProblemSet4/ps4b.py | 6,440 | 4.09375 | 4 | from ps4a import *
import time
#
#
# Problem #6: Computer chooses a word
#
#
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
... |
849bba2e11076003552bfa82571078c0ea151eb5 | y0m0/MIT.6.00.1x | /Lecture4/L4_P11_isVowel2.py | 219 | 4.03125 | 4 | def isVowel2(char):
'''
char: a single letter of any case
returns: True if char is a vowel and False otherwise.
'''
vowels = ('A','E','I','O','U','a','e','i','o','u')
return char in vowels
|
d23f7b3b6f6c380b5856ed3c47eb4caaa9028016 | pickledgator/tictactoe | /tictactoe.py | 5,155 | 4.375 | 4 | #!/usr/bin/env python
import itertools
""" Tic Tac Toe
Allows for two players to alternate turns placing their token
in a specific location on the game board. The game board consists
of 9 possible play locations, indexed 0-8.
0 1 2
3 4 5
6 7 8
Players place their token on the board with... |
8219b2e1ce1f3488383af91abc0936d876776901 | zhangdavids/offer_py | /029.py | 678 | 3.546875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if rotateArray == []:
return 0
_len = len(rotateArray)
left = 0
right = _len - 1
while left <= right:
mid = int((left + right) >> 1)
... |
ae7a22fcd5f08f669f5087618c0ac4c770d56071 | zhangdavids/offer_py | /015.py | 255 | 3.59375 | 4 | # -*- coding:utf-8 -*-
# 翻转单词顺序列
class Solution:
def ReverseSentence(self, s):
# write code here
ret = s.split(" ")
ret.reverse()
return ' '.join(ret)
print(Solution().ReverseSentence("i love lily"))
|
4a442570e403106067cd7df096500e2d34099819 | ge01/StartingOutWithPython | /Chapter_02/program_0212.py | 236 | 4.1875 | 4 | # Get the user's first name.
first_name = raw_input('Enter your first name: ')
# Get the user's last name.
last_name = raw_input('Enter your last name: ')
# Print a greeting to the user.
print('Hello ' + first_name + " " + last_name)
|
890970a087b0d0713bd6064d22d5db9f58aa06ac | Tamini/UWCourseGooseRepo | /data/getFaculties.py | 1,233 | 3.75 | 4 | #@Author Raunaq Suri
#@Date December 31, 2013
#Retrieves all the faculties of Waterloo
import json
import urllib.request
import urllib.parse
from pprint import pprint
print("Getting all the faculties of UW")
baseUrl = "https://api.uwaterloo.ca/v2/codes/groups.json"
api_key = input("Enter the api key here: ") #asked... |
9cb321f000f1dda865ea919f3cd8eb92979331a9 | XantanasZ80/FromZEROtoHERO | /spock_Xantanas_Z80.py | 1,708 | 3.953125 | 4 | import random
print("Piedra, papel, tijeras, lagarto, spock!")
salir = False
while not salir:
mi_jugada = input("Elige: ")
maquina = random.randint(1,5)
if maquina == 1:
su_jugada = "piedra"
elif maquina == 2:
su_jugada = "papel"
elif maquina == 3:
su_jugada = "tijeras"
e... |
d38fbf3290696cc8ca9ae950fd4fe81c0253bbfd | jiresimon/csc_lab | /csc_ass_1/geometric_arithmetic/geo_arithmetic_mean.py | 1,066 | 4.25 | 4 | from math import *
print("Program to calculate the geometric/arithmetic mean of a set of positive values")
print()
print("N -- Total number of positive values given")
print()
total_num = int(input("Enter the value for 'N' in the question:\n>>> "))
print()
print("Press the ENTER KEY to save each value you enter...")
... |
3000d969039c336a12b1ba2abb3df8d40c7cc3f4 | liuhuiwisdom/edx | /cs1156x/week9/zplay/kmeans-0.1/toolbox/clustering/kmeans.py | 3,444 | 3.75 | 4 | """
kmeans.py
Clusters a set of data points using Lloyd's algorithm, as follows:
- Given k initial cluster centers and a set of data points
- Repeat
- Assign each point to one of k clusters by distance from cluster centers,
adding to variance each time
- if variance is le... |
daa8233350c43e2884887521bcf8d9291e7129b7 | cesarbruschetta/analyze-kart-log | /analyze_kart_log/utils.py | 2,799 | 3.6875 | 4 | """ module to utils function """
from datetime import datetime, timedelta
def str2datetime(str):
""" convert string to datetime obj """
return datetime.strptime(str, "%H:%M:%S.%f")
def str2float(str):
""" convert string to float obj """
return float(str.replace(",", "."))
def str2timedelta(str):
... |
c91d6355a23c2420edc58756afd7f1314532ded5 | mohsinchougale/Python-Programming | /Numpy and Matplotlib/Student.py | 359 | 3.609375 | 4 | import numpy as np
data_types = [('name', 'S15'), ('height', float), ('class', int)]
students = [('Mohsin', 181.2, 12), ('Ameya', 175.9, 11),('Yash', 133.4, 7), ('Palaash', 120.1, 11)]
students = np.array(students, dtype = data_types)
print("Original array : ")
print(students)
print("On sorting by height : ")
pri... |
c26f1375db2c34e2d7d300bf7504e996e3b188ad | mohsinchougale/Python-Programming | /Elementary/Permutation.py | 225 | 3.671875 | 4 | #To find nPr (permutations) using while loop
n=int(input("Enter n \n"))
r=int(input("Enter r \n"))
a=1
d=n
while(n>0):
a*=n
n-=1
b=1
c=d-r
while(c>0):
b*=c
c-=1
ans=int(a/b)
print("The number of permutations =",ans)
|
08c70acbdf26766d384f6760bd7bb60f81f7c686 | basic-shadow/pathfinding-maze_generator-algorithms-python | /recursive_backtracking_maze_generator.py | 3,150 | 3.546875 | 4 | import random
import pygame
class MazeGenerator:
def __init__(self, columns, rows, grids, draw):
self.draw = draw
self.columns = columns
self.rows = rows
self.visitedGrids = []
self.grids = grids
self.stack = []
self.clock = pygame.time.Clock()
def divid... |
6f79a3189064b30e40bf614f1815bbd0ee1f6222 | suvojitd79/machine-learning | /LR/y=mx+c.py | 580 | 3.59375 | 4 | '''
given a list of brain-body weights. Predict the body weight for a
given brain value. y = mx + c
'''
import numpy as np
from sklearn import linear_model
import pandas as pd
import matplotlib.pyplot as plot
#data-set
data = pd.read_fwf('data.txt')
x = data[['Brain']]
y = data[['Body']]
#train the m... |
7e49e5b3ccb1db088bd837a6a09f08c4caebf805 | jeangiraldo/Python-Curso | /Número primo.py | 520 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 19:22:26 2020
@author: CEC
"""
def isPrime(num):
#Función que determina si un número es primo
if num<2:
return False
elif num==2:
return True
else:
for in range (1,20):
if isPrime(i+1):
... |
bcb4dd22aab6768e2540ccd3394a8078b8b38490 | RazvanCimpean/Python | /BMI calculator.py | 337 | 4.25 | 4 | # Load pandas
import pandas as pd
# Read CSV file into DataFrame df
df = pd.read_csv('sample 2.csv', index_col=0)
# Show dataframe
print(df) |
ebe140aabb1cb51378395dee84e2e4fde8041b04 | Roger6six/Paradigmas | /Exe10.py | 113 | 4.1875 | 4 | nome = ""
s = ""
nome = input("Informe o nome:")
for letra in reversed(nome):
s+=letra
print(s.upper()) |
a9cfa9463756a988acde76df57da14596c800169 | DebbyMurphy/project2_python-exercises | /wk4-exercises_lists/python-lists_q3-append.py | 487 | 4.5625 | 5 | # Q3) Ask the user for three names, append them to a list, then print the list.
# Input
# Izzy
# Archie
# Boston
# Output
# ["Izzy", "archie", "Boston"]
nameslist = []
firstname = input("Hi, what's your first name?! ")
middlename = input(f"Cool, hey {firstname} what about your middle name? ")
lastname = input(f"Th... |
526c14ac21cb62e89b4e50617a5b03c6c65954be | mbardoe/VotingSIm | /Election.py | 2,309 | 3.828125 | 4 | __author__ = 'mbardoe'
class Election(object):
def __init__(self, candidates):
self.ballots = []
self.candidates = candidates
def addBallot(self, ballot):
self.ballots.append(ballot)
def candidateCount(self):
results = {}
numVotes = float(len(self.ballots))
... |
efff83e99f31ee05f88e2bc99c2d19d2a9f4db7f | Debonairme/Rhine.github.io | /第一题:体重指数.py | 187 | 3.65625 | 4 | w=50
h=1.67
t=w/(h**2)
if t<18:
print("低体重")
elif t>=18 and t<=25:
print("正常体重")
elif t>25 and t<=27:
print("超重体重")
else:
print("肥胖")
|
8ef5be3c6d08a6e3177c751ed8112824ac370475 | vkchiu08/sc-projects | /stanCode_Projects/boggle_game_solver & anagram/anagram.py | 2,992 | 4 | 4 | """
File: anagram.py
Name: Victoria
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each w... |
60c66319b64fc3ecb5cc17bb9feadbfdfa4ede7c | Kenndal/DBProject | /interface/tools/time_converter.py | 359 | 3.59375 | 4 |
def time_converter(_time):
'09:59:14'
_hh = _time[0:2]
_mm = int(_time[3:5])
mm = float(_mm)/60
if mm < 0.1:
mm = '0' + str(mm*10)[0:1]
else:
mm = str(mm*100)[0:2]
new_time = _hh + '.' + mm
return float(new_time)
if __name__ == '__main__':
_time = '09:07:14'
ke... |
b60dcb37c6e84f642efc820eb82a0c5f057306da | KudynDmytro/Practice | /hw12.py | 700 | 3.984375 | 4 | # Напишите функцию, которая бы вытащила из произвольного текста
# все номерные знаки Украины используя регулярные выражения.
# За стандарты номерных знаков примем AА1234AА, 11 123-12АА, а1234АА.
# Их намного больше, но вам достаточно этих.
import re
def num():
s = input('Enter:')
shab1 = re.findall(r'[А-ЯA-Z]... |
79f88ee9f34f4935fa863328da892c611cefb1fe | Roshini28/pythonpgm | /hunter2.py | 152 | 3.53125 | 4 | pe1=int(input())
qe1=list(map(int,input().split()))
qe1.sort()
qe1.reverse()
if qe1[0]==0:
print(0)
else:
for j in qe1:
print(j,end='')
|
b1db6cc93c5a8c080fd78145169504dfe7a2a387 | neerajahuja0104/pythonzoomclass | /py_tasks/Task4.py | 3,126 | 3.859375 | 4 | # TASK 4
# 1
def rev(a2):
return a2[::-1]
b = input("Enter a string to reverse:")
c = rev(b)
print(c)
# 2
def ques2(d1):
upr = 0
lwr = 0
for i1 in d1:
if i1.isupper() == 1:
upr += 1
elif i1.islower() == 1:
lwr += 1
return upr, lwr
e = input("Enter a str... |
5455a86da41fc3ced9f7882f442625947ab71c3c | ReachAayush/ctci | /1_5.py | 766 | 3.640625 | 4 | def compress(x, y = "", l = 0):
print "x = ", x, " y = ", y, " lx = ", l, " ly = ", len(y)
if x == "":
if len(y) > l:
return decompress(y)
else:
return y
elif len(x) == 1:
if y == "":
return x
elif x == y[-2]:
y += str(int(y[-1]) + 1)
y = y[:-2] + y[-1]
return compress("", y, l + 1)
else:... |
d8c212a8290b9441254d88d11f30aacc24694bc0 | HanhKieu/Hangman-Python | /hangman.py | 2,625 | 4.0625 | 4 | #!/usr/bin/python3
import random
HANGMAN = (
"""
____________
|
|
|
|
|
|
|___________
""",
"""
____________
| |
|
|
|
|
|
|___________
""",
"""
____________
| |
| 0
|
|
|
|
|___________
""",
"""
____________
| |
| 0
| /
|
|
|
|___________
""",
"""
____________
| |
| 0
| / \\... |
83e386a5c63cbd9696b0fa7ce04ca9ac248b6555 | prabhakarchandra/python-samples | /Question4.py | 694 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 11:08:55 2019
@author: v072306
"""
# Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
# Suppose the following input is supplied to the program:
# 34,67,55,33,12,98
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.