blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a98f02bd6c756f698b4eb1aa3d935eb9acd7c2a9 | toantranbao/demo_python | /main.py | 407 | 3.765625 | 4 | from car import Car
#creating an object car
m = Car()
#Assigning the properties for car
m.color = "Red"
m.brand = "Mes"
#involke/call the function on car
m.di_chuyen()
print(m.color)
print(m.brand)
#creating an object car
m1 = Car()
#Assigning the properties for car
m1.color = "White"
m1.brand = "BMW"... |
145e510ea433a9fcea35ab789658f6df9bb62317 | RCBSi/advent-of-code-2020 | /day23b_cupswitch.py | 2,093 | 3.5 | 4 | def create_successor(seq):
top = 1000000 #20 #1000000
succ = {int(seq[i]):int(seq[i+1]) for i in range(len(seq)) if i+1 in range(len(seq))}
succ[int(seq[-1])]=len(seq)+1
extra = range(len(seq)+1,top+1)
succ = succ | {i:i+1 for i in extra if i+1 in extra}
succ[top] = int(seq[0])
return succ
... |
3b752dc0a499c715157bab5036a3284993126f41 | sutarnilesh/DataStructuresPython | /datastructures/Stack/baseConverter.py | 622 | 3.640625 | 4 | from datastructures.Stack.stack import Stack
def baseConverter(decNumber, base):
digits = "0123456789ABCDEF"
remstack = Stack()
while decNumber > 0:
#print(decNumber)
rem = decNumber % base
#print(rem)
remstack.push(rem)
decNumber = decNumber // base
... |
4ad5ecd56bef90946d2187763ef8cff865ded0e7 | sutarnilesh/DataStructuresPython | /algorithms/Searching/runhashtables.py | 304 | 3.609375 | 4 |
from algorithms.Searching.hashtable import HashTable
H=HashTable()
H[54]="cat"
H[26]="dog"
H[93]="lion"
H[17]="tiger"
H[77]="bird"
H[31]="cow"
H[44]="goat"
H[55]="pig"
H[20]="chicken"
print(H.slots)
print(H.data)
print(H[20])
print(H[17])
H[20]='duck'
print(H[20])
print(H[99])
|
60701615a33f77151e6916bd67d6a11ede4290f8 | Gulsah-Yagci/python-projects | /python_oop/class.py | 560 | 3.703125 | 4 | class Insan():
isim = "ali"
guc = 55
# bu sekilde isime ve guce erişim verir
class Insan2():
# yapıcı method
def __init__(self,name,guc): # name ve guc dışarıdan atanacak
self.name = name
self.damage = guc # self'i farklı adlandırabilirsin
# self ile bu yukarıdaki değişk... |
68726fedcb051ddef24e438f1e38d2358b53e695 | sachag678/Algorithms-coding-interview | /one_away.py | 2,236 | 3.796875 | 4 | #check if a given string is one edit or zero edits away from another given string. There is an assumption that order of the chars in the string
#doesn't matter. If the order does matter, a different approach may be taken.
import timeit
def check(word1, word2):
'''Finds the longer word and then iterates through the l... |
7480d0ae0594263ea05be8b2e41ee889be424c66 | rfreiberger/Automate-the-Boring-Stuff | /ch3/collatz2.py | 550 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 23:00:54 2016
@author: Robert Freiberger
"""
def collatz(number):
if number % 2 == 0: # even
number = number // 2
else:
number = 3 * number + 1
print(number)
evenOddLoop(number)
def evenOddLoop(number):
if ... |
2d5db7becc0735cb8c8ff29b2f306b7965a06c2c | jhaneto/jhan | /Curso_Formcao_DS/exercicio_house_price1.py | 2,438 | 3.765625 | 4 | import pandas as pd
import numpy as np
#Importando Data Set
data = pd.read_csv("C:\\Users\\win10\\Desktop\\python_excel\\kc_house_data.csv")
data.head()
#1. Quantas casas estão disponíveis para compra?
#Quantidade de dados da tabela
data.shape
## Ao todo são 21613 casas disponíveis para compra
#2. Quantos atributos... |
938a9b86ebc67a12e320b680b93cd4f5668c5c35 | dotslash/dotslash.github.io | /codepg/rec-stack.py | 3,407 | 3.90625 | 4 | def hanoi(n, fr, to, buf):
if (n == 0):
return
#print "deb", 'l', n, fr, to, buf
hanoi(n-1, fr, buf, to)
#print "deb", 'r', n, fr, to, buf
print "{} {}->{}".format(n, fr, to)
hanoi(n-1, buf, to, fr)
def hanoi_iter(n, fr, to, buf):
stack = list() #python's list can be used as stack
... |
283fe24ea0aa9545a24c2315522476f6ad8a1efb | richardmillson/Calkin_Wilf_tree | /tree.py | 2,316 | 3.84375 | 4 | from fractions import Fraction
import math
import itertools
def succ(x):
"""
takes an element of the Calkin Wilf tree and returns the next element
following a breadth first traversal
:param x: Fraction
:return: Fraction
"""
x_int = Fraction(math.floor(x))
x_nonint = Fraction(x.numerato... |
53745aadfc51ae8f61452eadb461b64f95c429f2 | atjeprahmat/Pembagian-Gaji | /PembagianGaji.py | 934 | 3.625 | 4 | #ATJEP RAHMAT
print("Menghitung Penghasilan Budi oleh @atjeprahmat")
print("*"*40)
gaji_per_jam = float(input("Gaji Perjam yang diinginkan : "))
jumlah_jam = float(input("Jumlah jam kerja selama seminggu : "))
gaji_bersih = gaji_per_jam * jumlah_jam
pajak = gaji_bersih-(gaji_bersih*0.14)
baju_aksesoris = (gaji_bers... |
41fdb91d4aa0fae102f904405a138419aa8f83ca | al85ko/algo_and_structures_python | /Lesson_2/8.py | 706 | 4.0625 | 4 | """
8. Посчитать, сколько раз встречается определенная цифра в введенной
последовательности чисел. Количество вводимых чисел и цифра,
которую необходимо посчитать, задаются вводом с клавиатуры.
"""
nums = input('Введите через пробел последовательность чисел')
num = int(input('Введите цифру'))
count = 0
nums = nums.s... |
fb53a1aea947d69319143158f4dc5e5798c72084 | annarob/testing | /christopher's programming/GuessGame.py | 569 | 3.859375 | 4 | #This is a number game.
import random
print('hello! What is your name?')
name = input()
print('Well, %s, I am thinking of a number between 1 and 20' % name)
print('Take a guess.')
tries = 1
num = random.randint(1, 20)
for x in range(1, 7):
response = input()
guess = (int(response))
if guess == num:
... |
32553569f74e33ee639b207daa2861dafa4d3aa2 | annarob/testing | /christopher's programming/tkinter5.py | 427 | 3.609375 | 4 | from tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=500, height=500)
canvas.pack()
def random_rectangle(width, height, fill_color):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectan... |
e515ec61933d8ec1dc3d44ee53489d5fbae1c73b | Shin-jay7/AtCoder_Python3 | /AcCepted.py | 129 | 3.703125 | 4 | # Task: https://atcoder.jp/contests/abc104/tasks/abc104_b
import re
print("AC" if re.match("A[a-z]+C[a-z]+$", input())else "WA")
|
fcf5bdb08bd242c49136d02b1724f5698f66c228 | Shin-jay7/AtCoder_Python3 | /MakeThemEven.py | 860 | 3.765625 | 4 | # Task: https://atcoder.jp/contests/abc109/tasks/abc109_d
# Move: (1,1)->(1,2)...->(1,W)->(2,W)->(2,W-1)...
# ->(2,2)->(2,1)->(3,1)->(3,2)...
# If you find odd number,
# subtract 1 from the column and add 1 onto the next column.
H,W = map(int, input().split())
matrix = [list(map(int, input().split())) for _... |
59dcbbd08b53d168688366c702058cab6421b14d | jairajsahgal/DailyByte | /Uncommon_words.py | 217 | 3.890625 | 4 | def fun(s1,s2):
s1=set(s1.split())
s2=set(s2.split())
print("S1: ",s1,"\nS2",s2)
# print(s1-s2)
return (s1.union(s2))-(s1&s2)
def main():
s1=input("Enter s1")
s2=input("Enter s2")
print(fun(s1,s2))
main() |
9394a92e52ff8381dd629cdb78b8e26b2cd27aa0 | RYLiang18/Problem-Creator | /FileMaker.py | 2,484 | 3.5 | 4 | import RandomMathQuestionGenerator as rmqg
addDict = {}
subDict = {}
subDict2 = {}
multDict = {}
divDict = {}
#10 ADDITION
for i in range(12):
addDict.update(rmqg.generateAddition(1, 100, 1, 100))
#10 SUBTRACTION WITH WHOLE NUMBER SOLUTIONS
for i in range(12):
subDict.update(rmqg.generateSubtractionPositive(... |
f2cd9527c7aa7e89907e5d29efbb624bc045c4cd | sudo-apt-install/hello-world | /coffee.py | 2,921 | 3.875 | 4 |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
... |
9ba6df1d6eb985bf15d4d3338c61220a1a71dbf9 | JakubRada/maze_keeper | /maze_generator.py | 8,560 | 4.125 | 4 | from maze_keeper import ACTIONS, get_cell_positions, get_unique_cell, add_tuples
import random
"""
When supplied with the size of the maze as NxM tuple (M - number of rows,
M - number of columns), function generate mazemust generate a maze layout of
given size.
Coordinates in the maze are such that c is the index of t... |
6ee6c2beaa6bc4e8486fe74b4c2027ff4f905ef8 | juliusrain/numbers | /numbers.py | 1,343 | 3.875 | 4 | #!/usr/bin/env python
import random
import sys
def evaluate(code, guess):
feedback = []
codecp = list(code)
for i in xrange(0, len(guess)):
if guess[i] == code[i]:
feedback.append("1")
codecp.remove(guess[i])
for i in xrange(0, len(guess)):
if guess[i] in codecp... |
6436c907bf62c8baa3e2bf633f1e84fe24bedc90 | AmyL19/PCC-Coding-Camp | /2020/advanced/double_advanced/recursion_examples.py | 682 | 3.90625 | 4 | #============================= Factorial Example =============================
def factorial(n):
res = 1
for i in range(n):
res *= (i+1)
return res
def factorialRecursive(n): return n * factorialRecursive(n - 1) if n > 1 else 1
#============================= List Sum Example ==================... |
822e9a6bc75fbbe87990f0ab3736b32ce871f567 | AmyL19/PCC-Coding-Camp | /2020/advanced/tic-tac-toe/tic-tac-toe-ex-minimax.py | 6,553 | 4.03125 | 4 | # starter code for implementing tic-tac-toe
# HINTS:
# - think about the types of the variables and functions
# - don't be afraid to ask for help
def otherLetter(letter):
if letter == 'X':
return 'O'
else:
assert(letter == 'O')
return 'X'
def insertBoard(letter, pos, board):
#... |
ffc00b7630a143847eb6374a03d9c090ae6b2228 | pmcloete/alien-invasion | /alien.py | 1,492 | 3.6875 | 4 | from pygame.sprite import Sprite
class Alien(Sprite):
"""A class to represent a single alien in the fleet"""
def __init__(self, ai, row_number=0):
"""Initialize the alien and set its starting position."""
super().__init__()
self.screen = ai.screen
self.settings = ai.settings
... |
b93cc21a96cf883f802ac0dc60c4be07cc3e2038 | rzbasereh/PythonLab_Group6 | /lab4/3/tuple.py | 501 | 4.15625 | 4 | # 3-2
##### Part 1
# Notice: Once a tuple is created, you cannot add items to it.
tuple1 = ('95105968', 'reza')
print(tuple1)
# update tuple values
tuple1 = ()
arr1 = list(tuple1)
arr1.append('95105968')
arr1.append('reza')
tuple1 = tuple(arr1)
print(tuple1)
##### Part 2
tuple2 = ('95105965', 'ali')
tuple3 = (... |
a448d46df05460a64d5693d05f272f5d2c138fec | rzbasereh/PythonLab_Group6 | /lab4/2/collatz_generator.py | 253 | 3.84375 | 4 | #2-5
def calc(n):
n = int(n)
if n == 1:
print(n, end='.\n')
else:
print(n, end=', ')
if n % 2:
n = 3 * n + 1
else:
n /= 2
calc(n)
n = int(input('Enter a number: '))
calc(n)
|
d96a8ff38171329738d6edea14f6d8a33c78d7de | cash2one/Postr | /postr/schedule/writer.py | 3,271 | 3.640625 | 4 | from datetime import datetime as dt
import os
import sqlite3
import time
class Writer():
"""
Inserts rows into the database tables regarding scheduling
operations
"""
def __init__(self) -> None:
file_path: str = os.path.join('postr', 'schedule', 'master_schedule.sqlite')
self.conn... |
c56bc9b49816b4baf8cbc1ba9a9fc5f42925d9d5 | BillShoulder/codewars | /list_squared.py | 761 | 3.796875 | 4 | """ Codewars kata: Integers: Recreation One. https://www.codewars.com/kata/integers-recreation-one/train/python """
try:
from math import sqrt, isqrt
except ImportError:
# Python < 3.8
from math import sqrt
isqrt = lambda n: int(sqrt(n))
def factors(n):
factors = {1, n}
for i in range(2, isqrt... |
faba0805e9edfa5fff06d2728991662e83bfb771 | gaganbhattarai/python_programs | /qn_3.py | 376 | 4.1875 | 4 | #Compute the volume of a cylinder
import math as m
def volume():
rad = eval(input("enter the radius of the cylinder:"))
height = eval(input("enter the height of the cylinder:"))
area = m.pi * rad * rad
print("the area of a cylinder with radius",rad,"is:",area)
volume = area * height
print(... |
56a0b8bcf85a8ea8305febfe38e4699e1a1e035a | agcastro1994/Python2020 | /ScrabbleAR3.14/ScrabbleAR3.14-master/Funciones/IA.py | 3,563 | 4.03125 | 4 | from Funciones.Validez import esValida
from Funciones import Letras
def CPUdesarmar(ind,letras):
"""recibe las letras del atril y las pocisiones ordenadas para formar la palabra"""
l=[]
for i in ind:
l.append(letras[i])
return l
def CPUformarPalabra(letras):
"""junta la lista de caracter... |
01449cf88d1179765edb24bb420871e6cb35f46f | yami-five/programming-challenge | /05_FizzBuzz.py | 147 | 4.03125 | 4 | for x in range(1,100):
if x%3==0 and x%5==0: print("FizzBuzz")
elif x%5==0: print("Buzz")
elif x%3==0: print("Fizz")
else: print(x) |
3054a28f656aa52cc9508ed498ffef529e3d835d | yami-five/programming-challenge | /07_Project_Euler_07_10001st_prime.py | 411 | 3.796875 | 4 | import math
prime_numbers=[]
def is_prime_number(n):
if len(prime_numbers)==0:
return True
else:
for x in prime_numbers:
if n%x==0:
return False
return True
counter=5000
number=1
while(counter!=10001):
number+=1
if is_prime_number(number)==True:
pr... |
3333263a8d5d83f7688f26cccb3e25751b06d5a1 | godwin-kachi/zuri_internship | /improved_atm.py | 4,204 | 3.859375 | 4 | import datetime
import random
from os import system
clear = lambda: system("cls") #I need to read the full implementation of this function
allowedUsers = {
"onyekachi": "imagine",
"mary": "bontel",
"naomi": "pleasant",
"dolapo": "sweetheart",
"martina": "loverbae",
} #the usernames are passe... |
b6aeb37e0d89904d3aa6f640f7200b3207373c49 | seholevas/PackageDeliverySystem | /DataStructures/Graph.py | 1,429 | 3.96875 | 4 | # Name: Steven Holevas
from collections import namedtuple
from collections import defaultdict
# same as tuple, just allows you to name it and its tuple items, which makes
# it visibly maintainable and efficient to get variables
Node = namedtuple('Node', ['vertex', 'weight'])
class WGUPS_Graph:
"""this ... |
57b45e530070d72dbda433df958bc7bec8068e0e | nindalf/euler | /07-tenthousandprime.py | 919 | 4.03125 | 4 | #! /usr/bin/env python3
"""
Important concept: DRY - Don't repeat yourself.
These 2 functions copied from problem 3.
Program improved after learning the enumerate() function.
Earlier the main() function looked like
index = 0
for prime in prime_generator():
index = index + 1
The current method is more pythonic.
"""... |
fb27a286c32ad8221aad6cc684f79a75c94c1735 | lekyapurnima/Homework | /task2.py | 1,471 | 4.3125 | 4 | import sys
"""Printing the top ten repeated sequences along with its count in a given fasta file
"""
def count_sequence(fasta_file):
"""Counting the number of times a sequence is repeated and giving it to a dictionary with keys as sequence and
value is the repeat counts of the sequence in the file
... |
fda8f5a60b7ee1584ef2bc97126918c554ebbbe7 | digant0705/python-code | /leet_code_30day/_9_April.py | 326 | 3.640625 | 4 | #string --> #is treated as backslash ie backspace
# a#b#c ==a#c --> c==c true
def f(s1,s2):
s3=""
s4=""
for i in s1:
s3=s3+i
if i=="#":
s3=s3[:len(s3)-2]
for i in s2:
s4=s4+i
if i=="#":
s4=s4[:len(s4)-2]
return s3==s4
print(f("ab#c","a... |
e20da52fc59934b6f1690414f4a682f11de354e2 | digant0705/python-code | /Trees-BST/tree_insert_bst.py | 2,089 | 4.15625 | 4 | class Node:
def __init__(self,val):
self.left=None
self.right=None
self.val=val
def insert(root,Node):
if root.val is None:
root=Node
print(f"inserted-->root {Node.val}")
return True
elif root.val<Node.val:
if root.right is None:
root... |
30c3530ddf9e537662010b847ba5c7a753e651f1 | digant0705/python-code | /Leet_code/_299_Bulls_Cows.py | 1,488 | 4.0625 | 4 | """You are playing the following Bulls and Cows game with your friend:
You write down a number and ask your friend to guess what the number is.
Each time your friend makes a guess, you provide a hint that indicates
how many digits in said guess match your secret number exactly in both digit and position
(calle... |
951eb630ee4c7ad8f445032ea422cc50aa1f7740 | digant0705/python-code | /day4.py | 1,463 | 3.90625 | 4 | """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.
For example, the input [3, 4, -1, 1] should give 2. The input [1,... |
a58e4d0513f3bd48686d2482ab21e4843a3bc968 | VictorArowo/leetcode_problems | /Twosum.py | 982 | 4 | 4 | '''
First Pass
Loop through list twice checking if the sum at each iteration is equal to the target
Time Complexity => O(n^2)
Space Complexity => O(1)
'''
def two_sum_1(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
r... |
ee82012b9983b26f60d29d78d1245f3ebaa390b4 | luis1415/knearest_neighbors | /sample.py | 761 | 3.6875 | 4 | from numpy import random
import numpy as np
import matplotlib.pyplot as plt
import seaborn
seaborn.set()
# se crea un array de 10 filas y dos columnas
X = random.rand(10, 2)
# se imprime el array aleatorio
print(X)
# se imprimen las componentes x
print(X[:, 0])
# se imprimen las componentes y
print(X[:, 1])
# se hace... |
53614ab094e65c131f5f001d064eae05781b58ba | rishav-1994/python-programs | /Music.py | 353 | 4 | 4 | Notes=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
#for Major scale
n=input("Enter root note of the scale: ").upper()
index=Notes.index(n)
for i in range(1,9):
if index>11:
index-=12
if i==3 or i==7:
print(Notes[index],end=" ")
index+=1
else:
print(Notes[... |
3851b188f2b81acdc310a5f48f31defa749f5e48 | galipkaya/exercism-python | /guidos-gorgeous-lasagna/lasagna.py | 924 | 3.671875 | 4 | EXPECTED_BAKE_TIME = 40
# TODO: define the 'PREPARATION_TIME' constant
def bake_time_remaining(elapsed_bake_time):
"""
:param elapsed_bake_time: int baking time already elapsed
:return: int remaining bake time derived from 'EXPECTED_BAKE_TIME'
Function that takes the actual minutes the lasagna has ... |
b83414aae552fa725c74cb9cdd2bd0a17ea3d08b | galipkaya/exercism-python | /dot-dsl/dot_dsl.py | 1,617 | 3.65625 | 4 | NODE, EDGE, ATTR = range(3)
class Node:
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge:
def __init__(self, src, dst, attrs):
self.src = src
self... |
340568e74ae5c4e8274d5db3e7bfe69bea32ee2f | galipkaya/exercism-python | /secret-handshake/secret_handshake.py | 457 | 3.5 | 4 | def commands(number):
handshakes = ["wink", "double blink", "close your eyes", "jump"]
number_string = f"{number%32:b}".zfill(5)
reverse_commands = len(number_string) == 5 and number_string[0] == '1'
number_string = number_string[1:][::-1]
result = []
for i, command in enumerate(number_string):... |
3a182825f9f9524d45864cb794646809766c0b84 | galipkaya/exercism-python | /rectangles/rectangles.py | 2,526 | 3.5625 | 4 | from itertools import combinations
from math import sqrt
def is_rectangle(points: [tuple]) -> bool:
x1 = points[0][0]
x2 = points[1][0]
x3 = points[2][0]
x4 = points[3][0]
y1 = points[0][1]
y2 = points[1][1]
y3 = points[2][1]
y4 = points[3][1]
cx = (x1 + x2 + x3 + x4) / 4
cy = ... |
d618f11c0f605f7b518cb200e53716985b2a195a | galipkaya/exercism-python | /two-bucket/two_bucket.py | 1,492 | 4.09375 | 4 | ONE = "one"
TWO = "two"
def measure(bucket_one, bucket_two, goal, start_bucket):
def is_bucket_1_filled():
return b1 == bucket_one
def is_bucket_2_filled():
return b2 == bucket_two
def is_bucket_1_empty():
return b1 == 0
def is_bucket_2_empty():
return b2 == 0
t... |
aaf5c88e23a80aafe8fae2ebc9f3fda8535363cc | galipkaya/exercism-python | /rotational-cipher/rotational_cipher.py | 375 | 4 | 4 | from string import ascii_lowercase
from string import ascii_uppercase
def rotate(text, key):
result = ""
for ch in text:
if not ch.isalpha():
result += ch
continue
source = ascii_lowercase
if ch.isupper():
source = ascii_uppercase
result +=... |
5f4e2cf72df1556d4870193a3754ac0387ff702a | galipkaya/exercism-python | /simple-linked-list/simple_linked_list.py | 1,767 | 3.890625 | 4 | class Node:
def __init__(self, value, next_node=None):
self._value = value
self._next = next_node
def value(self):
return self._value
def next(self):
return self._next
def set_next(self, node):
self._next = node
def __str__(self):
return self._valu... |
829d04f669c30d69e58f2c957fabea1a050ffb1e | galipkaya/exercism-python | /meetup/meetup.py | 1,709 | 3.609375 | 4 | from datetime import date
# range end inclusive
def meetup_date(year, month, day_of_week, range_start, range_end, day_order=1):
current_day_order = 0
last_date = None
for day in range(range_start, range_end+1):
result_date = date(year, month, day)
if result_date.strftime("%A") == day_of_wee... |
dc17d93c936e522cbbebcd548a8418608b7ee98c | Aegistov/Python_Practice | /area_calculator.py | 971 | 4.4375 | 4 | #This will calculate the area of a Circle or Triangle
#With the magic of code
from math import pi
from time import sleep
from datetime import datetime
now = datetime.now()
print "CALCULATOR INITIATED"
print "%s/%s/%s %s:%s" % (now.month, now.day, now.year, now.hour, now.minute)
sleep(1)
hint = "Don't forget to include ... |
31018f0ad5f9e5e079941787d8b5fc1cd0b847e2 | ionhandshaker/Project-Euler | /projecteuler45.py | 599 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 02 16:16:25 2016
@author: Nandhakishore
"""
def is_pentagonal(n):
disc=1+4*3*2*n
disc=disc**0.5
x=(1+disc)/6
if(x-int(x)==0):
return True
else:
return False
def is_hexagonal(n):
disc=1+4*2*n
disc=disc**0.5
... |
d27bb8fd5a422d61e5cb1140f6a395bcaf1a9a2d | ionhandshaker/Project-Euler | /projecteuler26.py | 1,276 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 05 22:19:58 2016
@author: Nandhakishore
"""
#Code based on Fermat's Little Theorem
import math
def isPrime(n):
if(n==1):
return False
elif(n<4):
return True
elif(n%2==0):
return False
elif(n%3==0):
return Fal... |
8dd43e71c686aec811f70392bacf24b813d2b0f1 | Mansi650/geitpl2 | /q12.py | 435 | 4.375 | 4 | #Declare a function named reverse_list. It takes an array as a parameter and it returns the reverse of the array (use loops).
#print(reverse_list([1, 2, 3, 4, 5]))
# [5, 4, 3, 2, 1]
#print(reverse_list1(["A", "B", "C"]))
# ["C", "B", "A"]
def reverse_list(l):
l1=[]
for i in range(len(l)-1,-1,-1):
... |
44b8b99f8b32a66104e173a5f378338d838b46bf | Mansi650/geitpl2 | /q15.py | 480 | 3.890625 | 4 | #Declare a function named remove_item. It takes a list and an item parameters. It returns a list with the item removed from it.
#food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
#print(remove_item(food_staff, 'Mango')) # ['Potato', 'Tomato', 'Milk'];
#numbers = [2, 3, 7, 9];
#print(remove_item(numbers, 3)) # [... |
d0dab74de25403057ce5162a30e61e7bf5518655 | adnanshahz2018/DataStructure | /Queue_Array.py | 1,842 | 4.1875 | 4 |
# Implementation of queue using ARRAY in Python
class queue_array:
size = 0
queue = []
front = 0
back = 0
def __init__(self, size):
self.size = size
array = [0]*size
self.queue = array
def enqueue(self, value):
if self.isFull(): return
self.queue... |
2641541362fc6a15ee624b411fd3d491486a1beb | hasithaearn/Manage-Entered-and-Left-on-Discord | /example/regular_messages/post_day.py | 865 | 3.78125 | 4 | class PostDay():
def __init__(self, times_of_day, day_of_week):
"""
Constructor of a class to set the time of regular posting.
定期投稿の時刻を設定するクラスのコンストラクタ
Parameters
----------
times_of_day : string
Time to post
投稿する時刻
day_of_week : DayOf... |
cd39684e20f124a457065822812919222db3d0fe | nipy/workshops | /170327-nipype/notebooks/testing/pytest_solutions/maxima.py | 394 | 3.875 | 4 | def find_maxima(list_of_numbers):
maxima = []
if list_of_numbers[0] > list_of_numbers[1]:
maxima.append(0)
for i in range(1, len(list_of_numbers)-1):
if list_of_numbers[i-1] < list_of_numbers[i] > list_of_numbers[i+1]:
maxima.append(i)
if list_of_numbers[-1] > list_of_num... |
5edc5eabec5f794d2c976cb1baae5b081af11104 | ismailismail38/login | /Super Inventory NEDERLANDS .py | 4,439 | 3.75 | 4 | import os
import fileinput
def menuDisplay():
print('=============================')
print('= Inventory Programma =')
print('=============================')
print('(1) Nieuwe Item Toevoegen')
print('(2) Een Item Verwijderen')
print('(3) Update Inventory Lijst')
print('(4) Zoek e... |
e50d8d7c1c3ca62ba8d373e7adda15e05992af28 | kiboook/Programmers | /Programmers/Bridge.py | 1,106 | 3.796875 | 4 | from collections import deque
def check_add_truck(bridge, trucks, weight):
total_weight = 0
for cur in bridge:
total_weight += cur[0]
if trucks[0][0] + total_weight <= weight:
return True
else:
return False
def solution(bridge_length, weight, truck_weights):
trucks = deque([[val, 1] for val in truck_wei... |
c16fde87720d5dd2e8def44222ff07acb1fe3dc9 | kiboook/Programmers | /Programmers/70129.py | 555 | 3.65625 | 4 | def remove_zero(s):
return "".join(s.split('0'))
def change_binary(length):
output = []
while length:
output.append(str(length % 2))
length //= 2
return "".join(reversed(output))
def solution(s):
work_cnt = 0
zero_cnt = 0
while s != '1':
work_cnt += 1
s_... |
8825a738a896e1fbb20cfae9f457d283e8eff43f | kiboook/Programmers | /Programmers/JoyStick.py | 1,116 | 3.578125 | 4 | from string import ascii_uppercase
def make_alpha(val):
alpha = list(ascii_uppercase)
value = alpha.index(val)
if value <= 13:
pass
else:
value = 26 - value
return value
def right_move(name, idx):
cur_idx = idx
move_cnt = 0
while name[cur_idx] == 'A':
cur_idx = (cur_idx + 1) % len(name)
move_cnt +... |
6f97459c07099ee233001e187bed7a6c6b80e563 | kiboook/Programmers | /Programmers/Camouflage.py | 387 | 3.734375 | 4 | from collections import Counter
def solution(clothes):
answer = 1
clothes_cnt = [val[1] for val in clothes]
clothes_dict = dict(Counter(clothes_cnt))
for val in clothes_dict.values():
answer *= val + 1
return answer - 1
# clothes = [['crow_mask', 'face'], ['blue_sunglasses', 'faces'], ['smoky_makeup', 'fac... |
f4100254694c791cfd42bbba452576a09fb9cd7d | kiboook/Programmers | /Programmers/KeyLock.py | 1,281 | 3.53125 | 4 | def is_unlock(lock_map, lock_len):
for i in range(lock_len):
for j in range(lock_len):
if lock_map[i + lock_len][j + lock_len] == 0 or lock_map[i + lock_len][j + lock_len] == 2:
return False
return True
def push_key(start, lock_map, key):
for i in range(len(key)):
for j in range(len(key)):
lock_map[... |
bf7e1ea63085c86b3b98e8f76ee9b6b6c889838d | kiboook/Programmers | /Programmers/84325.py | 1,106 | 3.609375 | 4 | def solution(table, languages, preferences):
answer = ""
language_score = dict()
for data in table:
tmp = data.split()
language_score[tmp[0]] = list(reversed(tmp[1:]))
max_score = 0
for job in language_score:
cur_score = 0
for idx, job_language in enumerate(language... |
cafe8ef8f793a0b8c3e826976eb8892c23722457 | kiboook/Programmers | /Programmers/Mocktest.py | 688 | 3.640625 | 4 | def check_answer(answers, checkList, checkCnt):
for index,value in enumerate(answers):
if checkList[index % len(checkList)] == value:
checkCnt += 1
return checkCnt
def solution(answers):
answer = []
answerCnt = []
one = [1, 2, 3, 4, 5]
two = [2, 1, 2, 3, 2, 4, 2, 5]
three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]... |
d20f27326ab3d8b6abb35c48e1201b2c637ed3c0 | kiboook/Programmers | /Programmers/BestAlbum.py | 971 | 3.546875 | 4 | def solution(genres, plays):
answer = []
_dict = {i: [0, []] for i in set(genres)}
for idx, song in enumerate(zip(genres, plays)):
genre, play = song
_dict[genre][0] += play
_dict[genre][1].append([idx, play])
for genre in _dict:
# 재생횟수로 오름차순 정렬 후 고유 번호로 내림차순 정렬
_dict[genre][1] = sorted(_dict[genre][1],... |
fd4b6f7e503f6f7fa414031a4654832fa0cddce5 | Arefka/Search_and_sort_algorithms | /search_the_nearest_points.py | 4,214 | 3.8125 | 4 | '''
===============================================================
Task about search the nearest points on Euclidean plane:
Algorithmic complexity of brute force way = O(n^2).
Algorithmic complexity of way with soft = O(n*log n).
===============================================================
'''
class ... |
4c8533218ace73b41a2be263e9ade471f1fcb28c | Arefka/Search_and_sort_algorithms | /guess_the_number_in_50_steps.py | 1,546 | 4.03125 | 4 | import random
'''
===============================================================
We have a task of "guess the number in 50 steps".
We should find planned number in array of 1000000 numbers in 50 steps.
If we find it, we should return 0, else we think about finding number
and compare it with pl... |
d5bcc768351fec49e5f2d012c7b7a0687e4799b2 | Arefka/Search_and_sort_algorithms | /greedy_algorithm_for_sets.py | 2,214 | 4.5625 | 5 | '''
===============================================================
An interesting example of how greedy algorithms and sets simplify the solution of a problem.
In this example we have some radio stations, information about city coverage and
a task of making algorithm of maximize the coverage with costs m... |
54a0a27dc29a38154eadf52448ff0ebad3fb6a49 | DaveTheFinder/PSP_Course_Programs | /PSP PROGS/PROG_1.py | 6,262 | 3.71875 | 4 | """
Program Assignment: Prog 1
Name: David Ernesto Saenz Saenz
Date: 08/17/2016
"""
"""
Listing Contents:
Reuse instructions:
Class Node:
Purpose: To create Nodes with given elements: Number or Text
Limitations: Previously secify what type of element you are going to add: Number or Text.
Avoi... |
26b7ce9ec0803913d600a6a29f203599fa01cc40 | IvonFis/MachineLearning | /Polynomial.py | 1,333 | 3.921875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
dataset = pd.read_csv("Position_Salaries.csv")
# remember to consider X as a matrix and not as a vector
X = dataset.iloc[:, 1:2].values
Y = data... |
253b47f5ee3c22b28e5edff074bea11c697808c7 | vimleshtech/python_feb | /oops file.py | 577 | 3.625 | 4 | class salary:
def get_input(s):
s.ecode= input('enter ecode :')
s.ename = raw_input('enter ename :')
s.bs= float(input('enter basic salary :'))
def cal(s):
s.a= s.bs*0.4
s.b= s.bs*0.2
s.c= s.bs*0.1
s.d= s.bs+s.b+s.c
def display(a):
... |
d9c4001483d2b160f7cf644e405b624b0ff38e84 | singhabhinav/knowbigdata | /session2_mapreduce/problem_2/mapper.py | 361 | 4.0625 | 4 | #!/usr/bin/python
'''
Find anagrams in a text file
'''
import sys
def read_input(file):
for line in file:
yield line.split()
def main(separator='\t'):
data = read_input(sys.stdin)
for words in data:
for word in words:
print '%s%s%s' % (''.join(sorted(word)), separator, word... |
43ecccf3bf1402b1faada733280f53192d8f1a99 | wmr123456/LPTHW | /ex21.py | 720 | 3.890625 | 4 | #coding=utf-8
#加法
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
# 减法
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
#乘法
def multply(a, b):
print "MULTILYING %d * %d" % (a,b)
return a * b
#除法
def divide(a,b):
print "DIVIDING %d / %d" % (a,b)
return a /b
print "Let's do ... |
c63b482dd15b549a8066359de9c76c101e0e1df4 | ShridharShanbhag/Tic-Tac-Toe | /tic_tac_toe.py | 4,794 | 3.515625 | 4 | import pygame
pygame.init()
win=pygame.display.set_mode((600,700))
pygame.display.set_caption("TIC TAC TOE")
run=True
(a,w,a11,a12,a13,a21,a22,a23,a31,a32,a33)=(180,30,' ',' ',' ',' ',' ',' ',' ',' ',' ')
class coin:
def __init__(self,face1,face2):
self.face1=face1
self.face2=face2
def switch(se... |
2bbc9e8f48b191ed18f803c055ee4cffc0f4afa9 | wenduzi/Simple-Code-Example | /OS-SYS/more.py | 400 | 3.9375 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
def more(text, numlines=2):
lines = text.splitlines()
while lines:
prelines = lines[:numlines]
lines = lines[numlines:]
for line in prelines: print(line)
if lines and str(input('More?')) not in ['Y', 'y']:
break
if _... |
8b2620158edf39a6d3c89e6a9f3b4d8e20b22783 | wenduzi/Simple-Code-Example | /List - Dict - File/file-char-counter.py | 631 | 3.65625 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
res = {}
with open('file') as f:
# f.read()按字符读取,不是按行。
for char in f.read().replace(' ', ''):
# get为如果没有此key则设置为0,一行语句可以取代下面的四行语句
res[char] = res.get(char, 0)+1
# if char in res:
# res[char] += 1
# else:
# r... |
dda0c823fd484b24af062b3da30a31b6c446125d | poojavarshneya/dat-chapter-1 | /labs/exercise_1/solution.py | 285 | 4.03125 | 4 | #Author: Pooja Varshneya
# Find all numbers in a list that are divisble by 33
def divisible_by_33(num):
return num % 33 == 0
def list_div_by_33(input):
output = filter(divisible_by_33, input)
return output
if __name__ == '__main__':
input = [10,20,33,5,66]
print list_div_by_33(input) |
8d99362ae417eb259c2a75eecffad24d1dd3fe5b | jgraykeyin/sprintshoppingsystem | /shop.py | 8,629 | 3.6875 | 4 | # Python Shopping System by Team 2-9
# Sprint Week Project #3 November 2020
# Program that allows users to select items from a list of available products.
# User can then choose an amount for each product until they're done shopping.
# Receipt is printed and posted to S3 bucket at the end of program.
import boto3
impo... |
bc6a96e1760badc851463cc79b9e31d7f1dd974c | sergey-byk0v/Examples_from_book | /softmax.py | 1,492 | 3.734375 | 4 | from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
def _main():
#load training data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
# placeholder for variable train size
X = tf.placeholder(tf.float32,[N... |
9d593afddfa2861b9bd45f229789932720402403 | mcalleromero/webminery_project | /clickbait_detector/data_preprocessing.py | 3,949 | 3.8125 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import pandas as pd
import spacy
class Preprocessing:
"""Preprocessing class whose purpose is to cleanse, filter and extract the news' titles features.
"""
def count_words(self, title):
"""This method counts the number of wo... |
2b2837fe3c2f932f4b99bae6ed29b10e8505c94f | soehlert/python_homework | /oehlert_x442.3_Assignment7.py | 1,328 | 4.40625 | 4 | #!/usr/bin/env python3
import sys
#########
# Q1
#########
def string_to_number(x):
"""Suppose you want to determine whether an arbitrary text string can be
converted to a number. Write a function that uses a try/except clause to solve
this problem. Can you think of another way to solve this problem?"""
... |
ef08d5868107a83d1fb75cdfd1542a7e577e0872 | Codez01/Python | /Dictionary.py | 1,856 | 4.1875 | 4 | print("1: Mathematical Operations")
print("2: Simple Bio")
option=int(input("Choose your choice : \n"))
if(option ==1):
FirstNum = int(input("please write your first number : \n"))
SecNum = int(input("please write your second number : \n"))
print("choose one of the following mathematical operations ... |
079245f64cdffd7a4b42a13f310e6f25311a7b5f | bidlocoder1422/Pesonal_OS_1.4 | /current_loc.py | 800 | 3.546875 | 4 | import requests
import json
class location:
"""returns current loc dict or city
or 1 if connection is down
"""
def return_city():
send_url = 'http://freegeoip.net/json'
try:
answer = requests.get(send_url)
sort = json.loads(answer.text)
except Excep... |
135ee53bb225338a3f562c843de20f94d030f8f9 | yzzjohn/python_learning | /table_print_chapter_6.py | 1,521 | 4.1875 | 4 | #! Python3
# a table printing script for text in Chapter 6
# check if any content in the table data
def check_content(items, column, raw):
try:
items[column][raw]
return True
except IndexError:
return False
def print_table(items, columns, raws, col_widths):
# draw the table
for... |
8f8d6f7cd3e6622d3a3250b453cb874dbb9b20b5 | yzzjohn/python_learning | /dungeon_chapter_5.py | 1,199 | 3.984375 | 4 | #! Python3
# Test Chapter 5
# initialize your items in pocket and the loot for defeating a dragon
your_item = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# a function to display player's currrent items
def display_inventor... |
654ae80b417fe187481d30e6f10c975c7c90074a | mg-blvd/Kattis_Solutions | /Nasty_Hacks.py | 324 | 3.59375 | 4 | import sys
amount = int(input())
for i in range(amount):
nums = input().split()
no_ads = int(nums[0])
net_ads = int(nums[1]) - int(nums[2])
if no_ads > net_ads:
print('do not advertise')
elif net_ads > no_ads:
print('advertise')
else:
print('does not matter... |
974f5262e25c6560873c5fe9648631a95b8b61e3 | mg-blvd/Kattis_Solutions | /HelpAPHDCandidateOut.py | 288 | 3.828125 | 4 | def add_nums(equation):
divider = equation.index('+')
print(int(equation[:divider]) + int(equation[divider + 1:]))
sets = int(input())
for i in range(sets):
equation = input()
if '+' in equation:
add_nums(equation)
else:
print("skipped")
|
9baef606e422037128325410cc213c3819bb29b2 | mg-blvd/Kattis_Solutions | /HeartRate.py | 268 | 3.5625 | 4 | times = int(input())
for i in range(times):
beats, time = input().split()
beats = float(beats)
time = float(time)
t = 60 / time
bpm = 60 * beats / time
print("{0:.4f}".format(bpm - t),"{0:.4f}".format(bpm), "{0:.4f}".format(bpm + t))
|
77eb6ab35b26797cb20b9075f109e47bcf01cf9e | mg-blvd/Kattis_Solutions | /SimonSays.py | 185 | 3.6875 | 4 | steps = int(input())
for i in range(steps):
directions = input()
if len(directions) > 10:
if directions[:10] == "Simon says":
print(directions[11:])
|
398ed97bad64d92c995e7eee1d75a8002e7db8ee | mg-blvd/Kattis_Solutions | /TheAmazingHumanCannonball.py | 657 | 3.921875 | 4 | from math import cos, sin, radians, pow
def find_time(distance, angle, velocity):
divisor = velocity * cos(radians(angle))
return distance / divisor
def find_height(velocity, time, angle):
lhs = velocity * time * sin(radians(angle))
rhs = pow(time, 2) * 9.81 / 2
return lhs - rhs
sets =... |
e9005a630bc7f6eca5cff88a56df6a70d2639387 | mg-blvd/Kattis_Solutions | /Herman.py | 96 | 3.75 | 4 | import math
radius = int(input())
print((radius ** 2) * math.pi)
print((radius ** 2) * 2)
|
9ca99d11a96b903dcd261d07ee822d2cdaa56c71 | mg-blvd/Kattis_Solutions | /Tri.py | 873 | 3.734375 | 4 | def check_first(num):
if num[1] + num[2] == num[0]:
print(f"{num[0]}={num[1]}+{num[2]}")
elif num[1] * num[2] == num[0]:
print(f"{num[0]}={num[1]}*{num[2]}")
elif num[1] - num[2] == num[0]:
print(f"{num[0]}={num[1]}-{num[2]}")
elif num[1] / num[2] == num[0]:
print... |
949601403ecba00a7b5c805d9249fb1af4730f6e | mg-blvd/Kattis_Solutions | /JudgingMoose.py | 244 | 3.765625 | 4 | tines = input().split()
for i in range(2):
tines[i] = int(tines[i])
tines.sort()
if tines == [0, 0]:
print("Not a moose")
elif tines[0] == tines[1]:
print(f"Even {tines[0] * 2}")
else:
print(f"Odd {tines[1] * 2}")
|
7e480c8782957f84fac9d46a39f86581b0ff65ca | mg-blvd/Kattis_Solutions | /cudoviste.py | 770 | 3.6875 | 4 | rows, columns = input().split()
parkingSquishes = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0
}
row1 = input()
for rowNum in range(1, int(rows)):
row2 = input()
for columnNum in range(int(columns) - 1):
numOfCars = 0
buildingInWay = False
spacesToTake = row1[... |
6876219ba07f08940fb2a816d2c0991f85fb3c54 | mg-blvd/Kattis_Solutions | /RacingAroundTheAlpahabet.py | 855 | 3.859375 | 4 | # in progress
space_size = 60 / 28
def getLetterValue(letter):
if letter == ' ':
return 27
if letter == "'":
return 28
return ord(letter) - ord('A') + 1
def getSpacesAway(firstLetter, secondLetter):
letter1 = getLetterValue(firstLetter)
letter2 = getLetterValue(second... |
0f7957eadc1ac409b060c29c14ccf614d4125437 | mg-blvd/Kattis_Solutions | /Trik.py | 419 | 3.75 | 4 | positions = [1, 0, 0]
moves = input()
def switch_places(char):
if char == "A":
positions[0], positions[1] = positions[1], positions[0]
elif char == "B":
positions[1], positions[2] = positions[2], positions[1]
elif char == 'C':
positions[0], positions[2] = positions[2], posi... |
8fdf54ccec4a8e5c3db571d55b3e879deb4603fd | mg-blvd/Kattis_Solutions | /Mjehuric.py | 446 | 3.65625 | 4 | #work in progress
def print_list(list):
for i in range(5):
if i == 4:
print(list[i])
else:
print(list[i], end=' ')
order = list(map(int, input().split()))
while sorted(order) != order:
for i in range(5):
if order[i] > order[i + 1]:
place... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.