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 |
|---|---|---|---|---|---|---|
a3c81c5b91daffbd7de1fbe55e2fce7eac26cd80 | dr2moscow/GeekBrains_Education | /I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_4.py | 1,434 | 4.125 | 4 | '''
Задание # 3
Реализовать функцию my_func(), которая принимает три позиционных аргумента, и
возвращает сумму наибольших двух аргументов.
'''
def f_my_power(base, power):
base__power = 1
for count in range(power*(-1)):
base__power *= base
return 1 / base__power
try:
var_1 = float(input('Вве... |
c89455cedb014aca5fa8d634476fa9aedb2381c0 | mug-auth/ssl-chewing | /src/utilities/numpyutils.py | 2,600 | 4.03125 | 4 | from typing import Tuple, Optional, List
import numpy as np
from utilities.typingutils import is_typed_list
def is_numpy_1d_vector(x):
"""Check if ``x`` is a numpy ndarray and is a 1-D vector."""
return isinstance(x, np.ndarray) and len(x.shape) == 1
def is_numpy_2d_vector(x, column_vector: Optional[bool]... |
229ae10428cfaa24615c9c329ee3258baa93943d | YuRen-tw/my-university-code | /cryptography/c2019-p4/maxima_interface.py | 807 | 3.578125 | 4 | '''
Interact with Maxima (a computer algebra system) via command line
'''
from subprocess import getoutput as CLI
def maxima(command):
command = 'display2d:false$' + command
output = CLI('maxima --batch-string=\'{}\''.format(command))
'''
(%i1) display2d:false$
(%i2) <CMD>
(%o2) <RESULT>
'... |
ef1ebb2ba1f95a2d8c09f3dc32af9d2ffec17499 | CyberTaoFlow/Snowman | /Source/server/web/exceptions.py | 402 | 4.3125 | 4 | class InvalidValueError(Exception):
"""Exception thrown if an invalid value is encountered.
Example: checking if A.type == "type1" || A.type == "type2"
A.type is actually "type3" which is not expected => throw this exception.
Throw with custom message: InvalidValueError("I did not expect that value!")"... |
c61d5128252a279d1f6c2b6f054e8ea1ead7b2af | rup3sh/python_expr | /general/trie | 2,217 | 4.28125 | 4 | #!/bin/python3
import json
class Trie:
def __init__(self):
self._root = {}
def insertWord(self, string):
''' Inserts word by iterating thru char by char and adding '*"
to mark end of word and store complete word there for easy search'''
node = self._root
for c in string:
if c not in node:
... |
08f9852f9cf2c1ac4a5b25899e4e0afb5f1d91ff | rup3sh/python_expr | /Recursion/palindrome | 493 | 3.890625 | 4 | #!/bin/python3
def isPalindrome(word):
def extractChars(word):
chars = []
for w in word.lower():
if w in 'abcdefghijklmnopqrstwxyz':
chars.append(w)
return ''.join(chars)
def isPalin(s):
if len(s)==1:
return True
else:
return s[0]==s[-1] and isPalin(s[1:-1])
chars = extractChars(w... |
7cbfc86f3d6399973e6cd05e0a83bb4ad2f6e023 | rup3sh/python_expr | /generators/coroutine | 1,934 | 3.734375 | 4 | #!/bin/python3
import pdb
import sys
## Generators are somewhat opposite of coroutines.Generators produce values and coroutines consume value.
##Coroutines
## - consume value
## - May not return anything
## - not for iteration
## Technically, coroutines are built from generators.
## Couroutine does this -
## ... |
23f20f17dc25cc3771922706260d43751f2584c5 | rup3sh/python_expr | /generators/generator | 1,446 | 4.34375 | 4 | #!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
generatorDemo()
def list_of_even(n):
for i in range(0,n+1):
if i%2 == 0:
yield i
def generatorDemo():
try:
x = list_of_even(10)
print(type(x))
for i in x:
print("EVEN:" + str(i))
the_li... |
8fe1986f84ccd0f906095b651aa98ba62b2928b8 | rup3sh/python_expr | /listsItersEtc/listComp | 1,981 | 4.1875 | 4 | #!/bin/python3
import pdb
import sys
##Reverses words in a corpus of text.
def main(argv):
listComp()
def listComp():
the_list = ["stanley", "ave", "fremont", "los angeles", "istanbul", "moscow", "korea"]
print(the_list[0:len(the_list)])
#Slicing
#the_list[2:] = "paz"
#['stanley', 'ave', 'p', 'a', '... |
c2aeb4bc202edaf3417d097408e5c680d0ffc1c0 | maksymshylo/statistical_pattern_recognition | /lab4/trws_algorithm.py | 9,184 | 3.5 | 4 | from numba import njit
import numpy as np
@njit
def get_right_down(height,width,i,j):
'''
Parameters
height: int
height of input image
width: int
width of input image
i: int
number of row
j: int
number of column
Returns
... |
928c18324e7cfa1493ec890560c4adf3501a67f2 | jromero132/pyanimations | /animations/monte_carlo/pi.py | 5,178 | 3.546875 | 4 | from matplotlib import animation
import math
import matplotlib.pyplot as plt
import numpy as np
def is_in_circle(center: tuple, radius: float, point: tuple) -> bool:
return math.sqrt(sum((c - p) ** 2 for c, p in zip(center, point))) <= radius
class MonteCarloPiEstimation:
def __init__(self, display: "Display"):
... |
6a13d6d6451f023372ed1583ef6d77c5ea9ca1fa | uribe-convers/Genomic_Scripts | /VCF-to-Tab_to_Fasta_IUPAC_Converter.py | 2,107 | 3.578125 | 4 | #!/usr/bin/python
def usage():
print("""
This script is intended for modifying files from vcftools that contain
biallelic information and convert them to fasta format. After the vcf file has
been exported using the vcf-to-tab program from VCFTools, and transposed in R,
or Excel, this script will c... |
af559157ebe1d11b16c38556ed60da92a9694098 | bryanluu/AdventOfCode2020 | /Day11/Day11.py | 4,326 | 3.71875 | 4 | #!/bin/python3
import sys
import numpy as np
filename = sys.argv[1] if len(sys.argv) > 1 else "input"
part = (int(sys.argv[2]) if len(sys.argv) > 2 else None)
while part is None:
print("Part 1 or 2?")
reply = input("Choose: ")
part = (int(reply) if reply == "1" or reply == "2" else None)
# characters in problem... |
bf9c44aa4e028f2c736743cdc88956637a73a7c7 | GuoZhouBoo/python_study | /basics/container.py | 1,605 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : container.py
# Author: gsm
# Date : 2020/5/6
def test_list():
list1 = [1, 2, 3, 4, '5']
print list1
print list1[0] # 输出第0个元素
print list1[0:3] # 输出第1-3个元素
print list1[0:] # 输出从0到最后的元素
print list1[0:-1] # 输出从0到最后第二元素
list1.append(6... |
283ce2bf5201efde8d0b6998758be87d8b06db3d | shamoons/Reinforcement_Learning_Textbook_Exercises | /Chapter_5/Exercise_12/env.py | 4,713 | 3.546875 | 4 | '''
This will build the enviroment of the racetrack
'''
import numpy as np
import random
class RaceTrack():
def __init__(self):
super(RaceTrack, self).__init__()
print("Environment Hyperparameters")
print("=====================================================================... |
86643d87a3010f92442c579b7a6fd3f7154af55f | scottfoltz/pythonpractice | /password-gen.py | 1,419 | 4.03125 | 4 | import random
print ('**********************************************')
print ('Welcome to the Welcome to the Password Generator!')
print ('**********************************************')
#define an array that will hold all of the words
lineArray = []
passwordArray = []
#prompt user
filename = input('Enter the name o... |
3b597cae9208d703e6479525625da55ddc18b976 | DahlitzFlorian/python-zero-calculator | /tests/test_tokenize.py | 1,196 | 4.1875 | 4 | from calculator.helper import tokenize
def test_tokenize_simple():
"""
Tokenize a very simple function and tests if it's done correctly.
"""
func = "2 * x - 2"
solution = ["2", "*", "x", "-", "2"]
assert tokenize.tokenize(func) == solution
def test_tokenize_complex():
"""
Tokenize a... |
56f1c9051a35ef64d3eb05510e2025089fb30315 | potsawee/py-tools-ged | /gedformatconvert.py | 1,861 | 3.671875 | 4 | import sys
def one_word_to_one_sentence(input, output):
with open(input, 'r') as f1:
with open(output, 'w') as f2:
newline = []
for line in f1:
if line == '\n':
if len(newline) > 0:
f2.write(' '.join(newline) + '\n')
... |
bf3e0d3733919a06c12fdbb8fede6596bd237db3 | potsawee/py-tools-ged | /assertdata.py | 1,286 | 3.59375 | 4 | #!/usr/bin/python3
'''
Count how many lines in the target files have zero, one, two, ... field
Args:
path: path to the target file
Output:
print the output to the terminal e.g.
linux> python3 assertdata.py clctraining-v3/dtal-exp-GEM4-1/output/4-REMOVE-DM-RE-FS.tsv
zero: 3649
one: 0
two:... |
3d3306cf4afef96d48911f7bda81ff98f595be84 | jvcampbell/py-bits-n-bobs | /Udemy-Python-Bootcamp/Capstone Project/Caesar Cipher/Caesar Cipher.py | 2,877 | 4.03125 | 4 | # Encode/Decode text to caesar cipher. Includes a brute force method when the key is not known
import os
class CaesarCipherSimple(object):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
def __init__(self):
pass
def encode(self,input_text,cipher_key = 1):
'''Encodes text by receiving an intege... |
4b7dbbf640d118514fa306ca39a5ee336852aa05 | francoischalifour/ju-python-labs | /lab9/exercises.py | 1,777 | 4.25 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 9 - Functional Programming
# François Chalifour
from functools import reduce
def product_between(a=0, b=0):
"""Returns the product of the integers between these two numbers"""
return reduce(lambda a, b: a * b, range(a, b + 1), 1)
def sum_of_numbers(numbers):
... |
8a8d59fe9276270dada61e63ac8037f0dc580a2c | francoischalifour/ju-python-labs | /lab4/five-in-a-row/five_in_a_row.py | 5,086 | 4.21875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Five in a row
# François Chalifour
def print_game(game):
"""
Prints the game to the console.
"""
print(' y')
y = game['height'] - 1
while 0 <= y:
print('{}|'.format(y), end='')
for x in range(game['width']):
print(g... |
ba5bce618d68b7570c397bc50d6f96766b600fd9 | francoischalifour/ju-python-labs | /lab4/exercises.py | 1,024 | 4.1875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Dictionaries
# François Chalifour
def sums(numbers):
"""Returns a dictionary where the key "odd" contains the sum of all the odd
integers in the list, the key "even" contains the sum of all the even
integers, and the key "all" contains the sum of all integer... |
86c803756a5548226d81b32cbfc0e66b04e4b240 | nano13/tambi | /interpreter/structs.py | 950 | 3.5 | 4 | # -*- coding: utf_8 -*-
class Result:
# category is one of:
# - table
# - list
# - text
# - string
# - error
# (as a string)
category = None
payload = None
metaload = None
# header is a list or None
header = None
header_left = None
# name is a stri... |
a81ce65a4df9304e652af161f5a00534b35cc844 | Abuubkar/python | /code_samples/p4_if_with_in.py | 1,501 | 4.25 | 4 | # IF STATEMENT
# Python does not require an else block at the end of an if-elif chain.
# Unlike C++ or Java
cars = ['audi', 'bmw', 'subaru', 'toyota']
if not cars:
print('Empty Car List')
if cars == []:
print('Empty Car List')
for car in cars:
if car == 'bmw':
print(car.upper())
elif cars ==... |
42a371f596cef5ecf7185254ca45b00fa737ecb4 | Abuubkar/python | /leet_code/week_1/counting_elements/counting_elements.py | 1,744 | 3.953125 | 4 | """
Authors
---------
Primary: Abubakar Khawaja
Description:
----------
Given an integer array arr, count element x such that
x + 1 is also in arr.
If there're duplicates in arr, counts them also.
"""
# Imports
from collections import defaultdict
class Solution:
arr = []
def set_arr(self, arr: [int]):
... |
b117d36f9a8ce6959fcbea91ffb1878efea633b1 | Abuubkar/python | /leet_code/week_1/anagram/anagram.py | 1,357 | 4.03125 | 4 | """
Authors
----------
Primary: Abubakar Khawaja
Short Description:
----------
This file contains function that will group anagrams together from given array of strings.
"""
from collections import defaultdict
def groupAnagrams(strs: [str]):
"""
This function take array of string and adding new words by us... |
bf49e0e95c9efd7a9b08d2421709159ef6e6bbae | lujun94/Name_Your_Own_Price_Simulation | /nyop.py | 4,684 | 3.59375 | 4 | import random
class NYOP:
def __init__(self):
self.profit = 0
#WeightedPick() is cited from
#http://stackoverflow.com/questions/2570690/python-algorithm-to-randomly-select-a-key-based-on-proportionality-weight
def weightedPick(self, d):
r = random.uniform(0, sum(d.itervalues()))
... |
e20320e6e6486193eac99150b8501fed599cdf3e | IHautaI/game-of-sticks | /hard_mode.py | 788 | 3.53125 | 4 | from sticks import Computer
import random
proto = {}
end = [0 for _ in range(101)]
for i in range(101):
proto[i] = [1, 2, 3]
class HardComputer(Computer):
def __init__(self, name='Megatron'):
super().__init__(name)
self.start_hats = proto
self.end_hats = end
def reset(self):
... |
e5bcd3a8455d4e189132665021f26e221155addd | maiduydung/Algorithm | /M_valid_sudoku.py | 833 | 3.84375 | 4 | # https://leetcode.com/problems/valid-sudoku/
# Each row must contain the digits 1-9 without repetition.
# Each column must contain the digits 1-9 without repetition.
# Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
class Solution:
def isValidSudoku(self, board: Lis... |
f0c35498afbb6364b93c260ddea75e15ce4b8264 | maiduydung/Algorithm | /Array - String/isPalindrome.py | 394 | 3.9375 | 4 | import string
#two pointer approach
def isPalindrome(s):
s = s.lower()
s = s.replace(" ", "")
s = s.translate(str.maketrans('', '', string.punctuation))
end = len(s)-1
for start in range(len(s)//2):
if(s[start] != s[end]):
return False
end = end - 1
print(start, e... |
e37c122f96ffabe7349ca690a11bac98a7898b7e | maiduydung/Algorithm | /Array - String/Tribonacci.py | 391 | 3.765625 | 4 | #https://leetcode.com/problems/n-th-tribonacci-number/
#using dynamic programming
class Solution:
def tribonacci(self, n: int) -> int:
if(n==0): return 0
elif(n==1) or (n==2): return 1
arr = [0]*(n+1)
arr[0] = 0
arr[1] = 1
arr[2] = 1
for i in range(3, n+1):
... |
0e3213a15f8f4f2a7f9d1d03fa9e9d0f1d886c1a | maiduydung/Algorithm | /Network Flow/find_augmentpath.py | 743 | 3.5 | 4 | #Maximum flow problem
#if there is augment path, flow can be increased
import networkx as nx
import queue
N = nx.read_weighted_edgelist('ff.edgelist', nodetype = int)
def find_augmentpath(G, s, t): #graph, source, sink
P = [s] * nx.number_of_nodes(G)
visited = set()
stack = queue.LifoQueue()
stack.put(... |
098bc9cec885d3f67a8e6d972af59bf4bd1f4dc9 | thiekAR/Prog_VR | /directo_01/assigment_python_02.py | 878 | 3.859375 | 4 | # ex. 8.7
def make_album(artist_name, title_name, tracks = 0):
if tracks != 0:
return {'artist': artist_name, 'title': title_name, 'tracks': tracks}
return {'artist': artist_name, 'title': title_name}
print(make_album('Bob', 'album1', 9))
print(make_album('Jack', 'album2', 1))
print(make_album('Joh... |
36762d67cf6ce86b5f091e3c6e261fb37f704224 | thiekAR/Prog_VR | /directo_01/C_08/Function2.py | 250 | 3.84375 | 4 | import this
print(this)
def print_separator(width):
for w in range(width):
print("*", end="")
def print_separator_2(width):
print("*" * width)
print("This is line 1")
print_separator(50)
print("\n")
print_separator_2(50)
|
2e68dd629dddfae3f29e44e12783594272c21131 | gacl97/Artificial-Intelligence | /Problem 1/tree.py | 6,891 | 3.59375 | 4 | from node import *
class Tree:
def createNode(self, qnt_m1, qnt_c1, qnt_mb, qnt_cb, qnt_m2, qnt_c2, flag, prev):
return Node(qnt_m1, qnt_c1, qnt_mb, qnt_cb, qnt_m2, qnt_c2, flag, prev)
def compare(self, node1, node2):
if(node1.side1[0] == node2.side1[0] and node1.side1[1] == node2.side1[1] an... |
2bfe1d887f9779dff2e87dcae17132899e851175 | gacl97/Artificial-Intelligence | /Problem 2/Graph.py | 3,565 | 3.671875 | 4 | from Node import *
from queue import PriorityQueue
class graph:
colors = [-1, [0,0],[0,1],[0,3],[0,2],[0,1],[0,0],[1,1],[1,2],[1,3],[1,1],[3,3],[2,2],[2,3],[2,2]]
def createNode(self, id1, heuristDist, dist, prevColor):
return Node(id1,heuristDist,dist,prevColor)
def createGraph(self, distances, ... |
b64e7152f33c0f6b4b7b7b600b17d5259f65322b | asiya00/Exercism | /python/anagram/anagram.py | 325 | 3.734375 | 4 | def find_anagrams(word, candidates):
result = []
word = word.lower()
for i in candidates:
candi = i.lower()
if candi!=word and len(candi)==len(word) and word!='tapper':
if set(candi) == set(word):
result.append(i)
else:
continue
return re... |
035e394d57ef25672cced5b26f08d4694efddd07 | TheJust1ce/ML_lab1 | /lab2.py | 1,193 | 3.5625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path = 'data/ex1data2.txt'
data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
data.head()
data.describe()
data = (data - data.mean()) / data.std()
data.head()
data.insert(0, 'Ones', 1)
cols = data.shape[1]
X = data.iloc[:... |
383c07aa7a0b5ed08ec2600f0046da8687448c90 | IvanLopezMedina/MapReduce | /shuffler.py | 766 | 3.53125 | 4 | # En aquesta classe processem la llista del map i agrupem les paraules
# Retornem llista paraula : { { paraula: 1 } , {paraula: 1 } }
class Shuffler:
def __init__(self, listMapped):
self.listMapped = listMapped
self.dictionary = {}
def shuffle(self):
# Per cada paraula, si existeis una ... |
b583554675d3ec46b424ac0e808a8281a339de67 | NandanSatheesh/Daily-Coding-Problems | /Codes/2.py | 602 | 4.21875 | 4 | # This problem was asked by Uber.
#
# Given an array of integers,
# return a new array such that each element at index i of the
# new array is the product of all the numbers in the original array
# except the one at i.
#
# For example,
# if our input was [1, 2, 3, 4, 5],
# the expected output would be [120, 60, 40, 3... |
7b805bc4acdb0409bab9c84388f8fc83f4bfbbed | nincube8/Hydroponic-Automation | /Turn on Feed Pump Feed Plant.py | 1,845 | 3.796875 | 4 | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# init list with pin numbers
#pinList = [7, 11, 13, 15, 19, 21, 29, 31, 33, 35, 37, 40, 38, 36, 32, 22]
pinList = [7, 11, 13, 15, 19, 21, 29, 31, 33, 35, 37, 40, 38, 36, 32, 22]
# loop through pins and set mode and state to 'low'
for i in... |
9e1d837c4a2f0998e3b1344331ff4ea407de6582 | IamWilliamWang/Leetcode-practice | /2020.8/爱奇艺-2.py | 629 | 3.59375 | 4 | def nextXY(ch: str):
if ch == 'N':
nextStep = (visited[-1][0] - 1, visited[-1][1])
elif ch == 'S':
nextStep = (visited[-1][0] + 1, visited[-1][1])
elif ch == 'E':
nextStep = (visited[-1][0], visited[-1][1] + 1)
elif ch == 'W':
nextStep = (visited[-1][0], visited[-1][1] - ... |
9f531639340fbd945ed2ec054629ca12cfb30675 | IamWilliamWang/Leetcode-practice | /2020.6/SpiralOrder.py | 1,476 | 3.53125 | 4 | from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
x, y = 0, 0
restCount = len(matrix) * len(matrix[0])
clockwiseTrave... |
6c6b2f49a7531bbb887a4013e3a31268b5b24d03 | IamWilliamWang/Leetcode-practice | /2020.5/LargestNumber.py | 1,049 | 3.515625 | 4 | from typing import List
from functools import lru_cache
class Solution:
@lru_cache(maxsize=None)
def searchPotentialResult(self, restMoney: int, choicesInt: int) -> None:
if restMoney == 0:
if choicesInt > self.maxResult:
self.maxResult = choicesInt
for i in range(l... |
046ec5426d71fba6f4665d11543b2af0071c4ebf | IamWilliamWang/Leetcode-practice | /2020.4/CanJump.py | 1,301 | 3.609375 | 4 | from functools import lru_cache
class Solution:
def canJump(self, nums: list) -> bool:
if nums == []:
return False
@lru_cache(maxsize=None)
def find(index: int) -> bool:
"""
寻找该位置出发有没有可能到达终点
:param index: 当前位置
:return:
... |
5a721e63b018a73a7ed2dd8a4cdfd2f3b719af9c | IamWilliamWang/Leetcode-practice | /2020.8/贝壳-最大公约数.py | 6,728 | 3.84375 | 4 | from functools import lru_cache
from itertools import islice
from math import sqrt
class Prime:
"""
获得素数数组的高级实现。支持 in 和 [] 运算符,[]支持切片
"""
def __init__(self):
self._list = [2, 3, 5, 7, 11, 13] # 保存所有现有的素数列表
def __contains__(self, n: int) -> bool:
"""
判断n是否是素数
:par... |
66d2376ad3932fea1810da8fcc2d4bf1863f31ef | murali-koppula/programming-problems | /python/bttest.py | 1,094 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test simple B-Tree implementation.
node values are provided as arguments.
"""
__author__ = "Murali Koppula"
__license__ = "MIT"
import argparse
from btnode import Node
from btree import BTree
def add(root=None, vals=[]) ->'Node':
# Walk through the tree in a... |
42d12efe04c51bf489a6c252b2815811135e7de6 | 2Gken1029/graduateReserchProgram | /wordFind.py | 1,183 | 3.59375 | 4 | #! python3
# wordFind.py - 単語リストにある単語が文章ファイルにどれほどでてくるか
import os, sys
def wordFind(file_name):
word_file = open('frequentList.txt') # 単語リストを読み込み
word_list = word_file.readlines() # リストに書き込み
word_file.close()
voice_file = open(file_name) # 最初の引数を音声文章ファイルとする
voice_list = voice_file.readlines()
... |
c34644cf434d5bc7942b95f5b66548faa13a606c | 702criticcal/1Day1Commit | /Baekjoon/15815.py | 1,874 | 3.78125 | 4 | # 1차 시도. 런타임 에러.
mathExpression = input()
stack = []
for s in mathExpression:
stack.append(s)
if len(stack) >= 3 and stack[-1] in ['*', '/', '+', '-']:
operator = stack.pop()
num2 = stack.pop()
num1 = stack.pop()
stack.append(str(eval(num1 + operator + num2)))
print(stack[-1])
#... |
abe21d85d69621041f41f2124725c45a2e8e3c52 | 702criticcal/1Day1Commit | /Baekjoon/2941.py | 272 | 3.65625 | 4 | str = input()
str = str.replace("c=","1")
str = str.replace("c-","1")
str = str.replace("dz=","1")
str = str.replace("d-","1")
str = str.replace("lj","1")
str = str.replace("nj","1")
str = str.replace("s=","1")
str = str.replace("z=","1")
count = len(str)
print(count)
|
452845da256217de1bb1cde425dc1103ff25a97b | 702criticcal/1Day1Commit | /Baekjoon/1427.py | 119 | 3.59375 | 4 | n = input()
n_list = sorted(list(map(int, n)))
n_list.reverse()
n_list = list(map(str, n_list))
print(''.join(n_list))
|
905f2b287938bbb3d80cdce951ac736a26b15871 | 702criticcal/1Day1Commit | /Baekjoon/1193.py | 162 | 3.671875 | 4 | x = int(input())
line = 1
while x > line:
x -= line
line += 1
if line % 2 == 0:
print(f'{x}/{line - x + 1}')
else:
print(f'{line - x + 1}/{x}')
|
51f082d3dde89a5467ca199d24e848e3ee3aafe4 | 702criticcal/1Day1Commit | /Baekjoon/1225.py | 376 | 3.6875 | 4 | # 1차 시도. 시간 초과 실패.
A, B = input().split()
result = 0
for a in A:
for b in B:
result += int(a) * int(b)
print(result)
# 2차 시도. 성공. 형변환이 반복문 안에 있는 것이 문제였던 것 같다.
A, B = input().split()
A = list(map(int, A))
B = list(map(int, B))
result = 0
b = sum(B)
for a in A:
result += a * b
print(result)
|
0791b5afa28e707de3ddac9947e2aa0df5ab962f | 702criticcal/1Day1Commit | /Baekjoon/10988.py | 109 | 3.90625 | 4 | S = input()
reversedS = ''.join(list(reversed(list(S))))
if S == reversedS:
print(1)
else:
print(0)
|
deab3ceba37a0c163e0dcfa73c78fcfdd58dc32f | 702criticcal/1Day1Commit | /Baekjoon/14916.py | 158 | 3.84375 | 4 | n = int(input())
if n == 1 or n == 3:
print(-1)
elif (n % 5) % 2 == 0:
print(n // 5 + (n % 5) // 2)
else:
print((n // 5) - 1 + (n % 5 + 5) // 2)
|
adfa64097aeb927cd37d57f18b9570658350cc95 | 702criticcal/1Day1Commit | /Baekjoon/1343.py | 281 | 3.59375 | 4 | board = list(input())
for i in range(len(board)):
if board[i:i + 4] == ['X', 'X', 'X', 'X']:
board[i:i + 4] = ['A', 'A', 'A', 'A']
if board[i:i + 2] == ['X', 'X']:
board[i:i + 2] = ['B', 'B']
if 'X' in board:
print(-1)
else:
print(''.join(board))
|
98eb446e51c509fd9f82721cd874474d7738880d | 702criticcal/1Day1Commit | /Programmers/stringIWanted.py | 275 | 3.5625 | 4 | import string
def solution(strings, n):
answer = []
for j in string.ascii_lowercase:
for i in sorted(strings):
if i[n] == j:
print(i[n])
answer.append(i)
return answer
# print(solution(["sun","bed","car"], 1)) |
bf4e9fe092735101ec7d741d73d40e54d60b9a44 | allysonja/hangman_steps | /3/maingame.py | 855 | 3.53125 | 4 | import random
import pygame
import sys
from pygame import *
pygame.init()
fps = pygame.time.Clock()
# CONSTANTS #
# DIMENSIONS #
WIDTH = 600
HEIGHT = 400
# COLORS #
WHITE = (255, 255, 255)
BLACK = (0 ,0, 0)
# GAME VARIABLES #
word_file = "dictionary.txt"
WORDS = open(word_file).read().splitlines()
word = random.cho... |
1ef246ae4f95f6727d38c8e55dfbe69cc8ba1385 | susoooo/IFCT06092019C3 | /PedroL/ejercicios/multi/python/ejercicios/4/Respuestas.nonexec.py | 2,155 | 4.09375 | 4 | #1
words = []
n = int(input("palabras a incluir"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
#2
words = []
n = int(input("palabras a incluir:"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
q = input("palabra a c... |
b673338a1fd0bc8bd15fbc1993d06ff520150693 | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_1/Ejercicio1.py | 162 | 3.84375 | 4 | numero1=int(input("Introduzca el primer numero: "))
numero2=int(input("Introduzca el segundo numero: "))
media=(numero1 + numero2) / 2
print("La media es ",media) |
3c749b7db4951b609149529c15e025b2bc059383 | susoooo/IFCT06092019C3 | /Riker/python/05.py | 283 | 3.625 | 4 | # 5-Escriba un programa que pida una temperatura en grados Fahrenheit y que escriba esa temperatura en grados Celsius. La relación entre grados Celsius (C) y grados Fahrenheit (F) es la siguiente: C = (F - 32) / 1,8
f = int(input("Fahrenheit? "))
print("Celsius: ", (f - 32) /1.8)
|
6d540eb2495904a59fdf91444ce77d2a11e7fc94 | susoooo/IFCT06092019C3 | /Riker/python/11.py | 481 | 3.890625 | 4 | # 4-Escriba un programa que pida el año actual y un año cualquiera y que escriba cuántos años han pasado desde ese año o cuántos años faltan para llegar a ese año.
import datetime
year = int(input("Year? "))
current_year = datetime.datetime.now().year
if (year < current_year):
print("Years since ", year, ", ", ... |
a6183dcb8aba1708c72862fd23d82a50147e946d | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_4/Ejercicio4.py | 442 | 4.09375 | 4 | # Escriba un programa que pregunte cuántos
# números se van a introducir, pida esos
# números y escriba cuántos negativos ha introducido.
iteracion=int(input("¿Cuantos números va a introducir?: "))
negativo=0
for i in range(iteracion):
numero=int(input("Introduzca el numero: "))
if numero < 0 :
negati... |
cfd6225160256d38046ffa0d99ac9863945a553c | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e7.py | 294 | 3.71875 | 4 | #7-Escriba un programa que pida una cantidad de segundos y que escriba cuántas horas, minutos y segundos son.
print("Segundos:")
sgd=int(input())
min=0
horas=0
while sgd>3600:
horas+=1
sgd-=3600
while sgd>60:
min+=1
sgd-=60
print("Horas: ", horas, "Minutos: ", min, " Segundos: ",sgd)
|
9ec0866daee52c1def3a8a9fed5299154dd92f64 | susoooo/IFCT06092019C3 | /Riker/python/14.py | 429 | 3.90625 | 4 |
# 8-Escriba un programa que pida tres números y que escriba si son los tres iguales, si hay dos iguales o si son los tres distintos.
n1 = int(input("n1 ? "))
n2 = int(input("n2 ? "))
n3 = int(input("n3 ? "))
if ((n1 == n2) and (n2 == n3)):
print("They are equal.")
else:
if ((n1 == n2) or (n1 == n3) or (n2 ==... |
babcf1bc7df6069a229344b05e97d97acfddca39 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/while4.py | 522 | 4.0625 | 4 | #4-Escriba un programa que pida primero dos números enteros (mínimo y máximo) y que después pida números enteros situados entre ellos. El programa terminará cuando se escriba un número que no esté comprendido entre los dos valores iniciales. El programa termina escribiendo la cantidad de números escritos.
print("Númer... |
e08d5430b054d56ae0ac12b818ad476158cfa51f | susoooo/IFCT06092019C3 | /elvis/python/bucle5.py | 645 | 4.125 | 4 | # Escriba un programa que pregunte cuántos números se van a introducir, pida esos números
# y escriba cuántos negativos ha introducido.
print("NÚMEROS NEGATIVOS")
numero = int(input("¿Cuántos valores va a introducir? "))
if numero < 0:
print("¡Imposible!")
else:
contador = 0
for i in range(1, numero + 1... |
14ddefb42599d0209461b9d3c7be587fdec95dab | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e2.py | 324 | 3.984375 | 4 | #2-Escriba un programa que pida el peso (en kilogramos) y la altura (en metros) de una persona y que calcule su índice de masa corporal (imc). El imc se calcula con la fórmula imc = peso / altura 2
print("Peso: (kg)")
peso = float(input())
print("Altura: (m)")
altura = float(input())
print("imc: ",peso/(altura*altura)... |
cedf8afaea566b52bc6e58b2162e4f8884244155 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/listas2.py | 410 | 4.0625 | 4 | #2-Amplia el programa anterior, para que una vez creada la lista, se pida por pantalla una palabra y se diga cuantas veces aparece dicha palabra en la lista.
palabras = []
print("Número de palabras?:")
num=int(input())
for n in range(num):
print("Palabra ", n+1, ": ")
palabras=palabras+[input()]
print(palabras)
... |
37a04841bddbb99f65213075c1c8524b62fb4494 | susoooo/IFCT06092019C3 | /Riker/python/10.py | 303 | 3.828125 | 4 | # 3-Escriba un programa que pida dos números y que conteste cuál es el menor y cuál el mayor o que escriba que son iguales.
n1 = int(input("n1? "));
n2 = int(input("n2? "));
if(n1 > n2):
print(n1, ">", n2)
else:
if (n2 > n1):
print(n2, ">", n1)
else:
print(n2, "=", n1)
|
aea888ce79f3f38a5347cd8208531a8978cb1a01 | susoooo/IFCT06092019C3 | /Tere/python/ejercicio7.py | 345 | 3.828125 | 4 | #7-Escriba un programa que pida una cantidad de segundos y
#que escriba cuántas horas, minutos y segundos son.
print("Escribe unos segundos: ")
segundos= input()
horas= int(segundos)/3600
minutos = (int(segundos) - int (horas)*3600)/60
seg = int(segundos) % 60
print (int(horas),"horas,",int(minutos), "minutos y", i... |
16ec073e55924a91de34557320e539c750f377a3 | susoooo/IFCT06092019C3 | /jesusp/phyton/Divisor.py | 215 | 4.125 | 4 | print("Introduzca un número")
num = int(input())
if(num > 0):
for num1 in range(1, num+1):
if(num % num1 == 0):
print("Divisible por: ", num1)
else:
print("Distinto de cero o positivo")
|
6a1f6dfefe46fd0ff31c1b967046182d90e61d9a | susoooo/IFCT06092019C3 | /Riker/python/13.py | 427 | 3.90625 | 4 | # 6-Escriba un programa que pida dos números enteros y que escriba si el mayor es múltiplo del menor.
n1 = int(input("n1 ?"))
n2 = int(input("n2 ? "))
if (n1 == n2):
print("Numbers are equal")
else:
if (n1 > n2):
max = n1
min = n2
else:
max = n2
min = n1
if(max%min == ... |
b2ba8e45c360ae96a08209172ba05811dd3a3b96 | susoooo/IFCT06092019C3 | /jesusp/phyton/Decimal.py | 201 | 4.15625 | 4 | print("Introduzca un número")
num = int(input())
print("Introduzca otro número")
num1 = int(input())
while(num > num1):
print("Introduzca un numero decimal: ")
num1= float(input())
|
6e848cdacf2855debfa5adb7ee6164758a53f8e7 | susoooo/IFCT06092019C3 | /Riker/python/08.py | 232 | 3.609375 | 4 | # 1-Escriba un programa que pida dos números enteros y que calcule su división, escribiendo si la división es exacta o no.
n1 = int(input("n1? "))
n2 = int(input("n2? "))
if (n1%n2 == 0):
print("yes")
else:
print("no")
|
52cc76a4a00bb9d8b7cb7aa335b7060a434dc29c | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_4/Ejercicio2.py | 344 | 4 | 4 | # Escriba un programa que pida un número entero mayor que cero y que escriba sus divisores.
numero=int(input("Introduzca un número entero mayor que cero: "))
while numero<=0 :
numero=int(input("Error.Introduzca un número entero mayor que cero: "))
for i in range(1,numero+1) :
if numero%i==0 :
print(i,"e... |
22bac0fd997d87e501d018b3af30dc76fd60f2c7 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e3.py | 322 | 4 | 4 | #3-Escriba un programa que pida una distancia en pies y pulgadas y que escriba esa distancia en centímetros.Un pie son doce pulgadas y una pulgada son 2,54 cm.
print("Distancia en pies:")
pies = float(input())
print("Distancia en pulgadas:")
pulgadas = float(input())
print("Distancia en cm: ", (pies*12+pulgadas)*2.54)... |
b41ed3fc64e7a705c9be5060c0b034528f0a5f98 | chrisfoose/randomColor.py | /randomColor.py | 195 | 3.953125 | 4 | # Random Color Generator
# Chooses random color from out of four choices
# Christopher Foose
import random
colorList = ["Red", "Blue", "Green", "Yellow"]
print("Your color is: ", random.choice(colorList))
|
ff3e2b0d818421e8924334b9658d12560c3fa3fd | Bakley/literate-bassoon | /rename_files.py | 576 | 3.53125 | 4 | from __future__ import print_function
import os
def renaming_files():
# get the path to the files and the file names
file_list = os.listdir("/home/koin/Desktop/HackRush/Bakley/Python/Learning/Udacity/prank")
print(file_list)
# get the saved path of the directory
saved_path = os.getcwd()
print(... |
08f116b143a9b8e78849c29f1df7a810ebd78352 | devangsharmadj/Python_Workbook_Course | /palindrome.py | 360 | 4.0625 | 4 | verifier = input('String to be checked: ')
split_verifier = verifier.split()
str_verifier = ''
for char in split_verifier:
str_verifier += f'{char}'
j = len(str_verifier)
for i in range(len(str_verifier)):
if str_verifier[i] == str_verifier[j - 1 - i]:
continue
else:
print('Not a palindrome!... |
63092169b0fbdedc99931c707dd8248feb413c5e | Chelton-dev/ICTPRG-Python | /loopinf01.py | 79 | 3.75 | 4 | # Infinite loop
j=0
k = 0
while j <= 5:
#while k <= 5:
print(k)
k = k+1 |
4885f7041431e60298e6655303696a9120fe272e | Chelton-dev/ICTPRG-Python | /setex01.py | 400 | 3.921875 | 4 | # Example of a set
# unique elements
# https://www.w3schools.com/python/python_sets.asp
# https://pythontic.com/containers/set/construction_using_braces
# Disadvantage that cannot be empty
# https://stackoverflow.com/questions/17373161/use-curly-braces-to-initialize-a-set-in-python
carmakers = { 'Nissan', 'Toyota', ... |
0b67e25ac38cfb32a6fe9a217f59a394a832ffa7 | Chelton-dev/ICTPRG-Python | /func03main2.py | 128 | 3.734375 | 4 | def main():
nm = get_name()
print("Hello "+nm)
def get_name():
name = input("Enter name: ")
return name
main() |
a8e222aca3153a0085ddf66b482b335c594042c9 | Chelton-dev/ICTPRG-Python | /format05printf.py | 326 | 3.984375 | 4 | # printing a string.
mystring = "abc"
print("%s" % mystring)
# printing a integer
days = 31
print("%d" % days)
# printing a float number
cost = 189.95
print("%f" % cost)
# printf apdaptions with concatenation (adding strings)
print("%s-" % "def" + "%f" % 2.71828)
# 2021-05-25
print("%d-" % 2021 + "0%d-" % 5 + "%d" ... |
19bfe557a5e0d351be9215b2f8ea501587337fda | Chelton-dev/ICTPRG-Python | /except_div_zero.py | 242 | 4.1875 | 4 | num1 = int (input("Enter num1: "))
num2 = int (input("Enter num2: "))
# Problem:
# num3 = 0/0
try:
result = num1/num2
print(num1,"divided by", num2, "is ", result)
except ZeroDivisionError:
print("division by zero has occured") |
6b5ac6244d890d1b5dcb135f22563bb8dc825abf | sorozcov/Digital-Sign-RSA | /digitalSign.py | 2,814 | 3.703125 | 4 | # Universidad del Valle de Guatemala
# Cifrado de información 2020 2
# Grupo 7
# Implementation Digital Sign.py
#We import pycryptodome library and will use hashlib to sha512
from Crypto.PublicKey import RSA
from hashlib import sha512
#Example taken from https://cryptobook.nakov.com/digital-signatures/rsa-sign-verify... |
c32ecd30c2fabc11127d5081d029a6c6271f3d2a | wtnb-msr/codeforces | /problem/118/A/solver.py | 233 | 3.609375 | 4 | #!/usr/bin/env python
import sys
origin = sys.stdin.readline().rstrip()
vowels = set(['a', 'A', 'o', 'O', 'y', 'Y', 'e', 'E', 'u', 'U', 'i', 'I'])
ans = [ '.' + c.lower() for c in origin if c not in vowels ]
print ''.join(ans)
|
1da02181c7de871672ec58d0ca79e721a0232367 | kunalkishore/Reinforcement-Learning | /Dynamic Programing /grid_world.py | 2,506 | 3.640625 | 4 | import numpy as np
class Grid():
def __init__(self,height,width,state):
self.height=height
self.width = width
self.i = state[0]
self.j = state[1]
def set_actions_and_rewards(self,actions, rewards):
'''Assuming actions consists of states other than terminal states and w... |
67817397c76aea7ecd61a6030af87a5990fedb11 | alejandroverita/python-courses | /python-pro/iterators.py | 1,148 | 3.890625 | 4 | import time
class FiboIter:
def __init__(self, nmax):
self.nmax = nmax
def __iter__(self):
self.n1 = 0
self.n2 = 1
self.counter = 0
return self
def __next__(self):
if self.counter == 0:
self.counter = +1
return self.n1
elif ... |
7562ed11cc98623910e7d9cd183bebad7bc207c0 | alejandroverita/python-courses | /bucles.py | 321 | 3.859375 | 4 | def run(veces, numero):
if veces <= numero:
print(f"La potencia de {veces} es {veces**2}")
run(veces + 1, numero)
else:
print("Fin del programa")
if __name__ == "__main__":
numero = int(input("Cuantas veces quieres repetir la potenciacion?: "))
veces = 0
run(veces, numero)... |
3c2ad960ec48388d2ed06952c26d9e044c851387 | Jumaruba/LeetCode | /328.py | 795 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
... |
8c81082771a896fe45aa9f868c19ae9f64d6736e | Jumaruba/LeetCode | /235.py | 1,437 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Implemented with a small improvement
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
... |
b40e2dbb8f231e4f7056ded68a1e01f363f1ed7d | Jumaruba/LeetCode | /844.py | 402 | 3.578125 | 4 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s = self.filterString(s)
t = self.filterString(t)
return s == t
def filterString(self, s):
s_ = ""
for i,l in enumerate(s):
if l == "#":
s_ = s_[:-1]
... |
011363075fb0db01ec2c1e91509a1d298c739790 | Jumaruba/LeetCode | /028.py | 550 | 3.578125 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
needle_size = len(needle)
haystack_size = len(haystack)
# Case the size is not compatible
if needle_size == 0:
return 0
if needle_size > haystack_size:
return -1
... |
9b44ba0b5d7221bf80da5243b2a8a9a349f32f1e | Jumaruba/LeetCode | /019.py | 1,004 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
numberOfElements = self.countElements(head)
toRe... |
fb77723ea81b139766b51c2d7df89e2d5e20f8d0 | Ka1str/Python-GB- | /lesson-4/task-3-4.py | 73 | 3.640625 | 4 | print([num for num in range(20, 240) if num % 20 == 0 or num % 21 == 0])
|
22ebd991c03e65777566bc730ccd7d4dc7a304a3 | Ka1str/Python-GB- | /lesson-3/task-6-3.py | 1,243 | 4.03125 | 4 | def int_func(user_text):
"""
Проверяет на нижний регистр и на латинский алфавит
Делает str с прописной первой буквой
:param user_text: str/list
:return: print str
"""
if type(user_text) == list:
separator = ' '
user_text = separator.join(user_text)
latin_alphabet = ["a",... |
917c3cda891b29c1d1ed0471be3ec773332a7b93 | ritika-rao/Machine-Learning | /03 Categorical Data.py | 1,086 | 3.78125 | 4 | # Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1] #Take all the columns except last one
y = dataset.iloc[:, -1] #Take the last column as the result
# Taking ca... |
3daa982b7c0f53c73325d26a82935d5568eae25c | rnjsrntkd95/piro12 | /PYTHON_week2/argorithm/bracket(9012).py | 548 | 3.703125 | 4 | number = int(input())
bracket = []
tmp = ''
for i in range(number):
bracket.append(input())
for target in bracket:
stack = []
target = list(target)
for check in target:
if check == '(':
stack.append(check)
else:
if not stack:
stack.append(check)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.