blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0ba6890507f6bceef5d31191728f89947f309d37 | Ukwuani/data-structures-and-algorithms | /Python/chapter01/p08_zero_matrix/camilosalazar98.py | 1,602 | 3.859375 | 4 | """
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0,
its entire row and column are set to 0.
Hints:#17, #74, #702
I've been stuck on this for a couple of days..
Really good resource:
https://www.youtube.com/watch?v=ZzpJgRvqSJQ&t=113s
https://www.youtube.com/watch?v=qWeNXOCff3o&t=408s
""... |
c80dae4f3c033699c57717248c03e24034f54335 | gluoneros/python | /BasicoPhyton/22_errors.py | 312 | 3.71875 | 4 | try:
print(0 / 0)
assert 1 != 1, 'Uno no es igual que uno'
age = 10
if age < 18:
raise Exception('No se permiten menores de edad')
except ZeroDivisionError as error:
print(error)
except AssertionError as error:
print(error)
except Exception as error:
print(error)
print('Hola')
print('Hola 2') |
41ad7d0fed97d389fbf266bc77642890d4df8cf1 | iLegendJo/GClegend | /Midterm01/q10.py | 998 | 3.78125 | 4 | # read original csv file.
# filter the data to grab females and males
# Create 2 new csv files
def question_ten_test(gender):
try:
gender = gender.upper()
with open("Popular_Baby_Names.csv", 'r') as file_object:
next(file_object)
lines = [line.strip().split(",") ... |
190208ae0ee32d9cab6d79df9cc867e4a8e2867e | MaximeMoutet13/Stage_2020 | /tbs/graph/__init__.py | 1,937 | 3.5 | 4 | """Generic Graph module.
.. currentmodule:: tbs.graph
We assume that edges are subsets of `X`. In its
whole generality, one can just supposes that `E` is a set of two element
tuples. Such graph are said to be *directed*. That is if `(x, y)` is an edge,
`(y, x)` is not necessarily one. It is possible to produce dire... |
72c746207fe793430f2a8c80f55ff4ea2c5fc668 | SoheeKwak/Python | /workspace/python_study/python_gspark/day2-3.py | 4,086 | 4.3125 | 4 | print(range(5))
print(list(range(5)))
print(list(range(0,5)))
print(list(range(3,8,2)))#3~7까지 홀수만
print(list(range(8,-5,-2)))
#sorted함수:값을 정렬->결과를 리스트로 리턴
#sort함수:리턴값이 없음
print(sorted([5,3,4]))
print(sorted(['k','i','m']))
print(sorted("seoul"))
data = [5,3,4]
data = sorted(data)
print(data)
data2 = [5,3,4]
print(da... |
93206391021af227b540acbe2c53e0896dad1244 | iamedwardshen/leetcode-solutions | /python/intert_interval.py | 736 | 3.875 | 4 | #!/usr/bin/env python
__author__ = 'Rio'
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def insert(self, intervals, newInterval):
if not intervals:
return [newInterval]
intervals.append(newInterval)
intervals.sor... |
d9c76815b5612cd0fbf9938d54e03e8fcf0cc0bc | abheeacharya2019/PythonPractise | /OopsPractise/superExample.py | 571 | 3.78125 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("The name is : ", self.name)
print("The age is : ", self.age)
class Student(Person):
def __init__(self, name, age, rollno, marks):
super().__init__(name, age)
... |
c3930403acd05c2b0b5ba26f4cdfa38f6c110422 | Biddy79/eclipse_python | /Functions/Funtions_part1/__init__.py | 1,080 | 4.15625 | 4 | #define a function
def python_food():
print("Spam and eggs")
#call to function python_food
python_food()
#call function python_food.
#Using print will print functions return value which in this case is None
print(python_food())
print("-" * 30)
#function defined to print text in center of screen (if screen is 8... |
e16eaecb37b9432cd979af5802b8897ae5b67b3d | rajeshgupta88/DeepLearning | /keras_cifar10/CIFAR-10_Keras_largeCNN_rajesh.py | 5,880 | 3.578125 | 4 |
# coding: utf-8
# ### Referred from: http://machinelearningmastery.com/object-recognition-convolutional-neural-networks-keras-deep-learning-library/
# In[1]:
from keras.datasets import cifar10
from matplotlib import pyplot
from scipy.misc import toimage
# In[2]:
# load data
(X_train, y_train), (X_test, y_test) ... |
ab0a7b6f5b5c66a0c1292ceca98f5fe6894d9fad | elzlee/Maze-Generator-Solver | /hard_level.py | 20,954 | 3.5 | 4 | ##########################################
# Hard maze level
# Perfect maze generation: Prim's
# Maze Searching: Breadth First Search
# Pathfinding: parent/child connection
##########################################
# Citations referenced in this file #
# Jamis Buck: 'An Example' section only
# https://weblog.... |
9b386fadc8ef85dda4aeac268c65f9692a4acd68 | AhmetTuncel/CodeKata | /CodeKata/7_Rank/Two_to_One_Kata.py | 643 | 4.0625 | 4 | """
Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,
each taken only once - coming from s1 or s2. #Examples: ``` a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz" lo... |
5457c84133ede957f84f32fa9c41f315a9ccd039 | vaishali305/CompetitiveCoding | /guard.py | 183 | 3.59375 | 4 | import math
x_l = int(input())
y_l = int(input())
x_w = int(input())
y_w = int(input())
flt = float(input())
if (y_l+y_w)==0:
a = x_l*flt
print("{0:.6f}".format(math.floor(a))) |
ea7c6e2de6b660fcc4611b3d9d612caa781e5217 | travisreed-dfw/teamtreehouse-techdegree-python-project-01 | /league_builder.py | 2,266 | 3.9375 | 4 | import csv
# Teams are created with zero players and strings for team names
dragons = [0, 0, 'Dragons']
sharks = [0, 0, 'Sharks']
raptors = [0, 0, 'Raptors']
league_of_teams = [dragons, sharks, raptors] # Oh my!
# Define function for assigning players to teams, with an even amount of exp
def assign_player(player)... |
95e6ab0a45b8db643b895046ad061009c778dc45 | ameykaran/CSAssn1 | /Head/Greetings.py | 595 | 3.90625 | 4 | from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
def morning():
print("Hello! Good morning")
def afternoon():
print("Hello! Good afternoon")
def evening():
print("Hello! Good evening")
def night():
print("Hello! Good night")
if "00:00:00" <= current_t... |
d283571d906adf521685ee2edc2b70c4f5eb79f3 | DanielFernandoYepezVelez/Documentacion-Algoritmos | /05-AlgoritmosBasicosSecuenciales/01-CodigoPython/03-AreaTriangulo.py | 329 | 3.9375 | 4 | print(' ')
base = float(input('Ingrese El Valor De La Base Para Un Triangulo: '))
altura = float(input('Ingrese El Valor De La Altura Para Un Triangulo: '))
areaTriangulo = ((base * altura) / 2)
print('')
print('Base Triangulo: ', base)
print('Al tura Triangulo: ', altura)
print(f'Area Triangular: {areaTriangulo}')
p... |
bf920dbe380caab969d7fea0610fb73146c2b7b0 | aparecida-gui/learning-python | /exercicios/quantidadeDeDigitos.py | 473 | 4.03125 | 4 | '''
O exercicio deve contar o numero de digitos que um numero tem
'''
def number_length(a: int) -> int:
a = str(a)
return len(a)
if __name__ == '__main__':
print("Example:")
print(number_length(10))
# These "asserts" are used for self-checking and not for an auto-testing
print(number_length(10) == ... |
c775ae9538cd5b80329150c5f84bbbb5e6c15257 | yashasvi-goel/Algorithms-Open-Source | /Sorting/Bead Sort/Python/bead_sort.py | 2,021 | 3.546875 | 4 |
m = s = 1
GRAVITY = 9.81*m/s
class Bead:
def __init__(self, row, height):
self.row = row
self.height = height
self.velocity = 0
self.touching_ground = False
def fall(self):
if not self.touching_ground:
self.velocity += GRAVITY
self.height -= se... |
382a04567820ccba224bfa9301aa2b03b8c55d8f | linhnvfpt/homework | /python/w3resource/python-execises/part-I/18.py | 254 | 4.125 | 4 | # Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum
def sum(a,b,c):
if a == b == c:
return 3 * a
return a + b + c
print(sum(1,2,3))
print(sum(1,1,1)) |
f1b3504ae81f24908a99968b4d4e92c9d4e75d5d | GennaDIY0000Radchenko/Practice | /Practice_15_KM-04_Radchenko/main.py | 6,762 | 4.25 | 4 | from factorial import factorial
from exp_root import root, exponentiation
from logarithm import logarithm
def main():
while True:
choose1 = str(input('\nEXPONENTIATION -> E'
'\nFACTORIAL -> F'
'\nLOGARITHM -> L'
... |
425a6ff21970f3ec8c1a7d746d56c27b09271bbc | azunic/pyhton-tasks | /pmf_vjezba_7/zad_7_8.py | 407 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 10:51:09 2020
@author: Ana
"""
#Napišite program koji učitava riječ i
#ispisuje novu riječ dobivenu tako da se iz unesene r
#iječi izbriše svaki treći znak.
string = "majmun"
#treba izbacit svako treci znak majmun
# 123456 triba izbac... |
e0318c33ed0c3f696b99efdace61b7496cb17047 | jeffreyongley/Neural_Networks_Project | /fashion_mnist_classifier.py | 1,439 | 3.765625 | 4 | import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
data = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = data.load_data()
print(train_labels[6])
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal'... |
bd1e451f6c3965624976dd5c08352fe23d68f9a9 | jamesnatcher/Old-Python-Stuff | /CS 101/CS 101 Labs**/june 3, 2020.py | 755 | 3.75 | 4 | '''rawtext = input('Enter the text to be encoded with the Cesar cypher: ')
shift = int(input('Enter the Cesar cypher shift amount: '))
cleartext = ''
for c in rawtext:
if ((ord('A') <= ord((c)) and (ord(c)) <= ord('Z'))):
m = c
elif ((ord('a') <= ord((c)) and (ord(c)) <= ord('z'))):
m = chr(or... |
af3ddb55e4553d1b3f2674423c66e955847d0cc7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/ptrjas005/question1.py | 1,356 | 3.796875 | 4 | '''Jason Pietersen'''
def Message():
print("Welcome to UCT BBS\nMENU \n(E)nter a message \n(V)iew message \n(L)ist files \n(D)isplay file \ne(X)it \n")
x=input('Enter your selection: \n')
while x not in "Xx":
#selection
if x in'Ee':
y= input('Enter the message: \n')
... |
817d8fd3afe3a9b31aa58c8f9dc4104c4e6c2a4d | kruupos/sniwi | /sniwi/utils.py | 1,042 | 3.6875 | 4 | # -*- encoding: utf-8 -*-
"""
Utils functions needed by Sniwi class to make them more readable
"""
from operator import itemgetter
from urllib.parse import urlparse
def top_three(d):
"""
Get the three best items sorted by value in a dict
params:
d: dict or defaultdict
returns:
list o... |
3cd0d1154d9cb33d65593d0e8d3520066a8dca78 | hizkiawilliam/random-python-programs | /test2.py | 198 | 3.640625 | 4 | def negative(lst):
neg = False
for i in range(0,len(lst)):
if lst[i]<0:
return i
neg = True
break
if neg == False:
return -1
|
ff34fa05c87a9551afae9ca5974276879673e386 | AlfonsoBallesterosOrtiz/Python | /Clase 22/BuclesWhile.py | 1,410 | 4.0625 | 4 | # contador = 0
# print (" 2 elevado a " + str (contador) + " es igual a: "+ str (pow(2,contador)))
# contador = 1
# print (" 2 elevado a " + str (contador) + " es igual a: "+ str (pow(2,contador)))
# contador = 2
# print (" 2 elevado a " + str (contador) + " es igual a: "+ str (pow(2,contador)))
# contador = 3
# pri... |
d471abea6c94d8724e65144c998edd070622239f | WangZhenhai/random_idcard | /identity.py | 3,296 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version 3.0+
import random
import re
# 导入某个模块的部分类或方法
from datetime import datetime, timedelta
# 导入常量并重命名
import constant as const
class IdNumber (str):
def __init__(self, id_number):
super (IdNumber, self).__init__ ()
self.id = id_number
self.area_id = ... |
2fff91a6b6411547411798000a3f491eed0b567f | 32r143/code | /collatz.py | 461 | 4.34375 | 4 | import sys
def collatz(number):
if number %2 == 0:
result = number//2
else:
result = 3*number + 1
print(result)
return result
print("Enter an integer")
while True:
try:
userinput = int(input())
except ValueError:
print('Entered value is not an integ... |
36ebb06a5a385a610204ea64b079a63f6f4ffe36 | cubeguerrero/euler-problems | /021/solution.py | 833 | 3.546875 | 4 | from functools import reduce
def get_divisors(n):
divisors = [1]
for i in range(2, n//2+1):
if n%i == 0:
divisors.append(i)
return divisors
def get_sum(d):
return reduce(lambda total, i: total + i, d)
def solution(n):
numbers = []
for i in range(1, n):
if i in ... |
dc349350eeb46cb74beb24d05b693ca1bffc0b57 | Ankit-Sharma-1/Data-Processing-Object-Oriented-Programming | /processing.py | 13,051 | 3.671875 | 4 | """
Logical processing classes used in the second assignment for CSSE1001/7030.
ProcessResults: Abstract class that defines the logical processing interface.
AthleteResults: Provides details of one athlete’s results for all of the
events in which they competed.
CountryResults:... |
6c76908c04419b0544a260a79d7fb8b137712ea9 | saurabhgade45/Algorithmic-toolbox-coursera | /week 2/fibbonacci.py | 222 | 3.609375 | 4 | n=int(input())
def sumlastagain(n):
if n<=1:
print(n)
quit()
a = 0
b = 1
c=0
for i in range(n):
c = c + b
a,b = b,a+b
print(c)
sumlastagain(n) |
ab01c876edd66a0a3591eae6da6cc2d87d3e22a9 | Malphite12138/kyy | /TF_Mnist.py | 4,637 | 3.59375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
INPUT_NODE = 784 #输入节点的个数,也就是图片的像素,因为用的是手写数字集,所以输入节点为784
OUTPUT_NODE = 10 #输出节点个数,因为手写数字集是十个类别,所以输出节点个数是十
#配置参数
LAYER1_NODE = 500 #隐藏层节点个数
BATCH_SIZE = 100 #一个batch的大小
LEARNING_RATE_BASE = 0.8 #基础学习率
LEARNING_RATE_DECAY = 0... |
56e36efc9941f4a0c6d019e0cc64bbe6dcb323df | jinka161997/ExcelR-solution-assignments- | /ExcelR-solution-assignments-/random forest/company.py | 1,993 | 3.765625 | 4 | import pandas as pd
import numpy as np
# Reading the Diabetes Data #################
company= pd.read_csv("file:///F:/ASSIGNMENTS/random forests/company(randomforest).csv")
company.head()
## Creating dummy variables for the given categorical data in the input
## Adding the dummy to the dataset
du... |
a498022e1f455cfe17532b1b90f67fa80ee4e38f | gm332211/workspace_p3x | /day1/guess_age_for.py | 412 | 3.75 | 4 | #coding=utf-8
#Author:gm
age_of_my=22
for i in range(0,3): #判断的条件
age=input('age:')
age=int(age)
if age_of_my==age: #判断语句
print('guess ok')
break #跳出循环的语句
elif age>age_of_my:
print('think smaller..')
else:
print('think bigger...') #计数器自增
else: #while条件不成立执行
... |
1bbed7903ed04529f7097b55ee39f07042dd0ad2 | WisTiCeJEnT/tar-com-pro | /bowling.py | 362 | 3.953125 | 4 | Frame = 1
s = 0
while Frame <= 10:
pin = 10 #pin left
print("Frame # %d" % Frame)
d = int(input("Number of pins down: "))
pin -= d
if pin > 0: #strike
print("Frame # %d" % Frame)
d = int(input("Number of pins down (0-%d): " % pin))
pin -= d
s += 10-pin #Add score
... |
18524be175c74e45bd13ccf806e5a91d489bbbfb | nezihoglu/OOP-Exercises | /InvoiceItem.py | 1,127 | 3.59375 | 4 | class InvoiceItem:
def __init__(self, id, desc, qty, unitPrice):
self.id = id
self.desc = desc
self.qty = qty
self.unitPrice = unitPrice
def __str__(self):
return "InvoiceItem[" + "id= " + self.id + ", " + \
"description= " + self.desc + ", " + \
... |
4f040aee71a5b460a330a7af254a0b0b928395b6 | lukasz-f/data-camp | /importing-data/web/bs4_.py | 895 | 3.796875 | 4 | # Import packages
import requests
from bs4 import BeautifulSoup
# Parsing HTML #
# Specify url
url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response
r = requests.get(url)
# Extracts the response as html
html_doc = r.text
# Create a BeautifulSoup object from the HTML
s... |
86d7888efde2c95aac9b04db5c29f8f32a4353e8 | KPZNet/PotHolesFlask | /PotHolesFlask/PotHolesFlask/views.py | 2,025 | 3.75 | 4 | """
Routes and views for the flask application.
"""
from datetime import datetime
from flask import render_template, request
from PotHolesFlask import app
@app.route('/')
@app.route('/home')
def home():
"""Renders the home page."""
return render_template(
'index.html',
title='Home Page',
... |
c6c00d51752a685c39ed04095999b7790e2f6841 | sunyikang/skilltraining | /python/features/namedtupler.py | 1,043 | 4.1875 | 4 | """
run: python features/namedtupler.py
namedtuple instances are just as memory efficient as regular tuples because
they do not have per-instance dictionaries. Each kind of namedtuple is represented
by its own class, created by using the namedtuple() factory function.
The arguments are the name of the new class ... |
3033e0e82ea0c2542028520dc55cc0ae1a62dcd5 | sauravgupta2800/MyCodingPractice | /miscellaneous/jan1.py | 265 | 3.75 | 4 | import re
def findWholeWord(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
t=int(input())
for _ in range(t):
str=input()
if(findWholeWord('not')(str)):
print("Real Fancy")
else:
print("regularly fancy")
|
274bfa3b1cdf0abc3516d100fc39996feb932538 | hammad93/hurricane-net | /docs/data/hurdat2.py | 2,594 | 3.515625 | 4 | ''' Hammad Usmani
PURPOSE: To provide a class and API for the HURDAT2 database
METHOD: Read the text file provided by the NOAA and NHC into a pandas DataFrame and
create an API for common functions and applications.
INPUT: HURDAT2 database http://www.nhc.noaa.gov/data/#hurdat
'''
import pandas as pd
import numpy as n... |
d9413fd77e6e4b84f139c25bba4976ae6606c233 | ju-c-lopes/Logica-de-programacao | /Python/lanchonete.py | 534 | 3.671875 | 4 | codigo = int(input("Código do produto comprado: "))
qtd = int(input("Quantidade comprada: "))
preco: float
total: float
if codigo >= 1 and codigo <= 5:
if codigo == 1:
preco = 5.00
total = qtd * preco
elif codigo == 2:
preco = 3.50
total = qtd * preco
elif codigo == 3:
... |
a81a34d8de18df5ffdea8f71d7056dca200dbeb9 | craftgarrick04401/An_Adventure_Game | /InventoryClass.py | 2,789 | 3.53125 | 4 | from ItemClass import Item, Equipment
class Inventory(object):
def __init__(self, name):
self.name = name
self.inv = []
def add(self, itemAttributes, amount=1):
for i in self.inv:
if i['ItemName'] == itemAttributes['It... |
e4250986c1948cb7bf9597c283478b7169059d1d | hackutk/historical-crypto | /solutions/caesar-solver.py | 578 | 4.15625 | 4 | def caesar(msg, n):
"""Performs a caesar cipher encryption"""
lets = 'abcdefghijklmnopqrstuvwxyz'
r = ''
for c in msg:
if c.lower() not in lets:
r += c
else:
if c in lets:
r += chr(((ord(c) - ord('a') + n) % 26) + ord('a'))
else:
... |
0bc02a8b623c2e03d53ac0970edfd9149df8ba46 | branham-computer-science-19-20/iterative-prisoners-dilemma-period-2 | /team6.py | 5,273 | 3.6875 | 4 |
####
# Each team's file must define four tokens:
# team_name: a string
# strategy_name: a string
# strategy_description: a string
# move: A function that returns 'c' or 'b'
####
team_name = 'C.L.A.S.S.' # Only 10 chars displayed.
strategy_name = 'The name the team gives to this strategy'
strategy_desc... |
6b9d1352d6995ce8204e74dbbd30258f596e99e2 | jzf21/player-stats | /Player stats/program.py | 1,135 | 3.578125 | 4 | from tkinter import*
from PIL import ImageTk, Image
import os
def clicked():
from login import login2
def signup():
import signup.py
window=Tk()
window.configure(bg='black')
window.title("WELCOME")
logo=ImageTk.PhotoImage(Image.open("rose.jpg"))
img = ImageTk.PhotoImage(Image.open("signup.gi... |
4115cfdd98b2cae03295f92900128744936bb45d | smba-camera/image-processing | /image_processing/simulation/Car.py | 602 | 3.84375 | 4 | import numpy as np
#a general description of a simulated car
class Car:
#x and y are reflected as the center of the car rear axle
def __init__(self,x=0,y=0,length=5,width=2,theta=np.pi):
print("Car created")
self.x_coor = x
self.y_coor = y
self.length = length
self.widt... |
94c1d6edfa39db474e60d91aeb771f6c72a2652e | Coola4kov/algorothms | /lesson2/digits.py | 776 | 3.96875 | 4 | digits = []
even = []
not_even = []
while True:
digit = input('Введие любое целое число: ')
if digit.isdigit():
digit = int(digit)
break
else:
print('Введённые данные не являются числом!')
while digit > 0:
digits.append(digit % 10)
digit //= 10
for i in digits:
if i % ... |
fd6f5b752594acbf3c0fcdef3896e16cc160a818 | JaspinderSingh786/Python3BasicsToAdvance | /Basics/Operators/Relational.py | 159 | 4.0625 | 4 | # >,<,<=,>= are the relational operators
a = 10
b = 5
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
# We can apply for strings also
print('a'>'ab')
|
f41609300361cb716402195a00bc8d97125f83da | Nauna/Practice-Python | /a.py | 96 | 3.59375 | 4 | print("practice")
a = ["you","are", "awesome"]
for i in range(len(a)):
print(i, a[i])
|
bb4cf1aed8851fcbd22deeb2c9c86fad40c55b1b | bachp2/find_duplicate_images | /testalgo.py | 994 | 3.796875 | 4 | list1 = [1,2,6,7,8,11,12,14,15]
list2 = [0,3,4,5,9,10,13]
'''
A problem with deleting multiple items from qlistwidget using QListWidget.takeItem is that
the index of each item will change relative to the deleted position, thus making a for loop for deletion impossible.
A solution for this problem is to find the th... |
42e0b20a55c1abade85ce2611df193010bb7ea7a | dawidgdanski/python-training | /learningpython/managedattributes/subject.py | 367 | 3.578125 | 4 | class Descriptor: # Add "(object)" in 2.X
def __get__(self, instance, owner):
print(self, instance, owner, sep='\n')
class Subject: # Add "(object)" in 2.X
attr = Descriptor() # Descriptor instance is class attr
if __name__ == "__main__":
print('-' * 50)
X = Subject()
X.attr
print... |
5795555cb2e0baa8cff40b19377215e39117048b | FanNotFan/Python_momgodb | /商城/购物说明.py | 1,226 | 3.765625 | 4 | #__author__ = "Alex Li"
#date = 2016/08/22 10:31
#购物车程序
product_list=[
('Mac',9000),
('kindle',800),
('tesla',900000),
('python book',105),
('bike',2000),
]
salary = 5000
saving = input('请输入你本金:')
shopping_car=[]
if saving.isdigit():
saving = int(saving)
while True:
for i,v in enum... |
f16d5780fb2f8ed8b70f8bc0a39a6571dff28249 | tecWang/knowledges-for-cv | /剑指offer/Codes/10_下象棋_数组_模拟.py | 2,586 | 3.65625 | 4 |
#
#
# @param chessboard string字符串一维数组
# @return string字符串
#
class Solution:
def playchess(self , chessboard ):
# write code here
# 牛妹想要获胜则需要牛牛的将被杀掉,可以先找到牛牛的将再判断能否杀死
for row_index in range(len(chessboard)):
chessboard[row_index] = [x for x in chessboard[row_index].st... |
2bdc6ec93908b4c3c6867cad307460160bc8f981 | fahadshaikh09/B.Sc-Python-Practicals | /2b.py | 197 | 4.21875 | 4 | # Define a function that computes the length of a given list or string.
def main():
s = input("Input a String : ")
length = len(s)
print("Length of string '%s' is %d " % (s, length))
main() |
6d18555357c65737bbf72083906a3212cacd76d9 | yanmarques/Ciphers | /atbash.py | 1,069 | 3.875 | 4 | # -*- coding: UTF-8 -*-
import string
# Alphabet list
ALPHA = list(string.ascii_letters)
def encrypt(text):
"""Encrypt data using old atbash cipher"""
crypted = []
text = text.replace(' ', '')
for iten in text:
i = 0
while i < len(iten):
index = ALPHA.index(iten[i])
... |
7fc73f3670b976a9d3a91ff537c06d07403f11b9 | tsoy/algo | /01_variables.py | 400 | 3.890625 | 4 | # 1.1.2
def swap(a, b):
a = a + b
b = a - b
a = a - b
print(a, b)
# swap(12, 28)
# 1.1.3
# print(2**3)
# 1.1.4
def power(a, b):
s = a
z = 1
while b > 0:
# for n in range(b, 1, -1):
if 0 == b % 2:
b /= 2
s = s * s
else:
z ... |
330f6fb54e7ffbf62b90607b5b1c313990a39f6b | ellismckenzielee/codewars-python | /simple_fun_176_reverse_letter.py | 208 | 3.5 | 4 | #simple fun #176: reverse letter kata
#https://www.codewars.com/kata/58b8c94b7df3f116eb00005b
def reverse_letter(string):
return ''.join(list(map(lambda x: x if x.isalpha() else '', string))[::-1])
|
c0b26370c44ccd5c68c41b9680537b42c5eb47d1 | feizei2008/nowcoder-huawei | /073.py | 745 | 3.71875 | 4 | # 闰年和2月判断一下
def isleap(x):
return x % 4 == 0 and x % 100 != 0 or x % 400 == 0
dic = {
1: 0, 2: 31, 3: 59, 4: 90, 5: 120, 6: 151,
7: 181, 8: 212, 9: 243, 10: 273, 11: 304, 12: 334
}
month_day = {
1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31,
}
while True:
... |
2870a18824cedfde0c8543210332ca474aa499ba | alfanick/mps | /algorithms/bruteforce.py | 2,254 | 3.546875 | 4 | import sys
sys.path.append('..')
from base import *
from itertools import permutations
class Bruteforce(object):
def __init__(self, graph):
self.graph = graph
self.cycles = []
def find_cycles(self, node=0, path=[], cost=0):
path.append(node)
if len(path) > 1:
... |
900067fcc005e5dbd13877e112672fef746101b0 | Gaterny/PythonTechnical | /algorithm/选择排序 | 700 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放到序列起始位置。
# 时间复杂度:O(n^2),需要进行的比较次数为第一轮 n-1,n-2....1, 总的比较次数为 n*(n-1)/2
# 稳定性:不稳定
def select_sort(alist):
# 遍历次数
for i in range(len(alist)-1):
# 默认设置当前值为最小值
min = i
for j in range(i+1, len(alist)):
... |
698f0b6591c30fe32c40b50684d743ce707c2c2a | naveenbe66/guvi | /15.py | 186 | 3.703125 | 4 | value=input()
value=value.split()
start=int(value[0])
end=int(value[1])
temp=0
for value in range(start+1,end):
if (value % 2)==0:
if(temp!=0):
print(" ")
print(value)
temp=1
|
0423353c5cf17d447e5056eed8d7b01138d4fdfd | nsudhanva/mca-code | /Sem3/Python/assignment2/assignment_2.py | 3,753 | 4.125 | 4 | # 1. Find the largest of three numbers.
print(max(list(input('Enter three numbers: ').replace(' ', '').split(','))))
# 2. Find the smallest of three numbers.
print(min(list(input('Enter three numbers: ').replace(' ', '').split(','))))
# 3. Read the list of fruits and perform the following:
# If number of fruits are... |
f448fe1974971388f6b5ac910fa1b9e60d80e234 | veritakim/study_python | /study_python/day4/list_string.py | 1,558 | 3.5625 | 4 | # 문자열과 리스트
# 문자열 : 문자들의 나열, 리스트 : 자료형들의 나열
# 공통점이 있다
# 인덱싱이 가능하다
# 알파벳 리스트의 인덱싱
alphabets_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
print(alphabets_list[0])
print(alphabets_list[1])
# 알파벳 문자열의 인덱싱
alphabets_string = 'ABCDEFGHIJ'
print(alphabets_string[0])
print(alphabets_string[1])
# for 반복문으로도 가능
fo... |
b1d13973128f89bb059b281d7ff913c7aeec9d25 | zhangruochi/leetcode | /077/solution.py | 878 | 3.84375 | 4 | """
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
from itertools import combinations
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
return ... |
9152e2b3a057f5a8a43c70f5b9e5e85d9fef9094 | xScoopy/OOP | /app.py | 868 | 3.75 | 4 | from Map import Map
from Player import Player
from Survivor import Survivor
from Traitor import Traitor
# instantiation of map class:
example_map = Map("repair", "wolf defense", "helicopter")
# instantiation of Player object:
# disclaimer: Player object is not really meant to be instantiated, but moreso to contain th... |
f2d65487e3fec78153f8c3d5a298fb713ae5b173 | artfuss/projecteuler | /0017-Number letter counts.py | 1,005 | 3.578125 | 4 | #! /usr/bin/env python
g={}
g[0]=0
g[1]=len('one')
g[2]=len('two')
g[3]=len('three')
g[4]=len('four')
g[5]=len('five')
g[6]=len('six')
g[7]=len('seven')
g[8]=len('eight')
g[9]=len('nine')
g[10]=len('ten')
g[11]=len('eleven')
g[12]=len('twelve')
g[13]=len('thirteen')
g[14]=len('fourteen')
g[15]=len('fifteen')
g[16]=len... |
538ed8cb42ac9fd3abb7c3a7a92ba4c5ae359908 | uchihanuo/helloworld | /Program/F2C_conversion.py | 390 | 3.828125 | 4 | # coding = utf-8
temp_str = input('Please enter the temperature with the unit.')
if temp_str[-1] in ['F', 'f']:
temp_con = (eval(temp_str[0:-1]) - 32) / 1.8
print('The temperature is {:.2f} C.'.format(temp_con))
elif temp_str[-1] in ['C', 'c']:
temp_con = eval(temp_str[0:-1]) * 1.8 + 32
print('The tempe... |
b416fd87ea770b0c9c7948c4ef0dde66c0ac0f95 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/79555d512d144ad5886d0f700c76cc3a.py | 512 | 4.03125 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
def hey(what):
#strip all leading and trailing whitespace
what = what.strip()
# check if string is empty
if not what:
return 'Fine. Be that way!'
# check if all letter are uppercase and if there are any letters
if what == what.upper() an... |
85d1c081e7ac65de5a02dd6001076a1254b673a0 | trinahaque/Python_OOP | /animal.py | 533 | 3.640625 | 4 | import random
class Animal(object):
# def __init__(self, name, health=100):
def __init__(self, name, health):
#health = 100 or self.health = 100 ==> better method
self.name = name
self.health = health
def walk(self):
self.health = self.health + 1
return self
def... |
f440bd9b4ad4cf2599c847729cbeca5d62074d88 | leinefran/AirBnB_clone_v2 | /web_flask/4-number_route.py | 948 | 3.5 | 4 | #!/usr/bin/python3
''' Flask Module'''
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def hello():
''' return welcoming str '''
return 'Hello, HBNB!'
@app.route('/hbnb', strict_slashes=False)
def display_HBNB():
''' returns HBNB '''
return 'HBNB'
@app.route... |
1abda17f93d3ed4330fff4bde60179cd956f3c5b | psychopurp/ML-Course | /线性回归分类器/regression_model.py | 3,225 | 3.59375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
class LinearRegression:
def __init__(self, learn_rate):
self.learn_rate = learn_rate
def load_data(self, file_name):
'''加载数据'''
data = pd.read_csv(file_name)
array = np.array(data.values.astype(f... |
23499d7f876ffe2304c4b3813fab5b3344efa70b | jacekkubacki/projectEulerInPython | /euler029.py | 658 | 3.953125 | 4 | #!/usr/bin/env python3
# Distinct powers
# Problem 29
#
# Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5:
#
# 2^2=4, 2^3=8, 2^4=16, 2^5=32
# 3^2=9, 3^3=27, 3^4=81, 3^5=243
# 4^2=16, 4^3=64, 4^4=256, 4^5=1024
# 5^2=25, 5^3=125, 5^4=625, 5^5=3125
# If they are then placed in numerical or... |
245f10aac0abe8d84b7914a6a42a75981c12a9f2 | sounitha12/Testing | /HelloWorld/if.py | 1,159 | 4.25 | 4 | # # hot_day1 = "It's a hot day"
# # hot_day2 = 'Drink plenty of water'
# # cold_day1 = "It's a cold day"
# # cold_day2 = 'wear warm cloths'
# # otherwise = "It's a lovely day"
# #
# # is_hot = False
# # is_cold = True
# # if is_hot:
# # print(hot_day2)
# # elif is_cold:
# # print(cold_day2)
# # else:
# # pr... |
909090f79dc0c9a1f0aed38bcf3296f1fd05a94e | wlsgp012/code-kata | /kata-python/algorithms/hanoi/simple.py | 475 | 4.03125 | 4 | import time
def hanoi2(n, frm=1, to=3, empty=2):
if n == 1:
print(f'{frm}>>{to}')
else:
hanoi2(n - 1, frm, empty, to)
print(f'{frm}>>{to}')
hanoi2(n - 1, empty, to, frm)
def hanoi(n, frm=1, to=3, empty=2):
if n > 0:
hanoi(n - 1, frm, empty, to)
print(f'dis... |
31199020d4028c3a1d3de3617fc0ca08b185e9b9 | ding1995/Leetcode | /342.py | 417 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 15 07:48:54 2017
@author: dell
"""
def isPowerOfFour(num):
if num==0:
return False
while(num):
if num==1:
return True
if not num%4:
num=num/4
else:
return False
def isPowerOfFour2(num):
... |
0956a82e24fd2a2e9f1c9b87ca3a517c7848d62b | imgourav/codigosProgramacion | /Python/Varios/IfAnidados.py | 450 | 4 | 4 | # Indicar al usuario que ingrese una palabra
# y asignarlo a la variable userWord.
print("Ingrese una palabra:")
userWord = (input()).upper()
for letra in userWord:
# Completa el cuerpo del ciclo for.
if(letra=='A'):
continue
elif (letra=='E'):
continue
elif (letra=='I'):
... |
4ea16c9dfbea9feb412fd6b5e67949b369a9aa07 | wangfucai/python-demo | /urllib/parse.py | 1,000 | 3.59375 | 4 | from urllib.parse import urlparse
from urllib.parse import urljoin
from urllib.parse import urlencode
#urlparse对传入的url地址进行拆分
result = urlparse("www.baidu.com/index.html;user?id=5#comment", scheme="https")
print(result)
#urlunpars用于拼接
#urljoin拼接
print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(url... |
2b86d917aa40f9c418198cb4ff6602bd54df6114 | croyen/pydeco | /examples/example_class_decoration.py | 2,375 | 3.734375 | 4 | """
==============================================================================
Example: decorating specified methods of a custom class with custom decorators
==============================================================================
This example shows how to decorate methods of a custom class with custom
decor... |
34ad891978cd4825910b71414a2518a9a1171fb0 | djangogirl-crypto/Hello-world | /matrix.py | 2,129 | 3.828125 | 4 | import sys
# Function to find the maximum sum `k × k` submatrix
def findMaxSumSubMatrix(mat, k):
# `M × N` matrix
(M, N) = (len(mat), len(mat[0]))
# preprocess the input matrix such that `sum[i][j]` stores
# sum of elements in the matrix from `(0, 0)` to `(i, j)`
sum = [[0 for x in rang... |
c90383c0cbf44fa216d4638138b43af14a5905a5 | dizhaung/Elusive | /log_generator/generators/generator.py | 798 | 3.53125 | 4 | import threading
import sys
import time
class LogGenerator:
def __init__(self, sleep = 1):
self.generators = []
self.sleep = sleep
def add_generator(self, generator):
self.generators.append(generator)
def generate(self):
while True:
time.sleep(self.sleep)
... |
a4a96fff970e95900cffe22d57b73ca0aaebe7e5 | sumanes4u/Anaconda-Projects | /vehicle reservation/TowersHanoi.py | 6,949 | 4.09375 | 4 | # Towers of Hanoi Program
from turtle import *
import time
def getNumDisks():
"""Returns number of disks requested by user."""
num_disks = int(input('Enter the number of disks(2-8): '))
while num_disks < 2 or num_disks > 8:
print ('Must select between 2 and 8 disks')
num_disks = int(inp... |
5f00b59b2c4069867f19e5d8d73370ec4c6dc606 | arund22/Python_Learning | /src/Class_Employee.py | 501 | 3.71875 | 4 | class Employee:
def __init__(self,first_name,last_name,pay):
self.first_name=first_name
self.last_name=last_name
self.pay=pay
self.email=first_name + '.' + last_name + '@company.com'
def fullname(self):
print('{} {}'.format(self.first_name,self.last_name))
def appl... |
98116fb4c8e31907e74087c7c16f9ddc42cae10a | hwakabh/codewars | /Python/6/TwoSum/two_sum.py | 552 | 3.859375 | 4 | import sys
def two_sum(numbers, target):
for i, n in enumerate(numbers):
for j in range(len(numbers)):
if j == 0:
pass
else:
if n + numbers[j] == target:
return [i, j]
if __name__ == "__main__":
if len(sys.argv) == 1:
... |
5f132865338a6ae6cbb5d9c4b2b797040b3387bd | v97/python-file-explorer | /db.py | 653 | 3.78125 | 4 | conn = sqlite3.connect('users.db')
c = conn.cursor()
#uses built-in hashlib library to generate hash for password for storage in database
def make_pw_hash(password):
return str(hashlib.sha256(str.encode(password)).hexdigest())
# Create table
try:
c.execute('''CREATE TABLE users
(username text, password text,... |
a6752559ae20e011823747d1b68b989ef0200f1c | Aasthaengg/IBMdataset | /Python_codes/p03543/s630994247.py | 84 | 3.65625 | 4 | s=input()
if len(set(s[:-1]))==1 or len(set(s[1:]))==1:print("Yes")
else:print("No") |
45c0457c3fb75c21fb57c606816b7a96aa795e92 | Dadinel/Alura_python-collections-listas-e-tuplas | /src/tupla01.py | 728 | 3.625 | 4 | class ContaCorrente:
def __init__(self, codigo):
self.codigo = codigo
self.saldo = 0
def deposita(self, valor):
self.saldo += valor
def __str__(self):
return "[>>Codigo {} Saldo {}]<<".format(self.codigo, self.saldo)
conta_do_gui = ContaCorrente(15)
print(conta_do_gui)
co... |
2c4fd4e44c0b0e09ebf171f64fc470150d4659a3 | trentm/dotfiles | /home/bin/tRentify | 1,005 | 3.609375 | 4 | #!/usr/bin/env python
"""tRentify!"""
import re
import sys
import os
import random
FREQ = 0.6
def tRentifyWord(match):
word = match.group(0)
if word.upper() == word:
pass
elif word.startswith('T') or random.random() < FREQ:
#print "tRentifyWord: %r" % (match.group(0),)
if random... |
a15e8e748ad823cfd34a643061a78c871798be42 | raiela/CodigosCC | /Estrutura de Dados/Filas/fila_encadeada.py | 791 | 3.5 | 4 | class Celula:
def __init__(self, valor):
self.valor = valor
self.prox = None
class Fila:
def __init__(self):
self.ini = None
self.fim = None
def vazia(self):
return self.ini == None
def enfileirar(self, valor):
item = Celula(valor)
if self.vazia... |
d28c087c4f08ff852d10701cff557264f1316eff | asherkobin/Data-Structures | /binary_search_tree/binary_search_tree.py | 4,422 | 4.21875 | 4 | """
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for... |
c32de70c4c99e5d696ba514dea028bb73b8f377c | dojorio/dojo-centro | /2011/20110720 - contaletras - python/main.py | 3,030 | 3.78125 | 4 | from unittest import TestCase, main
def contaLetrasEmUmNumero(numero):
mapa = {
1:len("um"),
2:len("dois"),
3:len("tres"),
4:len("quatro"),
5:len("cinco"),
6:len("seis"),
7:len("sete"),
8:len("oito"),
9:len("nove"),
10:le... |
c2031dd95d42d97d13c61dd0d46206fd9accf78d | max180643/Pre-Programming-61 | /Online/Week-4/Geometric Sequence.py | 250 | 3.78125 | 4 | """Geometric Sequence"""
def main():
"""Main Function"""
frist = float(input())
amount = int(input())
joint = float(input())
for _ in range(amount):
print("%.2f"%(frist), end=" ")
frist *= joint
main()
|
5c231e9560649d898477d4765fe2d995ce3235a7 | olgarozhdestvina/pands-project | /analysis.py | 11,031 | 3.609375 | 4 | # Olga Rozhdestvina
# This program is a part of the project on Fisher's Iris Data Set
# It outputs a summary of each variable to a single text file,
# saves a histogram of each variable to png files,
# outputs a scatter plot of each pair of variables to png files
# importing libraries
import pandas as pd ... |
0a655931d599b4df5a5aaa8e840c4c6b123a8da7 | HenriFeinaj/Simple_Python_Programs | /Fibonacci_Sequence.py | 514 | 4.46875 | 4 | #Fibonacci Program.
#=================================================
#Function.
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
#=================================================
#Input of a number.
n = float(input("Enter... |
e2e14e2be106f3461775733c78ae0d150b5d8d61 | MohamedGassem/ai_for_tetris | /src/tetris/base/GameParameters.py | 4,279 | 3.703125 | 4 | class GameParameters:
"""
Data class holding all game parameters
Supported parameters are :
board_size: two int tuple
The size of the board
pieces: array of src.tetris.base.Piece
The pieces for the game to use
seed: int
... |
9b9be202c86ed6e90b8b0b5e7cbe2047500c4b92 | miroslavio/Python_Euler | /sieve.py | 778 | 4.03125 | 4 | def sieve(n):
"""Generate list of prime numbers up to n."""
# is_prime[i] = 1 means i is prime
is_prime = [1]*n
# 0 and 1 are composites
is_prime[0] = 0
is_prime[1] = 0
# Cross out all composites from 2 to sqrt(n)
i = 2
# Loop from 2 to int(sqrt(n))
while i*i <= n:
... |
559cbaa747a3e0b3b5d81fb17a9d06e5228dd915 | sjzyjc/lintcode | /239/239-mono-queue.py | 726 | 3.5 | 4 | from collections import deque
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums or k <= 0:
return []
queue = deque([])
ans = []
for index i... |
30c100224896e28d0ca2525125a87486dd4801ec | JialiangHan/Principle-of-Robot-Motion | /Grid-based Algorithm/D-star.py | 5,966 | 3.859375 | 4 | import math
import os
import time
import pygame
pygame.init()
# trying to reproduce example in principle of robot motion, appendix H, H.3 D* algorithm
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.h = float('inf')
self.k = 0
self.t = 'new'
self... |
0def418cbd926f0674dbe4c734f446a56889e219 | yuchench/sc101-projects | /stanCode_Projects/class_review/class_reviews.py | 2,531 | 4.3125 | 4 | """
File: class_reviews.py
Name: Jennifer Chueh
-------------------------------
At the beginning of this program, the user is asked to input
the class name (either SC001 or SC101).
Attention: your program should be case-insensitive.
If the user input -1 for class name, your program would output
the maximum, minimum, an... |
a24667cef3edd2a692556eb1c4d68c4a3db9947a | dremerten/linux_notes | /RHCSA_NOTES/test.py | 133 | 4.34375 | 4 | #!/usr/bin/env python3
def reverse_evens():
list = [0, 1, 2, 3, 4, 5]
for i in list:
print(list)
reverse_evens()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.