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 |
|---|---|---|---|---|---|---|
37ab9d9a9345b725e1e5f677008c7c2e23b6b26d | david8801/Algorythms1 | /sortLedders.py | 3,001 | 3.671875 | 4 | from timeit import default_timer as timer
from copy import copy
start = timer()
counter = 0
class Ledder:
def __init__(self, producer, max_length, max_weight, material):
self.producer = producer
self.max_length = int(max_length)
self.material = material
self.max_weight = int(max_w... |
a38dfe882914cdf1237e4e9cdc6d46e0b220877f | pyroRocket/Python | /Python101/Strings.py | 239 | 3.65625 | 4 | # Strings
# Use Double quotes:
print("Hello World!")
# Or single quotes:
print('Hello World!')
# But not both
# Dont do this: print("Hello world')
# Multi Line strings use 3 double quotes:
print("""This is a
Multi-line string""")
|
3674c62c670327d324a08a2bb13a6cc111b9b973 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab4Problem4.py | 1,143 | 4.34375 | 4 | __author__ = 'Michele'
#How to test either a string or numeric
#Initial age question and valid entry test
age = int(input('Enter the child\'s age: '))
BooleanValidAge = age <= 200
#Is age entry valid
while BooleanValidAge == False:
print('Invalid entry. Please re-enter a valid age for the child.')
ag... |
d6367e97e6ccaf962e55a12019ff4d57ae1e2423 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab4Problem1.py | 689 | 3.703125 | 4 | __author__ = 'Michele'
Midterm = int(input('Enter student\'s midterm score: '))
Final = int(input('Enter student\'s final exam score: '))
Difference = Final - Midterm
BonusTotalScore = Midterm + Final + 5
if Difference < 20:
TotalScore = Midterm + Final
print('Your total score for the course is ', Tota... |
2c330237b90116e7f55075a360f4290fe334d533 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab9Problem3.py | 2,927 | 4.375 | 4 | __author__ = 'Michele Johnson'
# Write a program to play the rock-paper-scissors game.
# A single player is playing against the computer.
# In the main function, ask the user to choose rock, paper or scissors.
# Then randomly pick a choice for the computer.
# Pass the choices of the player and the computer to ... |
ba9e9753af0ce41ee2b220db1dc202677a8d73e7 | mischelay2001/WTCIS115 | /PythonProjects/CIS115PythonProjects/Lab5Problem1.py | 1,570 | 4.25 | 4 | __author__ = 'Michele'
print('It is time to select your health plan for the year.')
print('You will need to select from the table below:')
print('')
print('Health Plan Code Coverage Premium')
print('E Employee Only $40')
print('S ... |
bcf304cfe8697c4f190d9c51c1a6277a546d7010 | vlrieg/rosalind-code | /bioinformatics-stronghold/recursive-seq-text.py | 883 | 3.6875 | 4 | #!/anaconda3/bin/python3
# https://oeis.org/A204631
# solutions:
# http://saradoesbioinformatics.blogspot.com/2016/06/mortal-fibonacci-rabbits.html
# https://stackoverflow.com/questions/17310051/fibonacci-rabbits-dying-after-arbitrary-of-months
# https://www.khanacademy.org/computing/computer-science/algorithms/recur... |
e7ebd4014751019ade82e46ca89c8c42b2a42960 | vlrieg/rosalind-code | /bioinformatics-stronghold/fibd-simplified-firststep.py | 1,044 | 3.59375 | 4 | #!/anaconda3/bin/python3
# http://rosalind.info/problems/fibd/
# sequence for m = 5: https://oeis.org/A204631
# solution: http://saradoesbioinformatics.blogspot.com/2016/06/mortal-fibonacci-rabbits.html
#problems encountered in solving this question:
# 1) figuring out the recursive algorithm (see solution link above... |
e850440f7f3c0f5056ea964a49b80a3d8ea261c1 | AnEvilCabbage/Host-Discovery | /portchecker.py | 257 | 3.53125 | 4 | #!/usr/bin/python
import socket
ip = raw_input("Enter Target IP: ")
port = input("Enter Target Port: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if s.connect_ex((ip, port)):
print "Port", port, "is closed"
else:
print "Port", port, "is open"
|
e56961de6c7ba64b8e535813fb083f60f0a0423a | sivalavinod/practice | /hcl.py | 845 | 3.8125 | 4 | # n=6
# name="vinod"
# res=name*12
# l=[]
# print(l)
# a=l.append(res)
# print(l)
#with open(r"vinod/kumar/sivala",'r') as v:
# print(v.read())
#OUTPUT::::::::::::
#hello every one
# with open(r"C:\Users\vinu\Desktop\Empty\nothing\hello.txt") as vp:
# print(vp.read())
# OUTPUT::::::::::
# helloooooooooooo
#... |
9064ac7da7fdd4590c08c13fb788042b9d9ae21d | ForrestMccrosky/time-series-exercises | /time_prepare.py | 2,104 | 3.78125 | 4 | import numpy as np
import seaborn as sns
import datetime
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
########################################## Prepare Function File #################################
def make_time(df):
'''
This function is set up t... |
6ada85f20cdb23622af24f5a146823b12742b04a | mawenbinzz/Newfish | /xAyB.py | 520 | 3.59375 | 4 | #!/usr/bin/env python3
from collection import Counter
def sameNum(fst,sec):
"""
calculate same and different nums
"""
length = min(len(fst),len(sec))
x = 0
for index in range(length):
if fst[index] == sec[index]:
x += 1
z = sum((Counter(fst) & Counte... |
1f6d6cf624485580ec6fd90132ed217062db0151 | SSJ007/Week1 | /Week4/tree_traversals_iterative.py | 3,010 | 3.90625 | 4 | from collections import deque
class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
def insert(self, node):
if self.key > node.key:
if self.left is None:
self.left = node
... |
a56f679f3f1d19d664ac2d1793760fb7780fa869 | SSJ007/Week1 | /Week7/Validate Binary Search Tree.py | 438 | 3.59375 | 4 | class Solution:
def isValidBST(self, root):
stack = []
nodes = []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
return True
right_root = stack.pop()
if nodes and right_root.val ... |
fdbcae0f9ee8c6ce10799ec3085337aed336dbb7 | GabrielFiel/CursoemVideo-Python | /ex012.py | 163 | 3.625 | 4 | preco = float(input('Digite o preço do produto: \n'))
precoDesconto = preco * 0.95
print('O preço do produto com desconto é R${:.2f}.'.format(precoDesconto))
|
67b370c4d3e988eddac70648fe04a0b0f47a86d6 | GabrielFiel/CursoemVideo-Python | /ex008.py | 253 | 3.78125 | 4 | num = float(input('Digite um valor em metros: \n'))
centimetros = num * 100
milimetros = centimetros * 10
print('=' * 20)
print('Esse valor em centímetros é {:.2f}'.format(centimetros))
print('Esse valor em milímetros é {:.2f}'.format(milimetros))
|
7c685c14355d58450a8f73c856e194a0fc197ffb | HunterBarrows/UH_Summer2021_CIS2348 | /Homework1/Zylab 5.22.py | 1,177 | 3.625 | 4 | # Hunter Barrows 1550107
# Zylab 5.22 Automobile service invoice
# service menu
print('Davy\'s auto shop services')
print('Oil change -- $35')
print('Tire rotation -- $19')
print('Car wash -- $7')
print('Car wax -- $12')
print()
menu1 = {'Oil change': 35, 'Tire rotation': 19, 'Car wash': 7, 'Car wax': 12}
... |
f65da41c4a3a6ff79559c81ade1ea21f31294513 | HunterBarrows/UH_Summer2021_CIS2348 | /Homework1/Zylab 3.19.py | 795 | 4.03125 | 4 | # Hunter Barrows 1550107
# Zylab 3.19 Painting a Wall
# Prompt User
import math
Height = int(input('Enter wall height (feet):\n'))
Width = int(input('Enter wall width (feet):\n'))
Wall_Area = Height * Width
print('Wall area:', Wall_Area, 'square feet')
# Gallons of Paint Needed
Gallon = 350
pa... |
104a40016adc3126fac83fcd8f47ed9809d76d38 | NeuroLaunch/Metis_Submissions | /Project2_Week02_Luther/IMDbSuite.py | 6,787 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utility functions for scraping from IMDb.com w/ Beautiful Soup.
For Metis Weeks 2-3, Project Luther.
@author: Steven Bierer
Created on Sun Oct 7 12:19:54 2018
"""
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
import time
from datetime i... |
bcdabc8a0691cf97df478322a973bf4160478b4a | Piggyknight/quant_invest | /currency_db_search.py | 4,492 | 3.671875 | 4 | # -*- coding:utf-8 -*-
from typing import List
from currency_db import *
import sys
def _validate(db: List[CurrencyRow], start_idx: int, back_count: int) -> int:
# 1.1 safe check db is empty
if 0 == len(db):
print("[Search]Error: db is empty")
return -1
# 1.3 don't support back_count is ... |
87d41262544d257e29a0e0e438150be0f893da62 | BenHighsted/ComputerInfoUI | /ComputerInfoUI.py | 1,053 | 3.515625 | 4 | """
ComputerInfoUI project. Plan is to make a interface where I can display all the information about my CPU/GPU.
By Ben Highsted. Started April 15th 2020.
"""
import psutil
import platform
import os
import time
import string
#At the moment just want to get all the data working in a terminal app, then convert it i... |
eeeaf82f862a44ce16617b2306bae569ba836771 | jaelyangChoi/CodingTest | /_syntax/lib/defualt_dict.py | 438 | 3.78125 | 4 | from collections import defaultdict
d = defaultdict(list)
print(d[1]) # []
d[1].append("first")
print(d[1]) # ['first']
d[1].pop()
print(d[1]) # [] 리스트는 이미 생성되어 버렸다.
"""초기값이 주어지지않을때만 default값으로 생성"""
# print(d[2][0]) #error 빈 리스트니까..
d[2] = "new"
print(d[2]) # 참조값을 리스트가 아닌 문자열로.
print(d.items()) # dict_items([(1,... |
63aa2d207a4b7ca6d68276e6716e51a6f3711ab3 | jaelyangChoi/CodingTest | /sort/[계수 정렬].py | 687 | 3.53125 | 4 | # 계수 정렬(Counting Sort) : 각각의 데이터가 총 몇 번 등장하는지 갯수를 센다. O(N+K)
# 데이터의 크기 범위가 제한(K)되어 정수 형태로 표현할 수 있을 때만 사용 가능
# 동일한 데이터가 여러 번 등장하며 데이터 범위가 크지 않을 때 효과적!
# 모든 원소의 값이 0보다 크거나 같다고 가정
array = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2]
# 모든 범위를 포함하는 리스트 선언 (모든 값은 0으로 초기화)
count = [0] * (max(array) + 1)
for i in range(len(a... |
50f77fa628839fa1a9f372d36adce54dabc0a361 | jaelyangChoi/CodingTest | /sort/[퀵 정렬].py | 1,739 | 3.59375 | 4 | # O(NlogN)
# 퀵 정렬 - 기준보다 큰 데이터와 작은 데이터의 위치를 바꿈 (최악의 경우 O(N^2)
def quick_sort(array, start, end):
if start >= end: # 원소가 1개인 경우 종료
return
pivot = start
left = start + 1
right = end
while left <= right:
# 피벗보다 큰 데이터를 찾을 때까지 반복
while left <= end and array[left] <= array[pivot]:... |
ac4c160347ea4e78ff46a3a55bfa4d14dd804e55 | jaelyangChoi/CodingTest | /기타/a^b.py | 601 | 3.703125 | 4 | a, b = 10, 3
# O(b)
ans = 1
for _ in range(b):
ans *= a
print(ans)
# O(logb) 분할정복을 이용한 방법
# b가 짝수일 때, 홀수일 때 다르게 나뉨.
def calc(a, b):
if b == 0:
return 1
elif b % 2 == 0:
temp = calc(a, b // 2)
return temp * temp
else:
return a * calc(a, b - 1)
print(calc(3.141592, 3))
... |
918083509bf3e60b73f3f12f7169abfd1487d15e | EtienneBrJ/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 200 | 3.875 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for ligne in matrix:
for col in ligne:
print("{:d}".format(col), end=" " if col != ligne[-1] else "")
print()
|
c3bec77407894ad0425a6c44b57733ff67beb1d7 | EtienneBrJ/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 2,210 | 4.21875 | 4 | #!/usr/bin/python3
""" Module Square
"""
from models.rectangle import Rectangle
class Square(Rectangle):
""" Square class inherits from Rectangle
"""
def __init__(self, size, x=0, y=0, id=None):
""" Initialize an instance square from the class Rectangle.
"""
super().__init__(size, ... |
408e98d191d79c5d3106b35bc6bd7bde0158e073 | EtienneBrJ/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_square.py | 2,020 | 3.890625 | 4 | #!/usr/bin/python3
"""Unittest for Rectangle class
"""
from models.square import Square
from models.rectangle import Rectangle
from models.base import Base
import unittest
class test_Square (unittest.TestCase):
"""Unittest class Square
"""
def test_rect(self):
"""Unittest:
Does Square ... |
a79d589999ec8780f062fd6a351dc66ed0d2d4e8 | Lasoko/gr3PSI | /cw2/zad5.py | 578 | 3.8125 | 4 | class Calculator:
@staticmethod
def add(liczba1, liczba2):
return liczba1 + liczba2
@staticmethod
def difference(liczba1, liczba2):
return liczba1 - liczba2
@staticmethod
def multiply(liczba1, liczba2):
return liczba1 * liczba2
@staticmethod
def divide(liczba1,... |
28ec6557d0b6fc57b585aa61795c9259a4d4e714 | atfelix/exercism-python | /bracket-push/bracket_push.py | 544 | 3.890625 | 4 | def is_paired(string):
starting_pairs = {
'[': ']',
'(': ')',
'{': '}'
}
ending_pairs = {
']': '[',
')': '(',
'}': '{'
}
stack = []
for char in string:
if char in starting_pairs:
stack.append(char)
elif stack and char in... |
ccd42ff60c61673b3f4917c13985daf47ddf7135 | atfelix/exercism-python | /say/say.py | 2,634 | 3.796875 | 4 | def say(number):
number = int(number)
if not is_valid(number):
raise ValueError('Unexpected input value: input must be between 0 and 999,999,999,999 inclusively')
if number == 0:
return 'zero'
billions_string = billions(number)
millions_string = millions(number)
thousands_s... |
5439111b0711989d5a86f159609571c17e3a5b5d | atfelix/exercism-python | /robot-name/robot_name.py | 1,127 | 3.578125 | 4 | import random
class PatternGenerator(object):
InvalidPatternCharacterError = ValueError('Pattern character no recognized: Expecting \'a\' or \'#\', given \'%c\'')
def __init__(self, pattern):
self.generator = random.Random()
self.pattern = pattern
def name(self):
map_functio... |
9e4ec601eb575911e8be1c38ff4ac18a61690185 | atfelix/exercism-python | /rna-transcription/rna_transcription.py | 385 | 3.671875 | 4 | from functools import reduce
def to_rna(dna_strand):
if is_not_valid(dna_strand):
raise ValueError
return replace(dna_strand, {'C': 'G', 'G': 'C', 'T': 'A', 'A': 'U'})
def is_not_valid(dna_strand, alphabet='ACGT'):
return any(ch not in alphabet for ch in dna_strand)
def replace(string, dictionar... |
19436c47d89d52e1b4ffeb44ce9c03d82e43f8bd | devSchnitzel/python | /src/preg.py | 932 | 3.859375 | 4 | '''
python 正则
pattern = re.compile(r'\d+[^\d]*\d+')
# match,匹配字符串的开头(必须是起始位置),如果无法匹配或者到达末尾则返回None
string = '123fdadfa123'
result = re.match(pattern,string)
print(result)
print(result.group())
string = 's123fdadfa123'
result = re.match(pattern,string)
print(result)
# search 和match类似,只不过search会扫描查找整个字符串,并非必须要从头开始... |
0bb096d593ed6b2cd3f3a039b13e38a689938f8d | devSchnitzel/python | /old/test.py | 747 | 3.65625 | 4 | def func(list):
list[0] = 'test'
return list
list = [1, 2, 3]
# list是引用传值,如果直接传入list,里面的值被改掉的话,list本身也会被更改
print(func(list))
print(list)
# 使用[:]可取消list修改
print('=============================')
list2 = [1, 2, 3]
print(func(list2[:]))
print(list2)
### 多参数传递
def func1(test, *tupleP... |
fd652e217183b18d19d847a8a8ad2a10f45cdf1e | devSchnitzel/python | /src/condition/bool.py | 418 | 3.90625 | 4 | '''
bool假比对,其它则为真
# False 0 None {} [] () "" 0.0(浮点型)
if 0.0:
print('true')
else:
print('false')
if []:
print('true')
else:
print('false')
if () or {}:
print('true')
else:
print('false')
# 将其它值转换为bool
print(bool(0.2))
# is来判断两个对象是否相同,即同址
x = y = list('string')
z = list('string')
pr... |
f6a1dd3f918fd65332a29594eb63d6a257d9358c | zcutlip/WithTimer | /withtimer/withtimer.py | 2,412 | 3.609375 | 4 | from __future__ import absolute_import
from __future__ import print_function
from timeit import default_timer
class Timer(object):
timer_stack = []
max_depth = 0
timing_enabled = False
def __init__(self, name=None):
"""
Create a Timer object. If timing is enabled, the timer starts on ... |
4352db4d5bcc2873dcb947c49f35763beb61d84c | MartinHowarth/est8 | /tests/test_backend/test_street.py | 12,804 | 3.59375 | 4 | """Tests for the Street class."""
import pytest
from est8.backend.errors import (
FencePlacementError,
HousePlacementError,
BisPlacementError,
)
from est8.backend.definitions import NeighbourhoodDefinition
from est8.backend.house import House
from est8.backend.street import Street
@pytest.fixture()
def ... |
80300b3641b89451921a76681aae4f5c9dda8d37 | tharakkrishnan/simpledb | /simpledb.py | 6,990 | 3.640625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*
"""Simple in-memory database
This module implements a simple in-memory database using a dictionary.
It implements the following DATA commands:
SET name value – Set the variable name to the value value.
Neither variable names nor values will contain spaces.
GET na... |
d21fc72f0f6e63c27c29861b3ccfe9efedda2d61 | kieczkowska/CTF_scripts | /colours.py | 832 | 4 | 4 | # colours.py facilitates conversion between the hex RGB format to dec and binary
# a hex number in the format #RRGGBB to decimal
def hex_to_dec(col):
answer = []
answer.append(["red", int(col[1:3], 16)])
answer.append(["green", int(col[3:5], 16)])
answer.append(["blue",int(col[5:7], 16)])
return an... |
24dc49bd4c9ff2656eddac100b1d495a1394cde5 | GokoshiJr/algoritmos2-py | /src/algoritmos-ordenacion/propuestos/repetido.py | 534 | 3.75 | 4 | # Se desea eliminar todos los numeros duplicados de una lista o vector
# Por ejemplo si toma los valores [4,7,11,4,9,5,11,7,3,5]
# Ha de cambiarse a [4,7,11,9,5,3]
def eliminar(numArray: list) -> list:
largo = len(numArray)
unicos = list()
for i in range ((largo - 1), -1, -1):
if (numArray[i] not in ... |
308ea5c0e2acca3d87e8e9390843aa9905d03e26 | GokoshiJr/algoritmos2-py | /src/modular/restas.py | 685 | 3.65625 | 4 | # 5. Encuentre el cociente y el residuo de dos números mayores a cero dados en base a restas
# sucesivas. Ejemplo: Si A = 435 y B = 21 → Cociente = 20 y Residuo = 15
num1 = int(input('Ingrese A: '))
num2 = int(input('Ingrese B: '))
def division(numerador, denominador):
temp = numerador
cociente = re... |
5786dc99f7a6cb6df7c04b09633ab9e761ddbc39 | GokoshiJr/algoritmos2-py | /src/modular/contar.py | 242 | 3.90625 | 4 | # 2. Contar la cantidad de dígitos que tiene un número.
num = int(input('Ingrese un numero: '))
contador = 0
aux = num
while (aux > 0):
aux //= 10
contador += 1
print('Su numero tiene ', contador, 'digitos.')
|
64c8a33693b8db0533a3baa275c47a7d4b8e8e38 | GokoshiJr/algoritmos2-py | /src/modular/invertir.py | 246 | 4.125 | 4 | # 3. Invertir un numero
numero = int(input('Ingrese un numero: '))
digito = result = 0
aux = numero
while (aux > 0):
digito = aux % 10
result = (result * 10) + digito
aux //= 10
print('Su inverso es:', result)
|
afc7ec3b8c23aef0f5f50f120d2a8f4d6967109b | killercatfish/chatbot | /learning/test4.py | 707 | 3.5625 | 4 |
log_length = 0
previous_length = 0
with open('/Applications/tmp/mylog.txt', 'r') as file:
lines = file.readlines()
log_length = len(lines)
previous_length = log_length
# print("length: " + str(log_length))
# print("last line: " + lines[len(lines)-1])
while True:
with open('/Applications/tmp/my... |
9db67faec01695982a7b561d1e32423782776dd9 | Govindkm/password_generator | /password_generator.py | 2,676 | 3.796875 | 4 | """
For running this module you need to install random_word package
You should be able to install using easy_install or pip in the usual ways:
$ easy_install random-word
$ pip install random-word
Or just clone this repository and run:
$ python3 setup.py install
Or place the random-word folder that you downloaded so... |
4b1c629bb724f1876a8ce4778e2bee6343a74464 | LuiArroyo/Homework-3 | /main zyLab10.11.py | 1,492 | 3.921875 | 4 | # Luis Arroyo
# PSID: 2037081
# CIS 2348
class FoodItem: # TODO: Define constructor with parameters to initialize instance # attributes (name, fat, carbs, protein)
def __init__(self, foodname='None', gramsfat = 0.0, gramscarbs =0.0, gramsprotein = 0.0):
self.name = foodname
self.fat = gramsf... |
0e64bca7387895049932233134b3468547bb2db4 | jamacias/Dice | /dice.py | 6,545 | 3.78125 | 4 | #This program aims to throw a dice and the user has to guess the number
#To Do:
# -Menu (play, view log, delete log, change user, difficulty, activate advises)
# -Read log lastlines maybe(?)
# -Multiuser implementation with stadistics stored in files
# Ability to change user in a season, store what user is playing i... |
3652ebb7e587c0744c3f4cdb098cd9392c5fe65d | mzabary/PyProjects | /ForestHouse/calctax.py | 1,610 | 3.734375 | 4 | import os
from tkinter import *
from tkinter.messagebox import *
import sys
n1=0
n2=0
def show_answer():
n0 = int(tax_rate.get())
n1 = int(gross_income.get())
Ans = round((n1 / ((n0 / 100) + 1)), 2)
Ans = round((n1-Ans),2)
total_tax.insert(0,Ans)
main = Tk()
RTitle=main.title("... |
02b48c73e7f1a9899a70e62b6e1186431750bceb | namcent/TorneoTiro | /main.py | 2,478 | 3.796875 | 4 | from clases import Disparo, Concurso, Participante
print(" ______ __ _______ ")
print(" /_ __/__ _______ ___ ___ ___/ /__ /_ __(_)______ ")
print(" / / / _ \/ __/ _ \/ -_) _ \ / _ / -_) / / / / __/ _ \ ")
print(" /_/ \___/_/ /_//_/\__/\___/ \_,_/\__/ /_/ /... |
366b54996d3152ac7bee13e218f167480699acd8 | rutujak24/crioTryout | /swapCase.py | 707 | 4.4375 | 4 | You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
'''For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
Input Format
A single line containing a string
.
Constraints
Output Format
Print the modifie... |
c3c642e2e74474bf201270001d7521650b720924 | tulu1688/MLCourses | /HandOnML/P02_Regression/regression_template.py | 1,412 | 3.796875 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('data.csv')
# X must be matrix not a vector. So we need to specify the range of collumn [1:2]
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:,... |
ebccce0daa22f5f37a06b778f7d5b9b8c297bbc0 | sean-m-higgins/financials | /src/python/tutorials.py | 1,592 | 3.5625 | 4 | import yfinance as yf
import pandas as pd
import pandas_datareader.data as web
import datetime
# ------------------------------------------------------------------------------------------
# SOURCE: https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75
# Historical data example:
# #define the... |
013fa2de563fa0d5704df5fdc758e4a259802733 | alan-nguyen/hackerrank | /02-algorithms/09_pickingNumber.py | 354 | 3.640625 | 4 | def pickingNumbers(a):
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
max = 0
for i in a:
c = a.count(i)
d = a.count(i - 1)
c = c + d
if c > max:
max = c
return max
# test case
a = [1, 1, 2, 2, 4, 4,... |
ce0519d312edf301fa0cbf225ac601a1ef141549 | alan-nguyen/hackerrank | /02-algorithms/17_catAndMouse.py | 348 | 3.671875 | 4 | def catAndMouse(x, y, z):
catA = abs(x - z)
catB = abs(y - z)
if catA > catB:
return 'Cat B'
elif catA < catB:
return 'Cat A'
else:
return'Mouse C'
# test case
print(catAndMouse(6, 1, 4)) # Should be Cat A
print(catAndMouse(1, 5, 4)) # Should be Cat B
print(catAndMouse(3,... |
4143c5b2932b8ba4afee1f960571eee01f3b2aae | alan-nguyen/hackerrank | /01-python/011_splitAndJoin.py | 257 | 4 | 4 | def split_and_join(line):
"""Split and join string with - """
line_split = line.split(" ")
line_join = "-".join(line_split)
return line_join
# test case
line = 'this is a string'
print(split_and_join(line)) # should be "this-is-a-string" |
d3c7223f8b8e3412f225d39d5cf7da58d924d53f | BastianKD/LPTHW | /EX40/ex40.py | 874 | 3.71875 | 4 | class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_p... |
8ff7b71954d5efa383b4422fbc99444d79834f1a | LeonardoSaid/uri-py-solutions | /submissions/1179.py | 570 | 3.5 | 4 | def printapar(a):
for i in range(0, len(a)):
print("par[%d] = %d" % (i, a[i]))
def printaimpar(a):
for i in range(0, len(a)):
print("impar[%d] = %d" % (i, a[i]))
par = list()
impar = list()
for i in range(15):
x = int(input())
if x % 2 == 1:
if len(... |
fcd45042b397c3fd5d3c2009a394807a3bdf8735 | LeonardoSaid/uri-py-solutions | /submissions/1029.py | 453 | 3.671875 | 4 | #fast fib using memorization (https://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series)
def fib(n, computed = {0: 0, 1: 1}):
if n not in computed:
computed[n] = fib(n-1, computed) + fib(n-2, computed)
return computed[n]
def fib_numcalls(n):
return 2*fib(n+1... |
507bc990c31585684e9e4a31d0ed099d07955a89 | LeonardoSaid/uri-py-solutions | /submissions/1866.py | 149 | 3.59375 | 4 | n = int(input())
while n > 0:
x = int(input())
if x % 2 == 1:
print(1)
else:
print(0)
n -= 1 |
b32531fbaacea524209d89654f74a8bf8770c5e4 | LeonardoSaid/uri-py-solutions | /submissions/1180.py | 176 | 3.609375 | 4 | n = int(input())
asd = list()
s = input().split()
for i in s:
asd.append(int(i))
print("Menor valor: %d" % min(asd))
print("Posicao: %d" % (asd.index(min(asd))) ) |
a14c5a0c660b421fd79e09766fcd924bd76b60c6 | hoang-ph/Othello-with-Python-Processing | /Othello/computer.py | 2,964 | 4.25 | 4 | class Computer:
"""A class represent AI's move for Othello game"""
def __init__(self, board, game_controller, tile_color):
self.gc = game_controller
self.board = board
self.tile_color = tile_color
self.legal_moves = []
def place_tile(self):
"""
:rty... |
d6986108f39f829c52df06de73815767db6ff1bb | miwiwa/python-projects | /Practice_Python/oddeven-2.py | 230 | 4.03125 | 4 | userNum = input("Please enter a number: ")
if int(userNum) % 4 == 0:
print(userNum + " is a multiple of 4")
elif int(userNum) % 2 == 0:
print(userNum + " is an even number")
else:
print(userNum + " is an odd number")
|
418096d15f163828f2810bc6f14c4db475448460 | kikikikikikikiki/fractal-lump | /1/fract.py | 2,258 | 3.765625 | 4 | import pygame
import math
pygame.init() # prepare the pygame module for use
# Create a new surface and window.
surface_size = 900
main_surface = pygame.display.set_mode((900,800),pygame.HWSURFACE+pygame.DOUBLEBUF+pygame.FULLSCREEN)
my_clock = pygame.time.Clock()
def draw_tree(order, theta, theta... |
2da50a0899066599e9beeede2263067519d7a19b | minalchaudhari5695/PythonTutor | /list_exercise1.py | 394 | 3.859375 | 4 | """ list exercise"""
__author__='minal'
__version__=1.0
def main():
count=0
strlist=['abc','mam','aa','asda','a','121']
print 'the number of strings having length greater than 1 and first and last letter must be same\n'
print strlist
for i in strlist:
if len(i)>1 and i[0]==i[-1]:
... |
71c78d7935a915ca4a7ceb4a71bba760622f2c3d | Duclearc/turtle-crossing | /main.py | 1,229 | 3.640625 | 4 | import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
# Screen setup
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
# Game setup
player = Player(screen.window_height())
cars = CarManager(screen.window_height(), scre... |
f8b0cc15b14ebbd285cc454d02d06c078377ac5c | lxjlovewcx/source_code | /study/fun_pro/py_zip.py | 608 | 3.734375 | 4 | '''
Created on 2018年8月17日
@author: lixue
'''
from builtins import zip
from itertools import groupby
'''
补充几个高阶函数
zip
-把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容
往数据库丢数据经常用到
'''
l1 = [1,1,2,2,3,4,5,5]
l2 = [11,22,33,44,55,66,23,24]
z = zip(l1,l2)
print(type(z)) #<class 'zip'>
#print([ i for i in z])#[(1, 11), (2, 22), (3, 3... |
458a25db4ad8dd6910e07506709c13fef9f456da | lxjlovewcx/source_code | /study/fun_pro/py_decrate.py | 1,557 | 3.6875 | 4 | '''
装饰器(decrator)
-在不改动函数代码的基础上无限制扩展函数功能的一种机制,本质上讲,装饰器是一个返回函数的高阶函数
-装饰器的使用:使用@语法,即在每次要扩展的函数定义前使用@+函数名
任务:
对hello函数进行功能扩展,每次执行hello前打印当前系统时间
'''
import time
from tornado.test.httpclient_test import HelloWorldHandler
#高阶函数,以函数作为参数
def printtime(f):
def wrapper(*args,**kwargs):
print("time:",time.ctime... |
a3299199b3ba815029331490376dc04d24accbb1 | Nathanllee1/Transcript | /speech_to_text.py | 560 | 3.5625 | 4 | #import library
import speech_recognition as sr
import sys
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
# Reading Audio file as source
# listening the audio file and store in audio_text variable
with sr.AudioFile(sys.argv[1]) as source:
audio_text = r.record(source)
# recogini... |
e1e030f49ef32f021ccd1803c63ba88fecc4bffa | daniel-kauffman/calpoly-vue | /dist/202/p8tests.py | 1,581 | 3.78125 | 4 | # Name:
# Course: CPE 202
# Instructor: Daniel Kauffman
# Assignment: Problem Set VIII
# Term: Spring 2021
import re
import unittest
import pset8
def search(pattern: str, text: str) -> str:
"""
Given a regular expression (pattern) and string (text) to search, return
the substr... |
d24e203a534e593185599c64e76deffdc36ddd3c | daniel-kauffman/calpoly-vue | /dist/480/boardstupid.py | 9,856 | 4.25 | 4 | # Name:
# Course: CSC 480
# Instructor: Daniel Kauffman
# Assignment: Board Stupid
# Term: Spring 2021
import math
import random
from typing import Callable, Generator, Optional, Tuple
class GameState:
def __init__(self, board: Tuple[Tuple[Optional[int]]], player: int) -> None:
... |
5973c5e1af6b2527a3d8d6e64a549a6e2044dd75 | daniel-kauffman/calpoly-vue | /dist/202/pset2.py | 5,394 | 4.1875 | 4 | # Name:
# Course: CPE 202
# Instructor: Daniel Kauffman
# Assignment: Problem Set II
# Term: Spring 2021
from typing import Optional, Tuple
# do not modify this class
class StackNode:
"""
A StackNode is like a ListNode except that its ref attribute may only be
accessed in the p... |
4ce2a9d5b3396501e4f79f61c609d03e270d7225 | EvyW/salary_calculator | /test.py | 3,855 | 3.546875 | 4 | # import libraries
import unittest # testing library
import sys # import current path (allow us to call our own modules/packages)
sys.path.append('../') # append current path
from ioet_exercise import compute_employees_salary # import our own modules/packages
class testSalaryComputation(unittest.TestCase):
def ... |
df0c56a891380c0bb48bd13dc713efb0bf193cda | jay-munjapara/CSES | /Introductory Problems/Weird Algorithm/Wierd algorithm Vedant Manelkar.py | 98 | 3.75 | 4 | n=int(input())
print(n)
while n!=1 :
if n%2==0:
n=n//2
print(n)
else:
n=n*3+1
print(n)
|
121d20a4dd27cca3dc1d26d4bd4a7b8726d26d2f | zahra-zarrabi/seri_3 | /4.py | 72 | 3.65625 | 4 | a=input('Enter a sentence:')
b=a.split()
print('Number of words',len(b)) |
ab35f690af9e78ab7b94c76e15afa948b48819ae | ChrisHayduk/Gaussian-Elimination | /matrixManipulation.py | 11,059 | 3.84375 | 4 | class Matrix(object):
def __init__(self, A):
self.matrix = A
self.numRows = len(self.matrix)
if self.numRows != 0:
self.numCols = len(self.matrix[0])
#Checks if the matrix is valid
#If not, raises and handles an exception. Also returns ... |
b585acc6820a2a013d1dacf883fc961d618f78a3 | mlarva/projecteuler | /Project1.py | 743 | 4.1875 | 4 | #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.
def multipleFinder(min, max, *multiples):
multiplesSet = set()
if min >= max:
print("Minimum is not smaller than ma... |
4dfb6434289298817f1badc95cde78bb9c169a1d | fanpl-sourse/all_study_practice | /myunittest/testcase/test_unittest.py | 1,935 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/10/14 07:39
# @Author : 饭盆里
# @File : test_unittest.py
# @Software: PyCharm
# @desc :
import unittest
class TestMethods(unittest.TestCase):
@classmethod
def setUpClass(self) -> None:
print('>>>>>>>>>>>method setUpClass')
@classmethod
def tearDown... |
7b63637042f069d12fbabcbeaaebf75710accf35 | MariaLeg/LeetCode | /Array/RemoveDuplicatesFromSortedArray.py | 654 | 3.5 | 4 | #https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/
class Solution(object):
def removeDuplicates(self, nums):
if len(nums) == 0:
return 0
unique_number_index = 0
last_unique_number = nums[0]
for i in range(len(nums)):
if nu... |
81158d0977dae10e3b28102e6808ecc190017537 | MariaLeg/LeetCode | /Array/ContainsDuplicate.py | 411 | 3.828125 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/578/
from typing import List
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
s = set()
for i in nums:
if i in s:
return True
else:
s.add(... |
5911f5f7c9613b462362dabe2b40d2182104eda3 | hossnys/codescalers_training | /python101/.vscode/9_funcs.py | 823 | 3.953125 | 4 | # BASIC IDEA OF FUNCTIONS and DOMAIN -> RANGE
# SQUARE
# ABS
# IS NEGATIVE
# IS EVEN NUMBER (HANDS ON)
# FACTORIAL EXTRA ASSIGNEMENT
import string
#x={string.ascii_lowercase}
def encode ():
reslist = []
alist = input("enter your text to be encoded")
for i in alist:
u = string.ascii_lo... |
1972a58de1455540f75f504c5516bee64e75de53 | CodecoolBP/progbasics-lightweight-erp-project-csad | /accounting/accounting.py | 6,857 | 3.5625 | 4 | """ Accounting module
Data table structure:
* id (string): Unique and random generated identifier
at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters)
* month (number): Month of the transaction
* day (number): Day of the transaction
* year (number): Year of t... |
6205ce04a990b36d3a18e04968ebdadf9a62f29a | LisaVysochyn/lab-3 | /1.py | 702 | 4.15625 | 4 | """
The Fibonacci numbers are the sequence below, where the first two numbers are 1, and each number thereafter is the sum of the two preceding numbers. Write a program that asks the user how many Fibonacci numbers to print and then prints that many.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
>>> Введіть скільки чисе... |
38513a558b2fe5cd41b58a716b03c3ead022ed1c | LisaVysochyn/lab-3 | /Q5.py | 472 | 3.984375 | 4 | """Write a program that asks the user to enter integer number. Then check if the number is prime.
>>>Введіть число: 3
Число є простим
>>>Введіть число: 4
Число не є простим
"""
a = int(input("Введіть число: "))
k = 0
for i in range(2, a // 2+1):
if (a % i == 0):
k = k + 1
if (k <= 0):
print(... |
ef45c74bdbd59c2ae53c74c0fa55fbb113a42c37 | samdel123/Ejercicios-1 | /Ejercicio_04.py | 367 | 4.03125 | 4 | #Palindromo de una palabra
def Palindromo():
Palabra1 = input('Ingrese una palabra:\n').lower()
Palabra2 = input('Ingrese su palindromo:\n').lower()
Reverso = Palabra1[::-1]
if Reverso == Palabra2:
print(Palabra1,'Es Palindromo de:', Palabra2)
else:
print(Palabra1,'N... |
24eb5814815445beec59914800137d12941ae87d | samdel123/Ejercicios-1 | /Ejercicio_01.py | 240 | 3.953125 | 4 | #Numero de Palabras de una Cadena de Caracteres
def contar ():
Texto = input('Ingrese una cadena de caracteres:\n')
Texto_Separado = Texto.split()
print('El Numero de palabras es:',len(Texto_Separado))
contar()
|
7f0a94a8cacbd5068799fdecbeb5befd4b792603 | rghvat/Hackerrank-python | /python-domain/Collections/ordered_dict.py | 266 | 3.734375 | 4 | from collections import OrderedDict
menu = OrderedDict()
n = int(input())
for _ in range(n):
a = input().split()
price = a.pop()
name = ' '.join(a)
menu[name] = menu.get(name, 0)+int(price)
for ele in menu:
print("{} {}".format(ele, menu[ele]))
|
6cc9fe316620418ce0492f01257d27def3acd7ad | rghvat/Hackerrank-python | /problem_solving/missing_number.py | 894 | 3.921875 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/missing-numbers/problem
import os
# Complete the missingNumbers function below.
def create_freq(arr):
freq = dict()
for ele in arr:
freq[ele] = freq.get(ele, 0) + 1
return freq
def missingNumbers(arr, brr):
first = create_freq(arr)
sec... |
998b295239426b89029c1e030b5d27fb7b297f16 | melandur/MelanomaClassification | /Augmentor/ImageSorter.py | 4,182 | 3.671875 | 4 | import os
import errno
import csv
import shutil
class ImageSorter:
"""
Copies the images in a new structure based on a separate folder for each class
Args:
origin_path (str): The path of the images
label_file_path (str): The CSV file, which contains the labels
t... |
8f55c63052fd78c78d42ab72105f8d8314dd0df9 | soedjais/dodysw-hg | /ProjectEuler/Problem94.py | 3,166 | 3.796875 | 4 | """
For equilateral triangle with side a
Area = a*a*0.25*3**0.5
Perimeter = 3a
For triangle with 2 equal side (Isosceles)
http://mathworld.wolfram.com/IsoscelesTriangle.html
If b is the equal side, and a is the different one:
Area = 0.5 * a**2 * (b**2/a**2 - 0.25)**0.5
this is also called heronian triangle
http://en.... |
e439bcc4865fed706c517365096febaeb83bfea4 | soedjais/dodysw-hg | /ProjectEuler/Problem31.py | 636 | 3.53125 | 4 | coins = [200,100,50,20,10,5,2,1]
target = 200
combination = []
stack = []
def calc(lvl=0, prev_total=0):
if lvl >= len(coins):
return
for m in xrange((target/coins[lvl])+1):
total = prev_total + m*coins[lvl]
if total < target:
#print "Under target", lvl, m, total
... |
df937304b9d1bb3e93a058c337ec400f735a3399 | soedjais/dodysw-hg | /ProjectEuler/Problem91.py | 1,743 | 3.59375 | 4 | """
for 2x2:
00 10 01
00 10 11
00 10 02
00 10 12
00 20 01
00 20 11
00 20 21
00 20 02
00 20 22
00 11 01
00 21 01
00 11 02
00 12 02
00 22 02
a^2 + b^2 = c^2
00 01 10
v1,v2,v3
1, 1, sqr(2)
sorted:
00 01 10
00 01 11
00 01 12 X
00 01 20
00 01 21
00 01 22 X
00 02 10
00 02 11
00 02 12
00 02 20
00 02 21 X
00 02 22
00 1... |
433e06a43544f6f2d41e15c45f85110a46972917 | soedjais/dodysw-hg | /ProjectEuler/Problem58.py | 866 | 3.8125 | 4 | #faster to use the following prime checking function, since the number is skipped alot, and
#too big for standard sieve to store
def is_prime(i):
#only 2 is even prime
if i == 2:
return 1
if i % 2 == 0:
return 0
#skip even numbers
for t in xrange(3, int(i**0.5)+1, 2):
if i %... |
7696267a751e50ff101e20be49ae26ebf036222d | soedjais/dodysw-hg | /ProjectEuler/Problem45.py | 1,201 | 4.3125 | 4 | import math
def is_pentagonal(y):
"""
y = x(3x-1)/2.
y is the input, we need to find x, and whether it's an positive integer. Using quadratic equation, we convert to the following:
x = (-b +- sqrt(b^2-4ac))/2a
since y = x(3x-1)/2 is 1.5*x^2 - 0.5*x - y = 0, then a = 1.5, b = 0.5, c = -y
x =... |
e67486218574da5cdea0f7761231d39e6f5c8478 | memoherreraacosta/metodos_cuantitativos | /hackerrank/day1/standard_derivation.py | 301 | 3.6875 | 4 | from math import sqrt
n = 5 #int(input())
x = "10 40 30 50 20".split(" ") #input().split(" ")
x = [int(number) for number in x]
mean = sum(x)/n
square = lambda x: x*x
standard_dev = sqrt(
sum([
square(element - mean)
for element in x
])/n
)
print(round(standard_dev,1))
|
14e730e9a89c1fed3cf2dd5536f4d5c49c0d8e55 | jesseolivas/Tic-Tac-Toe | /Tic-Tac-Toe/task/tictactoe/tictactoe.py | 903 | 3.859375 | 4 | # write your code here
cells = list(input("Enter cells: "))
print("---------")
print("| " + cells[0] + " " + cells[1] + " " + cells[2] + " |")
print("| " + cells[3] + " " + cells[4] + " " + cells[5] + " |")
print("| " + cells[6] + " " + cells[7] + " " + cells[8] + " |")
print("---------")
countx = 0
counto = 0
counts =... |
81a7d56d5d4d420004bca0e924fe272c6f9351c7 | cuckooooo/OJ | /PYTHON/junior/PanDuanZiFuChuanShiWenBenHaiShiErJinZhi/src/demo.py | 894 | 3.671875 | 4 | #coding:utf-8
'''
Created on 2013-7-16
@author: l00165154
'''
'''
功能:判断字符串是文本还是二进制
输入:s 需要判断的字符串
输出:无
返回:返回一个bool类型, True/False
'''
import string
class Demo:
def istext(self, s):
#TODO
text_characters = "".join(map(chr, range(32, 127))) + "\n\r\t\b" #@IndentOk
_null_trans = strin... |
a2a0d3d7844cf935a891bd23908d9e9c89afc2df | murraymilton/RPSLS | /player.py | 722 | 3.734375 | 4 |
class Player:
def __init__(self):
self.name = ""
self.gesture_list = ["Rock", "Paper", "Scissors", "Lizard", "Spock"]
self.score = 0
self.chosen_gesture = ""
def choose_gesture_player(self):
gesture_input = input(f"{self.name} Enter your gesture")
for gesture i... |
716f41bd9010142c6fc785b2a96a4859d52fa155 | phucnguyen070995/PPL | /buoi3/Rational.py | 1,125 | 3.609375 | 4 | class Rational:
@staticmethod
def gcd(a, b):
if b == 0:
return a
else:
return Rational.gcd(b, a % b)
def __init__(self, numer = 0, denom = 1):
try:
assert denom != 0, "denom must # 0"
assert isinstance(numer, int), "numer must be Int"... |
3d8b587f07835f3449a67d8592e2918311f0a1cc | childofthefence/python_algo_ds | /reverse_words_in_string.py | 307 | 4.03125 | 4 | class ReverseWordsInAString(object):
def reverse_words(s):
"""
:type s: str
:rtype: str
"""
s = s.split(' ')
new_string = ''
for words in reversed(s):
new_string = new_string + words + ' '
new_string = new_string.strip()
return new_string
print(reverse_words('here is a test')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.