blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
89276c4f46022a90079f99469c9a2d824dce9d16 | niki4/leetcode_py3 | /easy/122_best-time-to-buy-and-sell-stock-ii.py | 2,536 | 4.15625 | 4 | """
Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy... |
19ca147d12684d211bf0a38038515ad705ad0759 | msleylok/dz_py_1291-21 | /2.2.py | 182 | 3.765625 | 4 | def CP(a,b,c):
S = (a+b+c)/3
return S
a= int(input())
b= int(input())
c= int(input())
S = CP (a,b,c)
print("Среднее арифметическое = ", S)
|
d7d055d054b2f2e22f8538b13af0d99dcc3e0e7c | nikmalviya/Python | /Practical 3/card_game.py | 494 | 3.703125 | 4 | import random
import math
num = random.randint(1, 52)
card = math.ceil(num % 13)
cardtype = math.ceil(num / 13)
print(num)
if card == 1:
card = "Ace"
elif card == 11:
card = "Jack"
elif card == 12:
card = "Queen"
elif card == 0:
card = "King"
if cardtype == 1:
cardtype = "Clubs"
elif cardtype == 2:
... |
5aa5da2c7c4390356e431da072aee40f11b99d55 | killingwolf/python_learning | /homework/Part 3/3-1.py | 493 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: killingwolf
# Email: killingwolf@qq.com
def find_median(L):
if L:
L.sort()
if len(L) % 2:
value = L[len(L) / 2]
else:
value = (L[len(L) / 2 - 1] + L[len(L) / 2]) / 2
return value
else:
rais... |
33cf82899b0877c364badbff5089cb76ea0f8127 | sanathkumarbs/coding-challenges | /recursion/basic/pairstar.py | 864 | 4.09375 | 4 | """Pair Star.
Given a string, compute recursively a new string where
identical chars that are adjacent in the original
string are separated from each other by a "*".
pairStar("hello") > "hel*lo"
pairStar("xxyy") > "x*xy*y"
pairStar("aaaa") > "a*a*a*a"
http://codingbat.com/prob/p158175
"""
def pairstar(input, index... |
29816fbdd471f9d4a3e3627bfc883936e02a15d1 | lydiayhuang/HB-Self-Assessments-Dict-OO | /assessment-OO.py | 3,121 | 4.78125 | 5 | """
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
1.1 Abstraction: Hide details we don't need and prevent errors from happening. Abstraction lets you focus on what the object does instead of how it does it.
1.2 Encapsulation: Encap... |
b73808a2426d4703750e20bd1e981ddd89681365 | joorgej/tytus | /parser/fase2/team15/TytusDB_G15/PLSQL/tfPLSQL.py | 1,327 | 3.640625 | 4 | from enum import Enum
class TIPO_DATO(Enum):
VARIABLE = 1
ARREGLO = 2
ENTERO = 3
FLOTANTE = 4
CHARACTER = 5
STRING = 6
ETIQUETA = 7
class Funcion():
'Esta clase representa una funcion dentro de nuestra tabla de funciones'
def __init__(self, tipo_funcion, id, tipo, parametros, te... |
88f2ae060d907b9b48546332406b9826434f6470 | M-Rafay/Python | /numpy/10.py | 191 | 3.5625 | 4 | import numpy as np
def f(x,y):
return 10*x+y
b=np.fromfunction(f,(5,4),dtype=int)
print(b)
print(b[2,3])
print(b[0:5,1])
print(b[:,1])
print(b[1:3,:])
print(b[:,1:3])
print(b[-1]) |
cc983630a7b82197a79ac9d07fa8b31ad947e881 | atscott/StringSearchAlgorithms | /lib/algorithms/KnuthMorrisPratt.py | 1,510 | 3.703125 | 4 | from lib.algorithms.StringSearcher import StringSearcher
__author__ = 'http://en.wikibooks.org/wiki/Algorithm_Implementation/String_searching/Knuth-Morris-Pratt_pattern_matcher'
class KnuthMorrisPratt(StringSearcher):
def search(self, text, pattern):
"""Yields all starting positions of copies of the patt... |
161bc33c08582f680b3a4bf95744b6b4727a0734 | jaehui327/PythonProgramming | /Lab0508/Lab05.py | 153 | 4.0625 | 4 | # String split 메소드
# string_name.split(): Split a
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split()
x = txt.split(", ")
print(x) |
ecabd1232a8ed866f2068d258ca19a33aa676c85 | KageniJK/password-locker | /user.py | 1,410 | 4 | 4 | import random
import string
from typing import Dict, Any
class User:
"""
A class to create all instances of the users
"""
user_list = {}
def __init__(self, name):
"""
defining the properties of the user class
"""
self.name = name
self.accounts = Credential... |
e9de6c648efcbeea43a13be7567df01434dc4b4a | phanisai22/Python | /100 Days of Code/Day 4/heads_or_tails.py | 167 | 3.59375 | 4 | import random
test_seed = int(input("Create a seed number: "))
random.seed(test_seed)
face = random.randint(0, 1)
if face:
print("Head")
else:
print("Tail")
|
bb4768a8bd63785118d56f6c93f6a9ec2aa46912 | rohini-nubolab/Python-Learning | /odd_range.py | 142 | 4.03125 | 4 | # Python program to Odd Even Numbers in given range
start = 4
end = 20
for i in range(start, end+1):
if (i % 2 != 0):
print(i)
|
c256991b745f9c4325a3c9803fe9b2691521d852 | sl99897/Leecode | /滑动窗口/python/209长度最小的子数组.py | 1,401 | 3.671875 | 4 | # coding=utf-8
'''
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的
长度最小的连续子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
示例:
输入:s = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
'''
执行用时:
执行用时... |
1bb34c9d6ba63e0fb09f729575e7b2a43eadc730 | adheepshetty/leetcode-problems | /Linked List/Remove Nth Node From End of List.py | 1,448 | 4.15625 | 4 | import unittest
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
'''
Given a linked list, remove the n-th node from the end of list and return its head.
'''
def removeNthFromEnd(self, head, n):
... |
271270d98fd971682c0302bc156f45b0fb8e8b80 | VachaArraniry/python_portfolio | /sqlbasic.py | 664 | 3.828125 | 4 | import sqlite3
try:
connection = sqlite3.connect('countrydb.db')
select_query = 'SELECT * FROM countries'
cursor = connection.cursor()
cursor.execute(select_query)
countries = cursor.fetchall()
select_singapore = 'SELECT * FROM countries WHERE id=2'
cursor.execute(select_... |
5620aeaee5aa07e7abca4277b5a6dace19abf806 | Sabrina-Btt/Exercicios-e-Trabalhos | /Python/exercicio1.py | 348 | 4.03125 | 4 | x = int input("Digite um número x: ")
y = int input("Digite outro número y: ")
if(x==y):
print("Números iguais")
elif(x>y):
print("x é maior que y")
else:
print("y é maior que x")
a = input("Digite uma palavra: ")
b = input("Digite outra palavra: ")
c = input("Digite mais uma palavra: ")
print( ... |
213e1412ddf8cefd19734a16c6945f33343c6ed8 | turtlean/daily-recall | /setup.py | 844 | 3.6875 | 4 | import os
import sqlite3
from sqlite3 import Error
DB_NAME = 'entries.db'
dir_path = os.path.dirname(os.path.realpath(__file__))
conn = sqlite3.connect(dir_path + '/' + DB_NAME)
sql_create_entries_table = """
CREATE TABLE IF NOT EXISTS entries (
... |
34a2967c0d862ff705cd5960672b4c511802d8fd | CHemaxi/python | /002-python-oop/code/func_test.py | 136 | 3.5 | 4 | num1 = None
num2 = None
def add1(self, num1, num2):
return num1 + num2
def mul1(self, num1, num2):
return num1 * num2
|
fc966b5d29c8dee9993dacaf04085f2cd1d5d5e4 | GoktugEk/CENG | /Freshman/CENG111/nihil_exercises/palindromes.py | 211 | 3.671875 | 4 | def palindromes(num):
res= []
for i in range(num+1):
bin_i= str(bin(i))[2:]
i = str(i)
if (i[::-1] == i) and (bin_i[::-1] == bin_i):
res.append(int(i))
return res
|
bdc6a9493746f933cf2a64d250b953e6e17fd410 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/86b69d4179a043dfba7b2bea4db1552c.py | 460 | 3.75 | 4 | from collections import Counter
class Anagram:
def __init__(self, word):
self.word = word
self.word_counter = Counter(word.lower())
def match(self, words):
return [word for word in words if self.is_anagram(word)]
def is_anagram(self, new_word):
if (self.word != new_word):
new_word_counter... |
d3907a6bcdaf2015dcbe9562a6def335bf87d211 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/lngyas001/question3.py | 2,857 | 3.9375 | 4 | """program to check if a completed sudoku grid is valid
yasha longstaff
15 may 2014"""
def sudoku():
# creating rows
r1 = list(input())
r2 = list(input())
r3 = list(input())
r4 = list(input())
r5 = list(input())
r6 = list(input())
r7 = list(input())
... |
4d5065fe56dccf113160cac276357748713f3bc2 | dev-nas/Python_Interm-diaire_Exercice | /advanced/class_and_object.py | 1,789 | 3.8125 | 4 | class A:
# attribut de classe
param = 100
def __init__(self, *args):
# attribut d'instance
for arg in args:
self.param = arg
def some_method(obj):
return obj.param
@classmethod
def some_class_method(cls):
return cls.param
@stati... |
71e9fd3e90c6cc8c6fb33f55cb5de0c1b9088c43 | NYU-Python-Intermediate-Legacy/lyau-ipy-solutions | /lyau-2.2.py | 2,172 | 3.5625 | 4 | #Part a)
#creating a list of cities from looping through lines of file
city_list=[]
for line in open('bitly.tsv').readlines()[1:]:
els = line.split('\t')
city_list.append(els[3])
#sorting list by passing the lower function to all city names and
#converting list into a set since sets are unique and will elimin... |
593a651760702c14d9897aa59cc7af0db6f1ba62 | MarcoPerdomo/Connect4-Deep-Reinforcement-Learning | /AI_Brain.py | 8,259 | 3.8125 | 4 | # AI for Self Driving Car
# Importing the libraries
import numpy as np
import random
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.autograd as autograd
from torch.autograd import Variable
# creating the architecture of the Neural N... |
a2bb59a16b146a00d39147442dfd010bdcf3bc36 | ArfHbb/smarthome | /relay_on.py | 624 | 3.5 | 4 | # https://sourceforge.net/p/raspberry-gpio-python/wiki/Home/
# https://docs.python.org/2/library/sys.html
# http://www.tutorialspoint.com/python/python_functions.htm
import RPi.GPIO as GPIO
import time,sys
def f(x):
return {
'1':2,
'2':3,
'3':17,
'4':18,
}[x]
# sys.argv[1] is the next input after the name
# Ex... |
95cc28c08602047586209a2fa13f9c0463aa2d3d | cs-fullstack-fall-2018/python-task-list-homework-myiahm | /answers.py | 1,288 | 4.125 | 4 | # Congratulations! You're running [YOUR NAME]'s Task List program.
#
# What would you like to do next?
# 1. List all tasks.
# 2. Add a task to the list.
# 3. Delete a task.
# q. To quit the program
# function = ["list all task", "Add a task to the list ", "Delete a task" "To quit the program "]
print()
def listAllOp... |
1c33b799e7047de756cdacf0956937b1754709a9 | gschen/sctu-ds-2020 | /1906101018-湛鑫/Day0219/20200219-test01.py | 340 | 3.921875 | 4 | #连接字符
a='hi'
b='s'
print(a+b)
#重复字符
c='hi'
print(c*3)
#切片
str1='abcde'
print(str1[0])
print(str1[-1])
print(str1[0:4])
#格式化输出
print("我叫%s"%'李四')
print("我今年%d"%(10))
#列表
lis1=[5,4,2,8,3,8]
#lis1.append(7)
#lis1.extend([1,2])
lis1.sort()
print(lis1)
#元组
tup=('s',100,[1,2])
print(tup)
|
1d2fb1c5fb54cb2faa857dbd450571ed95f942c9 | ripley57/CW_Tools | /tools/python/data_handling_demos/csv_write_demo.py | 1,203 | 3.53125 | 4 | """ cvs module demo - note in particular the use of 'lineterminator' """
import csv
temperature_data = [ ['State', 'Month Day, Year Code', 'Avg Daily Max Air Temperature (F)', 'Record Count for Daily Max Air Temp (F)'],
['Illinois','1979/01/01','17.48','994'],
['Illinois','1979/01/02','4.64','994'] ]
# NOTE: l... |
1c267a7287399c831e84546ba9e14f9602a1241b | rsoemardja/HackerRank | /Problem Solving/Algorithms/Implementation/Drawing Book/Drawing_Book.py | 383 | 3.5 | 4 | #!/bin/python3
import os
import sys
#
# Complete the pageCount function below.
#
def pageCount(n, p):
#
# Write your code here.
#
front = (p - (p % 2)) * 0.5
back = (n - p + ((n + 1) % 2)) * 0.5
return int(min(front, back))
n = int(input())
p = int(input())
result = pageCou... |
801d41c3f2d6ab34f98da68ea1f8e5fce3d1865e | vineel2014/Pythonfiles | /python_exercises/16data_structures/tuple.py | 141 | 4.0625 | 4 | print("")
print("*******TUPLE ITERATOR*****")
l=(1,2,3,4)
print("TUPLE:",l)
for z in l:
print()
print("TUPLE ITEMS:",z)
print()
|
b7f1707ab231e986ed788d8840e47a6a82e087d6 | ZhekaiJin/pass2act | /wordinv.py | 253 | 3.734375 | 4 | noundict = {'i':'me', 'we':'us', 'you':'you', 'he':'him', 'she':'her', 'they':'them', 'them':'they', 'her':'she', 'him':'he', 'us':'we', 'me':'i'}
def nouninv(noun):
n = noun.lower()
if n in noundict:
return noundict[n]
return noun
|
6bc99f94b600e17d40e53bb6b65f3d6e7271765e | Ishan1717/CodingSchool | /hwfin.py | 3,464 | 4.46875 | 4 | '''
Create a banking program that represents the process of banking and utilizes two classes: The Bank class and the customer class
The classes will have (but are not limited to) the following attributes and methods. Feel free to add more if you'd like
The bank class has the following attributes:
Name, Current Balanc... |
2f7bd87820b3a935f8d0cc184c55de466b26d4c1 | 0xideas/datamap | /code/set_settings_helpers.py | 1,571 | 3.953125 | 4 | """
Functions:
validate_regex: test if a regular expression can be compiled and return bool. Option to pass update function
get_inputs: take multiple inputs and return a list. Options for prompt, stopword to stop inputting, and max # of inputs
remove_quotes: remove quotes from string in case of 'string-in_string... |
b2611f3ba6f5ea86cbf4adde946aebc130491936 | manojkumar-github/books | /professional-python/part-2-classes/magic-methods/type-conversion.py | 1,240 | 4.15625 | 4 | """
__str__, __unicode__, __byte__
"""
class MyObject(object):
def __str__(self):
return 'My Awesome Object!'
print MyObject()
print str(MyObject())
"""
In py2 - all strings are ASCII strings
In py3 - all strings are unicode strings
However, py2 does have Unicode strings (__unicode__) and Python3 intro... |
b89ee01d4c6165d7ae291d47f9a01be42fd9c90a | zabess/homeworkpythonscripts | /fastareformat.py | 1,525 | 3.859375 | 4 | #! /usr/bin/env python
#This file reformats the structure of the regex.practice1.fasta file so that
#the name rows are replaced with 'Homo_sapens' followed by the numeric string.
"""Pseudocode:
Import the re module
Open the regex.practice1.fasta file and store it as ‘InFile’
Establish initial line number as 1.
Use a ... |
b2f5148bbc636d0ba142e91c03cf786998dcad6a | A01630323/Learn-To-Program | /Mastery11a.py | 913 | 3.609375 | 4 | print ("****************************")
print ("*** IMPORTAR FUNCIONES *****")
print ("****************************")
import numbers
import math
import cmath
import decimal
import fractions
import random
import statistics
Numeros = dir (numbers)
Matematicas = dir (math)
MatematicasC = dir (cmath)
Decimales = dir (decima... |
c6bb85c98a454724f04744724d335e0c51423dc6 | cdingding/exercises | /test_prime_list.py | 412 | 3.859375 | 4 | from math import sqrt
def is_prime(n):
if n <= 1:
return False
for i in xrange(2, int(sqrt(n) + 1)):
if n % i == 0:
return False
return True
def prime_generator():
n = 900
while n <= 1000:
if is_prime(n):
yield(n)
n = n + 1
if __name__ == '__main__':
... |
087f4a2ff93f9ce7a61cb250b1ee49b198832eaf | amadi5892/PythonPrac | /functions.py | 3,263 | 3.765625 | 4 | # def say_hello(name='Default'):
# print(f'Hello {name}')
# def add_num(num1,num2):
# return num1 + num2
# res = add_num(3,4)
# def print_result(a,b):
# print(a+b)
# def return_result(a,b):
# return a + b
# res = print_result(10,20)
# def even_check(number):
# return number % 2 == 0
# print(... |
2292cae2865f29f0237aa4338c5e33df1069246e | 600tomatos/exponea_challenge | /src/interfaces/validator.py | 996 | 3.703125 | 4 | from abc import ABC, abstractmethod
class ValidatorInf(ABC):
"""Base class for validators"""
@classmethod
def check(cls, value):
"""Helper method that takes out the logic of creating a validator outside view.
It is understood that validation begins with the perform_validate method.
... |
a920c51f558f72a6820b843b1a825d0ac6f899b5 | sangaml/python | /bootcamp/assignment4.py | 980 | 4.09375 | 4 | filename = input("Enter file name:")
a=''
try:
f = open(filename)
f.close()
a='exists'
except IOError:
print()
if a=='exists':
print('File is there')
n = int(input("1. Press 1 to read containts of:\n "
"2. Press 2 to delete the file content and start over:\n "
"3. Append... |
b2f8b67ed106d74ebbb9e607f4f87005a29453e4 | yaggul/Programming0 | /week3/4-Problems_construction/triangles.py | 1,144 | 3.78125 | 4 | def is_triangle(a,b,c):
if max(a,b,c)-min(a,b,c)<(a+b+c)-(max(a,b,c)+min(a,b,c)) and max(a,b,c)+min(a,b,c)>(a+b+c)-(max(a,b,c)+min(a,b,c)):
return True
else:
return False
#S=sqrtp(p-a)(p-b)(p-c)
def area(a,b,c):
p=(a+b+c)/2
s=round((p*(p-a)*(p-b)*(p-c))**0.5,2)
return s
def is_py... |
fdecc7138b36dfe6b81dadc63eab5f646999d980 | rbarrette1/Data-Structures | /LinkedList/Node.py | 209 | 3.703125 | 4 | value = 0 # value of the node
next = "null" # next node to this one
class Node():
def __init__(self, val):
self.value = val
self.next = None
print("New Node Created: " + str(val))
|
982aaba729ca86d4af57052125cbed6e6caee0f0 | DimaOmb/Tkinter_Lecture | /5. check_box - Solution.py | 656 | 3.625 | 4 | from tkinter import *
root = Tk()
root.title('title')
root.geometry("400x400")
def show():
text = want_pizza.get() + " " + size.get()
Label(root, text=text).pack()
want_pizza = StringVar()
size = StringVar()
pizza_check = Checkbutton(root, text="Want a pizza?", variable=want_pizza, onvalue="Yes :)", offv... |
81c2415b863cceffd0dffab67906de6efb852a7d | v1ll41n/Cryptopals | /Set1/detect_aes_ecb.py | 1,679 | 4.03125 | 4 | from binascii import unhexlify
# The simplest of the encryption modes is the Electronic Codebook (ECB) mode (named after conventional physical codebooks).
# The message is divided into blocks, and each block is encrypted separately
# The disadvantage of this method is a lack of diffusion.
# Because ECB encrypts ident... |
2bd95ae9c0b098635d73c4fb1fe8cd3f34ad06c7 | TrendingTechnology/ElectricPy | /electricpy/_ind_motor_circle.py | 11,340 | 3.625 | 4 | ################################################################################
"""
`electricpy._ind_motor_circle` - Support for plotting induction motor circle.
Hidden module.
"""
################################################################################
import numpy as _np
import matplotlib.pyplot as _plt
... |
aa033ebd2e16bf2eec1b63722f5c257e24d2b0e1 | conejo1995/pythonLabs | /change_return.py | 2,561 | 3.96875 | 4 | hundred_bill = 10000
twenty_bill = 2000
ten_bill = 1000
five_bill = 500
dollar_bill = 100
quarter_value = 25
dime_value = 10
nickel_value = 5
penny_value = 1
register = {'hundreds' : 1,'twenties' : 4, 'tens' : 1, 'fives' : 1, 'ones' : 9, 'quarters' : 3, 'dimes' : 9, 'nickels' : 1, 'pennies' : 4}
def give_change(chang... |
83c3b21092018c6db426f75f770e3761e9574ccd | allblackkankam/samples | /functions.py | 351 | 3.5 | 4 | # def x(one):
# print one+one
# x(4)
def form():
name = raw_input("what is your name?")
age = raw_input("How old are you?")
gender = raw_input("what is your gender?")
address = raw_input("where do you live?")
return name , age,gender,address
print form()
def x(one,two):
print one+two
x(4,8)
# def x(one... |
3ba087cb7295c8fd6eb9d39c4b5bdf3511c8083f | deyoung1028/Python | /algorithm.py | 1,262 | 3.84375 | 4 | # data structure
#STACK - Activity
#FILO first in last out
class Stack:
def __init__(self):
self.items=[]
def push(self,item):
if item is not None: #item with value none are not allowed
self.items.append(item)
def pop(self):
if len(self.items)... |
89a0237ef0bc1336037afcdc139b7b69300f38cf | kriegaex/projects | /Python/projectEuler/PrimePermutations.py | 863 | 3.59375 | 4 | from uint_prime import isprime
import time
start = time.time()
def generate_prime(lowerbound, upperbound):
a = []
for i in range(lowerbound, upperbound):
if isprime(i):
a.append(i)
return a
prime_list = generate_prime(1000, 10001)
print(prime_list)
def ispermutation(num1, num2):
st... |
937b99cb910cc1963d91e3897b0c25e324a131f6 | aj07mm/code-interview | /sherlock_holmes.py | 924 | 3.6875 | 4 | import re
sherlock_paragraph = """
In the year 1878 I took my degree of Doctor of Medicine of the
University of London, and proceeded to Netley to go through the
course prescribed for surgeons in the army. Having completed my
studies there, I was duly attached to the Fifth Northumberland
Fusiliers as Assistant Surgeo... |
c3ad9ed553d430ba9955226f86ea5f3afe289e70 | iHoHyeon/BOJ | /BASIC 2/#1934.py | 143 | 3.71875 | 4 | def GCD(A,B):
return GCD(B%A,A) if B%A else A
T = int(input())
for i in range(T):
A,B = map(int,input().split())
print(int(A*B/GCD(A,B))) |
ab2e8dc22aea4e6327d3ffb0ec81d79533808706 | JSchrtke/money-python | /tests/test_money.py | 2,387 | 3.9375 | 4 | from money.money import Expression, Bank, Sum, Money
def test_equality():
assert Money.dollar(5) == Money.dollar(5)
assert Money.dollar(5) != Money.dollar(6)
assert Money.dollar(5) != Money.franc(5)
def test_multiplication():
five: Money = Money.dollar(5)
assert Money.dollar(10) == ... |
fe36d3cfcef00b7b7a06d21e3a853d2a1dbdc70b | Kabir12401/FIT1008 | /Prac 1/task2.py | 1,076 | 3.921875 | 4 | def print_menu():
print('\nMenu:')
print('1. append')
print('2. reverse')
print('3. print')
print('4. pop')
print('5. count')
print('6. quit')
def reverse(my_list):
length = len(my_list)
for i in range(length//2):
temp = my_list[i]
my_list[i] = my_list[length -i-1]
... |
b80fe89536d641f83b52b8292a6cfd6e5f23d807 | Malherebastien/SpaceShooterPython | /src/game/Game.py | 1,820 | 3.859375 | 4 | from tkinter import Tk, Canvas
from src.game.Player import Player
PLAYER_X_START = 200
PLAYER_Y_START = 200
class Game :
def __init__(self):
self.frame = Tk()
self.canvas = Canvas(self.frame, width=1000, height=1000, background="black")
self.rectangle = self.createPlayer()
self.... |
91e0f19841da0e82d1c9b0b1cc176df71a81e466 | senmelda/PG1926 | /problemSet_3.py | 593 | 3.671875 | 4 |
sayilar = []
girdi = int(input("Kaç sayı girilecek ? : "))
for i in range(girdi):
sayi = int(input("{}. sayıyı giriniz :".format(i+1)))
sayilar+=[sayi]
print(sayilar)
"""rakamlar = []
rakam = 0
while rakam <= 7 :
sayi = int(input("Lütfen bir sayı giriniz : "))
rakam = sayi+1
rakamlar.append(rakam... |
39589c1a6c9d93bd6a773a6634876b53da6c93e3 | CharlesYang1996/cell_detection_1.0.0 | /feature_test_1.0.0/test.py | 1,119 | 3.546875 | 4 | key_value ={}
key_value[1,2] = 56
key_value[3,4] = 2
key_value[5,6] = 12
key_value[7,8] = 24
key_value[8,9] = 18
key_value[10,10] = 323
print("按值(value)排序:")
sorted_key_value=sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]),reverse=True)
print(sorted_key_value)
print(sorted_key_value[0])
print(sorted_key_value[... |
2949e29e529ccf64a716c4e3e3a7f296bb61101d | free43/Pac-Man-in-Python-with-pygame | /Game_Field.py | 22,271 | 4 | 4 | """
Copyright 2020, Köhler Noah & Statz Andre, <NoahsEmail> & andrestratz@web.de, All rights reserved.
"""
import pygame as pg
import Colors
class Game_Field(object):
"""
Represents the Game-Field.
"""
"""
The const_look_up_table represents the Game-Field. Each of the strings has his o... |
0871028e44a6bdfc2adee23324257fd206a6eabc | beatriznaimaite/Exercicios-Python-Curso-Em-Video | /mundo1/exercicio020.py | 643 | 4.0625 | 4 | """
O mesmo professor do desafio anterior quer sortear a ordem de apresentação de trabalhos dos alunos.
Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.
"""
# importando a biblioteca
import random
# inserção dos dados pelo usuário e posterior adição a lista
alunos = []
for aluno in range... |
e8e6ec4a55fbbc9fdca68b1bacd8e110f8f8a854 | luozhaoyu/study | /lc/alien_dictionary_269.py | 3,489 | 3.84375 | 4 | from typing import List
class Node:
def __init__(self, val, whole_dict=None):
self.val = val
# key is char, value is next Node
self.index = {}
self.latest_val = None
self.whole_dict = whole_dict
def insert(self, word):
"""insert new word into Node
1. che... |
4d55e262aaf83b9d2fc422582be3db661b0519f5 | Jigar710/Python_Programs | /ternary_op/map3.py | 344 | 3.78125 | 4 | lst = list(range(1,11))
print(lst)
lst1 = []
'''
for i in lst:
if(i%2==0):
lst1.append(0)
else:
lst1.append(1)
'''
for i in lst:
lst1.append(i%2)
print(lst1)
def evenorodd(n):
'''if(n%2==0):
return 0
else:
return 1
'''
return n%2
lst2 = list(map(evenorodd,lst))
print(lst2)
lst3 = list(map(lambda n... |
03ae51eca1ef0b92bda6e1a314a0ff4a28cb90fe | Duuuda/Coursework2Course | /requirements_update.py | 1,065 | 3.546875 | 4 | from os import system
def requirements_update():
system('pip3 freeze > requirements.txt')
print('All requirements was collected into "requirements.txt"')
def requirements_install():
system('pip install -r requirements.txt')
print('All requirements was installed from "requirements.txt"')
def main()... |
dc5e17497a8913371c5222d37d30925416b314ca | BThomann/GPA_Playground | /kollektionen_beispiele.py | 6,467 | 3.609375 | 4 | # Folie 13
a = (1, 2, 3)
b = ("Hello", "World")
c = (1, 2, (3, 4, (5, 6)))
d = (1, "Test", ("Here", (2, 3), "And"), 5)
print(len(a), len(b), len(c), len(d))
print(a[1], b[1])
print(c[2], c[2][2], c[2][2][0])
print(d[2][0:2])
print(a + b)
print(a * 3)
a, b = b, a
print(a)
print(b)
# Folie 14
def read_input():
na... |
31f1d75c6d6ce2a07411e527bf6322548ce73a6e | mnjulacodes/Python_Fundas | /factorial.py | 106 | 4 | 4 | #factorial
fact=1
m=int(input("Enter a number"))
for i in range(1,m+1):
fact=fact*i
print(fact)
|
f42de5ccb71312d2178da7c628e41726876f3744 | BarbosaRicardo/CST383_Data_Science | /Week6/Labs/lab5.py | 2,794 | 4.15625 | 4 | # %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsRegressor
# %%
df = pd.read_csv(
'https://raw.githubusercontent.com/grbruns/cst383/master/College.... |
e5b5d9bd1478f69c21f6cab66ac1c605182b90ff | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-29-martins-iq-test.py | 1,391 | 4.3125 | 4 | '''
Martin is preparing to pass an IQ test.
The most frequent task in this test is to find out which one of the given characters differs from the others.
He observed that one char usually differs from the others in being alphanumeric or not.
Please help Martin! To check his answers, he needs a program to find the dif... |
c5f2881eaff6a0af7b9bf039a238b2b67e4d16ff | hsouporto/Note-Everyday | /Slides_Note/Stanford_Algorithms/PythonCode/Course1/Week4/PA4v3.py | 1,432 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
(original code running in Python2)
https://gist.github.com/aymanfarhat/6098683
@author: HYJ
"""
import random
# generate dict-based graph from txt
def load_graph():
return {int(line.rstrip().split()[0]): [int(i) for i in line.rstrip().split()[1:]] for line in
open("./k... |
a4743db852e7c3d2bc62dca763d8199b6cb4499b | StefanoD/AI-for-Trading | /Lesson 14 Exercises/volatility.py | 1,123 | 3.625 | 4 | import pandas as pd
import numpy as np
def get_most_volatile(prices):
"""Return the ticker symbol for the most volatile stock.
Parameters
----------
prices : pandas.DataFrame
a pandas.DataFrame object with columns: ['ticker', 'date', 'price']
Returns
-------
ticker : strin... |
50c01a8035a81cd789ef0b88c681015014a4049a | KoryHunter37/code-mastery | /python/firecode/repeated-elements-in-array/solution.py | 276 | 3.6875 | 4 | from collections import Counter
def duplicate_items(list_numbers):
count = Counter(list_numbers)
redundant_numbers = []
for key in count.keys():
if count[key] > 1:
redundant_numbers.append(key)
return sorted(redundant_numbers)
|
c9d4c3b69f0b9aadc3ab0d981f867ee72caa8c99 | imjaya/Leetcode_solved | /268_Missing_number.py | 370 | 3.765625 | 4 | #finding the missing number in a consecutive set of numbers
class Solution:
def missingNumber(self, nums: List[int]) -> int:
max_num=len(nums)
min_num=min(nums)
expected_sum=0
for i in range(min_num,max_num+1):
expected_sum+=i
actual_sum=sum(nums)
... |
ea36bb5e1b03a83e90bf928bd3a2efaa351d8c8c | chiragmacwan2411/Json_sort_selenium_exercises | /utilities/json_reader.py | 604 | 3.875 | 4 | import json
"""
utility method to read json file and return python dict
"""
def json_data_reader(json_file_path):
try:
with open(json_file_path) as f:
data = json.load(f)
return data
except OSError:
print("file can not be found :: " + json_file_path)
"""
re... |
895776451aff8be697905098249cd80b04a00a77 | XuWeidongCQ/OAIS_backend | /util/statistic.py | 3,214 | 3.5 | 4 |
def is_in(key, value):
val = float(value)
if '-' in key:
min = float(key.split('-')[0])
max = float(key.split('-')[1])
if val >= min and val < max:
return True
else:
return False
else:
min = float(key[2:])
return val >= m... |
289d1fd5ea7a601a30eff0c6c81fde966b83fe26 | paulagmar/ejerecicios-OOP | /alumno.py | 821 | 3.796875 | 4 | class alumno():
def __init__(self, matricula, nombre, nota1, nota2, nota3):
self.matricula=matricula
self.nombre=nombre
self.nota1=nota1
self.nota2=nota2
self.nota3=nota3
self.nota_final=0
def get_matricula(self):
return self.matricula
def get_nombre(... |
7aad09690df845ebd73ce2948bff631f8af9c7ef | rohith5803/python | /escapechar.py | 683 | 3.734375 | 4 | splitstring = "This lines has\nbeen split\nover into \nseveral\nlines"
print(splitstring)
print(" ") #this line is for leaving a gap
tabstring = "1\t2\t3\t4\t5"
print(tabstring)
print('The pet shop owner said "No, no, \'e\'s uh,...he\'s resting".')
#or
print("The pet shop owner said \"No, no, '... |
08020cfdb59055b2dc1f62cd3b22e7f084c24b53 | rohanbaisantry/simple-speech-to-text | /speech_to_text.py | 5,427 | 3.796875 | 4 |
"""
Accepts a .mp3 or a .wav file and performs speech to text using google's speech recognition api and get's the transcription.
REQUIREMENTS:
____________
> Python3
https://www.python.org/downloads/
> Speech Recognition python module [ google could speech to text ]
pip install google
pip install --up... |
4999287b24e669a33bdf2962f7b09b7ad8fc8cc2 | onlysw/face-detection | /face_detection_attendace_system/create_table.py | 808 | 3.578125 | 4 | '''
20-2-19
1.connecting to database creating needed tables
'''
import psycopg2
try:
con = psycopg2.connect(user = "face_detection",
password = "master@2510",
host = "127.0.0.1",
port = "5432",
... |
63435656a87babd4428571e4fffcbbef86998ec5 | parasyadav1999/paras_python | /vowels.py | 672 | 4.125 | 4 | vowels=["a","e","i","o","u"] #refrence sequence to compare the input
x=input("enter the sentence")
found=[] #empty list used to store the vowels present in input sentence
for i in x: #loop to find vowels present in input sentence
if i in vo... |
b2914a9423ddf4263063698ce3596b5830222f14 | vpstudios/Codecademy-Exercise-Answers | /Language Skills/Python/Unit 3/1-Conditionals & Control Flow/Review/15-The big If.py | 373 | 3.640625 | 4 | # Make sure that the_flying_circus() returns True
def the_flying_circus():
if True or True: # Start coding here!
return True # Don't forget to indent
# the code inside this block!
elif 7 >= 2:
return 'nooo' # Keep going here.
# You'll want to add the else statement, too!
e... |
b71aeadedd3939c8ee54d0b369d157cef0b6f301 | om-sonawane/object_oriented_programming | /create_class_programmer.py | 329 | 3.6875 | 4 | class programmer:
company ="Microsoft"
def __init__(self,name,product):
self.name= name
self.product= product
def getInfo(self):
print( f"the name of programmer is {self.name} and the product is {self.product}")
om =programmer ("om","skype")
anna=programmer("anna","Github")
om.... |
bc816c7127ce8f15ac05a7b297b9ff92648a824b | HoangHip/TaHoangAnh-fundamental-C4E-29 | /Session04/word_jumble.py | 503 | 3.859375 | 4 | from random import choice
words = ["champion", "football", "hello"]
word = choice(words)
world_list = list(word)
shuffle_word = []
for i in range(len(word)):
character = choice(world_list)
shuffle_word.append(character)
world_list.remove(character)
loop = True
while loop:
print(*shuffle_word, sep=" ") ... |
b98d88c8a6799e15f77b6ca4edfc20328d4e0632 | danghao96/CSE231-Projects | /Project11/times.py | 7,000 | 4.15625 | 4 | class Time( object ):
def __init__( self, hh=0, mm=0, ss=0, zz=0 ):
"""This method initializes a Time object."""
validate = False
try:
if 0 <= hh < 24 and 0 <= mm < 60 and 0 <= ss < 60 and -12 <= zz <= 12:
validate = True
except:
validate = Fal... |
a1ec41d862b378283d10b9cced62016e0011a968 | asxzhy/Leetcode | /leetcode/question_819/solution_1.py | 1,900 | 4.0625 | 4 | """
I used two lists to store the basic information from the paragraph. One list stores every word that occurs in the paragraph (does not contain duplicates). The other list stores
the frequency of each word's usage. I used another string to keep track of each word when I loop through the paragraph letter by letter. I... |
fbebf30c3d129e5fefc4a699afc4cd136867fa89 | hm14/LeetCode-Problems | /searchInsert.py | 747 | 4.3125 | 4 | # Problem Prompt
# Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
# You may assume no duplicates in the array.
# Here are few examples.
# [1,3,5,6], 5 gives 2
# [1,3,5,6], 2 gives 1
# [1,3,5,6], 7 gives 4
# [1,3,... |
edd4a2d501189bc6211bd9e227dbb54ba65a1980 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/Exercícios MUNDO 1/ex007 (média).py | 162 | 3.875 | 4 | n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
print('A média entre {} e {} é: {:.1f}'.format(n1, n2,(n1+n2)/2)) |
10c06b3b5abe72cbfe4e0358268f54415e7e1743 | majkelmichel/simple_banking_system | /banking.py | 4,916 | 3.609375 | 4 | import random
import sqlite3
conn = sqlite3.connect('card.db')
cur = conn.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='card';")
if len(cur.fetchall()) == 0:
cur.execute('CREATE TABLE card (id INTEGER , number TEXT, pin TEXT, balance INTEGER DEFAULT 0);')
conn.commit()
card_... |
8cb8298d809c41e8db27963f24c7d4f654930775 | sleepbuxing/django.ftp | /python3/py/斐波那契数列.py | 194 | 3.625 | 4 | #coding=utf-8
def Nums(num):
a,b = 0,1
for x in range(num):
yield b
a,b= b, a+b
ret = Nums(10)
a = next(ret)
a = next(ret)
a=ret.__next__()
for i in ret:
print(i)
|
ae721852f7c8d5519830e49c440d0c9cb1707ab6 | tonberarray/datastructure-and-algrorithm | /线性表操作/栈/栈.py | 2,035 | 3.71875 | 4 | # 堆栈的实现 元素后进先出
## binary to decimal
'''二进制转化为十进制时的公式:
a1*2^0 + a2*2^1 +a3*2^2+...+an*2^(n-1)
a1,a2...an二进制从低到高位的值
'''
## binary to octal
'''二进制转化为八进制时,二进制数每三个位对应八进制一个位数
即a1*2^0+a2*2^1+a3*2^2 对应oct第一位数,以此类推,得八进制数
a1,a2...an二进制从低到高位的值
'''
## binary to hexadecimal
'''二进制转化为十六进制时,二进制数每四个位对应十六进制一个位数
即a1*2^0+a2*2^1+a3*2^2+a... |
e1b1a996d5941d05dcf87a497c94e6afc9185304 | clwater/lesson_python | /old/learn_old/functioncode.py | 243 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#变量可以指向函数
# f = abs
# print f(-10)
# def add(x, y, f):
# return f(x) + f(y)
# print add(-5 ,6 ,abs)
def f(x):
return x * x
r = map(f , [1,2,3,4,5,6,7,8,9])
print list(r)
|
79ea83709a3a43a5e7db22bfa5296c52b0391d7e | NoelArzola/10yearsofPythonWoot | /1 - intro/multiple_if_statements.py | 834 | 3.9375 | 4 | country = input('What country do you live in? ')
tax = 0.0
# if province == 'Alberta':
# tax = 0.05
# if province == 'Nunavut':
# tax = 0.05
# if province == 'Ontario':
# tax = 0.13
# print(tax)
# if province == 'Alberta':
# tax = 0.05
# elif province == 'Nunavut':
# tax = 0.05
# elif province == ... |
3f1a725de6e1d6ea33dbe8cb12369c8f6a3c3218 | LucasAzvd/Tkinter_elements | /main.py | 4,622 | 3.578125 | 4 | from tkinter import *
window = Tk()
#-------------- APARENCIA
window.title("CRIANDO")
window.geometry('1000x1000')
#-------------- LABEL
window.title("Bem-vindo")
lbl = Label(window, text="Hello", font=("Arial Bold", 50))
lbl.grid(column=0, row=0)
#-------------- BUTTON
def clicked():
response = in_txt.get()
... |
3a87f2730fcf2539659f9c8850b06a6a51220530 | josephwood21/datacode-interview-task | /datacode_interview_task.py | 1,300 | 4.46875 | 4 | # Python program to read in json files for
# language conversion application
import json
# open the english, french and pirate json files
with open("languages-english.json") as f1, open("languages-french.json") as f2, open("languages-pirate.json") as f3:
# create dicts from json objs
data1 = json.load(f1)
... |
fa3166c1b6bd043cdb21823c161c347c7c4f11fb | AnshThayil/snakenbake | /app/main.py | 7,194 | 3.5 | 4 | import json
import os
import bottle
from api import ping_response, start_response, move_response, end_response
@bottle.route('/')
def index():
return '''
Battlesnake documentation can be found at
<a href="https://docs.battlesnake.io">https://docs.battlesnake.io</a>.
'''
@bottle.route('/static/<pat... |
6155420ebfaec2383f3f9feb692adb35eec1c012 | eataix/algorithms | /leetcode/562.longest-line-of-consecutive-one-in-matrix.python3.py | 1,598 | 3.75 | 4 | #
# [562] Longest Line of Consecutive One in Matrix
#
# https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/description/
#
# algorithms
# Medium (41.16%)
# Total Accepted: 8.1K
# Total Submissions: 19.8K
# Testcase Example: '[[0,1,1,0],[0,1,1,0],[0,0,0,1]]'
#
# Given a 01 matrix M, find the long... |
1b3a25d91d31244acf8f2b4443e88973cb34f507 | cladren123/study | /AlgorithmStudy/백준/무지성 랜덤풀이/10월/10.2/9935 문자열 폭발(시간초과).py | 395 | 3.578125 | 4 | """
문제유형 :
자료 구조
문자열
스택택
이중반복문을 쓰면 시간초과가 발생
"""
import sys
input = sys.stdin.readline;
# 입력단
string = input().strip();
bomb = input().strip();
while True :
if bomb not in string :
break;
else :
string = string.replace(bomb, "");
if len(string) == 0 :
print('FRULA');
else :
print... |
93ffb9c84a34bce68a56b393a38af0dd3ca8cd9e | WreetSarker/python-oop | /intro_to_oop/phone.py | 382 | 3.71875 | 4 | from item import Item
class Phone(Item):
def __init__(self, name: str, price: float, quantity: int = 0, broken_phones=0):
super().__init__(name, price, quantity)
# Run validations on received arguments
assert broken_phones >= 0, f"Quantity {broken_phones} can't be negative"
# Ass... |
07b8b2f21757141aa5553491be4fb097b0627270 | jaechoi15/DojoAssignments | /Python/MultiplesSumAverage/multiplesSumAverage.py | 626 | 4.5 | 4 | # Multiples
# Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
for x in range (1, 1001, 2):
print x
# # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
for x in range (5, 50, 5):
print x
# # S... |
05571dfae09802ee279a255931006fe26a06ded8 | kjy/python_classes | /Constructing_Classes/1.2_ObjectsAsArguments&Parameters.py | 21,314 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[29]:
# Objects as Arguments and parameters
import math
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY): # Constructor with double underscore, "dunderscore"
self.x = initX # Initializ... |
4d6ce7aadc11e7354c76c0bea65984e73f1336a3 | SivaCn/Hands-On | /iter.py | 350 | 3.828125 | 4 | class MyIter(object):
def __init__(self, iterable):
self.iterable = iterable
def __iter__(self, *args, **kwargs):
return self
def next(self):
while self.iterable:
return self.iterable.pop(0)
raise StopIteration()
for i in iter([1,2,3]):
print i
for i in... |
88e5940c75d8ad835851c0ea406597080af13812 | onurakkaya/image-processing | /opencv-basics/image-layers-bgr.py | 882 | 3.890625 | 4 | import cv2
image = cv2.imread("opencv-basics\image.jpg")
# image [ first, second, third]
# -> first parameter is used to select coord of x-axis (":" means select all pixels )
# -> second parameter is used to select coord of y-axis
# -> third paramter is used to select the color layer.
# ->> The layer order is... |
53bbc1ebaff8d8acef756f9d04fef60cf59a9b28 | JiteshSindhare/Algorithms | /Sorting/QuickSort.py | 750 | 3.953125 | 4 | def swap(arr,k,i):
temp = arr[k]
arr[k] = arr[i]
arr[i] = temp
def partition(arr,low,high):
pivot=arr[high]
#pivot_index= high
i=low-1
for k in range(low,len(arr)-1):
if arr[k]<pivot :
i+=1
temp=arr[k]
arr[k]=arr[i]
arr[i]=temp
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.