blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
28c4debdf930dd843a06f1be5f864ff3c36ec799 | EsJuan-az/EjerciciosAlgoritmia-Python | /B- Fundamentación/Ejercicio22.py | 2,347 | 3.828125 | 4 | #Ejercicio 22: Estudiantes que aprueban la asignatura
#Construir un algoritmo que lea los datos de codigo y tres notas parciales (n1, n2 y n3) de un conjunto de estudiantes.
#para cada estudiante se deberá calcular e imprimir su nota definitiva, teniendo en cuenta que la primera nota parcial
#aporta el 35 porciento a... |
531178083562a6e514b2ce2f094767c4394fd738 | rester71/Burbuja | /burbuja.py | 652 | 3.640625 | 4 | class Burbuja(object):
lista = None
tam_lista = 0
def __init__(self, lista):
self.lista = lista
self.tam_lista = len(lista)
def ordenar(self):
i = 1
Ordenado = False
while i<self.tam_lista or not Ordenado :
i+=1
Ordenado = True
... |
f14be5dc633fe1027f1edb30210b596bac008252 | Toga13/python_study | /FizzBuzz_ver1.py | 307 | 3.6875 | 4 | i = 0
for i in range(1,101):
if i%15==0: #15で割り切れる場合
print("FizzBuzz")
elif i%5==0: #5で割り切れる場合
print("Buzz")
elif i%3==0: #3で割り切れる場合
print("Fizz")
else: #どれでも割り切れない場合
print(i) |
ff7d574923722f1a965a67f67de4f10380fc6c50 | msabbir007/Scalable-GUI-Project | /GUI_gameboard.py | 2,097 | 3.703125 | 4 |
# PROJECT description: This is a scalable GUI project which can create numerical puzzle game board. Here User can define
# the size of the board ( technically matrix'' dimention).
from tkinter import *
# Define the puzzle game board size.
SIZE=int(input("Please Define the Puzzle Board Size: "))
class GameGUI:
... |
413d7ba5353fc4f65de6fbb9547e438b6d5d9ef3 | diksha12p/DSA_Practice_Problems | /ImpmentTrie_alt.py | 1,129 | 3.921875 | 4 | import collections
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.ends_here = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
... |
8ed8291c15d0b44575a150037efbb50fea1adb90 | Dragon-L/L.leetcode | /generate_parenthesis.py | 1,472 | 3.703125 | 4 | # 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
#
# 例如,给出 n = 3,生成结果为:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
#
# cost 60ms and beat 65.17%
#
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
return self._generate_parenthesi... |
a1675fe88ef2a4c0680149bc46f233b148bafe62 | Leopoldarroyo25/progavanzada | /ejercicio30.py | 514 | 4.28125 | 4 | #ejercicio30
# In this exercise you will create a program that reads a pressure from the user in kilopascals. Once the pressure has been read your program should report the equivalent
# pressure in pounds per square inch, millimeters of mercury and atmospheres. Use
# your research skills to determine the conversion ... |
6250e424492cf983ef297eeb462aa42a8df96bf8 | jsearfoo/beginner-project-solutions | /Mean_Median_Mode.py | 1,109 | 4 | 4 |
def mean(list):
sum=0
for item in list:
sum += item
mean=sum/len(list)
return mean
def median(list):
sortedlist=sorted(list)
print("Sorted list = \n", sortedlist)
mid=int(len(list)/2)
return list[mid]
def mode(list):
sortedlist=sorted(list)
mo... |
efc79101e04c0caaff17b603e5f705fd3da20272 | zpoint/Reading-Exercises-Notes | /core_python_programming/6/6-12.py | 995 | 3.78125 | 4 | #a
def findchr(string,char):
if string.find(char):
return string.index(char)
else:
return -1
str = raw_input('Enter a string:\n')
chr = raw_input('Enter a char to be founded\n')
print findchr(str,chr[0])
#b
def rfindchr(string,char):
str2 = ''
l = len(string)
if string.f... |
338a79d4a92dd9ab766a047a138ef59bb3820613 | franciscogomes2020/exercises | /pt/104/python/main.py | 225 | 3.734375 | 4 | # Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
Ex: n = leiaInt('Digite um n: ')
|
ef03021cf3465f2873cb49ef57114497e46db552 | LucasLCarreira/Python | /ex039.py | 696 | 3.984375 | 4 | # Exercício Python 039
# LEIA O ANO DE NASCIMENTO E MOSTRE SE:
# AINDA VAI SE ALISTAR AO SERVICO MILITAR
# HORA DE SE ALISTAR
# JÁ PASSOU DO TEMPO
# DEVERA MOSTRAR TBM QUANTO TEMPO FALTA E QUANTO TEMPO PASSOU
from datetime import date
a = int(input("Qual é o ano de nascimento? "))
idade = date.today().year - a
if idad... |
f184b472d519043ff5190ca8c16dd96eaad6b06a | antoinemadec/test | /python/programming_exercises/q68/q68.py | 446 | 3.890625 | 4 | #!/usr/bin/env python3
print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt
Question:
Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
Answe... |
e61725ad02c3e63c19b2eedd22f8acf4e2433a64 | Ardhra123/Python-Programming | /isogram.py | 354 | 3.65625 | 4 | def is_isogram(string):
if isinstance(string, str) and len(string) != 0:
string = string.lower()
if len(string) == len(set(string)):
result = True
else:
result = False
elif not string:
result = False
else:
raise TypeError('Argument should be a st... |
6129277f4250bb3cfd0a19cdf19d04e9bfd4e222 | lin-justin/covid-viz | /plot.py | 10,194 | 3.515625 | 4 | import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
import plotly.figure_factory as ff
import plotly.graph_objects as go
from data import load_data
from utils import load_state_abbrevs, load_args, calculate_surrounding_coords, check_county, check_state
def plot(df, county = "Bar... |
afa4fa0b5ad53a1553bf690c1fb8bf32080e6173 | TrueFoXDeN/Kryptographie | /caesar.py | 465 | 3.65625 | 4 | def encrypt(x, k, alphabet):
return ''.join(reconvert([(n + k) % alphabet for n in convert(x)]))
def decrypt(x, k, alphabet):
return ''.join(reconvert([(n - k) % alphabet for n in convert(x)]))
def convert(x):
return [ord(a) - 65 for a in x]
def reconvert(x):
return [chr(a + 65) for a in x]
def ... |
c49b2173e31f549ef50ca6a36cfd407b88440303 | johnisanerd/theshadow | /home/pi/open_cv/old/camera-head_detection.py | 6,775 | 3.75 | 4 |
'''
1. THIS EXAMPLE READS THE FRONT and the side of the head.
"Brute Force" method.
K-Nearest Neighbor. - Idea is to search for closest match of the test data in feature space.
Face Detection using Haar Cascads -
Haar-cascade Detection in OpenCV. OpenCV comes with a trainer as well as detector. If you want to t... |
66d17f76eda2aaf54dc4c0d2550fec73ccefd119 | amamov/pythonic | /01_syntax/10_dictionary.py | 1,498 | 3.75 | 4 | #### Dictionary
# 변경할 수 없는 자료만 immutable(string, tuple, int 등)만 dictionary의 key가 될 수 있다.
# 순서(X), 중복(X), 수정(O), 삭제(O)
# dic={key1 : val1, key2: val2. ...]
"""
.keys()
.values()
.items()
.get(key, default)
"""
my_dic = {
"name": "sang seok-Yoon",
"age": 23,
}
print(my_dic) # {'name': 'sang seok-Yoon', 'ag... |
8b1f7329d82f99acbb8fa1c0f86d74758f2f47d8 | lilyfofa/python-exercises | /exercicio83.py | 628 | 3.78125 | 4 | expressão = input('Digite a expressão: ')
# contador = 0
# contador2 = 0
# for c in expressão:
# if c == '(':
# contador +=1
# elif c == ')':
# contador2 += 1
# if contador == contador2:
# print('A expressão está correta!')
# else:
# print('A expressão não é válida!')
lista =... |
7d941f4848a878ce87691d223857a05a7917b75d | isheebo/ShoppingLister | /shoppinglister/models/shoppinglist.py | 2,583 | 3.765625 | 4 | from datetime import datetime
class ShoppingList:
def __init__(self, list_id, name, notify_date):
self.list_id = list_id
self.name = name
# date on which to remind the owner of the shopping list
self.notify_date = notify_date
self.items = dict() # dictionary of Items and t... |
228c25e71f74c193e344f0d56d2123a57dde0731 | freeland120/Algorithm_Practice | /CodingTest_Python/BaekJoon/17210.py | 173 | 3.59375 | 4 |
n = int(input())
k = int(input())
if n>=6:
print("Love is open door")
else:
for i in range(1,n):
if k == 0:
print(i)
elif k == 1:
|
151d07213dfe18ebefbe33d83ee08761f634e18a | vyraun/nnlib | /nnlib/layers/layer.py | 1,251 | 3.5625 | 4 | from abc import ABC, abstractmethod
class Layer(ABC):
"""Base class for all layers implementations."""
@abstractmethod
def forward(self, *args):
"""Should perform a local forward pass of the layer. Parameters
should be the inputs to the layer and the outputs of the layer
should be... |
cb6468ae3347ef2abf1330c7517c2445e60b5b82 | triphazardd/ppbot | /cogs/utils/gambling/blackjack.py | 4,723 | 3.546875 | 4 | import typing
from dataclasses import dataclass
from enum import Enum
from .cards import *
class BlackjackState(Enum):
"""
BlackjackState of a blackjack game.
"""
DEALER_TURN: int = 1
DEALER_BUST: int = 2
DEALER_BLACKJACK: int = 3
DEALER_WIN: int = 4
PUSH: int = 5
PLAYER_TURN: in... |
6429efaaef583765276e946a9d2411d62db060e9 | GitZW/LeetCode | /leetcode/editor/cn/day_013.py | 1,576 | 3.796875 | 4 | """
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example:
Input: (7 -> 1 -> 6) + (5 -> 9 -> 2).... |
bd9c4e8d92a549c626753c4d15150c8a6e25c401 | koushik-chandra-sarker/PythonLearn | /a_script/m1_Dictionaries.py | 3,741 | 4.46875 | 4 | """
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
"""
user = {
"username": "koushikStack",
"password": 1234,
"active": True
}
pr... |
13b36f14ba6e1c27d376172096c029c0593ad213 | ChengQian505/StudyPython | /2019/12/first_week/day5_weekend.py | 354 | 3.890625 | 4 | # 打印九九乘法表
for i in range(1,10):
for j in range(1,i+1):
result=i*j
if result<10:
result=str(result)+" "
else:
result=str(result)
if j == i:
print(str(i)+"*"+str(j)+'='+result)
else:
print(str(i) + "*" + str(j) + '=' ... |
461649f93e470af8142fa9102ccf24fe07600b92 | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio131.py | 718 | 4 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" Definir una lista de enteros por asignación en el bloque principal. Llamar a una función que reciba la lista y
nos retorne el producto de todos sus elementos. Mostrar dicho producto en el bloque principal de nuestro programa. """
def producto_elementos(owo):
pro... |
7ef6122891eb87252beb26ced549d20cb4696d8d | Ankityadav200/python_course | /day4/chalenge7.py | 485 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 15:28:48 2019
@author: ankit
"""
#challenge7
#Lets give user the option to play again
import random
secret_no=random.randint(0,10)
i=input("do you want to play again (Y/N):")
while(i!="N"):
if (i=='Y'):
gues_no=int(input("enter the no:"))
if(gues_no... |
fa973be5a75da561d3c6dc41f27b588829cb7cec | szhua/PythonLearn | /Unit1/Lesson8.py | 1,400 | 3.75 | 4 |
#生成器 generate
#
# classmates =['ff',"szhua","leilei"]
# L=[x+x for x in classmates ]
#
# print(L)
#
# g =(x for x in classmates)
#
# print(g)
#
# for x in L:
# print(x)
#
# #斐波拉契数列
# def fib(max):
# n,a,b =0 ,0 ,1
# while n<max:
# yield b
# #a=>b b=>a+b 一直往前赶着走
# a,b =b,a+b
# ... |
a3dbc065dd873668fa66293bb77f57cfff933440 | Leshens/Pytong | /test.py | 470 | 3.5 | 4 | import random
n = int(input("Podaj liczbę wierszy: "))
m = int(input("Podaj liczbę kolumn: "))
M = [[0] * m for i in range(n)]
s=0
def macierz():
for i in range(n):
for j in range(m):
M[i][j] = random.randint(0, 9)
print(M[i])
return print()
macierz()
def wysmacierz():
for i in r... |
5027989e862be026d2fa31f01896e20a9a3aa913 | hvu53/Algorithms | /stack/balancedsymbols.py | 446 | 3.515625 | 4 | from stack import Stack
def parChecker(parStr):
stack = Stack()
for par in parStr:
if par in '([{':
stack.push(par)
elif par in (')]}'):
if matches(stack.peek(),par):
stack.pop()
if stack.isEmpty():
return True
else:
return False
def matches(open,close):
opens = "([{"
... |
89672babf973952783424bd165f991833a6e5a58 | leejaeyeong/Algorithm | /Programmers/OnlineTest/우아한테크코스/우아한테크코스_3_P5.py | 479 | 3.515625 | 4 | def solution(penter, pexit, pescape, data):
answer=''
print(len(data)//len(penter))
for i in range(len(data)//len(penter)):
divided_data=data[i*len(penter):(i+1)*len(penter)]
if divided_data in [penter, pexit, pescape]:
answer+=pescape+divided_data
else:
answe... |
c0a25d25a73f22b163ae33846dd3c0a2001fcac6 | suttacentral/suttacentral | /server/server/common/hyphenator.py | 2,237 | 3.765625 | 4 | """ High precision hyphenator
Uses a list of segments to attempt to hyphenate words
Then performs corrections to move hyphens in between double consonants
and such
"""
import logging
from pathlib import Path
import regex
from data_loader.util import json_load
FOLDER = Path(__file__).parent
class Hyphenator:
_H... |
3ecbc6e5f98d2f067c910d3b4b4fa0aa255fc5f9 | rhea2801/tuktuktuk | /DSA/Linked List/Find-loop-in-LL.py | 722 | 3.71875 | 4 | """Find Loop - Write a function that takes in the head of a Singly Linked List that contains a loop (in other words, the list's tail node points to some node in the list instead of None / null ). The function should return the node (the actual node--not just its value) from which the loop originates in constant space. ... |
8d2c431b85000473fa11404b8a91415acc84a124 | konayuki002/latextool | /core.py | 1,274 | 3.65625 | 4 | class Statement:
def __init__(self):
self.strformat = ""
self.value = []
def strout(self):
strvalue = []
for v in self.value:
if type(v) == type(''):
strvalue.append(v)
else:
strvalue.append(v.strout())
tempformat = ... |
57e2bb10b390c5138b42bbc4661ac26745f98189 | AllenTango/BasePythonE | /hexagon.py | 381 | 3.578125 | 4 | # 绘制六边形
import turtle as t
import random
# 绘制单个六边形
def drawHexagon():
t.pensize(15)
for i in range(6):
t.pencolor(random.choice(['blue', 'green', 'red', 'magenta', 'gold', 'pink', 'tomato', 'purple']))
t.fd(100)
t.right(60)
def main():
for i in range(6):
drawHexagon()
... |
bff825fe0f4adb9a445c3990c79fe079ad183945 | tommyphan8/verdant-octo-sniffle | /stack.py | 2,738 | 3.75 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def isEmpty(self):
if len(self.items) == 0:
return True
... |
6593dcc0bdc89c788ad0a24b5986a4d45efd3fa1 | ThanushaJ/coding-bootcamp | /LoopingProblems/reverseNumber.py | 244 | 4.0625 | 4 | """Write a program to enter a number and print its reverse.
"""
number2R = int(input())
reverseNum = 0
while(number2R>0):
remainder = number2R % 10
reverseNum = (reverseNum*10) + remainder
number2R = number2R//10
print(reverseNum) |
0c05b914cac3fdba9c3e58662aa23484c592290c | varungodhani/First-Repo | /express_statements.py | 4,201 | 4.1875 | 4 | # 1. Take the input from the user for(Total number of people,Number of seats for bus. Based on two inputs
# Decide how many number of buses required
people = int(input("Number of people: "))
seats = int(input("Number of seats in a bus: "))
if (people % seats) is 0:
buses = int(people/seats)
else:
buses = int(p... |
90b7277992ad5420b6426c722edf8fc7f0f70863 | AdarShaked/diaryProject | /models/event.py | 441 | 3.515625 | 4 | from datetime import datetime
class DiaryEvent:
id: int
title: str
description: str
date: datetime
def __init__(self, id: int = None, title: str = '', description: str = '', date: datetime = None):
self.id = id
self.title = title
self.description = description
# ev... |
e5d63fa62b3bd3a58d810ae6acb345e072be392e | adachepally/test | /problem7.py | 242 | 4.0625 | 4 | num = 0
next = 3
while num < 10000:
isPrime = True
for i in range(2, next):
if next % i == 0:
isPrime = False
if isPrime:
#print (num," : ", next)
num = num + 1
next = next+1
print(next-1) |
8d09b5b87689653d092c81b661de1ef51b1c5d5f | ZippeyKeys12/ambrosia | /python3/euler.py | 2,076 | 3.90625 | 4 | from typing import Callable
def time(func: Callable, *args):
import time
start = time.time()
print(func(*args))
end = time.time()
print("Elapsed Time: {}".format(end-start))
def multiple_sum(num: int) -> int:
total = 0
for x in range(num + 1):
if x % 3 == 0 or x % 5 == 0:
... |
6256a54f4964bf32d98560a6bc894bcd56e7d17a | niteesh2268/coding-prepation | /leetcode/Problems/1315--Sum-of-Nodes-with-Even-Valued-Grandparent-Medium.py | 700 | 3.59375 | 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 getSum(self, root, level):
if not root:
return 0
if level == 0:
return root.val
retur... |
d4d20d7282b7d80b370bfbdf072af32a1ce76d2c | prodax/ras | /lib/PasBuz.py | 3,331 | 3.515625 | 4 | #!/usr/bin/env python
#---------------------------------------------------
#
# This file defines a class to use
# a Passive Buzzer Module
#
# Passive buzzer RPi GPIO Pin
# VCC ----------------- PinPower
# GND ----------------- GND
# SIG ----------------- PinBuz
#
#--------------------------------... |
7f005bc986d63938773f2a475a670e1968ce4456 | srishag/Machine-Learning-For-Trading | /Lesson 4/24_modify_array_elements.py | 550 | 3.984375 | 4 | """Modifying NumPy arrays."""
import numpy as np
def test_run():
a = np.random.rand(5, 4)
print("Array:\n", a)
# Assigning a value to a particular location
a[0, 0] = 1
print("Modified (replaced one element):\n", a)
# Assigning a single value to an entire row
a[0, :] = 2
print("Modifi... |
dd35ca05a772a95f269abaa22b68186d37dfa803 | DaryaRomannova/Python-HomeWork | /HomeWork 2.1.py | 732 | 3.625 | 4 | def rec(a, b, k):
while(a > 0 and b > 0):
if a < b:
k += 1
l = b - a
print("Квадрат с стороной ",a," Прямоугольник иммеет размер " ,a,"x",l)
return rec(a,l,k)
else:
k += 1
l = a - b
print("Квадрат с стороно... |
26b381561212613d84842f603eb23e6407b63119 | paralysedforce/whistlelock | /app/distance.py | 990 | 3.53125 | 4 | import numpy as np
def edit_distance(s1, s2, del_cost, ins_cost, sub_cost = None):
"""Calculates Levenshtein distance between s1 and s2, with substitution
costs given by the L1 norm"""
d = np.zeros((len(s1)+1, len(s2)+1), dtype=int, order='F')
m = len(s1) + 1; n = len(s2) + 1
if not sub_cost:
... |
2cb131f43e480894ceb7f2087dbb1fa763a28360 | sagarPakhrin/PP4E | /Gui/Intro/gui4.py | 295 | 3.765625 | 4 | from tkinter import *
def greeting():
print("Hello stdout wrld")
win = Frame()
win.pack()
Button(win, text="Hello",command=greeting).pack(side=LEFT, anchor=N)
Label(win, text="Hello container world").pack(side=TOP)
Button(win, text="Quit",command=win.quit).pack(side=RIGHT)
win.mainloop()
|
5b0ff71e24e669d5e82d4e7010bf36b969c24881 | rabhatna/CM146 | /Pa3/src/mcts_modified.py | 4,953 | 3.625 | 4 |
from mcts_node import MCTSNode
from random import choice
from math import sqrt, log
num_nodes = 1000
explore_faction = 2.
def traverse_nodes(node, board, state, identity):
""" Traverses the tree until the end criterion are met.
Args:
node: A tree node from which the search is trave... |
4f5c15827f27099288f6c7ec965983f8222c61e9 | germ/cmp145 | /a5/a5q3.py | 2,731 | 3.953125 | 4 | # Assignment 5 Question 3
# Jeremy Bernhardt, jrb569, 11119747, CMPT 145: 2020ST2
import node as N
from a5q1 import to_string
from node import node
def check_chains(chain1, chain2):
"""
Purpose:
Checks 2 node chains.
If they are identical (the same objects),
... |
54bee7ae02f33a535e3a7eaaa367dc4060ea2cda | Julian-Chu/leetcode_python | /lintcode/lintcode683.py | 2,658 | 3.6875 | 4 | class Solution:
"""
@param: : A string
@param: : A set of word
@return: the number of possible sentences.
"""
def wordBreak3(self, s, dict):
if not s:
return 0
ans = 0
lowercase_dic = set()
for key in dict:
lowercase_dic.add(key.lower())
... |
8acb294988c36e24205990de2fd11f6dbee9aa86 | manuel-martin3/PryPython | /Querys_Aprendiendo_Python/Entrada_Estandar_input.py | 2,971 | 4.4375 | 4 | # Entrada Estándar: input()
#================================================
print(); titulo = "Entrada Estándar: input()"; print(titulo)
print("================================================")
#
## La función input() permite a los usuarios introducir
# datos de distintos tipos desde la entrada estándar
# normal... |
81c3658d1c44f8f11a725cba6e303c7211aa5541 | ataabi/listadeexercicios | /estrutura_sequencial/EstruturaSequencial6.py | 699 | 3.859375 | 4 | print('Medidando seu peso ideal usando sua altura como base.')
print('Qual sua Altura ?')
while 1:
try:
altura = input(':')
altp = float(altura)
pesoh = (72.7*altp) - 58
pesom = (62.1*altp) - 44.7
print()
print('Se for Homen, Digite (h)')
print('Se for Mulher,... |
aff6efc30354d783197d6ad5b8fa4237a3210878 | Rich43/rog | /albums/3/challenge98_easy/code.py | 1,338 | 4.15625 | 4 | '''
Write a program that reads two arguments from the command line:
a symbol, +, -, *, or /
a natural number n (≥ 0)
And uses them to output a nice table for the operation
from 0 to n, like this (for "+ 4"):
+ | 0 1 2 3 4
-------------------
0 | 0 1 2 3 4
1 | 1 2 3 4 5
2 | 2 3 4 5 6
3... |
d01a6edc7d79344cdee2b7884551bd9f269d451e | prateek3255/CrackingTheCodingInterview | /StringRotation.py | 81 | 3.578125 | 4 | s1=input()
s2=input()
s=s2*2
if s1 in s:
print("yes")
else:
print("no")
|
1b45ad6cf796203573b743c36735f5725c38b8ff | ChillBroYo/StringsAndArrays | /search_and_replace.py | 1,736 | 3.84375 | 4 | # Find specified character in string and replace with supplied one in place
# Strategy: Create new string with properly filled values after splitting inital string
# O(n) => linear | Mem Usage: O(n) => linear
def search_and_r(s_string, char_to_r, char_to_rw):
f_string = []
for char in s_string:
if char... |
87cf993f65ef36d2b789065640e607481f1df76a | rlpmeredith/datastructures | /tests/test_dictionary.py | 1,096 | 3.671875 | 4 | import unittest
from dictionary import CustomDictionary
class TestCustomDictionary(unittest.TestCase):
def test_set_get(self):
# Arrange
my_dict = CustomDictionary(100)
my_dict.set("Key1", 12345)
my_dict.set("Key2", 67890)
# Act
result1 = my_dict.get("Key1")
... |
21532cd914b045bfa1e2be5f35e72bf48f8dd42e | rithik-dev/Tic-Tac-Toe | /Tic Tac Toe Without Database.py | 7,716 | 3.640625 | 4 | import pygame
from pygame.locals import *
import os
dir = os.path.dirname(__file__)
winWidth = 601
winHeight = 601
BACKGROUND_COLOR = (0, 0, 255)
TEXT_COLOR = (255, 255, 0)
def display_text(text, pos, size=30, color=TEXT_COLOR):
"""displays text on the screen
Args:
text (string): ... |
0b4c1a3b2b378009745630500a66dde0f159b1d8 | amrit2356/Dev-Training-Python-Fundamentals | /01_Python_OOP/01_0_OOP_Basics/05_OOP_methods.py | 1,369 | 4.1875 | 4 | """
Types of Methods in OOP
"""
class Student:
school = "VIT"
"""
There are 3 types of methods:
- Class Methods: These methods are used to work on class variables.
In order to use the class methods you need to declare @classmethod
decorator be... |
b823bb3cbd1a188ff7c203dd626bbc48d17f3891 | DonghaiYu/pyDP | /pyDP.py | 7,295 | 3.734375 | 4 | # -*- coding: utf8 -*-
# @Time : 2016/11/30 13:34
# @Author : Dylan东海
# @Site :
# @File : pyDP.py
# @Software: PyCharm Community Edition
"""
This is an implementation of Douglas-Peucker Algorithm, which can be used for trajectory compression.
When there are enough points in a trajectory, this alg... |
f226dd124525ac9130b8052d41da60ef077bf102 | Fernando-Rodrigo/Exercicios | /Ex008.py | 152 | 3.796875 | 4 | n1 = float(input(' Digite um valor em metros: '))
c = n1*100
mm = n1*1000
print('O valor em centimetros é {} e em milímetros é {}.'.format(c, mm))
|
0cf4cc4eb0a34baeefd17eb1f2c4735e3241c403 | dingleton/python_tutorials | /logging_test2.py | 2,794 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Sample python code to test/experiment with the logging function
"""
import logging
#Useful link - https://docs.python.org/3/howto/logging-cookbook.html
#Step 1 : Create/Instantiate a logger object based on the dunder name attribute
#It returns a reference to a logger instance with the spe... |
9b33b2d6ad56120c51b0191c317f42d6cc7c64c4 | Aasthaengg/IBMdataset | /Python_codes/p02383/s665631451.py | 1,027 | 3.515625 | 4 | class Dice:
def __init__(self):
self.top = 1
self.dside = 2
self.rside = 3
self.lside = 4
self.uside = 5
self.bottom = 6
def north(self):
(self.top, self.dside, self.bottom, self.uside) = (self.dside,
self.bottom, self.uside, self.top)
def... |
4d4188182b4dcbc0b0c5abccc82137b1d8ca2fbf | Ykutyrla/python | /HW1-3.2.py | 908 | 4.0625 | 4 | #Сформировать одномерный список целых чисел A,
# используя генератор случайных чисел (диапазон от 0 до 99).
# Размер списка n ввести с клавиатуры. В соответствии со своим вариантом написать программу по условию, представленному в таблице ниже.
#Все четные по значению элементы исходного списка A поместить в новый спи... |
b3a9ab04c92c7dc7d22a07475ad83752a974dbcb | tweinyan/big-data | /spark/dataframe/data_clear.py | 6,041 | 3.53125 | 4 | '''
1.删除重复数据
groupby().count():可以看到数据的重复情况
'''
df = spark.createDataFrame([
(1, 144.5, 5.9, 33, 'M'),
(2, 167.2, 5.4, 45, 'M'),
(3, 124.1, 5.2, 23, 'F'),
(4, 144.5, 5.9, 33, 'M'),
(5, 133.2, 5.7, 54, 'F'),
(3, 124.1, 5.2, 23, 'F'),
(5, 129.2, 5.3, 42, 'M'),
], ['id', 'weight', 'height', 'age', 'gender'])... |
87a8ffaaaa1c2d69f6449cc3fcc558d22d8f4c93 | hanbinchoi/Python_practice | /ex2_1.py | 353 | 4.34375 | 4 | import math
print('Result>')
radius=int(input('Please Enter the Radius of a Cylinder:'))
height=int(input('Please Enter the Height of a Cylinder:'))
volume=math.pi*radius**2*height
area=(2*math.pi*radius**2)+(2*math.pi*radius*height)
print("\n The Surface Area of a Cylinder = {}".format(area))
print(" The Volume of a ... |
754680ce129ab8fb5edcb942d5a3c4cea750dd75 | stevegoldman/Just-for-Fun | /element_words.py | 1,231 | 3.640625 | 4 | # Because of the Thinkgeek Bacon Elements t-shirt
# Find all arrangements of element symbols that spell a given word
import sys
import os.path
ELEMENT_DIR='./'
ELEMENT_FILE='elements.txt'
def make_element_symbols():
element_data=os.path.join(ELEMENT_DIR,ELEMENT_FILE)
return dict([(symbol.lower(),n... |
d6ad1f3f79097d3697b1682853d97bb3e96f010e | jke-zq/myleetcode.py | /Palindrome Linked List.py | 909 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
#other solution: reverse the first ha... |
23945a99c71cb357750585fd75d113bc4b76d57b | bengineer1981/TJREVERB_SDR | /TJREVERB_SDR_PYTHON_COMMS/old_python_tcp_stuff/old_tcp_TJ_cubesat_echo_server.py | 2,590 | 3.65625 | 4 | #!/usr/bin/python2.7
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#take user inputs for ports between 5500 and 5599
startup = 0
while startup == 0:
if len(sys.argv) == 2:
port_num = int(sys.argv[1])
if (port_num>=5500 and port_num<=5599)... |
5bdd9656616a204a723dc32ba017bff7ffd43ab3 | Gerile3/My_Python | /Math/MultiplicationTable.py | 963 | 4.46875 | 4 | #!/usr/bin/env python3
import pandas as pd
import numpy as np
def multiples(number, limit=11):
"""Prints out multiplications for the given number"""
for i in range(1, limit):
print('{0} x {1} = {2}'.format(number, i, number * i))
def multiples_table(limit=11):
"""Prints out multiplication table ... |
e1d0992463ef6b4bf2cbdb86bb13ca5531d61f36 | RanjitThakur678/Python_DB | /Postgresql.py | 1,514 | 3.5625 | 4 | import psycopg2
#
def create_table():
conn = psycopg2.connect("dbname='student'user='postgres' password='Rony1995$' host ='localhost' port='5432'")
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS shop(Item TEXT,Quantity INTEGER,Price REAL)')
conn.commit()
conn.close()
create_table()
... |
d2741f9ee6f214ef32bd8eb0c476f44c80521fb5 | prathmesh-jagtap/Python_Programming_Youtube | /prime_number.py | 303 | 4.1875 | 4 | num=int(input("Enter the number : "))
# check prime number
if(num>1):
for i in range(2,num):
if(num%i==0):
print("this number is not prime")
break
else:
print("this number is prime number")
else:
print("this number is not prime number ") |
7e05540f9f8287e2c43e9f9dfb3242f3e9d5a1d1 | Hippoleveque/machine-learning-vanilla-implementation | /knn.py | 3,063 | 4.09375 | 4 | import numpy as np
from scipy.stats import mode
class KNearestNeighbor:
""" a kNN classifier with L2 distance """
def __init__(self):
pass
def fit(self, X, y):
"""
Train the classifier. For k-nearest neighbors this is just
memorizing the training data.
Inputs:
... |
2fdc22e7c5d685e94eefb422f38004f0cbde1624 | WayneChen1994/Python1805 | /day15/5.记录错误.py | 662 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Wayne
import logging
'''
当程序没有进行异常捕捉的时候,Python解释器会自己将错误的堆栈信息打印出来。
但是,工作中我们需要查看错误的信息还需要使程序继续运行,也就是说,我们既需要捕捉错误,也需要打印错误信息以便对错误进行处理。
这时候,我们可以使用logging模块来打印错误信息。
logging.exception(e)
'''
def func(a, b):
try:
return a / b
except Exception as e:
... |
f9edbc8863ee3536a99b09242bc1505ea5c77649 | JayantDwivedi/Basic-Python-programmes | /number gassing game.py | 233 | 3.9375 | 4 | print("****Number gussing game*****")
x=input("What are you gussed choose a number between the range of 1 to 10\n")
x=int(x)
y=int("3")
if x==y:
print("CONGRATS YOU WON THE GAME")
else:
print("BETTER LUCK NEXT TIME")
|
a32eaad1be8ad2180c9d1726452d72781de0f985 | GaoPeiRu/python-vs-code | /6-6.py | 210 | 3.796875 | 4 | a=int(input())
i=0
sum=0
while a!=0:
i+=1
sum+=a
a=int(input())
print(sum)
#a = int(input())
#sum_of_sequence = 0
#while a != 0:
#sum_of_sequence += a
#a = int(input())
#print(sum_of_sequence) |
b864be330894bf750ae7a2a13e226c6563efd3ec | Frecy16/learning | /py_study/objectDesign/6、魔法方法介绍.py | 2,181 | 4.0625 | 4 | class Person(object):
def __init__(self, name, age): # self 谁调用就指向谁,不调用不指向
self.name = name
self.age = age
def eat(self):
print(self.name + '正在吃东西')
def __eq__(self, other):
return self.name == other.name and self.age == other.age
# def __ne__(self, other): # 使用 != 运... |
559fe7cd82db70bd9d916dc4ec6c89fcd541d85d | Joshua7u7/AnimacionJS | /p2.py | 837 | 3.8125 | 4 | def lcs(A,B):
'''return the longest common substring (lcs) between two strings, A and B.
'''
L=[['']*len(B) for a in range(len(A))]
for a in range(0, len(A)):
for b in range(0, len(B)):
left = ''
if a > 0:
left = L[a-1][b]
up = ''
... |
5e74cdb0adb487822d737311dd54621f57a1b2f7 | YifengGuo/DeepLearningStudy | /NN_vector_programming/FullConnectedLayer.py | 1,986 | 3.84375 | 4 | # re-form the layer implementation in backpropagation
# this new class implements forward and backward calculation in full connected layers
import numpy as np
class FullConnectedLayer(object):
def __init__(self, input_size, output_size, activator):
'''
constructor of class
:param input_siz... |
5d482366a342dd72a633f95b314c66001da0f354 | mangabhi/Python | /factorial_module.py | 314 | 4.21875 | 4 | #Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
import math
n=int(input("Enter a number: "))
p=math.palindrome(n)
print(p)
|
43372081e983980f92ce03f863e337e6cc18254e | aguinaldolorandi/Python_exercicios_oficial | /Lista de Exercícios nº 03 Python Oficial/Ex.42-lista03.py | 936 | 3.921875 | 4 | # EXERCÍCIO Nº 42 - LISTA 03 - ESTRUTURA DE REPETIÇÃO
print('\nIntervalos de números')
print('#####################\n')
intervalo_a=0
intervalo_b=0
intervalo_c=0
intervalo_d=0
número=0
while número<=0:
número =float(input('Insira um número inteiro: '))
if número==-1:
print('No intervalo [00... |
6b1e7048048df2f3cf95ae3228aead2c5b14277d | nithyaganeshan/set | /ll.py | 149 | 3.671875 | 4 | bv=int(input())
if(bv%400==0):
print ("leap")
elif(bv%4==0):
print ("leap")
elif(bv%100!=0):
print ("leap")
else:
print ("not leap")
|
dd2cf6bc8b74dcd302a2e824c7edb36b40a19f60 | tinyplasticgreyknight/mini-utils | /url-expand.py | 829 | 3.640625 | 4 | #!/usr/bin/env python3
"""
Invocations:
url-expand.py http://tinyurl.com/2g9mqh
echo http://tinyurl.com/2g9mqh | url-expand.py
Output:
If the URL supplied has an HTTP redirect, displays the target URL.
Otherwise, displays "None".
"""
import sys
from http.client import HTTPConnection, HTTPSConnection
... |
9ac54e5c77c2e61a72de827f8d1399c56ef52462 | masehk/Utech-Summer-2020 | /Ex7.py | 240 | 4 | 4 | def Fib(n):
if n <= 0:
print("Run Again")
elif n == 1:
return 1
elif n == 2:
return 1
else:
return Fib(n-1)+Fib(n-2)
n = int(input('Please Enter n: '))
print(Fib(n))
|
d28146908faa2a409840aa6327242951b330b472 | Viccari073/extra_excercises | /Tuplas extras 01.py | 700 | 4.1875 | 4 | """
Crie um programa que tenha uma tupla totalemnte preenchida com uma contagem por extenso, de zero até vinte.
Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
"""
cont = ('zero', 'um', 'doi', 'três', 'quantro', 'cinco',
'seis', 'sete', 'oito', 'nove', 'dez', 'onz... |
ff34a8e2f65b5a35d546a08f2f017ccd119ef88c | kevinszuchet/itc-fellows-part-time | /lesson_3/copyspecial/copyspecial.py | 4,336 | 3.828125 | 4 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import subprocess
"""Copy Special exercise
The p... |
5655ceae70152c95ed8141079979c95dcfc07191 | zaobasy/advent_of_code | /2020/day_9.py | 2,192 | 3.734375 | 4 | from day_1 import get_multi_target_sum
def read_inputs(path):
with open(path, 'r') as in_file:
lines = in_file.readlines()
return [int(l.strip()) for l in lines]
def XMAS_error_finder(in_list, xmas_size):
"""
Find the first number not following the xmas scheme
"""
list_len = len(i... |
40f5649948c39165e61d9d13a5e88f568ea72e01 | rich1jake2/ComputationalPhysics | /Ch9Newman/Richter_Newman91.py | 2,623 | 3.859375 | 4 | '''
Write a program or modify from 9.1 to solve Poisson's Equation for the system described in example 9.2.
work in units where e0 = 1 and continue the iteration until your solution for the electric potential changes
by less than 10^-6V per step at every grid point
'''
import numpy as np
import matplotlib.pyplo... |
419fcde889af5b9bb09ee80872cc45ee9bb67c0d | microease/Python-Cookbook-Note | /Chapter_3/3.2.py | 356 | 4.03125 | 4 | # 你需要对浮点数执行精确的计算操作,并且不希望有任何小误差的出现。
a = 4.2
b = 2.1
print(a + b)
from decimal import Decimal
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b)
from decimal import localcontext
a = Decimal('1.3')
b = Decimal('1.7')
print(a / b)
with localcontext() as ctx:
ctx.prec = 3
print(a / b)
|
8bad991557e8bcc46d6099b705246efe6b396c42 | MISAKIGA/hm_car | /my_pyqt/test.py | 431 | 3.71875 | 4 |
class MyClass:
def __init__(self):
# 构造函数
# 初始化属性
self.a = 10
self.name = 'itcast'
self.is_ok = True
def say_hello(self):
print('hello itcast')
# 类的实例化,创建对象
# my_class = MyClass()
# my_class.say_hello()
class Car:
def __init__(self):
self.speed =... |
cf90c2b23f1004b7cb4549b1ed0cb1e536201195 | nazhot/Project-Euler-Solved | /Project Euler, Solved, Problem 35, Circular Primes.py | 1,159 | 3.75 | 4 | from math import sqrt
def nth_prime_number(n):
total=0
f, c, primes = 1, 11, [2, 3, 5, 7]
if n < 5:
return primes[n]
while n>=primes[-1]:
root = sqrt(c)
for prime in primes:
if not c % prime: # If c is Composite
break
elif... |
30eec56ef66725e9fd521dd36d3b26ee8a2a1a22 | myungwooko/algorithm | /easy/1011_121_best_time_to_buy_and_sell_stock.py | 2,115 | 4.03125 | 4 | """
121. Best Time to Buy and Sell Stock
Easy
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot se... |
8dad9f73fe06f38076c5e0f82addddd6dd1a4783 | laohou/Leetcode | /25_Reverse Nodes in k-Group.py | 2,016 | 4.125 | 4 | __author__ = 'yghou'
"""
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may n... |
b509662a668f682d217232995e67f1412c996671 | Jigar710/Python_Programs | /function_progs/f1.py | 283 | 3.625 | 4 | for i in range(1,41):
print("*",end='')
print("\nhi")
for i in range(1,41):
print("*",end='')
print("\nhello")
for i in range(1,41):
print("*",end='')
print("\nbye")
for i in range(1,41):
print("*",end='')
print("\nwelcome")
for i in range(1,41):
print("*",end='')
|
d1e28116535df02577889164b046c97221e43209 | Rider66code/PythonForEverybody | /bin/p3p_c2w5_ex_003.py | 860 | 4.375 | 4 | #2. Below, we have provided a list of strings called nums. Write a function called last_char that takes a string as input, and returns only its last character. Use this function to sort the list nums by the last digit of each number, from highest to lowest, and save this as a new list called nums_sorted.2. Below, we ha... |
9b12675ddc80240cc5fbd292d297fdeb6f9b68f2 | pedrohenriquebraga/Curso-Python | /Mundo 1/Exercícios/ex_015.py | 275 | 3.953125 | 4 | # Calcula o valor de um aluguel de um carro
km = float(input("Quantos Km foram percorridos? "))
dias = int(input("Quantos dias o carro ficou alugado? "))
valor = (60 * dias) + (0.15 * km)
print(f"O valor do aluguel é R${valor} por ter percorrido \n{km}Km e {dias} dias.")
|
2b6c9402c3ee90c22f33d28911a5af3a95169daa | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/df5e6508420542f19c02517f7952a6be.py | 281 | 3.796875 | 4 | from collections import Counter
import string
def remove_punctuation(str_):
return str_.translate(string.maketrans('', ''), string.punctuation)
def word_count(str_input):
return Counter(word.lower() for word in
remove_punctuation(str_input).split())
|
501174af183aa9397f57042da2bb1677dc2a15d5 | AtulCoder01/Python-Notes | /Python With Encryption/transposition_decryption.py | 612 | 3.8125 | 4 | import math
def main():
mymessage = input('Enter Encrypt text to Decrypt:')
mykey = 8
plaintext = decryptMessage(mykey, mymessage)
print (plaintext)
def decryptMessage(key, message):
numOfColumns = math.ceil(len(message)/key)
numOfRows = key
shadedBox = (numOfColumns * numOfRows)-len(message)
plaintext = ['']*... |
c0413aa9b82b3db5cfaa1cd7e1731c06971a5545 | victorcocuz/DSAN-Unscramble_Computer_Science_Problems | /Task2.py | 1,190 | 4 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the ... |
50472b9be8fb6ab88bbb34fbfcba145f1725ac95 | weizsw/IT1040 | /TripPlanner/destinations.py | 1,250 | 4.28125 | 4 | # Destinations Module
# -------------------
# This module provides information about European destinations and rates
# All rates are in euros
def print_options():
# Print travel options
print("Travel Options")
print("--------------")
print("1. Rome")
print("2. Berlin")
print("3. Vienna")
p... |
133f886ff78f6a3d95ab0517d95675283f5f9f67 | RAHULJ07/Assignments | /A1T23.py | 115 | 4.21875 | 4 | word=input('Enter the word to be reversed: ')
for char in range(len(word)-1,-1,-1):
print(word[char], end ="")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.