blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
fdab3ee8f01efe9aff801aaf283283feaefc9913 | Ming-H/leetcode | /530.minimum-absolute-difference-in-bst.py | 921 | 3.765625 | 4 | #
# @lc app=leetcode id=530 lang=python3
#
# [530] Minimum Absolute Difference in BST
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
... |
aa475f2d31db091e693c600935228511c4e3c189 | Ming-H/leetcode | /508.most-frequent-subtree-sum.py | 1,000 | 3.515625 | 4 | #
# @lc app=leetcode id=508 lang=python3
#
# [508] Most Frequent Subtree Sum
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findFre... |
270a0a1bb386fb1ac9c27a928e9c2a09b6690949 | Ming-H/leetcode | /98.validate-binary-search-tree.py | 1,210 | 3.828125 | 4 | #
# @lc app=leetcode id=98 lang=python3
#
# [98] Validate Binary Search Tree
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
"""... |
d49e9e34ab5c9504fc2c4263993aa6a1a842c023 | Ming-H/leetcode | /345.reverse-vowels-of-a-string.py | 602 | 3.578125 | 4 | #
# @lc app=leetcode id=345 lang=python3
#
# [345] Reverse Vowels of a String
#
class Solution:
def reverseVowels(self, s: str) -> str:
if not s:
return s
l = list(s)
i = 0
j = len(l)-1
vowels = ['a','e','i','o','u','A','E','I','O','U']
while i<j:
... |
94d595fe3ddc7a112c4d67956a4657a479f3327a | Ming-H/leetcode | /106.construct-binary-tree-from-inorder-and-postorder-traversal.py | 1,130 | 3.84375 | 4 | #
# @lc app=leetcode id=106 lang=python3
#
# [106] Construct Binary Tree from Inorder and Postorder Traversal
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inord... |
e90df2a11acae253d151df7da29a8404bc387b85 | Ming-H/leetcode | /20.valid-parentheses.py | 564 | 3.65625 | 4 | #
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
class Solution:
def isValid(self, s: str) -> bool:
"""
Time complexity : O(n)
Space complexity : O(n)
"""
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for item in s:
if ite... |
400b36dd36749bb7bcf7a173fb3e7f75052da8bb | Ming-H/leetcode | /151.reverse-words-in-a-string.py | 1,071 | 3.53125 | 4 | #
# @lc app=leetcode id=151 lang=python3
#
# [151] Reverse Words in a String
#
class Solution:
def reverseWords(self, s: str) -> str:
"""
https://www.cnblogs.com/chruny/p/5478262.html
"""
# if len(s) == 0:
# return ""
# ans = []
# begin = i = 0
# m... |
96983d1659c4e99eb05ac098c3c11478c727b1d1 | Ming-H/leetcode | /328.odd-even-linked-list.py | 863 | 3.78125 | 4 | #
# @lc app=leetcode id=328 lang=python3
#
# [328] Odd Even Linked List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
"""
Ti... |
4fb3330239f7107a48510f14b5958ee23dd6cad7 | Ming-H/leetcode | /24.swap-nodes-in-pairs.py | 786 | 3.640625 | 4 | #
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# pre, pre.next = self, head
... |
381edf35abc3c4a37fbf96c6bde790e070524975 | avitalze/Football-system-project | /Match_Prediction/readfile_continue.py | 4,672 | 3.53125 | 4 | import pandas as pd
def get_last_matches(matches, date, team, x=10):
''' Get the last x matches of a given team. '''
# Filter team matches from matches
team_matches = matches[(matches['home_team_api_id'] == team) | (matches['away_team_api_id'] == team)]
# Filter x last matches from team matches
... |
ddacb9f68b0e0c99c3df92f775099dea3076d263 | witcher73/ASM.18.Lab1 | /st26/container.py | 4,556 | 3.625 | 4 | # -*- coding: utf-8 -*-
import pickle
from time import sleep
from os import system
from .read_write import ReadWrite
class Container(ReadWrite):
"""
Контейнерный класс
"""
group = ''
company = ''
students = []
teachers = []
other = []
def __init__(self, t):
self.t = t
... |
52e7bd50c08a6e8869563a2fed1b59d9c23711e8 | msafakdal1/C-programming-examples | /toplamAlınanYol.py | 249 | 3.765625 | 4 | yakıtToplam = float(input("Toplam aktığınız yakıt miktarını giriniz :"))
yolToplam = float(input("Kaç kilometre yol aldığınızı giriniz :"))
toplamHarcama = yakıtToplam * yolToplam
print("Toplam Harcama : {}".format(toplamHarcama))
|
90c89a801eb025b774c7c1b6538d08453716fd71 | msafakdal1/C-programming-examples | /secimİfadesiİleMantıksalİfadeler.py | 1,147 | 3.875 | 4 | secim = str(input("Ucgen mi dörtgen mi?"))
if secim == "Ücgen":
a = int(input("a sayısını giriniz :"))
b = int(input("b sayısını giriniz :"))
c = int(input("c sayısını giriniz :"))
if (abs(b-c)<a<abs(b+c)) or (abs(a-c)<b<abs(a+c)) or (abs(a-b)<c<abs(a+b)):
if a == b and a == c and b == c:... |
e39f3fd97ade869876f12e0fc6338b38a7473f98 | sonofice/Boten-card-game | /eindopdracht.py | 7,005 | 3.53125 | 4 | import time, random, os
print("Welkom bij het drankspel 3 kaarten!", "\nDit zijn de ronde's: ")
def sleep():
time.sleep(1)
def volgende_ronde():
print("Volgende ronde!")
# kaartdeck generation zwart
ranks_zwart = ["2","3","4","5","6","7","8","9","10","boer","koningin","koning","Aas"]
cat_zwart =... |
b9a7101f268e719bb0d1de5bbf6526c7e346e40b | zengfhui/learnpy | /test2_calculator.py | 882 | 3.59375 | 4 | #!/usr/bin/env python3
def count_tax(salary):
rate = 0.165 # 0.08 + 0.02 + 0.005 + 0.06
amount = salary * (1 - rate) - 3500
tax = 0
#tax = 0 is impotant! if loss,
# will raise erroe when salary > 5000 (amount >0))
if amount < 0:
tax = 0
elif amount < 1500:
tax = amount * 0.03
elif tax < 4500:
tax = ... |
1a4c2d8a5ff279c6b64d15c8f91670a2f83f956c | Giuco/data-structures-and-algorithms | /course-1-algorithmic-toolbox/week-1/1-max-pairwise-product/max_pairwise_product.py | 796 | 4.15625 | 4 | # python3
from typing import List
def max_pairwise_product_original(numbers: List[int]) -> int:
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product, numbers[first] * numbers[second])
return max_product
def max_... |
9df0cd672b79c4cf1b0c72898837a02f766aafdc | Giuco/data-structures-and-algorithms | /course-1-algorithmic-toolbox/week-2/2-last-digit-fibonacci-number/fibonacci_last_digit.py | 635 | 3.953125 | 4 | # Uses python3
import sys
def get_last_digit(x: int) -> int:
return int(str(x)[-1])
def get_fibonacci_last_digit_efficient(n: int) -> int:
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, get_last_digit(previous + current)
return current
def get_fibonacci_... |
7289abe95d9b8ba852a51edaac7605cfd25eff2c | Giuco/data-structures-and-algorithms | /course-1-algorithmic-toolbox/week-2/6-last-digit-of-the-sum-of-fibonacci-numbers/fibonacci_sum_last_digit.py | 820 | 4.09375 | 4 | # Uses python3
import sys
def fibonacci_sum_naive(n: int) -> int:
if n <= 1:
return n
previous = 0
current = 1
total_sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
total_sum += current
return total_sum % 10
def fibonacci_sum_efficien... |
a55bbd45554b23e61a699e93ed71bef0b21f09b1 | Giuco/data-structures-and-algorithms | /course-1-algorithmic-toolbox/week-3/3-car-fueling/car_fueling.py | 667 | 3.671875 | 4 | # python3
import sys
from typing import List
def compute_min_refills(distance: int, tank: int, stops: List[int]):
stops = sorted(stops)
stops.append(distance)
last_stop = 0
number_of_stops = 0
for i, stop in enumerate(stops):
if (stop - stops[i - 1]) > tank:
return -1
... |
8c59499947d2278615b1b472ec476be243e9cb0d | jtauber/lotro | /utils.py | 1,418 | 3.546875 | 4 | import struct
import sys
def zeros(s):
"""
test whether the given string is all zeros
"""
return (s == "\0" * len(s))
def printable(ch):
"""
test whether the given character is printable
"""
if 0x20 <= ord(ch) < 0x7F:
return True
else:
return False
def dump(byte... |
fc5acf6505e90ff4f7016a432f53c01a1abcff7d | hansinla/Qualtity_Code | /Lesson code/Palindrome.py | 221 | 4 | 4 | def is_palindrome(s):
"""(str)->bool
This fundction should return True if
and only if the string s is a palindrome.
>>> is_palindrome('noon')
True
>>> is_palindrome('racecar')
True
>>> is_palindrome('ented')
False
"""
|
a51905806e947ea0c67f2b6b308cdb0b063e03e5 | fishjawzrex/python-exercises-with-some-data-visualization | /pie_chart_1.py | 559 | 3.671875 | 4 | '''The purpose of this code is to demostrate
the use of a pie chart in Python for data
visualization'''
import numpy as np
import matplotlib.pyplot as plt
chart = [38,23,54,56,12,43]
labels = ['Food', 'Gas', 'Water', 'Rent',
'Insurance', 'Electricity']
colors = ['yellow','green','red',
'blue', 'c... |
0e41fa4d56678906a9a4a995d4e2aec795eb7552 | fishjawzrex/python-exercises-with-some-data-visualization | /sine_plot.py | 470 | 3.765625 | 4 | '''exploring plotting 2d waves'''
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-2*np.pi, 2*np.pi, .01)
y1 = np.sin(3*x)/x
y2 = np.sin(2*x)/x
y3 = np.sin(x)/x
plt.xlabel('x values')
plt.ylabel('y = f(x)')
plt.title('Trigonometric 2D Waves', fontsize=20,
fontname='Times New Roma... |
bdf2ade575e9fbbedee67f24165a99e0c87ab33d | fishjawzrex/python-exercises-with-some-data-visualization | /normed.py | 836 | 3.5625 | 4 | import numpy as np
import new_mat
#import mnist
#data = mnist.train_images()
def normed(d):
'''THIS IS A FUNCTION THAT TRANSFORMS MATRIX DATA BY NORMALIZING AND
STANDARDIZING THE IMAGE, AND THEN APPENDING IT TO A LIST AND \
RETURNING THE RESULT'''
m,s = new_mat.ms(d)
p = len(d)
#Cr... |
5f54a1d849c6b5045025e50a8e0b601aabe3e243 | PramodBorana/CryptCodes | /Elagamal.py | 2,666 | 3.703125 | 4 | import math
def pRoot(q):
ctain = [None]*(q-1)
#we only find minimum primitve root after that we work co-prime to decrease time complexity
for i in range(2,q):
ch = 0
for j in range(1,q):
ctain[j-1] = (i**j)%q
#print(ctain)
for j in range(1,q):
if(j in ctain):
ch = ch + 1
... |
1e3b9170b9889479e75844c9c7fe7284bda153d9 | PramodBorana/CryptCodes | /CaesarCipherEncrypt.py | 643 | 3.6875 | 4 | # A-Z = 65-90
# a-z = 97-122
s = input("Enter PlainText : ")
l = list(s)
print("------------ For Caeser Cipher key is 3 ------------")
k = int(input("Enter the value of key : "))
for i in range(len(l)):
u = ord(l[i])
if( u >= 97 and u <= 122 ):
u = u + k
if(u > 122):
#print(u)
d = u - 1... |
ef659af897dffdefdc8b7f79dee28a591b5998c0 | itnewcomer/Python100 | /chapter01/06.py | 1,067 | 3.671875 | 4 | ## 06. 集合
## "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
## さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
def n_gram(sentence,n,CorW):
if CorW == 'W':
sentence = sentence.split(' ')
elif CorW == 'C':
sentence = sentence
else:
print('n_gram(sentence,... |
e8594c41e87e3e56d28623ea37daa62c060eaafa | System73/tamarco | /tamarco/core/patterns/proxy.py | 5,642 | 3.71875 | 4 | class Proxy:
"""Proxy pattern to be used as a pointer. When the value of _obj changes, the reference to
the proxy remains.
"""
__slots__ = ["_obj", "__weakref__"]
def __init__(self, obj):
"""Initialize the Proxy class.
Args:
obj (object): New object to be used in the p... |
b3407f8d02fd44f62fab65c5fd523083c7db6e81 | dmitryzhurkovsky/stepik | /module_datetime.py | 222 | 3.609375 | 4 | import datetime
year, month, day = map(int, input().split())
cur_date = datetime.date(year, month, day)
delta = datetime.timedelta(days=int(input()))
result = cur_date + delta
print(result.year, result.month, result.day)
|
f620ca7985ffd8f7804459c2e764a09437592934 | dmitryzhurkovsky/stepik | /Test_generator.py | 344 | 3.546875 | 4 | import itertools
def primes():
i = 2
deviser_count = 0
while True:
for deviser in range(1, i + 1):
if i % deviser == 0:
deviser_count += 1
if deviser_count <= 2:
yield i
deviser_count = 0
i += 1
print(list(itertools.takewhile(lambda ... |
4710d526b1c43bd18e7e4f7077c823043f36d94d | dmitryzhurkovsky/stepik | /python_profiling/euler_7.py | 1,873 | 3.546875 | 4 | """Project euler problem 7 solve"""
from __future__ import print_function
import math
import sys
import cProfile
def profile(func):
"""Decorator for run function profile"""
def wrapper(*args, **kwargs):
profile_filename = func.__name__ + '.prof'
profiler = cProfile.Profile()
result = p... |
1918cbdf1fe6ac478e0bb387929f066ad9d30085 | dmitryzhurkovsky/stepik | /coding_or_decoding.py | 635 | 3.6875 | 4 | key_in, key_out, str_to_encrypt, str_to_decode = (input() for i in range(4))
key_encrypt = dict(zip(key_in, key_out))
key_decode = dict(zip(key_out, key_in))
def encrypt(data):
result = []
for symbol in data:
result.append(key_encrypt[symbol])
return result
def decode(data):
result = []
... |
923d839c12a06d1aaa1a7dc0ddf3c6ad30bd74dc | DrM00G/machine-learning | /src/Riley_matrix.py | 9,546 | 3.515625 | 4 | class Matrix:
def __init__(self, elements=None, shape=None, fill=0):
self.elements = elements
if shape != None:
self.elements = [[0 for j in range(shape[1])]
for i in range(shape[0])]
else:
self.shape = (len(elements), len(elements[0]))
... |
e799642ea4e97cc2aa588f0c717b5a4efb426c8f | DrM00G/machine-learning | /src/matrix.py | 10,493 | 3.671875 | 4 | class Matrix:
def __init__(self, elements = None , shape = None , fill = 0):
self.elements = elements
self.final_determinant = 1
if shape != None:
self.elements =[ [0 for j in range(shape[1])]
for i in range(shape[0])]
else:
self.shape = (len(elements),len(elements[0]))
if ele... |
41d867deb5d0bc5042ca1e73a29a31094dac8683 | free-tiu/Python | /Django/EmployeeManagement-v2.0/app01/utils/pagination.py | 6,697 | 3.546875 | 4 | """
封装分页组件
后期需要使用此组件时,需进行如下操作:
一、在views.py视图函数中
def num_list(request):
# 1、根据个人实际情况获取筛选出需要的数据
queryset = PrettyNum.objects.all()【或filter()】
# 2、实例化分页组件对象
page_object = Pagination(request, queryset) # 可以直接将此写到context中对应的键值中
page_queryset = p... |
a75fe3b76cbda284021daf3f146472372b80bc3f | Kat2bk/cs-guided-project-python-ii | /src/demonstration_07.py | 1,118 | 3.921875 | 4 | """
Challenge #7:
Given a string of lowercase and uppercase alpha characters, write a function
that returns a string where each character repeats in an increasing pattern,
starting at 1. Each character repetition starts with a capital letter and the
rest of the repeated characters are lowercase. Each repetition segmen... |
956860f098f6c55732c4a40b89f61ffe46a35cb9 | hugomacielads/Introducao_Python_3 | /fundamentos/04-correcao-automatica.py | 117 | 3.515625 | 4 | # No caso das divisões o float é utilizado como tipo do resultado
print(10 / 2)
print(type(10 / 2))
print(10 / 3)
|
19ee5e9823a3a592514c51795d64680c97ff859a | hugomacielads/Introducao_Python_3 | /fundamentos/07-listas.py | 864 | 4.09375 | 4 | # A lista é uma estrutura de dados móvel,
# não necessitando de uma nova atribuiçao
lista = []
print(type(lista))
dir(lista)
print(len(lista))
lista.append(1)
lista.append(2)
print(lista)
print(len(lista))
nova_lista = [1, 5, 'Ana', 'Bia']
print(nova_lista)
nova_lista.remove(5)
print(nova_lista)
nova_lista.reverse... |
5333db5858e175603de8ef643227d988f5d80f8f | yost1219/PythonNetworking | /labs/lab5/lab5Ac.py | 1,169 | 3.875 | 4 | """
Author: Yost
Title: Lab 5A - client
Date: 27 Sep 2018
Lab 5A:
Write a TCP Server that will generate a random number from 0 to 100. Then write a TCP Client that
will receive an input from the user (number 0 to 100) and send the guess to the server. The server
will then send back a message prompting the us... |
11a95599a193700dfdca012bb355380914702fb6 | longm89/Python_practice | /870_advantage_shuffle.py | 2,136 | 3.78125 | 4 | """
Given two arrays A and B of equal size,
the advantage of A with respect to B is the number
of indices i for which A[i] > B[i].
Return any permutation of A that maximizes its
advantage with respect to B.
Example 1:
Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]
Example 2:
Input: A = [12,24,8,32]... |
03e1f167ce7bf0212b7556e2bb5ef2615ada7488 | longm89/Python_practice | /513_find_bottom_left_tree_value.py | 1,010 | 4.125 | 4 | """
Given the root of a binary tree,
return the leftmost value in the last row of the tree.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findB... |
fcfac0921fcf5ee017dda7c652e748fa7baa53cb | longm89/Python_practice | /322_coin_change.py | 1,995 | 3.9375 | 4 | """
You are given coins of different denominations and
a total amount of money amount. Write a function to compute
the fewest number of coins that you need to make up that amount.
If that amount of money cannot be made up by any combination of the coins,
return -1.
You may assume that you have an infinite number of ea... |
6a24129e548d532382f589487891e390187284b5 | longm89/Python_practice | /1461_string_contains_all_binary_codes_of_size_k.py | 1,222 | 4.09375 | 4 | """
Given a binary string s and an integer k.
Return True if every binary code of length k is a substring of s.
Otherwise, return False.
Example 1:
Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11".
They can be all found as substrings at indicies 0, 1, ... |
a18b926704febe19ac9cd70081b09b3ea583fc98 | ppysjp93/Effective-Computation-in-Physics | /Functions/lambdas.py | 852 | 4.4375 | 4 | # a simple lambda
lambda x: x**2
# a lambda that is called after it is defined
(lambda x, y=10: 2*x +y)(42)
# just because it isi anonymous doesn't mean we can't give it a name!
f = lambda: [x**2 for x in range(10)]
print(f())
# a lambda as a dict value
d = {'null': lambda *args, **kwargs: None}
# lambda as a keywo... |
8d4dcc0931d3f3a15c7c8865d2a03e42d7b17616 | ppysjp93/Effective-Computation-in-Physics | /NumpyArrays/gradMid.py | 1,519 | 3.9375 | 4 | import numpy as np
print("\nPERFORMING DERIVATIVE\n")
print("""The only problem with this method is the length of the gradient and
midpoint arrays are one less than the original arrays.""")
a = np.arange(10, 20)
b = np.arange(20, 30)
a = np.array(a ** 2)
print("The points in x and y are bin boundaries in t... |
a7a5c4e4218a5e4405dd82ec5c35ac1e155833c1 | ppysjp93/Effective-Computation-in-Physics | /PythonBasics/compphys/physics.py | 236 | 3.609375 | 4 | import constants
two_pi = 2 * constants.pi
h_bar = constants.h / two_pi
sentence_1 = "The value of two_pi is {0}".format(two_pi)
sentence_2 = "h_bar is the value of h divided by {0}".format(h_bar)
print(sentence_1)
print(sentence_2)
|
5c01549c5e88fef47d466803ace0862a8f2331c2 | ppysjp93/Effective-Computation-in-Physics | /Functions/generators.py | 1,482 | 4.4375 | 4 | def countdown():
yield 3
yield 2
yield 1
yield 'Blast off!'
# generator
g = countdown()
next(g)
x = next(g)
print(x)
y, z = next(g), next(g)
print(z)
for t in countdown():
if isinstance(t, int):
message = "T-" + str(t)
else:
message = t
print(message)
# A more complex exam... |
b496e323dae346544c5c2138b75aeb602da6fe43 | trungnguyen1618033/backend-thesis | /convertJson.py | 1,385 | 3.890625 | 4 | # Python program to convert text
# file to JSON
import json
# the file to be converted
filename = "mapping.txt"
# resultant dictionary
dict0 = {}
sno = "celeb"
# fields in the sample file
fields = ["stt", "ten", "link", "path"]
with open(filename) as fh:
dict1 = []
for line in fh:
# print(line,... |
b170d52c83f8fa6ccf798f9aa51bb8cc9ee038c6 | ethiclesshacker/priceTracker | /mergeData.py | 1,316 | 3.609375 | 4 | import pandas as pd
import numpy as np
nonSale = pd.read_csv("phoneDetails2403NonSale.csv")
sale = pd.read_csv("phoneDetails1903Discounted.csv")
nonSale = nonSale.rename(columns={"Price":"Original Price"})
nonSale["Sale Price"] = sale.Price
nonSale = nonSale.drop(["Internet Connectivity 4G"],1)
nonSale = nonSale[no... |
07cd97744983a2971e0f5afc9b8412c393c63bbe | z-sector/algorithms-course | /homework_2/arrays.py | 6,309 | 3.53125 | 4 | import ctypes
class Array:
def check_index(self, index):
if not self.size:
raise IndexError('Array is empty')
if index >= self.size or index < 0:
raise IndexError('Invalid index')
def __getitem__(self, index):
return self.array[index]
def __se... |
7b68cf4e8fcee83d9a1dcbeed91907e7f47c3033 | AmarthigaK/Python-programming | /function2.py | 186 | 3.921875 | 4 | def addNumbers(x,y):
return x+y
a=int(input("type 1st number:"))
b=int(input("type 2nd number:"))
print(addNumbers(a,b))
#cls Task1
larger/smaller
#cls task2
def odd_even():
|
edbb19417baa55c576dd4c029d3f475b060d9e64 | computerMoMo/algorithm-python | /select_sort.py | 558 | 4.25 | 4 | # -*- coding:utf-8 -*-
import sys
def find_largest(sort_arr):
res_index = 0
res = sort_arr[0]
for i in range(0, len(sort_arr)):
if sort_arr[i] > res:
res = sort_arr[i]
res_index = i
return res_index
def select_sort(sort_arr):
new_arr = []
length = len(sort_arr... |
44d25959105b873f4071c4db9b0d55292a9ca496 | KangHyunWook/Zero-shot-cross-modal-retrieval-for-affective-images | /howmany.py | 419 | 3.625 | 4 | """
shows how many files
"""
import os
def getFileList(root):
files=os.listdir(root)
pathList=[]
for file in files:
path=os.path.join(root, file)
if os.path.isdir(path):
pathList.extend(getFileList(path))
else:
pathList.append(path)
return... |
4d1e8a6eaf77b532d236178ce49d8815604a5576 | TakuyaKurimoto/fishing | /app/Http/Controllers/pytgrjeijgose.py | 405 | 3.515625 | 4 |
n=int(input())
a = []
#リストAにappend()を使って格納していく
for _ in range(n):
a.append(input())
B=[]
for i in range(n):
if a[i][0]=="!":
b=a[i].replace('!', '')
b=b+"!"
else:
b=a[i]
B.append(b)
B=sorted(B)
ans=0
for i in range(n-1):
if B[i]+"!"==B[i+1]:
print(B[i])
ans+=... |
e92ac8ef71d8aeef216b0d4d59a83cf35e979737 | shumbul/DSA | /Algorithms/Dynamic Programming Algorithms/Python/fibonacci_memo.py | 385 | 3.796875 | 4 | #recursive:
def fib_rec(n):
if(n == 1 or n == 2):
return 1
if (memo[n] != 0):
return memo[n]
memo[n] = fib(n-1) + fib(n-2);
return memo[n]
#iterative:
def fib_it(n):
memo[1] = memo[2] = 1
for i in range(3,n):
memo[i] = memo[i-1] +memo[i-2]
return memo[n-1]
x=int... |
f363ae1a92d3328efcfbf6c20fd7c61595f9e2a6 | nairarunraj/advent_of_code | /y2020/day23.py | 1,987 | 3.6875 | 4 | """
--- Day 23: Crab Cups ---
"""
from y2020.file_utils import get_input_line
def solve(input_line, is_puzzle2):
no_of_cups = len(input_line) if (not is_puzzle2) else int(1e6)
next_cup = [None for _ in range(no_of_cups + 1)]
cup_labels = [int(cup_label) for cup_label in input_line]
for i in range(le... |
53aa1cb4f6da76b603338efef669aa71a7a1e274 | nairarunraj/advent_of_code | /y2020/day21.py | 2,863 | 3.65625 | 4 | """
--- Day 21: Allergen Assessment ---
"""
from collections import defaultdict
from y2020.file_utils import get_input_data
def puzzle1(input_file) -> int:
input_content = get_input_data(input_file)
foods = []
for line in input_content:
(ingredients, allergens) = line.split(' (contains ')
... |
813a18178899bafee78eda1e77b83c32802d431e | nairarunraj/advent_of_code | /y2020/day3.py | 1,330 | 3.5625 | 4 | """
--- Day 3: Toboggan Trajectory ---
"""
from y2020.file_utils import get_input_data
def get_tree_count_for_slope(input_content, slope_x, slope_y):
max_len = len(input_content)
start_row = start_col = tree_count = 0
while start_row < max_len:
line = input_content[start_row]
col_len = l... |
555585d12c095d20783924b193fdcfbc827186a9 | Alison-Rodrigues/Python-Estudo-Faculdade | /exercicio_radar.py | 252 | 3.828125 | 4 | #python 3.7.1
import random
velocidadeCarro = random.randrange(60,120,10)
if velocidadeCarro > 80:
multa = (velocidadeCarro - 80) * 7
print('Você foi multado!')
print(f'O valor da multa foi de R${multa:.2f}')
else:
print('Velocidade OK!')
|
97af4ddcd22bdd184a69ddb5edd84cf0610f6913 | ShakirKhurshid/Fibonacci-Series-Tester | /Fibonacci Tester.py | 468 | 3.828125 | 4 | import math
import random
def isPerfectSq(x):
q = int(math.sqrt(x))
return q*q == x
def isFibonacci(List=[]):
for n in List:
if isPerfectSq(5*n*n + 4) or isPerfectSq(5*n*n - 4):
FiboList.append(n)
List=[]
FiboList=[]
for i in range(100):
r=random.randint(0,100)
if r not in List: List.append... |
94f0a48d76b5b0c9a5445b13065b3426aa7fdb4d | alexmorley/spikeextractors | /spikeextractors/SortingExtractor.py | 18,358 | 3.53125 | 4 | from abc import ABC, abstractmethod
import numpy as np
import copy
class SortingExtractor(ABC):
'''A class that contains functions for extracting important information
from spiked sorted data given a spike sorting software. It is an abstract
class so all functions with the @abstractmethod tag must be impl... |
2c7926ba3280dbee2c3bb85dd16100a607c5374a | SDSS-Computing-Studies/004-booleans-ssm-0123 | /task1.py | 602 | 4.5 | 4 | #! python3
"""
Have the user input a number.
Determine if the number is larger than 100
If it is, the output should read "The number is larger than 100"
(2 points)
Inputs:
number
Outputs:
"The number is larger than 100"
"The number is smaller than 100"
"The number is 100"
Example:
Enter a number: 100
The number is... |
e7087895dad8fa6b023001614913a122e75b3a0b | ShaunHoward/robot_security | /packages/project1/utilities/csv2dict.py | 2,863 | 3.65625 | 4 | __author__ = 'shaun'
import csv
import os
import math
def get_file_paths_and_names(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yiel... |
ad95a715fa638fe3b17d2fe15ae52f59ed8fb58d | inker610566/pyalgorithm | /splay_tree/splay_tree.py | 1,343 | 3.75 | 4 | '''
A minimal implementation of splay tree.
'''
class SplayTree:
def __init__(self):
self.ch[0] = self.ch[1] = self.p = None
self.value = None
def __getitem__(self, qValue):
if self.value == qValue:
return self
if self.value == None:
return None
... |
10c80e1cf40351fa10753638917077d33ea78e54 | sdws/face | /第二题.py | 780 | 3.53125 | 4 | # 读取data.json,取出所有值为数字的Key-Value对,按值从大到小排列,存入目标文件p2.txt
with open('data.json', 'rb') as fr:
content_j = fr.read().decode('utf-8')
fr.close()
content_dict = eval(content_j)
dict_new = {}
def dict_v_num(d):
for k, v in d.items():
if isinstance(v, int):
dict_new[k] = v
elif isinstance... |
e0d91e5470225199e2c2eb4085e21dbabe055dd3 | YouMKim/CS51_Final_Project | /take_in_txt.py | 5,173 | 3.5 | 4 | '''
CS51 Final CS51_Final_Project
take_in_txt.py
This is a function to help us with preprocessing data
in a format that our random tree will follow
'''
import os
import string
#counts the number of words in a file
def count(f):
words = string.split(f)
wordCount = len(words)
return wordCount
#list of key words we... |
2ec3881522fe87180342c17ac80690cbc867112d | KateBilous/Python_Class | /Task_13.py | 1,050 | 4.34375 | 4 | # Пользователь вводит длины катетов прямоугольного треугольника.
# Написать функцию, которая вычислит и выведет на экран площадь треугольника и его периметр.
# Площадь прямоугольного треугольника S = 1/2 a*b
import math
class SquareAndPerimOfTriangle:
@staticmethod
def print_input():
a = int(input(... |
74e1b3bd36e8b51e932b2dee3b0730594145c1b0 | KateBilous/Python_Class | /Task_10.py | 1,161 | 3.6875 | 4 | import datetime
import time
# Дана строка вида "Leo Tolstoy*1828-08-28*1910-11-20".
# В этой строке указаны имя писателя и через символ * даты рождения и смерти.
# Даты указаны в формате "YYYY-MM-DD". Требуется написать программу,
# которая по переданной строке определит возраст писателя и вернет его имя и возраст.
... |
83b82cf97db7a34d5317cb2c66e79bd000ff5043 | PengDauan/qrlab | /lib/math/interpolator.py | 643 | 3.609375 | 4 | import numpy as np
class Interpolator:
def __init__(self, xs=None, ys=None, order=2):
if xs is not None:
self.set_interpolation(xs, ys, order)
def set_interpolation(self, xs, ys, order=2):
self.params = np.polyfit(xs, ys, order)[::-1]
def __call__(self, arg):
... |
02b0aeebab04235c4ebd3f1944e059e6faf581d2 | kayartaya-vinod/2019_04_PYTHON_NXP | /examples/ex08.py | 708 | 4.21875 | 4 | '''
More loop examples:
Accept two numbers and print all primes between them
'''
from ex07 import is_prime
from ex06 import line
def print_primes(start=1, end=100):
while start <= end:
if is_prime(start): print(start, end=', ')
start += 1
print()
line()
# this function re-writes (overwrit... |
23c74a448ad146eb0800971b1757c93cc2efba10 | kayartaya-vinod/2019_04_PYTHON_NXP | /examples/ex09.py | 609 | 4.09375 | 4 | '''
Exceptions Demo
'''
def main():
n1 = input('Enter a number: ')
n2 = input('Enter another number: ')
try:
n1 = int(n1)
n2 = int(n2)
n3 = n1 // n2
print('{} / {} = {}'.format(n1, n2, n3))
# print('%s / %s = %s' % (n1, n2, n3))
# print(n1, '/', n2, '=', n3)... |
c7cfafe6eff93379c2882662843ca8e953f7f885 | TheDroker/4-Bit-RPG | /Barnyard.py | 493 | 3.609375 | 4 | class Animal:
def __init__(self,name):
self.name = name
def speak(self,sentence):
print(sentence)
#def bark(sale
class Dog(Animal):
def __init__(self,name,bark):
super(Animal,self).__init__(name)
self.bark = bark
def speak(self):
super(Animal,se... |
058a01fa70d67c4322fa03dcb7b7ba1bfbf2d5b8 | gabrielriqu3ti/GUI_Tkinter | /src/grid.py | 381 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 22:24:18 2020
@author: gabri
"""
from tkinter import *
root = Tk()
# Creating Label Widget
myLabel1 = Label(root, text = "Hello World!")
myLabel2 = Label(root, text = "My name is Gabriel H Riqueti")
# Shoving it onto the screen
myLabel1.grid(row = 0... |
25774d8ba7fb7c757e5d520a8312255cb5041d8d | MachelleBa/EindOpdracht_Python_Machelle | /Session.py | 5,377 | 3.515625 | 4 | #Machelle Bakker - Python - 30/09/2019
#To start the entire program, first run Server.py, then run Program.py
from Manager import Manager
from Cook import Cook
from HeadChef import HeadChef
class Session(object):
def __init__(self):
self.login = self.new_login()
def logout(self):
self.login =... |
25fdf02e83531caf2b52182a5eca1dbbb0bde4ce | CarlosTheran/pyspark_examples | /hadoop_read_covi.py | 1,498 | 3.765625 | 4 | from pyspark.sql import SparkSession
from pyspark import SparkConf, SparkContext
sparkSession = SparkSession.builder.appName("rwHDFS").getOrCreate()
sparkcont = SparkContext.getOrCreate(SparkConf().setAppName("rwHDFS"))
# Read csv file from HDFS as DataFrame
df = spark.read.csv('hdfs://namenode:8020/covi/csv_covi19'... |
e8b17247c209bdd31a4b0950172a477bb7d32ad6 | AaryaBatchu/micropython | /src/robots/param-bot/rotary-read-test.py | 655 | 3.5625 | 4 | import time
from machine import Pin
rotaryA = Pin(16, Pin.IN, Pin.PULL_DOWN)
rotaryB = Pin(17, Pin.IN, Pin.PULL_DOWN)
val = 0
# we set the old value to zero for both bits being off
old_combined = 0
while True:
A_val = rotaryA.value()
B_val = rotaryB.value()
# a sifts by one bit and then is ORed with the B... |
6badf00a0f749a79502b5a8e6df11e4de8c5cc78 | AaryaBatchu/micropython | /src/robots/param-bot/button-irq-example.py | 822 | 3.578125 | 4 | import machine, utime
# globals
button_presses = 0
last_time = 0 # the last time we pressed the button
# the lower right coner has a wire that goes throuh
count_input = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_DOWN)
# this function gets called every time the button is pressed
def button_pressed_handler(pin):... |
2c9dc951ab32255fcc05c7761b286892d6e08698 | ChubbyPotato/Birthday-quiz | /birthday.py | 3,288 | 4.6875 | 5 | """
birthday.py
Author: Suhan
Credit: None
Assignment: Birthday
Your program will ask the user the following questions, in this order:
1. Their name.
2. The name of the month they were born in (e.g. "September").
3. The year they were born in (e.g. "1962").
4. The day they were born on (e.g. "11").
If the user's bir... |
876187f5eba3156eeca16e965f281ff5a00a898d | StudentTechClubAsturias/TallerGitBasico | /esPrimo.py | 843 | 4.125 | 4 | """
Autor: X
"""
#Nota: los primos son: Naturales, > 1, divisibles entre ellos mismo y entre 1
def esPrimo(n):
"""
Metodo para comprobar si un numero n dado es primo o no
params: un numero n
return: True si es primo y False de no serlo
"""
#Si es menor que 2 no puede ser primo
if n < 2: return False
#El r... |
9b9dc46ec831bbf9fcc04e79a2ffa498186d8e95 | princedan5106/guvi | /vorc.py | 267 | 3.5625 | 4 | ch = input()
v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
c = [ chr(x) for x in range(65, 91)]
for x in c:
c.append(x.lower())
for x in c:
if x in v:
c.remove(x)
if c in v:
print("Vowel")
elif ch in :
print("Consonant")
else:
print("invalid")
|
a1905baefee28f49d28502aa9b988636d7e4ba82 | AmaanSingh/python_projects | /GuessDatabase2.py | 1,303 | 3.84375 | 4 | import random
import shelve
def Highscore():
db = shelve.open("Highscores")
print("Scores:")
print(db["scores"])
db.close
exit = 0
while exit == 0:
try:
Highscore()
except:
KeyError
print("Setting up database...")
db = shelve.open("Highscores")
db["scores"] = []
db.close
print("W... |
0390ae5b1294c1f4508737f3a8096ba5a64c522e | pilarOrtega/pdl1 | /auxiliary_functions/read_csv.py | 226 | 3.640625 | 4 | import csv
def read_csv(file_path):
with open(file_path, newline='') as file:
reader = csv.reader(file, delimiter=',')
list = []
for row in reader:
list.append(row)
return list
|
8117eed08dbe2803db65510843a217ad1602808e | yhoang/rdm | /IRI/20170619_IRI.py | 2,620 | 4.3125 | 4 | #!/usr/bin/python3.5
### printing methods
# two ways to print in Python
name = 'Florence'
age = 73
print('%s is %d years old' % (name, age)) # common amongst many programming languages
print('{} is {} years old'.format(name, age)) # perhaps more consistent with stardard Python syntax
### dictionary
shopping_dict = {'... |
fe7219d3dcbcb122404675c79678ec2aa46fec85 | pascalmcme/myprogramming | /week5/lists.py | 392 | 4.25 | 4 |
list = ["a","b","c"] #changeable and orderable collection
tuple = (2,3) # not changeable
print(type(list))
print(len(tuple))
list.append(99)
print(list)
newlist = list + [1]
print(newlist)
lista = [1,2,'a',True] # different data types in list
print(lista[0])
print(lista[1:]) # 1 to end
print(lista[::-1])
p... |
a0403d41c2db65b5a7e307a0b52bf778553ed921 | pascalmcme/myprogramming | /week7/files.py | 586 | 3.71875 | 4 | #with open(".\lecture1.txt", "r+") as f: # does not exist, then cannot open
# print("create a file")
#with open(".\lecture1.txt", "w") as f:
#print("create a file")
with open("testdata.txt","rt") as f:
data = f.read()
print(data)
with open("testdata.txt","rt") as f:
data = f.read(4) # number of ... |
5229b88af0e36af6b3830ed199059b11815bfe51 | pascalmcme/myprogramming | /week7/messingWithJson.py | 255 | 3.609375 | 4 | #json for storing data
import json
electricBill = {
"name":"Andrew",
"Amount":"999"
}
with open("storeData.json","wt") as f:
json.dump(electricBill,f)
with open("storeData.json","rt") as f:
readDict = json.load(f)
print(readDict["name"]) |
5907c80dd55ac3a4941be4e83b4785894bae4b9a | pascalmcme/myprogramming | /week6/flexibleArguements.py | 160 | 3.625 | 4 | print("hi",55,[])
def average(*numbers):
sumOf = sum(numbers)
return sumOf / len(numbers)
ave = average(1,2,3,4,5,6,7,8,9)
print("average is: ",ave) |
88044fba92673eae63292c65aa63c804fc4fb041 | ridersw/Karumanchi---Algorithms | /selectionSort.py | 448 | 4.125 | 4 | def selectionSort(arr):
size = len(elements)
for swi in range(len(elements)-1):
minIndex = swi
for swj in range(minIndex+1, size):
if elements[swj] < elements[minIndex]:
minIndex = swj
if swi != minIndex:
elements[swi], elements[minIndex] = elements[minIndex], elements[swi]
if __... |
6c6446047ab205e0c0ebdb48e9ceb9756e4bbd61 | thomas-smith-v/decorate | /decorate/core.py | 10,243 | 3.5 | 4 | from typing import Any, Callable, Dict, Iterable, Tuple, Union
from functools import wraps
import inspect
class precall(object):
"""General function decorator for calling function(s) ~before~ the wrapped functions.
"""
def __init__(
self,
prefunctions: Union[Callable, Iterable[Callable]] =... |
cdbe4bb71cef4fc4897b0241243ee4c01f63bea3 | TassiaBastos/Treatment-of-incomplete-kernels | /Scenario_Modified/Analysis_average/Total_analysis/analysis_desvio.py | 1,374 | 3.59375 | 4 | import sys
from typing import List
from math import sqrt
# input
F1_score_final_STANDARD_DEVIATION = sys.argv[1]
# RMSE_final_STANDARD_DEVIATION = sys.argv[1]
# Pearson_correlation_final_STANDARD_DEVIATION = sys.argv[1]
# output
analysis_F1_score_Desvio = sys.argv[2]
# analysis_RMSE_Desvio = sys.argv[2]
# analysis_Pea... |
9dc55ee70b4aecfa0304be1ec4f3ee86c7fea22b | AlexGioffDev/morse_code_translator | /main.py | 2,961 | 3.765625 | 4 | from util import clear, logo
import time
CODE_MORSE_TABLE = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
... |
9998e91b6ebc15ab4b3dec130adb81ba1e556ea4 | cbassp/empezando_en_la_escuela | /adivina_un_numero.py | 322 | 4.0625 | 4 | numero_a_adivinar = 0
numero = 1
while numero_a_adivinar != numero:
numero_a_adivinar = int(input('Introduce un numero para que lo adivinen: '))
numero = int(input('Adivina el numero: '))
if numero_a_adivinar == numero:
print('Bien, has acertado.')
else:
print('Mal, sigue intentandolo.'... |
e4e00113ef04328f36118f6fd4679d49f47941d5 | dz0/pyCharmEDU_course_creation_helpers | /src/idioms/_3_loop_list.py | 1,573 | 3.90625 | 4 | # List loops
finances = [10, -5, 15]
###TASK: foreach loop without indices
for x in finances: ###PLACEHOLDER: -->for i in range(len(finances)):
print( x ) ###PLACEHOLDER: x--> finances[i]
###TASK: foreach with numeration
for i , x in enumerate(finances): #use i, x in ... ###PLACEHOLDER: , x in enumera... |
6baf2a5dc52ba55005b7cbb6fb78f28bc7ea51ac | shivam221098/data-structures | /trees.py | 5,847 | 3.953125 | 4 | """
Max Heap
"""
import sys
def parent(pos):
return pos // 2
def left_child(pos):
return pos * 2
def right_child(pos):
return (2 * pos) + 1
class MaxHeap:
def __init__(self, size):
self.maxsize = size
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Hea... |
e2ba05960bea2140c368e71a68ee2b65a7456334 | gavthetallone/daily-python-challenges | /programs/wednesday.py | 669 | 4.03125 | 4 | def evendigits(user_input):
numbers_list = user_input.split()
num1 = int(numbers_list[0])
num2 = int(numbers_list[1])
number_string = ""
for count in range(num1, num2+1):
if count % 2 == 0:
if count > 9:
temp = [int(digit) for digit in str(count)]
... |
35abeac292754572c174d2817c97c3031aa09b83 | Haider8/python-webapp2 | /make_rot.py | 890 | 3.765625 | 4 | # make_rot.py
#ascii of m is 109
#ascii of a is 97
#ascii of z is 122
#ascii of M is 77
#ascii of A is 65
#ascii of Z is 90
def rot_func(text):
i = 0
rot_text = [None] * len(text)
while i < len(text):
s = text[i]
asci = ord(s)
if asci >= 97 and asci <= 122:
if asci <= 1... |
7173c636c6d0f748a6c189ea944a279f1bf49332 | pfothergill/ciphers-and-codes-using-python | /transpositions/transpose1to8and4to5.py | 2,730 | 3.828125 | 4 | #!/usr/bin/python3
class Cipher:
def __init__(self, phrase):
self.phrase = phrase
self.length = len(phrase)
self.bracketedWords = []
def printPhrase(self):
return self.phrase
def validate(self):
if self.length % 8 == 0:
return
else:
... |
23be72a89cd1a6fdde00d57be9ebbcc63525bd3b | elevinixl/git_practice | /elevin/atbs/ch7/isStrongPassword.py | 412 | 3.828125 | 4 | import re
def isStrongPassword(text):
lengthRegex = re.compile(r'.{8}.*')
upperRegex = re.compile(r'[A-Z]')
lowerRegex = re.compile(r'[a-z]')
numRegex = re.compile(r'\d')
if lengthRegex.search(text) and upperRegex.search(text) and lowerRegex.search(text) and numRegex.search(text):
return Tr... |
b0a18d4615a88c3f29546b977c2185569bcfe4df | elevinixl/git_practice | /elevin/py_practice/listManipulation.py | 619 | 3.734375 | 4 | def remove1(n, element):
for index in range(len(n)-1,-1,-1):
if n[index] == element:
n.pop(index)
return n
def remove2(n, element):
newList = []
for value in n:
if value != element:
newList.append(value)
return newList
def addElement(n,element):
return n... |
ae404d45401a240df5aa47686ca68712a8c5eb5c | elevinixl/git_practice | /jmejia/py/refresher/longlist.py | 7,900 | 4.15625 | 4 | import time
# This is a mergesort...turns out mergesort is easier to remember than quicksort, and the slice syntax makes it a lot easier.
# This will output the sorted listed -- it will not sort the list in place.
def sortList(list) :
if len(list) <= 1 : # both [] and [x] are perfectly sorted -- no work needed
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.