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 |
|---|---|---|---|---|---|---|
25aea65ac6c50ea7b51898551b1b43dfc0f12747 | 5outh/evolve | /nqueensredux.py | 5,698 | 3.75 | 4 | import random
import sys
"""
Author: Benjamin Kovach
Representation: Permutation of the set {0..N-1}. Each element indicates the row
of the queen at index i (i corresponds to the queen's column).
Parenthood Selection: Tournament selection twice with three combatants.
Mutation: Swap two elements of an individual'... |
03474e7db571f4dd4bd5131820379f7ac137adaf | jiajunhit/ProjectEuler_Python | /005_smallest_multiple.py | 282 | 3.671875 | 4 | def main():
result = 0
while True:
result += 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19
for each in range(1, 21):
if result % each:
break
if each == 20:
break
print(result)
if __name__ == "__main__":
main()
|
3b18a05831329230b889ce8ac3e9c80bc84f6da4 | jiajunhit/ProjectEuler_Python | /014_collatz_sequence.py | 556 | 3.734375 | 4 | def main():
record = [0, 1, 2]
max_length = 0
for num in range(3, 1000000):
a = num
length = 0
while(a != 1):
if a < num:
length += record[a]
break
if(a % 2):
a = 3 * a + 1
else:
a ... |
bc2e29c9695532c4866c242440ecbc9ad2b66bf0 | iceberg-1337/Python4sem | /main.py | 5,016 | 3.796875 | 4 | '''
class Person:
def __init__(self, arg_name, arg_age):
self.name = arg_name
self.age = arg_age
def __str__(self):
return 'Имя {}, Возраст {}'.format(self.name, self.age)
class Student(Person):
def __init__(self, arg_name, arg_age, st_id):
super().__init__(arg_name, arg_a... |
4b400c91a2d5c8c918c7af9c216fbd687c357751 | andreylrr/PythonDeveloperHW5 | /borndayforewer.py | 1,053 | 4.5 | 4 | """
МОДУЛЬ 2
Программа из 2-го дз
Сначала пользователь вводит год рождения Пушкина, когда отвечает верно вводит день рождения
Можно использовать свой вариант программы из предыдущего дз, мой вариант реализован ниже
Задание: переписать код используя как минимум 1 функцию
"""
def birth_year():
year = input('Ввведит... |
2730415044d6dc5b633a0e8f780b43fc98180d86 | diangs/Proyecto-02 | /Proyecto 2/REPORTE_2_RAMIREZ BARRIOS_JORGE.py | 7,700 | 3.734375 | 4 | """
Proyecto 2: Introducción al análisis de datos
"""
from os import system
import csv
import operator
# =============================================================================
# Creación del código principal menú
# Se definen las opciones validas y se espera una selección
# ===========================... |
5b26291158d8b335b97ca95c7a4689d65cfa4a3c | allainclair/disc-alg-est-dados | /aulas_exercicios/aula3.py | 385 | 3.734375 | 4 | def main():
list_ = [1, 2, 3, 'joao', 'maria']
element = [1, 2, 3]
return_ = my_in(element, list_)
print(return_)
def my_in(element, list_):
for e in list_:
if e == element:
return True
# else:
# return False
return False
def remove(lista, elemento):
... |
c9e3ac54c8b654c13797464b916f1b63fd7d4620 | allainclair/disc-alg-est-dados | /aulas_exercicios/nota.py | 651 | 4 | 4 | NF = input('Entre com a nota final do aluno: ')
print('Nota final do aluno', NF)
tipo_da_nf = type(NF)
# print('Tipo do NF', tipo_da_nf)
# print('Tipo do NF', type(NF))
NF = float(NF)
# print('Tipo do NF', type(NF))
# MF = input('digite um valor: ')
# print('Nota do aluno', MF)
if NF >= 6.0:
print('aprovado')
e... |
b402090ba1096b6c8e1c690cd3b5b73a4c71db70 | PKSHATechnology-Research/camphr | /typings/ahocorasick/__init__.py | 343 | 3.578125 | 4 | from typing import Iterator, Optional, Tuple
class Automaton:
def iter(
self, string: str, start: Optional[int] = None, end: Optional[int] = None
) -> Iterator[Tuple[int, str]]:
...
def make_automaton(self) -> None:
...
def add_word(self, key: str, value: Optional[str] = None... |
1c853b322c573054ff75b32e69d9168afb1bf6c0 | jcgaza/leekcodes | /productOfNumbers.py | 1,219 | 3.546875 | 4 | class ProductOfNumbers:
def __init__(self):
self.stack = []
def add(self, num: int) -> None:
if num == 0:
self.stack = []
elif len(self.stack) == 0:
self.stack.append(num)
else:
ans = num*(self.stack[len(self.stack)-1])
self.stack.append(ans)
def getProduc... |
e7a18a9becddd4239babc843f4f2b7072c3a369b | Hasib-rafi1/comp-py | /guess.py | 3,362 | 3.953125 | 4 | #Main python class
"""
This is the "guess" module.
Python class for controling user menu and Conditions.
"""
import stringDatabase
import game
import re
class guess:
game_list = []
limit = 100
numbering = 1
total_score = 0
stringDatabaseObj = stringDatabase.stringDatabase()
while (limit > 1): #... |
e5e5371e19bd606e5455dc87e2f637b67e4b4b45 | peterpepo/AdventOfCode2015 | /puzzle_17/puzzle_17.py | 1,741 | 3.65625 | 4 | import os
from puzzle_commons.puzzle_commons import read_puzzle_input
"""
Thanks to @Manuel Salvadores for answer posted here: https://stackoverflow.com/a/4633515
Note: I'm not the OP, just found it useful
"""
def get_combinations_of_sum (numbers, target_sum, partial=[]):
current_sum = sum(partial)
if curren... |
1afd31248b7cb7629ca39818a2486f7111f1d200 | mukulboro/complement-calculator-python | /nines_complement.py | 2,294 | 3.84375 | 4 | class NinesComplement:
def __init__(self, number1, number2):
self.num1 = str(number1)
self.num2 = str(number2)
self.complement = ""
self.sum = ""
self.carry_over=""
self.to_be_added =""
self.final_result=""
self.make_bits_equal()
self.nines_com... |
723c188db0fe6d8db6827d8e5b7581434cb35382 | Ademilson12/Aulas_Digital | /Basico/aula2.py | 849 | 3.828125 | 4 | nota1 = float(input('Entre com a nota: '))
while nota1 > 10:
nota1 = float(input('Nota invalida. Entre com a nota correta: '))
nota2 = float(input('Entre com a segunda nota: '))
while nota2 > 10:
nota2 = float(input('Nota invalida. Entre com a nota correta: '))
nota3 = float(input('Entre com a terceira nota: ')... |
e3b9ea3993f0a24a039861e55b411f9b94b48c0c | Ademilson12/Aulas_Digital | /Basico/aula11_personalizar_excecao.py | 613 | 3.890625 | 4 | """
Personalizando excecao
"""
class Error(Exception):
pass
class InputError(Error):
def __init__(self, message):
self.message = message
while True:
try:
nota1 = int(input('Entre com uma nota de 0 a 10: '))
print(f'Nota: {nota1}')
if nota1 > 10:
raise InputError... |
b8e45f32a37202fa082cc6a6aa268ffca28b2691 | Gabriel4256/algorithm-study | /Python/CANADATRIP.py | 1,294 | 3.65625 | 4 | ## 간단한 최적화 -> 결정 문제
## 분명 알고리즘은 맞는데, Python이라서 시간초과가 뜬다.
## CPP로 같은 코드를 짰더니 가볍게 통과했다...
global picket_numbers
def generate_picket_numbers(cities):
global picket_numbers
picket_numbers = [[0] * len(cities)]
for city in cities:
picket_numbers.append(city[1] / city[2])
def decision(cities, distance... |
d2ed73f9acd4f9e7fa2c0d263c9c8918bf29fe2f | alpha-martinez/recurssion- | /recurssion.py | 861 | 4.03125 | 4 | # def say_hello(name):
# print('Hello, {}'.format(name))
# say_hello(name)
# say_hello("Alpha")
# def countdown(num):
# if num == 0:
# print('blast off')
# return
# # recurssive step here
# print(num)
# countdown(num - 1)
# countdown(10)
# handles edge case for negative ... |
3ec4e7096c3b99c6c3c8542b016c3f3e7889afc0 | vafin-mk/codingame | /src/main/java/puzzles/easy/onboarding/Solution.py | 282 | 3.65625 | 4 | import sys
import math
while True:
enemy_1 = raw_input() # name of enemy 1
dist_1 = int(raw_input()) # distance to enemy 1
enemy_2 = raw_input() # name of enemy 2
dist_2 = int(raw_input()) # distance to enemy 2
print enemy_1 if dist_1 < dist_2 else enemy_2 |
217751f2e6d8ba22a43ad9867b342f3241a17e55 | germcauley/PythonScripts | /ReadFromExcelSpreadSheet.py | 591 | 3.765625 | 4 | #Script allows you to read data from a spreadsheet
#Gerald McAuley 2017
#!!Important!!
#Spreadsheet must be locatedin the same directory as the python file
import xlrd
xl_workbook = xlrd.open_workbook('sheet.xls')#insert name of your spreadsheet here
#Selects a specific page in spredsheet
xl_sheet = xl_workbook.sheet... |
458e785c74d4ad58520e9065b876a4288fa73839 | germcauley/PythonScripts | /Find_Hi_Low_num_in_str_Codewars.py | 305 | 3.578125 | 4 | def high_and_low(numbers):
# ...
myArr =[]
ans = ""
for i in numbers.split(" "):
myArr.append(int(i))
myArr.sort()
ans = str(myArr[0]) +" "+ str(myArr[len(myArr)-1])
return ans
# return ans
num = '4 5 29 54 4 0 -214 542 -64 1 -3 6 -6'
print(high_and_low(num)) |
fe536c47fe819858f099db84b740f4faa1261f48 | Kalsara01/tkinter-learining | /9_msgbox.py | 867 | 3.546875 | 4 | from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("image")
root.iconbitmap("C:/Users/kalsa/Documents/python gui codemy youtube/icon_0m1_icon.ico")
frame1=LabelFrame(root,text="Pizza Types",padx=10, pady=10)
frame1.grid(row=0,column=0, padx=10,pady=10)
PizzaTypes = [
("pepperoni... |
8815da970ebf4ca685f151d79aadf781ea00bb0d | xarchived/hackerrank | /problem_solving/implementation/13-counting-valleys.py | 620 | 3.765625 | 4 | #!/bin/python3
import os
# Complete the countingValleys function below.
def countingValleys(n, s):
level = 0
valley = False
total = 0
for c in s:
if c == 'U':
level += 1
else:
level -= 1
if not valley and level < 0:
valley = True
... |
510b5e901b5c925d3edd67f24de5c650ea234bcf | xarchived/hackerrank | /problem_solving/warmup/05-diagonal-difference.py | 748 | 3.796875 | 4 | #!/bin/python3
import os
def main_diagonal(mat):
dia = []
col = 0
for row in mat:
dia.append(row[col])
col += 1
return dia
def anti_diagonal(mat):
dia = []
col = len(mat[0]) - 1
for row in mat:
dia.append(row[col])
col -= 1
return dia
def diagonal_d... |
acf4fdfa4bbe88df5a63df369f9e38b8701697cc | xarchived/hackerrank | /problem_solving/implementation/05-breaking-best-and-worst-records.py | 661 | 3.734375 | 4 | #!/bin/python3
def breaking_records(scores):
minimum = None
maximum = None
total_min = 0
total_max = 0
for score in scores:
if minimum is None and maximum is None:
minimum = score
maximum = score
continue
if minimum > score:
total_m... |
200d08a8264557fb87d97493f6c644520a1d53a5 | srokks/tic_tac_toe_cli | /Simple Tic-Tac-Toe/task/tictactoe.py | 4,216 | 3.953125 | 4 | # write your code here
def gen_board(placeholder_char = '-'):
'''Returns matrix[3][3] with placeholder - as empty field'''
board = [['_' for i in range(3)] for j in range(3)]
return board
def print_board(board):
"""Prints board"""
print('---------')
for el in board:
print('| ' + ' '.j... |
e84a8e8edaf283f601d94c4f46d6e3b74819f6f7 | sichen1210/CS0008-f2016 | /ch2-ex9.py | 221 | 3.84375 | 4 | #calculate the temprature
Fahrenhei = float(\
input("please input your temprature in Fahrenhei(number please): "))
Celsius_temperatures = 5*(Fahrenhei-32)/9
print("Celsius temperatures = " + str(Celsius_temperatures)) |
6619c361ab4d2f9ea9a308ac033b06559cf1812d | sichen1210/CS0008-f2016 | /ch4-ex2.py | 146 | 3.703125 | 4 | time = 10
CaloriesB = 4.2
while time >= 10 and time <= 30:
CaloriesB = CaloriesB * time
time = time + 5
print(format(CaloriesB,'.1f')) |
177bee615adc88ce3b59c1f87bd37259ac8cab55 | wcheung8/data-structures-algorithms | /union-find.py | 1,507 | 3.625 | 4 | class UnionFind:
def __init__(self, items):
n = len(items)
self.items = []
self.item_to_index = {items[i]:i for i in range(n)}
self.parent = [i for i in range(n)]
self.weight = [0 for i in range(n)]
def union(self, a, b):
ra = self.root(a)
... |
5edebd8cdbebcb9ae782c6d8571b7e15f41a8da1 | fm3ssias/python-exercices | /02_oddOrEven.py | 529 | 4.15625 | 4 | '''
Objetivo: Mostrar pro usuário se o numero inserido é par ou impar
Entrada: Um numero
Saida: Se é impar ou par
'''
numero = 1
while numero != 0 :
numero = int(input("Digite um numero (0 para sair): "))
if numero == 0:
break
divPorQuatro = str(numero)
if int(divPorQuatro[-2:])%4 == 0 or int... |
6b1302a3ea50c09f3a108173faa4a23eab020e17 | connorescajeda/Algorithims | /main.py | 1,233 | 3.546875 | 4 | def main():
f = open("graphs/graph-F21.txt")
edges = f.readline()
f = f.read().splitlines()
s = {}
for line in f:
if len(line.split()) != 1:
(one, two) = line.split()
if one not in s:
s[one] = []
if two not in s:
s[two] = []... |
572dd36105b8fb955d38b17de095888f134386b3 | aneeshvv/ICTA-full-stack-Calicut | /anishpython/palindrome.py | 143 | 4.125 | 4 | a=raw_input("Enter the string").upper()
b= a[::-1]
if a==b:
print "The string is a palindrome"
else:
print "The string is not a palindrome"
|
5f582628e6f3444ba06ea7d819ca17562332e76d | aneeshvv/ICTA-full-stack-Calicut | /anishpython/for1.py | 73 | 3.609375 | 4 | n=int(input("Enter the limit"))
for i in range(n,0,-1):
print("tick",i)
|
cbe2b1f52c82bec3932af7f3fff4eac104340d46 | aneeshvv/ICTA-full-stack-Calicut | /anishpython/list.py | 125 | 4 | 4 | a=[1,"hello",3.5,[2,"welcome",4.5],5.6]
print a[1]
print a[3]
for i in a:
print i
a[0]=2
print a
a[3][1]="Hi"
print a[3][1]
|
c6fc6845f5aa2789ca2e7def765950c3cca6ea3a | kagomesakura/infinite2 | /infinite2.py | 89 | 3.8125 | 4 | num = 100
while not False:
if num < 0:
break
print('Number is ' + str(num))
|
c1be3e136a6c8aef5efa97e4164f19ae3e6545d6 | Kru47/Python | /Algo.py | 153 | 3.640625 | 4 | def count_sb(n):
output=0
while(n):
n=n & (n-1)
output= output+1
return output
Num=int(input())
print(count_sb(Num)) |
67ef5588ac729598abab5d9dc0b5f43f23a898e6 | Kru47/Python | /DhananjayAsci.py | 1,200 | 3.59375 | 4 | '''variable="="
print(ord(variable))
print(chr(67))'''
def is_prime (factor):
for ifactor in range(2,factor):
if factor%ifactor==0:
check = "N"
break
else:
check = "Y"
if check is "Y":
return 1
else:
return 0
#Number... |
9531543bf20974868913f8c4651fc93f5db1b828 | ssyze/Codes | /Nowcoder Multi-University/7/D.py | 326 | 3.65625 | 4 | '''
@Date : 2020-08-01 12:07:11
@Author : ssyze
@Description :
'''
from math import *
t = int(input())
for ti in range(t):
for n in range(1, 1000000000):
sum = n * (n + 1) * (2 * n + 1) / 6
sq = int(sqrt(sum))
if sq * sq == sum:
print("Fake news!")
pri... |
a1b9bf680534dbbfbc310a822deb14f1bb4e2dad | prataprc/gist | /py/loop.py | 657 | 4.65625 | 5 | #! /usr/bin/python
# Some examples using the looping constructs in python
a = ['cat', 'dog', 'elephant']
x = 10
print type(x)
for x in a :
print x, type(x), len(x)
b = 'hello \n world'
for x in b :
print x, type(x), len(x)
# Dangerous iteration on a mutable sequence (list)
# for x in a :
# a.insert(1,... |
62bd1656589684f1b68834a05649b0345a9df830 | prataprc/gist | /py/control.py | 312 | 3.859375 | 4 | #! /usr/bin/python
# Some examples to use the control flow statements.
x = int(raw_input("Please enter an integer : "))
y = float(raw_input())
print x, y
if x < 0 :
x = 0
print "Negative changed to Zero"
elif x == 0 :
print "Zero"
elif x == 1 :
print "Positive"
elif x > 1 :
print "More"
|
80f43b81248339e2502f851768202f2a01fff3d2 | prataprc/gist | /py/func.py | 210 | 3.546875 | 4 | #! /usr/local/bin/python
import os
def func(arg1, arg2, *args, **kargs) :
print arg1, arg2
for arg in args :
print arg
for k in kargs :
print k, ":", kargs[k]
a = (1,2,3)
func(a)
|
f13aaf8bb5b21ce59b62b1471e4ab4f2a97321f4 | prataprc/gist | /py/generator.py | 246 | 3.9375 | 4 | #! /usr/bin/env python
def compare_item( a, b ) :
return a == b
def compare_items(a, b) :
for i in range(len(a)) :
yield compare_item( a[i], b[i] )
a = [ 0,1,2,3,4]
b = [ 0,2,1,3,5]
for s in compare_items( a, b ) :
print s
|
a73736d32143141ee7a794e8dbee169441c640d1 | TungstenRain/Python-conditionals_and_recursion | /koch_curve.py | 1,357 | 4.4375 | 4 | """
This module contains code from
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
This is to complete the exercises in Chapter 5: Conditionals and Recursion in Think Python 2
Note: Although this is saved in a .py file, code was run on an interpreter to get results
No... |
882fd0de2497fb825f0915674d6bf33b50024f6f | oneplusTree/Python | /扩展/排序.py | 3,705 | 3.8125 | 4 | alist = [22, 13, 4, 6, 8, 9, 23, 45, 76, 1]
"""冒泡排序"""
def bubble(alist):
for j in range(len(alist) - 1):
for i in range(1, len(alist) - j):
if alist[i - 1] > alist[i]:
alist[i - 1], alist[i] = alist[i], alist[i - 1]
print(alist)
# bubble(alist)
"""选择排序"""
def select(a... |
1dd19fd6ba1f3b6a819781ad35a087a73db32d78 | vitoss-ux/ITMO.Python | /Lab_5/DiceModule.py | 1,312 | 3.65625 | 4 | import time
from random import randint
counter1 = []
counter2 = []
# Ввод имени
def name_input():
player1 = input('Имя первого игрока: ')
player2 = input('Имя второго игрока: ')
return player1, player2
# Логика игры
def game_core(player1, player2):
attempt = int(input('Ведите количество бросков для... |
3e6022fad1ec9aa0f267ccfa7175dc22631b35e9 | EricRybicki/Computing-Python | /Compyting&Python/Lecture_5_Recursion.py | 2,212 | 3.6875 | 4 | # Iterative exponent calc
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
if exp != 0:
result = base
while exp > 1:
exp -=1
result *= base
return result
else:
re... |
553dac4289f659e451c03900b34c0ea558605567 | xxxxgrace/COMP1531-19T3 | /Labs/lab03/19T3-cs1531-lab03/timetable.py | 733 | 4.25 | 4 | # Author: @abara15 (GitHub)
from datetime import date, time, datetime
def timetable(dates, times):
'''
Generates a list of datetimes given a list of dates and a list of times. All possible combinations of date and time are contained within the result. The result is sorted in chronological order.
For examp... |
f0745bc74b1021ae5ad22aeab395b613473e2bd9 | chowdhurynawaf/algorithm-implementation | /linear_search.py | 642 | 3.75 | 4 | #linar - searching
#using while loop
pos = -1
print("enter your number that you want to find")
def search(list , n):
i = 0
while i < len(list):
if list[i] == n:
globals()['pos'] = i
return True
i = i+1
return False
list = [9,4,24,5,1,50]
n = int(input())
if searc... |
e3db8eee447d70e75de764dbab32751b8ea85bcf | kimjunghak/Queue_Python | /Queue.py | 1,124 | 3.984375 | 4 | class Queue:
def __init__(self):
self.length = 0
self.head = None
def size(self):
return self.length
def empty(self):
return (self.length == 0)
def put(self, item):
node = Node(item)
if(self.head == None):
self.head = node
else:
p = self.head
while(p.next != None):
p = p.next
p.n... |
a392987a5b1455949ccc720689b5c585c383940f | wangjm12138/python_other_script | /sockets_server.py | 1,193 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#import sys
##reload(sys)
##sys.setdefaultencoding('utf8')
#import socket
## 建立一个服务端
#server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#server.bind(('127.0.0.1',1080)) #绑定要监听的端口
#server.listen(5) #开始监听 表示可以使用五个链接排队
##flag=1
##while True:# conn就是客户端链接过来而在服务端为期生成的一个链接实例... |
ad6204a6012e9fdf0a9bcd67b933e4fcfdaa416e | jerryduan07/gametime | /build/lib.linux-x86_64-2.7/gametime/interval.py | 2,169 | 3.734375 | 4 | #!/usr/bin/env python
"""Defines a class that maintains a representation of,
and information about, an interval of values.
"""
"""See the LICENSE file, located in the root directory of
the source distribution and
at http://verifun.eecs.berkeley.edu/gametime/about/LICENSE,
for details on the GameTime license and autho... |
3d92c1652dbd42f4dab56316e0a64bd12f8d1a3b | luiscarlosbolanhos/master | /Century.py | 148 | 3.671875 | 4 | number = input( "Ingrese una fecha: " )
if number%100 == 0 :
print "Siglo " + str(number/100)
else :
print "Siglo " + str((number/100)+1)
|
a1b96498860d27c397fb2713cda40c85ada6b51a | sabu0912/reto3 | /reto.py | 1,965 | 4.21875 | 4 | #CADA UNA DE LAS NOTAS
while True:
try:
nota1 = int(input("Ingresa la primera nota : "))
print(f"La primera nota es :", (nota1))
nota2 = int(input("Ingresa la segunda nota : "))
print(f"La segunda nota es :", (nota2))
nota3 = int(input("Ingresa la tercera nota : "))
print(f"La tercera... |
2323b6570606fb1b7ad155680f0d77cbeaf5dac2 | M01eg/algo_and_structures_python | /Lesson_1/3.py | 596 | 4.125 | 4 | '''
Урок 1
Задание 3
По введенным пользователем координатам двух точек вывести уравнение прямой
вида y=kx+b, проходящей через эти точки.
'''
X1 = float(input("Введите X1: "))
X2 = float(input("Введите X2: "))
Y1 = float(input("Введите Y1: "))
Y2 = float(input("Введите Y2: "))
K = (Y2 - Y1) / (X2 - X1)
B = Y2 - K * X2... |
cef458405aa0dffffe25bf9815b3646842a0debb | FridayAlgorithm/juhee_study | /BOJ/STACK/4949.py | 675 | 3.5 | 4 | #-*- encoding: utf-8 -*-
"""균형잡힌 세상"""
import sys
while 1 :
stack = []
strings = sys.stdin.readline().rstrip()
flag = 1
for i in strings :
if i == '(' or i == '[' :
stack.append(i)
elif i == ')' :
if stack and stack[-1] == '(' :
stack.pop()
... |
333ad2ae9ad598190dccacd4df6aa2d4a274216d | FridayAlgorithm/juhee_study | /BOJ/STACK/9012.py | 1,217 | 3.734375 | 4 | #-*- encoding: utf-8 -*-
"""괄호"""
size = int(input())
stack = []
for _ in range(size) :
parens = list(input())
while len(parens) != 0 :
if parens[0] == ')' or parens[-1] == '(' :
print('NO')
break
else :
if '(' and ')' in parens :
parens.rem... |
b51027d239d6ff61968b6af5854cf906c1e6b4bf | FridayAlgorithm/juhee_study | /BOJ/PRIORITY_QUEUE/1927.py | 1,015 | 3.765625 | 4 | #-*- encoding: utf-8 -*-
"""최소 힙"""
import sys
def insert(heap, x):
heap.append(x)
i = len(heap) - 1
while i > 1:
if heap[i//2] > heap[i] : # 부모가 자식보다 크다면 교체
heap[i], heap[i//2] = heap[i//2], heap[i] # swap
i = i // 2
else:
break
def remove(heap):
... |
0f7dc33af769f496908fb57790b2bc9957e17766 | BenHarries/coding_challenge_pipeline | /random_transform.py | 1,592 | 3.5625 | 4 | # For each image in the dataset we want to create N new images
# where random transformations have been applied.
# The transformations are:
# rotation from -100 to 100 degrees
# following a uniform distribution translation
# from -40% to 40% both axis following a uniform distribution
# The transformed images must be... |
890c4329e04e8b9a27654f9ed552adf722d1a14a | Mariocgo/CursoPython | /Test Operadores/Oplogico.py | 420 | 3.859375 | 4 | c = "python"
print(len(c) < 8 or c[0] == "f")
print("sistemas de becas 2021")
kilometros = int(input("A cuantos kilometros vives de la escuela?: "))
hermanos = int(input("Cuantos hermanos tines en la escuela?"))
ingreso = int(input("de cuanto es el ingreso de la casa?: "))
if kilometros < 10 and hermanos < 2 or ingr... |
c96b82741ad50384e4ff8f5e29e60bdcd63c554c | Mariocgo/CursoPython | /Scripts/scrip.py | 210 | 3.765625 | 4 | import sys
if len(sys.argv)==3:
texto = sys.argv[1]
repeticiones = int(sys.argv[2])
for i in range (repeticiones):
print(texto)
else:
print("Error: Introdujiste 1 o más elementos")
|
3dcff9225c428635cae49e5f48d8e4849da0fb6a | Mariocgo/CursoPython | /Prueba Plenum/Prueba2.py | 527 | 3.953125 | 4 | def invertir_cadena(cadena):
cadena = list(cadena)
if "+" in cadena:
cadena.remove("+")
cadena.append("+")
strA = "".join(cadena)
return strA[::-1]
elif "-" in cadena:
cadena.remove("-")
cadena.append("-")
strA = "".join(cadena)
return strA[::-... |
30e901c77786c1803fa054cc36961361a43b68ca | Jenoe-Balote/ICS3U-Unit6-04-Python | /list_average.py | 1,558 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Jenoe Balote
# Created on June 2021
# This program determines the average of a 2D list
# with limitations inputted by the user
import random
def calculate_average(number_list, rows, columns):
# This function calculates the average
# sum of numbers in list
total =... |
5a48a755920332aa67400b5256f34739068fc0fa | Shreevatsa25/Live-Session-codes | /Popped element.py | 401 | 3.8125 | 4 | num=[]
"""user input"""
numcount=int(input("how many numbers do you want to input?"))
for i in range(numcount):
element= int(input("enter number:"))
num.append(element)
userNum=[]
for i in num:
if i not in userNum:
userNum.append(i)
print(num)
print(userNum)
poppe... |
33a35a97d3c936a6c6cc4bd0250904f8022b67d8 | arpitdixit445/Leetcode-30-day-challenge | /Day_12__Last_Stone_Weight.py | 1,664 | 3.703125 | 4 | '''
Problem Statement ->
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together.
Suppose the stones have weights x and y with x <= y.
The result of this smash is:
If x == y, both stones a... |
cfa3db9cd7599d1a15291c5d6c2f954ebc3080c6 | arpitdixit445/Leetcode-30-day-challenge | /Day_11__Diameter_of_Binary_Tree.py | 1,135 | 4.1875 | 4 | '''
Problem Statement -> Given a binary tree, you need to compute the length of the diameter of the
tree. The diameter of a binary tree is the length of the longest path
between any two nodes in a tree. This path may or may not pass through the root.
Examp... |
7020565cfecd92cb40895526c19405ad3ffb0074 | arpitdixit445/Leetcode-30-day-challenge | /Day_13__Contiguous_Array.py | 884 | 3.875 | 4 | '''
Problem Statement -> Given a binary array, find the maximum length of a contiguous subarray
with equal number of 0 and 1.
Example -> Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1... |
4fc3a0b0d7d516af99d0c2090cd5cf517377f334 | inwk6312winter2019/week4labsubmissions-charanpreet13 | /lab4_task7.py | 510 | 3.765625 | 4 | def fun(pattern,replacement,file1,file2):
try:
fin1=open(file1,"r")
fin2=open(file2,"w")
for word in fin1:
if word==pattern:
word=word.replace(pattern,replacement)
fin2.write(word)
print("file copying was successful")
return fin2
except:
print("file cop... |
b6a66e86e7b93481f9c8ae497a3b003721b80ca2 | Kleber9/Python | /forca.py | 3,279 | 3.59375 | 4 | import random
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 21:26:24 2020
@author: kleber
"""
def jogar():
apresentacao()
palavra_secreta = gera_palavra()
letras_corretas = verifica_tamanho_palavra(palavra_secreta)
enforcou = False
acertou = False
erros = ... |
adbe79b817c61549ce5cd59ea62bef08f88fefc4 | erldas/week2.4 | /task2-10.py | 308 | 3.5 | 4 | # Дан список, состоящая ровно из двух строк. Переставьте эти слова местами. Результат запишите
# в список и выведите получившийся список.
list_= ['stroka1', 'stroka2']
list_.reverse()
print(list_) |
b95a6c6882907504cfa7442d906117bed63a04f8 | hkkmalinda/python_simple_calculator | /simple_python_calculator.py | 641 | 4.15625 | 4 | # define functions
def add(a,b):
result = a + b
print(f'{a} + {b} = {result}')
def sub(a,b):
result = a - b
print(f'{a} - {b} = {result}')
def mul(a,b):
result = a * b
print(f'{a} * {b} = {result}')
def div(a,b):
result = a / b
print(f'{a} / {b} = {result}')
#getting inputs
a = int(i... |
21855146c0b188e86c385e7a0000436f6cbdba40 | vireulgr/myscripts | /Python/mathLabs/lab.py | 5,334 | 3.59375 | 4 | # -*- coding: cp1251 -*-
#
#
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
points = [] #
funcVals = [] #
#a = 0 #
#b = 10 #
#L = 5 #
epsilon = 10**-2 #
Q = sp.Function('Q') #
x = ... |
da9072f2dda579515dc64e2a086393349e0a9208 | Programator2/ppds | /fei/ppds/sync.py | 6,087 | 3.96875 | 4 | """
Author: Allen B. Downey, Matus Jokay, Roderik Ploszek
This file contains an example program from The Little Book of
Semaphores, available from Green Tea Press, greenteapress.com
This code is in the public domain.
"""
import os
import signal
import sys
import _thread
import threading
from random ... |
4a0a595c9ac1d6b2c212243a804d3ab5e954ed35 | DoseDjalmadaDunhaJunior/Estudo-de-python | /Arquivos/Aula1.py | 197 | 3.84375 | 4 | # Recebendo dados do usuario
nome = input("Qual seu nome?\n")
idade = input("E sua idade?\n")
print("ola {0} com {1} anos".format(nome, idade))
print(f"Seja bem vindo {nome} com {idade} anos")
|
501ffe752802f697255dc9c0fb7d8dba3bbd8b6e | DoseDjalmadaDunhaJunior/Estudo-de-python | /Arquivos/loops.py | 685 | 3.828125 | 4 | nome = "Vai tomar no cu"
lista = [1,2,3,4,5,6,7,8,9]
numeros = range(1, 10)
for i in nome: #iterando sobbre string
print(i)
print("===========================================")
for i in lista: #iterando lista
print(i)
print("===========================================")
for i in range(0, 10): #iterando range... |
32c14a010bea772305aada5a1e2a0575732ef02e | DoseDjalmadaDunhaJunior/Estudo-de-python | /Arquivos/ranges.py | 421 | 3.859375 | 4 | for num in range(11): #imprime de 0 a 10
print(num)
print("========================================")
for num in range(5,11): #imprime de 5 a 10
print(num)
print("========================================")
for num in range(1,11,2): #imprime de 1 a 10 indo de 2 em 2
print(num)
print("=====================... |
1593d4d5cf1d8acabcfa52e599bf77ead29a047c | UgreninovaAlena/Netology_Modul4_Homework4 | /HW3.py | 4,943 | 3.515625 | 4 | def find_document(documents, number = ''):
if number == '':
number = input('Enter document number: ')
index = -1
for docum in documents:
index = index + 1
for v in docum.values():
if v == number:
return {'result': index}
return {'result': None, 'massag... |
69e3a9fce70fd3e38092aeb2df6b0fe79a4995be | rsingh2020/BlockChain | /biggest.py | 421 | 3.9375 | 4 | def biggest (x,y,z):
if x >= y + z:
return x
if y>z:
return y
else:
return z
print(biggest(11,12,5))
'''
if y>z and x>y:
return x
if y<z and x>z:
return x
if y>z and y>x:
return y
if y<z and x<y:
return z
if y>z and x... |
fd23f9beba1f5e6fb0266e3f7b3e18097a6b8983 | rsingh2020/BlockChain | /median.py | 580 | 3.84375 | 4 | def median(x,y,z):
s = (x, y, z)
c = list(s)
median_value = sum(c)/len(c)
v = round(median_value)
return v
#print(median(1,2,2))
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def median(x, y, z)... |
8d50fa01fef2a1e441858630b926a2be4d240675 | Himayeth/GitTest | /Test.py | 297 | 3.75 | 4 | import re
regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
def check(email):
if(re.search(regex,email)):
print("Valid Email")
else:
print ("Invalid email")
if __name__ == '__main__':
email ="ankitrai@gmail.com"
check(email)
email = "ankitrai"
check(email)
|
3f33e0fcdfce8acc247c6117949c4d6dbbb6449b | iamprayush/Stanford-Algorithms | /Part 2/Contraction Algortithm/minCut.py | 1,027 | 3.8125 | 4 | # Version 3.6
import random
from copy import deepcopy
# There will be an adjacency list of the given undirected graph
graph = {}
def minCut(graph):
'''
Input: Dictionary containing the adjacency list of the graph
Output: # of crossing edges after the min-cut
'''
while len(graph) > 2:
# picking vertices of a ra... |
1d2a521273eebe36f5f1df1ddb7f0c0d02e363d9 | nikkim97/Transit | /src/db_func.py | 732 | 3.609375 | 4 | import pandas as pd
def set(key, value):
"""Sets value associated with a key. No return value"""
new_data = pd.DataFrame({
'Trains': key,
'Times': [value]
})
new_data.to_csv('Transit-Info.csv', mode='a', index=False, header=False)
def fetch(key):
"""Retrieve object set at a key. Re... |
ce310820c9f1317e2a827def7344c29ce772876e | NiteshBaith/FSDP_2019 | /day2 challanges/restart.py | 325 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 6 17:12:34 2019
@author: Baith
"""
str2 = "RESTART"
count =0
for i in str2:
if i=="R":
print(count)
if count>0:
str3=str2.replace("R","$")
count=count+1
str4=str3.replace("$","R",1)
print(str4)
... |
7634825fbcf56d07c42d319296652f08802e121a | NiteshBaith/FSDP_2019 | /jason and taking to net/faculty.py | 1,401 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 15:04:10 2019
@author: Baith
"""
"""
Code Challenge
Name:
Student and Faculty JSON
Filename:
student.json
faculty.json
Problem Statement:
Create a student and Faculty JSON object and get it verified using jsonlint.com
Write a JSON for facu... |
805ccac7d158a651f4b5f5acd5723e4eb750436f | NiteshBaith/FSDP_2019 | /day2 challanges/factorial.py | 284 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 6 16:15:19 2019
@author: Baith
"""
n = int(input("Enter the no"))
i=0
fact=n
while (i<n):
n=n*(fact-1)
fact=fact-1
i=i+1
if (fact==1):
break
print(n)
"""and"""
import math as m
fct=m.factorial(no)
|
deca8f389ad35af32e8b1f5413f0880fe70ee291 | NiteshBaith/FSDP_2019 | /jason and taking to net/correncyconvert.py | 1,243 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 22 14:12:12 2019
@author: Baith
"""
"""
Code Challenge
Name:
Currency Converter Convert from USD to INR
Filename:
currecncyconv.py
Problem Statement:
You need to fetch the current conversion prices from the JSON
using REST API
Hint:
http:... |
4e035af0d0f80139ad28b802cfedc75226ad6e90 | NiteshBaith/FSDP_2019 | /day3 challanges/operation.py | 669 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 14:34:32 2019
@author: Baith
"""
import functools
import operator
def Add(x):
print("Sum is :",sum(x))
def Multiply(x):
print(functools.reduce(operator.__imul__ ,x))
def Largest(x):
print("maximum is:",max(x))
def Smallest(x):
print("minimum is:",m... |
7093bc7c2842360eeda079159b37ea3b9b70c656 | NiteshBaith/FSDP_2019 | /day3 challanges/centered.py | 321 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 22:13:53 2019
@author: Baith
"""
input_avg=input("Enter inputs ")
input_avg=input_avg.split()
input_avg=list(map(int,input_avg))
srt_avg=sorted(input_avg)
srt_avg.remove(srt_avg[0])
srt_avg.remove(srt_avg[len(srt_avg)-1])
avg=sum(srt_avg)/len(srt_avg)
print(avg)
... |
3a879072ef47ca5095eb088672944bb1e5a9ae80 | NiteshBaith/FSDP_2019 | /day 1 challanges/gravity_cal.py | 177 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 5 16:45:13 2019
@author: Baith
"""
time= float(input("Enter the time in sec"))
print("distance travelled is", 9.81*time*time/2)
|
4e7bf4438135af2f6782353d2c54ea4047976ef8 | split-t13s/Anagram_Solver | /solver.py | 3,233 | 3.890625 | 4 | import nltk
import re
from nltk.corpus import wordnet as wn
all_words = wn.all_lemma_names()
regexp = re.compile('^[A-Za-z]{3,}$') # Strings with 3 or more letters
"""
Takes the list of all words and removes any word that does not match the
specified regular expression 'regexp'.
"""
def filter_all_words():
... |
c43ebbe77c89e0e72019436179ee8fd22bdc2a50 | CeciFerrari16/Esercizi-Python-1 | /es31.py | 1,924 | 4.21875 | 4 | # Esercizio 31
'''
Fornisci la rappresentazione in binario di un numero decimale.
Dopo aver acquisito il valore del Numero da trasformare, si esegue la divisione del numero per 2
e si calcola quoziente e resto. Il resto è la prima cifra della rappresentazione binaria.
Si ripete il procedimento assegnando il quozien... |
8b2d7ddd6ab83f9050b327cf5fe40c50b43547ca | mvpanda10/maze_game | /rooms/room_11.py | 3,144 | 3.921875 | 4 | import adventure_game.my_utils as utils
room11_interacts = {
'fire' : True
}
room11_inventory = {
}
# # # # # # # # #
# Room 2
# This room can only be gotten too from Room 1
# You can only go to room 1
# You can take a key0
# There is nothing to use in this room
#
# ... |
2aea405d4ce58e2e726163d42ca7d815e7c901dc | mvpanda10/maze_game | /rooms/room_6.py | 5,119 | 3.640625 | 4 | import adventure_game.my_utils as utils
# # # # #
# ROOM 3
#
# Serves as a good template for blank rooms
room6_description = '''
. . . 6th room ...
Another room with blank bright white walls. In the corner, however, there lies a sink.
The faucet is running and there appear to be no knobs or clam... |
c0379fcf57445e141b569634ec8a0cb27ef250d9 | Sudani-Coder/python | /Turtles/index7.py | 350 | 3.796875 | 4 | import turtle
square = turtle.Turtle()
square.width(5)
square.penup()
square.backward(140)
square.pendown()
for prettycolor in ["red", "orange", "yellow"]:
square.color(prettycolor)
for side in range(0, 4):
square.forward(50)
square.right(90)
square.penup()
square.forward(100)
... |
df40f13d105229bd08bb69536e0a1c05a606acfa | Sudani-Coder/python | /Rock Paper Scissor Game/index.py | 2,249 | 4.5 | 4 | ## project11
# Rock - Paper - Scissor "Game"
import random
print(
"""
Winning Rules: \n
"Rock vs paper => paper wins" \n
"Rock vs scissor => Rock wins" \n
"paper vs scissor => scissor wins \n
"""
)
# Step 1: Conditions for the User
while True:
print("\nEnter Choice 1.Rock 2.Paper 3.Scisso... |
72080afb57f4c2e02c0a15b7a5ba49fe378cb50b | Sudani-Coder/python | /Silly sentences/silly.py | 1,050 | 4.15625 | 4 | import random
import words
def silly_string(nouns, verbs, templates):
# Choose a random template.
template = random.choice(templates)
# We'll append strings into this list for output.
output = []
# Keep track of where in the template string we are.
index = 0
# Add a while loop here.
... |
0670936deb07cafc9fbf1b223f60274a453392f7 | Sudani-Coder/python | /Turtles/index15.py | 272 | 4.03125 | 4 | import turtle
def polygon(sides, length):
t = turtle.Turtle()
t.color("lime")
t.speed(0)
angle = 360 / sides
for side in range(sides):
t.forward(length)
t.right(angle)
t.hideturtle()
for n in [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]:
polygon(n, 35)
input()
|
590c6535d0271e48b25e4357a15f0f4fe114ff91 | Sudani-Coder/python | /Encryption Using Dictionary/index.py | 752 | 4.09375 | 4 | ## Project: 3
# Encryption using Dictionary
# i will develop my script by adding decrypthion key mother fuckers حطور الكود بتاعي من التشفير الى فك التشفير
keys = {
"A":"E", "B":"F", "C":"G", "D":"H", "E":"I",
"F":"J", "G":"K", "H":"L", "I":"M", "J":"N",
"K":"O", "L":"P", "M":"Q", "N":"R", "O":"S",
"P":... |
6de3c086aa7b872c11bc56a4d1129b1e640f07d0 | Sudani-Coder/python | /Turtles/index19.py | 421 | 3.75 | 4 | import turtle
import random
riley = turtle.Turtle()
riley.width(5)
mood = random.choice(["happy", "sad", "angry", "party"])
if mood == "happy":
riley.color("yellow")
elif mood == "sad":
riley.color("blue")
elif mood == "angry":
riley.color("red")
elif mood == "party":
riley.color("magenta")
else:... |
30ed6e03789443de3629b9bc7e61c2ea21a573bb | Sudani-Coder/python | /Object Oriented Programming/index.py | 2,635 | 3.84375 | 4 | # Python Object Oriented Programming
import datetime
class Employee:
num_of_emps = 0 # Class Variable
raise_amount = 1.02 # Class Variable
def __init__(self, FirstName, LastName, salary):
self.FirstName = FirstName
self.LastName = LastName
self.salary = int(salary)
Employ... |
65cf2845d8c237a4b53f0d3091269a33557a57f2 | Sudani-Coder/python | /User Input/index.py | 286 | 4.125 | 4 | fName = input("\nwhat is your first name? ").strip().capitalize()
mName = input("\nwhat is your middle name? ").strip().capitalize()
lName = input("\nwhat is your last name? ").strip().capitalize()
print(f"\nHello World, My name is {fName:s} {mName:.1s} {lName:s}, Happy to see you.")
|
61a80d70de9b33de441c91e575d5f940da876dee | Sudani-Coder/python | /Number Guessing Game/index.py | 568 | 3.984375 | 4 | ## Project: 4
# Number Guessing game
import random
guess = []
cpu_num = random.randint(1, 100)
player_num = int(input("Please Enter A Number Between 1 To 100 --> "))
guess.append(player_num)
while player_num != cpu_num:
if player_num > cpu_num:
print("Too High !")
else:
print("Too Low !")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.