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 |
|---|---|---|---|---|---|---|
448abffb797417c1721cce7a8d54e5720a9e281c | ledpear/algorithm | /PROGRAMMERS/Level 1/숫자 문자열과 영단어_python/CodingTest.py | 477 | 3.671875 | 4 | import string
def solution(s):
answer = ''
num_list = list(string.digits)
dic = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9}
temp = ''
for c in s:
if c not in num_list:
temp += c
if temp in dic:
... |
24a149550d5efb124ebe62dc6fcbf14bf91d01a3 | ledpear/algorithm | /LEETCODE/9. Palindrome Number - Python/CodingTest.py | 483 | 3.6875 | 4 | class Solution:
def reverse(text):
result = ""
for i in text :
result = i + result
return result
def isPalindrome(self, x: int) -> bool:
Num = str(x)
ReverseNum = Solution.reverse(Num)
return Num == ReverseNum
print(Solution.isPalindrome(None, 121)... |
dbe8972828d8a1fb980cdb6e57ef7d4479b8d61c | ledpear/algorithm | /BAEKJOON/15000~/15654_N과 M(5)_python/CodingTest.py | 619 | 3.578125 | 4 | import string
import sys
input = sys.stdin.readline
arrSize, permutationSize = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
def permutationsPrint(arr, size, result, used):
if len(result) == size:
for num in result:
print(num, end=' ')
print()
for... |
2e045de83fd7aa18e3e13758215025950768c1d8 | sushtend/100-days-of-ml-code | /code/basic python in depth/11 logical operator.py | 202 | 4.15625 | 4 | name = "Abdul Kalam"
if not name:
print("1st name is empty")
name = ""
if not name:
print("2nd name is empty")
# Chaining comparison operator
age = 25
if 18 <= age <= 25:
print("Eligible")
|
3798e1209d1c9b72ea564fdaf497ba308224e273 | sushtend/100-days-of-ml-code | /code/basic python in depth/20 stacks.py | 489 | 3.921875 | 4 | # https://www.youtube.com/watch?v=NKmasqr_Xkw&list=PLTjRvDozrdlxj5wgH4qkvwSOdHLOCx10f&index=11
# stack : Last in First out
class Stack:
items: list = []
def __init__(self):
pass
def insert(self, value):
self.items.append(value)
def pop(self):
if self.items:
retu... |
144afc3ab864c66f4398397805d9baaa15a011c4 | sushtend/100-days-of-ml-code | /code/basic python in depth/14 for else.py | 364 | 4.0625 | 4 | names = ["KAbdul", "Vikram", "Satish"]
# Old programming style
# found = False
# for name in names:
# if name.startswith("A"):
# found = True
# print("Found")
# pass
# if not found:
# print("Not found")
# New style
for name in names:
if name.startswith("A"):
print("Found")... |
6c8326308e4df9e5a607376b8ccf1c68a1ba6478 | sushtend/100-days-of-ml-code | /code/basic python/13.5 guessing game.py | 361 | 4.1875 | 4 | Guess_count=1
guess=9
print("+++++ This program lets you guess the secret number +++++")
while Guess_count<=3:
num = int(input("Gues the number: "))
if guess==num:
print("Correct")
#exit()
break
Guess_count+=1
# Else for while loop evaluates after completion of all loops without brt... |
01f1a28072145cf5655eae9b816f411a8c1c9aa6 | sushtend/100-days-of-ml-code | /code/Advanced Python 1/1 classes.py | 600 | 3.90625 | 4 | # Attributes and methods
# https://www.youtube.com/watch?v=ZDa-Z5JzLYM
class Employee:
def __init__(self, first, last, pay): # Instance is passed always
self.first = first
self.last = last
self.pay = pay
def fullname(self):
return "{} {}".format(self.first, self.last)
emp_1... |
a957102ba9b196c13b102ecdf02e81ed94796a8b | sushtend/100-days-of-ml-code | /code/basic python in depth/21 sets.py | 1,367 | 4.5 | 4 | # https://realpython.com/python-sets/
#
numbers = [1, 2, 3, 4]
first = set(numbers)
second = {1, 5}
print(first | second) # Uniion
print(first & second) # Intersection
print(first - second) # Differece
print(first ^ second) # semantic difference. Items in either a or b but not both
# ----------------------------... |
70e59998daf19ad49399b7a29cc40444e33ae72c | sushtend/100-days-of-ml-code | /code/basic python in depth/8 useful string methods.py | 198 | 3.65625 | 4 | msg = " Bangalore is a cool city"
print(msg.upper())
print(msg.lower())
print(msg.title())
print(msg.strip())
print(msg.find("cool"))
print(msg.replace("cool", "hot"))
print("Bangalore" in msg)
|
3c92b9ece8799c32c3d8128830b9e7bf7e59ff2e | sushtend/100-days-of-ml-code | /code/Python Modules/04 date time.py | 1,368 | 3.5625 | 4 | # https://www.youtube.com/watch?v=eirjjyP2qcQ&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=24
import datetime
import pytz
d = datetime.date(2019, 9, 23) # only date and not time
tdy = datetime.date.today()
print(d)
print(tdy)
print(tdy.year)
print(tdy.weekday()) # Monday = 0 Sunday = 6
print(tdy.isoweekday()) # ... |
dd8bef1f7eefa14ceb02fafa677de8ba03fe8946 | sushtend/100-days-of-ml-code | /code/Advanced Python 1/10 iter tools.py | 597 | 3.5 | 4 | # https://www.youtube.com/watch?v=Qu3dThVy6KQ
import itertools
counter = itertools.count()
# data = [100, 200, 300, 400]
# daily_data = list(zip(counter, data))
# print(daily_data)
counter = itertools.count(start=5, step=-5)
print(next(counter))
print(next(counter))
print(next(counter))
print(next(counter))
# Zi... |
25458689b8b5c4aa66d4c6ac1ac46e86a59c10f0 | zxpgo/sort-algorithm | /radix_sort.py | 751 | 3.71875 | 4 | import math
def radix_sort(arr):
radix = 10 #基数
k = int(math.ceil(math.log(max(arr),radix)))#k可以表示任意整数
#math.log对arr中最大的数取对数,log(max(arr),10),并对其取整得到最大值的位数
bucket =[[] for i in range(radix)]
for i in range(1, k+1):
for value in arr:
bucket[int(value%(radix*... |
04bbf05486c89b09eb6980fe2c148a03bc6dadab | ash-19/Foundations-of-Data-Science | /Linear Regression/multiVarLinearRegression.py | 2,893 | 3.53125 | 4 | import numpy as np
import scipy as sp
import math
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
from numpy import linalg as LA
from numpy import genfromtxt
# import the data from the .csv file to a 100x4 array. Randomize its order
data = genfromtxt('HW03/D3.csv', delimiter=',')
... |
610f66fa72a58f3c3ae926645d0f71de61f5a0a7 | henrique93/GoogleHashcode | /auxiliarBetter E worse B.py | 3,794 | 3.53125 | 4 | def fileReader(f):
rides = []
j = 0
with open(f, 'r') as file:
line = file.readline()
rows, columns, vehicleNum, rideNum, bonus, steps = [int(val) for val in line.split()]
for line in file:
line = line.split()
#ride [ride number, start coordinates, finish coor... |
635a67a18e9542866a68fc362ecc2941069da6e1 | jinm808/Python_Crash_Course | /chapter_4_working_w_lists/pracs.py | 1,661 | 4.5625 | 5 | '''
4-1: Pizzas
Think of at least three kinds of your favorite pizza.
Store these pizza names in a list, and then use a for loop to print the name of each pizza.
Modify your for loop to print a sentence using the name of the pizza instead of printing just the name of the pizza.
For each pizza you should have one lin... |
cab02298ed5b609d152d734f11416bf9442792f8 | jinm808/Python_Crash_Course | /chapter_8_functions/user_album.py | 712 | 4.21875 | 4 | def make_album(artist_name, album_title, tracks = 0):
"""Build a dictionary describing a music album."""
album_dict = {
'artist' : artist_name.title(),
'album' : album_title.title()
}
if tracks:
album_dict['tracks'] = tracks
return album_dict
print("Enter 'q' at any time to stop.")
while True:... |
55f364668b5929fcc741ec3051fabd0b6e95a0b2 | Toad2186/cs164 | /tests/correct/class_def_complex.py | 491 | 3.984375 | 4 | # Class definition with an instance variable which is a statement
# Also use the keyword 'self' to refer to the object itself.
class A:
x=1+2
def hello(self):
if self.x < 10:
return self.x
x = A()
y = x.hello()
# Class definition with multiple methods
class Car:
def on(self):
r... |
30218e6b84130e7a9de10633a2c5dabad5fc1ad6 | Toad2186/cs164 | /tests/correct/keyword_notin.py | 317 | 4.0625 | 4 | # A bit repetitive. I am basiscally just testing the mixing of keywords not and in
# Remember 'in' has to be on some type which is iterable
a = [1,2,3,4,5]
# Simple one-liner
3 not in a
# Print statement
print 3 not in a
# if statement
if 3 not in a:
print 'what'
# Loop
while 3 not in a:
print 'hello'
|
bd0ab02331b8e5f8052ad64220f667202fe8db42 | Toad2186/cs164 | /tests/correct/typing_def.py | 236 | 3.546875 | 4 | # Typing simple definition
def incr(n::int):
return n + 1
def exclamation (x::str):
return x + '!'
# Typing where we specify the return type as int
def decr(n::int)::int:
return n - 1
incr(3)
exclamation('hello')
decr(3)
|
97b6d78b11aac64c8168003a5569cd1237fe2ab2 | Toad2186/cs164 | /tests/correct/closure.py | 210 | 3.53125 | 4 | # Simple closure
def a():
def b():
return 'hello'
return b
j = a()
k = j()
# More complicated closure
def plus_2(num):
def y():
return num + 2
return y
x = plus_2(3)
y = x()
|
3dea073666ef50d050193ec9edeb013c26e6d5bd | Toad2186/cs164 | /tests/correct/class_mult_assign.py | 239 | 3.5 | 4 | # Testing a class where the attributes use multiple assignment
class a:
a = 10
(b,c,d) = (15,12,9)
def hello(self, x, y):
a = 5
print a
# This should wipe out the class definition interestingly enough.
a = 15
|
8db45f9ded6b4a03b6ecb5f37bdb65bc7df7f60c | Toad2186/cs164 | /tests/autograder/test-if.py | 229 | 3.71875 | 4 | x = 8
y = 13
z = 5
if x > y: print 1; print 2
if x < y: print 9; print 10
if x > y: print 1; print 2
else: print 3; print 4;
if x > y:
print 5
elif x > z:
print 6
if x > y:
print 5
elif z > x:
print 6
else:
print 7
|
a1bedaeb02f985c9525789be836deca5d03a8eb8 | JingGY/Introduction_to_Software_Fundamentals | /LAB assessment/lab17 Binary Trees.py | 5,170 | 4.15625 | 4 | #Q3
class BinaryTree:
def __init__(self, data, left=None, right=None):
self.__data = data
self.__left = left
self.__right = right
def insert_left(self, new_data):
if self.__left == None:
self.__left = BinaryTree(new_data)
else:
tree = B... |
aea20636bfc41dc581b2a20c93689ec36fe86f5a | JingGY/Introduction_to_Software_Fundamentals | /LAB assessment/lab20 Priority Queues.py | 2,060 | 3.859375 | 4 | #4
class PriorityQueue():
def __init__(self):
self.__binary_heap = [0]
self.__size = 0
def __str__(self):
return str(self.__binary_heap) # MUST CONVERT TO STRING
def __len__(self):
return len(self.__binary_heap) - 1
def add_all(self, a_list):
for ... |
29d07a6fa13e8e60435c559bc5bbd05497702cb3 | JingGY/Introduction_to_Software_Fundamentals | /LAB assessment/lab7 Test Revision.py | 10,763 | 4.03125 | 4 | #1
def insertion_sort_by_id(data):
for index in range(1, len(data)):
item_to_insert = data[index]
i = index - 1
while i >= 0 and data[i] > item_to_insert:
data[i + 1] = data[i]
i -= 1
data[i + 1] = item_to_insert
return data
def insertion_sort(... |
40e97634cc38b8f4a55acdb4b0bf5ce630ce0b35 | techtrainer4/2021_04_21 | /main.py | 569 | 3.546875 | 4 | friends = ['Chelsea Moreno',
'Jessica Ritter',
'Jessica Wilson',
'Christina Tucker',
'Stanley Jackson',
'Christine Stout',
'Lori Roberts',
'Monique Johnson',
'Penny Kline',
'Jennifer Johnson',
'Bill Adams',
'Brenda Rosario',
'Kimberly Ray',
'Thomas West',
'Joy Shaw',
'Robert Briggs',
'Angela Morrison',
... |
a4c0b18001e28ed1093f3d856f8995aa4ff0c7dc | wandingz/daily-coding-problem | /daily_coding_problem04.py | 911 | 3.78125 | 4 | '''
Daily Coding Problem: Problem #4
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well... |
2fc1a9a57b5e8713e1fd8b231289656d1838e32c | wandingz/daily-coding-problem | /daily_coding_problem61.py | 1,695 | 4.28125 | 4 | '''
This problem was asked by Google.
Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.
Do this faster than the naive method of repeated multiplication.
For example, pow(2, 10) should return 1024.
'''
class Solution:
def powNaive(self, a, b)... |
4dfaf7a83d6a83816a002aa8f14e7ccbaef6e4cc | jrupp68/python-IM | /workingServer.py | 13,388 | 3.640625 | 4 | #Server registration
# After login, GUI should show friends list with current online status and
# if there are any new/undelivered messages
# To send a message to a friend (either offline or online) you click on the
# button for that specific friend. Clicking that button opens a chat (not sure
# if this should be in ... |
5503d10bbcf8a15a7e6e4d4e1becb769f87839d1 | glemvik/Knowit_julekalender2017 | /Luke11.py | 2,087 | 4.375 | 4 | # -*- coding: utf-8 -*-
from time import time
from math import sqrt
def mirptall(primes):
"""
Returns all positive 'mirptall' smaller than 'number', where 'mirptall' are
primes which are also primes when the digits are reversed without being
palindromes.
"""
# INITIALIZE
... |
043eff2d6aeea3d36e6eb13f9b3f978f2f2f6cde | glemvik/Knowit_julekalender2017 | /Luke5.py | 1,283 | 3.859375 | 4 | from time import time
def sum_of_series(limit):
"""
Returns the sum of the first 'limit' numbers in the series where:
* Every entry is at least as big as the previous (a_(i+1) >= a_i)
* The value in the a_i describes the number of occurrences of number i
* The series start at a_i = 1
"""
# Prepare val... |
585392031b1e6d8a6ee33b6403f3cfbfc1b654c1 | AChelikani/Computational-Humor | /src/trainer/trainer_funny.py | 769 | 3.703125 | 4 | import re
import words
def populateFunny(comments, syns):
'''
Populates funny words by cleaning the comments and removing tags.
Arguments:
comments -- nested list of comments
syns -- image tags and their synonyms
Return value:
Set of funny words (comments - tags)
... |
fd3f9a274c8d3adf02671614de353ddce950df7d | ch4n3-yoon/ctf_tools | /xortool/app.py | 1,060 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
import sys
import string
def isPrintable(data):
for d in data:
if not d in string.printable:
return 0;
return 1;
def xor(data, key, printable = True):
# data: str type
# key: int type
result = ''
for d in data:
result += chr(or... |
f8497daae641c7faac7b28ce36fe50031a3c1812 | avbpk1/PYTHON_31_MAY_2021 | /demo/basics/factorial.py | 209 | 3.96875 | 4 | import sys
if len(sys.argv) < 2:
print("Usage : python factorial.py number")
exit(0)
num = int(sys.argv[1])
fact = 1
for i in range(2, num + 1):
fact *= i
print(f"Factorial of {num} is {fact}")
|
ba91af1f85ba406dd6694323b5ed1570ca10fbcf | gitdreams/data_structure | /sort/selection_sort.py | 1,112 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/6/5 8:38
# @Author : li
# @File : selection_sort.py
import random
# 迭代选择排序
def selection_sort(array):
for j in range(0, len(array)):
small_value_index = j
for i in range(j, len(array)):
if array[i] < array[small_value_index]:
... |
eac2ad217899883d06da84eb3efbd0aa424e34bb | romkravets/python-data | /41/list_and_if/list_numbers.py | 1,600 | 3.671875 | 4 | #Напишіть програму Python, щоб роздрукувати всі парні числа із заданого списку чисел у тому самому порядку та зупинити друк,
#якщо в послідовності є числа, що приходять після 237.
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412,... |
5f1c55c7802f40bc62174720857200329b6884eb | Wjonke/Sprint-Challenge--Hash | /hashtables/ex2/ex2.py | 3,343 | 3.65625 | 4 | # Hint: You may not need all of these. Remove the unused functions.
class Ticket:
def __init__(self, source, destination):
self.source = source
self.destination = destination
def reconstruct_trip(tickets, length):
"""
YOUR CODE HERE
"""
cache = {}
route = []
for i in ti... |
731559b90aaf8bf0fc4544a75a8b2befa3fbfb68 | dehghanr/Data_analytics_Final_project | /project_predictive/deepLearning_model.py | 6,260 | 3.671875 | 4 | import pandas as pd
''' Load iris.name file (make a data frame) '''
df = pd.read_csv('iris.data', header=None) # ( What happens if you don't set header? )
# print(df.tail())
# print(df.head()) # Shows only 5 first rows
''' Set column names '''
df.columns = ['Sepal_Length', 'Sepal_Width', 'Petal_Length',... |
db545519dc14cf85b7b0a0b7c146974958756205 | pipa0979/barbell-squats | /Singly Linked List/Insertion/LL-Insertion-end.py | 1,746 | 4.28125 | 4 | # Purpose - to add node to the end of the list.
class Node(object):
def __init__(self, val):
self.data = val
self.next = None
class LinkedList(object):
# Head, Tail in a new LL will point to None
def __init__(self):
self.head = None
self.tail = None
... |
e9f2d195fd295c879d9b9ecac7c6d44a8b26c75b | pipa0979/barbell-squats | /Singly Linked List/Misc/SLL_plays.py | 3,446 | 4.0625 | 4 | # Program to play around.
import random
class Node(object):
def __init__(self, val):
self.data = val
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def isEmpty(self):
if self.head == None:
return True
... |
89a8b976b36d6690ee320128f0f4360a0731260a | Terry-Xiang/XZY | /exchange rate.py | 957 | 3.546875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
编者:XZY
日期:2020.2.15
功能:实现美元与人民币汇率转换
"""
#提示用户输入基本信息
print('美元货币单位是USD,人民币的货币单位是CNY')
print('汇率为直接标价法,CNY/USD,其含义为 1 美元 = ?人民币')
print('汇率查询参考网站:https://www.boc.cn/sourcedb/whpj/')
print('请注意大小写')
exchange_rate = input('请输入今日汇率:') #汇率标价为 CNY/USD
currency = in... |
ed82a4d1376c0a38b951b24f7b067bf9f4b73640 | danicon/MD3-Curso_Python | /Aula16/ex02.py | 191 | 3.703125 | 4 | lanche = ('Hambúrgue', 'Suco', 'Pizza', 'Pudim', 'Batata Frita')
for cont in range(0, len(lanche)):
print(f'Eu vou comer {lanche[cont]} na posição {cont}')
print('Comi pra caramba!') |
0e17237019b0e9b9d2fffd20065aa55684d66ec5 | danicon/MD3-Curso_Python | /Aula19/ex08.py | 1,202 | 3.78125 | 4 | from datetime import datetime
dados = dict()
dados['nome'] = str(input('Nome: '))
nasc = int(input('Ano de Nascimento: '))
dados['idade'] = datetime.now().year - nasc
dados['ctps'] = int(input('Carteira de Trabalho (0 não tem): '))
if dados['ctps'] != 0:
dados['contratação'] = int(input('Ano de Contratação: '))
... |
347bca1ef9a9014c8672fe9ee46cd1bb9708b5c3 | Kobemeka/Wisharedom-YouTube-Python-Dersleri | /ornek3.py | 386 | 3.953125 | 4 | # Bir matrisin tersçaprazını veren bir fonksiyon yazınız.
m = [
[1,2],
[3,4],
[11,-3]
]
def transpose(matris):
y = []
for sutun in range(len(matris[0])):
s = []
for satir in range(len(matris)):
deger = matris[satir][sutun]
s.append(deger)
... |
208e12c2e86f140d231b0a946d21c9c4a24128c6 | Kobemeka/Wisharedom-YouTube-Python-Dersleri | /integers.py | 488 | 3.671875 | 4 | """ Print - Yazdırma"""
print("Merhaba Wisharedom!")
""" Integer | Float - Tam Sayılar | Ondalıklı Sayılar """
print(10)
print(2.5)
integer1 = 11
float1 = 2.0
""" Aritmetik İşlemler """
# Toplama
print(integer1 + float1)
# Çıkartma
print(integer1 - float1)
# Çarpma
print(integer1 * fl... |
321d60bab24fe9723ef5c49f55fc4b3b062b3182 | shavkat1717/dastur.uz_1000_ta_masala_01 | /20_masala.py | 523 | 3.71875 | 4 | x1=float(input("Tekislikdagi nuqtaning birinchi X uchi koordinatalarini kiriting x1 = "))
y1=float(input("Tekislikdagi nuqtaning birinchi Y uchi koordinatalarini kiriting y1 = "))
x2=float(input("Tekislikdagi nuqtaning ikkinchi X uchi koordinatalarini kiriting x2 = "))
y2=float(input("Tekislikdagi nuqtaning ikkinchi... |
0b6584683a8b9e20b513c85929b84ade35ced981 | shavkat1717/dastur.uz_1000_ta_masala_01 | /28_masala.py | 130 | 3.65625 | 4 | A=int(input(" qiymat kiriting A = "))
a=A**2
b=A**3
c=A**5
d=A**10
e=A**15
print(a)
print(b)
print(c)
print(d)
print(e) |
dcc964723517ea8e13fd766280d270facfd0b470 | shavkat1717/dastur.uz_1000_ta_masala_01 | /21_masala.py | 744 | 3.5625 | 4 | x1=float(input("Uchburchakning birinchi X uchi koordinatalarini kiriting x1 = "))
y1=float(input("Uchburchakning birinchi Y uchi koordinatalarini kiriting y1 = "))
x2=float(input("Uchburchakning ikkinchi X uchi koordinatalarini kiriting x2 = "))
y2=float(input("Uchburchakning ikkinchi Y uchi koordinatalarini kiritin... |
8d90eb725e1b93cafb1f814f531052d52f7db673 | emcguirk/atbs | /Chapter 7/strongPass.py | 573 | 4.1875 | 4 | import re
import pyperclip
# Regexes for each requirement:
hasLower = re.compile(r'[a-z]')
hasUpper = re.compile(r'[A-Z]')
hasNumber = re.compile(r'[0-9]')
def isStrong(pwd):
assert type(pwd) == str
lower = hasLower.findall(pwd)
upper = hasUpper.findall(pwd)
number = hasNumber.findall(pwd)
if len(lower) < 1 or l... |
59fd79652d6875796d832b8114ace76449e40883 | laudisa93/empresa_epd09 | /src/empleado.py | 2,612 | 3.9375 | 4 | __author__ = 'Laura'
class Empleado():
"""Esta clase representa el empleado de un departamento"""
def __init__(self, nombre, apellidos, dni, direccion, edad, email, salario):
"""Metodo constructor de empleado
En este metodo se define un objeto de tipo Empleado con sus atributos
:par... |
5588d7196d61e643bdf5ae9d9979adde3bf9208f | tonylizj/CCC_and_contests | /christmas contest/1.py | 333 | 3.78125 | 4 | import math
base = input().split(' ')
for i in range(3):
base[i] = int(base[i])
counter = 0
for j in range(3):
star = input().split(' ')
if math.sqrt((int(star[0]) - int(base[1])) ** 2 + (int(star[1]) - int(base[2])) ** 2 ) < int(base[0]):
counter += 1
if counter == 3:
print("YES")
else:
... |
92a40b1e80f6dc4803dbb4c5239da6678cada046 | tonylizj/CCC_and_contests | /VM7WC13#3Silver-CanShahirEvenGetThere.py | 737 | 3.84375 | 4 | from sys import stdin
input = stdin.readline
visited = []
def bfs(g, start):
seen, queue = [start], [start]
while queue:
current = queue.pop(0)
for adjacent in g[current]:
if adjacent not in seen:
seen.append(adjacent)
queue.append(adjacent)
... |
c0a3fe1df634954ac95cd0d4a1f65237c426a738 | tonylizj/CCC_and_contests | /CCC00J1-Calendar.py | 329 | 3.78125 | 4 | starting = input()
total = int(starting[2:])
starting = int(starting[0])
print("Sun Mon Tue Wed Thr Fri Sat")
for i in range(starting-1):
print(" ", end=' ')
for i in range(total):
if (i+starting) % 7 != 0 and i+1 != total:
print("{0:>3d}".format(i+1), end=' ')
else:
print("{0:>3d}".forma... |
7abb32c404dc18b4b383f9806b4472d7650f47d4 | tonylizj/CCC_and_contests | /CCC17J2.py | 143 | 3.625 | 4 | number = int(input())
shifts = int(input())
newnumber = number
for i in range(shifts):
newnumber += number * (10**(i+1))
print(newnumber) |
1d7e9f609a9335e3d68b7b62d041640b94a4ada3 | sanidhyamangal/interviews_prep | /code_prep/short_phone_interview_problems/tower_of_hanoi.py | 1,878 | 3.9375 | 4 | # Move the blocks on tower1 to tower3.
class Tower(object):
def __init__(self, name, discs=[]):
self.name = name
self.discs = discs
def pop(self):
return self.discs.pop()
def append(self, item):
self.discs.append(item)
class Towers_of_hanoi(object):
def __init__(self... |
bdda28a5757631ec16a8a7c3543f975ccd493dc0 | sanidhyamangal/interviews_prep | /code_prep/abstract_structures/linked_list/base.py | 642 | 4.0625 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def _add(self, node):
if self.next is not None:
self.next._add(node)
else:
self.next = node
class LinkedList:
def __init__(self):
self.head = None
de... |
e6c27f8ac97eab7c41558dff6e6d9534c704b5dd | sanidhyamangal/interviews_prep | /code_prep/short_phone_interview_problems/coins.py | 742 | 3.78125 | 4 | # Count the number of ways to make change for a given number of cents.
__author__ = 'tchaton'
import unittest
def coins(n):
count = 0
for c in range(n, -1, -25):
count+=coins_pnd(c)
return count
def coins_pnd(c):
count = 0
for c in range(c, -1, -10):
count += (c//5)+1
return co... |
57f07910f82344891c534ef61bf259988aa1985b | sanidhyamangal/interviews_prep | /code_prep/abstract_structures/linked_list/double_linked_list.py | 2,018 | 4.03125 | 4 | __author__ = "tchaton"
''' Implement a double-linked list, which is very simple, we just need inherits
from a Linked List Class and add an attribute for previous.'''
from .base import LinkedList
def test():
dll = DoubleLinkedList()
for i in range(10):
dll.add(i)
assert dll.head.next.next.previou... |
423e4d38748098b078fe7905d9304a82452476bc | sanidhyamangal/interviews_prep | /code_prep/abstract_structures/arrays/josephus_problem.py | 631 | 3.75 | 4 | """
There are people sitting in a circular fashion,
print every third member while removing them,
the next counter starts immediately after the member is removed.
Print till all the members are exhausted.
For example:
Input: consider 123456789 members sitting in a circular fashion,
Output: 369485271
"""
def test():
... |
6863c8d43d81dbc8de4e474ff65bcbeeb9aa0c07 | sanidhyamangal/interviews_prep | /code_prep/short_phone_interview_problems/tree.py | 4,469 | 4.09375 | 4 | '''
Binary Search Tree Algorithm
'''
def test():
l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4]
tree = Tree()
for i in l:
tree.add(i)
assert sorted(tree.get_tree_values()) == sorted(l)
assert tree.root.left.right.right.right.value == 9
assert tree.root.left.left.value == 3
# Searching for ... |
c2db7a8d9acb52049b315930fe07c25de3218899 | sanidhyamangal/interviews_prep | /code_prep/bit_manipulation/russian_peasant.py | 780 | 3.84375 | 4 | # Multiply two positive integers without *.
__author__ = 'tchaton'
# O(lg(min(a, b)))
def multiply(a, b):
'''
Russian peasant multiplication
Reference : https://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication#Russian_peasant_multiplication
'''
if b > a: a, b = b, a
res = 0 # initialize... |
9a02a67551a4b078a3e7cba38ff4d5237b3ed100 | AnandVetcha/IntelEdison_Python | /DigitalWrite.py | 434 | 3.5625 | 4 | import time
import mraa
###### Programe Begins ####
print (mraa.getVersion()) #Print mraa version for reference
# Initiate Digital Pin 4 with direction out
Led = mraa.Gpio(4)
Led.dir(mraa.DIR_OUT)
value = 0
while 1:
if value == 0:
value = 1
else:
value = 0
... |
578fd979afe99cf6332d18ebb602664a5a7291fa | pokan975/Py-for-Rapid_Engineering | /hw4.py | 5,811 | 3.90625 | 4 | #!/usr/bin/env python
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
# =============================================================================
# Function:
# Calculate the wealth at the end of every year according to user's input
# wealth of year N is the cumulative number at the end of ... |
4b535d1a65282008c850bf6f95a0c8b0f6d02476 | pokan975/Py-for-Rapid_Engineering | /hw1_13.py | 2,681 | 3.75 | 4 | #!/usr/bin/env python
# =============================================================================
# Function:
# Calculate the factorial of input n:
# n! = 1, if n = 1
# n! = n * (n-1)!, if n > 1
# =============================================================================
def factorial(num):
# ... |
2bfb4e79c693aa43eeab76369354448e4d6fb2f0 | lavawong/python-learn | /mergeSort.py | 933 | 4.0625 | 4 | #!/usr/bin/python2.7
"""
This is divide-conquar algorithm
Merge Sort
"""
def merge(left, right):
i = 0
j = 0
ret = []
while i<len(left) and j<len(right):
if left[i] > right[j]:
ret.append(left[i])
i += 1
else:
ret.append(right[j])
j += 1
... |
873ef1dfb04dc67b9f327a0cd2bc45ec0d935183 | HonkeeChan/curl_video_address | /test/thread_test.py | 1,171 | 3.671875 | 4 | #coding=utf-8
import threading
from time import ctime,sleep
def music(func,func1):
print func
print func1
for i in range(2):
print "I was listening to %s. %s" %(func, i)
sleep(1)
def move(func):
for i in range(3):
print "I was at the %s! %s" %(func, i)
sleep(5)
def ne... |
15fb72f2665468248b1173fa6794f83488fa9e0e | AP-MI-2021/lab-2-konyaanna | /main.py | 3,158 | 4.21875 | 4 | def is_prime(x):
'''
determina daca un numar este prim sau nu
:param x: numar intreg
:return: True, daca x este prim sau False in caz contrar
'''
if (x < 2):
return False
for i in range(2, x // 2 + 1):
if x % i == 0:
return False
return True
de... |
137a5ed866041b1c4a444847949b7f47fbc345d7 | Cazeck/PracticeProjects | /2. Volcano & Population Web Map/2a. Geocoding/GeocodingTest.py | 808 | 3.59375 | 4 | import pandas
import geopy
from geopy.geocoders import ArcGIS
nom = ArcGIS()
df = pandas.read_csv("supermarkets/supermarkets.csv")
# Turns n into a location object for the specified address
n = nom.geocode("3995 23rd St, San Francisco, CA 94114")
# Combines info into a new Address Column
df["Address"]=df["Address"]... |
db8740d46e83185a4c694cc88ba16b73a525ad66 | Cazeck/PracticeProjects | /2. Volcano & Population Web Map/2b. Numerical and Scientific Computing/ImageConversion.py | 678 | 3.625 | 4 | import numpy
import cv2
# Read image file 0 is grayscale, 1 is rgb (color)
im_g = cv2.imread("smallgray.png", 0)
#print(im_g)
# Create image from info from numpy array
cv2.imwrite("newsmallgray.png", im_g)
# Slice data (normal array methods/indexing)
#print(im_g[0:2, 2:4])
# For iterating by columns use .T (transp... |
e7f7aaaa4bd69eaee42e49d18f175b27b70d75f6 | Momayaz/data-structures-and-algorithms-401 | /data_structures_and_algorithms_401/ll_zip/ll_zip.py | 695 | 4.03125 | 4 | # from data_structures_and_algorithms_401.linkedList1.linked_list import LinkedList
# def zip_lists(list1, list2):
# if not list1 :
# return list1
# if not list2 :
# return list1
# output =LinkedList()
# current1 =list1.head
# current2 =list2.head
# while current1 :
# ou... |
e9f808d18e4714d94e96beec8ee330d6c3a5b7f8 | jurebb/advent_of_code_2020 | /day12/task1.py | 1,725 | 3.765625 | 4 | from enum import Enum
import sys
class Heading(Enum):
north = 0
east = 90
south = 180
west = 270
class ShipStatus:
def __init__(self):
self.pos_x = 0
self.pos_y = 0
self.heading = Heading.east
def move_heading(self, heading, value):
if heading == Heading.nort... |
5f47bd243cd454c49ed7721be05b90ae114ca167 | jurebb/advent_of_code_2020 | /day10/task1.py | 797 | 3.609375 | 4 | import sys
def find_diffs(adapters):
one_jolt_diffs = 0
three_jolt_diffs = 0
for i in range(len(adapters) - 1):
diff = adapters[i + 1] - adapters[i]
if diff == 1:
one_jolt_diffs += 1
elif diff == 3:
three_jolt_diffs += 1
return one_jolt_diffs, three_j... |
73e55e7675654282dd58cec2381c159798feb433 | Wolfstroid/tasks | /week 0/quick sort.py | 897 | 3.84375 | 4 | import random
def quick_sort(arr):
if len(arr) <= 2:
return arr
else:
i,j = 1,len(arr)-1
while i != j:
if arr[j] < arr[0]:
arr[j],arr[0] = arr[0],arr[j]
break
j = j - 1
while i != j:
while i != ... |
3a84498749c9a069e18cef3fbe94d53e1b708563 | ArhamChouradiya/Payroll-Management-System | /search.py | 1,886 | 3.9375 | 4 | from os import remove, rename
# Searching in Employee File using following fields: Employee Number and Employee Name
# Searching using Employee Number
def search1():
fout = open('EMPLOYEE_FILE.txt', 'r')
no = int(input('Employee Number? '))
found = 0
for line in fout:
line = line.strip()
... |
159c7cf258c708281d9f1cc17d48e9f871f0ece8 | jakubwosko/Algorithms | /number_of_bits.py | 792 | 4.1875 | 4 | ##########################################################
# Several ways to count bits in Python 3.6
# JW 2018
##########################################################
# classic bit shift
def number_of_bits1(n):
x = 0
while n > 0:
x += n & 1
n >>= 1
return x
# bin.count method
def numbe... |
7073cb578f0feb99d84b875f3b076d8c3b9b0bb3 | sarathp12/excel-test | /basic-excel.py | 1,225 | 3.59375 | 4 | #! /usr/bin/python
import xlrd
import pandas as pd
workbook = xlrd.open_workbook("test-py.xlsx")
worksheet = workbook.sheet_by_index(0)
df = pd.read_excel('test-py.xlsx')
#print(df.sheet_names)
df1 = df[df.columns[5:7]].dropna()
df1.columns = ['ip','ports']
print("Head")
#print(df1.head(10))
for index, row in df1.it... |
84127274652294d01d58c9f5c66e7e3e6007539a | AshleyBrooks213/lambdata-AshleyBrooks213 | /lambdata-AshleyBrooks213/test_module4.py | 739 | 3.53125 | 4 | import unittest
import pandas as pd
import numpy as np
from example_module import FAVORITE_ANIMALS, FAVORITE_COLORS, add, increment
class ExampleTests(unittest.TestCase):
"""Making sure examples work as expected"""
def test_add(self):
"""Testing that add function works as expected"""
num1 =... |
fba780be1dd24436cd3908a5b8a2f90bb1d60fa9 | UkuleleString/The-Kingdom-Of-Animalia | /gameFunctions/timeEvents.py | 385 | 3.875 | 4 | class timer(object):
"""Creates timer to return values based on
what period of the day it is"""
def __init__(self):
self.minutes = 15
self.hours = 0
def checktime(self):
hour = int(self.minutes / 60)
hour /= 18
return hour
def quarterPass(self):
self.mi... |
235ff7d75011bc50b555ca529df46a47cb3bac0a | khanna98/Improving-Coding-Concepts | /Python/Basic/first_last_reverse.py | 112 | 3.9375 | 4 | first = input("Enter first name: ")
last = input("Enter last name: ")
print("Hello I am " + last + " " + first) |
73517d02ea827ed387410a9c064a9941e2b6625f | Jeyaprakash-dr/python101 | /Ex_Files_Python_EssT/Exercise Files/Chap04/ternary.py | 208 | 3.875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
hungry = 1
#x = 'Feed the bear now!' if hungry else 'Do not feed the bear.'
print('Feed the bear now!' if hungry else 'Do not feed the bear.')
|
d690055103b9eda3fb396958fa6924707bca3fe4 | mattdrake/pdxcodeguild | /python/find_every_other.py | 307 | 4.09375 | 4 | __author__ = 'drake'
#get user input for number
question = input("Enter a number. ")
#variable to start counting from
num = 0
#create loop to increment every other number and avoid printing greater than user input number
while num <= question:
print(num)
#operator to increment by 2
num += 2
|
f242ca44b241f49b69bd857d106747af2bcf5e2c | mattdrake/pdxcodeguild | /python/fizz_buzz.py | 757 | 4.1875 | 4 | __author__ = 'drake'
#reques input from user for any number
question = input("Enter a number. ")
#created variable for incrementing input from user
num = -1
#create loop to count from zero to user input number
while question > num:
#incrementing by one
num += 1
#test if number is a multiple of both 3 and 4 not in... |
45a317bef2db3b77589fbcc7c12fbfe7237b0282 | AryanGanotra07/Computer-Graphics | /LabEvaluation2.py | 1,060 | 3.53125 | 4 | import time
from graphics import *
def trafficLights():
win = GraphWin()
rect = Rectangle(Point(60,20 ), Point(140,180))
rect.draw(win)
red = Circle(Point(100, 50), 20)
red.setFill("black")
red.draw(win)
yellow = Circle(Point(100, 100), 20)
yellow.setFill("black")
yellow.draw(win)
... |
902828e5232a254c77b558537d868957111943d2 | AryanGanotra07/Computer-Graphics | /Exp3-1.py | 633 | 3.5625 | 4 | import matplotlib.pyplot as plt
# Data to plot
# labels = 'Python', 'C++', 'Ruby', 'Java'
# sizes = [215, 130, 245, 210]
# colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
# explode = (0.1, 0, 0, 0) # explode 1st slice
n = int(input("Enter No. of elements: "))
labels = list(map(str, input("Enter list of... |
121e5b32264c121ed4a9c531d34886645fe41e95 | C-CCM-TC1028-111-2113/homework-1-AdrielOlvera | /assignments/19Editorial/src/exercise.py | 332 | 3.65625 | 4 | def main():
#escribe tu código abajo de esta línea
import math
words=input("Dame el número de palabras: ")
pages=math.ceil(int(words)/475)
cost=int(pages)*60
discount=(int(cost)*10)/100
total=int(cost)-float(discount)
print("El costo de la publicación es: "+str(total))
pass
if __name__ == '__main__':
... |
ea668dee6cf42ef3bf0ecf3ff721f64a7e0ebe97 | vitalkhali/Amazon_Crawler | /crawler/crawler/show.py | 587 | 3.578125 | 4 | import matplotlib.pyplot as plt
import sqlite3
conn = sqlite3.connect("books.db")
curr = conn.cursor()
review_counts = [review_count[0] for review_count in curr.execute("SELECT review_count FROM books_tb")]
prices = [price[0] for price in curr.execute("SELECT price FROM books_tb")]
for i in range(len(review_counts))... |
6b13d2af721850dc4748bd0f0b43426d47206356 | SnoWHandS/Cellular_JCAC_simulation | /JCAC.py | 8,347 | 3.5 | 4 | #The following python 3 code is used to simulate the blocking and dropping states of a 2 RAT heterogeneous network
#The states are determined for each new call and handover call arrival rate and the relevant probabilities are calculated.
#Author: Dillon Heald
#Date: 30 May 2020
import math
#This is the main function ... |
742e5d7916310d6be17299e6d47c40c901498635 | kebron88/essential_libraries_assignment | /question11.py | 941 | 4.21875 | 4 | import numpy as np
import pandas as pd
#Do not import any other libraries
"""
Suppose you have created a regression model to predict some quantity. Write a function that takes 2 numpy arrays that both have the same length, y and y_pred.
The function should return the loss between the predicted and the actual values wh... |
0f59189d825676e2b5501b0054a5548081b14df6 | ivory2006/forecasting_profession | /unintroduced programs_some middle results/plot1.py | 520 | 3.5 | 4 | import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
#import plotly.plotly as py
multiple_bars = plt.figure()
x = ['a','b','c']
x = date2num(x)
a=4
b=9
y = [a, b, 2]
z=[1,2,3]
k=[11,12,13]
ax = plt.subplot(111)
ax.bar(x-0.2, y,width=0.2,color='b',align='center')
ax.b... |
898805dffac9558bab0ad2517ff5e5f601dabf9b | kmichali/planets_mar27 | /mars.py | 310 | 3.96875 | 4 | print("Hello, I am Count Dracula!")
print("My friends and I are interested in colonising Mars.")
colour = "red"
temperature = -60
humidity = 80
moons = 2
if colour == "red":
print("Good, my favourite colour!")
else:
print("Colour is irrelevant.")
print("moons: ", moons)
print("temperature: ", temperature)
|
8094350956d49b64afda1dc1f56dbf9aebd0398a | cdek11/PLS | /Code/PLS_Algorithm.py | 6,277 | 3.71875 | 4 |
# coding: utf-8
# In[ ]:
# Code to implement the initial version of the PLS Algorithm
import pandas as pd
import numpy as np
def pls(path, path_test, predictors, response):
'''Function that takes a dataframe and runs partial least squares on numeric predictors for a numeric response.
Returns the residuals ... |
cf8732ccc36d137928e995b136b105ac0bfa7c4b | NaveeenSemwal/PythonByPyCharm | /untitled/lambda.py | 279 | 3.703125 | 4 | text = lambda x: x * 7
print(text(7))
# Use of lambda() with filter()
arr_lst = [2, 3, 4, 4, 54, 22, 36]
lambda_lst = list(filter(lambda x: (x % 2 != 0), arr_lst))
print(lambda_lst)
# Use of lambda() with map()
map_lst = list(map(lambda x: x * 2, arr_lst))
print(map_lst)
|
a9afa7e2e4d56ea2186e2399f475679b2af0011f | abhijithneilabraham/Reccomender-Systems | /labelcreation.py | 1,817 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 12:01:23 2019
@author: abhijithneilabraham
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
x=[]
def get_id(n):
print('enter all the customer ids')
for i in range (n):
x.append(i)
return x
'''
print(get_... |
6864c2589210d97e05609ff12bdb8c8a3e3d7e55 | darienjh/PPC---Book-1 | /Python Practice/practice 5.py | 227 | 4 | 4 | #Darien Hayes
#9/29/14
#Program 5
first = input("What is your first name? ")
last = input("What is your surname? ")
print(first, last, first, last, first, last)
#Yes
#Forgot commas the first time
#added commas and worked
#nothing
|
e4b666ae89a960f47255cc020e0ddc15798868f9 | aws-samples/aws-open-data-satellite-lidar-tutorial | /libs/solaris/utils/log.py | 778 | 4.0625 | 4 | import logging
def _get_logging_level(level_int):
"""Convert a logging level integer into a log level."""
if isinstance(level_int, bool):
level_int = int(level_int)
if level_int < 0:
return logging.CRITICAL + 1 # silence all possible outputs
elif level_int == 0:
return logging... |
21ffdf9a2e5f93e2f6e194e50b685df7c20afac3 | bus1029/LeetCode | /ReverseInteger.py | 684 | 3.546875 | 4 | import sys
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
result = -1
str_x = str(x)
pos_limit = 0x7fffffff
neg_limit = -0x80000000
if x < 0:
result = int("-" + str_x[::-1][:-1])
else:
... |
b15993bdf7ba30a7f3440e0b0c067c5d3f5a1153 | huanyd1/BTL-Python | /BTTL/ButtonWindown/BMI.py | 1,575 | 3.59375 | 4 | from tkinter import *
window = Tk()
window.title("BMI Caculate")
window.geometry("540x360")
def on_btn_clicked():
weight = float(txt.get())
height = float(txt2.get())
bmi = weight/(height ** 2)
lbl_bmi['text'] = str(round(bmi,2))
if bmi < 16:
lbl_bmi_result['text'] = "Severe Thinness"
el... |
45b12f398d04c8e709bc201c172a499eeae9c852 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaSequencial/Respostas/11_Questao.py | 474 | 4.21875 | 4 | # 11. Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# A. o produto do dobro do primeiro com metade do segundo .
# B. a soma do triplo do primeiro com o terceiro.
# C. o terceiro elevado ao cubo.
num = []
for i in range(3):
inpNum = int(input(f'Escreva o {i + 1}º número: '))
... |
b273a2dab85ae15b681619a7289ac9aa8c673ac6 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaSequencial/Respostas/8_Questao.py | 354 | 4 | 4 | # 8. Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
print('Calculadora de salário.')
salHora = float(input('Salário por hora: '))
horaMes = float(input('Horas trabalhadas por mês: '))
print(f'Seu salário mensal é... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.