blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7173d7bb39a40e9c8920688db1fb44c3a5d10c57 | DarkMemem/Homework | /HomeworkLesson3/three_digit_number.py | 184 | 4.125 | 4 | number = int(input("Please enter three-digit number: "))
dig1 = number % 10
dig2 = number // 10 % 10
dig3 = number // 100
print("Your number:", dig1 * 100 + dig2 * 10 + dig3, sep="")
|
71e04911e56364b63e6b0e37b88e147168ab44c3 | vrastello/Data-Structures---all | /CS 261/HW2/queue_da.py | 2,281 | 4.1875 | 4 | # Course: CS261 - Data Structures
# Student Name: Vincent Rastello
# Assignment: A2, Dynamic Array and ADT's Implementation
# Description: Queue ADT, has methods to enqueue or dequeue, uses dynamic array ADT
# Last revised: 02-03-21
from dynamic_array import *
class QueueException(Exception):
"""
Custom exce... |
6a1894e43af5cdea4661ddd5df2f0587cb9d19ca | vrastello/Data-Structures---all | /CS 261/HW4/bst.py | 22,149 | 3.875 | 4 | # Course: CS261 - Data Structures
# Student Name: Vincent Rastello
# Assignment: 4
# Description: Binary Search Tree
class Stack:
"""
Class implementing STACK ADT.
Supported methods are: push, pop, top, is_empty
DO NOT CHANGE THIS CLASS IN ANY WAY
YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS... |
38d3047d956b4487183950103cf7d55821958990 | ifamojuro/bootcamp-python | /exercises-spellchecker/dictionary.py | 1,336 | 4.25 | 4 | """
We represent an English dictionary by using a python set
(don't confuse our English definition of dictionary
with a python dictionary here--anytime you see the word
"dictionary", we mean English dictionary).
"""
def load(dictionary_name):
"""
Opens the file called `dictionary_name` and returns
the set... |
3ec6724dc0917c0086cf711eb73427e53d6a3cd5 | navinamahesh/machine-learning-classifier | /run.py | 6,259 | 3.828125 | 4 | import json
import csv
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler, RobustScaler
# Config Variables
NUM_COLS = 8 # The number of columns in the original data set. Used to discard the original columns when extracting features.
NUM_RECS = 100 # The number of recommendations to g... |
c99c31572e16c0d8b8db8733aa0d47d578245892 | suxian06/leetcode | /735.AsteroidCollision.py | 968 | 3.609375 | 4 | # Runtime: 92 ms, faster than 99.73% of Python3 online submissions for Asteroid Collision.
# Memory Usage: 13.9 MB, less than 25.00% of Python3 online submissions for Asteroid Collision.
# updated using stack
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
... |
655e44dc042d859814d6a507eba5b71cadbdd694 | suxian06/leetcode | /912.SortanArray.py | 1,563 | 3.9375 | 4 | # use merge sort
# Runtime: 456 ms, faster than 12.03% of Python3 online submissions for Sort an Array.
# Memory Usage: 19.3 MB, less than 92.86% of Python3 online submissions for Sort an Array.
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def merge(a,b):
res = []
... |
6f35dc2e35bc9fb07107081cc24cc14b894a708b | suxian06/leetcode | /112.PathSum.py | 898 | 3.90625 | 4 | # Runtime: 40 ms, faster than 92.73% of Python3 online submissions for Path Sum.
# Memory Usage: 14.6 MB, less than 100.00% of Python3 online submissions for Path Sum.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.ri... |
44f16dcf0aa61beb3277384617249fd8c19ee53b | suxian06/leetcode | /1252.CellswithOddValuesinaMatrix.py | 1,459 | 3.71875 | 4 | # Runtime: 52 ms, faster than 38.69% of Python3 online submissions for Cells with Odd Values in a Matrix.
# Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Cells with Odd Values in a Matrix.
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
empty... |
008584df358750864f877fbb85aa12278b180edf | suxian06/leetcode | /2.AddTwoNumbers.py | 1,419 | 3.625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
prev = ListNode(0)
ans = prev
tmp = 0
while l1 and l2:
v... |
ff41a5a6c670e34735238c6a15071ca4a167d59b | suxian06/leetcode | /54.SpiralMatrix.py | 1,525 | 3.546875 | 4 | # Runtime: 36 ms, faster than 74.13% of Python3 online submissions for Spiral Matrix.
# Memory Usage: 13.8 MB, less than 8.70% of Python3 online submissions for Spiral Matrix.
#
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0:
return []
i... |
1b103179ed55b691f05798a4e7f8c016827fdf37 | suxian06/leetcode | /240.Searcha2DMatrixII.py | 583 | 3.5625 | 4 | class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
m, n = len(matrix), len(matrix[0])
if n == 0:
return False
... |
9dba456bf9722465b9dbef29d638fc99f97b43a7 | suxian06/leetcode | /701.InsertintoaBinarySearchTree.py | 792 | 3.953125 | 4 | # Runtime: 108 ms, faster than 98.24% of Python3 online submissions for Insert into a Binary Search Tree.
# Memory Usage: 14.9 MB, less than 100.00% of Python3 online submissions for Insert into a Binary Search Tree.
class Solution:
def insertIntoBST(self, root, val):
if not root:
return TreeNo... |
c108e714ff9f79b2c456d472a874b69ae6fedf95 | suxian06/leetcode | /98.ValidateBinarySearchTree.py | 874 | 3.84375 | 4 | # Runtime: 36 ms, faster than 98.85% of Python3 online submissions for Spiral Matrix.
# Memory Usage: 15.0 MB, less than 100.00% of Python3 online submissions for Spiral Matrix.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# ... |
501b3b7428ad2d260ab2edbe11d8eb74d2fc5bc6 | suxian06/leetcode | /70.ClimbingStairs.py | 342 | 3.59375 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return n
prevOne = 1
prevTwo = 2
while n > 2:
cur = prevOne + prevTwo
prevOne, prevTwo = prevTwo, cur
n -= ... |
ff352428b36ca4abc4a1a2c1bf1ccde21f330080 | flipperji/python_study | /base_study.py | 3,834 | 4.125 | 4 | # 单行注释,在’#‘后面需要加一个空格,避免黄线警告
"""
多行注释
"""
print("hello python")
"""
算数运算符
// 取整
% 取余
字符串可以使用运算符来使用 例如:”test“ *2 = ”testtest"
"""
# 变量的使用 变量=值
"""
变量名只有第一次出现的时候才是定义变量
数据类型
str/列表/元组/字典
int/bool/float/complex
bool 非0即true
数字型变量跟字符串型变量 可以通过"+" 跟 "*" 进行算术计算
name = "etest"
print(name)
格式化输出
%s 输出字符串
%d 输出整数
%f 输出浮点型
%%... |
e2f8a7846d73c19d740a23eb8221228fa89d175f | oldmuster/Data_Structures_Practice | /array/python/169_majorityElement.py | 1,468 | 4.25 | 4 | #!/usr/bin/env python
#coding:utf-8
"""
算法: 169.多数元素
Desc: 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
Referer:
- https://leetcode-cn.com/problems/majority-element/
"""
from collections import Counter
class Soluti... |
5278289d3decd3771e5b0c821948e4be167ca52e | oldmuster/Data_Structures_Practice | /stack/224_calculate.py | 4,186 | 3.828125 | 4 | #!/usr/bin/env python
#coding:utf-8
"""
224. 基本计算器
https://leetcode-cn.com/problems/basic-calculator/
"""
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
思路:
通过两个栈来实现,一个保存运算符的栈,另一个保存操作数的栈。从左到右遍历表达式,
遇到操作数,就压入操作数栈,遇到运算符,就与运算符栈的栈顶元素进行比较:
1. 如果比运算符栈顶元素的优先级高,就将当前运算符压入栈
... |
63a2efc4d02552e3edce56fcf3053432372f3067 | oldmuster/Data_Structures_Practice | /binarysearch/searchRange.py | 1,923 | 4.34375 | 4 | #!/usr/bin/env python
#coding:utf-8
"""
算法: 在排序数组中查找元素的第一个和最后一个位置
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
排除法二分查找在寻找第一个等于target索引以及最后一个target的索引中的应用。
原理: 当mid被分到左区间时,搜索到的是第一个target索引。
当mid被分到右区间时, 搜索到的是最后一个target索引。
"""
class Solution(object):
def searchRange(s... |
51e7e6de93fe0cc1992a0a02b2ba6028c925b9e2 | oldmuster/Data_Structures_Practice | /string/longestCommonPrefix.py | 626 | 3.6875 | 4 | #!/usr/bin/env python
#coding:utf-8
"""
14. 最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix/submissions/
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
min_str = min(strs, key=lambda x:len(x))
min_... |
f3ba213c421ef6aee8d055480f2c9c0d469709ee | mochba/Python---Variables | /Payroll.py | 1,000 | 4.125 | 4 | """Write a program to prompt the user for hours and rate per hour using input to
compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program
(the pay should be 96.25). You should use input to read a string and float() to
convert the string to a number.
1.Use try and except handles non-numeric in... |
46b87c8bd797ec16d80b2c9cfc2c01a343ae49fd | kailashnathan/Sentiment-Analysis-using-NN | /beautiful_data.py | 1,437 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 11 01:29:42 2017
@author: Neelesh
"""
import pandas as pd
import balance as b
def get_data(data_size, max_features):
# data_size = int(input("\n***ENTER DATASET SIZE***: "))
print("\nLoading ",data_size," records.......")
#1. First ... |
87a87a030ae3fd1744db2fbbd5eb51c474f159b5 | tuduier/selfteaching-python-camp | /19100205/Ceasar1978/d6_exercise_stats_word.py | 1,128 | 4.125 | 4 |
# 统计各单词出现的次数
def stats_text_en(text):
text = text.replace('.', '')
text = text.replace('!', '')
text = text.replace('--', '')
text = text.replace('*', '')
text = text.replace(',', '')
text = text.replace('(', '')
text = text.replace(')', '')
text = text.replace(';', '')
text = ... |
fb655e1b82e15bd181fe84c2909944acfc1e9e5f | Krebrov001/MPI-Project | /Ethan/Python/mm.py | 390 | 3.78125 | 4 | import numpy as np
size = input("Size: ")
N = int(size)
#Randomly generate matricies
matrix_a = np.random.rand(N, N)
matrix_b = np.random.rand(N, N)
matrix_a = matrix_a * 100
matrix_b = matrix_b * 100
matrix_a = matrix_a - 50
matrix_b = matrix_b - 50
print("Matrix_A:")
print(matrix_a)
print(" ")
print("Matrix_B")
p... |
5365a1d06040557930b463d1f3e480ad45c52fa9 | kevinhkr/Cra | /parse_encode.py | 376 | 3.671875 | 4 | import urllib.request
import urllib.parse
word = input('What do you want to search in Baidu: ')
url = 'http://www.baidu.com/s?'
data = {
'ie': 'utf-8',
'wd': word,
}
query_string = urllib.parse.urlencode(data)
url += query_string
response = urllib.request.urlopen(url)
name = word + '.html'
with ... |
03a59f96864a2e9c831eb58f5689f9bb01962ddc | kevinhkr/Cra | /reg_exp_sub.py | 552 | 3.609375 | 4 | import re
string = 'i love you, you love me'
pattern = re.compile(r'love')
ret = re.sub(pattern, 'hate', string)
ret1 = pattern.sub('hate', string)
# 两种方法一样
print(ret)
print(ret1)
# 目标:将string1中的身高替换为身高-10
# 例:string1 = '我喜欢身高为170的女生'
# 结果:我喜欢身高为160的女生
string1 = '我喜欢身高为170的女生'
def fn(a):
b = int(a.group()) - 1... |
1d5856bedd9e9d9744104858ba6bc3498ded617d | jwc218/ISE172 | /Lab2/OOPLifeGame.py | 5,519 | 3.671875 | 4 | #object oriented version of game of life
# make neccesary imports
__version__ = '1.0.0'
__author__ = 'G-Do (http://www.daniweb.com/members/G-Do/37720)'
__maintainer__ = 'Ted Ralphs'
__email__ = 'ted@lehigh.edu'
__url__ = 'http://coral.ie.lehigh.edu/~ted/files/ie172/code/life.py'
__title__ = 'The... |
f97cda2c96a08bca1dde107a0410cd6126175b7f | Raghavareddy21/Google-parseer | /webparser.py | 478 | 3.515625 | 4 | from bs4 import BeautifulSoup
import requests
search=raw_input("Enter the link:")
base = "http://www.google.de"
url = "http://www.google.de/search?q="+ search
response = requests.get(url)
soup = BeautifulSoup(response.text,"lxml")
for item in soup.select(".r a"):
print(item.text)
for next_page in soup.select(".fl")... |
29807cb10c6008221448a55657b19fc4aefcf8cf | Thaiyathep/python | /Testopp.py | 1,314 | 3.859375 | 4 | """
a1 = input('First number: ')
a2 = input('Second number: ')
print((a1),'==',(a2),":",a1 == a2)
print((a1),'>',(a2),":",a1 > a2)
print((a1),'<',(a2),":",a1 < a2)
"""
"""
a = 60
b = 13
c = 0
c = a & b
print(c)
c = a | b
print(c)
c = a ^ b
print(c)
c = ~a
print(c)
c = a << b
print(c)
c = a >> b
print(c)
"""
"""
... |
2174258fd1bd6659c4cc594f340df4ee47396ad8 | jolizanton/Data-visualization-project | /Sitka_rainfall.py | 871 | 3.5 | 4 | import csv
from datetime import datetime
import matplotlib.pyplot as plt
filename = 'data/sitka_weather_2018_simple.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
print (header_row)
for index, column_header in enumerate(header_row):
print (index, column_header)
... |
7343b452f80158ce19bff7c71b1c25e4090b77a0 | hjchoe/T2-python | /statescapitalgame.py | 2,707 | 4.0625 | 4 | import random
from os import path
if path.exists("statescapitals.txt"):
src = path.realpath("statescapitals.txt")
# open file this time to only read, type: "r"
f = open(src, "r")
# var = f.readlines() reads the txt file and puts each lined into a list: var
lines = f.readlines()
# finding how many states+capital... |
8c7f626e3a3f347956de6ba0c823c0a5d41d5517 | schonmann/icpc-project | /uva/combinatorics/369.py | 404 | 3.546875 | 4 |
mem = dict()
def fat(n, floor):
if n == floor: return 1
if n == 0: return 1
return n*fat(n-1, floor)
n, m = map(int, input().split())
while not (m == 0 and n == 0):
res = 0
if n - m <= n/2:
res = int(fat(n,n-m)/fat(m, 0))
else:
res = int(fat(n,m)/fat(n-m, 0))
print(f"{n} ... |
2b48fcae34a92ac65f9d8f36d37fc86d0f8310f5 | Addi-11/Algorithms-n-DataStructures | /DataStructures/stack/uses/infix-postfix.py | 1,440 | 3.5625 | 4 | #infix to postfix transformation
def Infix_Postfix(exp):
opans = []
ans = []
dans = []
operand = IdentifyOperand(exp.split(" "))
operator = IdentifyOperator(exp.split(" "))
explist = exp.split(" ")
for i in explist:
if i in operand:
ans.append(i)
#empty the... |
5eaf7016fd33ca05b6754559798a3439d2023d8f | dmoschet84/CodingDojo_Python | /animals.py | 991 | 3.78125 | 4 | class Animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print(self.name + " - " + str(self.health))
... |
2b0e62681a337d1f996bc28b2b198d7e6910dc3b | atutgorkhali/LearnPython | /Learning Phase/2_basicOperators.py | 1,567 | 4.375 | 4 | """Types of Operator
-----------------------
# Arithmetic Operators
# Comparison (Relational) Operators
# Assignment Operators
# Logical Operators
# Bitwise Operators
# Membership Operators
# Identity Operators
"""
#------Arithmetic Operators--------
# Addition (+)
# Substraction (-)
# Multiplication (... |
1c4ca2e36ab0720be5e76e181cf9d0cbc8bdbbe3 | alvas-education-foundation/CSE-K-Thrishul-4AL17CS038 | /Machine Learing Class/02-Sept/P4_02-Sept.py | 361 | 4.09375 | 4 | '''
4. Write a Python program to sum of three given integers. However, if two values are equal sum will be zero
'''
def sum(x, y, z):
if x == y or y == z or x==z:
sum = 0
else:
sum = x + y + z
return sum
a = int(input("Enter a number :"))
b = int(input("Enter a number :"))
c = int(input(... |
0d61090f72ea19f53ccd5fd8ebe3ccd7163bcdd9 | alvas-education-foundation/CSE-K-Thrishul-4AL17CS038 | /coding_solutions/Python/positiveNumbers.py | 230 | 4.03125 | 4 | a = []
n = int(input("Enter the size of list\n"))
print("Enter the list elements\n")
for i in range(n):
num = int(input())
a.append(num)
print("The postive numbers are\n")
for num in a:
if(num > 0):
print(num)
|
6013d28fe6f03f3395e9b9070d7c24c50d4a6993 | nickwilson3/containers_nick | /containers/Heap.py | 8,359 | 4.25 | 4 | '''
This file implements the Heap data structure as a subclass of the BinaryTree.
The book implements Heaps using an *implicit* tree with an *explicit* vector
implementation,
so the code in the book is likely to be less helpful than the code for the
other data structures.
The book's implementation is the traditional im... |
726f458df77c8703dcc8b37a8c12205627c2c0b1 | mahadi137/Python-Projects | /guess the number game.py | 864 | 4.25 | 4 | # This is a guess the number game
# udemy course: Automate the boring stuff with python programming
import random
print('Hey! What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20.')
secretNumber = random.randint(1, 20)
for guessedNumber in range (1, 5):
... |
58e34bae6ffb3b687b682a476b76480f1951ae6c | peepeespace/studybuddy | /db.py | 811 | 3.53125 | 4 | import psycopg2
from psycopg2 import sql
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def create_db_if_not_exists():
db_name = 'studybuddy'
conn = None
try:
conn = psycopg2.connect(
dbname='postgres',
host='localhost',
port=5432
)
exc... |
4bb9fea40c357c48f78bd621fd59064aac3474ad | mithunmo/python | /map-util.py | 671 | 3.71875 | 4 |
x = [1,2,3,4,5]
def two(x):
print "here"
return x*2
print map(two, x)
class PureMap:
def __init__(self, function, sequence):
self._f = function
self._sequence = sequence
self.i = 0
self.n = len(sequence)
def __iter__(self):
return map(self._f, self._sequenc... |
02ce37db7e2add5221539d582c9fc17c66ed9d13 | zachklaus/past-projects | /Python Projects/RSA/transposition-encr.py | 4,000 | 4.03125 | 4 |
import string
def main():
print("-This program encrypts messages using a double transposition cipher and two keys provided as input.")
print("-Keys must be 10 characters long. Each character must be selected from the 26 letters of the alphabet.")
print("-Each character must be used only once in a sin... |
592a09807ad214e15bf9717cc09001bcd60c1106 | YanpingDong/leetcodeSolution | /ReverseBits.py | 367 | 3.625 | 4 | class ReverseBits(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
rvalue = 0
for i in range(0,32):
rvalue <<= 1
rvalue += n & 1
n >>= 1
return rvalue
if __name__ == '__main__':
rb = ReverseBits()
... |
f0d3aa2a152eeb85cb8446a127dd5761f0828bbd | zac-chu/Pillar-Word-Search-Kata | /puzzle.py | 6,166 | 3.984375 | 4 | class Puzzle():
def __init__(self, puzzle):
self.matrix = puzzle.replace(", ", "").split("\n")
self.rows = len(self.matrix)
self.cols = len(self.matrix[0])
def __find_word_in_matrix(self, word, strings, reversed_string=False):
"""
Find the given word in the matrix using... |
b153fbb26a80740fa05ae2b0204880d1a0645cda | HenriettaHolze/advent_of_code_2020 | /08.py | 2,212 | 3.578125 | 4 | INPUT = '''nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6'''.split('\n')
def find_loop(INPUT):
'''finds the value of the accumulator before the game enters the second loop'''
position = 0
accumulator = 0
visited_positions = []
while position not in visited_positions:
inst... |
bb8c423dc813809799c345ddb2dae3b45c2efa73 | HenriettaHolze/advent_of_code_2020 | /05.py | 1,492 | 3.625 | 4 | from math import floor, ceil
INPUT = 'FBFBBFFRLR'
def find_seat(pattern):
'''Find assigned seat and return seat ID'''
row_spec, col_spec = pattern[:-3], pattern[-3:]
# find row
row_lower = 0
row_upper = 127
for i, letter in enumerate(row_spec):
if letter == 'B':
row_lower ... |
b643377aeed6fd595217d971d69665c227a040e6 | jusKutz/DataTypes_ManipulatingStrings | /Tip_Calculator.py | 1,153 | 4.03125 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪
#HINT 1: https://www.google.com/search?q=how+to+round+number+to... |
47bd1cfb37f783d02914ec8b6f56584ba3243a65 | anthonywww/CSIS-9 | /rock_paper_scissors.py | 2,090 | 4.34375 | 4 | # -*- coding: utf-8 -*-
# Program Name: rock_paper_scissors.py
# Anthony Waldsmith
# 6/15/2016
# Python Version 3.4
# Description: Simulated "Rock Paper Scisors" game
# Optional import for versions of python <= 2
from __future__ import print_function
# import random class
import random
# Do this until valid input is... |
e2de1ac586316a46a3633df92efb7154722fc091 | anthonywww/CSIS-9 | /dice.py | 2,277 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: dice.py
# Anthony Waldsmith
# 6/16/2016
# Python Version 3.4
# Description: Dice game, roll and try to get the highest number vs the computer
# Optional import for versions of python <= 2
from __future__ import print_function
# import utilities/libraries
... |
408239806a64e001f8587c8331e77fcde6abe289 | anthonywww/CSIS-9 | /codingBat2.py | 992 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: codingBat2.py
# Anthony Waldsmith
# 07/24/2016
# Python Version 3.4
# Description: Extra Credit
# Optional import for versions of python <= 2
from __future__ import print_function
def cigar_party(cigars, is_weekend):
if cigars < 40:
return False
... |
581ab0543bf83d3903a008e21c8ba4b247e93aca | anthonywww/CSIS-9 | /sum_of_positive_and_negative_numbers.py | 2,230 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: sum_of_positive_and_negative_numbers.py
# Anthony Waldsmith
# 6/16/16
# Python Version 3.4
# Description: Sums of positive and negative numbers with a repeat ability
# Optional import for versions of python <= 2
from __future__ import print_function
# Thi... |
09287125057d95bd8365205361c10ad78ccca8bd | anthonywww/CSIS-9 | /split_sentence.py | 1,261 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: split_sentence.py
# Anthony Waldsmith
# 07/27/16
# Python Version 3.4
# Description: Split a sentence and count the words in it
def countWord(words, word):
count = 0
for s in words:
if word == s:
count += 1
return count
def requestSearchWord():
w... |
25566468bad278f10ce5ba7366440f5978228658 | anthonywww/CSIS-9 | /smallest_largest_sum_average.py | 1,336 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Program Name: smallest_largest_sum_average.py
# Anthony Waldsmith
# 6/16/2016
# Python Version 3.4
# Description: A program that generates X random numbers (between 10 to 15) (integers) and those random numbers are between 20 to 50
# Optional import for versions of pyth... |
17026e6e2fb5814ad356da12d3454922ca8faedb | anitalaw/arithmetic-2 | /math.py | 1,685 | 4.28125 | 4 |
"""Math functions for calculator."""
def add(numbers):
"""Return the sum of the two inputs."""
counter = 0
for num in numbers:
counter += num
return counter
def subtract(numbers):
"""Return the second number subtracted from the first."""
counter = 0
for num in numbers:
... |
9e883a5bf83d6cd01e426bac5fcb617731d97be9 | ScytheSoftware/TechDegreeBasketballStatsTool | /app.py | 9,868 | 3.5 | 4 | #DaVonte' Whitfield
#Python 3.7
#Tech Degree Project 2 Basketball Stats Tool
#I mainly used methods I did on the first project
import constants
import os
import re
import pdb
import copy
def clear(): #Note, This works with python program about not in Visual Studios, at least for me.
os.system("cls" if o... |
37169ff97c4e14c4d874d590d61e8a9b2bdc4c20 | AMK6610/DL-CA1 | /RBF.py | 4,646 | 3.5625 | 4 | from NN import NeuralNetwork, Layer
import numpy as np
import matplotlib.pyplot as plt
from mlxtend.data import loadlocal_mnist
hidden_neurons = 10
out_neurons = 10
learning_rate = 1e-14
epoch = 1000
batch_size = 128
num_train = 60000
np.random.seed(100)
class RBFLayer(Layer):
def __init__(self, n_input, n_neu... |
14ac02e80f89f54b6b35f8e22af885d5645222f6 | opavlyuk/word-search | /src/helpers/cli.py | 825 | 3.703125 | 4 | import argparse
class ArgumentError(Exception):
pass
def _validate_args(args):
if args.board_size < 0:
raise ArgumentError('Board size should be > 0')
def parse_cl_args():
parser = argparse.ArgumentParser(description='Find words in two-dimensional array of random letters.')
parser.add_argu... |
0f95b7a5e1e4763250118d5852cc3c96aca552e0 | Zhansayaas/webdev | /week10/CodingBat/warming-1/sumdouble.py | 77 | 3.6875 | 4 | def sum_double(a, b):
if(a==b):return((a*2)*2)
else:
return(a+b)
|
e27151c43f4aae885caf7dc14eabca38daa2e844 | Zhansayaas/webdev | /week10/Инфоматрикс/c.циклы/for/c)i.e.py | 69 | 3.578125 | 4 | x=int(input())
a=0
while(x!=0):
a+=x%10
x=x//10
print(a) |
7fd3ea7bc0a748f0386cfc8f0d8287daf45f5adc | aymenbelhadjkacem/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,127 | 3.921875 | 4 | #!/usr/bin/python3
"""
Module Devide Matrix
"""
def matrix_divided(matrix, div):
"""
Devides all elements in matrix
Args:
matrix (list[list[int/float]]) : matrice
div (int/float) Devider
Raise:
TypeError: div not int or float
TypeError: m... |
7ade29789a1dae0b128cc1120d1dfdf225ee6ae7 | Leo428/CS61A | /cats/typing.py | 10,016 | 3.78125 | 4 | """Typing test implementation"""
from utils import *
from ucb import main, interact, trace
from datetime import datetime
###########
# Phase 1 #
###########
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are few... |
26d9745dbae0a9999e8cb3b47b7aff425c57ca25 | benktesh/algorithm_dasgupta | /Ex6-1.py | 3,021 | 3.6875 | 4 | import time
### Fibnacchi by recustion
def fibRecursion(n):
if(n-1 <= 1):
return n-1;
return fibRecursion(n-1) + fibRecursion(n-2)
def fibDynamic(n):
F = [0 for x in range(n)]
F[0] = 0
F[1] = 1
for i in range (2, n):
F[i] = F[i-1] + F[i-2]
return F[n-1]
def contiguousSubs... |
4bce54102ad3845dfa8b5682172701e2116747cb | benktesh/algorithm_dasgupta | /Six_10_CountingHead.py | 2,958 | 3.796875 | 4 | ##Author: Benktesh
#benktesh1@gmail.com
#01/03/2017
import numpy as np
'''
Counting heads. Given integers n and k, along with p1; : : : ; pn 2 [0; 1], you want to determine the
probability of obtaining exactly k heads when n biased coins are tossed independently at random,
where pi is the probability that the ith coi... |
93a926598fb36300ced8fe3b02f1978c8e440aa5 | benktesh/algorithm_dasgupta | /Six_07_LongestPalidrome.py | 2,761 | 3.921875 | 4 | ##Author: Benktesh
#benktesh1@gmail.com
#12/29/2017
#Dasgupta Solutions 6.7
#https://sites.google.com/site/indy256/problems/longest_palindrome
import numpy as np
def lonestPalidrome(A):
'''
Finds and returns the longest palindromic subsequence using Dynamic Programming
maxLength and begin... |
57f2e728a14cd3a9793b40540378d1f35571dc29 | rjhansen/pluspora-algo | /depthfirst/dev/8/test_boggle.py | 747 | 3.71875 | 4 | #!/usr/bin/env python3
# coding=UTF-8
"""Provides unit testing for the Boggle solver."""
from boggle import solve
def test_boggle():
"""Checks for twelve known words in a specific board."""
board = """CATER
XLUAW
BDFGH
IJKMN
OPQST"""
board2 = """CATERWAULING
ASDFGHJKLZXC
QAZWSXEDCRFV
TGBYHNUJMIKL
OKMI... |
a172b64bdcb8ec48732315bb7d0af02e76eb3b26 | QunBB/Algorithm | /python/Tree/MinimumSpanningTree.py | 5,126 | 3.53125 | 4 | import numpy as np
class Graph:
"""
图的构造类
"""
def __init__(self, vertex_num):
"""
:param vertex_num: 顶点的数量
"""
self.vertex_num = vertex_num
self.vertexs = None
self.weights = None
def create(self, vertexs, weights):
"""
:param vertex... |
4f694d30702a147ce92952cc8ed7ac9deca03160 | studeri3819/cti110 | /P2HW2_MaleFemale_Percentage_IvanStuder.py | 772 | 4.15625 | 4 | # Finding out Male and Female percentages
# 9/20/2018
# CTI-110 P2HW2 Male Female Percentage
# Ivan Studer
#Get total number of males registered for class.
Males = int(input(' Enter total number of males registered: '))
#Get total number of females.
Females = int(input(' Enter total number of females regist... |
c34b27245b7776276a7c48e9817eb87b1776b927 | albertsuwandhi/Python-OOP | /python_inheritance.py | 950 | 3.75 | 4 | #/usr/bin/env python3
# Object : Attribute and Method
class Hero(object):
def __init__(self,inputName, inputHealth):
self.__name = inputName
self.__health = inputHealth
'''
# Treat as variable
@property
def info(self):
return "Name : {}, Armor : {}, Health :{}".format(self.__nam... |
4544c45d72d277c1f2e732e2a2a0edce93f8a738 | psuchand/capstone-taxi | /ml_helper_functions.py | 6,602 | 3.6875 | 4 | from random import random
from math import floor
from vincenty import vincenty
import pandas as pd
PENALTY_PROFIT_BAD_POS = -8
PENALTY_TIME_BAD_POS = 60*10
DRIVING_SPEED_IN_MPH = 12.5
COST_OF_TRAVEL_TIME_DOLLARS_HR = 42
OVERALL_AVG_WAIT_TIME = 11.4*60 #In Seconds
GOOD_POSITION_WAIT_TIME = 3*60 #In seconds
#Data is d... |
e6651cfb7eae2e7a10be978ed6bd37b6d71db423 | J-sudo-2121/codecademy_projects | /parrot.py | 585 | 4.28125 | 4 | # How the input() Function Works
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# Letting the user choose when to quit using a while loop.
prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "
message = ""
while messa... |
b2b839e1e6d9b34abf4b99bc90e3a9409660f2bc | J-sudo-2121/codecademy_projects | /dimensions.py | 759 | 4.40625 | 4 | # Tuples are immutable lists. Tuple looks just like a lit except you use () inst
# ead of [].
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# Tuples are defined by the presence of a comma. If you want to make a tuple
# with a single element, a comma needs to be included. my_t = (3,)
# Looping thro... |
a2caf186e65805da0d36d87ff332c903aab512fe | J-sudo-2121/codecademy_projects | /dice.py | 584 | 4.25 | 4 | # Exercise 9-13 Dice
from random import randint
"""A class to represent rolling a die"""
class Die:
def __init__(self):
self.sides = 6
self.ten_sided = 10
self.twenty_sided = 20
def roll_die(self):
print(f"You rolled {randint(1, 6)} with the {self.sides} sided die.")
def ten_sided_die(self):
print(f"Yo... |
cfdae26c00f0d7649a9b5c458c174b52ec508c5b | J-sudo-2121/codecademy_projects | /favorite_languages.py | 3,326 | 4.65625 | 5 | # A Dictionary of Similar Objects. You can use a dictionary to store one kind \
# of information about many objects.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python'
}
# Each key is the name of a person and each value is their language choice. \
# When you know you'll need m... |
28af3a287647436235f0c22c8a88effb2eca01c9 | J-sudo-2121/codecademy_projects | /people_info_ch6.py | 1,962 | 4.0625 | 4 | # Store info about a person in a dictionary.
personal_info = {
'Bob': {
'first_name': 'bob',
'last_name': 'smith',
'age': 56,
'city_of_residence': 'new york',
},
'Lisa': {'first_name': 'lisa',
'last_name': 'Yandi',
'age': 43,
'city_of_residence': 'singapore',
},
'Luke':{
'first_name': 'luke',
'... |
5afc1adf3bbb397cf13ef03508bf2d66324b2288 | J-sudo-2121/codecademy_projects | /cars.py | 2,022 | 4.90625 | 5 | # Organizing a List. Sorting a List Permanently with the sort() Method.
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# The cars are now in alphbetical order and we can never revert back to the original order.
# You can also sort the list in reverse alphabetical order by passing the argument rever... |
52a6826591f0b1b88d9c1f1ef2454d6fd2514812 | rylans/ctci | /ch2-linked-lists/question-2.py | 1,403 | 4.4375 | 4 | '''Implement an algorithm to find the nth to last element of a singly linked list'''
class LinkedList(object):
def __init__(self, val):
self.next_node = None
self.val = val
def get_next(self):
return self.next_node
def set_next(self, node):
if node != None and type(node) !... |
ea00fc628d08164db9ab9a1f0ab9b46f4162af9a | Svenvollfied25/ETL-On-NBA-Data | /NBAdata/AgeVPoints.py | 550 | 3.515625 | 4 | from pyspark.sql import SparkSession
from pyspark.sql import functions as F
import pandas as pd
from pyspark.sql.functions import desc
spark = SparkSession \
.builder \
.appName("Python NBA Salaries") \
.getOrCreate()
df = spark.read.csv("NBACleanData/StatsClean.csv", header=True)
df.createOrReplaceTempV... |
43878a5c085a2cb9b9e7461a1cb485933f4fc6d3 | alu-rwa-dsa/week-1-list-complexity-jules | /.github/q3c.py | 115 | 3.59375 | 4 | def Sort(list):
list.sort()
return list.sort()
list = [1, 3, 4, 3, 5, 6, 7, 66, 43, 23]
print(Sort(list)) |
1f2cb3c70e971ab612a890c037dc927a387529de | Yao-Ch/OctPyFun2ndDayPM | /dict2.py | 498 | 3.953125 | 4 |
phone={"maria":[34567, 56788],
"yann":[56789],
"lou":[]}
print(phone, len(phone), type(phone))
for n in phone:
print(n)
phone["lou"].append(89887) # To update an existing pair
phone["marco"]=[87776] # To add a new pair
print(phone, len(phone))
if "yan" in phone:
... |
c7cf0d54403e6e79c7abc8cc984368b6ad5e1ee0 | Pumala/python_function_exercises | /play_again.py | 174 | 3.671875 | 4 |
def play_again():
answer = raw_input("Do you want to play again? ").upper()
if answer == "Y":
return True
else:
return False
print play_again()
|
61dc38fca5cbb337f050e2cfb9b7c49e045f5bb9 | jzy67/python | /python学习代码笔记/cut.py | 1,215 | 3.609375 | 4 | # L=list(range(20))
# print(L[:10],'\n',L[-10:],'\n',L[:10:2],'\n',L[::5],'\n',L[:])
# d={'a':1,'b':2,'c':3}
# for k in d:
# print(k)
# for v in d.values():
# print(v)
# for k,v in d.items():
# print(k,'=',v)
# print([k+"="+str(v) for k,v in d.items()])
# from collections.abc import Iterable
# pr... |
0819f1df0e880203f167d82adefc8dee38482b85 | jzy67/python | /python学习代码笔记/type_.py | 1,645 | 3.671875 | 4 | # '''type'''
# def fn(self,name='world'):
# print("Hello,%s."%name)
# Hello=type('Hello',(object,),dict(hello=fn))
# h=Hello()
# print(type(Hello))
# print(type(h))
# '''metaclass'''
# '''没看懂 空'''
'''try'''
# try:
# print('try...')
# r=10/0
# print('result:',r)
# except ZeroDivisionErr... |
49513563578a70e6e06e2267a232aa9e11e84085 | devkral/wakemeupextreme | /wakemeupextreme/calculations/multiplication.py | 237 | 3.5625 | 4 | import random
from . import calculations
def multiplication():
p1 = random.randint(0, 10)
p2 = random.randint(0, 10)
return "What is {}x{}?".format(p1, p2), "{}".format(p1*p2)
calculations.questions.append(multiplication)
|
8c343ae18b3efbc18022205a8746e7530bd00ab5 | jurbanski/midterm | /movie_database.py | 1,369 | 3.9375 | 4 | """ Movie database module """
# 2015-02-10
# Joseph Urbanski
# MCS 50101
import json
from urllib.request import urlopen
class Movie():
""" Movie class contains the IMDB ID, the title of the movie, the IMDB
rating, and the movie's director.
"""
imdb_id = None
title = None
imdb_rating = None... |
5dbc2771b679452f37615de9189089867ab7603a | huojinhui/PycharmProjects | /初级python/8.7/24 霍晋辉.py | 9,013 | 3.5625 | 4 | # score = [68, 87, 92, 100,100, 76,100,100, 88,100, 54, 89, 76, 61]
# 1.查询score列表中成绩是满分的所有的学生学号
# score = [68, 87, 92, 100, 100, 76, 100, 100, 88, 100, 54, 89, 76, 61]
# num = score.count(100)
# for i in range(len(score)):
# if score[i] == 100:
# print(i+1, end=' ')
# 2.删除score列表中所有的数值100
# score = [68, 8... |
11381ba300d21242ba0e019a98493907c50eb3bc | huojinhui/PycharmProjects | /高级python/链表/链表.py | 3,305 | 4.09375 | 4 | # 节点
class node:
def __init__(self, date, next=None):
self.date = date
self.next = None
def __repr__(self):
return "node({})".format(self.date)
# 链表
class linkedlist:
def __init__(self):
self.head = None
# 头部插入
def insert_date(self, date):
new_node = node... |
392c69a5f8c76aa71375b8fb41da8f4dbfbe65e3 | omar-adel/Computer-Science-cs101 | /Lesson2/ProblemSet/next_day.py | 783 | 4.4375 | 4 | ###
### Define a simple nextDay procedure, that assumes
### every month has 30 days.
###
### For example:
### nextDay(1999, 12, 30) => (2000, 1, 1)
### nextDay(2013, 1, 30) => (2013, 2, 1)
### nextDay(2012, 12, 30) => (2013, 1, 1) (even though December really has 31 days)
###
def nextDay(year, month, day):
... |
ef5ecab07e0f0911899a6933de65d2ea8d2ed41c | sashgorokhov/python-course-2020 | /scripts/11_testing_examples/simple_tests/test_sqrt_func_with_unittest.py | 417 | 3.515625 | 4 | import unittest
from sqrt_func_with_doctest import sqrt
class TestSqrt(unittest.TestCase):
def test_square_root_of_9_positive(self):
self.assertEqual(sqrt(9), 3.0)
def test_square_root_of_negative(self):
with self.assertRaises(ValueError) as e:
sqrt(0)
self.assertEqual(... |
410f3693fc46a9a71e88c16f67d05375b779177f | Vikrant-Kalkal/Python-fun | /read_line_print_words.py | 474 | 4.3125 | 4 | # Program to read a txt file line by line and
# print the list of words that are in the file and
# also print the owrd count
fname = input("Enter file name: ")
fh = open(fname,'r')
lst = list() #defining a variable of "list" type
#nested for loops to read each line and then each word in that line
for line in... |
6acf4c7acbcbb778dba9af417a681b1a9d1476a6 | JayAllison/aoc2018 | /day19/day19_puzzle1.py | 3,521 | 3.609375 | 4 | # register: 0,1,2,3
# opcode: xxxx
# instruction: opcode, input, input, output
# input can be immediate (use value given) or indirect (use value in given register)
# output is always a register (indirect)
def parse_instruction_string(instruction_string):
# ex: 'seti 5 0 1'
if instruction_string.startswith('#'... |
9135ea5e2123f8ba422bc2dec94c011fa367119e | JayAllison/aoc2018 | /day13/day13_puzzle2.py | 4,679 | 3.796875 | 4 | class Cart(object):
def __init__(self, x_pos, y_pos, x_max, y_max, direction):
self.x = x_pos
self.y = y_pos
self.x_max = x_max
self.y_max = y_max
self.direction = direction
self.next_turn = 'L'
def __repr__(self):
return f'Cart({self.x}, {self.y}, {self... |
6d987ad5ac0710f9d4881585bf1634a3a9805625 | Niharrika/Tasks | /task-quiz.py | 1,266 | 3.859375 | 4 | q1=input("Name the three primary colours according to the colour order? ").lower()
q2=input("Who banned art in mordern germany in the 30's? ").lower()
q3=input("What was Leonardo da Vinci's most famous painting? ").lower()
q4=input("Name Paulo Coelho most famous book? ").lower()
q5=input("How many paintings did vin... |
aa2309c861d01e259b63174f72c589395f1f6caf | amitdivekar30/Neural_Networks_for_Classification_using_python | /NN_fireforests.py | 2,802 | 3.5 | 4 | # Neural Network forest fires problem
# Artificial Neural Network
## Importing the libraries
import numpy as np
import pandas as pd
import tensorflow as tf
tf.__version__
# Part 1 - Data Preprocessing
# Importing the dataset
dataset = pd.read_csv('forestfires.csv')
dataset.columns
dataset.describe()
... |
dd9079c1803ab8b90babf92da06bfc580d18bc6c | axju/Flow-in-a-hydrogel-encrusted-stent | /stent.py | 2,824 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy.linalg import inv
from scipy.integrate import odeint
from math import log, pi, sqrt, exp
class FunctTyp1:
"""Model equation: Typ 1"""
def __init__(self, pb, t1, t2):
self.pb = pb
self.t1 = t1
self.t2 = t2... |
0efbfffc863c93fb6987cc00dea2533cd6134d46 | victor-alegre-alten/py_spark | /ContarPalabrasDF.py | 1,065 | 3.640625 | 4 | from pyspark import Row
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
from WordsHelper import split_words, read_text_file, sanitize_text
def create_spark_session():
MASTER = 'local[3]'
return SparkSession.builder.master(MASTER).appName('Contador palabras spark').getOrCreate()
de... |
c1534681fc2e55c228d2cbad469cc2940994ca6a | JhonattanDev/Exercicios-Phyton-05-08 | /ex11.py | 596 | 4.375 | 4 | # Explicando o programa
print("====================================================")
print("|Digite o valor em R$ abaixo para converter para U$|")
print("====================================================")
# Usuário insirir o valor em reais
valorReais = int(input("Digite o valor em reais: "))
# Definindo ... |
46813952df0f54f13b6c1cf837660cf7b7d6c5e4 | seanwentzel/crypto-hons | /tut5-rsa/q3_helpers.py | 1,731 | 3.609375 | 4 | def gcd(a,b):
if b == 0:
return a
return gcd(b, a%b)
def fact(n):
if n == 0:
return 1
return n*fact(n-1)
def pollardPMinusOne(base, n):
print("\\item")
print("\\begin{tabular}{l l l}")
print("\\hline$j$ & ${0}^{{j!}} \\text{{ mod }} {1}$ & $\\text{{gcd}}({0}^{{j!}} - 1 \\t... |
3f11257cb768cb1c5ecc30d790ec6fce6cf2933f | chetan-singh-negi/calculator | /calculator.py | 3,257 | 3.53125 | 4 | from tkinter import *
def click(event):
global scrv
text=event.widget.cget("text")
if text=="C":
root.destroy()
elif text=="R":
scrv.set("")
scr.update()
elif text=="=":
value=eval(scrv.get())
scrv.set(value)
else:
scrv.set(scrv.get()+text)
root=Tk... |
7495f1c6bc2ee4b83eb8f275804bec86a6b82ea9 | karadisairam/operators | /38.py | 176 | 3.859375 | 4 | import operator
li=[1,5,6,7,8]
operator.setitem(li,slice(1,4),[2,3,4])
print("after setitems of list is :",end="")
for i in range(0,len(li)):
print(li[i],end="")
|
2318979d30f0e73dafa2361ba9b4fe26746acadd | karadisairam/operators | /32.py | 182 | 3.65625 | 4 | #Tuple method
a,b=10,20
print( (b,a) [a<b])
#Dictinory method
a,b=10,20
print({True:a , False:b} [a<b])
#lamba function
a,b=10,20
print((lambda: a,lambda : b) [a<b] ()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.