blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
aae667bfa260a201991210ec5bf6905f7f604985 | mpigelati/Mohansai_samples | /Decorators - Getters, Setters, and Deleters/Decorators_1.py | 302 | 3.921875 | 4 | class Employee:
def __init__(self,first,last):
self.first=first
self.last=last
self.email=first+"."+last+"@mail.com"
emp1=Employee("mohansai","pigelati")
print(emp1.__dict__)
emp1.first="manju"
print(emp1.__dict__) # here the draw back is the mail addredss is not updating |
16fa60fc84edc3db363e697ca35f1780fc24dc43 | Abhinandan578/PythonScripts | /GUI/second.py | 454 | 3.53125 | 4 | from tkinter import *
root=Tk()
topFrame=Frame(root)
topFrame.pack()
bottomFrame=Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame,text="Button 1",fg="red")
button2 = Button(topFrame,text="Button 2",fg="blue")
button3 = Button(topFrame,text="Button 3",fg="green")
button4 = Button(bottomFrame,text="Bu... |
076ccf91534d2b4cb54f1faea158fa901572106f | nikneural/MLRecipe6 | /Лексемизация текста.py | 995 | 4.03125 | 4 | # Дан текст, и требуется разбить его на отдельные слова.
# Комплект естественно-языковых инструментов NLTK (Natural Language Toolkit for
# Python) имеет мощный набор операций над текстом, включая лексемизацию на
# слова:
from nltk.tokenize import word_tokenize
string = "Сегодняшняя наука - это технология завтрашнего ... |
8c02c04b6a24f0bc072e784117a3d8d29737374f | robotpy/pyfrc | /pyfrc/physics/visionsim.py | 7,892 | 3.875 | 4 | """
The 'vision simulator' provides objects that assist in modeling inputs
from a camera processing system.
"""
import collections
import math
inf = float("inf")
twopi = math.pi * 2.0
def _in_angle_interval(x, a, b):
return (x - a) % twopi <= (b - a) % twopi
class VisionSimTarget:
"""
Target o... |
d5898d488f841891832d00e71572bb68ec2ec0a8 | MaraniMatias/machine-learning | /deep-learning-computer-vision/cnn_smiler/cnn.py | 3,960 | 3.515625 | 4 | # import the necessary packages
from keras import backend as K
from keras.layers.convolutional import MaxPooling2D, Conv2D
from keras.layers.core import Dense, Activation, Flatten, Dropout
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential
# INPUT => CONV => RELU => FC
class... |
155037eb90d9385f76fd3c9dd975eca7e6ca9bb1 | open-audio-controller-org/open-audio-controller | /tests/test_example_name.py | 1,483 | 3.84375 | 4 | import unittest
"""
Mandatory import for unit testing capability
The code you want to test should also be imported here.
"""
class TestGroupName(unittest.TestCase):
"""
Use a class which extends unittest.TestCase to
group your tests together.
"""
def setUp(self):
"""
setUp() is us... |
56522d30af5e10e624bb9429660381c9125db94f | andersonprovox/IntroProgPython | /exemplo/Cap5/exp5.12.py | 174 | 3.84375 | 4 | # Cálculo de média usando acumulador
x = 1
soma = 0
while x<= 5:
n = int(input("%d Digite o número:" % x))
soma += n
x += 1
print("Média: %5.2f" % (soma/5))
|
617c19a6d95c60eb22a710148c6113734a859970 | HanKin2015/ACM | /Spyder/knowagde/完美的图例显示.py | 2,790 | 4 | 4 | #作者:SunnyMarkLiu
#链接:https://www.zhihu.com/question/37146648/answer/80425957
#来源:知乎
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#!/usr/bin/python2.7
# _*_ coding: utf-8 _*_
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 准备数据
def file2matrix(filename):
fr = open(filename)
arr... |
62b9c8b2359804b0822e73fb502ef92fddc5f2f2 | lovetoburnswhen/blurwal-osx | /blurwal/frame.py | 2,762 | 3.5 | 4 | """
Transition frame generation via ImageMagick's convert utility.
Author: Benedikt Vollmerhaus
License: MIT
"""
import filecmp
import subprocess
from pathlib import Path
from blurwal import paths, utils, wallpaper
def generate(output_dir: Path, blur_level: int,
max_blur_level: int, max_sigma: int) ->... |
28b3b1858fdb92b887fdef2901fad64ad345b197 | nmotwani0/python | /decorators.py | 231 | 3.84375 | 4 | def sub(a,b):
return a-b
def subtract(func):
def inner(a,b):
if(a<b):
a,b=b,a
return func(a,b)
return inner
sub = subtract(sub)
res = sub(2,4)
print(res)
print(subtract(sub)(2,4))
|
965cb10c75acbf120e09a87ce8fe56594187e3d8 | efrainclg95/Sion | /Ejercicios_Web/Listas y Tuplas/ejercicio6.py | 820 | 4.1875 | 4 | # Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista,
# pregunte al usuario la nota que ha sacado en cada asignatura y elimine de la lista las asignaturas aprobadas.
# Al final el programa debe mostrar por pantalla las asignaturas que... |
5137fa94be7510e997266764269d68dddd227629 | oppenheimera/euler | /14_collatz.py | 328 | 3.765625 | 4 | def collatz(n):
i = 1
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
i += 1
return i
def collatzeral(lim):
dic = {}
for x in range(1, lim + 1):
dic[collatz(x)] = x
return dic
"""
>>> ans = collatzeral(10**6)
>>> ans[max(ans)]
83... |
ffa9280d350befb3dcdad4911f939ed04cdfbd76 | JeffreyAsuncion/CodingProblems_Python | /CodeBasics/graphs001.py | 2,807 | 4.09375 | 4 | class Graph:
def __init__(self, edges):
self.edges = edges
self.graph_dict = {}
for start, end in self.edges:
if start in self.graph_dict:
# one value already exists. append to list
self.graph_dict[start].append(end)
else:
... |
c29263990e028bbe830ccfb44fe35b2168184afc | abhishekjoshi1991/Python_Learning | /Debugging/addition_func.py | 192 | 3.875 | 4 | def add(a,b):
mysum=a+b
return mysum
if __name__=='__main__':
x=input('enter value of a:')
y=input('enter value of b:')
z=add(x,y)
print('addition of x and y is:',z)
|
543ff6350393ab1381461ce496c64799fdfe0e1b | oleoalonso/atvPython | /exerPython01.py | 341 | 4.6875 | 5 | # Leonardo L. Alonso Carriço
# leonardo@carrico.com.br
# Exercício Prático Python 01
###################################################################
# 1) Faça um Programa que converta metros para centímetros.
metros = int(input("\nEntre com um número em metros : "))
centimetros = metros * 100;
print(f"\n{metros... |
88b9319940c7e038b0d9477409814b101af32bbd | majdjamal/DD2424_labs | /LAB4/model.py | 14,649 | 3.515625 | 4 |
__author__ = 'Majd Jamal'
import numpy as np
from utils.utils import tanh, softmax
class VRNN:
""" Vanilla Recurrent Neural Network
used for natural language processing.
"""
def __init__(self):
self.W = None
self.V = None
self.U = None
self.b = None
self.c... |
91fe9c9b9a53847c435102aa4b77716852618eeb | luyuan2002/PythonLearn | /100/3循环结构.py | 4,919 | 4.25 | 4 | from math import sqrt
"""
循环结构
在我们写程序的时候,一定会遇到徐娅哦重复执行某条或者某些指令的场景。例如程序控制机器人踢足球
如果机器人只求而且还没有进入射门范围,那么我们就需要一直发出让 机器人向球门方向移动的指令。
在这个场景中,让机器人向球门方向移动就是一个需要重复的动作,
循环结构就是程序中控制某条或者某些只指令重复执行的机构
在Python中构造循环结构有两种做法,一种是for-in循环,一种是while循环。
"""
import random
"""
for-in循环
如果明确知道执行的次数或者要对一个容器进行迭代,那么推荐for-in的方式进行循环
"""
num = 0
for ... |
4f1b29ef2cfbe1535362635ce8b9ca0b623e2637 | vy538/algo-hw-code | /hw2_1.py | 1,312 | 3.8125 | 4 | import math as m
def BuildMaxHeap(array):
for i in range(m.floor(len(array)/2),0,-1):
MaxHeapify(array,i)
return array
def MaxHeapify(array,pos):
left = (pos+1)*2-1
right = left+1
big = pos
if left <len(array) and array[left]>array[pos]:
big = left
if right <len(array) and a... |
025234be32461255391d9c2237391b40420c24b0 | kushagra2194/python-exp | /validate_pass.py | 624 | 3.546875 | 4 | import re
def pass_validate(password):
flag = 0
while True:
if (len(password)<6):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif ... |
7b07077c8029317363a26cbf5c12f4fad7b50eb5 | chenhh/oj_snippet | /sort/quick_sort.py | 867 | 3.875 | 4 | # -*- coding: utf-8 -*-
from typing import List
def quick_sort(arr: List[int], left: int, right: int):
if left >= right:
return
idx = left
jdx = right
pivot = arr[left]
while idx != jdx:
while arr[jdx] > pivot and idx < jdx:
# 從右邊開始找,找比基準點小的值
jdx -= 1
... |
5b1dbf6060cac3614bda1f2300ff834bc3ed4f2c | kashifpk/smpp5 | /testing/echo_client.py | 693 | 3.71875 | 4 | #shares the same socket between multiple threads
import socket
import threading
def say_hello(thread_name, sock):
sock.sendall("hello from " + thread_name)
HOST = '127.0.0.1' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK... |
48fb952871dd0a9d62f217a7a00c97586faeeceb | ishantk/GW2019PA1 | /venv/Session5F.py | 304 | 3.890625 | 4 | S1 = {1, 2, 3, 'a', 'b'}
S2 = {1, 'a', 'b'}
print(1 in S1)
print(S2.issubset(S1))
print(S1.issuperset(S2))
print("S1 before is:",S1)
print(S1.union(S2))
print("S1 now is:",S1)
print(S1.intersection(S2))
print(S1.difference(S2))
# print(S1.symmetric_difference(S2))
# Explore -> symmetric difference |
155c2f17de00c22f7368cc99db1c0363dbfc2930 | HBinhCT/Q-project | /hackerearth/Algorithms/Pablo & The DEA/solution.py | 835 | 3.640625 | 4 | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
def check_code(num1, num... |
fb48e7efb6f58fbb1fd78b47afbddb5ce5442d78 | cohenguy1/89511 | /89511_ex6/mlp.py | 7,816 | 4.03125 | 4 | import numpy as np
import math
def sigmoid(x):
return 1.0 / (1.0 + math.exp(-x))
def init_mlp(inputs, targets, nhidden):
""" Initialize network """
# Set up network size
nin = np.shape(inputs)[1]
nout = np.shape(targets)[1]
ndata = np.shape(inputs)[0]
nhidden = nhidden
#Initialize ... |
f38e2400bc6fa0d23b913e2b72ddf62b023e5188 | creamboy/LeetCode | /Remove Nth Node From End of List/Remove Nth Node From End of List.py | 673 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
m=1
fast=head
while m<n:
m=m+1
fast=fast.next
s... |
6d0ddee72a92120d606248ce751741c1b9e91b03 | smisra77/Leetcode-Examples | /Longest Palindrome Substring.py | 1,009 | 3.734375 | 4 | s = 'babad'
#class Solution:
def longestPalindrome(s):
if len(s) == 0:
return ""
ma = 0
mu = ""
for i in range(len(s)):
for j in range(len(s) - 1, -1, -1):
if s[i] == s[j]:
print('s[i]::', s[i])
... |
70c3a75561064c2f7f8a5d0cee172b78c126e000 | libert-xyz/interactivePython | /revstring.py | 532 | 3.890625 | 4 | #Write a function revstring(mystr) that uses a stack to reverse the characters in a string.
from stackLesson import Stack
import time
def revstring(mystr):
start = time.time()
myStack = Stack()
for ch in mystr:
myStack.push(ch)
rev = ''
while not myStack.isEmpty():
rev = rev + myStack.pop()
end = time.... |
9bde859a68d5adcd23c288ce90fb4a50a14be1f0 | Chandrahas-Soman/Data_Structures_and_Algorithms | /Python/Strings/base_conversion.py | 426 | 3.875 | 4 | # base_conversion
#similar to string to integer conversion.
def get_decimal_digits(digit):
digits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
for x in range(len(digits)):
if digit == digits[x]:
return x
def hex_to_dec(hexNum):
decNum = 0
for digit in range(len(hexNum)):
decNum *=... |
2ba83bf537a3bc52d64b37df4a473208fe74d6ef | WildDogOdyssey/bitesofpy | /146/rhombus.py | 529 | 3.859375 | 4 | STAR = '*'
def gen_rhombus(width):
"""Create a generator that yields the rows of a rhombus row
by row. So if width = 5 it should generate the following
rows one by one:
gen = gen_rhombus(5)
for row in gen:
print(row)
output:
*
***
... |
f308ebab881b043b38953f111ec5d01d68b84fe2 | iDneprov/university | /NM/3/task4.py | 863 | 3.609375 | 4 | statement = {"x*": 1.0, "x": [0.0, 0.5, 1.0, 1.5, 2.0], "y": [0.0, 0.97943, 1.8415, 2.4975, 2.9093]}
def GetDerivativesValues(x, y, dot):
i = 0
while x[i + 1] < dot:
i += 1
while i + 1 > len(x) + 1:
i -= 1
firstDerivative = (y[i+1] - y[i])/(x[i+1] - x[i]) + ((y[i+2] - y[i+1])/(x[i+2] ... |
18e7124f4fec4a37e51a7198cc1116c1362cff36 | python-discord/code-jam-5 | /xyloid_xylophones/game/input.py | 4,530 | 3.796875 | 4 | '''Handles all user input from keyboard and mouse'''
import pyglet
from config import game_width, game_height
from . import keys, player, zone_map, current_display
def mouse_input(x, y):
if (current_display == 'zone'):
move_towards_coord(x, y, True)
else:
# TODO
pass
return
def m... |
a116db6c2919fd8c56b5474caa2f93342d4aab73 | cocoon333/lintcode | /1143_solution.py | 2,071 | 3.96875 | 4 | """
1143. Minimum Index Sum of Two Lists
中文
English
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, out... |
1209d1e10d21df1e1dad35a1901df253426cdbdc | Pankajkalbande/PYTHON | /Section 8 - Function Parameter/3 Exercise - Paint Area Calculator.py | 340 | 4 | 4 | import math
def paint_calc(height, width, cover):
Number_of_Cans = (height * width) / cover
cans = math.ceil(Number_of_Cans)
print(f"You need to buy {cans} cans of paint")
test_h = int(input("Height of wall: "))
test_w= int(input("Width of wall: "))
coverage = 5
paint_calc(height = test_h, width = test_w... |
d644c6eb50f3bf3dc01d89582ad32683faa9f1d9 | SFHS/Problem-Sets | /P-Set_1/turtle-TedGiardello.py | 2,515 | 3.953125 | 4 | import turtle
import math as m
turtle.Screen()
t = turtle.Turtle()
bird = t
def _draw_s_(r1, r2): #r1 > r2, r1 = 3, r2 = 2
a = (r1 * 20 * m.pi)/180
b = (r2 * 20 * m.pi)/180
k = 100/5.5
t.right(180)
t.right(20)
for i in range(180):
t.left(1)
t.forward(a)
for i in range(180):
t.right(1)
t.forward(b)
t.r... |
39e95e65f9f2ffd01f821efe46f77aafc0bf2c44 | daveomri/Similarity-join | /src/cosine_similarity.py | 604 | 3.5 | 4 | import math
# Sum[n,i=1](Ai * Bi)
#similarity(A,B) = -------------------------------------------------------
# Sqrt(Sum[n,i=1](Ai * Ai)) * Sqrt(Sum[n,i=1](Bi * Bi))
def cosine_similarity(A, B):
denominator_A, denominator_B, numerator = 0, 0, 0
#numer... |
f897f06374f1e7003f9eea2721ebfbc656d1fadb | gxmls/Python_NOI | /NOI1-7-20.py | 589 | 4.03125 | 4 | '''
描述
给定一个单词,如果该单词以er、ly或者ing后缀结尾, 则删除该后缀(题目保证删除后缀后的单词长度不为0), 否则不进行任何操作。
输入
输入一行,包含一个单词(单词中间没有空格,每个单词最大长度为32)。
输出
输出按照题目要求处理后的单词。
样例输入
referer
样例输出
refer
'''
word=input()
if len(word)>=3 and (word[-2:]=='er' or word[-2:]=='ly'):
print(word[:-2])
elif len(word)>=4 and word[-3:]=='ing':
print... |
5ac627c8588f1a1263c82d622e5f18369d7a96a3 | kibol/USF-Repo | /Python/ch06 (2).py | 2,585 | 4.125 | 4 | #5
def is_prime(x):
n = x-1
while n > 1:
if x%n == 0:
return False
else:
n-=1
return True
result = is_prime (17)
print result
#####6.
##
##def num_digits(n):
## count=0
## while n:
## count = count + 1
## ... |
29d93b42fb5bc4e6c24fae147870df05b7fd63f5 | chayabenyehuda/LearnPython | /She Codes/Le8Recursion.py | 1,538 | 4.28125 | 4 | def sum(x):
"""Computes the sum of all integers between 1 and n, inclusive.
Assume n is positive.
# sum(1)
1
#sum(5) # 1 + 2 + 3 + 4 + 5
15
"""
"*** YOUR CODE HERE ***"
if x == 0:
return 0
else:
return sum(x-1) + x
print(sum(6))
def sum_every_other_number(n):
... |
4bd068f381af3c93c4ff2dee033e10832214d76e | mchingate/Prueba_Mercadolibre_MonicaChingate | /Database.py | 3,549 | 3.71875 | 4 | from smtplib import SMTP
import pandas as pd
import sqlite3 as sql
import smtplib, ssl
import json
def read_csv(): # function to read csv file
f_csv = pd.read_csv('Csv_example.csv') # use pandas for read csv
f_csv = pd.DataFrame(f_csv) # use pandas to convert csv in dataframe
#print(f_csv)
return f_cs... |
3fb803120fe0f5eb43d67176ef3da7dfa6e5e851 | ZeweiChu/julyedu-python-datascience | /OOP/code/classes.py | 2,639 | 4.03125 | 4 |
'''
Student class
'''
class Student(object):
# method
def __init__(self, name, level=0):
# field
# self refers to the object that is being created
self.name = name
self.level = level
def print_info(self):
print("Name: {}, level: {}".format(self.name, self.level))
def take_exam(self, grade):
if grad... |
0231523cfcfe0892fe62b5a4cdb51997f59f657d | viniciusantigo/URIOnlineJudge | /Python 3/Iniciante/1004 - Produto Simples.py | 613 | 3.78125 | 4 | '''Leia dois valores inteiros. A seguir, calcule o produto entre estes dois valores e atribua esta operação à
variável PROD. A seguir mostre a variável PROD com mensagem correspondente.
Entrada
O arquivo de entrada contém 2 valores inteiros.
Saída
Imprima a mensagem "PROD" e a variável PROD conforme exempl... |
22715500e734881d047e7a9e41afb6bff29ec497 | IsaacMagno/python3_curso_em_video | /PythonExercicios/ex077.py | 1,033 | 3.5 | 4 | palavras = ('aprender', 'programar', 'linguagem', 'python', 'curso', 'gratis', 'estudar', 'praticar', 'trabalhar',
'mercado', 'programador', 'futuro', 'exercicios', 'importante')
count2 = A = E = I = O = U = 0
for c in palavras:
if palavras[count2].count('a') > 0:
A = palavras[count2].count... |
a1afacd5faf78369892bb5cafe18c3be68dd1c85 | kaladhar-mummadi/misc-contests | /Facebook Hackercup/45:Fighting the Zombie.py | 2,300 | 3.546875 | 4 | import math
def fact(n):
result = 1
for i in range(1,n+1):
result *= i
return result
def combination(n,r):
return fact(n)/(fact(n-r) * fact(r))
def comb(n,r):
digit = n
numerator = 1
for _ in range(r):
numerator *= digit
digit -= 1
denominator = fact(r)
ret... |
4e20f2cd3e9642861112179068202c2a1ba67815 | FabianoJanisch/CursoEmVideo-Python | /Exercício 098.py | 773 | 3.671875 | 4 | import time
def contador(início, fim, passo):
if passo < 0:
passo = passo*-1
if passo == 0:
passo = 1
if início < fim:
print (35*'-')
print (f'Contagem de {início} até {fim} com {passo} passos')
for n in range(início, fim+1, passo):
print (n, end = ' ', fl... |
06fd6a8f13c6e213528e88dda56b7ac357304027 | pragya1703/Programming | /Bactracking/StringPermutation.py | 1,196 | 4.09375 | 4 | """
Using Backtracking to solve string Permutation
"abc"
/ | \
/ | \
"{a}bc" "{b}ac" "{c}ba"
/\ /\ / \
/ \ / \ / \
... |
54f3d72b85c5c4d607cb37d37111d08d092f330f | Pradeepsuthar/pythonCode | /PythonProgramsTraining/programsFiles/js/json47.py | 984 | 3.9375 | 4 | import json
EMP_FILE = "empinfo.json"
def read_emp_info():
'to read all employee info from json file'
# opening json file in reading mode
fr = open(EMP_FILE)
# reading all data from json file into python compatible
info = json.load(fr)
fr.close()
for item in info:
print("... |
caf88e3468e37e6fc9b961f0d2add86275004d4b | Siyi1961/selenium | /007-数据驱动/dataCSV.py | 911 | 3.796875 | 4 | #coding=utf-8
import csv
print("=========读取CSV=============")
csvFile=open("csvData.csv","r",encoding='utf-8')
reader=csv.reader(csvFile)
data=[]
for item in reader:
print(item)
data.append(item)
print(data)
csvFile.close()
print("=========读取CSV2=============")
with open("csvData.csv","r",en... |
5b55147e06d33d90b7263b0401fd816ae876e4cd | 5ran6/Algorithm-challenges | /random_algorithms/number_to_ordinal.py | 1,601 | 3.859375 | 4 | def number_to_ordinal(number):
number_form = str(number)
number_form_list = list(number_form)
max_index = len(number_form_list) - 1
last_number = number_form_list[max_index]
p_last_number = number_form_list[max_index - 1]
# suffixes
suffix_1 = "st"
suffix_2 = "nd"
suffix_3 = "r... |
1e83f6c29fb7a66147c3c6e9b23600d071c9c8c2 | 13U1U/AprendendoLinguagems | /01-ExpRegularPython.py | 518 | 3.953125 | 4 | import re
endereco = "rua antoni luiz moura gonzaga, porto da lagoa, 23440-120 apocalipise now"
cpe = re.compile("[0-9]{5}[-]?[0-9]{3}")
# retorna objeto Metch
busca = cpe.search(endereco) # caso não encontre retorna o valor NONE
if busca:
resultado = busca.group()
print(resultado)
# [0-9] se achar qualq... |
af7b5eca75fa1d5647c12f2413dba2cb0a16b769 | Kavin1409/Exam-Preparation | /2018 Past Paper/testing_1/Model solution/simplemaths.py | 917 | 4.25 | 4 | class SimpleMaths():
'''
A simple class to allow calculations to be performed on an integer.
'''
def __init__(self, number):
if type(number) != int:
raise TypeError("Error: Integer not passed into SimpleMaths constructor")
self.number = number
def square(self):
r... |
2f6fd10b6d88e1b4f50bf244665d0c124ba7323b | jfernand196/Ejercicios-Python | /unir_caracteres_join.py | 223 | 3.859375 | 4 | # concatenar una n cantidad de caracteres
lenguajes = ['python', 'c', 'java']
cadena = ';'.join(lenguajes)
print(cadena)
z = []
x = input(' ')
y = input(' ')
z.append(x)
z.append(y)
print(z)
unir = '-'.join(z)
print(unir) |
6a1e6152ac40b40dabca1c15741dc0bd856adaf7 | lichangg/myleet | /titles/144. 二叉树的前序遍历.py | 988 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 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
from typing import List
from utils.util_funcs import TreeNode
# 递归
class Solution... |
f29173d2bf9875c2748b4cb686b2d63522dda286 | AdiKaran/Project-Euler | /Problem9.py | 720 | 4.15625 | 4 |
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a**2 + b**2 = c**2
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
sqr_roots = {}
ans = [] * 3
for x in range(500) :... |
d6ddf1cd0210e34f143a9cdc81e10f26d57f776c | heyuhang/python | /python/内建函数/enumerate.py | 77 | 3.65625 | 4 | mylist = ['a','b','c']
for index,obj in enumerate(mylist):
print index,obj
|
69d18e0ab906c9423b9d96767563cfb79cfee61f | DamManc/workbook | /chapter_1/10.py | 564 | 3.90625 | 4 | #Arithmetic
import math
first_int = int(input("Enter an integer: "))
second_int = int(input("Enter another integer: "))
sum = first_int + second_int
diff_b_a = second_int - first_int
product = first_int * second_int
division = first_int / second_int
remainder = first_int % second_int
log = math.log10(first_int)
exp = f... |
644b35c2935f365ca75d82832c889baaf0327bd0 | Flerken101/Python-Crash-Course | /Chapter 10/练习题相关/Chapter 10练习题.txt | 12,581 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding:utf8 -*-
'''10-1 Pythonѧϰʼǣı༭½һļ д仰ܽһѧ
Python֪ʶÿһжԡIn Python you canͷ ļ
Ϊlearning_python.txt 洢ΪɱϰдijڵĿ¼С
дһȡļдݴӡΣһδӡʱȡļ
ڶδӡʱļδӡʱд洢һб,withӡǡ'''
#һδӡʱȡļ
with open("learning_python.txt") as file_object:
content = file_object.read()
print(content)
#ڶδӡʱļ
with open("... |
f90615649d170fa1a7b450bb634793f38b11d52a | anandvv/CodingDojo | /projects/05-Python/Fundamentals/listToDictionary.py | 429 | 3.90625 | 4 | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar", "Anand", "Pats"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas", "puppies", "kittens", "munchkins"]
def make_dict(list1, list2):
if len(list1) > len(list2):
new_dict = dict(zip(list1, list2))
e... |
96dc86ae8165ac5272209fe163d4f1b107238a3f | jrobbins6956/yr10_SummerHW | /HW/2/tables.py | 690 | 4.25 | 4 | #paste code here
name = input("What is your name >>>") #asking user for name and assigning it to 'name'
print("Do you know your times table?")
print()
number = int(input("Please enter a number >>>")) #asking user for a number and assigning it to 'number'
stop = int(input("Please enter the amount of times table you wa... |
d64eced2703dd49b6f873365d0f18040de0647ce | jankee31/python-snippets | /Coursera/Python For Everybody - Specialization/Dictionary.py | 1,577 | 4.03125 | 4 | #9.4 Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count o... |
daa60b72013bd6b94cd62fea677fb3f55030a8a1 | jing-ge/Jing-leetcode | /offer/pdd/33.py | 154 | 3.6875 | 4 |
def getres(t):
return (t-1)//3
N = int(input())
res = []
for i in range(N):
t = int(input())
res.append(getres(t))
for i in res:
print(i) |
d12edccff39e6a3a5f86e03b921f3eef6bdbc1a7 | FelixProtich/QueuesImplementation | /main.py | 665 | 4.03125 | 4 | queue = []
def enqueue():
element = input("Enter the element: ")
queue.append(element)
print(element, "is added to the queue")
print()
def dequeue():
if not queue:
print("Queue is empty")
else:
e = queue.pop(0)
print(e, "is removed from the queue")
print()
def ... |
7e1c69086dafedb33761fd1ae0106fe85406c894 | json-tian/Competitive-Coding | /In Python/CCC10_S1_ComputerPurchase.py | 616 | 3.578125 | 4 | computers = int(input())
rankings = []
if computers != 0:
for i in range (0, computers):
temp = input().split()
rankings.append([temp[0], ((2 * int(temp[1])) + (3 * int(temp[2])) + int(temp[3]))])
rankings.sort(key=lambda x:x[1], reverse = True)
if (computers != 1):
if (rankings[0][... |
e26fdd27f0e24d5e73d606dc464006acb397c80a | lucabecci/IP-UNGS | /guia-3/exer4/b.py | 434 | 4.40625 | 4 | # ) Hacer un programa que permita al usuario elegir un número m y un n y luego
# muestre todos los naturales entre m y n, pero salteando de a 3. Por ejemplo, si el
# usuario ingresara un n igual a 2 y un m igual a 14, el programa deberá mostrar
# 2, 5, 8, 11, 14
print("==> Inserte N para inicio del ciclo:")
n = int(in... |
ef60f4bd231f462a4f367d7a05f69ca238a53ddb | akimi-yano/algorithm-practice | /lc/946.ValidateStackSequences.py | 1,270 | 3.609375 | 4 | # 946. Validate Stack Sequences
# Medium
# 1547
# 35
# Add to List
# Share
# Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
# Example 1:
# Input: pushed = [1,2,3,4,5], p... |
a3e7db98c53083529a2c36e01d3bfe1bb48398e3 | tonytamsf/python-learning | /array_zero.py | 420 | 3.953125 | 4 | #!/usr/bin/env python
# Given an array, write a function to return true if the sum of any two numbers in the array is zero
import numpy
import array
def main():
a = [1, 66, -1, -66, 3, 4, -2, 5, 2, -4, -1]
any_zero(a)
def any_zero(a):
a = sorted(a)
for i in a:
for j in a:
if (i + ... |
89b92b1b34483348f989277e0d4919a9d629fb06 | MirroAi/python-100 | /61-70/case69.py | 802 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-10 12:06:06
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-10 21:23:54
# 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下来的是原来第几号的那位
def create_a_list(n):
l = []
for i in range(1, n+1):
l.append(i)
return l
def func... |
9c438c27b19bc1e30ee0830fab4b23dde38cc2a4 | gipast/expdataproc | /lab1/program.py | 913 | 3.53125 | 4 | import os
import sys
# import csv
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
filename = './data/txt/data_group1.txt'
data = pd.read_csv(filename, delimiter=r'\s+', names=['year', 'month', 'flux', 'ssnum'])
array = np.array(data)
# plt.plot(data['x'], data['y'])
# plt.plot(array[0][:], arr... |
a02a6f697da9f32640241c28455a3be074dda9b8 | jalondono/holbertonschool-machine_learning | /unsupervised_learning/0x00-dimensionality_reduction/1-pca.py | 500 | 3.859375 | 4 | #!/usr/bin/env python3
"""PCA 2.0"""
import numpy as np
def pca(X, ndim):
"""
function def pca(X, ndim): that performs PCA on a dataset:
:param X: is a numpy.ndarray of shape (n, d) where:
:param ndim: is the new dimensionality of the transformed X
:return: T, a numpy.ndarray of shape (n, ndim) co... |
7af475828d7630bfb5e32ac6dbda000199fdcac1 | swapniljha001/chegg | /python/employee.py | 1,012 | 3.796875 | 4 |
# calculate new salary for given pay percentage and old salary
def calculateNewSalary(oldSalary: float, payPercent: float) -> float:
return oldSalary + oldSalary * payPercent / 100
# read employees salary details from file
def readEmployeeData() -> list:
with open("CH3_Ex5Data.txt", 'r') as inFile:
re... |
5efef8b632185e0389be9baf6b4332dee9b4c20d | lkilcher/score_site | /io.py | 1,762 | 3.734375 | 4 | """
This module defines the function for reading data into
:class:`base.HotSpotCollections`.
"""
from .base import HotSpotCollection
import pandas as pd
def load_excel(fname):
"""
Load data from the Excel file 'fname'. This file must contain
'SiteData' and 'ResourceData' sheets. It can also contain a
'... |
702738ac4bad4805bca31da9c48ddbb00397510c | RadoslawP/avatars | /avatars.py | 454 | 3.546875 | 4 | def cecha(zapytanie, domyslna):
pytanie = zapytanie + '[' + domyslna + ']? '
odpowiedz = input(pytanie)
if (odpowiedz == ''):
odpowiedz = domyslna
print ('Wybrales: ', odpowiedz)
return odpowiedz
wlosy = cecha('Jaki kolor wlosow', 'brazowy')
wlosy_dlugosc = cecha('Jaka dlugosc wlosow', 'krotkie')
oczy = cecha('... |
7ae336a9cebff0aba99a923c9a20f7ec5c7ed86f | ocipap/algorithm | /baekjoon/3009.py | 352 | 3.71875 | 4 | x = []
y = []
def findOneElement (arr):
if arr[0] == arr[1] :
return arr[2]
elif arr[1] == arr[2]:
return arr[0]
else :
return arr[1]
for i in range(0, 3) :
a, b = map(int, input().split())
x.append(a)
y.append(b)
answer_x = findOneElement(x)
answer_y = findOneElement(... |
40f14abc125dd0889df1c80b3b6c1729695e66a6 | iamsaptorshe07/Python-Cheat-Codes | /Numpy Part 3.py | 415 | 3.765625 | 4 | ''' Performing some mathematical operation on numpy array'''
# Note : Not Linear Algebric Calculation
import numpy as np
arr1 = np.array([[1,2,3],[4,5,6]])
arr2 = np.array([[1,2,3],[4,5,6]])
arr3 = arr1 + arr2
arr4 = arr1 * arr2
arr5 = arr1 ** arr2
print(arr1,end='\n')
print(arr2,end='\n')
print(arr3,end... |
a60f402bdfb999ec8d77ef0dae5b40128614361f | cabulioj8165/cabulio_jake | /cabulio_jake-master/Pylesson_06/Box.py | 175 | 4.09375 | 4 | box = input("Please enter a word: ")
def printBox():
for i in range(0 , len(box)):
output = ""
output = box + " "
print(output + " ")
printBox()
|
751412739d01ec7f28e7ae1225e96a4cdc0b7f74 | fushengx/test | /order.py | 254 | 4.0625 | 4 | def sort(array):
for i in range(len(array)-1):
for j in range(len(array) -i -1):
if array[j] > array[j +1]:
array[j], array[j +1] = array[j +1], array[j]
array = [5, 99, 2, 1, 33, 57, 6]
sort(array)
print(array)
|
10792207a9694b5f0f16b4b5dafe4c5aee9060ca | eevee/raidne | /raidne/game/things/bits.py | 712 | 3.78125 | 4 | """Not actually things in here -- just little classes that help represent bits
of things."""
class Meter(object):
"""HP or magic; some integral thing that has a maximum and can be lowered
and filled.
"""
__slots__ = ('current', 'maximum')
def __init__(self, maximum):
if maximum < 1:
... |
c83811cdae12404c19155ed05fabfb8a76eef689 | ParulProgrammingHub/assignment-1-nikitajain1998 | /program4.py | 185 | 3.953125 | 4 | #program 4
#wpp to enter value in celcius and convert it to farheneit
cel=float(input("enter the temperature in celcius"))
far=cel*9/5+32
print("temperature in farheneit = %f" %(far))
|
1ae070d7172fa5d76b8ea5ea40ce7bac6ec4077a | punimor/ReferenceHandler | /Backend/PaperSorter.py | 5,247 | 3.765625 | 4 | import sys
import re
import os
# def wordExists(w):
# return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search is not None
# findWholeWord('seek')('those who seek shall find') # -> <match object>
# findWholeWord('word')('swordsmith')
class DesiredPhrase:
# words which should be contribute t... |
f60c4eb1c30397e64492113a1d8813d135850ab9 | sajjanparida/DS-Algorithms | /LinkedList/deleteNodeRecursion.py | 860 | 4.1875 | 4 | #write a recursive method to delete the node
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp=self.head
while(temp):
print(temp.data,end=' ')
... |
6527e1890862f5f781bfebbaf88dabd96ab82510 | poojithayadavalli/codekata | /probality of getting 1 on or before nth roll.py | 295 | 3.59375 | 4 | x=int(input())
l=[]
if(x%6!=0 and x>6):
l.append(str(x))
l.append("6")
elif(6%x!=0 and x<6):
l.append(str(x))
l.append("6")
elif (x>6 and x%6==0):
l.append(str(x//6))
l.append(str(1))
elif (x<6 and 6%x==0):
l.append(str(1))
l.append(str(6//x))
print(' '.join(l))
|
30fdfc1ca4d2082cbfbda139789120fc9dc1e26b | AliceSkilsara/python | /tasks/task20c.py | 852 | 3.96875 | 4 | #В три переменные a, b и c явно записаны программистом три целых попарно неравных между собой числа. Создать программу,
# которая переставит числа в переменных таким образом, чтобы при выводе на экран последовательность a, b и c
# оказалась строго возрастающей.
a=int(input("Input first number: "))
b=int(input("Input s... |
78e18223e9e5d976a9aa78af8ca1f5e3cb7b04c7 | Long0Amateur/Self-learnPython | /Chapter 6 Strings/Problem/19. A program adds comma to large integer.py | 343 | 4.15625 | 4 | # A program that asks the user for a large integer and inserts commas into it
# according to the standard American convention for commas in large numbers.
# For instance, if the user enters 1000000, the output should be 1,000,000
x = eval(input('Enter an integer:'))
number_with_commas = '{:,}'.format(x)
prin... |
ec6920762f04e3c0d3374f6fd63cd39eb33ac7a9 | mahehu/SGN-41007 | /exercises/Ex5/log_loss_template.py | 2,514 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 04 15:59:14 2016
@author: hehu
"""
import numpy as np
import matplotlib.pyplot as plt
def log_loss(w, X, y):
"""
Computes the log-loss function at w. The
computation uses the data in X with
corresponding labels in y.
"""
L = 0 # Accumulat... |
64e102b5f8b6b1acc8dba5e85d2ffdb73249f0ca | andrelima19/Projetos_Python | /Developer/Python_Definitivo/Exercícios/Dicionários/Ex 95 – Aprimorando os Dicionários.py | 1,151 | 4.125 | 4 |
# Exercício Python 095: Aprimore o desafio 93 para que ele funcione com vários jogadores,
# incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador.
# O programa vai ler o nome do jogador e quantas partidas ele jogou.
# # Depois vai ler a quantidade de gols feitos em cada partida.
... |
fcae345f5e97d8a3fe710c1ab16719b289162a3e | wjqmichael/workspace | /leetcode/rotate_list.py | 528 | 3.5625 | 4 | from my_list import Node, iter_to_node, node_to_iter
def rotateRight(head, k):
assert(head)
leng = 1
tail = head
while tail.next:
leng += 1
tail = tail.next
if not k % leng:
return head
count = leng - (k % leng)
prev = None
rt = head
while count:
pr... |
c00fcd88245c2315c0977e376917888fca036601 | DongjiY/Kattis | /src/thisaintyourgrandpascheckerboard.py | 694 | 3.890625 | 4 | def checkBoard(nums):
rows = []
for x in range(nums):
thisInput = input()
if thisInput.count('W') != thisInput.count('B'):
return 0
if "BBB" in thisInput or "WWW" in thisInput:
return 0
rows.append(thisInput)
columns = []
for x in range(nums):
... |
22279aabdcefd6117d7b8a9a4cf7b1239689fffc | Diego77Blaze/Algoritmia | /Lab3/Ejer3.py | 580 | 3.703125 | 4 | def division(p1, p2, k, epsilon, lista):
if p2-p1 < epsilon:
y1 = p1**3 - 6 * p1**2 + 4*p1 + 12
y2 = p2**3 - 6 * p2**2 + 4*p2 + 12
if y1 <= k <= y2 or y2 <= k <= y1:
lista.append([p1, p2])
else:
puntoMedio = (p2-p1)/2
tp = division(p1, (p1+puntoMedio), k, eps... |
4119786cc9610a35340eccfa6a195869d20cd211 | charles041644/python_code | /邏輯控制/猜數字.py | 533 | 3.703125 | 4 | def function():
import random
number = random.randrange(1, 100)
for i in range(5):
print("請猜一個數字")
x=eval(input())
i+=1
if(x==number):
print("Congratulations! You win!")
break
elif(x>number):
print("太大了")
else:
p... |
8dab6ccf65f5528c622107c4c37286f6a39b87a8 | Joneone124/myFirstGit | /newProperty.py | 976 | 3.796875 | 4 | #练习描述符
class MyProperty:
def __init__(self,fget,fset,fdel):
self.fget = fget
self.fset = fset
self.fdel = fdel
def __get__(self, instance, owner):#该方法由‘.’触发
#instance是MyProperty描述符拥有者的实例对象,即下面的的m,owner是MyProperty描述符拥有者本身,即man类
return self.fget(instance)
def __set__(s... |
de542e5187b7bcdf8fa2539bfd9302ef60e45fa4 | roy19-meet/yl1201718 | /lab2/listslab.py | 372 | 3.671875 | 4 |
#def listsfun():
#list1=[5, 10, 15, 20, 25]
#list2=[list1[0]] + [list1[-1]]
#print(list2)
#listsfun()
#a=[1,1,2,3,5,8,13,21,34,55,89]
#for i in range(len(a)):
#if a[i]<5:
#print(a[i])
def listsfun1():
a=[1,1,2,3,5,8,13,21,34,55,89]
b=[1,2,3,4,5,6,7,8,9,10,11,12,13]
for i in a:
for ... |
ac59157b9dffc5b98a43fbba6c00a3ebcbbe9329 | sptechguru/Python-Core-Basics-Programs | /continue.py | 193 | 3.859375 | 4 | while(True):
inp =int(input("Enter a Number: "))
if inp>100:
print("congrats You have 100 in Numbers/n")
break
else:
print("Try again/n")
continue |
51b190c8332c246453a1d180bcdb153a125116e4 | MatanDanos/AttnGAN-v1.1 | /src/models/attention.py | 4,701 | 3.53125 | 4 | import torch
import torch.nn as nn
from loguru import logger
class Attention(nn.Module):
"""The attention mechanism as implemented in the paper
Parameters:
word_feature_dim (int, default=256): the dimension of the word encoding as output by the text_encoder
image_feature_dim (int, default=128... |
de149df5cf6539451b867b8b37a7dfdff5695836 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2751/60640/294598.py | 855 | 3.515625 | 4 | def find_min(arr, x, y):
curr_dis = 1 << 31 - 1
min_dis = 1 << 31 - 1
for ii in range(len(arr)):
for jj in range(len(arr[0])):
if arr[ii][jj] == 0:
curr_dis = abs(x-ii) + abs(y-jj)
if curr_dis < min_dis:
min_dis = curr_dis
return mi... |
7ae532ae20bd0fe06a2c66174bbebeb7e38690ac | kviiim/AdventOfCode2020 | /day5/day5-1.py | 705 | 3.6875 | 4 | import math
def findRow(currentRange, halfs):
if halfs[0] == 'F' or halfs[0] == 'L':
newRange = [currentRange[0], math.floor((currentRange[1]-currentRange[0])/2) + currentRange[0]]
else:
newRange = [math.ceil((currentRange[1]-currentRange[0])/2) + currentRange[0], currentRange[1]]
if len(ha... |
19c8be3ab215fe3bc6042d579c9d60e3872aa35e | alexandre146/avaliar | /media/codigos/36/36sol314.py | 176 | 3.625 | 4 | n=int(input())
m=int(input())
a=0
while m>n:
if m%n==0:
print(m)
a=1
break
m-=1
if a==0:
print('sem multiplos menores que %i'%m)
|
c63c55b802c2edf4f4cefbf7aefd33badbefe2b4 | poojamalviya/ds-algo | /subsetArray.py | 241 | 3.71875 | 4 |
def subset():
s = [1,2,3]
res =[]
count =0
while count < len(s):
arr =[]
for i in range(0, count):
arr.append(s[i])
res.append(arr)
count = +1
return res
print(subset()) |
e3841062722c68a3953b87ccf45d948b751c2f34 | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/kahyee/Session03/list_lab.py | 1,405 | 4.1875 | 4 | #!/usr/bin/env python3
#Part 1
fruit = ["Apples", "Pears", "Oranges", "Peaches"]
print(fruit)
response = input("add a fruit to the list...")
fruit.append(response)
print(fruit)
user_number = input("write the number of the fruit you want ")
print(user_number)
print(fruit[int(user_number) - 1])
fruit = ["Bananas... |
7bab69fc77ff895650d47014e7e29353fca61ecc | guoea/sample-code | /python/projecteuler/p46.py | 780 | 3.796875 | 4 | from bisect import bisect_left
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
twice_square_list = [2 * i ** 2 for i in range(1, 100)]
import math
upper_bound = 10000
def is_prime(num):
for i in range... |
4c0c72e6a9140aff0ae67c8cc4dda64e54c17a75 | singularity0/HackBG_Pro0 | /week4/neighbours_count.py | 289 | 3.9375 | 4 | numbers = [1, 2, -2, 0, 0, 5, -5]
def count_zero_neighbours(numbers):
count = 0
for i in range(0,len(numbers)-1):
if numbers[i] + numbers[i + 1] == 0:
count += 1
print('numbers ' + str(numbers[i]) + 'and' + str(numbers[i+1]))
return count
print(count_zero_neighbours(numbers))
|
1235dae40b6b80a7b628aef66350bc5ac64a313b | JackeyGuo/Algorithms | /Leetcode/其他/766-托普利茨矩阵-e.py | 1,079 | 3.65625 | 4 | from typing import List
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
"""
从第二行第二列开始遍历,依次判断 [i,j] 位置的值是否等于 [i-1,j-1]位置的值
"""
n, m = len(matrix), len(matrix[0])
for i in range(1, n):
for j in range(1, m):
if matrix[i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.