blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
cf80ba60673c0dfd46555625f4abad97df402e30 | gbaweja/consultadd_assignments | /assignment1/A1-4.py | 224 | 4.03125 | 4 | # Govinda Baweja
# Assignment 1
# Date: 04-26-2019
x = int(raw_input("Please Enter a Number Value and not a Float: "))
if (x %2 == 0) & (x%5 ==0):
print "Hurray it is what I am looking for"
else:
print "wrong input"
|
dfb6d90f75f7c2fbe370185856549fdf6c089927 | gbaweja/consultadd_assignments | /assignment1/A1-6.py | 654 | 4.1875 | 4 | # Govinda Baweja
# Assignment 1
# Date: 04-26-2019
# Nested if else statement
i = 10
if (i == 10):
# First if statement
print ("\ni is 10")
if (i < 15):
print ("\ni is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
... |
6a707354b0f0697c3a740bcb9dc97ce4aeaef45c | ZhbitEric/PythonLearning | /Python_work/_40address_book.py | 1,850 | 4.03125 | 4 | # -- coding: utf-8 --
# 需求:做一个通讯录,人的姓名、电话、地址,支持增删改
import os
import pickle
class address_book:
def __init__(self, name, phone, address):
self.name = name
self.phone = phone
self.address = address
def getDetail(self):
return self.name + ',' + self.phone + ',' + self.address
... |
4182316191f1b325cb7640dd77c1acc023045c82 | ZhbitEric/PythonLearning | /Python_work/_20ds_reference.py | 310 | 4.1875 | 4 | # 引用
shopList = ['apple', 'mango', 'carrot', 'banana']
myList = shopList
del shopList[0]
print(shopList)
print(myList)
# 这样的引用就没有指向同一个对象了
myList = shopList[:] # 切片操作,相当于循环复制拿元素出来
print(myList)
del myList[0]
print(shopList)
print(myList)
|
2c9e28f2ba948e0b4c4ff61eb80015392dc95536 | MorenoIsChino/justForFunny_Python | /ToolsForRenameVedioFiles/_change_add_.py | 858 | 3.90625 | 4 | import os
import string
# 获取文件夹绝对路径
current_dir = os.path.abspath(os.path.dirname(__file__))
print(current_dir)
fileName = ""
#对目录下的文件进行遍历
for file in os.listdir(current_dir):
# 判断是否是文件
if os.path.isfile(os.path.join(current_dir, file))==True:
# print(file)
fileName = file
... |
51a5abe38e875b65e0a0329d692857992b742842 | sxb42660/MachineLearning_Fall2019 | /LAB_EXAM_QUESTIONS/Solutions/airline_systems/ticket.py | 787 | 3.828125 | 4 | class Ticket:
def __init__(self, passenger, employee, flight):
self.passenger = passenger
self.employee = employee
self.flight = flight
def print_travel_iternary(self):
print("Hello {0}, your ticket from {1} to {2} has been confirmed, \nPlease find internary details below".forma... |
03dd93bf261e4fa3e1d0dcfda020833e5a00afb2 | sxb42660/MachineLearning_Fall2019 | /LAB_EXAM_QUESTIONS/Solutions/airline_systems/airline_main.py | 1,967 | 3.90625 | 4 | """
Problem 3 :
Airline Booking Reservation System (e.g. classes Flight, Person, Employee, Passenger etc.)
"""
import json
from airline_systems.passenger import ask_passenger_info
from airline_systems.object_handler import handle_objects
from airline_systems.employee import Employee
with open('config.j... |
d4288f47754e680948464e33473535bc637a6584 | GerardoASP/Actividades_Corte-2-TAD-I-Gerardo | /Parcial2Gerardo/lista_circular_s.py | 1,746 | 3.859375 | 4 | import math
class Circular_Liked_List:
class Nodo:
#metodo constructor de la clase Nodo
def __init__(self,value):
self.value = value
self.next_node = None
def __init__(self):
self.head = None
self.tail = None
self.length = 0
#Metodos de la clase Circular_Liked_List
#Metodo... |
cd88ba99282d9880ba0c628a439ad8b0e9ad9854 | thisismsp78/PythonCodsLearn | /p14/PackDemo/PackDemo.py | 216 | 3.640625 | 4 | import tkinter
form=tkinter.Tk()
#label=tkinter.Label(text="test").pack()
#label=tkinter.Label(text="test").grid(row=0,column=0)
label=tkinter.Label(text="test")
label.pack()
print(label)
form.mainloop()
|
414b0e36fa488c2a51cc2482d8afb8fb47fa8464 | thisismsp78/PythonCodsLearn | /p5/PhoneBookDemo/PhoneBookDemo.py | 1,371 | 3.734375 | 4 | rows=[]
family=""
name=""
phone=""
while True:
print("1-New")
print("2-Search")
print("3-Print")
print("4-Filter")
print("5-Exit")
select=int(input("Select : "))
if select==1:
family=input("Enter family : ")
name=input("Enter name : ")
phone=input("Enter... |
e0873220bb5430803abed07d1bece3d5c6990cd3 | thisismsp78/PythonCodsLearn | /p2/MaxMinDemo/MaxMinDemo.py | 195 | 4.09375 | 4 | numbers=[2,7,8,3,9,4,15,6]
min=0
max=numbers[0]
for number in numbers:
if number<min:
min=number
if number>max:
max=number
print("Min : ",min)
print("Max : ",max) |
6e56478cb9703d08e667ba2d538b1429352accc1 | thisismsp78/PythonCodsLearn | /p18/ClassDemo/ClassDemo.py | 295 | 3.71875 | 4 | from Person import Person
from AgeException import *
try:
age=int(input("Enter age : "))
family=input("Enter family : ")
name=input("Enter name : ")
person=Person(age,family,name)
except AgeException as ex1:
print(ex1)
except Exception as ex:
print("Error !") |
bcb4bcbf0022f236f511f4b089acec630c3ee3df | thisismsp78/PythonCodsLearn | /p3/NestedLoopsDemo/NestedLoopsDemo.py | 248 | 3.875 | 4 | min=int(input("Min : "))
max=int(input("Max : "))
#result=[x*y for x in range(min,max) for y in range(min,max)]
result=[f"{x} * {y} = {x*y}" for x in range(min,max) for y in range(min,max)]
#print(result)
for data in result:
print(data)
|
c49beb80fcf1011aeb42556be5ecfbf3458e0813 | thisismsp78/PythonCodsLearn | /p2/ComplexDemo/ComplexDemo.py | 176 | 4.0625 | 4 | number=int(input("Enter number : "))
half=number//2
result="Prime"
while half>1:
if number%half==0:
result="Complex"
break
half-=1
print(result) |
2f95f3150f969cdbc9c4ae044d091ee1400cf234 | thisismsp78/PythonCodsLearn | /p1/BinaryDemo/BinaryDemo.py | 119 | 4 | 4 | number=int(input("Enter number : "))
bin=""
while number>0:
bin=f"{number%2}{bin}"
number//=2
print(bin)
|
6a178cf163df0fa5e59cd39318538b49dab0a22e | thisismsp78/PythonCodsLearn | /p1/RangeDemo/RangeDemo.py | 210 | 4 | 4 | number=int(input("Enter number : "))
if number>100 or number<0:
print("Invalid !")
elif number>75:
print("A")
elif number>50:
print("B")
elif number>25:
print("C")
else:
print("D") |
9821766ec0a665311639f5cfab4107ae44ea1c75 | thisismsp78/PythonCodsLearn | /p7/InitDemo/InitDemo.py | 470 | 4 | 4 | class Person:
family=""
name=""
def __repr__(self):
return f"{self.family}-{self.name}"
def __init__(self,family="",name=""):
self.family=family
self.name=name
#def __init__(self):
# self.family=""
# self.name=""
people=[Person("ramezani","sha... |
6369e755132e11ba167c0242aec020d70bf81bb4 | thisismsp78/PythonCodsLearn | /p2/NewRangeDemo/NewRangeDemo.py | 232 | 4.03125 | 4 | from random import randint
numbers=[]
length=int(input("Enter length : "))
min=int(input("Enter min : "))
max=int(input("Enter max : "))
for i in range(0,length):
numbers.append(randint(min,max))
print(numbers[i])
|
ad3d13f6419359a43c7757d30d052f3dc31b47ea | thisismsp78/PythonCodsLearn | /p3/RangeDemo/RangeDemo.py | 74 | 3.734375 | 4 | #for x in range(10):
# print(x)
for x in range(1,6):
print(x*-1) |
29e8df7682661fe9c4ae5e1d073e1d48f526be91 | thisismsp78/PythonCodsLearn | /p14/GridDemo/GridDemo.py | 307 | 3.53125 | 4 | import tkinter
form=tkinter.Tk()
tkinter.Label(text="First : ").grid(row=0,column=0,sticky="W")
tkinter.Label(text="Second : ").grid(row=1,column=0)
tkinter.Entry().grid(row=0,column=1)
tkinter.Entry().grid(row=1,column=1)
tkinter.Button(text="+").grid(row=2,column=1,sticky="WE")
form.mainloop()
|
71874a5224eea304ba34229c2afea8c9e38f45d4 | Talha-Ahmed-1/Frog-Puzzle-Problem | /FrogPuzzle.py | 2,238 | 3.671875 | 4 | class FrogPuzzle(object):
def __init__(self, initial, goal):
self.initial = initial
self.goal = goal
self.count = 0
def hopR(self):
if self.initial == self.goal:
print(f"Goal state achived with {self.count} moves.")
else:
index = self.initial.inde... |
351af5f5f6fbcfffc3d49857c950a982d091cd63 | MarcYin/atmo_cor | /python/create_training_set.py | 1,353 | 3.765625 | 4 | import scipy.stats as stats
from lhd import lhd
def create_training_set ( parameters, minvals, maxvals, n_train=200 ):
"""Creates a traning set for a set of parameters specified by
``parameters`` (not actually used, but useful for debugging
maybe). Parameters are assumed to be uniformly distributed
bet... |
73d37bf82e89c293e0e0fd86e99d74ec79b3b275 | SRAH95/Rodrigo | /input_statement.py | 1,748 | 4.15625 | 4 | """message = input("Tell me something, and I will repeat it back to you: ")
print(message)"""
########################################################################################
'''name = input("Please enter your name: ")
print("Hi, " + name.title() + "!")'''
####################################################... |
8a120aef3f52d7c41b8acdffd4cb5818b51f70db | prashusat/Bayesian-Linear-Regression | /task2.py | 4,728 | 3.796875 | 4 | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
#fucntion to read data in pandas dataframe
def read_data(data_file,regression_values_file):
df_data=pd.read_csv(data_file, sep=',',header=None)
df_regression_values=pd.read_csv(regression_values_file, sep=',',header=None)
return ... |
ef29e7f62517a2224ba5749fb3a7ee5a56ca3157 | AndyMcB/CloudRAID | /raid/RAIDStorage.py | 821 | 3.625 | 4 | from abc import abstractmethod
class RAIDStorage:
def __init__(self, storage_id, capacity=0 ):
self.storage_id = storage_id
self.capacity = capacity
self.data = []
def __repr__(self): ##ToDo - fix descriptor
return repr(self.storage_id) + ":" + repr(self.data)
def __len... |
cbd7a99244ab9c7db021420a22081d7f90b0d675 | codewithgsp/hyperskill-coffee-machine | /Problems/Magic methods/single_object.py | 214 | 3.625 | 4 | class Sun:
n = 0
def __new__(cls):
if cls.n == 0:
instance = object.__new__(cls)
cls.n += 1
return instance
sun1 = Sun()
sun2 = Sun()
print(sun1)
print(sun2)
|
6cc95de145539a9172bf2a511262afc229b9b5ba | Jose-Pedro-Da-Paz/Meu-codigo-Python | /ConvertDoll.py | 142 | 3.53125 | 4 | reais = float(input('quantos reais vc tem? '))
dolars = reais / 3.27
print('com R${:.2f} você pode comprar US${:.2f}'.format(reais,dolars)) |
24961c81a561f9018abe75106835199cc4197ae7 | Lmanti/proyectowhalejaguar | /wjproject/CreditCardValidator/luhn.py | 939 | 3.671875 | 4 | from functools import reduce
# El agoritmo de Luhn toma la string, la invierte y la recorre de 2 en 2 de derecha a izquierda, multiplicando por 2 cada target donde se ubique
# Luego de multiplicar, si el producto es un número de 2 digitos lo separa en unidades y suma esas unidades, el resultado reemplaza al valor que ... |
759109c56aa09fd818a7a35e97cbe22f5ea5d296 | iluvjava/Math-381 | /Project1/resultsInterpretor.py | 2,280 | 3.90625 | 4 | """
Name: Group 4
Class: Math 381
This file contains codes that read the results output from the lp_generate.
Given the file name in the source codes, it will read the file and get the result,
then it will print it out and tell the user what the solution is.
"""
from lp_generate import *
import os.path as p
# Macro ... |
29ac981a73df465308a69d7824bf73f417206fd5 | panchupichu/CodecademyPractice_Python | /ShippingCostCalculator.py | 1,799 | 4 | 4 | """ Shipping Cost Calculator
Exercise: List/Dictionary/Control Flow
"""
#Create a dictionary for price list
prices = {
"ground" : [20.00, 1.50, 3.00, 4.00, 4.75],
"drone" : [0.00, 4.50, 9.00, 12.00, 14.25],
"premium" : 125.00
}
#Calculate cost for Ground Shipping
def cost_ground(weight):
flat =... |
1f96359d2987d3744ca459e787ecbc77cf592031 | ak-abhishek/algorithms-in-python | /math/fibonacci.py | 505 | 4.0625 | 4 | class Fibonacci:
def __init__(self, number):
self.d = {0: 1, 1: 1, 2: 2}
self.n = number
if self.n > 2:
for i in range(3, self.n):
self.d[i] = self.d[i - 1] + self.d[i - 2]
def fibonacci_nth_number(self):
return self.d[self.n - 1]
def sum_of_fibo... |
33d5f09600f0534f582878528d0941b6a633de32 | ak-abhishek/algorithms-in-python | /design-patterns/mvc.py | 1,253 | 3.53125 | 4 | #!/usr/bin/python
class Model(object):
def __init__(self, name, roll_no):
self.set_name(name)
self.set_roll_no(roll_no)
def get_roll_no(self):
return self.roll_no
def set_roll_no(self, roll_no):
self.roll_no = roll_no
def get_name(self):
return self.name
... |
d7bd4393f578df4b437b601609344c74af6e3613 | hassanhamade/mypythoncode | /display_exercice.py | 252 | 3.515625 | 4 | days=["A", "B", "C", "D", "E", "F", "G"]
months=["HI", "JK", "LM", "NO", "PQ", "RS", "TU"]
for d in days:
print ("{0:4s}".format(d.rjust(2)), end="")
print("")
for m in months:
print ("{0:4s}".format(m), end="")
print("")
|
bb6cbff619d18e22f7367636c4b3df3797101bc8 | hassanhamade/mypythoncode | /reading_files_BackAndForth.py | 550 | 3.671875 | 4 | import datetime
import os
import random
#create a text file and write out a bunch of lines.
f=open("MyTextFile2.txt","w")
for i in range(0,1000):
f.write("This is line {}".format(i))
f.close()
print("Wrote the file to {}".format(os.getcwd()))
#Now, re-open the file for read access.
f=open("MyTextFile2.txt","r")
... |
720295a308d66733935fbb4582c9381fc277733b | hassanhamade/mypythoncode | /Modules_and_Packages/stringfunc2.py | 115 | 3.5 | 4 | def func1(stor):
s=""
for c in range(len(stor)-1,-1,-1):
s=s+stor[c]
return s
maximumlength=10
|
194b9045d1e40b9fc3066bee7b80d52549e89a6c | hassanhamade/mypythoncode | /birthday.py | 1,282 | 3.921875 | 4 | import datetime
import time
#declaration de ma date de naissance
mybirthday=datetime.date(2009,3,6)
#creation de la variable year que l'on va incrémenter à partir de mon année de naissance.
#On fait cela car la fonction native pour incrémenter des dates, timedelta, n'accepte pas des incréments en années.
year=2009
#on ... |
6ba360475505bafdc4ec18b75bdd0ad1a499e49c | hassanhamade/mypythoncode | /account_balance.py | 884 | 4 | 4 | account=int(input("Enter the current balance:"))
#if the account is negative, apply a 10 dollars fee
if account<0:
account=account-10
print("checked first if statement")
#if the account is zero, apply a 5 dollars fee
elif account==0:
account=account-5
print("checked second if statement")
#if the accou... |
7f1d4bd628eb850dfdcaff9015607dc94552fa82 | pradg73/assign | /misc/wordexpansion.py | 704 | 3.640625 | 4 | def isInt(s):
try:
int(s)
return True
except ValueError:
return False
def ex(e):
print "e ",e
r = ""
i = 0
N = len(e)
while i < N:
if isInt(e[i]):
m = int(e[i])
i = i+1
assert(e[i]=='[')
c = 1
j = i ... |
03a5125c0fcacb67d435a4c37ac714fd8666e951 | Crepusculo/LeetCode | /LeetCode/020_Valid_Parentheses.py | 1,550 | 3.78125 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for letter in s:
# letter = copy.deepcopy(copys)
if letter == "(" or letter == '{' or letter == "[":
stack.append(letter)
el... |
04ed519d7e122afd39730325cb7052d3fa389b03 | Abnormally/SHpp | /CS50/pset06/caesar.py | 1,005 | 3.90625 | 4 | #!/usr/bin/env python3
import sys
def quit(reason):
if reason == 1:
print('Usage: ./caesar n\nWhere n is non-negative value.')
elif reason == 2:
print('Wrong value!')
sys.exit(reason)
big = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S... |
3a04b50054ecb4c1da15e0800c481ecc05f52b10 | kibazhang/Computer_and_Network_Security | /Prime Numbers/Zhang_prime.py | 1,231 | 4.0625 | 4 | #!/usr/bin/env python
### Author: Zaiwei Zhang
### This is for finding all the prime numbers before input n.
import sys
if len(sys.argv) != 2:
sys.stderr.write("Usage: %s <integer>\n" % sys.argv[0])
sys.exit(1)
n = i... |
ba982e9794b3cbaaa034584cbb1f2017068f5ce5 | Pranalihalageri/Python_Eduyear | /day5.py | 516 | 4.125 | 4 | 1.
list1 = [5, 20, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Even numbers in the list: ", even_count)
print("Odd numbers in the lis... |
d34f6c2c28cc87074c8f87a4a31a4d68c9a8dcb7 | omikun/HexDSL | /python/orbitaldom/economy.py | 8,997 | 4 | 4 | 'models a rough economy'
import yaml
import math
from market import Market, Trade
range = xrange
# basic system of industries being producer/consumers
class Value:
'tracks market price and quantity?'
'''
market is a dumping ground of all outputs, combined,
if each industry sells to ... |
756f4eaee8fd322751fed49fe8075ddc042bc801 | JacksonJ01/LinkedQueue | /LinkedListTail.py | 3,176 | 3.90625 | 4 | class Data:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedListTail:
def __init__(self):
self.head = None
self.tail = None
def add_head(self, data):
new_node = Data(data)
if self.head is None:
self.head = new_node
... |
258d4ea28ffe6b9a85b2ecd34a34214ccb3a0682 | FredericoVieira/listas-python-para-zumbis | /Lista 02/lista2ex5.py | 433 | 4.15625 | 4 | # -*- coding: utf-8 -*-
num1 = int(raw_input('Digite o valor do primeiro inteiro: '))
num2 = int(raw_input('Digite o valor do segundo inteiro: '))
num3 = int(raw_input('Digite o valor do terceiro inteiro: '))
list = [num1, num2, num3]
num_max = max(list)
num_min = min(list)
print('O maior número entre %d, %d, %d é %... |
8df16a09422756e3adef67ad6c8725f9d2d38c2f | naren6195/pythonProject | /venv/Teusuko3.py | 702 | 3.53125 | 4 | class Student:
company="Wells Fargo"
def __init__(self,name,age,cell):
self.name=name
self.age=age
self.cell=cell
self.b1= self.b()
@classmethod
def class_meth(cls):
print("Class Method",Student.company)
@staticmethod
def info(deta):
print("Sta... |
dc1c439dbacfeaf119ea448c87beee7a75d81b53 | naren6195/pythonProject | /venv/Iterator.py | 376 | 3.625 | 4 | class Student:
def __init__(self):
self.num=1
def __iter__(self):
return self
def __next__(self):
if self.num<=10:
val=self.num
self.num+=1
return val
else:
raise StopIteration
val=Student()
print(next(val))
#print(iter(i))... |
d5db3495732df49efe9eb2893236d3aaa528f363 | naren6195/pythonProject | /venv/TEST1.py | 1,076 | 3.875 | 4 | def Hello():
print("Hello_world")
Hello()
x=1
y='Narendr'
print(x,y)
if x>1:
print("X is greater then 1")
elif x<1:
print('x is less than one')
elif x==1:
print('Fucker')
Lett =[1,'a','b',30]
Let=(1,12,'a','am')
for x in 'Lett':
print(x)
for x in Let:
print(x)
nu=1
while nu<10:
nu+= 1
... |
142cbfb3d358cb3fc1c4d35ece7294ffe24bbb24 | sandeep-india/careercup | /onedot7.py | 624 | 3.765625 | 4 | '''
Write an algorithm such that if an element in an MxN matrix is Zero, its entire row and column is set to Zero.
'''
def zerofy(my_list):
rows=len(my_list)
columns =len(my_list[0])
row_list = []
column_list = []
for i in range(0,rows):
for j in range(0,columns):
if my_list[i][j] == 0:
if not i in row_... |
a0b85c959fbcbbfdb89793743bc4fc0b9b3e5d8d | sandeep-india/careercup | /onedot5.py | 136 | 3.5625 | 4 | '''
Write a method to replace all spaces in a string with
'''
def replacespace(string1):
return string1.replace(' ','%20')
'''
'''
|
17ed3fb9a7db31c557d3c31280be82da404c692c | susifohn/HS2020_Machine_Learning | /programming_assignment_2/assignment2/svm_loss.py | 1,247 | 3.53125 | 4 | import numpy as np
def svm_loss(w, b, X, y, C):
"""
Computes the loss of a linear SVM w.r.t. the given data and parameters
Args:
w: Parameters of shape [num_features]
b: Bias (a scalar)
X: Data matrix of shape [num_data, num_features]
y: Labels corresponding to X of size [... |
20a50adbadad7de745d1e9354156627ff8d800f7 | niuyacong/python | /InnerModule/time.py | 7,413 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'时间模块 module'
__author__ = 'nyc'
# 概要:
# timestamp、datetime互转
# datetime、str互转
# 本地时间转换为UTC时间
# 时区转换
# datetime是Python处理日期和时间的标准库。
# 获取当前日期和时间
from datetime import datetime
now=datetime.now();
print(now);
# 2018-02-07 09:15:07.595110
print(type(now))
# <class 'dateti... |
a554825f93a3c6c95a4b8da8b175437531db7834 | niuyacong/python | /面向对象高级编程.py | 23,265 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'面向对象高级编程'
__author__ = 'nyc'
# 简要说明:
# __slots__
# @property
# 多重继承
# 定制类(__str__、__repr__、__iter__、__getitem__、__getattr__、__call__)
# 枚举类
# 使用元类(type(),metaclass())
# __slots__
# 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性
class Student(obje... |
10897d6a0ac597b81b98a904bed569cda60d980e | niuyacong/python | /relation/Hello.py | 1,419 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'a test module'
__author__ = 'nyc'
class Hello(object):
def Hello(self,name='world'):
print('Hello,%s'% name);
# 使用type()创建出类nyc,而无需定义class nyc...
def fn(self,name='haha'):
print('nyc:%s'%name);
NYC=type('NYC',(object,),dict(nyc=fn));# 创建NYC class
n=... |
deafc71abff0881e84277fd12102f139cb216079 | wolkerzheng/code_life | /ReverseSentence.py | 437 | 3.53125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
if s is None or s.strip()=='':
return s
ss = s.split(' ')
start,end = 0,len(ss)-1
while start<end:
ss[start],ss[end] = ss[end],ss[start]
start+=1
... |
0fee24dd4888a74f572a1cc04c60ed390b359c88 | wolkerzheng/code_life | /Permutation.py | 1,402 | 3.65625 | 4 | # -*- coding:utf-8 -*-
import itertools
class Solution:
def Permutation(self, ss):
# write code here
"""
"""
res =[]
if ss == '':
return res
lst = list(itertools.permutations(list(ss),len(ss)))
for i in range(len(lst)):
... |
b0398f9d1751611c505aa530849336dbb7f3ef00 | Ran05/basic-python-course | /ferariza_randolfh_day4_act2.py | 1,153 | 4.15625 | 4 | '''
1 Write a word bank program
2 The program will ask to enter a word
3 The program will store the word in a list
4 The program will ask if the user wants to try again. The user will input
Y/y if yes and N/n if no
5 If yes, refer to step 2.
6 If no, Display the total number of words and all the words that user enter... |
bbcc2897811b439b743a3e173a6fdda43ad9ef4b | Ran05/basic-python-course | /day2.py | 3,526 | 4.46875 | 4 | # Day 2
#Basic string operation
#Displaying
# Note
# print('John said "I don\'t like vegetables"') \ it is use for escape character
# print("Mike said 'I love eating burger!' ")
# print("This next text will move to the \nnext line") \n for a new line
# print("\t\t\t\tThis text comes after a tab")
#######
... |
9bbd5a19586ff1c2c02e2d37d0f8ae388c6392a4 | Ran05/basic-python-course | /day3_act2.py | 1,009 | 4.09375 | 4 |
#Activity 2 of Day 3:
emp_Name = input("Enter employee name: ")
yrs_in_service = input("Enter years of service: ")
office = input("Enter office: ")
o = f"""
=======Bunos Form========================
"""
print(o) # divider
if int(yrs_in_service) >= 10 and office == "it" :
print("Hi" + " " + emp_Name + "," +... |
9d4a6c99774a934a89069328d778b622004b0acd | niteshrawat1995/MyCodeBase | /python/practise/merge_two_sorted_stack.py | 810 | 4.09375 | 4 | # Merge to sorted stack in to 1 sorted stack.
# Conquer part of Merge Sort.
# Using list as stack with only allowed function append(push),pop(pop).
s1 = [5,4,3,2,1]
s2 = [10,9,8,7,6]
def conquer(s1,s2):
s3 = []
i = len(s1)-1
j = len(s2)-1
while len(s1) or len(s2):
# if s1 gets exhausted.... |
92151c4a1ceca1910bd60785b2d5d030559cd241 | niteshrawat1995/MyCodeBase | /python/concepts/classmethods.py | 1,481 | 4.125 | 4 | # Class methods are methods wich take class as an argument (by using decorators).
# They can be used as alternate constructors.
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
sel... |
5f109dfef4214b33302401e473d9b115a65bffa5 | niteshrawat1995/MyCodeBase | /python/concepts/getters&setters&deleters.py | 1,284 | 4.15625 | 4 | # getters,setters and deleters can be implemented in python using property decorators.
# property decorators allows us to define a mehtod which we can access as an attribute.
# @property is the pythonic way of creating getter and setter.
class Employee(object):
def __init__(self, first, last, pay):
self.... |
41028c0e5073272fefbd516909e5e14d97d45e2a | niteshrawat1995/MyCodeBase | /python/practise/DS/string_rev_Stack.py | 195 | 3.671875 | 4 | # Reversing a string using stack
def rev_str(seq):
seq = list(seq)
rev = []
for i in range(len(seq)):
rev.append(seq.pop())
return ''.join(rev)
print(rev_str('Nitesh'))
|
95484e7fe8d71eaa0fbcd723b67eddeafd17f535 | niteshrawat1995/MyCodeBase | /python/practise/DS/Doubly_LinkedList.py | 937 | 4.34375 | 4 | # Implementing doubly linked list:
class Node(object):
"""Node will have data ,prev and next"""
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class LinkedList(object):
"""Linked list will have head attribute."""
def __init__(self):
self.... |
87438791435fbb68e52e08b74eb5368c78bf84b2 | niteshrawat1995/MyCodeBase | /python/concepts/algorithms_concepts/fixed_pt_using_BS.py | 680 | 3.734375 | 4 | # fixeed point is the value which is equal to the index value in which t is placed.
# Problem is to search the element and return None is no such element exist.
# Sequence is present in ascending order and distinct which makes it a suitable candidate for Binary Search.
def fixed_point(seq, low, high):
if low > hi... |
977052ad4fd82e3bbf760bf4560339e6f9f85502 | shuoyan73/hello-world | /Leetcode/155#_Min Stack_05170221.py | 900 | 3.90625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.item=[]
self.min=0
self.tempmin=0
def push(self, x: int) -> None:
self.item.append(x... |
1c64c398c2f5388d693371b4e88337a30d06c37d | john911120/SampleTest | /Python_Project/Recursion/Test1.py | 609 | 3.90625 | 4 | """
num = 0
def main():
counter(num)
def counter(num):
print(num)
num += 1
counter(num)
main()
"""
def main():
loopnum = int(input("How Many times would you like to loop?\n"))
counter = 1
recurr(loopnum,counter)
#루프를 도는 회수를 지정해준다.
def recurr(loopnum, counter):
if loopnum > 0:
... |
c6f1b9fe870ff1cdb14b3ed32cc5853003a43160 | BruhJerem/EPITECH_TEK3_CAESAR | /challenge09.py | 1,957 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import codecs
from Crypto.Cipher import AES
# Read file
try:
with open(sys.argv[1]) as file:
keytext = file.readline().strip('\n')
ivtext = file.readline().strip('\n')
text = file.readline().strip('\n')
except IOError:
print(sys.argv[1], '- does not e... |
cdc7e794d4e5d5bc5dd973e07bf1a92d993c3043 | sxd942/fascist_text_classification | /Code/classification_system/classification/classification_experiments.py | 13,463 | 3.703125 | 4 | from classification.classification_metrics import *
from feature_extraction.feature_constants import *
from utils.pipeline_utils import *
from utils.common_constants import *
from preprocessing.preprocess import stem
from utils.multi_pipeline_utils import *
"""
@Author: Siôn Davies
Date: July 2020
"""
"""
make_classif... |
0ea09106319145b30870a019e4ca6dec41a2507a | sxd942/fascist_text_classification | /Code/classification_system/feature_extraction/tfidf_features.py | 2,785 | 3.546875 | 4 | from nltk.tokenize.treebank import TreebankWordTokenizer
from sklearn.feature_extraction.text import TfidfVectorizer
"""
tfidf_features.py contains two Tf-idf vectorizer classes for text feature extraction.
Tfidf_word_vec_features is a transformer class that extracts word n-grams in the form of
uni-grams, bi-grams an... |
d8395dde5f7d4e7a08aef12da9cebceb6280037c | GUERMACHAIMAE/atelier1-2 | /question_last atelier1.py | 322 | 3.8125 | 4 | # atelier 1 exercice 9
# fonction qui cherche un élément dans une matrice puis renvoi sa position
def get_position(matrice, element):
for i in matrice:
for j in i:
if j == element:
return [i, j]
return None
print(get_position(list(input("saisir 2D array ici or array")), 1)) |
a433024d34f70fc233d58ef599dd54f15fb080d2 | jeffding1993/simple_game | /zombie.py | 930 | 3.625 | 4 | class Zombie:
def __init__(self, name):
armor_list = ["无", 0, "路障", 5, "铁桶", 15]
self.name = name
self.hp = 100
if self.name[:2] == "普通":
self.__armor = armor_list[0]
if self.name[:2] == "路障":
self.__armor = armor_list[2]
if self.name[:2] == "... |
8cb08bdeaac09779f4a0ff5184b68e648c68c548 | anshupandey/Deploy_Machine_Learning_Projects | /mnist_flask_project/train_mnist.py | 2,106 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 1 10:25:47 2019
@author: anshu
"""
from tensorflow.keras.datasets import mnist
from tensorflow.keras import models,layers
from tensorflow.keras.utils import to_categorical
class train_mnist:
def __init__(self,epochs=10,batch_size=1000,validation_split=0.1):
... |
3162550f818df1c7b89930ed77815addccc6b95f | roshbaby/astronomy | /coordinates.py | 5,656 | 3.5625 | 4 | import sys
from math import sin, cos, tan, asin, atan2, pi, radians
from angle import Angle, Longitude, Latitude
from constants import epsilon_j2000
DEFAULT_ENCODING = 'UTF-8'
"""
A Spherical Coordinate is a Longitude and Latitude pair.
It is a glorified tuple, but useful for type checking inputs to functions and
con... |
1e25857c8a1c0987c981f8bc1ee2f61308adf856 | AlexanderGonzalezMMG/Inventory-Management | /inventory.py | 2,887 | 3.78125 | 4 | # !/usr/local/bin/env python3.8
import tkinter as tk
from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askopenfilenames
from tkinter import ttk
import numpy as np
from pathlib import Path
import pandas as pd
import os
import sys
import csv
# TODO: Add options to remov... |
b390c30ede10ebef0cf9210786d5e9b1b8d8302d | Boris17210/development | /experimental/emonhub_development/PythonThreading/01.py | 1,385 | 3.75 | 4 | #!/usr/bin/python
import os, sys
import threading
import time
import Queue
class Dispatcher(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self._queue = queue
self.stop = False
def run(self):
# Loop until we stop is false (our exit signal... |
b1686f25387acc9a8eb62bc0c19377904d168977 | jigripokhri/PandasNumPyMatplotlib | /3-Part2.py | 585 | 3.59375 | 4 | import pandas as pd
def convert_people_cell(cell):
if cell=="n.a.":
return "sam walton"
return cell
def convert_revenue_cell(cell1):
if cell1 < 0:
return None
return cell1
df=pd.read_excel("stock_data.xlsx", "Sheet1", converters={
"people" : convert_people_cell,
"revenue" : convert_revenue_... |
15a3e8f6061792f0c3371ee52226f253870c793f | jigripokhri/PandasNumPyMatplotlib | /2-CreatingDataFrame.py | 296 | 3.5 | 4 | import pandas as pd
#df = pd.read_excel("weather_data.xlsx")
#df = pd.read_csv("weather_data.csv")
#print(df)
weather_data = {"Day" : ['1/1/2017','1/2/2017','1/3/2017'],
"Temperature" : [32,35,38],
"Event" : ["Rain","Sunny","Snow"]}
df=pd.DataFrame(weather_data)
print(df) |
e78334b2ae75714172fad80bf81e8c76497f7cb5 | scantea/hash-practice | /hash_practice/exercises.py | 2,554 | 4.3125 | 4 |
def grouped_anagrams(strings):
""" This method will return an array of arrays.
Each subarray will have strings which are anagrams of each other
Time Complexity: O(n)
Space Complexity: O(1)
"""
freq_hash = {}
for word in strings:
key = ''.join(sorted(word))
... |
e04c11c800f77f2c3f16159f2dc32e6677c46933 | guigui0609/LOG635_TP3 | /data/data.py | 581 | 4.09375 | 4 | from enum import Enum
class Directions(Enum):
TOP = "Top"
RIGHT = "Right"
BOTTOM = "Bottom"
LEFT = "Left"
def get_opposite_direction(self):
if self == Directions.TOP:
return Directions.BOTTOM
elif self == Directions.BOTTOM:
return Directions.TOP
e... |
fe2be41b9346cf783f383b57a7f925c913cbb330 | Aguinore/hackerrank | /src/main/python/org/aguinore/crackInterview/crack_interview.py | 216 | 3.703125 | 4 |
def number_of_pairs(arr):
stack = set()
pairs = 0
for num in arr:
if num in stack:
pairs += 1
stack.remove(num)
else:
stack.add(num)
return pairs
|
a80e733f631158a81c737f0158a187a3469b7df2 | LucasMassazza/Python | /CursoBPBA/Clase5/EjerciciosResueltos.py | 686 | 3.5 | 4 | import numpy as np
import pandas as pd
Nombre = ["nery Pumpido",
"Jose Schiuffino",
"Jose Schiuffino",
"Jose Luis Brown",
"Oscar Ruggieri"
"Segio Batista",
"Ricardo Giusti",
"Jorge Burruchaga",
"Hector Enrique",
"Julio Olartich... |
5b119b5d6ee2dfeb455b174a2b2332de7cd7a6a7 | sivaram143/python_practice | /conditions/ex_01.py | 202 | 4.3125 | 4 | #!/usr/bin/python
# program to check whether a given no is even or ood
num = input("Enter any number:")
if num % 2 == 0:
print("{0} is even".format(num))
else:
print("{0} is odd".format(num)) |
de43dc0d3c246bfdd7a124e2942be5ebc717cb9d | sivaram143/python_practice | /operators/arithmetic.py | 706 | 4.375 | 4 | #!/usr/bin/python
# Arithmetic Operators: +, -, *, /, %, **(exponent:power)
num1 = input("Enter first number:")
num2 = input("Enter second number:")
print("************* Arithmetic Operators *************")
print("Addition(+):{0}+{1}={2}".format(num1,num2,num1+num2))
if num1 > num2:
res = num1 - num2
else:
... |
86577bc7d1217ef40bc22ae208433701dc15a162 | sivaram143/python_practice | /modules/num.py | 1,263 | 4 | 4 | #!/usr/bin/python
"""
NumPy and SciPy are open-source add-on modules to Python that provide common
mathematical and numerical routines in pre-compiled, fast functions.The NumPy (Numeric Python)
package provides basic routines for manipulating large arrays and matrices of numeric data.
The central feature of NumPy is ... |
590c938cbbce7a508822ec36f1859c5fd6aa82e3 | limgeonho/Algorithm | /inflearn_practice/section8/알리바바와 40인의 도둑(TD).py | 711 | 3.5 | 4 | #알리바바와 40인의 도둑(top - down)
# top - down 방법: 구하고자 했던 수부터 거꾸로 처음 시작수까지 내려온다.
# 메모이제이션과 재귀함수 활용
# 나머지 방법은 동일함...
def DFS(x, y):
if dy[x][y] > 0:
return dy[x][y]
if x == 0 and y == 0:
return arr[0][0]
else:
if y == 0:
dy[x][y] = DFS(x-1, y) + arr[x][y]
elif x == 0:
... |
17bf47ef963e3cfb37ec00ff326dc9a5c7c6d652 | limgeonho/Algorithm | /inflearn/DFS/DFS기본/이진트리순회.py | 167 | 3.6875 | 4 | #이진트리순회(전위순회)
def DFS(x):
if x > 7:
return
else:
print(x, end='')
DFS(x*2)
DFS(x*2+1)
DFS(1)
|
54cbd91b6a6877e9e22bc5b1fadd2608bfc99509 | JuanYam/sudoku_engine | /sudoku.py | 8,972 | 4.03125 | 4 | import copy
import random
class Board:
"""
__init__ [code (optional): string]:
Initilise the board object
boardToCode [input_board (optional): list]:
Convert a board represented by a list into a string representation
findSpaces []:
Finds the first empty space, represented by a 0, on the curre... |
8e0e352a6394800d3eb45053b05acaed2b4f2447 | Jiter/HSKa_vdki2019 | /print | 270 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 07:47:45 2019
@author: david
"""
startzahl = 12
for i in range(66,125,2):
print("[{}, 0, 0, 0, 0], # {} - {}".format(startzahl,i, i+1))
startzahl = startzahl + 1; |
3e4abc491fe3f3e60980eb2a55d68a67a96348a4 | igajurel/nodeapp_new | /age_sorter.py | 1,962 | 3.796875 | 4 | #usecase
# 3,2,1,4,6
# 3,2<---------->1,4,6
# i=0,j=0
# is 3<=1, no
# a[k]=a[0]=1; i=0,j=1
# is 3<=4, yes
# a[k]=a[1]=3; i=1,j=1
# is 2<=4, yes
# a[k]=a[2]=2; i=1 (max-cap),j=1
# is 4, yes
# a[k]=a[3]=4; j=2
# is 6, yes
# a[k]=a[4]=6; j=2 (max-cap)
def sortuserages(input_list):
#input_list = [3,2,7,6,4]
#print(... |
97c55afbb14d50210665f7798f5fe1f98ad058c3 | ysonggit/leetcode_python | /1628_DesignanExpressionTreeWithEvaluateFunction.py | 1,553 | 3.984375 | 4 | import abc
from abc import ABC, abstractmethod
"""
This is the interface for the expression tree Node.
You should not remove it, and you can define some classes to implement it.
"""
class Node(ABC):
@abstractmethod
# define your fields here
def evaluate(self) -> int:
pass
class NumNode(Node):
... |
25e545284a53ce76c3b3ded92892c10a221ac654 | ysonggit/leetcode_python | /0126_WordLadderII.py | 1,623 | 3.5 | 4 | class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
# https://leetcode.com/problems/word-ladder-ii/discuss/269012/Python-BFS%2BBacktrack-Greatly-Improved-by-bi-directional-BFS
wordset = set(wordList)
if endWord not in wordset:
... |
cecc29c811ce95a90ef178456740d3c1dc300541 | ysonggit/leetcode_python | /0071_SimplifyPath.py | 379 | 3.625 | 4 | class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
tokens = path.split("/")
for cur in tokens:
if not cur or cur == '.':
continue
if cur == '..':
if stack:
stack.pop()
else:
... |
45726ba54cf64f57902d9998674cb19c9e586c97 | ysonggit/leetcode_python | /0295_FindMedianfromDataStream.py | 1,360 | 3.765625 | 4 | from heapq import heappush, heappop
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
A max-heap to store the smaller half of the input numbers
A min-heap to store the larger half of the input numbers
"""
self.minheap, self.maxheap = []... |
7f1f4511ac2e81279ceb83015742cb3b68f12280 | ysonggit/leetcode_python | /0403_FrogJump.py | 658 | 3.578125 | 4 | class Solution:
def canCross(self, stones: List[int]) -> bool:
jumpPos = {}
for stonePos in stones:
jumpPos[stonePos] = set()
jumpPos[stones[0]].add(0)
for stonePos in stones:
jumpUnits = copy.deepcopy(jumpPos[stonePos]) # avoid set size changed during iterati... |
e119325078ba928f8f66fb78467db1d96f29e6ee | ccmxy/Networking-Assignments | /Project1/Chatting_with_Sockets/chatserve.py | 2,497 | 3.53125 | 4 | import sys
from sys import stdin
import SocketServer
import argparse
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
clien... |
adf1f7fa4c55b0341a3d507ca009be159559e881 | asmitasharma16/Assignment-5 | /Assignment 5.py | 4,866 | 4.25 | 4 | print("*****************************DECISION AND FLOW CONTROL*****************************")
#Q.1- Take an input year from user and decide whether it is a leap year or not.
year=int(input("Enter year "))
if((year%100!=0 and year%4==0 )or year%400==0):
print("Leap year")
else:
print("Not a leap year")
#Q.2- Tak... |
f377b8d4cb9e1379247557b882244614d2aa98ae | Greatbar/Python_Labs | /15_2.py | 110 | 3.6875 | 4 | string = input()
temp = 0
for i in string:
if i != ' ' and i != '\t':
temp += 1
print(temp)
|
807d9e0be1070b98bbc3bbff5d0cac60a7065da8 | Greatbar/Python_Labs | /21_3.py | 192 | 4 | 4 | def swap(first, second):
third = first[:]
for i in range(len(first)): first.pop()
first.extend(second)
for i in range(len(second)): second.pop()
second.extend(third)
|
40264c2dc4e9f8e78283edb832ac8edca0f76fd1 | Greatbar/Python_Labs | /13_1.py | 317 | 3.6875 | 4 | number = int(input())
list_1 = [''] * number
for i in range(number):
list_1[i] = input()
k = int(input())
for i in range(k):
x = int(input())
temp = [''] * x
for j in range(x):
temp[j] = list_1[int(input()) - 1]
list_1 = temp
for i in range(len(list_1)):
print(list_1[i])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.