blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
85af5f57c80470118576937aef861da6a0832fff | pvpk1994/Leetcode_Medium | /Python/Palindromes/Break_Palindrome.py | 672 | 3.796875 | 4 | # Break A Palindrome
# Auhtor: Pavan Kumar Paluri
# LeetCode Question: https://leetcode.com/problems/break-a-palindrome/
class Solution:
def breakPalindrome(self, palindrome: str) -> str:
# break a pal
for i in range(0, len(palindrome)//2):
# If a non 'a' encountered in any pos of first... |
0d61ede6054cfb9d66d01ca74ad7a77b19d11460 | codeAligned/LEETCodePractice | /Python/AverageOfLevelsBinaryTree.py | 724 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
... |
25667443884c92a5d06900b1d77875b26a2b5238 | altanai/cirq_quantum_programming | /simulators/simulator_invertible.py | 809 | 4.15625 | 4 | # Invertible gates and operations
# cirq.inverse has a default parameter used as a fallback when value isn’t invertable.
# cirq.inverse(value, default=None) returns the inverse of value, or else returns None if value isn’t invertable.
import cirq
def main():
# Pick a qubit.
qubit = cirq.GridQubit(0, 0)
#... |
25d2df685c0a1767c7029e2dd2c44d76ac1ed612 | 4llower/create-app | /templates/python/main.py | 690 | 3.71875 | 4 | def main():
# fin = open('input.txt', 'r')
# fout = open('output.txt', 'w')
print('Hello world!')
if __name__ == "__main__":
main()
# print('anything', file = fout) -> write anything to output.txt with '\n', print('anything', file = fout, end = '') without '\n'
# fin.realine() -> get string from inpu... |
094f4e995a436f294871f196442d5e7e8869fdf0 | kyrajeep/reinforcement_learning | /Cartpole_Q_table.py | 1,191 | 4.09375 | 4 |
import numpy as np
import gym
#Load the gym environment
env = gym.make('FrozenLake-v0')
#create an empty array with shape of the environment
Q = np.zeros([env.observation_space.n,env.action_space.n])
#initialize the parameters. Why are we setting d and y such as they are??
d = .7
y = .95
num_episodes = 2000
rList = []... |
7309b8817c82fe55887713a102a1343c13c759c9 | Yquetzal/tnetwork | /build/lib/tnetwork/utils/intervals.py | 13,827 | 4.09375 | 4 | import copy
import sortedcontainers
import numbers
class Intervals:
"""
Class used to represent complex intervals
This class is used to represent periods of existence of nodes and edges. Nodes and edges can exist during
not continuous periods (e.g., from time 2 to 5, and from time 7 to 8). Those inter... |
5403107401740cf1dd483547ca6bd1024110baf0 | RyanHuang1102/python | /leetcode/Medium/DailyTemperatures.py | 481 | 3.546875 | 4 | #!/usr/bin/python
def dailyTemperatures(T):
"""
:type T: List[int]
:rtype: List[int]
739. Daily Temperatures(medium)
"""
n = len(T)
ret = []
start = 1
for i in range(n):
for j in range(start,n):
if T[i] < T[j]:
ret.append(j-i)
star... |
8cc4f947b79c5ad3cf5804758f659ed2bbef6686 | worldofmagic/leetcode | /python/110.balanced-binary-tree.py | 834 | 3.71875 | 4 | #
# @lc app=leetcode id=110 lang=python3
#
# [110] Balanced Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(s... |
91fb0123a856e15d6d63c0416415fd155de20b23 | lucasjoao/exercism_python | /run-length-encoding/run_length.py | 531 | 3.515625 | 4 | from itertools import zip_longest
def encode(chars):
encoded = ''
n = 1
for curr, nextt in zip_longest(chars, chars[1:]):
if curr == nextt:
n += 1
else:
encoded += curr if n is 1 else str(n) + curr
n = 1
return encoded
def decode(chars):
decoded... |
439954e817187f825bf8b000be257574c01ff1b5 | TypeLemon/For-Loops-Practice | /Solutions/2_8_4_for_loops_sol.py | 224 | 4.09375 | 4 | start = int(input("Enter a start number: "))
end = int(input("Enter an end number: "))
increment = 1
if start > end:
increment = -1
end = end - 1
else:
end = end + 1
for i in range(start, end, increment):
print(i) |
81ddcfa416646b10753842ca376da2f72ba00292 | AlexRuadev/python-bootcamp | /05 - Python Statements/useful_operators.py | 1,685 | 4.21875 | 4 | mylist = [1, 2, 3]
# range generates the number all the way to the number indicated but not including it
for num in range(10):
print(num)
# range from 3 to 10, excluding 10
for num in range(3, 10):
print(num)
# range from 0 to 10, excluding 10, going 2 by 2
for num in range(0, 10, 2):
print(num)
# for e... |
3113d9984d37c4055bdf1fdca35af0dfe356de01 | DasisCore/python_challenges-master | /pyChallenge_033.py | 223 | 4.03125 | 4 | import math
num1 = int(input("Enter the first number : "))
num2 = int(input("Enter the second number : "))
ans1 = num1 // num2
ans2 = num1 % num2
print('"' , num1 ,'dicided by', num2,'is', ans1, 'with',ans2, 'remaining "')
|
89efc384986b64c5850213a2a5865010825dd7c0 | alessandrogums/Desafios-Python_Variaveis_compostas-tuplas- | /Exercicio.73_CV.py | 952 | 3.8125 | 4 | # Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre:
# a) Os 5 primeiros times.
# b) Os últimos 4 colocados.
# c) Times em ordem alfabética.
# d) Em que posição está o time da Chapecoense.
times_brasileirao=('Atlético-MG','Pa... |
1031bc7c93c47e083ca8b8bffa3e9a0205c49743 | guankai1/hanshu | /gk_11for迭代遍历.py | 129 | 3.734375 | 4 | name_list = ["李讲","试试","后四十","为企业"]
for my_name in name_list:
print("傻逼的名字是: %s" % my_name) |
af7b3c0f89728cbf46f97166cdabd74f799dc436 | nahgnaw/data-structure | /exercises/array/merge_intervals.py | 815 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
"""
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
c... |
10d74071f00dfc43cc16902f17bb50dee2ee2f23 | RickUniverse/Python | /05_高级变量/hm_05_运算符.py | 917 | 3.90625 | 4 | # 运算符 + *
list_array = ["11", "22"] * 3
print(list_array + ["2"])
list_array.append(["q","d"])
print(list_array)
list_array.extend(["zzz", "zzzcd"])
print(list_array)
# in, not in
tuple_array = ("123", "abc")
print("abc" in tuple_array)
dictionary_dic = {"name": "xiaoming",
"age": 15}
print("name" in ... |
199c5f186d31393315a180428440b0c518821861 | max180643/PSIT-IT | /Week-4/Table I.py | 321 | 3.75 | 4 | """
Table I
Author : Chanwit Settavongsin
"""
def main(number):
"""
Print 15 x n (multiple table)
Ex. n = 10
output : 15 x 1 = 15
15 x 2 = 30
.
.
15 x 10 = 150
"""
for i in range(1, number + 1):
print("15 x %i = %i" % (i, 15 * i))
main... |
e197164706348030378e75d490672d715a7fe573 | Harshala-Gaikwad/Programming | /Leetcode/stack/backspace_string_compare.py | 422 | 3.75 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
S1 = ""
T1 = ""
for i,x in enumerate(S):
if x=="#":
S1 = S1[:-1]
else:
S1+=x
for i,x in enumerate(T):
if x=="#":
T1 = T1[... |
bd47b85e31a54428286e88fec9cc5eada8a8c7b8 | rbrowngt/Practice | /src/practice2.py | 909 | 3.734375 | 4 | class CWStack(object):
pass
def __init__(self):
self.stack = []
def isEmpty(self):
return self.stack == []
def push(self, element):
self.stack.append(element)
def pop(self):
return self.stack.pop()
def top(self):
if self.is... |
f1cc37024d0622fea0303320adf36471f8e198d6 | jiangsir/PythonBasic | /datas/Myclasses/Dog.py | 251 | 3.578125 | 4 | class Dog():
#-------------------
# __init__ 建構元
#-------------------
def __init__(self, name, age):
self.name = name
self.age = age
def humanage(self):
return 22+(self.age - 2) * 5
|
f9ed17ba738fdba0890b130d7a9cc45822d6d740 | ElijahDR/adventofcode-2018 | /day1.py | 828 | 3.5 | 4 | def part1(inputData = "input/input1.txt"):
freq = 0
with open(inputData) as f:
for line in f:
freq += int(line)
print("day 1, part 1: " + str(freq))
# Credit goes to Micah Waring
def part2(inputData = "input/input1.txt"):
seen = set()
with open(inputData, "r") as f:
dat... |
d20804e338d5379cd41e5c1a586c26ac71e3ff2d | dmitridrozdov/python-django-selenium | /daily_coding/day1.py | 783 | 3.984375 | 4 | # Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
def calc_for_list_head(lst_head, lst, possible_sum):
if not lst:
return False
else:
if lst_head + lst[0] == possi... |
9c460bd00d40d4b29c170aff37dac71971ec40bc | mirzasaad/EPI_Solutions | /merge_sort_in_place.py | 732 | 3.875 | 4 | import math
def merge(A, left, middle, right):
L = A[left:middle]
R = A[middle:right]
i = 0
j = 0
k = left
while i < len(L) and j < len(R):
if L[i] < R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
k += 1
while i < len(L):
A[k] = L[i]
i += 1
k += 1
w... |
221420c76070d0357f62736ec9bab5e2fd32e27c | defcxz/2020_prog.algoritmos | /EjerciciosGuia5/ejercicio4.py | 1,174 | 3.671875 | 4 | clp_usd = 0.0012
ars_usd = 0.015
mxn_usd = 0.042
pen_usd = 0.3
opc = int(input("Ingrese la opción requerida para convertir dinero.\n1 - Chileno\n2 - Argentino\n3 - Mexicano\n4 - Peruano\n5 - Salir\n"))
if (opc == 1):
print("-- Ha seleccionado pesos chilenos (CLP) --")
ing = int(input("Ingrese la cantidad de d... |
cbddabdf3fcae5e144ab3663d069d950013df4d5 | alegume/intro-python | /105.py | 3,341 | 3.96875 | 4 | #!/usr/bin/python3
# Importacao do modulo sys
import sys
'''
DESAFIO!!!
1) Crie uma lista com os 1000 primeiros numeros pares. Não use loop!
2) Crie uma lista com os numeros de 0 ate 99999999999999999999999999. Depois crie um loop para percorrer a lista ateh encontrar o primeiro multiplo de 5.
OBS.: U... |
899449231f1b219dbdebf84008bb2fa8a50cbb98 | vatana7/challenges-progress | /two_sum_hash_map.py | 789 | 3.53125 | 4 | #Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
#You may assume that each input would have exactly one solution, and you may not use the same element twice.
#You can return the answer in any order.
#Input: nums = [2,7,11,15], target = 9
#Output:... |
720e0a6f06aedb72ff6796e091d67c164a8598fd | Seigakuin/todays_task | /projects/sep_open_club/dice_animation.py | 1,381 | 3.96875 | 4 | """Dice 5
テーマ:
手順:
課題:
https://pygame-zero.readthedocs.io/en/stable/hooks.html#buttons-and-keys
"""
import random
# Global 変数をここに記述
WIDTH = 800
HEIGHT = 600
TITLE = "Dice!!!"
DICE_LIST1 = [
Actor("dice/die_white1"),
Actor("dice/die_white2"),
Actor("dice/die_white3"),
Actor("dice/die_white4"),
... |
955647d033ba4d4838f086afc483df8616b65637 | shiyymoon/leetcode | /reverseList.py | 322 | 3.90625 | 4 | def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
#不懂这个解法为什么不行
if head is None or head.next is None:
return head
p = head
while p.next:
q = p.next
p.next = q.next
q.next = head
head = q
return head |
9159c0bc425c3dfe04aad97cdde7a205959f5b6b | chrispm164/BlackJack | /main.py | 3,106 | 3.625 | 4 | from Deck import *
from Dealer import *
running = True
while running:
players = []
win_score = 0
winners = []
d = Deck()
d.shuffle()
dealer = Dealer()
print('Welcome to BlackJack.\n')
prompt = ''
while prompt == '':
try:
prompt = int(input("How many players?... |
0efaaaa50fe13e4d78e9e178cce1fc105857a20f | AlexPersaud17/my_python_progress | /labs/squares.py | 196 | 3.890625 | 4 | def main() :
num = 0
ITERATIONS = 6
i = 1
print("Number Square")
while i <= ITERATIONS:
num += 1
if num % 2 == 1 :
num_sq = num**2
print(num, num_sq, sep="\t")
i += 1
main()
|
da1f6d430dcd531828323afd3e8d68b091085f40 | vinodhkrishna/PyPrograms | /BasicPrograms/StringFormatting.py | 708 | 4.1875 | 4 | _author = "Vinodh krishna E M"
print("Vinodh age is " + str(32))
print("Vinodh age is {0}".format(32))
print("""Welcome to "Hello" World {0} and python's {1} programs altogether {0}""".format("program", "24"))
#formatting operator is replaced by replacement operator
print("There are {0} days in {1}, {2}, {3}".format(3... |
d7b76ad353373692c2b4574e29f7d9dcf54c6ea2 | GeorgeYan/op_py | /my_file.py | 301 | 3.75 | 4 | #-*-coding:utf-8-*-
import sys
import os
import re
if __name__=="__main__":
fl=file("aaa.txt","r")
count=0
for s in fl.readlines():
li=re.findall("hello",s)
if len(li)>0:
count=count+li.count("hello")
print "查找到"+str(count)+"个 hello"
fl.close()
|
07f899ded65c86df9ca31e1d9030e290634a6a69 | verisimilitude20201/dsa | /LinkedList/single_list.py | 3,133 | 3.765625 | 4 | class SingleLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
class Node:
def __init__(self, data):
self.data = data
self.next = None
def prepend(self, data):
"""
O(1) Space/Time
:param data:
... |
1f438e4e9bc9f437a1ece60403fe8288e8ef0cf6 | mfannick/password-locker | /user_test.py | 4,425 | 3.828125 | 4 | import unittest
from user import User
class TestClasses1(unittest.TestCase):
pass
'''
Test class that defines test cases for the user and credential classes behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
####### UserClass##########
########... |
e44be3de373fb0d3b6918c0d035f5cb7dd777773 | m1tix/projectEuler | /Problems/problem008.py | 499 | 3.671875 | 4 | from math import prod
def problem008(n, k):
'''
Returns the largest product of k consecutive digits in n
'''
if n < k:
raise ValueError('n is too small')
entries = [str(n)[i:i + k] for i in range(len(str(n)) - k + 1)]
return max(map(lambda x: prod(int(i) for i in x), entries))
if... |
5ce502415b0407d48a8aaa80108caf8f90d623fe | rinslow/regene | /tests/functional/test_simple.py | 2,569 | 3.65625 | 4 | from unittest import TestCase
from regene import Regene
class StringTest(TestCase):
def test_single_character(self):
assert Regene("a").simple() == "a"
def test_multiple_characters(self):
assert Regene("abc").simple() == "abc"
def test_empty_string(self):
assert Regene("").simpl... |
b0efe22d82ac3268bbea4cde260fd897b1ab2e5a | rizkynoormuhammad/UJIAN | /sort_odd_even.py | 1,367 | 3.78125 | 4 | num = [5,3,2,8,1,4]
even = []
odd = []
result_odd = []
result_even = []
1.
class Solution:
def solve (num):
for i in num:
if i%2==0 : #fungsi untuk memisahkan bilangan genap
even.append(i)
else : #fungsi untuk memisahkan ganjil
odd.append(... |
c75309df3e0317334b4835012c9c2adc7bcbb900 | zhanibekov/python-learning | /len.py | 93 | 3.53125 | 4 | s= input()
print(len(s))
t= input()
number = int(t)
u = str(number)
print(s*5)
print(s+''+ u) |
25dcb358a89d65f0f0f3aef3cfc983da01920443 | shashikapradeep/PythonTutorial | /class/basic.py | 973 | 4.46875 | 4 | class Dog:
pass
dog = Dog()
print(dog) #<__main__.Dog object at 0x7fa33ffeafd0>
dog.name = 'Casper'
dog.breed = 'Labrador'
print(dog.name, dog.breed)
class Cat:
def walk(self): # since object is passed in to the method first argument accepts it and we define it as self
print('inside', self)
cat ... |
808f4d9e05528d5c0d357241a37e1f442c45c4f4 | real3stone/python3-webapp-3stone | /samples/SQLite3.py | 1,695 | 3.984375 | 4 | # -*- coding: utf-8 -*-
# 【数据库】练习
# SQLite3是Python内置的数据库,SQLite的特点是轻量级、可嵌入,
# 但不能承受高并发访问,适合桌面和移动应用
import os
import sqlite3
db_file = os.path.join(os.path.dirname(__file__), 'test.db')
if os.path.isfile(db_file):
os.remove(db_file)
# 初始数据:
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute('... |
b5f96c746c3f9e35c1a46249fda49bf36f882af2 | zhihongsun51/cis4362 | /HW2/prog2_1 | 1,471 | 3.515625 | 4 | #! /usr/bin/python
import sys
def check_command_line():
pad_bool = True
block_size = 8
pad_input = ''
for args in sys.argv[1:]:
if args == '-p':
pass
elif args == '-u':
pad_bool = False
elif args[:2] == '-b':
if args[2:] == '':
... |
5358c776f0c06169e9e8ba6744ae703ae7bf46bf | emersonp/psu-python | /4.2.ReversePhrase.py | 245 | 4.25 | 4 | # Copyright (c) 2014 Parker Harris Emerson
# Exercise 4.2 from Dawson's "Python Programming for the Absolute Beginner (3d)"
phrase = input("Enter a phrase to reverse: ")
for letter in range(len(phrase) - 1, -1, -1):
print(phrase[letter], end="")
print()
|
4268d5d04525189f795ed6d5cf973db1d901aa43 | chavhanpunamchand/PythonPractice | /Strings/Reverse_and_swap_case.py | 124 | 3.921875 | 4 | string= "pUNAMCHAND iS A pROGRAMMER tHIS"
words=string.split()
words=list(reversed(words))
print(" ".join(words).swapcase()) |
c51ebcca8d8a1e79700f962358ffc1aa42d6b113 | gauravlalwani/PythonClassFall2017 | /tkinterExamples/Label.py | 188 | 3.859375 | 4 | from tkinter import Tk,Label
# initializing the root window
root = Tk()
# displaying the label widget
x = Label(root,text="Hello World")
x.pack()
# keep the window displayed
root.mainloop()
|
d6fd176eb48a86de3ec88ec793e612a9789baa2b | gade008/estudos_python | /cursoemvideo/desafio084.py | 546 | 3.6875 | 4 | cont = 'S'
pessoas = list()
dados = list()
pesada = list()
leves = list()
# Leitura dos dados
while 'S' in cont:
dados.append(str(input('Nome: ')).lower().capitalize())
dados.append(int(input('Peso: ')))
cont = str(input('Deseja continuar? [S/N]'))
pessoas.append(dados[:])
dados.clear()
# analise do... |
a455e6f7dcc79049299b79be4ff16c72feeab46f | polowis/text-based-rpg-game | /character.py | 38,923 | 3.59375 | 4 |
# import required Python modules
import time
import random
######
### Define the attributes and methods available to all characters in the Character
### Superclass. All characters will be able to access these abilities.
### Note: All classes should inherit the 'object' class.
######
class Character:
""" Define... |
ea01bbf926259b8ba555ca13938161e0353e047d | ruteshr/python-interview-kit | /pascal_Triangle.py | 429 | 3.625 | 4 | #pascal's triangle
num,a=int(input("enter no of rows")),[]
for i in range(num):
row=[]
for j in range(i+1):
if(j==0 or j==i):
row.append(1)
else:
row.append(a[i-1][j-1]+a[i-1][j])
a.append(row)
for i in range(num):
for j in range(num-i-1):
print(end=" ")
for j in range(i+1):
print(... |
dba69f6da20b473d4efc11adc7ee7b87b2f719d2 | CollinErickson/LeetCode | /Python/57_InsertInterval.py | 1,896 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 16 16:34:14 2018
@author: cbe117
"""
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __repr__(self):
return '[' + str(self.start) + ',' + str(self.end) + ']'
class Solu... |
ff78bd971995d6bc62dfeb537304fc0248ee2e31 | addfatdog/checkio-answer | /electronic-station/brackets.py | 753 | 3.84375 | 4 | def checkio(expr):
a_stack = []
for i in expr:
if i in '({[':
a_stack.append(i)
elif i in '}])':
if a_stack == []:
return False
else:
poped = a_stack.pop()
if poped == '(' and i != ')':
return... |
a6bd6b49eba6e07a0670306010b3ec71b1ef52d7 | alexcatmu/CFGS_DAM | /PRIMERO/python/ejercicio27.py | 354 | 3.796875 | 4 | '''
2) Volem fer un programa que ens mostri una
taula de multiplicar com per exemple la
que es mostra a continuació:
'''
#programa tabla multiplicar
#variables
tabla = " "
#codigo
for i in range (1,10):
tabla = " "
for cont in range (1,10):
mult = cont * i
tabla = tabla + str(mult) + " "
... |
3eb76489f19cb76e9f7d3bf1eb4e83c5cfca8643 | Hayden2018/COMP4331-Assignment | /Assignment 1/maximal.py | 818 | 3.765625 | 4 | # Read the frequent itemsets from text file
f = open('frequent.txt', 'r')
items = list()
frequency = list()
for line in f.readlines():
if len(line) > 2:
i, f = eval(line)
items.append(i)
frequency.append(f)
L = len(frequency)
maximal = [True for i in range(L)] # First assume maxial
for i in... |
78a73f730bd7e2ba09543463904ce72c8d403030 | USAMAWIZARD/datastructure | /Python/Array,List/multi dimentional Arrays/Matrix Multitplication.py | 257 | 3.859375 | 4 | array1=[[1,2,3],[1,2,3],[1,2,3]]
array2=[[1,2,3],[1,2,3],[1,2,3]]
array3=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(array1)):
for a in range(len(array2)):
for b in range(len(array2)):
array3[i][a]=array3[i][a]+array1[a][b]*array2[b][a]
print(array3) |
86aeb48adfad7762a2ac64e0fe85f50ee7af91b7 | noahklein/daily-coding-problem | /088.py | 428 | 4.09375 | 4 | """
Implement division of two positive integers without using the division,
multiplication, or modulus operators. Return the quotient as an integer,
ignoring the remainder.
"""
def divides(a, b):
if b == 0:
raise ArithmeticError()
if a < b:
return 0
return 1 + divides(a - b, b)
assert(d... |
aa09104eb55ce2d39f2971a5a47ef431590fdfb0 | formencode/formencode | /src/formencode/htmlgen.py | 6,402 | 3.5 | 4 | """
Kind of like htmlgen, only much simpler. The only important symbol
that is exported is ``html``.
This builds ElementTree nodes, but with some extra useful methods.
(Open issue: should it use ``ElementTree`` more, and the raw
``Element`` stuff less?)
You create tags with attribute access. I.e., the ``A`` anchor ... |
11d020f7a87b7b3841330d91e337b1421e825663 | tapioka324/atcoder | /ABC/145/b.py | 172 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# input
N = int(input())
S = input()
# solve
ans = False
if S[0:int(N/2)] == S[int(N/2):]:
ans = True
# output
print('Yes' if ans else 'No')
|
02b98f21e67981b0e7ef04060b3c72998d8d9ad2 | jamesmcc90/PythonProject | /python_james.py | 625 | 3.703125 | 4 | # Data Visualisation using Python#
# Pandas is used for working with tabular data
# Matplotlib is used for data visualization
import pandas as pd
import matplotlib.pyplot as plt
import pylab
df = pd.read_csv('BalanceDetails_20210806.csv', encoding = "ISO-8859-1")
print(df)
names = ['group_a', 'group_b', 'group_c'... |
28f8f0d45ddc28339d0b9e837ef4e4ab4e6e5ca4 | choi-jae-hyuck/Script_learning | /script_04.py | 5,253 | 3.9375 | 4 | class Rectangle:
def __init__(self,width=1,height=2):
self.width = width
self.height = height
def getArea(self):
return self.width*self.height
def getPerimeter(self):
return (self.width+self.height)*2
def test():
r1=Rectangle(4,10)
r2=Rectangle(3.5,35.7)
print("r... |
964909a213fc03e82904b75f5ae2062e1e7f4be4 | Ktsunezawa/Python-practice | /complete/1002/myclass.py | 293 | 3.65625 | 4 | class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def bmi(self):
result = self.weight / (self.height * self.height)
print(self.name, 'のBMI値は', result, 'です。')
|
e6d522cd6d1e86f59296afa5601e6972ce364eb4 | NoorKhan/cracking-the-coding-interview | /Chapter 1/1.2.py | 392 | 3.890625 | 4 | def is_permutation(string_a, string_b):
if len(string_a) != len(string_b):
return False
# sort strings and walk comparing each character, O(n log n)
sorted_a = sorted(string_a)
sorted_b = sorted(string_b)
for i in range(0, len(sorted_a)):
if sorted_a[i] != sorted_b[i]:
... |
4efa87164e3c3815b1487398f961692155378fa7 | iv-ivan/bot_chgk | /league.py | 215 | 3.53125 | 4 | class League(object):
def __init__(self, title: str):
self.teams = set()
self.title = title
def __str__(self):
s = "{}:\n".format(self.title)
for team in self.teams:
s += "{}\n".format(team)
return s |
1f0428377532a163ab7dbe6a3afb3ff4213c121f | huangkai31/practicepython | /ex16.py | 770 | 3.9375 | 4 | # https://www.practicepython.org/exercise/2014/05/28/16-password-generator.html
# Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every... |
dd2c5b50af5338c94c2017c7a66e2415260ec344 | ghostklart/python_work | /05.02.py | 1,193 | 4.03125 | 4 | #5.2
#1
line1 = "I need to study more."
line2 = "I need to get a good night sleep."
result = line1 == line2
print(f"1st line comparison result is: {result}.")
#2
line1 = "I need to study more."
line2 = "i need to study more."
result = line1.lower() == line2
print(f"2nd line comparison result is: {result}.")
#3
numb... |
5b3615cbfe5b8ceb3ed7ba78adec494e407943db | jingnanzh/linkedinCourser-Ex_Files_Learning_Python | /Ex_Files_Learning_Python/Exercise Files/Ch3/quiz2.py | 1,912 | 4.25 | 4 | # quiz2.py
import calendar
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
# Question 1 of 7
# Which code can you use to print a standard, text-formatted monthly calendar for every month in 2020, using Sunday as the first day of the week?
import calenda... |
66c7045896be39653bc90fb1dc3b90fa36c9a080 | santoro63/SudokuSolvers | /Python/sudoku.py | 2,095 | 3.765625 | 4 | #!/usr/bin/env python -w
import sys
def row(pos):
return pos/9
def col(pos):
return pos % 9
def square(pos):
row_g = row(pos)/3
col_g = col(pos)/3
return 10*row_g + col_g
def rcg(pos):
return [row(pos), col(pos), square(pos)]
IDX = [ rcg(i) for i in range(0,81)]
def load_puzzle(fname)... |
39149769e33a3c395033fe2a9357c80ffbb04364 | Hedroed/PyCalculator | /pycalclib/type/BaseType.py | 2,415 | 3.90625 | 4 | #!/usr/bin/env python3
# coding: utf-8
from typing import Any, Optional
from abc import ABC, abstractmethod
class BaseType(ABC):
"""Define a abstract Type object
Attributes:
name (str): The name of the type in pycalc syntax, if is None take the name of the class
"""
name: Optional[str] = No... |
4718cd26c3eb46d93a05343aac9721b07fb5670f | douglasdza/TIC | /3º Trimestre/Aula26.py | 4,091 | 4.3125 | 4 | # 18 de setembro de 2018
# Não é necessário colocar ponto e vírgula no código pois Python não exige.
# Este é um comentário.
print("Olá mundo :D") # Exemplo de print.
print("Olá Hueco Mundo")
'''
Um comentário em bloco é definido com três aspas.
As aspas podem ser simples ou duplas.
'''
# Variáveis não necessitam d... |
a15b4f2214c0b62545a272aca5a1f805bad6134b | alexthayn/PythonAlgorithms | /SREducationApplication.py | 335 | 4.1875 | 4 | #Alex Thayn 1/29/2019
#Sum of all multiples of 3 or 5 less than 1000
#Answer = 233168
def SumMultiplesOf3And5LessThan1000():
sum = 0
for i in range(1000):
#check if number is a multiple of 3 or 5
if i % 5 == 0 or i % 3 == 0:
sum += i
return sum
print(SumMultiplesOf3... |
2b15e700df808f3578c82edde7d76dfa1901a5c4 | dheeraj-khanna/Zero-to-Hero-bootcamp | /Code/ErrorsAndExceptions.py | 1,109 | 4.125 | 4 | # Problem 1
# Handle the exception thrown by the code below by using try and except blocks.
try:
for i in ['a','b','c']:
print(i**2)
except TypeError:
print("Some error")
# Problem 2
# Handle the exception thrown by the code below by using try and except blocks.
# Then use a finally block to print 'A... |
347e1ec7ca005ff50c8d7836e18a603072ef4f69 | shiyingyuxianshu/deep_learning | /DL01_1_from_WhaleChen.py | 682 | 3.578125 | 4 | # 上交作业的时候,才发现自己理解错误了,向WhaleChen学习了相关内容
# 打开文件,读取文件
with open('./happiness_seg.txt') as f:
file = f.read()
import collections
filelist = file.split()
filelist2 = list()
for i in range(len(filelist)-1):
#定义每个独立的词即为 长度需要至少为2的词
#当然,这可能是一种过度的简化
#这样的好处是对于标点符号也自然被去除
if (len(filelist[i]) > 1 and len(file... |
9c64e66eb647f0f3288b4e6e078687996e579803 | a-falcone/puzzles | /adventofcode/2021/03a.py | 2,481 | 4.46875 | 4 | #!/usr/bin/env python3
"""
--- Day 3: Binary Diagnostic ---
The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case.
The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things ab... |
85e351c77cce6a2b7a7e4d7178b652a567fce82e | haole1683/Python_learning | /Python/2019-8-8-丰富else.py | 570 | 3.5 | 4 | try:
print(int('1234'))
except ValueError as reason:
print('出错了'+ str(reason))
else:
print('没毛病')
##else 是当没有异常时执行
##with语句
try:
with open('data.txt','w') as f:
for each_line in f:
print (each_line)
except OSError as reason:
print('出错了' + str(reason))
##使用... |
62151d9046939fbef84425c4c6e7997f815575f5 | wangdu1005/Learn-Algorithm-And-Data-Structure | /127_Topological_Sorting.py | 2,978 | 3.890625 | 4 | __author__ = "Wangdu Lin"
__copyright__ = "Copyright 2018, The Algorithm Project"
__credits__ = ["Wangdu Lin, jiuzhang"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Wangdu Lin"
__email__ = "wangdu1005@gmail.com"
__status__ = "Production"
"""
Definition for a Directed graph node
class DirectedGraphNode:... |
7e2c900bb04f9a8b0c6f14b69dc08471dd5e1c10 | Ceruleanacg/Crack-Interview | /LeetCode/Trees and Graphs/103. Binary Tree Zigzag Level Order Traversal/solution.py | 972 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
... |
63363f0f0de91ff09122aa0ed437343d46d1871e | LoicGrobol/python-im-2 | /corrections/man_1.py | 4,989 | 4.0625 | 4 | def la_plus_grande(longueur1, longueur2, longueur3):
"""Renvoie la plus grande longueur."""
# cette fonction existe déjà en python, pensez à lire la doc,
# il n'y a pas toujours besoin de recréer la roue !
return max(longueur1, longueur2, longueur3)
def est_equilateral(longueur1, longueur2, longueur3):... |
c091152030e77e96a66a9d8df2d0f32ddcc820cf | TechWriterLisa/My-Python | /Exercises/Beginner/Exercise4.py | 405 | 3.9375 | 4 | import math
# from math import pi
var=math.pi
'''
print('Enter Radius: ')
rad=input()
rad=float(rad)
'''
rad=float(input('Enter Radius: '))
area=var * (rad ** 2)
print('The area of a circle is ' + str(area) + ' with radius of ' + str(rad))
'''
#area=pir**2
import math
bigNum=math.pi
myRad=(input('Enter the radius... |
a314b217dd357f7efb3514a60e5bd5acd3a09ef5 | beidou9313/deeptest | /第一期/上海-棒棒糖/第二次任务-每日代码练习/2017-1/1-11/set.py | 489 | 3.859375 | 4 | #set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
set_source = set([1, 1, 2, 3, 4, 5, 6, 7])
set_demo = set('google')
set_list = set(['qwe', 'wer', 2, 2, 4, 5, 6, 7])
print(set_source)
print(set_demo)
print(set_list)
#add增加
set_demo.add(9)
print(set_demo)
#update 新增多个值
list_demo=['a','b','b']
set_demo.update(list_d... |
c83d8aeb35fd10713442530c8f236ceb8e90c906 | Akhileshbhagat1/All-prectice-of-python | /switch_case_python.py | 565 | 4.0625 | 4 | print("Enter these keywords to perform mathematical operations like....add for addition "
"\"add for addition\" \"sub for subtraction\" \"mul for multiplication\" \"div for division\" ")
def dispatch_dict(operator, x, y):
return {
'add': lambda: x+y,
'sub': lambda: x-y,
'... |
87c995990ce8123a10e8db868c855433350c870e | BILLYtheKIDyang/algorithm_UdiManber | /heap_remove.py | 606 | 3.5625 | 4 | def Remove_Max_from_Heap( A, n ) :
# input: a array representation oa heap A, with n elements
# output: the maximum root, new heap A', number of elements in A'
maxA = A[0]
A[0] = A[n-1]
A = A[:(n-1)]
parent = 0
child = 1
n = n - 1
while child < n - 1 - 1:
if A[ child ] < A[ child + 1 ] :
ch... |
6f286d4d21499c320a6e053d5e68dabfe9021377 | AkhilDasPanicker/Python | /functions/fact.py | 101 | 3.8125 | 4 | def fact(n):
for i in range(1,n+1):
if(n%i==0):
print i,
n=input("Enter a number : ")
fact(n)
|
b87e6227199c37e58c64d374e2b12eb0942fa09b | shelly2904/DSA-Practice | /TREE/tree_traversals.py | 2,073 | 3.671875 | 4 | from tree_utils import *
def inorder(root):
if not root:
return None
inorder(root.left)
print(root.data)
inorder(root.right)
def inorder_without_recursion(root):
S = Stack()
current = root
S.push(current)
current = current.left
while current:
S.push(current)
... |
5b35caa0f2fd982fc00266594298949fce01afd0 | SelinaBlijleven/MachineLearning | /10574689_Blijleven_Prog5/bayes.py | 8,188 | 3.796875 | 4 | """
Selina Blijleven 10574689
Programming Assignment 5
December 2015
"""
import csv
import numpy as np
class GaussianNaiveBayes(object):
"""
Predict functions
"""
def test_model(self, filename, misclassified=False):
"""
Tests the model with the given file and r... |
84845d7cd712dc87c34782d321b06964a8c0d6cf | kmace999/robo-advisor | /app/robo_advisor.py | 6,581 | 4.125 | 4 |
addmore = True
entering = True
#start copied function from past project readme setups
def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
... |
ce9a8a72dda0fd35f21ca9472a96489c2e6c7336 | MattAHughes/basic_api_and_number_processing_in_python | /testing_random_walks.py | 937 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 00:06:24 2021
@author: Vitamin-C
"""
# Modified random walk as a plot instead of a scatter plot
import matplotlib.pyplot as plt
from random_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
# Set the figure plotting size
plt.figure(figsize = (10... |
8fcb78556e296b2b0d704661e5c6fe16100109fb | xMrShadyx/SoftUni | /Python Fundamentals - January 2020/Function_Exercise/10_Array_Manipulator.py | 1,435 | 3.734375 | 4 | import sys
def read_number_list():
input_arr = input()
nums = []
for i in input_arr:
nums.append(int(i))
return nums
def exchange(nums, index):
new_lsit = []
for i in range(index + 1, len(nums)):
new_lsit.append(nums[i])
for i in range(index + 1):
new_lsit.append(n... |
6976ba3d95c472682b828dcd7190f44ab12c72f8 | therohitsingh/CODE | /Generall/searchchar.py | 144 | 4.09375 | 4 | s = input("Enter the string:- ")
v = input("Enter the char to search:-")
if v in s:
print("Char Found")
else:
print("not found") |
3d00a42a52942f81cdf98eb7302998499dedf267 | mahraanusha/Hacktoberfest2021-4 | /python/game.py | 1,423 | 4.125 | 4 | import random
print("\n\t\t\t******* Game of Snake, Water and Gun *******\n")
print(" There are some rules in this game.These are:-")
print("\tRule no.1:- You need to choose snake, water or gun")
print('\tRule no.2:- To choose snake type 1, to choose water type 2 and to choose gun type 3')
print("\tRule no.3:- If y... |
dc0efc9008fbff7a9db886ac84e9b7e5a38d9fe5 | PYuen1029/nobis-alexa-services | /future/nobisalexaservices/stockservice/stocks.py | 1,567 | 3.734375 | 4 | """
Stock client that performs a fuzzy search for a stock symbol, then looks for its price
"""
import json
import requests
YAHOO_STOCK_SUGGEST_URL = 'http://d.yimg.com/aq/autoc?query={}®ion=US&lang=en-US'
IEX_STOCK_PRICE_URL = 'https://api.iextrading.com/1.0/stock/{}/quote'
def suggest_stock_symbol(stoc... |
5f06616f264598a64a9264ff478734c0044dad05 | hxbc/python | /ch06/T6/T6-8.py | 480 | 3.546875 | 4 | listnum=['zero','one','two','three','four','five','six','seven','eight','nine','ten']
num1=raw_input('enter a num 0 to 1000:')
list1=list(num1)
li=[]
for i in range(0,len(list1)):
num2=listnum[int(list1[i])]
li.append(num2)
str1='-'.join(li)
print str1
'''import re
str1=re.compile(' ')
str2=str1.sub('... |
913e0b8cd8a3d61fe1c94bab9aacfac4af9f21d8 | Nawarrr/Breadth-First-Traversal-of-AVL-Tree-using-Circular-Deque | /code.py | 8,136 | 4.125 | 4 | #This Code is Impelementation for Circular QUEUE (Deque) and AVL Tree
#Then performing Breadth First Traversal of AVL Tree using Circular Deque
class CircularDeque:
def __init__(self, capacity: int):
"""
Initialize your data structure here.
Set the maximum size of the deque to be capacity.
... |
da34badbdc3f2e0adf79fec702432c0e965f9d0c | IshpreetKGulati/100DaysOfCode | /day22.py | 1,126 | 4.375 | 4 | """
Given a dictionary with nested dictionaries as values, extract all the values with of particular key.
Sample Input -> Output
Input : test_dict = {‘sup’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “b”
Output : [9, 10, 19]
Explanation : All valu... |
1cafb8708f44bfae9a531e55cf167678bd8a5a00 | aguinaldolorandi/Python_exercicios_oficial | /Lista de Exercícios nº 05 Python Oficial/Ex.14II-lista05.py | 1,037 | 3.9375 | 4 | # EXERCÍCIO Nº 14II- LISTA 05 - LISTAS
print('\n Quadrado Mágico')
print('################\n')
import random
import numpy
n=int(input('Insira matriz quadrada (qtde de linhas ou colunas): '))
matriz=numpy.arange(1,(n*n+1))
matriz.shape=(n,n)
resultado=False
def quadradoMagico():
global resultado
... |
8676b4df3c723df0cb77759ded7a5a2f4621d16b | kubencjusz/codewars | /ISLR_Z/Ch. 2.8.py | 1,265 | 3.5625 | 4 | # import csv
# import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 8a
college = pd.read_csv('College.csv', header=0)
print(college)
# # 8b
college = college.set_index('Uni') # dobra praktyka to ustawić ją przy imporcie
# 8c i
print(college.describe()) # same as summary() in R
# 8c ii
import se... |
dbd66765806e09a994e647c5ad9d8d6edbace408 | z23han/Data-Structure-and-Algorithm | /Python/search_insert_pos.py | 2,221 | 4.0625 | 4 | # given a sorted array and a target value, return the index if the target is found. otherwise
# return the index where it would be if it were inserted in order.
import random
# generate an array with sorted order
class Array_Generate:
def __init__(self):
self.array = []
for i in xrange(10):
... |
cf71e42866ba92f1bf3997c027296983b35e95f1 | 164159-Suraj/Devops_Python | /Qusetion2.py | 140 | 3.78125 | 4 | def divisibility() :
for i in range(2000,3201):
if(i%7==0 and i%5!=0):
print(i, end=',')
divisibility() |
d60f8290071b2eb29f50677fd359cd3f05fd486d | mukhoiran/python-basic | /operator.py | 94 | 3.515625 | 4 | """
and or not
& | !=
"""
if (1<2) & (7>5):
print('Correct')
else:
print('Wrong')
|
79804a05f0d8c060db0dbbdea7e22644472f1ec2 | nileshnegi/hackerrank-python | /day010/ex62.py | 478 | 3.984375 | 4 | """
Set .intersection() Operation
You are given two sets of student roll numbers. One set has subscribed
to the English newspaper, one set has subscribed to the French newspaper.
Your task is to find the total number of students who have subscribed to
both newspapers.
"""
if __name__ == "__main__":
n = int(input(... |
6d1712611e7b1e278e42d251dea2f12b9fa8a578 | pydevjason/Python-VS-code | /keys_and_values_method.py | 595 | 3.765625 | 4 | cryptocurrency_prices = {
"Bitcoin": 400_000,
"Etherium": 7_000,
"Litecoin": 10,
}
print(cryptocurrency_prices.keys())
print(cryptocurrency_prices.values())
print()
for currency in cryptocurrency_prices.keys():
print(f"The next currency is {currency}")
print()
for price in cryptocurrency_prices.val... |
9908eb4a5092bd74aa90479ab86f6612c5198936 | dahiana00/angarita | /ejercicio4.py | 1,288 | 3.703125 | 4 | usuarios={}
preg="SI"
ingrese=1
contador=0
print("\n bienvenidos a nuestro sistema, es un gusto brindarle nuestros servicios")
while preg=="Si":
while ingrese==1:
print("\n ingrese datos para ingresar nuevo usuario\n")
nombre=input("ingrese su nombre")
apellido=input("ingrese su apellido")
edad=inp... |
e776bd0ab9dc47430ed914dbcbcb705ed0a757a8 | sc076/Yonsei | /Programming/lab7/lab7_p3.py | 733 | 4.34375 | 4 | import turtle
#set windows size
turtle.setup(800, 600)
window = turtle.Screen()
#Initializes a turtle
drawing = turtle.getturtle()
drawing.hideturtle() #hides the turtle (i.e. the cursor)
#Drawing
drawing.penup() #Lifts pen up in order not to draw additional lines
drawing.setposition(-400,... |
c2b0dc2fe27b67143ffb45ed67bfcbe095325592 | MCAR43/School-Work | /CS5602_Crpytography/Final/FinalZip/ANDERSONQ7.py | 2,239 | 3.78125 | 4 | #!/usr/bin/env python3
import math
def primesInRange(lower, upper):
primes=[]
for num in range(lower, upper + 1):
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
break
else:
primes.append(num)
return primes
def congruency(primes, b, n):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.