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 |
|---|---|---|---|---|---|---|
519a574e61e44ca81fa78011f2c44f0c602f8d3c | TerryOShea/algorithms | /interview_cake/single_riffle.py | 484 | 3.65625 | 4 | def single_riffle(shuffled_deck, half1, half2):
i, j, runner = 0, 0, 0
while runner < len(shuffled_deck):
if i < len(half1) and half1[i] == shuffled_deck[runner]:
i += 1
elif j < len(half2) and half2[j] == shuffled_deck[runner]:
j += 1
else: return False
... |
ab3b4adbf83c3fe36ee3bfb679abe459c0fff4bd | TerryOShea/algorithms | /interview_cake/cake_thief.py | 907 | 3.96875 | 4 | def cake_thief(cake_tuples, weight_capacity):
"""
takes a list of cake tuples (weight, value) and a weight capacity
returns the maximum value the weight capacity can hold
"""
max_values_at_capacities = [0] * (weight_capacity + 1)
for current_capacity in range(weight_capacity + 1):
curren... |
42f461846e86438a99fbde3e743a5f687f063535 | jackyen2000/workstation | /Mendal's First Law/mendalRule1.py | 1,247 | 3.84375 | 4 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
#Three positive integers k, m, and n, representing a population containing k+m+n organisms:
#k t are homozygous dominant for a factor, m are he... |
35f1385f3ef7f7b562fb51d9b135d89974e23e54 | stewartdunn/mmm-pi-workshop | /python/button_no_delay.py | 863 | 3.515625 | 4 | #!/usr/bin/env python
r_pin = 11
w_pin = 12
button_pin = 22
import RPi.GPIO as GPIO
from time import sleep
import time as time_
def millis():
return int(round(time_.time() * 1000))
GPIO.setmode(GPIO.BOARD)
GPIO.setup(r_pin, GPIO.OUT)
GPIO.setup(w_pin, GPIO.OUT)
GPIO.setup(button_pin, GPIO.IN)
last = False
pr... |
48139f7a40949375afd30c97872fd92b50448d8d | ptallrights/python | /westos/day4/test3.py | 485 | 3.640625 | 4 | #!/usr/bin/env python
class Tom(object):
def __init__(self,name):
self.name = name
self.a = 100
self.b = None
self.__c = 300
def test1(self):
print self.name
self.b = 200
print 'test1',self.b
def test2(self,age):
self.age = age
print 'test2',self.age
self.__test3()
def __test3(self):
prin... |
ca063750413348227c68c3705cd15ff44cd63161 | ptallrights/python | /westos/day4/test6.py | 1,002 | 3.875 | 4 | #!/usr/bin/env python
import datetime
class Dog(object):
def __init__(self,n):
self.n = n
self.__a = None
@property
def open_f(self):
return self.__a == None
@open_f.setter
def open_f(self,value):
self.__a = value
d = Dog(22)
print d.open_f
d.open_f = 'ok'
print d.open_f
print "#####################... |
e5255886e092a5235bd2ba4a9405659817cf3267 | ptallrights/python | /oldboy/shopping.py | 1,370 | 4.03125 | 4 | #!/usr/bin/env python
import sys
salary = int(raw_input('please input your salary:'))
#print '------Shopping Menu------'
products = [
['Iphone',':',3000],
['MacPro',':',12000],
['MX4',':',2200],
['Mp3',':',100],
['Cigarate',':',32],
['Nike shoes',':',500],
['Water',':',5]
]
#create a shop... |
65e8a7d44ca96af78b82f57f8ee99ffe5fa215a3 | ptallrights/python | /oldboy/login.py | 585 | 3.59375 | 4 | #!/usr/bin/python
import sys
uaername = 'pt'
password = 'ok'
locked = 1
counter = 0
while counter < 3:
user = raw_input("please input a name for you:").strip()
if len(user) == 0:
print '\033[31;1mUsername cannot be empty!\033[0m'
continue
passwd = raw_input("please input password:").strip()
if len(passwd) == ... |
8795d2b95cd9bf007b77e74289f46cb85a866a6e | Tiago489/DatabaseAsAService | /web/app.py | 3,890 | 3.5 | 4 | #imports Flask (runs the app on an instance of the Flask object), jsonify and request handle the requests made as a json format file for mongo
from flask import Flask, jsonify, request
#imports from flask_restful the Api and Resource (creates a class for the services used by the app)
from flask_restful import Api, Reso... |
d7d67479a3d56bb1187acd1e327c2d6a4430c6a5 | JasmineOsti/pythonProject1 | /Class.py | 813 | 4.21875 | 4 | #WAP to find the number is negative, positive or 0 that is entered y the user.
#num=int(input('enter a number'))
#if num<0:
# print('number is positive')
#elif num>0:
# print('number is negative')
#else:
# print('number is zero')
#dstring=input("how far did you travel today(in miles)?")
#tstring=input("How lon... |
156203c9c9a1c80101caf18ba558e1c89f682c42 | JasmineOsti/pythonProject1 | /Program.py | 289 | 4.3125 | 4 | #Write a program that takes three numbers and prints their sum. Every number is given on a separate line.
A = int(input("Enter the first number: "))
B = int(input("Enter the second number: "))
C = int(input("Enter the third number: "))
sum = A+B+C
print("the sum of three numbers is", sum) |
7149be47d3373508444898f27d68e06211fec3a2 | satoru-kikuchi/tech | /Tech/Text/Chapter6/Section6-2/practice/practice.py | 171 | 3.890625 | 4 | list1 = [1, 2, 10, 8]
list2 = [23, 19, 10, 9]
list1_new = list1.sort(reverse=True)
list2_new = list2.sort()
print(list1)
print(list2)
print(list2.reverse())
print(list2)
|
c4937d2c7aee162574e93633193fae3c2863b9e9 | satoru-kikuchi/tech | /Udemy/Section7/77.py | 300 | 3.71875 | 4 | class Person(object):
@classmethod
def first(cls):
print('first')
first = 'AAA'
def __init__(self, name='anounymos'):
self.name = name
def name(self):
print('name')
print(Person.first)
person = Person()
print(person.name)
|
b7a1b850c5dfe4c2baadf075f910038a18e84f0d | satoru-kikuchi/tech | /Tech/Text/Chapter5/Section5-1/if_or.py | 237 | 3.671875 | 4 | from random import randint
size = randint(5, 20)
weight = randint(20, 40)
if (size >= 10) or (weight >= 25):
result = "合格"
else:
result = "不合格"
text = f"サイズ {size}、重量{weight}:{result}"
print(text)
|
b8131854c104c12b2c0ff9651ce6470a49494ab9 | satoru-kikuchi/tech | /Tech/Text/Chapter16/Section16-4/boston_regression.py | 851 | 3.796875 | 4 | from sklearn import datasets
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame
# データセット読み込み
boston = datasets.load_boston()
boston_df = DataFrame(boston.data)
boston_df.columns = boston.feature_names
boston_df["Price"] = boston.target
print(boston_df[:10])... |
7f7246bb7a8b6573f48c337cfba0d7f2ff526428 | satoru-kikuchi/tech | /Tech/Text/Chapter9/Section9-1/dict_popitem.py | 340 | 4.0625 | 4 | fruit = {"apple": 7, "orange": 5, "peatch": 6}
while fruit:
ans = input("フルーツを取り出しますか?(y/n):")
if ans == "y":
key, value = fruit.popitem()
print(f"{key}は{value}値")
elif ans == "n":
print("終了しました。")
break
else:
print("もう空っぽです。")
|
48eb5ccbdf8bb0062738185dd8451e620a4596e5 | satoru-kikuchi/tech | /Tech/Text/Chapter6/Section6-4/list_in.py | 179 | 3.8125 | 4 | names = ["鈴木裕子", "田中里美", "桜木颯太"]
name = "里美"
result = False
for item in names:
if name in item:
result = True
break
print(result)
|
9fd1550d43a19ce91a1b216a4b679309fee41db3 | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/7. 추상 데이터 타입/eg_stack_balance_parenthesis.py | 1,282 | 3.96875 | 4 | from stack import Stack
def balance_parenthesis(string):
s = Stack()
for i in string:
if i == '(':
s.push(i)
else:
if s.isEmpty():
return False
s.pop()
return s.isEmpty()
def balance_parenthesis_book_answer(string):
s = Stack()
... |
f235564e58144498b3d120c5493d3c383689ebdd | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/11. 동적 계획법/greedy_coins.py | 297 | 3.71875 | 4 | coins = [500, 100, 50, 10]
def greedy_coins(money):
result = []
count = 0
for coin in coins:
num_coin = money // coin
count += num_coin
result.append(num_coin)
money = money % coin
return result, count
m = 5380
r, c = greedy_coins(m)
print(r, c)
|
bddfe341bf74485e3abc54d9b61c4a28a32ad77e | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Data_Structure/2. 시퀀스/문자열 압축/compress_string.py | 495 | 3.578125 | 4 | a = 'aaabbbbccccccddeeeeff'
def compress_string(s):
temp_arr = []
temp_arr.extend(s)
length = len(temp_arr)
result = ''
count = 1
for i in range(length):
if i == (length - 1):
result += str(count)
break
if i == 0 : result += temp_arr[i]
if temp_ar... |
cb442e6d02c8c1f648571be713a4d7aff03efad8 | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/10. 검색/binary_search.py | 752 | 3.8125 | 4 | # 재귀 함수
def binary_search_rec(seq, target, low, high):
if low > high:
return None
mid = (low + high) // 2
if target == seq[mid]:
return mid
elif target < seq[mid]:
return binary_search_rec(seq, target, low, mid-1)
else:
return binary_search_rec(seq, target, mid+1, hi... |
d4a5ef59b2ec2c3ead110b63fa66945847f14e1c | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/10. 검색/eg_find_max_unimodal_array.py | 757 | 3.8125 | 4 | def find_max_unimodal_array(l):
len_l = len(l)
mid = len_l // 2
if l[mid] > l[mid+1] and l[mid] > l[mid-1]:
return l[mid]
elif l[mid] > l[mid+1] and l[mid] < l[mid-1]:
return find_max_unimodal_array(l[:mid])
else:
return find_max_unimodal_array(l[mid+1:])
def find_max_unimo... |
4b87e33f12d5883216a26b491b3909ddf2533d7a | beomseok-kang/Algorithms-Python | /이코테/C15/30-1.py | 1,351 | 3.53125 | 4 | def bisect_get_left_right(word, left_search):
start = 0
end = len(word)
if left_search:
while start <= end:
mid = (start + end) // 2
if word[mid] == '?':
start = mid + 1
else:
end = mid - 1
return end + 1
else:
w... |
d4fccb61e6bc546cb4dc8c19ab951428ef82aaa6 | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/7. 추상 데이터 타입/eg_ll_part_linked_list.py | 1,156 | 3.96875 | 4 | from linkedListFIFO import LinkedListFIFO
def part_linked_list(ll, n):
result_ll = LinkedListFIFO()
ll_temp = ll
node = ll_temp.head
i = 0
while node:
if node.value < n:
result_ll.addNode(node.value)
ll_temp.deleteNode(i)
elif node.value == n:
... |
79470b6249b8e7e360b85853a48c2cbb0b332cb9 | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/10. 검색/eg_find_occurrence.py | 685 | 3.671875 | 4 | from binary_search import binary_search_iter
def find_occurrence(l, n):
i = binary_search_iter(l, n)
while l[i] == l[i-1]:
i -= 1
count = 1
while l[i] == l[i+1]:
i += 1
count += 1
return count
def find_occurrence_book_answer(seq, k):
index_some_k = binary_search_iter(se... |
9ada4ad01acf14442423cd6dcfc092dd14bbcdcb | beomseok-kang/Algorithms-Python | /파이썬 자료구조와 알고리즘/Algorithm/13. 이진 트리/AVL_BST.py | 4,413 | 3.984375 | 4 | from binary_tree import NodeBT, BinaryTree
class NodeAVL(NodeBT):
def __init__(self, value=None, height=1):
self.value = value
self.height = height
self.left = None
self.right = None
def insert(self, value):
new_node = NodeAVL(value)
if value < self.value:
... |
ad71df144c6bcea9478b532f033bacba2ecf2b8d | chan032/PS | /pg_greedy4.py | 694 | 3.609375 | 4 | def solution(n, costs):
answer = 0
costs.sort(key = lambda x : x[2])
# print(costs)
parent = [i for i in range(n)]
def find(parent, x):
if x == parent[x]:
return x
else:
parent[x] = find(parent, parent[x])
return parent[x]
def un... |
b6dbcc2a404140c98cc87d4a1a2361905862f529 | sn1572/leetcode | /160_intersection_of_two_linked_lists.py | 1,569 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def toLinkedList(list):
head = None
prev = None
current = None
for element in list:
current = ListNode(element)
try:
prev.next = current
... |
40c456e67e03069b74c4a5b025c04463397d971d | sn1572/leetcode | /240_search_a_2d_matrix_II.py | 2,952 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 12:06:16 2019
@author: mbolding3
"""
from bisect import bisect_left as bl
class Solution:
def diagSearch(self, matrix, target):
limit = min(len(matrix), len(matrix[0]))
left, right = 0, limit-1
while left != right:
m = (lef... |
32e0a7d7096b08bda252763666d6fadbcea1eb9a | sn1572/leetcode | /371_sum_of_two_integers.py | 3,499 | 3.671875 | 4 | class Solution:
def getSum(self, a: 'int', b: 'int') -> 'int':
def addBits(bit1, bit2, carry):
#returns (val, carry)
if bit1 == bit2 == '1':
if carry == '0':
return('0','1')
elif carry == '1':
return('1','1')
... |
d57b2dc440f71adc1f428325e8bdd627e0898231 | sn1572/leetcode | /21_merge_two_sorted_lists.py | 1,298 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
if l1 is None:
return(l2)
elif l2 is None:
return(l1)
... |
213e880581d8211252e7501de87be9ecb53420c2 | sn1572/leetcode | /131_palindrome_partitioning.py | 3,163 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 09:10:10 2019
@author: mbolding3
"""
class Solution:
def findMinimals(self, s):
# BFS stage, finds indices of all palindromes
# of length 2 or 3
len2, len3 = [], []
N = len(s)
for i in range(N-1):
if s[i] == s... |
1919e5e18a73e60bcc1788cfda67bd7e1c1d7ad1 | sn1572/leetcode | /234_palindrome_linked_list.py | 2,282 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def toList(array):
if array == []:
return(None)
else:
head = ListNode(array[0])
current = head
for element in array[1:]:
current.nex... |
46051a0192e97ba659c60434ecad79a5473969cd | cameron-stock/PythonPracticeTwo | /function.py | 589 | 3.921875 | 4 | #def foo(name):
#return "Hi %s" % name.title()
#This will make the first letter of the name uppercase
def sentence_maker(phrase):
interrogatives = ("how", "what", "why")
capitalize = phrase.capitalize()
if phrase.startswith(interrogatives):
return "{}?".format(capitalize)
else:
... |
a2f709f74b40ef44b21a4bcaef118fd1a3ce4905 | holyzala/CS361 | /Lab6/User.py | 7,741 | 3.671875 | 4 | import unittest
class User:
def __init__(self, username, password):
self.username = username
self.password = password
self.wishlist = []
self.accessList = []
def login(self, password):
return self.password is password
def append(self, item):
if item in sel... |
beffcfb37c088c9547a8d183e701d47c9be7e51e | dicai/stats_notebook | /importance_sampling.py | 2,238 | 3.59375 | 4 |
# coding: utf-8
# In[184]:
import numpy as np
import pylab
import scipy
import seaborn as sns
get_ipython().magic(u'matplotlib inline')
get_ipython().magic(u"config InlineBackend.figure_format = 'retina'")
# # Importance sampling
#
# We'll look at an example where we can compute the posterior exactly and compare ... |
00972148408e415f499c82e1fd1876d83123c9d6 | emribeiro/criptografia | /commons/conversor.py | 915 | 3.9375 | 4 | #Attention: All operations is coded in ASCII
import binascii
# Convert ASCII string into HEX string
def ascii_to_hex(ascii_str):
ascii_data = ascii_str.encode("ascii")
return binascii.hexlify(ascii_data).decode('ascii')
# Convert HEX String into ASCII string
def hex_to_ascii(hex_str):
hex_data = hex_str... |
ccf7f343af9acce1b0c25082688a6e0b847f4a7e | zeynepsaracbasi/Matrix | /matrix.py | 6,044 | 3.78125 | 4 | from copy import deepcopy
import math
from typing import List
class Matrix(object):
def __init__(self, liste):
self.set_matrix(liste)
def get_matrix(self):
return self.matrix
def set_matrix(self, liste): # input list controls to fit matrix requirements
if type(lis... |
75f90c4b763e1d36e35a2c6e495afa796ca781f1 | ZohanHo/untitled | /Задача 27.py | 574 | 4.1875 | 4 | """Факториалом числа n называется произведение 1 × 2 × ... × n. Обозначение: n!.
По данному натуральному n вычислите значение n!.
Пользоваться математической библиотекой math в этой задаче запрещено."""
#n = int(input("введите факториал какого числа необходимо вычислить: "))
def fun(n):
d = "*".join(str(i) for i... |
0182bd38a40144d1c1bad5937b801be0189363ab | jiyaaa/Diploma-CGPA-CALCULATOR | /Diploma_CGPA_BD.py | 494 | 3.609375 | 4 | print('System of 2016, Diploma In Engineering')
I = (float(input('1st semester: '))*5)
II = (float(input('2nd Semester: '))*5)
III = (float(input('3rd Semester: '))*5)
IV = (float(input('4th Semester: '))*10)
V = (float(input('5th Semester: '))*15)
VI = (float(input('Six Semester: '))*20)
VII = (float(inp... |
b82b037f0e3b9a29124ce8ab33260cb7fb29a029 | shiagit/temp | /guess3.py | 287 | 3.5 | 4 |
import random
ans = input('輸入數字:')
wrong = []
while True:
rnum = str(random.randrange(1000))
if rnum in wrong:
continue
if rnum == ans:
print('輸入數為'+ rnum)
break
else:
print(rnum)
wrong.append(rnum)
continue
|
8c84b194d5007ac731061b5da5d72561f5b08985 | yiyulanghuan/deeplearning | /docs/content/regularization/dropout.py | 516 | 3.625 | 4 | # %%
# During eval Dropout is deactivated and just passes its input.
# During the training the probability p is used to drop activations. Also, the activations are scaled with 1./p as otherwise the expected values would differ between training and eval.
# https://discuss.pytorch.org/t/model-eval-vs-with-torch-no-grad/... |
a95709257a74597a699a2f2f7a511e121902739a | rogeriosantosluz/pybologna | /test_game.py | 4,414 | 4.0625 | 4 | import unittest
from utils import *
from game import Game
import random
"""
TestGame class
"""
class TestGame(unittest.TestCase):
"""
Basic setup, creates 4 random users, with 4 random game levels
"""
def setUp(self):
random_names = ['Rogerio','John','Alexander','Fiona','Shrek','Martin','Luther... |
3b2ef1bdb63c5e83ae9497950c2f63459feeb3b5 | jrodrigolg/LivroIPP | /Capítulo 4/Ex4.8.py | 347 | 4.0625 | 4 | n1 = float(input("n1: "))
n2 = float(input("n1: "))
operacao = input("opreraçao: ")
if operacao == "+":
resultado = n1+n2
elif operacao == "-":
resultado = n1-n2
elif operacao == "*":
resultado = n1*n2
elif operacao == "/":
resultado = n1/n2
else:
print("operaçao invalida")
resultado = 0
print(f... |
4a96808a86799d59e9f806910a0af82157697a16 | MagicOctopusUrn/05AB1E | /lib/vectorizer.py | 3,874 | 4.4375 | 4 | def vectorized_evaluation(a, b, function, pre_function=None):
"""
Uses the given function in the form of a lambda and produces a vectorized result if
at least one of the items is an iterable value. Otherwise, it evaluates it as normal.
:param a: The first value for the function
:param b: The second ... |
aedfec68c603c422e16c51cb0dd2f6cc3260b9c2 | PaulFenton/KaggleHousePricing | /preprocess/drop_unimportant.py | 734 | 3.640625 | 4 | import pandas as pd
def simple(data):
before = data.columns.size
data = data.drop(['MiscFeature', 'MiscVal', 'Utilities', 'RoofMatl', 'Fence'], axis=1)
print("Dropped " + str(before - data.columns.size) + " unnecessary columns.")
return data
def remove_outliers(x_train, y_train):
#combine
combi = pd.conc... |
f912a2db8e51f55d88b16ccc0fbab8713a3e77e4 | zzid/Coding-Test-Practice | /2020/2020_06_17/programmers_2018 KAKAO BLIND RECRUITMENT_auto_complete.py | 896 | 3.5625 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/17685
class Trie:
def __init__(self):
self.val = 0
self.children = {}
def solution(words):
answer = 0
root = {}
for i in words:
child = root
for j in range(len(i)):
if i[j] not in child:
chil... |
b1f9390125bae38f421d1ca774a226ed67865302 | ArtOfHack/ares | /power_menu.py | 3,155 | 3.5625 | 4 | #!/usr/bin/python
#STEP 1
low = str(range(1, 1000))
medium = str(range(1, 2500))
high = str(range(1, 5000))
#mega = str(range(1, 10000))
#mega_low = str(range(1, 30000))
#mega_medium = str(range(1, 60000))
#mega_high = str(range(1, 100000))
#super = str(range(1, 300000))
#super_mega_low = str(range(1, 600000))
#super... |
e1057e1ddfbcf28c56fef7e736b90e1af988b655 | TrellixVulnTeam/allPythonPractice_R8XZ | /2019/04/0425/02-tcp-client循环使用服务器.py | 810 | 3.5 | 4 | import socket
def main():
# 创建套接字
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端口
tcp_server.bind(('', 8887))
# 监听端口
tcp_server.listen(128)
while True:
# 等待客户端链接 // 获取ip和内容 程序卡在这里等待客户端连接
new_client_socket, client_addr = tcp_server.accept()
... |
957a0b4055bc67923936088490e9708067ec8e08 | Ritakushwaha/Web-Programming | /loops.py | 457 | 4.1875 | 4 | #looping lists
for i in [0, 1, 2, 3, 4, 5]:
print(i)
#looping with range func
for i in range(6):
print(i)
#looping lists of name
for i in ["Rita", "Girwar", "Priyanshi", "Pragya", "Vijaya"]:
print(i)
#loop through each character in name
for i in "Rita":
print(i)
#loop through dictionaries
houses = {... |
d66fcaabbddc95fe887d582a7e6179a55cbc5fac | Sophieylchan/chapter9 | /projectiles.py | 472 | 3.703125 | 4 | from math import pi, tan, cos
g= 9.81
v0= 44
theta= 80
x= 0.5
y0= 1
# checking theta
theta = theta*(pi/180)
print("Acceleration =", g,"m/s")
print("Velocity =", v0, "m/s")
print("Theta =",theta, "radians")
print("Horizontal distance =", x, "m")
print("Barrel height =", y0, "m")
y = y0 + x*tan(theta) - g*x**2 / (2*(v0... |
325c241eaf735f944cf18a11852cdf219e5c4913 | s15003/algorythm_design_pattern | /power.py | 1,150 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import random
X = random.randint(3, 9)
LOOP_COUNT = 5000
def power(x, n):
ans = 1
for _ in range(n):
ans *= x
return ans
def power2(x, n):
if n == 0:
return 1
if n == 1:
return x
tmp = power2(x, n // 2)
... |
bc6b574bb3330e07bb7bef5f204be79fad4126d4 | asliboyar/freshman_codes | /missing_lowest.py | 201 | 3.78125 | 4 | #a is a list of int, we try to find the missing lowest positive number in the list.
def findlowest(a):
b=1
while b in a:
b+=1
return b
a= list(map(int,input().split()))
print(findlowest(a))
|
79df45c623ae762cf33cbd4470a95a50676de61e | pgDora56/NwakaCharrenge | /words.py | 1,104 | 3.5625 | 4 | import random
class Words:
def __init__(self, _word, _part):
self.word = _word
self.part = _part
def add_modifier(self):
raise Exception("add_modifier is undifined.")
class Nouns(Words):
def __init__(self, word, part):
super().__init__(word, part)
... |
25128923b4a2e0d5964657ff99b9e2955bbf5b45 | dirkk0/brython_sandbox | /data/sample_c.py | 151 | 3.6875 | 4 | import sys
import random
map = []
for i in range(3):
map.append([])
for j in range(3):
map[i].append(random.randrange(2))
print(map) |
7ac958f145fe8810dc2909404fb9b455334e11ab | CamilleB99/python | /tuples_sets.py | 820 | 4.09375 | 4 | # A Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
# Cretae tuple
fruits = ('Apples', 'Oranges', 'Grapes')
#fruits2 = tuple(('Apples', 'Oranges', 'Grapes'))
# Single value needs a trailing comma
fruits2 = ('Apples',)
# Get a value
print(fruits[1])
# Can't chage value
#fruits[0] =... |
8974954da3ae14c953c79828ac28c02bc0b04967 | RaysOfTheSun/DataStructures-Python | /DataStructures/Trees/BinaryTree/BinarySearchTree.py | 6,074 | 3.90625 | 4 | # Date: April 5, 2018
"""This is a simple implementation of a binary search tree
using python"""
from Trees.BinaryTree.Node import Node
from collections import deque
class BinarySearchTree:
__RootNode = None
def __init__(self):
self.__RootNode = None
# Inserts an item into the binary search t... |
42b4b6a670104699ba473a9260d56cb0133a598a | darthkenobi5319/Python-Lab-2 | /3.py | 375 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 10:38:02 2017
@author: ZHENGHAN ZHANG
"""
#prompt
x=input('Please enter a list of words separated by commas: ').split(',')
x.sort()
print(x)
#extend
y=input('Please enter another list of words separated by commas: ').split(',')
x.extend(y)
x.sort()
print(x)
#index
z=x... |
8c316610c103b79bb8b6f83bde58cdc1e810fcd5 | ochestra365/Rasberry_python | /PUTTY/Work/Pysrc/if.py | 93 | 3.859375 | 4 | money=500
if money>500:
print("taxi")
elif money==500:
print("bus")
else:
print("Walk")
|
a980dd15dc81e8c8d80941f2688f8685ffd63939 | faizannadeem784/OOP | /New folder (2)/PIAIC/Calculator using functions.py | 2,875 | 3.96875 | 4 | def Cal_INFO():
print("\t\t*****Welcome to my calculator*****")
print("\t\t******_____FAIZAN NADEEM_____*****")
print("\n\tPress 1. for Addition")
print("\n\tPress 2. for subtraction")
print("\n\tPress 3. for Multiplication")
print("\n\tPress 4. for Division")
print("\n\tPress 5. for Modulos... |
c1f60a6e99577115781d8d93ce32bbc8c2a44818 | tetreaum/DataCommSemesterProject | /src/euchre.py | 15,316 | 3.75 | 4 | """
A class to hold all of our game logic.
Card codes
NINE = 1
TEN = 2
JACK = 3
QUEEN = 4
KING = 5
ACE = 6
Suit Codes
CLUBS = 0
DIAMONDS = 1
HEARTS = 2
SPADES = 3
"""
import random
class Euchre:
def __init__(self):
self.dealingPhase = True # set to this at the start
self.choosingTrumpPhase1 = F... |
e514895602935ac6512e48ddfbc0162c28f23794 | ranganmostofa/Traveling-Salesman-Problem | /UndirectedGraph/Edge.py | 6,118 | 3.71875 | 4 | from GraphProcessing import GraphProcessing
class Edge:
"""
General-purpose Edge class for the BipartiteGraph module
NOTE: Multiple edges are not supported. As such, the incident node names uniquely identify an edge
"""
def __init__(self, weight, attributes, first_incident_node, second_incident_n... |
7ed22a12ea40aa5a8ef64699aba1efde12d90fa9 | Sheretluko/LearnPython_homeworks | /lesson2/13_for_2.py | 313 | 4.03125 | 4 | # Тема "Цикл for". Задание 2
# Ввести строку и вывести на экран вертикально:
# один символ на каждой строке
def main():
line = input('Введите любую строку: ')
for letter in line:
print(letter)
main() |
df5270ff28213fc89bf0ee436b9855c73e026d9d | Sakshi011/Python_Basics | /set.py | 1,190 | 4.21875 | 4 | # set data type
# unordered collection of data
# INTRO ----------------------------------------------------------------------------------
s = {1,1.1,2.3,3,'string'}
print(s)
print("\n")
# In set all elemets are unique that's why it is used to remove duplicate elements
l = [1,2,4,2,3,6,3,7,6,6]
s2 = list(set(l))
print(... |
241d30d64cb95891ecbd1fadbd32b61c662111d0 | rutujanaik1228/hello-world- | /python program to find average of given elements of a list .py | 334 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[22]:
l=[]
n=int(input("enter no. of elements :"))
for i in range(0,n):
a=int(input("enter list element"))
l.append(a)
print("the list is:",l)
sum=0
for i in range(0,n):
a=l[i]
sum+=a
print(sum)
avg=sum/n
print("the average is:",avg)
# In[19]:
5
... |
ab3226bee4eb3d03025e0cbaf57437feccec8801 | rutujanaik1228/hello-world- | /Fibonacci series.py | 385 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
n=int(input("enter number of terms:"))
n1,n2=0,1
cnt=0
if n<=0:
print("enter a positive integer")
elif n==1:
print("fibonacci series upto",n,"terms:")
print(n1)
else:
print("fibonacci series upto",n,"terms:")
while cnt<n:
print(n1)
n3... |
442c73939086c47bc00c620d94bde83dcd14fedd | pd-pony/machinelearning | /DecisionTree1.py | 784 | 3.5625 | 4 | print(__doc__)
import numpy as np
#Create a random dataset
rng=np.random.RandomState(1)
x=np.sort(5*rng.rand(80,1),axis=0)
y=np.sin(x).ravel()
y[::5]+=3*(0.5-rng.rand(16))
#Fit regression model
from sklearn.tree import DecisionTreeRegressor
clf_1=DecisionTreeRegressor(max_depth=2)
clf_2=DecisionTreeRegressor(max_dept... |
25401f5061ccabbded56366310f5e42e910eddd7 | gourdcyberlab/pollen-testbed | /scapy-things/varint.py | 1,438 | 4.375 | 4 | #!/usr/bin/env python
import itertools
'''
Functions for converting between strings (formatted as varints) and integers.
'''
class VarintError(ValueError):
'''Invalid varint string.'''
def __init__(self, message='', string=None):
ValueError.__init__(self, message)
self.string = string
# Can'... |
ff2095dd1e9162f1d071db51448b2556031860d4 | srishtii24/FreeCodeCamp-DataAnalysisWithPython | /Sea Level Predictor/sea_level_predictor.py | 1,138 | 3.75 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress
def draw_plot():
# Read data from file
df = pd.read_csv('epa-sea-level.csv')
lr = linregress(df['Year'], df['CSIRO Adjusted Sea Level'])
slope = lr.slope
intercept = lr.intercept
df_2 = df[df['Year'... |
9daf908b41101f42715f3e1c682702b78cd9a667 | darshneet2607/AI-self-practice | /q2.py | 565 | 3.78125 | 4 | Basic_Salary = float(input("Enter Basic Salary :"))
if Basic_Salary<=10000:
DA = (Basic_Salary * 80) / 100
HRA = (Basic_Salary * 20) / 100
Gross_Salary = Basic_Salary + DA + HRA
elif Basic_Salary<=20000:
DA = (Basic_Salary * 90) / 100
HRA = (Basic_Salary * 25) / 100
Gross_Salary = Basic_... |
4d53e54e9cb7a1328571f01e4da1462046e171a4 | dlitvak/sdcnd-term1-proj1-finding-lane | /pipeline_functions.py | 8,020 | 3.796875 | 4 | import math
import cv2
import numpy as np
"""Pipeline to process images and draw road lanes"""
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray'... |
9f252de1b0aeb54e159c35846c40bce395d24ad3 | Intern-Yago/lib_menu-Python | /usandoCadastrar.py | 657 | 3.875 | 4 | """
Exemplificação dos pacotes, subpacotes e módulos do menuArquivos_py
"""
from menuArquivos_py import cadastrar
from menuArquivos_py import menu
from menuArquivos_py.leiaIntFloat import leiaInt
while True:
escolha = menu.menu('menu principal', 'Ver pessoas cadastradas', 'Novo Cadastro', 'Sair do programa')
i... |
2c1699da529112c4820a06bdd0933ae4c6c11032 | colinmcnicholl/automate_boring_tasks | /firstWordRegex.py | 840 | 4.25 | 4 | import re
"""How would you write a regex that matches a sentence where the first word
is either Alice, Bob, or Carol; the second word is either eats, pets, or
throws; the third word is apples, cats, or baseballs; and the sentence ends
with a period? This regex should be case-insensitive."""
firstWordRegex = re... |
0697109331684d4fb71ac466ab98b023809b4e4b | siri3/Byte_Exercises | /py_basics/classes_hw.py | 1,274 | 3.796875 | 4 | #For each company, store the name, ticker
#symbol, purchase date, purchase price, and number of shares. Methods include: add
#new symbol (new purchase), remove symbol (all shares sold), and YTD or Annual
#Return performance for any or all symbols given a current price (and date).
import datetime
class stock:
... |
9ae978dfddea6edf33b41fd1614115fb53f18ad4 | Theerapatpt/pythonBasic | /Basic_GUI/basicGUI.py | 807 | 3.828125 | 4 | # is All Library (tkinter packageAll GUI Python)
from tkinter import *
from tkinter import ttk
def helloworld():
print('hello This is Diamond shop')
def calculate():
price = 85000 # Diamond Price:
quan = int(quantity.get()) # defualt of .get() is string
total = price * quan
print("Quantity of Diamond : %d Tot... |
6f3019f0bb9b7320ee1051267a74f4186c9ad8b1 | MagicalThread4/Wie-is-het | /wieishet.py | 819 | 3.625 | 4 | import sys
geel = input("Is de kaas geel? ")
if geel == "ja":
gaten = input("Zitten er gaten in? ")
if gaten == "ja":
duur = input("Is de kaas belachelijk duur? ")
if duur == "ja":
print("Emmenthaler")
sys.exit()
else:
print("leerdammer")
... |
f6cec6a3cd9c5ebb0c209b0d6091fa4feb260848 | ngthalogit/Hackerrank- | /Data Structures/balanced_brackets.py | 1,008 | 3.890625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'isBalanced' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
def isBalanced(strings):
loop = True
stack = list()
i = 0
while i < len(strings) and l... |
91b9cbfeca6f447427a3008795b05eb40c026163 | shakhovm/Classes_Lab5 | /Classes_Lab5/triangle.py | 1,777 | 4.25 | 4 | from math import sqrt
from Classes_Lab5 import line, point
class Triangle:
"""
Triangle
"""
def __init__(self, top_a, top_b, top_c):
"""
:param top_a: Point
:param top_b: Point
:param top_c: Point
>>> triangle = Triangle(point.Point(1,1), point.Point(3,1), poi... |
901cfcc418c14cbdc3dc6b67440c0bcd22c42a35 | bryano13/holbertonschool-interview | /0x09-utf8_validation/0-validate_utf8.py | 1,186 | 4.15625 | 4 | #!/usr/bin/python3
"""
This software defines rules to check if an integer combination is a valid
UTF-8 Encoding
A valid UTF-8 character can be 1 - 4 bytes long.
For a 1-byte character, the first bit is a 0, followed by its unicode.
For an n-bytes character, the first n-bits are all ones, the n+1 bit is 0,
followed by n... |
6e00ddc0bc863e9cb05fc895dcc14bddbc1055a9 | mfatima5bc/Design-patterns-em-python | /decorator/start.py | 307 | 3.59375 | 4 | def decorator(funcao):
def wrapper(*arg, **kwargs):
print('Entrou no decorator')
print(arg)
print(kwargs)
funcao(*arg, **kwargs)
return wrapper
class Hero:
@decorator
def metodo(self, num):
print('Entrou na class Hero')
deku = Hero()
deku.metodo(4) |
ad34250006ebd1305657f4ba94cd7982895f6ddb | sofiarani02/Assigments | /Assignment-1.2.py | 2,825 | 4.5 | 4 | print("***Python code for List operation***\n")
# declaring a list of integers
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# List slicing operations
# printing the complete list
print('myList: ',myList)
# printing first element
print('first element: ',myList[0])
# printing fourth element
print('f... |
2652b2c2f41d9efc2c0169204f70ec929bd32cac | ycl818/Python | /Feis/tuple.py | 194 | 3.796875 | 4 | t =('YIchien','60','D')
print(t)
print(type(t))
t2 = sorted(t)
print(t2)
print(type(t2))
# iterator is not a sequence
t3 = reversed(t)
print(type(t3))
print(t3)
for i in t3:
print(i) |
83c792d36c4f1c499f084de01e687092e9597d7a | ycl818/Python | /Feis/star_sign.py | 132 | 3.5 | 4 | # t =(1,2,3)
# *a,b =t
# print(a) #list
# print(b)
def f(a,b,*c):
print(a)
print(b)
print(c) #tuple
f(1,2,3,5)
|
c8596e484950554750e7f847b01086b2f779facd | ycl818/Python | /Feis/obj_class.py | 382 | 3.59375 | 4 | class Foo:
bar = 5 # 類別物件內可以定義屬性(attribute)
f = Foo()
g = Foo() # f, g 根本沒bar 但能用
print(Foo.bar, f.bar, g.bar)
print(Foo.bar) # 類別裡面取物件
Foo.bar = 10
print(Foo.bar)
print(type(Foo))
class Record:
pass
p = Record() # 產生一個物件
print(type(p))
print(id(p))
Record.name = "Yi-Chien Lee" # 可以
Record.scores = ... |
cfa899ab8f42cf9c2bf9fed2252fa2d535df37c2 | ycl818/Python | /CS200/vector_define.py | 283 | 3.59375 | 4 | class Vector:
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
p = Vector(3,4)
q = Vector(5,6)
print(object.__str__(p))
print(Vector.__str__(p))
print(p.__str__())
print(str(p))
print(p)
print(type(p)) |
818736d28fad406bf94e1ebbf46992e9938ee173 | ycl818/Python | /Feis/inheritance.py | 775 | 3.90625 | 4 | class Vector3:
def __init__(self,x,y,z):
self.x,self.y,self.z=x,y,z
def __str__(self):
return f'({self.x},{self.y},{self.z})'
def __add__(self,other):
return Vector3(self.x+other.x,self.y+other.y,self.z+other.z)
def length(self):
return (self.x**2+self.y**2+self.z**2)**0.... |
56cc4deeb8d82fe0a032ea4b0f84feff308315ab | baroquebloke/project_euler | /python/4.py | 541 | 4.125 | 4 | # A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 x 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# result: 906609
# time: 0.433s
#
# *edit: optimized*
def palind_num():
is_pal = 0
for x in range... |
149483d6f16e6df2424cac309492f0fe0e0a6d51 | mrh1997/headlock | /headlock/address_space/virtual.py | 3,135 | 3.546875 | 4 | from . import AddressSpace
class VirtualAddressSpace(AddressSpace):
"""
This is a dummy address space implementation. Maps all memory operations
to the python bytearray .content and all bridging operations to .funcs.
Its main purpose is for testing.
"""
CODE_ADR_OFFSET = 100000000
def __... |
6514f8fde7a116f59201bb5e21fe88bab68a6ed8 | aconbere/fixit | /fixit/__init__.py | 2,148 | 3.5 | 4 | from types import FunctionType
class Table(object):
"""
An abstract representation of a sqlalchemy table
"""
def __init__(self, model):
self.rows = []
self.model = model
self.columns = self.model.__table__.columns.keys()
def row(self, name):
row = Row(self.columns)... |
054eaa44d1652eb87ed365839643ee4e76d4bbe7 | codejoncode/Sorting | /project/iterative_sorting.py | 2,418 | 4.5 | 4 | # Complete the selection_sort() function below in class with your instructor
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j ... |
2633ea0e95cf62a4d428d84b261bd946c40bc1a5 | MattCCS/SecurityQuestions | /securityquestion.py | 652 | 3.71875 | 4 | """
Script for answering security questions!
"""
import argparse
import base64
import hashlib
import sys
def answer(response):
h = hashlib.md5(response).digest()
ans = base64.b16encode(h)[:8].decode('utf-8')
print(f"Answer: {ans}")
def parse_args():
parser = argparse.ArgumentParser(
descrip... |
276f4fa1e30601d902f29deb4dc3932ac430fd2d | geofferyj/WEJAPA_INTERNSHIP | /wave4/Labs/Functions labs/3.docstring.py | 333 | 3.8125 | 4 | def readable_timedelta(days):
# insert your docstring here
""" function to convert ints to date format
Args:
days (int): number to convert
Returns:
str: converted data in a sentence
"""
weeks = days // 7
remainder = days % 7
return "{} week(s) and {} day(s)".format(week... |
1ced62858071d7ea1ee50ff2bf50760f9ff7b65c | ElenaMBaudrit/OOP_assignments | /Person.py | 1,108 | 4.25 | 4 | #Todd's March 21st 2018
#example of a class.
class Person(object):
#Always put "object" inside the parentheses of the class
def __init__(self, name, age, location):
#double underscores in Python: something that is written somewhere else. "Dunder"= double underscores.
#constructor: name of the fu... |
1acb9ac0ece343d3fd7203e44ab2ede9e89f626b | amandadepperschmidt/Learning.Python-ChooseUrOwnAdventure | /Tower-Adventure.py | 12,000 | 4.25 | 4 | name = raw_input("What do other people call you? ")
location = raw_input("Where do you live? ")
fears = raw_input("What are you so afraid of? ")
print "\n\nSo, your name is %r, you live in %r, and you're scared of %r." % (
name, location, fears)
ans = raw_input("\nIs that correct? y/n ")
if ans == "y":
... |
4f09b254496a90f0955db7d649b5319111875eb8 | soniclinzj/Python_base | /流畅的Python/第二章序列构成的数组/lesson2_1.py | 2,370 | 3.8125 | 4 | # 2.1 内置序列类型概览
'''
序列类型
1.容器序列
list、tuple、collections.deque 这些序列能存放不同类型的数据。
2.扁平序列
str、bytes、bytearray、memoryview 和array.array 这类序列只能容纳一种类型,即一段连续的内存空间只能存放一些基础类型如字符、字节和数值。
也可按能否修改进行分类:
1.可变序列(MutableSequence)
list、bytearray、array.array、collections.deque 和 memoryview.
... |
23fc884294c13cdf236168d9c60a4be31683e060 | Falcn8/AoC | /d3-2-code.py | 822 | 3.796875 | 4 | import math # to calculate
import pyperclip # to copy
right_list = [1, 3, 5, 7, 1]
down_list = [1, 1, 1, 1, 2]
def get_trees_for_slope(right, down, lines):
x = right
y = down
trees = 0
while y < len(lines):
if x > len(lines[y]) - 1:
x = x % len(lines[y])
if lines... |
ae291db702da12fd49265214bb7b73ef009dc2d0 | PatoSayajin/Codigo-de-MAtesentre-otros | /Probabilidad condicional.py | 909 | 3.984375 | 4 | from fractions import Fraction
print("Probabilidad condicional:\n\nEjemplo: ")
ejemplo = {"titulo": "apro--repro = total","H": "H:12-----4 = 16", "M": "M:20-----4 = 24", "T": "T:32-----8 = 40"}
p_r_h = (4/40)/(16/40)
p_r_h_f = str(Fraction(p_r_h))
print(ejemplo["titulo"])
print(ejemplo["M"])
print(ejemp... |
334b56aaa81e6bf450e66fe672582d3fabac99e8 | Saphiraa/snar | /lexicon.py | 1,120 | 3.953125 | 4 | actions = ['attack', 'go', 'check']
directions = ['next room', 'previous room']
enemies = ['spider', 'bug', 'snake', 'wolf']
filler = ['from', 'with', 'to']
weapons = ['wood_sword', 'iron_sword', 'steel_mace', 'steel_sword', 'steel_dagger', 'iron_dagger']
lexicon = {
"actions": actions,
"... |
b586a65d5912be768b79dcd15da38c5868792759 | madhumitha1506/Python_Assignments | /Day-1/ex2.py | 252 | 3.984375 | 4 | a = 'madhu'
b = 2
c = a+str(b)
print(c)
#Adding integer with the string is getting error because two strings only get concatenate or we have to both in same type
# Above program give output because I convert integer into string then it will work |
6b0dcc7412e8d2a862c84144a264ec3320583703 | Kirill96/python_lab_2 | /task10/filter.py | 776 | 3.5625 | 4 | class Filter(object):
def __init__(self, arg):
self.obj = [el for el in arg]
def __iter__(self):
return iter(self.obj)
def __str__(self):
return str(self.obj)
def filtration(self, function):
length = len(self.obj)
for i in range(length):
if functio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.