blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6fd6b79dc41de69b5471aa9edd21a0ed8a1885e0 | atavener68/intro_to_python | /problem0.py | 435 | 3.96875 | 4 | def count_change(denomination_quantities):
total = 0
# TODO put code here
return total
denomination_quantities = {
1: 3,
5: 1,
10: 1,
25: 3,
}
print(count_change(denomination_quantities))
# Expected result: 93
# Try changing the quantities and adding other denominations
# SOLUTION
# for... |
848c04471ea6b75698aae6d08d7e20b17a611e4f | atavener68/intro_to_python | /cart.py | 1,250 | 3.828125 | 4 | # STore
# cart
# NOUNS/CLASSES: Categories e.g Electronics, Products: e.g. Television,
# AJECTIVES/ PROPERTIES: Product has: name, desc, price, stars, maker/brand
# VERBS:METHOD/FUNCTION: show __str__, compare
# CartItem product.price, quantity, VERB: subtotal(), show_checkout __str__
class Product:
def __init_... |
5522d0876ad9b735e3d75e00e0ac73d02d5f92b9 | atavener68/intro_to_python | /user_input.py | 279 | 4.09375 | 4 |
name = input("What is your name?")
print(f"\nHello {name}!!!")
total = 0
text = "default"
while text != "":
text = input("Enter number or blank line to quit:")
if text != "":
number = int(text)
total += number
print(total)
print("Thanks!")
|
2103c9503ea40e659a2eca735a0e0a0435400758 | wangxiaoyangwz/python_game | /code/yichang.py | 130 | 3.828125 | 4 | s=input("Enter a number:")
try:
number=float(s)
except:
number=0
answer=number*number
print(number,"*",number,"=",answer)
|
d63b4c63d9a2abc19d38c5b0f8a3e755574c4d9f | sunkyschooled/The-RPN-Calculator | /main.py | 1,486 | 3.859375 | 4 | print("Accepted Inputs:\nclr to Clear\nFloat or Integer\nOperator\np to Show Current Equation\nq to quit\ni to invert\nn to negate")
yee = 0
def RPN(c,a,b):
if c == "+":
return (a+b)
if c == "-":
return (a-b)
if c == "/":
return (a+b)
if c == "*":
return (a*b)
if c == "^":
return (a**b)
... |
41059ee4fec7bf6e4df9851528e1f59cfef4b4f7 | connorheckley/python-exercises | /library/library.py | 4,554 | 3.625 | 4 | """ Library """
import os
import time
# login screen
# login validation
# logout
# class book
# class CD
# class user
books = [{'title': 'Harry Potter', 'author': 'J.K.Rawling', 'date': 2004 }, {'title': 'Bible', 'author': 'J.Christ', 'date': 32}, {'title': 'PhD for Dummies', 'author': 'Andre... |
42ac4032c43e5f02f971bbf5d69843a7438d09f3 | google-code/avaloria | /src/objects/exithandler.py | 2,984 | 3.5625 | 4 | """
This handler creates cmdsets on the fly, by searching
an object's location for valid exit objects.
"""
from src.commands import cmdset, command
class ExitCommand(command.Command):
"Simple identifier command"
is_exit = True
locks = "cmd:all()" # should always be set to this.
destination = None
... |
9d0946fc233621fd42ed690c604135108c0ff449 | fellucard/ProjectEuler | /Problem1.py | 423 | 4.25 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
# -- coding: UTF-8 --
__author__ = 'Mateusz'
def problem1(endrage):
sume = 0
for i in range(1, endrage):
if ... |
d3ca04980766c74ad16618182ce6797474ce0024 | lalmanza/Python_Demo | /loan.py | 928 | 4.15625 | 4 | #Get the loan details
money_owed = float(input("How much money do you owe, in dollars?\n")) #50,000
apr = float(input("What is the annual percentage rate? \n")) #3%
payment = float(input("What will your monthly payment be, in dollars? \n")) #$1000
months = int(input("How many months do you want to see results for? \n")... |
77e44fee88f5184df19c73d3e881506461168280 | Dlyyy/self-study | /self-study/高阶函数_map,reduce.py | 3,495 | 4.4375 | 4 | # Python内建了map()和reduce()函数。
# 如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Processing on Large Clusters”,你就能大概明白map/reduce的概念。
# 我们先看map。map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
# 举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下:
def f(x):
ret... |
aea29273ac316dd47827cc7e146dce458e6dfa62 | Dlyyy/self-study | /self-study/break.py | 80 | 3.5625 | 4 | n=1
while n<=100:
print(n)
n=n+1
if n>10:
break
print('END') |
1bf45f347bc6043c0827ed29c04d6352e159477b | Dlyyy/self-study | /self-study/高阶函数_传入函数.py | 85 | 3.640625 | 4 | def add(x, y, f):
return f(x) + f(y)
x = -5
y = 6
f = abs
print(add(-5, 6, abs)) |
df776aeebcb44bc1df230cd8c3ce346565ccf095 | Dlyyy/self-study | /self-study/Iterator.py | 1,570 | 4.1875 | 4 | # 迭代器
# 我们已经知道,可以直接作用于for循环的数据类型有以下几种:
# 一类是集合数据类型,如list、tuple、dict、set、str等;
# 一类是generator,包括生成器和带yield的generator function。
# 这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
# 可以使用isinstance()判断一个对象是否是Iterable对象:
from collections import Iterable
print(isinstance([],Iterable))
print(isinstance({}, Iterable))
print( isinstanc... |
063304837620d94b1ccc27b8a724788c25819d50 | harshit2118/MyAssignment | /Logic Test/question3.py | 473 | 3.78125 | 4 | list1 = ["[","{","("]
list2 = ["]","}",")"]
def perenOrder(st):
temp = []
for i in st:
if i in list1:
temp.append(i)
elif i in list2:
a = list2.index(i)
if ((len(temp) > 0) and
(list1[a] == temp[len(temp)-1])):
temp.p... |
c8a04cf45b7e0217b61b32af79eaee4f26ef788b | dieutth/Spark-OCR | /src/utils/pdf_generator.py | 1,399 | 3.671875 | 4 | import sys
import random
from PyPDF2 import PdfFileWriter, PdfFileReader
def generate_pdfs(base_pdf_path: str, n_pdfs: int, n_pages: int, output_folder: str) -> None:
"""
Generate pdf files by randomly selecting pages from a given base pdf file.
:param base_pdf_path: The path to the pdf file from which m... |
dbe34efc138f661488cddec9383ffe0182ccb55b | ishikasishodiya/Python_basics_1 | /py/38.py | 110 | 3.515625 | 4 | a={"apple","banana","ornage"}
#print(a[1]) cannot access like this as sets are unordered
for x in a:
print(x) |
ce32c1e5f04fac9a800e65e7f6cfc805781db393 | ishikasishodiya/Python_basics_1 | /py/17.py | 62 | 3.71875 | 4 | a=["apple", "banana", "orange"]
#for x in a
#print(x)
print(a) |
c8bdfcb1725bc6c6d356a964a4816551c3e70989 | ishikasishodiya/Python_basics_1 | /py/43.py | 81 | 3.859375 | 4 | a={"apple","banana","ornage"}
x=a.pop()
print(x) #shows the removed item
print(a) |
e28f8b61b10a2a473ae9ae83457f092360b4d4ae | ishikasishodiya/Python_basics_1 | /py/ll.py | 112 | 3.609375 | 4 | a=["apple","banana","ornage"]
a[3]="cherry"
print(a)
#error list mai you can add only using append() or insert() |
751f47b9dde38439acdb731b57cb449b2e664895 | Hao-Jiun-Tu/Python-practice | /basic/data_type.py | 402 | 4.03125 | 4 | # DATA TYPE
# num
31415
3.1415
# string
"Testing"
'Testing'
print("Testing")
print('Testing')
print("'Testing'")
print("\"Testing\"")
# boolean
True
False
# list
[3,4,5]
["Hello", "World"]
# tuple
(3,4,5)
("Hello", "World")
# set
{3,4,5}
{"Hello", "World"}
# dictionary
{"apple" : "fruit", "python" : "program"}
#... |
83e56bd859f3572d70a8848e583debbbbdda5736 | Hao-Jiun-Tu/Python-practice | /basic/object.py | 358 | 4.0625 | 4 | # HOW TO USE OBJECT
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def show(self):
print(self.x, self.y)
def distance(self, targetX, targetY):
return ((self.x-targetX) ** 2 + (self.y-targetY) ** 2) ** 0.5
p = Point(3,4)
p.show()
result = p.distance(0,0) # dista... |
9407961523b30a8f36b8341f8f12c078a315c270 | Hao-Jiun-Tu/Python-practice | /statistics/pds_filter.py | 734 | 3.71875 | 4 | # PANDAS-FILTER
import pandas as pd
# Series
data = pd.Series([30, 15, 20])
condition = (data > 18)
print(condition)
filteredData = data[condition]
print(filteredData)
print("=======================")
data = pd.Series(["Hello", "world", "PYTHON"])
condition = data.str.contains("P")
filteredData = data[condition]
prin... |
6a24d4a32428474af2f6a5176a411f42cfcbb3c0 | emil79/project-euler | /67.py | 487 | 3.65625 | 4 | """
Algorithm: start on the penultimate row. For each number in this row, add the
maximum of the two beneath it. Repeat for each row, ascending until the top
is reached. Print out the very top number.
"""
with open("data/67/triangle.txt") as f:
data = f.read()
numbers = [map(int, line.split()) for line in data.sp... |
7e64872ff443895762c58d92cb370c477d4670e3 | emil79/project-euler | /19.py | 619 | 4.21875 | 4 | # To make things easier, months and days-of-the-month
# are counted from 0. We start on Sunday January 6, 1900
year, month, day = 1900, 0, 6
days_in_month = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
sundays = 0
while year < 2001:
if day == 0 and year > 1900: # We don't regard 1900 as being the 20th Century
... |
eab1ecdbfb63fa718f50c72faf3d29a460601478 | emil79/project-euler | /69.py | 936 | 3.5 | 4 | def primes(n):
L = range(n)
for i in range(n):
if L[i] > 1:
for j in range(2 * i, n, i):
L[j] = 0
return [i for i in L if i > 1]
# To speed things up (quite considerably, actually), we use a cache.
# This could be implemented as a memoization decorator. We preload
# the... |
456e66b6fd29b7fa68630d792462864452d67a63 | emil79/project-euler | /65.py | 376 | 3.5625 | 4 | def e():
yield 2
yield 1
k = 2
while True:
yield k
yield 1
yield 1
k += 2
# Using well-known recurrence relation; see e.g.
# http://en.wikipedia.org/wiki/Continued_fraction#Some_useful_theorems
H = [0, 1]
for a in e():
H.append(a * H[-1] + H[-2])
if len(H) == 10... |
de5c6b092956d654e47d20755e01eff71c313146 | emil79/project-euler | /59.py | 394 | 3.765625 | 4 | from itertools import product
import json
numbers = json.loads("[{}]".format(open("data/59/cipher1.txt").read()))
for key in product(range(ord('a'), ord('z') + 1), repeat=3):
transformed_numbers = [n ^ key[i % 3] for i, n in enumerate(numbers)]
plaintext = "".join(chr(n) for n in transformed_numbers)
if "... |
c47fd44f9067041bce3dafd373a00ff1b09690d3 | emil79/project-euler | /62.py | 308 | 3.546875 | 4 | digits_to_cubes = {}
for n in range(1, 10000):
ordered_digits = tuple(sorted(str(n ** 3)))
digits_to_cubes.setdefault(ordered_digits, []).append(n)
candidates = set()
for digits, cubes in digits_to_cubes.items():
if len(cubes) == 5:
candidates.add(min(cubes) ** 3)
print min(candidates)
|
90ebd36431106b948860dd15fc75b83d39e9332e | BrunoTruber/EdTech | /módulo_01/06_função/exemplos/exemplos.py | 8,378 | 4.0625 | 4 |
# lista1 = [4, 3, 2, 1, 0]
# lista2 = ["A", "B", "C"]
# lista3 = [1, 2, "um", "dois"]
# lista4 = [10, 20, [30, 40]]
# lista5 = [10, 20, [30, 40, [50, 60]]]
#índice 2 = [30, 40, [50, 60]]
#índice 2 do índice 2 = [50, 60]
# print(lista1[0]) # Printa apenas o indíce 0 da lista1
# print(lista2[2])
# print(lista3)
# pri... |
e9378af6ebeef58f283b3e43ac1ad6191f55e010 | amata525/python | /brain/complex/logistic_model.py | 810 | 3.90625 | 4 | #coding:utf-8
import numpy as np
from pylab import *
# 指数的成長モデルとロジスティック成長モデル
#写像funcで初期値をinitialとしたときの起動を描画
def drawModel(func, initial):
nList = []
yList = []
nList.append(0)
yList.append(initial)
for n in range(1, 10):
nList.append(n)
yList.append(func(yList[n-1]))
print ... |
91302bb05aad5ce0679590e281d123eac391d799 | NathanYP/ListenAgain | /scripts/init_db.py | 525 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import sqlite3
import os.path
db_file = os.path.join(os.path.dirname(__file__), '..', 'data', 'app.db')
print('db file: %s', db_file)
def create_table_audios():
db = sqlite3.connect(db_file)
cur = db.cursor()
db.execute('''
create table if not exists audio_files (
id int p... |
90f6f3cb78ba7566d43e1ab91aaa02ae95372ae3 | liuxiang0/fibonacci | /src/fibonacci.py | 10,658 | 3.609375 | 4 | #!/usr/bin/python3
# -*- coding = utf-8 -*-
"""
Fibonacci: 最经典算法,用Python实现,递归、迭代、公式法、矩阵方法等多种方法
下面给出了多种实现fibonacci(n)的方法,全部是用Python语句实现,
测试环境: Python3.8.6 64-bit Windows
Author: Liu Xiang
Email : liuxiangxyd@163.com
"""
from sympy import log, S
#from sympy.core import GoldenRatio # 矩阵运算需要其中的Matrix类
class Fibase(obje... |
86285b2748beb2b7ebb981fa8428725a6dc478cf | kakashiisawesome/Programs | /Arrays/BuySellStock.py | 562 | 4 | 4 |
# Write a program that takes an array denoting the daily stock price, and retums the maximum profit
# that could be made by buying and then selling one share of that stock. There is no need to buy if
# no profit is possible.
def stockProfit(A):
minPrice = A[0]
maxProfit = 0
for i in range(1, len(A)):
... |
567b789ab653027df90e9f94986be99322535bf0 | kakashiisawesome/Programs | /Arrays/PascalsTriangle.py | 400 | 3.765625 | 4 |
def generate(numRows):
res = []
for i in range(numRows):
if i == 0:
res.append([1])
elif i == 1:
res.append([1,1])
else:
temp = [1]
for j in range(len(res[i-1])-1):
temp.append(res[i-1][j] + res[i-1][j+1])
tem... |
41831f57b9d1968510c345eed7713fe3fb137cb2 | kakashiisawesome/Programs | /Arrays/BlocksToSpellWord.py | 1,562 | 3.5 | 4 |
def assignWords(target, index, words):
choices = []
for w in words:
if target[index] in w:
choices.append(w)
if index == len(target)-1:
return len(choices) > 0
for c in choices:
remaining = words.copy()
remaining.remove(c)
if assignWords(target, i... |
2156f0395c72debb7615e4ddf4caa9a3586e0e8e | kakashiisawesome/Programs | /Arrays/CountSquareSubmatricesWithAll1s.py | 752 | 3.59375 | 4 |
def checkSubMatrix(x, y, n, matrix):
for i in range(x, x+n):
for j in range(y, y+n):
if matrix[i][j] != 1:
return False
return True
def countSquares(matrix):
m = len(matrix)
n = len(matrix[0])
res = 0
# Count all 1X1 matrices
for row in matrix:
... |
fd11d94ac587af1e9d20e68abcc1ee4227ef2725 | khanfarhan10/thejumblewordgame | /gamefinale.py | 5,177 | 3.90625 | 4 | import random
# import only system to know OS type and store in the variable "name"
from os import system, name
# import sleep to show output for some time period
from time import sleep
#the default dictionary which will run no matter what
global cwords
cwords=['rainbow', 'dart', 'general', 'chemical', 'humb... |
80ef10e555b966961d302da8c542498bc9b681ed | jali-clarke/Python | /SMS Python Practice/student.py | 5,753 | 4.40625 | 4 | class StudentsandCourses:
'''Courses and the students enrolled in them.
The class creates a dictionary of courses and their students and a list
of all students, with each student appearing once in that list. It will
support adding new students, new courses, students enroling and dropping
cour... |
39b94f9fd518a892aefa1571135a98717364ee74 | Zgoss/COP1500-project-1 | /COP1500project.py | 793 | 4.28125 | 4 | """
Produces the number of characters, words, and the count of each word in a
sentence entered by the user
__author__= "Zachary Gossett"
COP1500-project-1
"""
print("Hello, this program will calculate the number of characters, "
"words,\nand count of each word of a sentence. Please enter a "
"sentence,\nbut... |
76cc80cd9597aa7246ccec6553225ba6ee01004a | nihilochyan/AlgorithmFoundation | /Divide-and-Conquer/Strassen-Maxtrix-Multipication.py | 4,376 | 3.859375 | 4 | """
Square Matrix Multiplication:
Cij = sigma(1,n){Aik * Bkj}
"""
from random import choice
def generate_matrix(n):
matrix = [[choice(range(-10, 10)) for j in range(n)] for i in range(n)]
return matrix
matrix1 = generate_matrix(2)
matrix2 = generate_matrix(2)
for i in matrix1:
print(i)
print()
for i in m... |
02f69f712f4502ede86bc7ec6621e527a34a17de | nihilochyan/AlgorithmFoundation | /Sorted/merge-sort.py | 844 | 3.640625 | 4 | from random import choice
a = []
for i in range(0, 20):
a.append(choice(range(0, 20)))
print(a)
def merge(a, l, p, r):
left = a[l: p+1]
right = a[p+1: r+1]
i = 0
j = 0
k = l
while i < len(left) and j < len(right):
if left[i] > right[j]:
a[k] = left[i]
i = i... |
1275eb226bc2fe045349a7435476c532e58201a0 | GRustle00/pathofpython | /lpthw/ex11/ex11_studydrill.py | 331 | 4 | 4 | print("What's your favorite food?", end=' ')
food = input()
print(f"realy you like {food}? ok... that's an odd taste... what's your favorite restaurant?", end=' ')
restaurant = input()
print(f"{restaurant}!!!? Oh... nah thanks... good bye...any last words?", end=' ')
last_words = input()
print(f"{last_words}? \N{NAUSEA... |
abaebecd626bd75ef85cfeb78c6f25234cddd407 | GRustle00/pathofpython | /lpthw/ex9/ex9.py | 702 | 4.125 | 4 | # Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun" #This is just a regular viarable with a string.
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"# This variable string has a line break function to separate the months in new lines
print("Here are the days: ", days)# Stan... |
5308755e88e68ea0008e2ba23bbffff54d2126be | tinaba96/coding | /acode/abc192/b.py | 248 | 3.859375 | 4 | S = str(input())
flag = True
if len(S) == 1 and S[0].isupper():
print('No')
exit()
for s in range(0,len(S)-1, 2):
if S[s].isupper() or S[s+1].islower():
flag = False
if flag == True:
print('Yes')
else:
print('No')
|
5f018e4ade34dd7d683721683942c65861dc0f8d | tinaba96/coding | /acode/typical90/038/ans.py | 240 | 3.5 | 4 | A, B = map(int, input().split())
def gcd(a, b):
if a < b: a, b = b, a
while a % b:
a, b = b, a % b
return b
l = A // gcd(A, B)
if l > 10**18 // B:
print('Large')
else:
print(l * B)
# lcm(a, b) = a*b/gcd(a, b)
|
f6be647bfd6a8500a82d9a1c76c5cb2e2897800e | tinaba96/coding | /algodstr/heap.py | 2,475 | 3.953125 | 4 | def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
return arr
class heap():
def __init__(self, arr):
self.list = []
for num in arr:
self.insert(num)
def percolate_up(self):
index = len(self.list)-1
while index != 0 and self.list[index] < self.list[(index-1)//2]:
self.list = swap(self... |
f141db0c95b8c360f58a35820ddb86fac80bedc8 | tinaba96/coding | /goo/find_longest_word.py | 3,224 | 4.125 | 4 | '''
#https://techdevguide.withgoogle.com/paths/foundational/find-longest-word-in-dictionary-that-subsequence-of-given-string/
def find_longest_word(S, D):
ans = ""
for ele in D:
proper_word = True
for alp in ele:
if alp not in S:
proper_word = False
... |
b6542276cde023d94b8618fe4f6445c3040f204e | tinaba96/coding | /acode/abc239/d/main.py | 647 | 3.9375 | 4 |
def isPrime(n):
if n < 2:
# 2未満は素数でない
return False
if n == 2:
# 2は素数
return True
for p in range(2, n):
if n % p == 0:
# nまでの数で割り切れたら素数ではない
return False
# nまでの数で割り切れなかったら素数
return True
if __name__ == "__main__":
A, B, C, D = list(map(int, input().split()))
for i... |
abde22bda3e828d05aa9281a28a4248d9710a6fb | tinaba96/coding | /acode/abc198/a.py | 95 | 3.71875 | 4 | N = int(input())
if N == 1:
print('0')
elif N == 2:
print('1')
else:
print(N-1)
|
699dbad69012614ce38d72805ff07caac6c4297d | tinaba96/coding | /lcode/go/others/plus_one_linkedList.py | 1,736 | 3.5625 | 4 |
#369
'''
Input: [1,2,3]
Output: [1,2,4]
'''
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
while self.next:
print( '%s' % (self.val))
self = self.next
return '%s' % (self.val)
class Solution... |
be939ac4357f9e47c506957d63a892ff588a65cf | tinaba96/coding | /cci/Rec_DP/8_1.py | 737 | 3.75 | 4 |
def TripleHop(x):
if x < 0:
return 0
if x == 0 or x == 1:
return 1
return TripleHop(x-1) + TripleHop(x-2) + TripleHop(x-3)
def Method2(x):
memo = [-1]*(x+1)
return TripleHopRecursive(x, memo)
def TripleHopRecursive(x, memo):
if x < 0:
return 0
memo[0] = 1
if x >= 0:
memo[1] = 1
if ... |
8ea7582a390380b05b54d9dd5b93811d59dacf78 | tinaba96/coding | /cci/Rec_DP/8_13.py | 1,459 | 4.09375 | 4 | #テキストの解法2だと思われる
def stack_boxes(boxes):
sorted_boxes = sorted(boxes, key = lambda a: a.height)
sorted_boxes.reverse()
return stack_more_boxes(sorted_boxes, None, 0)
def stack_more_boxes(boxes, base, index):
if index >= len(boxes):
return 0
without_box_height = stack_more_boxes(boxes, base, ... |
891a018d2777fbe08655617a9e8963d1ccae22d5 | Sibert-Aerts/dfasm | /src/dfasm/Parser.py | 20,531 | 3.53125 | 4 | import Instructions
import Assembler
import Lexer
import Symbols
import math
from Encoding import *
precedence = {
"asterisk" : 0,
"slash" : 0,
"percent" : 0,
"plus" : 1,
"minus" : 1,
"lessthanlessthan" : 2,
"greaterthangreaterthan" : 2,
"and" : 3,
"or" : 4
}
operations = {
"pl... |
ec0469aa4f4547ced4c770aa4da66e73baa841c1 | jadmasz/Skrypty | /lab_python_1/14.py | 690 | 3.625 | 4 | import random
import math
def W(matrix):
if len(matrix) == 1:
return matrix[0][0]
else:
A = 0
for x in range(len(matrix)):
try:
new_matrix = matrix[:x] + matrix[x+1:]
except IndexError:
pass
for i in range (len(new_matrix)):
new_matrix[i] = new_matrix[i][1:]
A = A + math.pow(-1, 2+x) * m... |
0e6244b1cc51dade30cb8a1cc009cdbab514e23b | googleknight/project-euler-solutions | /eu10.py | 280 | 3.859375 | 4 | def is_prime(x):
i=2
while i**2<=x:
if x%i==0:
return False
i+=1
else:
if x>1:
return True
else:
return False
sum=0
for x in range(2000001):
if is_prime(x):
sum+=x
print (sum) |
2f3ce059d0418198b0a781e31e7707c6e358ccb3 | googleknight/project-euler-solutions | /eu2.py | 267 | 3.578125 | 4 | def fibo(num):
first=1
second=2
if num<3:
return num
else:
for i in range(2,num):
sum=first+second
first=second
second=sum
if second>=4000000:
return first
return second
sum=0
for i in range (1,33):
if fibo(i)%2==0:
sum+=fibo(i)
print(sum) |
a08d5dd4db08a5263730dbae83d9ba8086b9af16 | Sinketsu/informatic-lessons | /ege_27_sort_by_string/main.py | 917 | 3.625 | 4 | # python 3
n = int(input())
m92, c92 = 3010, 0
m95, c95 = 3010, 0
m98, c98 = 3010, 0
for i in range(0, n):
# Так как это ЕГЭ, то мы не будем тратить процессорное время на проверки входных значений,
# а также не будем проверять результаты функций и обрабатывать исключения.
# Мне ужасно обидно за это, и я обещаю ни... |
7a80dc45c53c62872ed857351488491e568dafcb | MAdisurya/data-structures-algorithms | /questions/merge_sorted_arrays.py | 2,153 | 4.34375 | 4 | """
In order to win the prize for most cookies sold, my friend Alice and I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists. Write a function to merge our lists of orders in... |
36d7961ddb37f5cefe2b1db065a94461baac8635 | MAdisurya/data-structures-algorithms | /questions/highest_product_of_three.py | 2,042 | 4.1875 | 4 | """
Given a list of integers, find the highest product you can get from three of the integers.
The input list_of_ints will always have at least three integers.
"""
import unittest
def highest_product_of_3(list_of_ints):
if len(list_of_ints) < 3:
raise Exception()
high = max(list_of_ints[0], list_of_in... |
2d2e9c0a1470e259897d2f50b39dc7102e944bd9 | vinothkumarnair/python | /conditions.py | 496 | 4.03125 | 4 |
#simple conditions
user_name = input("enter your name")
if user_name == "vinoth" :
print("its me")
elif user_name == "kumar" :
print("its me again")
else:
print("others")
print("done compare")
#compare with list
my_name_list = ["vinoth","kumar","nair"]
name_to_check = input("enter your name")
if name_to_... |
8a10e0512c6da3ca1402eb3f193ca3253b568038 | 232620176/python | /workspace/myFunc.py | 538 | 4.15625 | 4 | #-------------------------------------------------------------------------------
# Name: 函数模块
# Purpose:
#
# Author: Hydra
#
# Created: 07/08/2017
# Copyright: (c) Hydra 2017
# Licence: <com.hydra>
#-------------------------------------------------------------------------------
def fibonacci(num)... |
7fe0dc330b25a2f2f5739f0513837af02fffb8fd | bharatsesham/Practice | /Hadoop/count_mapper.py | 335 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
import re
def purify(line):
k = re.sub('[°-°|\:,;!@#$%^&*()""''0123456789-_`“†✠.•”’—{}]-\'', '', line)
return k
for line in sys.stdin:
line = line.strip()
line = line.split(" ")
words = [w for w in line if w.isalpha()]
for word in words:
print('%s\t%s' % (word, 1))
|
002cace8a7a1da222dcef96396d20d80be650a51 | clarissavlsqz/Python | /Level1.py | 507 | 3.65625 | 4 | # Write a function that capitalizes the first and fourth letters of a name
def old_macdonald(name):
first = name[:3]
second = name[3:]
return first.capitalize() + second.capitalize()
# Given a sentence, return a sentence with the words reversed
def master_yoda(sentence):
new = sentence.split()
new.... |
f85effbe65f39d4ca46bfa259e7119fc477b5d0d | cctong-castiel/AnomalyModel | /handler/ziphelper.py | 3,402 | 3.515625 | 4 | import os
import tarfile
import glob
import logging
logging.basicConfig(level=logging.INFO)
def tar_compress(archive_name, source_dir, out_dir):
"""
input: zip_file name, directory of the file you want to zip
output: tar.gz file in current directory
"""
logging.info("compress file {}".format(archiv... |
bf99a61a9a6d8f600747f1dc86940bace4ec5ba3 | Bharathkumar-nb/Poco-Localization | /poco/main/media/course_1/module_7/assessmentFiles/module4_challenge_4_new.py | 1,508 | 3.640625 | 4 | #Module 4
#Challenge 4
'''
mean_applicantincome = float(sum_applicantincome_column)/len(int_applicantincome_column)
'''
import sys
def report( name, shortd, longd):
d = {'Name': name, 'Short': shortd, 'Long': longd}
print(str(d))
#Mock data goes first
import pandas as pd
xurl = 'https://docs.google.com/spreadshe... |
f37d3006272e1d2ecc7724ea625a981ee4ebb9ce | smu/gaerbox | /gaerbox/__init__.py | 3,617 | 3.53125 | 4 | import os
import logging
from datetime import datetime
import sqlite3
import RPi.GPIO as GPIO
class TemperatureSensor():
''' Read the current temperature from the temperature sensor.'''
# helpful references:
# * https://st-page.de/2018/01/20/tutorial-raspberry-pi-temperaturmessung-mit-ds18b20/
def ... |
ead7cbe9236abd043916d39713929721d7a5e548 | Ibrahimjalife/Bootcamp2019 | /classes/persona.py | 428 | 3.75 | 4 |
class Persona:
edad = 0
def __init__(self, un_nombre):
self.mi_nombre = un_nombre
print("Hola naci, me llamo", self.mi_nombre)
def cumple(self):
self.edad = self.edad + 1
def apellido(self):
self.ap = un_ap
print("Mi apellido es", un_ap)
pepe = Person... |
8817260111d4dec78344c39ed3fb44126f8af2c4 | imossim/Random-Stuff | /Pi_Generator_Monte_Carlo.py | 842 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 9 09:38:19 2018
@author: imossim
"""
import numpy.random as random
import math
#Monte Carlo style method to approximate pi
#Equation of semicircle is y = sqrt(r-x^2)
# should points on the line be included?
def in_quadrant(rad,x,y):
if(pow(y,... |
b5656a686ee3ea9f5e4a04de1ff096a83d71a2f2 | dallasmcgroarty/python | /DataStructures_Algorithms/graphs/graph_again.py | 952 | 3.671875 | 4 | from collections import OrderedDict
from enum import Enum
class State(Enum):
unvisited = 1
visited = 2
visiting = 3
class Node:
def __init__(self, num):
self.num = num
self.visitState = State.unvisited
self.adjacent = OrderedDict() # key = node, value = weight
def __str__... |
66d7562956563a713ade1def979b70af0e8421ca | dallasmcgroarty/python | /DataScience_MachineLearning/Matplotlib/part2.py | 1,236 | 3.671875 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,5,11)
y = x ** 2
fig, axes = plt.subplots(nrows=1,ncols=2)
# axes is a list of matplotlib axes, so can iterate through
print(axes)
# for current_ax in axes:
# current_ax.plot(x,y)
#axes.plot(x,y)
axes[0].plot(x,y)
axes[0].set_title('First')
... |
252ccda2ff79fc8c76360b3b0db2e09c27edc370 | dallasmcgroarty/python | /General_Programming/functions/functions.py | 1,289 | 4.28125 | 4 | #functions in python
#dont repeat code
#cleans up code
#can be reused elsewhere
def say_hi():
print('Hi!')
say_hi()
print()
#return values from functions
def say_hi2():
return 'Hi!'
greeting = say_hi2()
print(greeting)
print()
#create function that returns list of even numbers from 1 to 50 (not including 50... |
245e79776583d3f53c2d51767c84f3cc4d19646b | dallasmcgroarty/python | /DataScience_MachineLearning/Pandas/data_in_out.py | 865 | 3.59375 | 4 | import pandas as pd
#read csv file
ex = pd.read_csv('Pandas/example.csv')
print(ex)
print()
df = pd.read_csv('Pandas/example.csv')
# write dataframe to csv file
df.to_csv('Pandas/My_output',index=False)
df = pd.read_excel('Pandas/Excel_Sample.xlsx',sheet_name='Sheet1')
print(df)
print()
# write dataframe to excel ... |
82055e22eb35930b661176e3ffa3519fa9cb04a8 | dallasmcgroarty/python | /General_Programming/BI_Functions/lambdas.py | 208 | 3.921875 | 4 | # lambdas
# best used when passing a function into parameters of another function
def square(num): return num * num
square2 = lambda num: num * num
add = lambda a,b: a + b
print(add(3,10))
print(square(9)) |
d6573df33ac27799dd7aedf4bdc1e673e7ae270b | dallasmcgroarty/python | /General_Programming/strings/slicing.py | 409 | 4.34375 | 4 | #slicing in python
#reversing strings
string1 = "wassup"
string2 = string1[::-1] #"pussaw"
print(string2)
#syntax --> some_list[start:end:step] - exclusive on end
#change values in a list
numbers = [1,2,3,4,5]
numbers[1:3] = ['a','b','c']
print(numbers) # [1,'a','b','c',4,5]
#swapping values in lists or strings
na... |
f5d04181b91be5dc8c5aea9e56ab4d7761a8482f | dallasmcgroarty/python | /DataScience_MachineLearning/Pandas/missingdata.py | 871 | 4.09375 | 4 | # fixing missing data in pandas
import numpy as np
import pandas as pd
# dataframe with some missing values
d = {'A':[1,2,np.nan],'B':[5,np.nan,np.nan],'C':[1,2,3]}
df = pd.DataFrame(d)
print(df)
# drop na method - will drop any row with a Null value
# need inplace argument set to true to affect original dataframe
df... |
0514482a26ff1dd86c7a7b74f9a31289b02755ce | dallasmcgroarty/python | /General_Programming/FileIO/file_stats.py | 880 | 3.96875 | 4 |
# create a function that accepts a file and returns a dictionary where
# {lines: number of lines, words: number of words, characters: number of characters}
# in the file
def statistics(fileN):
with open(fileN) as file:
lines = file.readlines()
return { "lines": len(lines),
"words": sum(l... |
9f7116eff45bf617640692ff55ff0468d935419e | dallasmcgroarty/python | /General_Programming/iterators/beat_maker.py | 292 | 3.96875 | 4 | # infinite generator
# allows you to just hold one value instead of a giant list or dict
def current_beat():
nums = (1,2,3,4)
i = 0
while True:
if i >= len(nums): i = 0
yield nums[i]
i += 1
beat = current_beat()
num = 5
print(next(beat))
print(next(beat)) |
9aaca1c14c5edfd1508fe21ef18d65e34d9ac2d9 | dallasmcgroarty/python | /DataScience_MachineLearning/Seaborn/categorical_plots.py | 1,645 | 3.609375 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
tips = sns.load_dataset('tips')
print(tips.head())
# using plots to see categorical differences
# bar plot **
# allows you to aggregate the categorical data based of some function
# group by action
# one category column, one numerical column
# e... |
33c4b7cbf1bdece0035e33b2fbe40eb15fdd92a2 | dallasmcgroarty/python | /General_Programming/sets_tuples/tuples_sets.py | 2,686 | 4.46875 | 4 | #tuples and sets in python
#tuple is an ordered collection or grouping of items
tuple1 = (1,2,3,4)
#tuples are immutable, meaning they can't be changed after created
alphabet = ('a', 'b', 'c', 'd')
print(type(alphabet))
print()
#tuples faster than lists, safer from bugs/changes you don't want
#work as valid keys in a... |
42a11139329d687a62614ce03e489b1d94bb8b01 | dallasmcgroarty/python | /General_Programming/Error_Handling/try_except.py | 939 | 4.09375 | 4 | # handling errors
# try and excpet blocks
# be specific when using except or raise
# helps to identify the root error
d = {'name':'Ricky'}
def get(d,key):
try:
return d[key]
except KeyError:
return None
print(get(d,'city'))
print(get(d,'name'))
# else and finally
# else only runs if try doe... |
26a3ffcdf5d7f460dd41ebe2316381c4edceda3d | dallasmcgroarty/python | /DataScience_MachineLearning/Seaborn/matrix_plots.py | 794 | 3.546875 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
flights = sns.load_dataset('flights')
print(tips.head())
print(flights.head())
# want data in matrix form first
# in order to use heatmap
tc = tips.corr()
print(tc)
# heatmap **
# annot argument to specify number value
sns.heatmap... |
eafa7714b93f226e344f8556df1528c314590911 | alejorods/fibonacci-stuff | /fibonacci-sequence.py | 584 | 4 | 4 | # Programa que genera la secuencia
# de Fibonacci hasta el término
# solicitado por el usuario.
try:
element = int(input("¿Cuántos elementos de la secuencia quieres?: "))
fibo_list = [0, 1]
if element <= 0:
print("¡Debes ingresar un número entero mayor que cero")
elif element == 1:
pr... |
e0f6c9f52594a0ca964dd058e8a6fdeb6d1b7af0 | stasDomb/PythonHomeworkDombrovskyi | /Lesson2Homework/SecondExercise.py | 489 | 3.78125 | 4 |
from collections import defaultdict
def most_frequent(data):
# your code is here
##str_counter_dict = defaultdict(int)
##result_dict = {}
##for str_dict in list_var:
## str_counter_dict[str_dict] += 1
## result_dict.update({str_counter_dict[str_dict]: str_dict})
##return result_dict... |
03371f24bfad464e941c57b1af5a8b1f811a4ac6 | JoshuaJWatt/codenation-course | /Day2/variables.py | 1,279 | 3.78125 | 4 | import random as r;
import datetime as t;
#A1
names = ['James', 'Robert', 'John', 'Michael', 'William', 'David', 'Richard', 'Joseph'];
ages = range(19, 99);
colours = ['red', 'green', 'blue', 'indigo', 'violet'];
print("{} is {}, and their favourite colour is {}".format(names[r.randint(0, len(names)-1)], ages[r.randi... |
bb4bfb31dbd4a51179b6d3da13cc9b01c3d47928 | KnoxMakers/CodingWorkshops | /euler/euler1/euler1.py | 188 | 3.9375 | 4 | #!/usr/bin/python
x = range(1,1000)
woot = 0
for i in x:
if not i%3 or not i%5:
print i, "is a multiple of 3 or 5"
#woot += i
woot = woot + i
print "Total:",woot
|
25cfdb7e8d8c3eb37cf32fa03d1b32941c97c377 | shuvava/python_algorithms | /bst/test_bst_node_query.py | 3,838 | 3.78125 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2017-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
Test of base_bst module
https://docs.python.org... |
70477a338e298bbd52ee1fd30d1278257bb667ec | shuvava/python_algorithms | /design_patterns/tips.py | 773 | 4.0625 | 4 | #!/usr/bin/env python3
# encoding: utf-8
x = (1, 2, 4, 8, 16)
def func_opt_arg(value, seq=None):
if seq is None:
seq = []
seq.append(value)
return seq
if __name__ == '__main__':
print(x)
a, b, c, d, e = x
print(a, b, c, d, e)
a, *y, e = x # The point is that the variable with * ... |
9af8e688cf8e8cec589f31ce570aced0fc1cf67d | shuvava/python_algorithms | /graph/get_all_paths.py | 1,798 | 3.921875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2019-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Node:
def __init__(self, id):
s... |
5497493c816108b48a5c560d543b2e8d5ec4de83 | shuvava/python_algorithms | /sort/radix.py | 2,424 | 3.953125 | 4 | #!/usr/bin/env python3ß
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2017-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""
https://ocw.mit.edu/courses/electrical-engine... |
a206eafd6129916f9be40b9bbd65743316ee0f97 | shuvava/python_algorithms | /sort/merge_sort.py | 2,856 | 3.65625 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2017-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''Merge sort
Complexity: O(n*ln(n))
require double... |
4c7e365e6e24623ab3d2acd59f9c366c672d124b | shuvava/python_algorithms | /data-structure/list/listCycles/src/list_cycles.py | 1,898 | 4.21875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2019-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""
find a cycle in a linked list
"""
class Linke... |
ae3139aab01dd85ded0c672b4a9bd385c26b5f04 | shuvava/python_algorithms | /bst/test_avl.py | 1,215 | 3.765625 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2017-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
Test of base_bst module
https://docs.python.org... |
44688fdce64f0f806feabadf12c46d3608790d6e | shuvava/python_algorithms | /search/recursive_linear.py | 1,558 | 3.90625 | 4 | '''Implementation of Recursive-linear-search
Procedure RECURSIVE-LINEAR-SEARCH.A; n; i; x/
Inputs: Same as LINEAR-SEARCH, but with an added parameter i .
Output: The index of an element equaling x in the subarray from AOEi
through AOEn, or NOT-FOUND if x does not appear in this subarray.
1. If i > n, then return NOT-... |
b263e4435c922aafd8393a696a16692c2686185e | shuvava/python_algorithms | /bst/base_heap.py | 5,789 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2017-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""
Implementation of binary search tree (BST) - HE... |
94a24c278107316d05e3613802ad993eba830abb | shuvava/python_algorithms | /design_patterns/enum_sample.py | 226 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
enum example
"""
from enum import Enum, auto
class Fruit(Enum):
APPLE = auto()
ORANGE = auto()
GUAVA = auto()
if __name__ == '__main__':
print(Fruit.APPLE)
|
7ba7e670936dbedfbe98e11181b4ce6a52ad2891 | shuvava/python_algorithms | /bst/bst_heap_utils.py | 6,367 | 4 | 4 | import random
from os import path
DEFAULT_LENGTH = 10
def _print_tree(heap, index, with_ids=False, with_values=True):
"""Recursive function used for pretty-printing the binary tree.
In each recursive call, a "box" of characters visually representing the
current subtree is constructed line by line. Each l... |
ff50612d531ec6c1055e8305566088dfb0c3345c | shuvava/python_algorithms | /bit_operations/func.py | 2,278 | 4.125 | 4 | # -*- coding: utf-8 -*-
def get_mask(bits):
return (1 << bits) - 1
def get_bit(value: int, bit: int) -> bool:
"""return True if bit is set or False in opposite case"""
return True if value & (1 << bit) > 0 else False
def set_bit(value, bit):
return value | (1 << bit)
def clear_bit(value, bit):
... |
8dcfc1c9f7bf097231d11fa87d339fceb11dbf27 | kylezeeuwen/ds-stackoverflow2020-analysis | /notebook/multiple_choice_responses/compute_multiple_choice_response_stats.py | 4,337 | 3.78125 | 4 | import pandas as pd
def compute_multiple_choice_response_stats (df, mc_questions):
'''
INPUT:
df - dataframe - survey responses
mc_questions - array - list of columns that contain "choose all that apply" survey responses
OUTPUT:
question_counts - dataframe - question, question_response_count
... |
479eca8a94606b0b4af47e78fbb79152206f217b | thefirstcomma/Learn-Python-the-Hard-Way | /ex33.py | 392 | 4.1875 | 4 | numbers = []
def while_loop(end):
i = 0
while i < end:
print "The top i is: %d" % i
numbers.append(i)
i += 3
print "Number's now: ", numbers
print "At the bottom i is: %d" % i
print "\nThe numbers: "
for num in numbers:
print num
while_loop(8)
del numbers[:]
print "Now For Loops"
for start in... |
93c6c89e73aba9cc133bdaf83ab28817cee8db20 | thefirstcomma/Learn-Python-the-Hard-Way | /ex20.py | 904 | 4.1875 | 4 | from sys import argv #import for command line input
script, input_file = argv #var setup for argv
def print_all(f): #function print_all uses .read()
print f.read()
def rewind(f): #function uses.seek()
f.seek(0)
def print_a_line(line_count, f): #function prints 1 line at a time
print line_count, f.readline() #... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.