blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
842a0e1ba6bbd01a986e816b3a1c479d4f59fff5 | CreatorGhost/HackerRank | /2D Array DS | 1,163 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def findIt(u,p,a): #function just to add every single hourglass
an=0 #to add every elements
for i in range (u,u+3): #this function neds to sole for 3x3 so start and end with 3
for j in range (p,p+3):
i... |
421da4356fe1c641216ff34810950572251f4ada | alisatsar/itstep | /Python/HomeWork/04.04.2017.py | 1,723 | 4.1875 | 4 | """Напишите программу, запрашивающую у пользователя ввод числа. Если число принадлежит диапазону от -100 до 100,
то создается объект одного класса, во всех остальных случаях создается объект другого класса.
В обоих классах должен быть метод-конструктор __init__, который в первом классе возводит число в квадрат,
а во-вт... |
95d31d2b7728c6977bab65d0f27d02bbd6ed22e6 | fy88fy/studyPython | /study_example/2018.01.26/Hanshu.py | 467 | 3.765625 | 4 | #/usr/bin/env python
# -*- coding:utf-8 -*-
# @time :2018/1/26 21:37
# @Author :FengXiaoqing
# @file :Hanshu.py
def add(args):
total = 0
for i in args:
total += i
return total
def main():
number = list()
s = input("Please input some number add (a + b + c ..):")
print... |
01f44499d127d555c84c1411f6486eb95bbbcb8b | m4mayank/ComplexAlgos | /subsets.py | 874 | 3.71875 | 4 | # Given an integer array nums of unique elements, return all possible subsets (the power set).
# The solution set must not contain duplicate subsets. Return the solution in any order.
# Example 1:
# Input: nums = [1,2,3]
# Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
# Example 2:
# Input: nums = [0]
# Outp... |
513c3de6fc20fbebbeccca06ca9ca0a77b955a04 | SimZhou/algorithm014-algorithm014 | /Week_03/98. 验证二叉搜索树.py | 1,124 | 3.921875 | 4 | # https://leetcode-cn.com/problems/validate-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# '''递归'''
# ... |
a3ce138c0a54571d22232429b9283b0d45e92b96 | elefert400/Class_Work | /Algorithms/HW2/scc_e330l807.py | 3,387 | 3.53125 | 4 | from __future__ import print_function
import fileinput
import sys
class Graph:
def __init__(self,v):
self.Vertices = v
self.graph = {new_list: [] for new_list in range(self.Vertices)}
self.sorted = [[] for x in range(self.Vertices)]
self.counter = 0
#adds an edge ... |
ac19f9a5a561cb3a5fefd54248352fc3bd19f9d0 | twhit223/fundraising_simulation | /simulate_dynamic.py | 7,578 | 3.8125 | 4 | from startup import Startup
from definitions import STARTUP_STATES
from statistics import mean, stdev
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from wat import wat
# This is the main function that runs the simulation of the startup. It takes in an initialized Startup object and performs v... |
678cfbbc306b5c22f718d7f0378bc8a5b22323c9 | kaushal6038/ajax | /admin_test_pro/pro/testfile.py | 276 | 3.546875 | 4 | import datetime
seconds = datetime.datetime.now()
print(seconds.minute)
import time
time.sleep(4)
# with open("/checkfile.txt", "w") as f:
# f.write("Hello World form")
file = open("checkfile.txt", "a")
file.write("Your text goes here "+ str(seconds))
file.close()
|
b3b441ce41915714ae067851b2c2aa7b20c8c909 | sofiamalpique/fcup-programacao-01 | /3.6.py | 255 | 3.546875 | 4 | from turtle import*
def triangulo(lado):
for i in range(3):
forward(lado)
left(120)
def triforce(lado):
triangulo(2*lado)
penup()
forward(lado)
pendown()
left(60)
triangulo(lado)
|
833898a98dc90002e36939a5f923b441affa64b0 | benscruton/python_fundamentals | /coding_dojo_assignments/fundamentals/make_dictionary.py | 962 | 3.78125 | 4 | def make_dict_orig(list1, list2):
new_dict = {}
inverted = len(list2) > len(list1)
keys = list2 if inverted else list1
values = list1 if inverted else list2
for i in range(len(values)):
new_dict[keys[i]] = values[i]
return new_dict
def make_dict(list1, list2):
zipped = zip(list2, li... |
001c8f38937c2676dd7b0c4a9c58ee136e3b1a90 | Yaswanthbobbu/IQuestions_Python | /Questions/21. Reverse string.py | 162 | 3.96875 | 4 | str = input("Welcome to programming :")
words = str.split()
print(words)
words.reverse()
#words[-1::-1]
print(words)
outputstr=' '.join(words)
print(outputstr) |
439dad735e97009088f24b7c657a33c56a66ea6e | huangqiank/Algorithm | /leetcode/two_Pointer/p.py | 20,008 | 3.5 | 4 | def three_sum_smaller(nums, k):
nums = sorted(nums)
count = 0
for i in range(len(nums)):
l = i + 1
r = len(nums) - 1
while l < r:
if nums[l] + nums[r] + nums[i] == k:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
... |
8715b54a3571ede0e7d088d1f8821a9491abb9ea | the-eric-kwok/Wudao-dict | /wudao-dict/dict/dict_pys/wd.py | 15,650 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import re
tag_re = re.compile('^[a-z0-9]+$')
attribselect_re = re.compile(
r'^(?P<tag>\w+)?\[(?P<attribute>[\w-]+)(?P<operator>[=~\|\^\$\*]?)' +
r'=?"?(?P<value>[^\]"]*)"?\]$'
)
# /^(\w+)\[([\w-]+)([=~\|\^\$\*]?)=?"?([^\]"]... |
f40f9d9d96754c56f9a159c50cebe59932a50172 | HJSang/leetcode | /code/py/bfs/lc_207_Course_Schedule.py | 1,985 | 3.84375 | 4 | # 207. Course Schedule
# There are a total of numCourses courses you have to take
# labeled from 0 to numCourses-1.
# Some courses may have prerequisites
# for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
# Given the total number of courses and a list of prerequisite pa... |
7055d2e590c97790eadb061c37e45ac91e9ed57d | OlexandraSydorova/lab_works | /labaratory1/task2.py | 389 | 3.8125 | 4 | """Обчислення конкретної функції, в залежності від введеного значення х"""
from math import sin
import re
from validators.validators_library import validator
from validators.validators_library import re_float
x = float(validator(re_float,"Введіть х "))
if x<=3:
print( x**2 +3*x+9)
else:
print(sin(x)/(x**2-9))... |
6fa8a226cd1cbe56d99e17e1c63cbbc4c7eb8821 | zadfab/Backup | /Voodo_Prime.py | 566 | 3.9375 | 4 | user_input = int(input("enter the number :"))
def prime(number):
for i in range(2,number):
if number%i == 0:
print("not a prime")
break
else:
print("proceeding...")
return True
return False
if prime(user_input):
reciproc... |
069750d16a682f72735962d42e5d3d749f5b7cdc | raghubegur/PythonLearning | /0_tkinter/buttons.py | 252 | 3.90625 | 4 | from tkinter import *
root = Tk()
def myClick():
myLabel = Label(root, text='I clicked a button')
myLabel.pack()
myButton = Button(root, text='Click Me', command=myClick, fg='blue', bg='white')
myButton.pack()
root.mainloop()
|
bed46a8f641a535bc5c1ae71c9bf12a9f8d44a47 | yonglin/thinkPy | /Tree.py | 1,744 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 13 15:37:14 2013
@author: yuege
"""
class Tree:
def __init__(self, cargo, left = None, right = None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
def printTreePostorder(tre... |
a8fea4642764d65e6e067009d20da63bdc38a24f | adjeri/Data-Structures-And-Algorithms | /Arrays-HashTables/moveZeroes.py | 345 | 3.609375 | 4 | def moveZeroes(nums):
i = 0
while i < len(nums) - 1:
j = i+1
while j < len(nums):
if nums[i] == 0 and nums[j] != 0:
swap = nums[i]
nums[i] = nums[j]
nums[j] = swap
i += 1
j+= 1
i += 1
print(nums)
... |
2a9aaf0f3116eb0bed882c431d4e3d9f26e3bd34 | juan7914/prueba1 | /ejercicios clase dos 2/caracteresAa.py | 337 | 3.921875 | 4 | print("programa que calcula la longitud de la cadena de texto y las veces que aparece la letra a")
cadena = input("ingresa tu cadena de texto o frace " )
largoCadena = len(cadena)
contarA= cadena.upper().count("A")
print("la longitud de tu cadena de texto es {}, y aparece la letra A en tu cadena {} veces.".format(largo... |
d0bb52faad6b72afc7c6058ad478fcb814d74e0b | TerryAg/code1161 | /Tblock.py | 1,005 | 3.8125 | 4 | import turtle
import random
# Describe this function...
def draw_T():
global x, y
turtle.goto(x,y)
turtle.pendown()
turtle.color('#%06x' % random.randint(0, 2**24 - 1))
draw_base()
turtle.right(90)
turtle.forward(100)
draw_top()
turtle.penup()
# Describe this function...
def draw_base():
turtle.be... |
914b31cebd8156783ca86e3cefd13f70f387e111 | nidiamarquez13/plataforma_digital | /PYTHON/ejercicio008.py | 777 | 4.34375 | 4 | """
STRING y mas!
"""
esto_es_una_string = "Hola"
esto_es_otra_string = "Mundo"
#Concatenar
print(esto_es_una_string +' '+ esto_es_otra_string)
#hola mundo
#MAYUS
print (esto_es_una_string.upper())
#minus
print (esto_es_una_string.lower())
#Primera Mayuscula
print (esto_es_una_string.capitalize())
#Poner mayuscula en... |
6b0dc222dcb6815806c73f592b163f454d48619e | IlyaChebanu/machine-learning | /k-means-1.py | 867 | 3.609375 | 4 | import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
from sklearn.cluster import KMeans
style.use('ggplot')
# Some arbitrary points that can be easily formed into groups
X = np.array([[1, 2],
[1.5, 1.8],
[5, 8],
[8, 8],
[1, 0.6],
[9, 11]])
# Define the classifier t... |
9e6f5fc23518883a28137fd256dd0dd8837b541c | MarcosRibas/Projeto100Exercicios | /Python/ex081.py | 649 | 4.09375 | 4 | '''
Ex081 Crie um programa que vai ler vários números e colocar em uma lista. Depois disso mostre:
a) Quantos números foram digitados.
b) A lista de valores de forma decrescente.
c) Se o valor 5 foi digitado e está ou não na lista
'''
list = []
while True:
n = int(input('Digite um número: '))
list.append(n)
... |
c24a1055bce8c053b4fb7c249a19d794c554009f | huisai/Learning-Data-Mining-with-Python | /流畅的Python/C2.4+5.py | 747 | 3.671875 | 4 | """
Created on Mon Apr 9 14:46:18 2018
<流畅的Python2.4+5>
@author: Ethan
"""
#1-切片和区间忽略最后一个元素:;
# 快速返回元素个数
range(3)
# 后一个坐标减去前一个坐标即为切片长度
len = stop - start
# 利用任意一个坐标将序列分为两个不相重叠的两部分
my_list[:x]
my_list[x:]
#2-对切片进行赋值
l = list(range(10))
l[2:5] = [20]
del l[5:7]
#报出异常,此处仅可以赋值可迭代对象
l[2:5] = 100
l[2:5] = [100]
#3-对列表使用+... |
a914b1311076bc74f29049639af2e66bbdb8e88f | Eudasio-Rodrigues/Linguagem-de-programacao | /lista aula 07/questao 06.py | 298 | 4.125 | 4 | #Escreva uma função que receba como argumento uma lista e uma tupla
#e retorne um set composto pelas duas coleções.
lista = [x for x in range(0,11)]
tupla = ('eudasio',"mombaca",27)
def converte_set(lista,tupla):
a = set(lista)
b = set(tupla)
print(a|b)
converte_set(lista,tupla) |
315e4b278d7404e489330fc0ff1f401c0e36cc03 | DanielXuuuuu/AI_Principle | /hw2/Sudoku_Solver/BT.py | 1,035 | 3.609375 | 4 | # back-tracking (Constraint Satisfaction Problem, CSP)
def is_repeat(puzzle, row, col, num):
for i in range(9):
if puzzle[row][i] == num:
return True
for i in range(9):
if puzzle[i][col] == num:
return True
block_x = int(row / 3) * 3
block_y = ... |
b1accb3e1d2ec4593f5e1d65c5c403bdb28cb18e | Naysla/Machine_Learning | /1_Python_/Example_Comprehension_dictionary.py | 371 | 3.75 | 4 | #Practice from datacamp course: Phyton Data Science Tollbox
# Create a list of strings: fellowship
fellowship = ['hi', 'this', 'is', 'an', 'example']
# Create dict comprehension: new_fellowship
new_fellowship = {member:len(member) for member in fellowship}
# Print the new dictionary
print(new_fellowship)
#Result
#{... |
aabbb164733f55499d87ec9a03804e32b76c15e2 | anvarknian/preps | /Arrays/sorting/selection_sort.py | 377 | 3.921875 | 4 | value1 = 5
value2 = 7
array = [1, 2, 3, 4, 5, 6]
unsorted_array = [1, 2, 3, 4, 5, 6, 4, 3, 2, 6, 7, 8, 0]
def selection_sort(A):
for i in range(len(A)):
min_idx = i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A... |
32cf300e0a5a4459051ba1b052258a07354a6b66 | casjunior93/Introdu--o-ao-Python---DIO | /aula4-for.py | 258 | 3.703125 | 4 | #numeros primos
#itera de 1 até 101
for num in range(101):
#verifica se o número é primo
div = 0
for x in range(1, num+1):
resto = num % x
if resto == 0:
div += 1
if div == 2:
print('{}'.format(num))
|
58f33eba851006188bba21a86bbf119d84569a4e | parayc/FaceTrack_UE4 | /pythonScripts/knn.py | 608 | 3.578125 | 4 |
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import pandas as pd
import csv as csv
def buildKNN(file,PCA=False):
df = pd.read_csv(file, header=0)
# Store the id column before dropping it
id_column =df["id"]
# Drop it from th
df = df.drop(["id"],axis=1)
# Convert to usable format
tra... |
11c3081a6050aa729fd9d3d562bb63b423c68b8c | git-1024/Python | /Python/diffPythonHtml01.py | 918 | 3.53125 | 4 | #!/usr/local/env python
# -*- coding: utf-8 -*-
import difflib
import sys
try:
textfile1=sys.argv[1]
textfile2=sys.argv[2]
except Exceptions,e:
print "Error:"+str(e)
print "Usage:diffPythonHtml01.py filename1 filename2"
sys.exit()
def readfile(filename):
try:
fileHandle = open(filena... |
519abf741da9d46e9c52a718bca6655831de1ad4 | DominikaJastrzebska/PyLadies-projects | /Volume of cuboid.py | 498 | 4.03125 | 4 | a = float(input('Enter the side a of the cuboid: '))
b = float(input('Enter the side b of the cuboid: '))
H = float(input('Enter the height H of the cuboid: '))
V = a*b*H
if a != b and a != H and b != H:
classification = ''
if (a == b and a != H) or (a == H and b != H) or (b == H and a != H):
classif... |
34ba42316d825ba29f164f51d16c02cce47c77b0 | jorgeg73/PythonPro | /numeros al azar.py | 200 | 3.625 | 4 | import random
#numeros al azar
print "Numeros al Azar"
print random.random()
print "Da el rango:\n"
enum= input ("Primer rango\n")
enum1 = input ("Segundo Rango\n")
print random.randint(enum,enum1) |
c15ca359fa54695fd220d37ebba97db2c86ade69 | GavinAlison/python-learning | /06/consumer.py | 1,179 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/1/2 21:31
# @Author : alison
# @File : consumer.py
# 协程
# 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行。
#
# 注意,在一个子程序中中断,去执行其他子程序,不是函数调用,有点类似CPU的中断。比如子程序A、B:
#
# 协程本质
# Python对协程的支持是通过generator实现的。
# 在generator中,我们不但可以通过for循环来迭代,还... |
af03b6cc9b6507c3f751a4aa18c8760e31e0ca26 | JoaoFiorelli/ExerciciosCV | /Ex003.py | 131 | 3.90625 | 4 | n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n = n1 + n2
print('A soma desses número é ',n)
|
425b9277016f9297a02943ef3aa1ef9b55025572 | karanpathak/SPOJ | /CANDY3.py | 147 | 3.6875 | 4 | t=input()
for _ in xrange(t):
s=raw_input()
n=input()
sum=0
for _a in xrange(n):
sum+=input()
if sum%n==0:
print "YES"
else:
print "NO" |
82cc540a4314db5aa0f17a1b664936bb7390410b | Ranxf/laonanhai | /day3/3-11 func_demo2.py | 834 | 3.84375 | 4 | """
为什么要使用函数:减少重复代码;使程序变得可扩展;使程序变得易维护
日志文件处理(框架搭建必须有的)
"""
import time
def logger():
time_format = '%Y-%m-%d %X' # 年月日,时分秒
time_current = time.strftime(time_format)
with open('a.txt', 'a+') as f:
f.write('%s end action\n' % time_current) # 类似写日志文件
# 模拟一个功能,并将日志文件写入日志文件
def test1():
""... |
b0e1aa14fb4b68f97b7d10ec15d402e985eb884f | dianafa/coding_tasks_python | /karate-chop/binary_search3.py | 1,054 | 3.515625 | 4 | import unittest
def search(x, tab):
return find(x, tab, 0, len(tab) - 1)
def find(x, tab, start, end):
if end < start:
return -1
if end == start:
if tab[end] == x:
return end
else:
return -1
pivot = (start + end) / 2
if x < tab[pivot]:
return find(x, tab, start, pivot)
if x > tab[pivot]:
retu... |
388c3fadc989725441e616f78054122c34de9d85 | sujith1919/TCS-Python | /puzzle.py | 771 | 3.8125 | 4 | #puzzle
board=[3,5,4,1,0,2,6,7,8]
validmoves={0:(1,3),1:(0,2,4),2:(1,5),3:(0,4,6),
4:(1,3,5,7),5:(4,2,8),6:(3,7),7:(4,6,8),8:(5,7)}
def PrintBoard():
print board[0],board[1],board[2]
print board[3],board[4],board[5]
print board[6],board[7],board[8]
def GetMove():
return int(raw_input("\n Enter move : "))
... |
00b437101a71858975daabd4dad1ac867f1a0265 | nguyenphuclan/Sorting-and-Searching | /binarySearch.py | 535 | 3.84375 | 4 | def binary(myItem, mylist):
bot = 0
top = len(mylist) - 1
found = False
while bot <= top and not found:
middle = (bot + top) // 2
if mylist[middle] == myItem:
found = True
elif mylist[middle] < myItem:
bot = middle + 1
else:
top = middle -1
return found
if __name__ == "__main__":
numberList = [2... |
58b80867d306a44d223410adabdbec2ea91b2663 | WiPeK/python | /python_challenging/question11.py | 193 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#podzielne przez 5
inp = [x for x in input().split(",")]
res = []
for i in inp:
if int(i, 2) % 5 == 0:
res.append(str(i))
print (",".join(res)) |
ebff0801fcd35de67bfe2c78b1718011dc3381ed | namratab94/LeetCode | /reorder_log_files.py | 1,198 | 3.609375 | 4 | '''
Problem Number: 937
Difficulty level: Easy
Link: https://leetcode.com/problems/reorder-log-files/
Author: namratabilurkar
'''
'''
Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
'''
class Solution:
def re... |
756a094761a5c4bc91feca712e305a5d2051a2bd | mlmldata/raspi_tempProbe | /mug_temp.py | 1,319 | 4.28125 | 4 | '''
Write a program that measures and records temperature temperatures using the
raspberry pi and the attached temperature sensor.
'''
import tempProbe as tp # This is the library for the TempProbe class that we will use
import numpy as np
# This code will create and initialize an instance of an object called probe... |
68db3b7d4610eb3411f59271af19eca1722c74d5 | zuobing1995/tiantianguoyuan | /第一阶段/day02/exercise/birthday.py | 308 | 4.03125 | 4 | # 1. 今天是小明的20岁生日, 假设每年有365天,
# 计算它过了多少个星期天,余多少天(不要求精确)
# print('它过了', 20 * 365 // 7, '个星期天')
# print("余", 20 * 365 % 7, '天')
days = 20 * 365
print('它过了', days // 7, '个星期天')
print("余", days % 7, '天')
|
1cb4beb79b6a8cac38a4b8677200619d6f543751 | Banjiushi/wujiuDict | /wujiuDict.py | 1,196 | 3.75 | 4 | from tkinter import Tk, Button, Entry, Label, Text, END
from main import main, getInfo
class Application:
def __init__(self):
# 主窗口
self.window = Tk()
self.window.title('无咎词典')
self.window.geometry("280x350+500+200")
# 输入框
self.entry = Entry(self.window)
# ... |
12db01a1e965c3d0127dbfea941e2d8e03a8dd6d | abhishekkrsaw/Online-gas-booking-System | /register.py | 3,030 | 3.5 | 4 | from tkinter import *
from tkinter import messagebox
def back():
window.destroy()
import interface
def validation():
if v1.get()=='':
messagebox.showwarning('Error!!','Please enter your First Name!!')
elif v2.get()=='':
messagebox.showwarning('Error!!','Please enter your Last ... |
d9a85c435ad766b2bccb3e523e0cc4ebae22141e | Tanmay53/cohort_3 | /submissions/sm_103_apoorva/week_13/day_4/count_vowels.py | 255 | 3.765625 | 4 | userInput = list(input("Enter values of list with space between: ").split())
print(userInput)
vowels = ["A","E","I","O","U","a","e","i","o","u"]
count = 0
for i in userInput:
for j in i:
if j in vowels:
count += 1
print(count)
|
9746c4f6b92251f42c09eb39a72b0ae207be31f7 | sunxinzhao/LeetCode_subject | /simple/number/202.py | 1,362 | 4.03125 | 4 | # coding=utf-8
'''
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
来源:力扣(LeetCode)
链接:https://lee... |
755c53f29d56f0cf9645229d3dd2689f81c1cef1 | SureshUppelli/Python-Scripts | /test.py | 142 | 4.1875 | 4 | val = input ("Enter String: ")
rev = val [::-1]
if val == rev:
print ("String is palindrome")
else:
print ("String is not Palindrome") |
a756a0ead6ef1dfd8d7c9a11845808faa886e348 | suyundukov/LIFAP1 | /TD/TD2/Code/Python/5.py | 375 | 3.953125 | 4 | #!/usr/bin/python
# Tester si un entier choisi par USER est multiple de 5 ou de 7
print('Donne moi une valeur : ', end='')
a = int(input())
if (a % 5 == 0) and (a % 7 == 0):
print('C\'est le multiple de 5 et de 7')
elif a % 5 == 0:
print('C\'est le multiple de 5')
elif a % 7 == 0:
print('C\'est le multiple... |
6958d64ab507252e7adbedec1dc11089a1b432ef | ShiftingNova/bars | /lab.py | 289 | 3.6875 | 4 | # Jordan Walker CSC110 this code takes an imput and creates a bar thing and puts # on the left side of the bar
code = str(input("Enter bar string:\n"))
print("+---------+")
i = 0
while i<len(code):
print("|"+ "#" * int(code[i]) + " " * (9-int(code[i])) + "|")
i = i +1
print("+---------+")
|
ff12a1c6756c31988c8f4d422e96086fc75ee8d2 | moneymashi/SVN_fr.class | /pythonexp/a01_start/a15_tuple.py | 654 | 3.65625 | 4 | '''
Created on 2017. 7. 19.
@author: kitcoop
Tuple : 읽기 전용 - 리스트 보다 속도 빠름.
'''
t1 = "a", "b", "c","a"
t2 = ("a", "b", "c","a")
t3 = (1, 2, 3,4)
print(t1,t2)
print(t1, t1*2, len(t1), t1.count("a"), t1.index("b"))
print(t3, t3*2, len(t3))
p =(1,2,3)
# p[1]=20 수정 불가
''' 튜플데이터를 list으로 변경'''
q=list(p)
pri... |
ebcaa344f5afd6b1482d8746d37bfc626737c352 | harrygraham/DeepLearning-CreditCardFraud | /simple_logistic_regression.py | 2,842 | 3.703125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the conf... |
08a8270831b2b6cf129fb2755338ceb84273eae7 | erikanni/physics-calc | /menudict.py | 497 | 3.609375 | 4 |
def func_a():
print("func a")
def func_b():
print("func b")
def func_c():
print("func c")
def func_d():
print("func d")
def main():
print('''
function a
function b
function c
function d
''')
menu_dict = {"a": func_a, "b": func_b, "c": func_c, "d": func_d}
answer =... |
250a38503a3a3d55d4ca5098c1dca6d3d4c5f62b | MagicMoa/Learning-Python | /Dictionaries.py | 1,616 | 4.84375 | 5 | #Lesson 5: Dictionaries
#Dictionaries are groups of values that can be defined with key-value pairs
country = {'Name': 'Switzerland', 'Size': 'Small', 'Continent': 'Europe', 'Cities': ['Zurich', 'Basel']}
print (country)
print (country['Size']) #Can access the value for a specified key
print (country.get('Name')) ... |
872a18feb16cd8cb315305fdb5aaffeca821d6b2 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_96/1877.py | 1,181 | 3.71875 | 4 | def should_add(s,p,ts):
if(p == 0):
return True,s
if(ts == 0):
return False,s
d = int(ts/3)
if(ts%3 == 0):
if(d >= p):
return True,s
elif (d+1 >= p) and (s>0):
return True,s-1
else:
return False,s
elif ((ts-1)%3... |
c216c5c95d36cee7842255a7e618d70856781a32 | ramson/randomImage | /LineCollection.py | 1,008 | 3.578125 | 4 | from Line import Line
from Point import Point
from random import randint
class LineCollection:
def __init__(self, max_lines, max_x, max_y):
self.__lines = []
self.__maximum_number_of_lines = max_lines
self.__max_x = max_x
self.__max_y = max_y
def get_lines(self):
return... |
c5f71bbecb940ba9d2e3769e551877b99cf41e52 | VachaArraniry/python_portfolio | /inheritance.py | 888 | 3.84375 | 4 | class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def calculate_discount_price(self, discount):
return self.price - (self.price * (discount/100))
class Shoes(Product):
def __init__(self, name, price, brand, size, color):
Produ... |
d98a58623db4f6883a06fde2cce02297a93cb650 | dahu1/core-scrapy-learning | /t1.py | 587 | 3.59375 | 4 | #!/usr/bin/python
#coding=utf-8
#author=dahu
import pprint,sys
reload(sys)
sys.setdefaultencoding('utf-8')
b='haha'
def file_size(name):
if name.endswith('g') or name.endswith("G"):
a=1000*1000*1000
elif name.endswith('m') or name.endswith("M"):
a=1000*1000
elif name.endswith('k') or name.en... |
b093cd47bafb1651990639c5f71d521f64ab1fc9 | SongGithub/algorithm-data_structures | /tree.py | 6,793 | 4.09375 | 4 | """implementation of Binary Tree"""
class BinaryTreeNode(object):
def __init__(self, data, left=None, right=None, parent=None):
self.data = data
self.left = left
self.right = right
self.parent = parent
def __str__(self):
return str(self.data)
def ge... |
1402f9912860e1fbb84f1cde73c4d4283498f3e0 | SocioProphet/CodeGraph | /kaggle/python_files/sample851.py | 27,669 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## How Autoencoders work - Understanding the math and implementation
#
# ### Contents
#
# <ul>
# <li>1. Introduction</li>
# <ul>
# <li>1.1 What are Autoencoders ? </li>
# <li>1.2 How Autoencoders Work ? </li>
# </ul>
# <li>2. Implementation and UseCases</li>
# <ul>
# ... |
ee3e5ca9844fad8882a966777f08b1ba880222ba | mohamed-elsayed/python-scratch | /Iterator-generator.py | 7,280 | 4.53125 | 5 | # =================================================
################ Iterator/generator ###########
# =================================================
# Objectives
# Define Iterator and Iterable
# Understand the iter() and next() methods
# Build our own for loop
# Define what generators are and how they can be us... |
6fd24c90d8f11203073a20e92dc57a5d95e75aef | LinChiGong/Reinforcement-Learning-Racetrack-Problem | /src/racetrack.py | 5,631 | 3.90625 | 4 | #!/usr/bin/env python3
'''
This class stores the information about a racetrack on which the race car runs
'''
import numpy as np
class Racetrack():
def __init__(self, file):
self.file = file # Name of the racetrack file
# Stores the racetrack in a 2D list and remove the first line
self.t... |
6d958b209efb49ee3070ce8cca4171c708962a4b | DevYam/Python | /Ex3.py | 704 | 4.0625 | 4 | # Guess the number Game
key = 43
count = 10
print("Total guesses left = ", count)
while True:
guess = input("Enter a number to guess\n")
if not guess.isnumeric():
print("Enter a valid number")
continue
if int(guess) < key and count > 0:
print("you need to enter a higher value\n")
... |
c238078f55464429915d9c9f7b8987336966c957 | hcs42/hcs-utils | /bin/Catless | 2,227 | 3.703125 | 4 | #!/usr/bin/python
# Prints the text from the standard input or the given files using `cat` or
# `less` depending on whether the text fits into the terminal
import optparse
import os.path
import subprocess
import sys
def parse_args():
usage = 'Usage: Catless [options] [FILENAME]...'
parser = optparse.OptionPa... |
c24fdf73fee84a9be9b3eee03e9fc3889aec264b | tanx-code/levelup | /design_patterns/state.py | 858 | 4 | 4 | """状态机模式
允许对象在内部状态改变时改变它的行为,对象
看起来好像改了它的类。
"""
class State:
def __init__(self, m):
self.machine = m
class AState(State):
def db_a(self):
print('do a')
self.machine.set_state(self.machine.b_state)
class BState(State):
def do_b(self):
print('do b')
class Machine:
curr... |
a87aaf69c2971b2ae241cae12c4b3c2624005e83 | tjatn304905/algorithm | /SWEA/5186_이진수2/sol1.py | 411 | 3.59375 | 4 | import sys
sys.stdin = open('sample_input.txt')
def change(N):
result = ''
for i in range(1, 13):
if N >= 1 / 2**i:
result += '1'
N -= 1 / 2**i
if N == 0:
return result
else:
result += '0'
return 'overflow'
T = int(input())
... |
3a1c50c59e5819bf13bfd8b4ab7108fe0c639771 | ramaranjanruj/Machine-Learning | /Ridge Regression/Ridge.Regression.py | 5,393 | 3.75 | 4 | import pandas as pd
import numpy as np
from sklearn import linear_model
import math
dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int,
'sqft_living15':float, 'grade':int, 'yr_renovated':int,
'price':float, 'bedrooms':float, 'zipcode':str, 'long':float,
's... |
b9104f7316d95eaa733bbbd4926726472855046e | emma-rose22/practice_problems | /HR_arrays1.py | 247 | 4.125 | 4 | '''You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array.'''
import numpy as np
nums = input().split()
nums = [int(i) for i in nums]
nums = np.array(nums)
nums.shape = (3, 3)
print(nums)
|
34ad6779977c33d824b00a8b63e64d72566b3165 | alexandraback/datacollection | /solutions_1674486_0/Python/rfonseca/diamond.py | 885 | 3.5625 | 4 | #!/usr/bin/env python3
import sys
def dfs(visited, classes, node):
if visited[node]:
return True
visited[node] = True
for child in classes[node]:
res = dfs(visited, classes, child)
if res:
return True
return False
def diamond(n, classes):
for i in range(n):
... |
aa0e9bf9680e5b121616348f47a67511b7cbc3fb | LailaBenz/Bioinformatik-sose18 | /assignment2/fasterfrequentwords.py | 1,691 | 3.8125 | 4 | def PatternCount(text, pattern):
result = 0
for i in range(0, len(text)-len(pattern)+1):
if (text[i:i+len(pattern)] == pattern):
result += 1
return result
def FrequentWords(text, k=4):
#Return a list of the most frequent substrings in a given text.
# import previosly writ... |
8b43a57e4785d57809eb60a3a30b8590d5981b1c | ieee-saocarlos/desafios-cs | /Esther Bastos/produtos.py | 549 | 3.65625 | 4 | leite = int(input("Número de conjuntos de leite: "))
ovo = int(input("Número de conjuntos de ovo: "))
prendedores = int(input("Número de conjuntos de prendedores: "))
sabão = int(input("Número de conjuntos de sabão: "))
iogurte = int(input("Número de conjuntos de iogurte: "))
leite = 12 * leite
ovo = 12 * ovo
prendedo... |
46f1616e0375fee9c7de88544433c5655f22f912 | mittal-umang/Analytics | /Assignment-1/MinutesToYears.py | 580 | 4.15625 | 4 | # Chapter 2 Question 7
# Write a program that prompts the user to
# enter the minutes (e.g., 1 billion), and displays the number of years and days for
# the minutes. For simplicity, assume a year has 365 days.
def main():
minutes = eval(input("Enter the number of minutes : "))
days, years = _calculate_(minute... |
8980f33232eba85fc9f3532b53aa1cd3075fc066 | andrebaboim/data-lake | /src/pipelines/cache.py | 1,613 | 3.625 | 4 | class SourceCache():
singleton = None
def __init__(self):
"""
Class constructor.
Returns:
(SourceCache): A new instance of SourceCache class.
"""
self._sources = {}
@classmethod
def instance(cls):
"""
Gets or creates the singleto... |
de93fb69a0f878335bfb70abeedf1b9ed6d23cea | JBustos22/Physics-and-Mathematical-Programs | /computational derivatives/simpson.py | 597 | 3.859375 | 4 | #! /usr/bin/env python
"""
This program uses the simpson method of approximating integrals to find
the integral of x**4-2*x+1 from 0 to 2.
Jorge Bustos
Feb 22, 2019
"""
from __future__ import division, print_function
import numpy as np
def f(x):
return x**4 - 2*x + 1
N = 1000 #max value in summation
a = 0.0
b = 2.... |
0d5212d22101ff756968732a4b5e481d39e18286 | patterson-dtaylor/python_work | /Chapter_4/animals.py | 246 | 4.21875 | 4 | # 10/1/19 Exercise 4-2: Using for loops with a list of animals.
animals = ['flying squirell', 'gold fish', 'racoon']
for animal in animals:
print(f"A {animal} would make a great pet!\n")
print("Any of these animals would make a great pet!")
|
d894857c9d0e6d217782a7cfda00e31123cc0b30 | kevinelong/AM_2015_04_06 | /Week1/pocket_change_answer.py | 530 | 3.5625 | 4 | pocket_change = {
"pennies": 13,
"nickels": 3,
"dimes": 2,
"quarters": 4
}
change_values = {
"pennies": 1,
"nickels": 5,
"dimes": 10,
"quarters": 25
}
def add_up(pocket_change):
totals = {}
grand = 0
# ... DO YOUR WORK HERE
for k in pocket_change.keys():
subtot... |
c2898bd7a8bce643f164e03c7260d937283abfa8 | yueqiusun/DS1004-Big-Data-HW | /Map-Reduce/task3/map.py | 851 | 3.734375 | 4 | #!/usr/bin/python
# map function for matrix multiply
#Input file assumed to have lines of the form "A,i,j,x", where i is the row index, j is the column index, and x is the value in row i, column j of A. Entries of A are followed by lines of the form "B,i,j,x" for the matrix B.
#It is assumed that the matrix dimensions... |
2417bafe451e0957bb17ed1930679562bf13f7c6 | ShubhAgarwal566/Maze-Solver | /driver.py | 4,243 | 3.859375 | 4 | #global libraries
import turtle
import Tkinter as tk
# user libraries
import maze_generator
import LHR
import RHR
import randomMouse
import dfs1
import dfs2
import bfs
import deadendFilling
import aStar
#driver function which helps in setting up maze and calling respective algorthim function
def... |
a5c6fe96d40c81d888fc4d5f6ba0d26b1604e3ec | xilousong/test_git | /00打招呼.py | 649 | 3.859375 | 4 | #!/usr/bin/env python3
class Name():
def __init__(self,name,age):
self.__name = name
self.__age = age
def set_name(self,new_name):
self.__name = new_name
def set_age(self,new_age):
if new_age >0 and new_age <100:
self.__age = new_age
else:
... |
42754928e6000ce6c441e53d45a412d3a7a1cd0c | rado0x54/CTFs | /picoCTF2019/100_caesar/solve.py | 315 | 3.609375 | 4 | #!/usr/bin/env python3
CIPHERTEXT = 'dspttjohuifsvcjdpoabrkttds'
# (ord(K) - ord('a')) + {1-25} % 26 = ord(C)
def move(c_char, shift):
return chr(((ord(c_char) - ord('a')) + shift) % 26 + ord('a'))
# test all solutions. only 25 makes sense
print(f"picoCTF{{{''.join([move(c, 25) for c in CIPHERTEXT])}}}")
|
3b01eeb6abd077b89deb8a7e1d2c20d46cb1c844 | kaceyabbott/intro-python | /iterations.py | 1,489 | 4 | 4 | """
when working with iterators, generators, etc
look at the documentatoin for the itertools module
"""
from itertools import islice, count, chain
from listcomprehensions import prime
import statistics
def main():
"""
test function
:return:
"""
thousandprimes = islice((x for x in count() if pri... |
4ab61f9bff0812b77f63df896c80a61612fd03e2 | droomkan/AI_ML_weekopdrachten | /week_1/a_star/model.py | 5,203 | 3.5 | 4 | import random
import heapq
import math
import config as cf
# global var
grid = [[0 for x in range(cf.SIZE)] for y in range(cf.SIZE)]
class PriorityQueue:
# to be used in the A* algorithm
# a wrapper around heapq (aka priority queue), a binary min-heap on top of a list
# in a min-heap, the keys of parent ... |
465ef0a5df387181caa40ea565b69aeb3628129f | jproddy/rosalind | /python_village/ini3.py | 623 | 3.859375 | 4 | '''
Strings and Lists
http://rosalind.info/problems/ini3/
Given: A string s of length at most 200 letters and four integers a, b, c and d.
Return: The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our sli... |
ee09f1aa120c6ab960cc2a0caaa5e74cba1bd9dd | erjan/coding_exercises | /Find Maximum Number of String Pairs.py | 1,410 | 3.75 | 4 | '''
You are given a 0-indexed array words consisting of distinct strings.
The string words[i] can be paired with the string words[j] if:
The string words[i] is equal to the reversed string of words[j].
0 <= i < j < words.length.
Return the maximum number of pairs that can be formed from the array words.
Note that ea... |
feff1b82513e75dd2b2f9d86d07003c8d5d2ba20 | GirishJoshi/interviewcake | /Greedy algorithms/apple_stock.py | 2,807 | 4.09375 | 4 | """
Writing programming interview questions hasn't made me rich yet ... so I might give up and start
trading Apple stocks all day instead.
First, I wanna know how much money I could have made yesterday if I'd been trading Apple stocks all day.
So I grabbed Apple's stock prices from yesterday and put them in a list c... |
b387c6daa15dc9ad3c696b2ff2bbe115c03472f6 | webclinic017/TFS | /tfs/utils/charts.py | 6,699 | 3.59375 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import FuncFormatter
import pdb
class Chart(object):
pass
class BulletGraph(Chart):
"""Charts a bullet graph.
For examples see: http://pbpython.com/bullet-graph.html
"""
def draw_graph(self, data=None, labels=None, ax... |
823cf9d7be1ebf0db238e037f1936fa00d6c75d3 | talhahome/codewars | /Oldi3/Buddy_Pairs.py | 1,885 | 4.1875 | 4 | # You know what divisors of a number are. The divisors of a positive integer n
# are said to be proper when you consider only the divisors other than n itself.
# In the following description, divisors will mean proper divisors.
# For example for 100 they are 1, 2, 4, 5, 10, 20, 25, and 50.
#
# Let s(n) be the sum of th... |
723f26335ada24311601004e1b8c83fa0d0d1d0e | xnth97/Data-Structure-Notes | /DataStructurePython/heap.py | 2,151 | 3.5625 | 4 | class MaxHeap:
def __init__(self):
self.heap_array = []
def insert(self, key):
new_node = self.Node(key)
self.heap_array.append(new_node)
self.__percolate_up(len(self.heap_array) - 1)
def __percolate_up(self, index: int):
# save the bottom node
bottom = se... |
d4eb0130619c7b9110f00211fe47ca8b04279def | nsq974487195/pyldpc | /pyldpc/code.py | 7,736 | 3.515625 | 4 | import numpy as np
from scipy.sparse import csr_matrix
from . import utils
def parity_check_matrix(n, d_v, d_c, seed=None):
"""
Builds a regular Parity-Check Matrix H (n, d_v, d_c) following
Callager's algorithm.
Parameters:
n: Number of columns (Same as number of coding bits)
d_v: number ... |
869b7c1209d7863c8052005f2f05488bbb17a9c1 | phibzy/InterviewQPractice | /Solutions/MinimumRemoveToMakeValidParentheses/test.py | 1,209 | 3.6875 | 4 | #!/usr/bin/python3
"""
Test Cases:
- Empty string
- All letters
- Perfectly balanced string
- Starting with closed parentheses
- Starting with open
- Input of length N, output empty string
- Length 1 string, invalid and valid
"""
import unittest
from minRem... |
ed4920e82c04dfcb5e887b58d450f8fddb2286ad | halysl/code | /python/fibolique.py | 209 | 3.65625 | 4 | def fib(n):
count = 0
num1 = 1
num2 = 1
while count < n:
result = num1
num1, num2 = num2, num1+num2
count += 1
yield result
f = fib(10)
for i in f:
print(i) |
fd888d0d51184570ed83fb5e2cb92ecd5aafef5b | zerghua/leetcode-python | /N888_FairCandySwap.py | 2,784 | 3.703125 | 4 | #
# Create by Hua on 5/12/22
#
"""
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since ... |
643141e6a3807e3a64619c94a05660f1d4cfb12a | d3athwarrior/LearningPython | /NonSequentialDataTypes.py | 1,405 | 4.625 | 5 | # Dictionaries
# Different ways to declare a dictionary
dict_way_one = {'One': 1, 'Two': 2} # This requires the key, if a string, to be put in double (double) quotes
dict_way_two = dict(One = 1, Two = 2) # This takes in the string as keyword arguments. The part before the = becomes the keys
# Printing the dict
for k, ... |
75fb58b0beb1243b6ad53f936bef8cb98b53352a | egyilmaz/mathQuestions | /questions/src/question/year6/Question113.py | 801 | 3.65625 | 4 | import random
from questions.src.question.BaseQuestion import BaseQuestion
from questions.src.question.year6.Types import Types, Complexity
class Question113(BaseQuestion):
def __init__(self):
self.type = [Types.Geometry_circle_perimeter, Types.sat_reasoning]
self.complexity = Complexity.Moderate
... |
b50cf08167a4c1484c3bd482935ad18c950beac7 | pengyuhou/git_test1 | /leetcode/234. 回文链表.py | 452 | 3.515625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
cur = head
ret = []
while cur:
ret.append(cur.val)
cur = cur.next
l =... |
dfec3abe11bdf547f4bbec1f084e6d88d8a6dbc7 | ChenQQ96/flask_study | /test12.py | 848 | 3.578125 | 4 | #知道一个函数,怎么去获得这个URL呢:通过 url_for(函数名,查询参数)
from flask import Flask,url_for,request
app = Flask(__name__)
@app.route('/',methods=['POST','GET'])
def index():
if request.method=='POST':
return 'POST'
else:
return 'GET'
@app.route('/login/')
def login():
return 'login'
@app.route('/user/<user... |
4d337df370d6ba293ff86cc71cb4f5c79ba3c4c8 | FidelNava2002/Actividades-de-python | /condiciones-02.py | 398 | 3.953125 | 4 | """3. - Escribe un programa que pida dos números y que conteste cuál es el menor y
cuál el mayor o que escriba que son iguales."""
n1=int(input("Ingresa el numero 1: "))
n2=int(input("Ingresa el numero 2: "))
if n1>n2:
print(n1, "Es el mayor y ",n2,"es el menor")
elif n1<n2:
print(n2, "Es el mayor y ",... |
7fb91c0d4c32b04dd5fc1b791b5766aae6ec09de | geniousisme/CodingInterview | /leetCode/Python/157-readNCharsGivenRead4.py | 1,380 | 3.5625 | 4 | # Time: O(n)
# Space: O(1)
#
# The API: int read4(char *buf) reads 4 characters at a time from a file.
#
# The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
#
# By using the read4 API, implement the function int read(char *buf, int n) th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.