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 |
|---|---|---|---|---|---|---|
0966afba7b408899717116feb36d960434974d7b | CODEREASYPYTHON/Calculator | /easy_calculator.py | 661 | 4.21875 | 4 | while True:
number_one = input("Enter the first number:")
query = input("Which arithmetic operation should be carried out? (+,-,/.,*):")
number_two = input("Enter the second number:")
Equal_1 = float(number_one)
Equal_2 = float(number_two)
if query == "+":
print("Your result",Equal_1+E... |
b91f74e2774e901539f90ce7315542323e36c696 | MomsFriendlyRobotCompany/mjolnir | /ex8029/software/camera-imu/tools/hertz.py | 901 | 3.71875 | 4 | import time
class Hertz:
__slots__ = ["rollover", "format", "start", "count"]
def __init__(self, format, rollover):
"""
format: string format to use when printing
rollover: when to print string
"""
self.rollover = rollover
self.format = format
self.reset... |
366919c9cc78b5fbbb4b9320d61594b36b3c2e09 | MomsFriendlyRobotCompany/mjolnir | /ex8029/software/camera-imu/old/python/filters.py | 890 | 3.515625 | 4 |
from collections import deque
from collections import namedtuple
class AverageFilter(deque):
def __init__(self, maxlen=5):
super().__init__(maxlen=maxlen)
for i in range(maxlen):
# self.__setitem__(i, 0.0)
self.append(np.zeros(3))
def avg(self):
avg = 0
... |
8fc1f9ae760502e3dff87c84369319a8264ce645 | panluo/learn | /test/python/threading/prodcons.py | 1,360 | 3.5 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from random import randint
from time import sleep,ctime
from Queue import Queue
import threading
class Mythread(threading.Thread):
def __init__(self,func,args,name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
sel... |
13ebec916c6fc5bdefc1fad2756229ecd99c034d | panluo/learn | /test/python/string/reverse.py | 2,095 | 3.71875 | 4 | '''
created on 2014-10-20
@author : luopan
'''
class MyString():
def reverse(self, some_seq):
"""
input : Sequence
output : Sequence:
reversed version
"""
return some_seq[::-1]
def count_vowels(self, string):
"""
@para... |
ec002bc040269247d5414ab19f16f4c96ee57b6d | dalton-omens/hackjam-fa-2016 | /make_preferences.py | 1,020 | 3.90625 | 4 | def make_preferences(genre_list, num_users):
def prompt():
print('\nWhat are you interested in? Here are your options: If you\'re done, type \"Done\".\n')
lst = ''
for i in range(len(genre_list) - 2):
lst = lst + genre_list[i] + ', '
lst = lst[:-2] + '\n'
r... |
53683a4d01754dbc4cfa211524ed4c3f86259b03 | cocococosti/Tarea2IngSoftware | /classPension.py | 3,088 | 3.5625 | 4 | '''
Creado el 10 oct. 2018
@author: Constanza Abarca 13-10000
@author: Pedro Maldona 13-10790
'''
import datetime
from _datetime import date
class Pension():
def calcularSemanas(self, dia, mes, anio):
# Obtener fecha hoy
hoy = datetime.date.today()
fechaTrabajo = datetime.date(anio,... |
6d668b5191a2af61832ea30fddd53dfc650f684c | pengshancai/math-lego | /lego_basic.py | 3,633 | 3.5 | 4 | # Author: Pengshan Cai
# Email: pengshancai@umass.edu
from utils import *
delta_min = 1e-17
# the derivative is a constant
def const_bender(args):
num_steps = args['num_steps']
cur_angle = args['angle']
bend_rate = args['bend_rate']
for i in range(num_steps):
yield cur_angle, bend_rate
... |
9f343926f97ffa60ce5f1ea46e48b94cb8ff78b1 | siddhartht16/IR-web-crawler-python | /utils.py | 5,532 | 4 | 4 | import os
from urlparse import urlparse
def is_string_valid(p_string):
"""
Method to validate whether the input string is a valid string or not
:param p_string: Input string which needs to be validated
:return: true if string is valid else false
"""
if p_string == '':
return False
e... |
e7a9d09ad3b6b59dba8fbc816f32d48659a1908a | emiliocarcanobringas/15.-Imprimir_texto_mas_valor_concatenandolos_python | /15.-Imprimir_texto_mas_valor_concatenandolos_python.py | 473 | 3.953125 | 4 | # Este programa muestra como concatenar una texto con un valor
print("Este programa muestra como concatenar una texto con un valor")
print("Para hacerlo cerramos comillas, separamos con una coma y colocamos la variable")
print("Antes de cerrar el paréntesis")
numero1 = 34.12
print("El valor del numero es: ", num... |
9b206c69562b967ae955947990826b5861a68255 | franwatafaka/funciones_python | /ejemplos_clase/ejemplo_5.py | 2,452 | 4.4375 | 4 | # Funciones [Python]
# Ejemplos de clase
# Autor: Inove Coding School
# Version: 2.0
# Ejemplos de parámetros ocultos en funciones conocidas
def cantidad_letras(lista_palabras):
for palabra in lista_palabras:
cantidad_letras = len(palabra)
print('Cantidad de letras de {}: {}'.format(palabra, cant... |
2e71cea6007aedd41d0d4f297853f02b4ec28e48 | Shane-kolkoto/Unit_testing | /Unit_testing.py | 414 | 3.8125 | 4 | import unittest
from main import max_number
from main import descending_sort
class TestMaxNumbers(unittest.TestCase):
def test_max_numbers(self):
assert max_number([3, 5, 6, 9, 12, 78]) == 78, "The max number in [[3, 5, 6, 9, 12, 78]"
def test_descending_order_sorter(self):
assert descending_s... |
7a0e305ffc206484470efa1ea05cb3339810dbaf | markwilliams0/MWMass | /python_expts/eapprox.py | 416 | 3.859375 | 4 | def fact(x):
if x==0:
return 1
else:
return float(x*fact(x-1))
n=int(input('Enter a positive integer: '))
if n%100==11 or n%100==12 or n%100==13:
str='th'
elif n%10==1:
str='st'
elif n%10==2:
str='nd'
elif n%10==3:
str='rd'
else:
str='th'
est=0
for i in range(n+1):
est=... |
2d2b5427fcfc7e0fa204f6f03fdbba46018869a8 | MuslumErfidan/Binary_Tree | /BFS.py | 3,957 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.parent = None # yeni
self.data = data
def insert(self, data):
if self.data: # karılaştırma yaparak ekle
if data < self.data: # küçükse ... |
cf717c597321786c758d22056fd1c90eb8d4b175 | lima-oscar/GTx-CS1301xIV-Computing-in-Python-IV-Objects-Algorithms | /Chapter 5.1_Objects/Burrito5.py | 1,764 | 4.46875 | 4 | #In this exercise, you won't edit any of your code from the
#Burrito class. Instead, you're just going to write a
#function to use instances of the Burrito class. You don't
#actually have to copy/paste your previous code here if you
#don't want to, although you'll need to if you want to write
#some test code at the bot... |
c1140b6e9f15fd3f62915a7434688354cb0fbb91 | kpwhri/pyscriven | /src/pyscriven/utils.py | 373 | 3.6875 | 4 | import random
import string
def make_safe_title(s):
from string import ascii_lowercase
return ''.join(x if x in ascii_lowercase + '_-0123456789' else
'-' if x == ' ' else '' for x in s.lower())
def generate_random_string(size=8, charset=string.ascii_uppercase + string.digits):
return ... |
0cb569bae9d8335f3ca86f036d2cafd3ba7c6ebf | rsd16/Solo-Pong | /Solo Pong.py | 2,123 | 3.578125 | 4 | import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('pong')
rect_x = 400
rect_y = 580
rect_change_x = 0
rect_change_y = 0
ball_x = 50... |
f954e13fd82932e87e2e482007e828b3effaaf68 | douglasmg7/data_science | /matplotlib/exercise_2.py | 244 | 3.609375 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 100)
y = x*2
z = x**2
plt.subplot(1, 2, 1)
plt.plot(x, y, 'b', lw=4)
plt.subplot(1, 2, 2,)
plt.plot(x, z, 'r', lw=3, ls='--')
plt.show()
plt.show()
|
5ab600b4f8b67082d934ec0e244fb6f7570be53d | douglasmg7/data_science | /matplotlib/matplotlib_limits.py | 384 | 3.5625 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
# Plot x, y using function
x = np.linspace(0, 5, 11)
y = x ** 2
# Classes mode instead function mode
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, .8, .8]) # 0 - 1 (0 to 100% of window) x, y, width, height
ax.plot(x, y, color='purple', lw... |
fcda1b2cdb587bd28dfe91766a2a9d2662a74bbe | annp89/Weekly-Noodler | /folding_subsequence.py | 1,407 | 3.5625 | 4 | input_sequence = [1, 2, 2, 5, 3, 4]
output_sequence = []
sequence_length = len(input_sequence) - 1
check = False
for count, item in enumerate(input_sequence):
if count == 0:
output_sequence.append(item)
elif not check:
if input_sequence[count] < output_sequence[-1]:
if count != seq... |
449dfbec39900b6e6118ef3fe5cdf7c19f8e8031 | panhboth111/AI-CODES | /matplotlib/02.py | 286 | 4.09375 | 4 | #Question: Write a Python program to draw a line using given axis values with suitable label in the x axis , y axis and a title.
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,1]
plt.plot(x, y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Sample graph!')
plt.show()
|
09c67cc5a452e5af7021221d589c49e17f37d7b6 | panhboth111/AI-CODES | /pandas/4.py | 394 | 4.34375 | 4 | #Question: Write a Pandas program to compare the elements of the two Pandas Series.
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
prin... |
2bf7cbe5bcecf17ebaf46be2f5420ebbde0163b0 | panhboth111/AI-CODES | /pandas/16.py | 530 | 4.28125 | 4 | """Question: Write a Pandas program to get the items of a given series not present in another given series.
Sample Output:
Original Series:
sr1:
0 1
1 2
2 3
3 4
4 5
dtype: int64
sr2:
0 2
1 4
2 6
3 8
4 10
dtype: int64
Items of sr1 not present in sr2:
0 1
2 3
4 5
dtype: int64 """
import pandas as pd
sr1 = pd.Series([1,... |
290a5ce82e4fbface4e8ad3c975daee5a324c15a | panhboth111/AI-CODES | /numpy/15.py | 344 | 4.03125 | 4 | <<<<<<< HEAD
#Question: Write a NumPy program to create an array of all the even integers from 30 to 70.
import numpy as np
array = np.arange(30,70,2)
print(array)
=======
#Question: Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21.
import numpy as np
m= np.arange(10,22).reshape((3, 4))
p... |
48e57fc36b12184ca0475da829b1f5f626a2afcf | Claudiu1995/CN_3 | /equal_matrix.py | 947 | 3.875 | 4 | from math import *
epsilon = pow(10, -8)
def equals(matrix_A: tuple, matrix_B: tuple) -> bool:
diagonal_of_A = matrix_A[0]
vector_of_A = matrix_A[1]
diagonal_of_B = matrix_B[0]
vector_of_B = matrix_B[1]
if abs(len(diagonal_of_A) - len(diagonal_of_B)) >= epsilon:
print("diag dim", len(dia... |
379df23246686c37bc64e45d81a402e234379029 | Mr-Perfection/python-postgresql | /practice/python/division.py | 482 | 3.75 | 4 | def divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError("Divisor cannot be 0")
return dividend/divisor
try:
# average = divide(20, 0)
average = divide(20, 1)
except ZeroDivisionError as e:
print(e)
print('error')
else:
print('success')
print(average)
finally:
... |
95de3442c81369f3de708734c3742f6ab4b8ffdf | manishjain79/regular_expression | /17_regex_sub.py | 2,243 | 3.953125 | 4 | import re
# re.sub
# re.sub finds pattern in through out the file/multiline string and substitute it with desired string.
string = '''Manish works with IBM Singapore Pte. Ltd. and Kiran works with Wipro International.'''
result = re.sub('(Manish|Kiran)', r'\1 Jain', string)
print(result)
# output is: Manish Jain works ... |
337f69b86893036694a6603630f86ea38c39c587 | manishjain79/regular_expression | /05_regex_CharacterSet_1.py | 2,365 | 3.890625 | 4 | import re
# We will move from bigger character set metacharacter to more granular one.
#
# [.] = [a-z][A-Z][0-9] & any other symbol - [*%$#):;], except \n.
# [\w] = [a-z][A-Z][0-9][_]
# [\W] = opposite of \w. Represents anything other than: [a-z][A-Z][0-9][_]
# So, we can say
# [.] & \n == [\w] & [\W]
#
#
# ... |
e133ba7d9f305a476985d6d2659aefb7b91ddb51 | MariinoS/projectEuler | /problem1.py | 571 | 4.125 | 4 | # Project Euler: Problem 1 Source Code. By MariinoS. 5th Feb 2016.
"""
# task: If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# My Solution:
"""
list = ran... |
02bc2eb8476f2dc28cf62865c08741b2087e8c94 | oliverralbertini/euler | /003/solution.py | 560 | 3.953125 | 4 | """Problem 3: Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"""
import sys
import math as m
sys.path.append('../modules')
from isprime import is_prime
from prime_factorization import prime_factorization
"""find out the largest prime f... |
e308b5863276672ef888b77fb5bfcf8760c7dc42 | enzorossetto/uri-online-judge-problems | /python/1044.py | 181 | 3.828125 | 4 | num= input().split()
num[0]= int(num[0])
num[1]= int(num[1])
num.sort()
if((num[0] > 0) and (num[1]%num[0] == 0)):
print("Sao Multiplos")
else:
print("Nao sao Multiplos") |
5f92038718ec03fd850a2e02b4a925965c453e2b | enzorossetto/uri-online-judge-problems | /python/1064.py | 303 | 3.6875 | 4 | numeros = [float(input()) for i in range(6)]
somaPositivos = 0
quantiaPositivos = 0
for i in range (6):
if(numeros[i] > 0):
somaPositivos = somaPositivos + numeros[i]
quantiaPositivos += 1
print(quantiaPositivos, "valores positivos")
print("%.1f" %(somaPositivos/quantiaPositivos)) |
e7a2979469aadfd3022bc1c34ece80e951281a14 | enzorossetto/uri-online-judge-problems | /python/1065.py | 151 | 3.671875 | 4 | numeros = [int(input()) for i in range(5)]
pares = 0
for i in range(5):
if(numeros[i] % 2 == 0):
pares += 1
print(pares, "valores pares") |
5a16637a3b4e7687b6e270ebd40821c32dbb0672 | taimurshaikh/Record | /record.py | 1,992 | 3.59375 | 4 | import datetime
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
class Record:
def __init__(self, forename, surname, dob, gender, isCSStudent):
self.__forename = forename
self.__surname = surname
self.__dob = dob
self.__gender = gender
sel... |
fc613bf47803961e25733eb9eb3a4f4fb25a82cc | datascience-bitacademy/python-basics | /03/03.object_id.py | 1,031 | 3.65625 | 4 | # id 함수 : 실제 객체의 주소를 반환
i1 = 10
i2 = 20
print(hex(id(i1)), hex(id(i2)))
i1 = 1234567890
i2 = 1234567890
print(hex(id(i1)), hex(id(i2)))
i1 = 11
i2 = 10 + 1
print(hex(id(i1)), hex(id(i2)))
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(hex(id(l1)), hex(id(l2)))
s1 = 'hello'
s2 = 'hello'
print(hex(id(s1)), hex(id(s2)))
# is (동... |
af88a413fbbf74c6d68c4b3fd75577f2dc8bfebb | datascience-bitacademy/python-basics | /04/03.while.py | 486 | 3.515625 | 4 | # 1 ~ 10 합을 구하기
s, count = 0, 1
while count < 11:
s += count
count += 1
print(s)
# break
i = 0
while i < 10:
if i > 5:
break
print(i, end=' ')
i += 1
print("\n-------------------------------")
# continue
i = 0
while i < 10:
if i <= 5:
i += 1
continue
print(i, end='... |
dcb967c309149c9c849e515a8c05e3d4c8db2bbb | datascience-bitacademy/python-basics | /02/14.unpacking.py | 433 | 3.765625 | 4 | # packing은 tuple로만 가능하다.
t = 10, 20, 30, 'python'
print(t, type(t))
# unpacking
a, b, c, d = t
print(a, b, c, d)
# 오류: 패킹되어 있는 객체가 더 많은 경우
# x, y, z = t
# 오류: 패킹되어 있는 객체가 더 적은 경우
# l, m, n, o, p = t
# unpacking 확장
t2 = (1, 2, 3, 4, 5)
a, *b = t2
print(a, b)
*a, b = t2
print(a, b)
a, b, *c = t2
print(a, b, c)
a, ... |
4ede0c5bea3a9e14b82675234a3f43f5512d4a8f | datascience-bitacademy/python-basics | /03/04.object_copy.py | 766 | 4.28125 | 4 | # 레퍼런스 복사
import copy
a = 1
b = a
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = x
print(x)
print(y)
print(x is y)
# 얕은(swallow) 복사
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = copy.copy(x)
print(x)
print(y)
print(x is y)
print(x[0] is y[0])
# 깊은(deep) 복사
a = [1, 2, 3]
b = [4, 5, 6]
x = [a, b, 100]
y = copy.... |
0a97cf80ae62f3d30f7f1cf607e965d04f9c868d | datascience-bitacademy/python-basics | /02/18.zip.py | 457 | 3.859375 | 4 | # zip() 사용 예
# 여러 순차형을 하나로 묶어준다
seq1 = ['foo', 'bar', 'baz']
seq2 = ['one', 'two', 'three', 'four']
z = zip(seq1, seq2)
print(z, type(z))
for t in z:
print(t)
# zip 객체는 한번 순회하면 내용이 비어버린다
# 제네레이터이므로 실제 내부 데이터는 담고 있지 않다
z = zip(seq1, seq2)
for index, t in enumerate(z):
print(index, t)
z = zip(seq1, seq2)
for ... |
bb673dbbd1f50eec1d07a418d6fe01920e216747 | datascience-bitacademy/python-basics | /02/19.comprehension.py | 1,481 | 3.703125 | 4 | numbers = [1, 2, 3, 4, 5, 6, 7, 8]
results = []
# 리스트 컴프리헨션
# [ 값 연산식 for 객체 in 순차형 if 조건 ]
# numbers 순차형의 모든 내부 요소를 제곱
for n in numbers:
result = n * n
results.append(result)
print(results)
results = [num*num for num in numbers]
print(results)
# 문자열 리스트에서 길이가 2이하인 문자열만 새로운 리스트에 담기
strings = ['a', 'as', '... |
6a5fe6de000f85d985129f3df785a73f97f41de3 | NenadPantelic/Hackerearth-DSA-practise-track | /Data structures/Queues/micro_and_queue.py | 636 | 3.609375 | 4 | from collections import deque
class QueueWrapper:
def __init__(self):
self._queue = deque()
self._size = 0
def enqueue(self, elem):
self._queue.append(elem)
self._size += 1
print(self._size)
def dequeue(self):
x = -1
if self._size != 0:
... |
bb0d351a166c1cfd118979578e03067c82a1ab52 | reidtc82/8puzzle | /ForHumanstoPlay.py | 3,686 | 4.03125 | 4 | import sys
if sys.version_info[0] == 3:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
else:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
# This is not really part of the assignment
# I meant to incorporate the search algorithms to let the comp... |
8faa3c41a488d834d973c24546eab34f8c8f90f0 | Ayaan-Imran/Checklist | /checklist.py | 1,408 | 4.09375 | 4 | import sqlite3
# Create database and table
connection = sqlite3.connect("lists.db")
c = connection.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS list (
task text
)
""")
connection.commit()
# Takes mode
mode = input("Do you want to make a new task (1) or finish a task (2) or view your tasks (3): ")
if mode ==... |
529908b3397f08c8a5a6b1ba864c6bf1cef22add | VedranSagodic/SmartninjaHomework | /python1/Loops/main.py | 421 | 3.78125 | 4 | #x = 5
#y = 2
#print(x + y)
#print("Hello World")
#userName = input("Your name")
#print("Hello" + userName)
#favColor = input("Your favorite color")
#print("Favorite color" + favColor)
broj_a = int(input("Unesi prvi broj:"))
broj_b = int(input("Unesi drugi broj:"))
rezultat= broj_a + broj_b
print(rezultat)
if rez... |
787a20a9bb460a92944f38bfd011fc79eb726176 | VedranSagodic/SmartninjaHomework | /python1/lists.py | 322 | 3.78125 | 4 | #liste
lista_brojeva = [1, 99, 24, 46, 5]
print(lista_brojeva[3])
print()
lista_brojeva.reverse()
print(lista_brojeva)
print()
lista_brojeva.append(100)
print(lista_brojeva)
print()
lista_brojeva.sort()
print(lista_brojeva)
print()
auti = ["tesla", "audi", "bmw"]
print(auti)
for item in auti:
print(item)
... |
327accad9ef09bbcfa6c58d16cd49572d3982c02 | rsdavies/advent-of-code | /day_3/day_3.py | 2,498 | 4.03125 | 4 | from typing import List
from utils.read_input import read_wires
def get_positions(wire):
"""
Gives the x, y position of a wire after each instruction
:param wire: the wire instructions
:return: x, y. Assuming wire starts at 0, 0
"""
x = 0
y = 0
positions = [(0, 0)]
for instruction... |
299ddbbc61487dd6c38e0a1c4cba8061fc683695 | rsdavies/advent-of-code | /day_2/day_2.py | 2,149 | 3.984375 | 4 | class Computer:
def __init__(self, program):
self.program = program
self._instruction_pointer = 0
def add(self):
parameter_1 = self.program[self._instruction_pointer + 1]
parameter_2 = self.program[self._instruction_pointer + 2]
parameter_3 = self.program[self._instructi... |
9816db2f8a4bc992ca21113834898bcd879136a8 | Irlyue/DL-AI | /Concepts/receptive-field/calc_receptive_field.py | 2,731 | 3.765625 | 4 | """
Please refer to blog
https://medium.com/mlreview/a-guide-to-receptive-field-arithmetic-for-convolutional-neural-networks-e0f514068807
for detailed information.
"""
import math
from collections import namedtuple
class Kernel(namedtuple('Kernel', 'k s p name')):
def __repr__(self):
return '{}(kernel si... |
2bc939ea849abf9eae5df3bcb2c582774fe368dd | suazz/TEXT-ADVENTURE | /first_Text_Adventure.py | 7,426 | 3.875 | 4 | from sys import exit
print("""
===========Text Adventure ============
| |
| .---------. |
| |.-------.| |
| ||>run# || |
| || || |
| |"-------'| ... |
23e559cc1bd3a9f8000581702e68755464369780 | gyuree-kim/algorithm | /dfs_and_bfs/dfs/dfs_template.py | 612 | 3.59375 | 4 | graph = []
graph.append(list(map(int, input())))
# 1차원 그래프
def dfs(graph, v, visited):
visited[v] = True
print(v, end=' ')
for i in graph[v]:
if not visited[i]:
dfs(graph, i, visited)
# 2차원 그래프
def dfs(x,y):
# out of the map size
if x < 0 or y < 0 or x >= n or y >= n:
... |
72d0213b6cb5186226e0c748ac86dd4e124a200d | sonjoonho/InterviewPrep | /algorithms_ii.py | 12,496 | 3.78125 | 4 | import pytest
from typing import List
from queue import Queue
"""
Contains Python implementations of most algorithms encountered in the 2nd year
Algorithms II course at Imperial College London.
"""
"""
DYNAMIC PROGRAMMING
"""
"""
Quicksort
"""
def super_speedy_sort(arr, p, r):
# p is the beginning of the array, ... |
1890b26e7af1a71f45fc5cd6e56759d295b34c8d | sonjoonho/InterviewPrep | /stacksandqueues.py | 2,445 | 4.0625 | 4 | class Stack:
def __init__(self, stack=[]):
self.stack = stack
def pop(self):
# Get last element
#val = self.stack[-1]
# Remove last element
#self.stack = stack[:-1]
# Python lists have a pop method, but that's probably not what you're looking for
return ... |
38f472d2526c729eebc6e8cf927421db57a66c3f | onkarbk/OOPS | /Assignments/Trello/Python/Card.py | 2,709 | 3.640625 | 4 | import json
class Card:
def __init__(self, id, name):
"""
Creates a `Card` instance
Parameters:
id(str): Card ID
name(str): Card name
"""
self.id = id
self.name = name
self.description =""
self.assignedTo = ""
... |
4ee0bc9c49c58f4d225c2d5a4eedc3c2e124ead3 | linkenghong/Backtesting | /Backtesting/portfolio_handler/position.py | 2,431 | 3.65625 | 4 | import csv
class Position(object):
def __init__(
self, action, symbol, init_quantity,
init_price, init_commission,
cur_price
):
"""
Set up the initial "account" of the Position.
Then calculate the initial values and finally update the
market value of the... |
38597fbfee7395d38bb8f1a97b8184ec8ceff5ab | mboker/Cardinal_Katas | /kata_two.py | 1,572 | 3.578125 | 4 | import pandas as pd
import numpy as np
if __name__ == '__main__':
# First, read football.dat into a pandas dataframe
# using any contiguous block of whitespace as the delimiter between columns.
# Upon observing the data, I see that there is a column of hyphens between the 'for' and 'against'
# columns,... |
cd1c5a3524e3511df63ca649fb0a99242a290c24 | nirorman/DeepLearningAcademy | /kMeans/k_means.py | 3,201 | 3.578125 | 4 | from random import uniform
import math
from matplotlib import pyplot as plt
class KMeans(object):
def __init__(self, k, data):
self.k = k
self.data = data
self.clusters = self.get_clusters()
self.data = data
def get_clusters(self):
if type(self.data[0]) is float:
... |
ff0ea44b2231c4dc567931ad1d3c514f8be198b2 | kc97ble/testfmt5 | /testfmt/filelist.py | 7,416 | 3.640625 | 4 | #!/usr/bin/env python3
""" filelist.py
BaseFileList
FileList
ZipFileList
Usage:
file_list = FileList/ZipFileList(...)
print file_list.files
file_list.files = ...
success = file_list.move_files_indirectly(src, dst, real=..., quiet=...)
"""
import os
import sys
import zipfile
import datetime
import m... |
a51fca588c89afc244eab2b1fa734935933b1672 | maddiemooney/adventofcode2020 | /3.py | 422 | 3.65625 | 4 | def day3(lines, x, y):
count = 0
row = 0
col = 0
while row < len(lines):
if(lines[row][col] == '#'):
count += 1
row += x
col = (col + y) % len(lines[0])
return(count)
file3 = open('input3.txt', 'r')
lines = [line.strip() for line in file3.readlines()]
print(day3(lines, 1, 3))
a = day3(lines, 1, 1)
b = d... |
74d1e8ed8267e8af09cb20e8f9b4f75ae01b97eb | Phantom1721/python | /ip-py/main.py | 310 | 3.5625 | 4 | print("Welcome guys, today i will show you how you can get your ip with python")
# first we will import request library
import requests
# this will send a get request to the website and the website will return the ip
r = requests.get("https://httpbin.org/ip")
print(r.text)
# now lets test it |
385051c244641e98896c18a8fd8211f86a50143a | Puneethgr/MachineLearningLabVTU | /01 (Find S algorithm)/1.py | 655 | 3.703125 | 4 | # Program 1 (Find S):
import pandas as pd
data = pd.read_csv("EnjoySport.csv", header = None)
print(data)
numberAttributes = len(data.columns)-1
hypothesis = ['0' for _ in range(numberAttributes)]
print("hypothesis 0 : ", hypothesis)
for index, row in data.iterrows():
if row[len(row)-1] == "Yes":
f... |
717975751852860d17fb06e6f8e0b15afaaf20c9 | jose137sp/lab3-py | /problema1.py | 667 | 3.953125 | 4 | print()
lista=[]
for i in range(20):
lista.append(int(input("Introduzca un numero: ")))
print("\n Lista impresa: ")
print(lista)
print("\n Lista ordenada: ")
ordenada=sorted(lista)
print(ordenada)
print("\nLongitud: ")
print(len(lista))
print("\n--------------------------------------------------------------")
... |
000ca6ba92ba3927f35b2bf77eff25f74d60e862 | tasneem786/DNA-string-Complement_and_GC_content | /Problem7.py | 179 | 3.59375 | 4 | s = input("Enter ")
c = s[::-1]
print (c)
complementary =""
com_rule={"T":"A", "A":"T","G":"C","C":"G"}
for i in c :
complementary+= com_rule[i]
print (complementary)
|
eee5b0b3595809d6df59ab3cdd9733465b3dd466 | MasKong/Algorithms | /Merge k Sorted Lists_v2.py | 1,726 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists): #naive version
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
i = 0
n = len(li... |
175a33228e101c2b2b9b232a938eaa078a9cdccd | MasKong/Algorithms | /aigeng.py | 999 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sort(self, head): #naive version
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if head is None:
retu... |
0794f310ba90efe98b8bf0eeeeb4a5ce0ad74660 | MasKong/Algorithms | /Palindromic Substrings.py | 707 | 3.515625 | 4 | class Solution:
def countSubstrings(self, s: str) -> int:
res = []
for i in range(0, len(s)):
for j in range(i+1,len(s)+1):
if self.is_palindromic(s[i:j]):
res.append(s[i:j])
return len(res)
def is_palindromic(self, s: str):
if s =... |
329516d87315f02847f4842b34420df44b0b2fbe | MasKong/Algorithms | /用两个栈实现队列.py | 562 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.l = []
self.l1 = []
def push(self, node):
# write code here
# if self.l:
# self.l1.append(self.l.pop())
self.l.append(node)
def pop(self):
# return xx
if not self.l:
... |
4f863139c0e3767ce9aff281aa639a2730b2538a | MasKong/Algorithms | /Add Two Numbers.py | 757 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
if l1 is None and l2 is None:
return None
elif l1 is None:
return list(self.traverse(l2))
... |
16407eb4a356857abddcf2af40d351eb284b26f1 | MasKong/Algorithms | /Binary Tree Right Side View.py | 869 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
'''B... |
bb7964b4c045e07e7302a9ab908a02b86e28627b | iijii-0c/hangman | /Game_Petr.py | 6,828 | 3.671875 | 4 | import random
words=["лошадка","тумбочка","переводчик","компьютер",
"клавиатура","переплет","сиденье","наклейка",
"холодильник","зеркало"]
for i in range(2):
i=len(words)
nomber_word=random.randint(0,i)
def hangman(word): # Задаем функцию от параметра "word"
wrong=0 #Создаем ... |
14779d4fa7f2085220f8f41e784ff8fa7d701a17 | StRobertCHS-ICS4U1a-201819/rams-rewards-final-project-power-rangers | /Student.py | 1,210 | 3.5625 | 4 | class Student(object):
def __init__(self, first_name, last_name, student_id, grade):
self.__first_name = first_name
self.__last_name = last_name
self.__student_id = student_id
self.__grade = grade
self.__points = 0
self.__history = []
self.__selected = False
... |
5fe9ed06ba223240c33031393d01250ff0ccac3c | Marcus-Mosley/ICS3U-Unit4-07-Python | /numbers.py | 603 | 4.09375 | 4 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on October 2020
# This program states all integers from 1000 to 2000
def main():
# This function states all integers from 1000 to 2000
# Input
counter = 0
# Process & Output
print("Here are all integers 1000 to 2000:")
print("")
... |
f33f356480974c2cb73e997ff780bf8344dbc468 | ani30697/HELLO-PSS | /pract4.py | 161 | 3.859375 | 4 | num=int(input("enter a number of your choice:"))
x= list(range(2,50))
for y in x:
if num%y==0:
print(y)
else:
print("no number available")
|
45be402fa399778a342a55e19e35d9a26ca41fef | MaciejLaczynski/WizualizacjaDanych | /Cw5/Zadanie2-20.04.2020.py | 765 | 3.703125 | 4 | class Ksztalty:
def __init__(self, x, y):
self.x=x
self.y=y
self.opis = "Klasa Kształtów"
def pole(self):
return self.x * self.y
def obwod(self):
return 2 * self.x + 2 * self.y
def wpisz_opis(self, text):
self.opis = text
def skalowanie(self, czynnik):... |
6767f4dee61a6bae62c4c3ac6a7eec227fb198a3 | tryap1/Sudoku-Backtracking | /sudoku.py | 2,525 | 3.8125 | 4 | #Define a SOLVABLE sudoku board
board = [
[0,0,0,0,0,0,0,0,0],
[0,1,5,3,0,9,7,8,0],
[0,4,0,2,0,1,0,6,0],
[0,6,4,7,0,8,1,2,0],
[0,0,0,0,0,0,0,0,0],
[0,3,7,5,0,6,8,4,0],
[0,8,0,4,0,5,0,9,0],
[0,7,9,8,0,2,4,3,0],
[0,0,0,0,0,0,0,0,0]
]
#Sudoku solving function
def sudoku_sol... |
5eeffaa304c531ef1b7af40394f4e8c953e1d51c | SeYearSt/Analysis-algorithm | /lab6.py | 393 | 3.890625 | 4 | import random
def insertion_sort(A):
for j in range(1,len(A)):
temp = A[j]
i = j - 1
while (i>= 0 and A[i] > temp):
A[i+1] = A[i]
A[i] = temp
i=i - 1
def main():
size = int(input("Etner size of list: "))
A = [int(random.random()*10) for i in ... |
53e4f07e95344f78079d61bc7ad668ae242f0cce | theomartinsantoso/Kumpulan-Program-Python | /ContohException.py | 189 | 3.53125 | 4 | try:
x = 'Gunadarma'
input1 = input ("Masukan inputan 1 : ")
print x [input1]
except IndexError:
print 'Index tidak ada'
except NameError:
print 'Tidak boleh karakter'
|
b920948b31d211e1aa995b7609141ab11ce46d70 | theomartinsantoso/Kumpulan-Program-Python | /Ujian.py | 3,134 | 3.921875 | 4 | def menu():
print '''
============== MENU =============
1. PROGRAM KALKULATOR
2. PROGRAM LUAS SEGITIGA
3. PROGRAM LUAS PERSEGI
4. PROGRAM GAJI
5. PROGRAM SUHU
6. PROGRAM GANJIL
7. PROGRAM GENAP
8. PROGRAM RANGE
9. PROGRAM KOPI
10. EXIT
===============================... |
f4d9d333ada3342e7ec6a9cac6d653491e01b0d5 | awahl1/Insight_Project | /Grammar/Baseclasses.py | 1,139 | 3.546875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 13:38:41 2017
@author: alexanderwahl
"""
import random
class Template(object):
def __init__(self):
self.sequence = []
def generate(self):
self.lexicalized_sequence = []
f... |
07d8483c17ec09a9731afbf8f50aeead4e6fdc2a | scottgreenup/lum | /main.py | 2,969 | 3.90625 | 4 | #!/usr/bin/env python
"""
Example:
$ ./main.py --choices 10 --list host1 host2 host3 host4 host5 --number 4
['host1', 'host2', 'host3', 'host4']
['host1', 'host2', 'host3', 'host5']
['host1', 'host2', 'host4', 'host5']
['host1', 'host3', 'host4', 'host5']
['host2', 'host3', 'host4', 'host5']
... |
316843da752d708f6bf325a8e0bf20fac3569caa | ccheng3/Rosalind_Problems | /Python_Village/INI5.py | 780 | 4 | 4 | # Problem Description and Solution Design Notes
#
# Given a file containing at most 1000 lines,
# return a file containing all of the even-numbered lines from the
# original file. (The lines in the file are assumed to be 1-based numbered)
# Solution Design
#
# First, read the file and store each line as an element i... |
adc886d69bc57e080f0a5937233cc4d9285f950f | SilverXuz/TextBasedPythonGame | /Game.py | 4,449 | 3.765625 | 4 | import random as r
hp = 0
coins = 0
damage = 0
def printParameters():
print("У тебя {0} жизней, {1} урона и {2} монет.".format(hp, damage, coins))
def printHp():
print("У тебя", hp, "жизней.")
def printCoins():
print("У тебя", coins, "монет.")
def printDamage():
print("У тебя", dama... |
968b815966af601f07946e4fc0cdc7d7f107fd01 | komararyna/HW3 | /task3.py | 130 | 4.09375 | 4 | a=int(input('insert your number:'))
if a == 0:
print('your number is zero')
else:
print('your number isn`t equal to zero') |
2834050573db40f828573a3a5e88137c4851382e | P-RASHMI/Python-programs | /Functional pgms/QuadraticRoots.py | 979 | 4.3125 | 4 | '''
@Author: Rashmi
@Date: 2021-09-17 19:10:01
@Last Modified by: Rashmi
@Last Modified time: 2021-09-17 19:36:03
@Title : A program that takes a,d,c from quadratic equation and print the roots”
'''
import math
def deriveroots(a,b,c):
"""to calculate roots of quadratic equation
parameter : a,b,c
ret... |
a40e98c3231f4f3a16e86dfe2eeb9951ae29b05d | P-RASHMI/Python-programs | /oops_sample/Innerclass.py | 764 | 4.5 | 4 | '''
@Author: Rashmi
@Date: 2021-09-20 17:10
@Last Modified by: Rashmi
@Last Modified time: 2021-09-20 17:17
@Title : sample program to perform Concept of inner class and calling inner class values,inner class
'''
class Student:
def __init__(self,name,rollno):
self.name = name
self.rollno = rolln... |
2af7aa31f51f43d8d4cdaaaf245833f3c215e9cf | P-RASHMI/Python-programs | /Logicalprogram/gambler.py | 1,715 | 4.3125 | 4 | '''
@Author: Rashmi
@Date: 2021-09-18 23:10
@Last Modified by: Rashmi
@Last Modified time: 2021-09-19 2:17
@Title : Simulates a gambler who start with $stake and place fair $1 bets until
he/she goes broke (i.e. has no money) or reach $goal. Keeps track of the number of
times he/she wins and the number of bets he/she m... |
290e75703b068540669951c640dda07edf175a69 | Firtoshkr/Years_of_Experience-VS-Salary | /Years_of_Experience VS Salary.py | 1,575 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
# In[33]:
data = pd.read_csv("C:\\Users\\firto\\jupyter\\salary.csv")
# In[34]:
X = np.array(data['YearsExperience'])
y = np.array(data['Salary'])
# ... |
6e5145040d2cc26b349ed29cfcf259e6bdbfcd3c | kslee9572/stock-prediction | /plot.py | 351 | 3.53125 | 4 | # returns a heat map as a result
import matplotlib.pyplot as plt
import numpy as np
def plot(x_max, y_max, data):
x = np.arange(10, x_max + 1, 10)
y = np.arange(10, y_max + 1, 10)
plot = plt.contourf(x, y, data, cmap=plt.cm.coolwarm)
plt.title("Accuracy")
plt.ylabel("Forecast Days")
plt.xlab... |
11e3ef41dd81b901834dbd29be56f9657ddbc38e | NJIT-CS490-SP21/project2-sjr52 | /tests/unmocked/unit_tests.py | 5,571 | 4.15625 | 4 | '''
The file is used to do unmocked testing
'''
import unittest
KEY_INPUT = "input"
KEY_EXPECTED = "expected"
KEY_EXPECTED1 = "name_expected"
KEY_EXPECTED2 = "score_expected"
class SplitTestCase(unittest.TestCase):
'''This class is used to extend the unittest.TestCase and performs splitting of the string'''
... |
5313c423050296073aa06aa8cb09a47079920edf | sandhyakopparla/task1exam | /evenodd.py | 237 | 3.984375 | 4 | n1=int(input("enter the num"))
even=[]
odd=[]
def check(n1):
if n1%2==0:
even.append(n1)
else:
odd.append(n1)
check(n1)
if(len(even)>0 and len(odd)<=0):
print(even,"even no")
else:
print(odd,"odd no")
|
416cb191e71588c9e419a7e9b562328c2c925291 | AndresSanchezSanchez/master-ai | /cursoPython/numpy_example.py | 575 | 3.546875 | 4 | # %%
import numpy as np
import time
# %% Clock list vs numpy array
rango = 10000000
list1 = range(rango)
list2 = range(rango)
array1 = np.array(range(rango))
array2 = np.array(range(rango))
start1 = time.time()
result = [x - y for x, y in zip(list1, list2)]
end1 = time.time()
start2 = time.time()
r... |
f304620cb4866239d45abd9e74933815c0d7c5c8 | faseehahmed26/Python-Practice | /currentbill.py | 486 | 4.03125 | 4 | n=int(input("Enter units of Electricity:"))
if n<=50:
cost=n*0.5
#price=(cost+(cost/5))
#print("Cost=",price)
elif(50<n<=150):
cost=(50*0.5)+(n-50)*1.25
#print("Cost=",price)
elif(150<n<=250):
cost=(50*0.5)+(n-50)*1.25+(n-100)*1.75
#price=(cost+(cost/5))
#print("Cost=",pri... |
f48eebdf0a8d5f6dbd4ac0edcf8a4c981cd4fc53 | faseehahmed26/Python-Practice | /repetitionword.py | 72 | 3.75 | 4 | n=str(input("enter word:\n"))
for i in range(200):
print(n,end=" ")
|
e463a3faa5fb416d6e72537ed60a44c07c9932ea | faseehahmed26/Python-Practice | /dictionary.py | 528 | 3.984375 | 4 | """
Write a Python code to store the name and age of the employee of an organisation
in the dictionary from user, where name is "Key" and age is the "value".
Find the number of employees whose age is greater than 25 and display them.
"""
n=int(input("Enter number of persons:"))
l1={}
count=0
for i in range(n):
na... |
fdfcbcbed691b3d63e86da9952e16e754382cfb4 | faseehahmed26/Python-Practice | /listcommon.py | 143 | 3.828125 | 4 | a=[1,1,2,3,5,8,13,21,34,55,89]
b=[1,2,3,4,5,6,7,8,9,10,11,12,13]
l1=[]
for z in a:
if z in b:
l1.append(z)
print("new list is",l1)
|
ced83d41eba97d0378ac0632fdac951aa786f707 | faseehahmed26/Python-Practice | /sumofdigits.py | 119 | 3.953125 | 4 | n=int(input("Enter number to add sum of digits:\n"))
sum=0
while(n>0):
a=n%10
n=n//10
sum=sum+a
print(sum)
|
c3c0421e340c3bd8f196752426f1bcaa8ef3eb72 | faseehahmed26/Python-Practice | /nptelml0.py | 480 | 3.53125 | 4 | def compute_j(w1,w2):
j= w1**2 +w2**2 +4*w1-6*w2-7
return j
def compute_gradient_w1(w1,w2):
return(2*w1+4)
def compute_gradient_w2(w1,w2):
return(2*w2-6)
w1 = 5
w2 = 5
Alpha = 0.3
for i in range(1000):
j = compute_j(w1,w2)
print("iteration ",i+1)
print('w1=',w1)
print('w2=',w2)
... |
23bcf2c9399717fb3e0d89281eeba04312162395 | faseehahmed26/Python-Practice | /oop.py | 628 | 4 | 4 | class MyClass:
'''This is my DocString
Example of Class Variable a,Instance variable a
Instantiation,Call Function using object of class
Display'''
a=10 #Class Variable
def __init__(self): #Class Constructor
self.a=100 #Instance Variable
print("Instance variable a=",self.a)
def func(self... |
63b92439468f887c773942dbf97a10f21732ca14 | faseehahmed26/Python-Practice | /loopsintro.py | 207 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 7 09:16:23 2019
@author: abhishekbodapati
"""
count=0
while(count<5):
print('The count is:',count)
count+=1
print("Good Bye!") |
fd95b563863d2ed4ca81a7716abf830dc4aca51c | faseehahmed26/Python-Practice | /factors.py | 115 | 4.0625 | 4 | n=int(input("Enter any number to find factors:"))
for x in range(1,n+1):
if (n%x==0):
print(x,end=" ")
|
829a4118953274b9d8c4f1d3f2fb082d82c49d45 | faseehahmed26/Python-Practice | /armstrongnum.py | 178 | 3.796875 | 4 | a=int(input("Enter number:\n"))
sum=0
x=a
while(a>0):
d=a%10
sum=sum+d*d*d
a=a//10
if (sum==x):
print("Armstrong number")
else:
print("Not Armstrong number")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.