blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7b02e43bf71adf21b7002b8ce48cc97e2846715c | Song367/machine_learing | /pandas/案例-电影分类.py | 735 | 3.59375 | 4 | import pandas as pd
import numpy as np
#读取文件
a=pd.read_csv('movie.csv',usecols=["genres"])
print(a)
#获取每一列的分类
index_movie=[i.split('|') for i in a["genres"]]
print(index_movie)
#获取所有电影类别 unique去重
temp_list=np.unique([y for x in index_movie for y in x])
print(temp_list)
#生成一个全为0的数组
zero=np.zeros([a.shape[0],temp_list.s... |
bd32504b7d429db09d76c7ea443b56cbdcb7725c | sahildur/Machine-Learning-HandWritten-Digit-Classification-Using-Neural-Network | /nnScript.py | 15,822 | 3.75 | 4 | import numpy as np
from scipy.optimize import minimize
from scipy.io import loadmat
from math import sqrt
import random
#import matplotlib.pyplot as plt
#import matplotlib.cm as cm
import math
import timeit
def initializeWeights(n_in,n_out):
"""
# initializeWeights return the random weights for Neural Network ... |
8cdb53cd77d2b8df75f5d7a2cafda0225a33a23b | pcroissant/JV-SteeringBehaviors | /src/agent.py | 4,814 | 3.734375 | 4 | import random
import pygame
from pygame.math import Vector2
class Agent:
def __init__(self, width, height):
"""Initialize agent parameters
Args:
width (int): width of the game screen
height (int): height of the game screen
"""
self.position = Vector2(rando... |
6a163bfb06b31a891a4c2da6e027f54a766b43fe | madhavmalhotra3089/Introduction-to-python | /Assignment 1/file_8.py | 308 | 4.0625 | 4 | string='Madhav'
result = True
str_len = len(string)
print str_len
half_len= int(str_len/2)
print half_len
for i in range(0, half_len):
# you need to check only half of the string
print string[str_len-i-1]
if string[i] != string[str_len-i-1]:
result = False
break
print(result) |
2b1f44c0e4ff9910f52a2821f6244065a3485683 | cesarschool/cesar-school-fp-2018-2-lista1-PedroRetry | /questão_4.py | 336 | 3.90625 | 4 | def main():
d = int(input('por quantos dias você rodou com o carro?')) #d=número de dias
k = float(input('quantos quilômetros você rodou nesses dias?')) #K=quilômetros rodados o=orçamento
o1 = 60*d
o2 = 0.15*k
of = o1+o2
print('você terá que pagar R$', of)
if __name__ == '__main__':
... |
b229f0e0b3a9e3d52cf04178ee252fde81b5028b | Prash-10520536/v_p_n | /FormValidation.py | 636 | 3.78125 | 4 | #Code Reference https://datatofish.com/if-elif-else-python/
import tkinter
import tkinter.ttk
import tkinter.messagebox
import sqlite3
class FormVaidation:
def Validate(self, id, fName, lName, phone, email):
if not (id.isdigit() and (len(id) == 3)):
return "id"
elif not (fName.isalpha(... |
c2853f4bd7682ed91b22dd8040e727299bff2b52 | vharmers/Kn0ckKn0ck | /Parsing/Readers/Reader.py | 1,416 | 4.1875 | 4 | import abc
class Reader:
"""
Abstract class which defines the minimal functionality of Readers. You will need to extend from tis class
if you want to create your own reader.
"""
def __init__(self):
pass
@abc.abstractmethod
def get_count(self):
"""
Gets ... |
433d68cb33fd466e3851147d67875767560f3f6a | vharmers/Kn0ckKn0ck | /UnitTests/TableTest.py | 1,092 | 3.5625 | 4 | from unittest import TestCase
from Parsing.Readers.Table import Table
class TestTable(TestCase):
"""
Test case for testing the different methods of the Table class
"""
def setUp(self):
header = ['Animal', 'Name']
table = [['Dolphin', 'Joe'], ['Cat', 'Max'], ['Dog', 'John'], ['Hams... |
2356eae9581ae476d7ed9ce1ddf6a6d094830a2b | vharmers/Kn0ckKn0ck | /Proxies/Protocols/HttpProtocol.py | 9,135 | 3.65625 | 4 | import re
import collections
from Protocol import Protocol
from NoProtocol import NoProtocol
"""
This python file contains components for working with the http protocol. This file contains the following:
- The HttpRequest and HttpResponse classes for manipulating, reading and creating http requests and respon... |
5cb8bfcaeef21c8bceebb1abde992586e51c8309 | jraulcr/curso-python | /poo_1.py | 1,270 | 3.90625 | 4 | class Coche():
#constructor
def __init__(self):
#Propiedades La encapsulacion se añade a la variable __
self.__largoChasis=250
self.__anchoChasis=120
self.__ruedas=4
self.__enmarcha=False
#Comportamientos o métodos
def arrancar(self, arrancamos):
self.enmarcha=arrancamos
if self.enmarcha:
retu... |
0bb76f227b04593d109b4abf127f95aa5348c09f | jraulcr/curso-python | /practica_listas.py | 1,229 | 4.25 | 4 | miLista=["María", "Pepe", "Marta", "Antonio"]
#Accede a todos los elementos
print(miLista[:])
#Acceso por indice (Desde el primer lugar)
print(miLista[2])
#Acceso por subindice (Desde el último lugar)
print(miLista[-1])
#Acesso por porciones
print(miLista[1:3])
print(miLista[2:])
print(miLista[:2])
#Agrega nuevo elem... |
5117d713b1d991339487ccb2d23747cf51922c3e | laysakura/relshell | /relshell/timestamp.py | 3,721 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
relshell.timestamp
~~~~~~~~~~~~~~~~~~~~~~~~
:synopsis: Provides efficient data structure to represent timestamp
"""
import datetime as dt
class Timestamp(object):
"""Provides efficient data structure to represent timestamp
"""
def __init__(self, timestamp_str):
... |
abab4fd984f6f893848170cc47a300c3c5281f8b | laysakura/relshell | /relshell/test/shellcmd/simplest | 452 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
word_count
~~~~~~~~~~
:synopsis: input: word, output: occurence count of the word
"""
import sys
if __name__ == '__main__':
sys.stderr.write('input any word (Ctrl-D to finish)\n')
while True:
word = sys.stdin.readline()
if word == ... |
1a40131a878a6a43d2d0ccd531e76e22abc7a24c | Wsssssss/target-offer | /二叉树中和为某一值的路径.py | 817 | 3.703125 | 4 | # 题目描述
# 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
a, b = [],[]
def subfindpath(root):
if root:
b.append(root.val)
... |
7a754ccfe0d48c29930efc36a6bfc2aa4dedc389 | Wsssssss/target-offer | /数组中重复的数字.py | 1,073 | 3.703125 | 4 | # 题目描述
# 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。
# 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
if numbers == None or len(numbers)<1:
... |
f7c1e1735c5e1cdb904a8827b9bca6cb17e95861 | Wsssssss/target-offer | /二叉树的深度.py | 742 | 3.90625 | 4 | # 题目描述
# 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
class Solution:
def TreeDepth(self, pRoot):
if pRoot == None:
return 0
treelist = []
treelist.append(pRoot)
depth = 0
while len(treelist):
treelen = len(treelist)
while... |
5a5f34191a28725a3827b90ff01bbdf2a66566b0 | Wsssssss/target-offer | /二叉搜索树与双向链表.py | 1,375 | 3.515625 | 4 | # 题目描述
# 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
class Solution:
def Convert(self, pRootOfTree):
if not pRootOfTree:
return None
if not pRootOfTree.left and not pRootOfTree.right:
return pRootOfTree
left = self.Convert(pRootOfTree.left)
p =... |
6f24430002c67d04a428bc955c3012832b7c6e7b | tumioo/Python-Challenge | /Pypoll/Main.py | 3,375 | 3.515625 | 4 | # import libraries
import os
import csv
# set path to read in and output election data files
election_data_in = os.path.join("/Users/masterambassador/PycharmProjects/Python Challenge/Pypoll/election_data.csv")
Election_out = os.path.join("/Users/masterambassador/PycharmProjects/Python Challenge/Pypoll/election_a... |
cbee584aca9388c2ecaf43f95b0f4aa300958f36 | BSanandu88/CS50x | /pset6-python/readability.py | 692 | 3.703125 | 4 | from cs50 import get_string
text = get_string("Text:\n")
letters = 0
words = 0
sentences = 0
counter = 0
for i in text:
counter += 1
for i in range(counter):
if(ord(text[i]) >= 65 and ord(text[i]) <= 122):
letters += 1
elif (ord(text[i]) == 32 and (ord(text[i-1]) != 33 and ord(text[i-1]) !=... |
378fa2953c99f250bae26f7c442057d93785ebf2 | darioncassel/kale | /src/kale.py | 1,127 | 3.59375 | 4 | """
This file composes the various pieces of the Kale
interpreter in order to evaluate a given Kale
(.kl) file.
"""
import sys
from Lexer.Lexer import Lexer
from Parser.Parser import Parser
from Tokenizer.Tokenizer import Tokenizer
from Interpreter.Interpreter import Interpreter
"""
It takes a filename and performs th... |
51f66ab2496dfbd2170e2843c9070ded5a6b4325 | aurlien/AdventOfCode2020 | /d11/ex2.py | 2,527 | 3.546875 | 4 | FLOOR = '.'
SEAT_EMPTY = 'L'
SEAT_OCCUPIED = '#'
UP = -1
DOWN = +1
RIGHT = +1
LEFT = -1
def parse_input(filename):
with open(filename) as f:
return [list(line.strip()) for line in f.readlines()]
def print_grid(grid):
for line in grid:
print("".join(line))
print()
def adjacent(row, c... |
0ff710cd81836478d15f492e6e13a709f4b0d65b | aurlien/AdventOfCode2020 | /d4/ex2.py | 2,278 | 3.515625 | 4 | import re
def between(field, low, high):
return low <= int(field) <= high
def valid_height(height):
value, unit = height[:-2], height[-2:]
if unit == "cm":
return between(value, 150, 193)
elif unit == "in":
return between(value, 59, 76)
else:
return False
required_fields ... |
ffe9dd138bff8cbbdaa3999dffe4bdb0f5534394 | aurlien/AdventOfCode2020 | /d1/main.py | 691 | 3.609375 | 4 | from itertools import combinations
def parse_input(f):
return [int(n) for n in f]
def sum_to(n, *args):
return sum(args) == n
def ex1(ns):
pairs = combinations(ns, 2)
return next(a * b for (a, b) in pairs if sum_to(2020, a, b))
def ex2(ns):
triples = combinations(ns, 3)
return next(a * b * ... |
064039ef0efd56890bf9e7c96f44da3e2f072e2d | HaonanPu/Voting-System- | /instant_run_off.py | 5,578 | 3.546875 | 4 | # COMP 202 A3
# Name: Haonan Pu
# ID: 260846401
from single_winner import *
import doctest
from a3_helpers import *
import copy
################################################################################
def votes_needed_to_win(ballots, num_winners):
'''
(list) -> int
This function tak... |
7063987b6d8b17297b67971e64be6833303b438e | codeAligned/programming_interview_prep | /hackerrank/interview_prep_kit_all_code.py | 12,973 | 3.96875 | 4 | # https://www.hackerrank.com/interview/interview-preparation-kit
# 3-29-2019
####################
####################
# Dynamic Programming
####################
# Minimum Swaps 2
# https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slug... |
41fd4d6179b386fb0ddc418c848d71cc47a06534 | evanpcosta/Hangman-AI-Project | /Main.py | 2,460 | 3.578125 | 4 | from GUI import *
from Neuro import Neuro
class APP:
file = "/Users/evancosta/Desktop/Hangman-AI-Project/english3.txt"
root = Tk()
root.title('Hangman')
root.geometry("500x400")
global third_frame
third_frame = Frame(root)
third_frame.place(x=0, y=0, width=500, height=500)
global sec... |
cddafd7deb437dfa1b063caab557bcfcbee96bec | MarsX1e/Call_Center_form_PyhonOOP | /Call_Center.py | 2,434 | 3.6875 | 4 | class Call(object):
def __init__(self,caller_name,caller_phone_number,time_of_call,reason_for_call):
self.unique_id=None
self.caller_name=caller_name
self.caller_phone_number=caller_phone_number
self.time_of_call=time_of_call
self.reason_for_call=reason_for_call
def displ... |
2c020ab3ca0becbe2ef3acb094d544b7d449644d | jijin-github/practice | /binary_tree.py | 774 | 3.5625 | 4 | class NewNode(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def topViewDetails(root, m, hd, level):
if not root:
return
if hd in m:
if level < m[hd][1]:
m.update({hd: [root.data, level]})
else:
m[hd] =... |
51dc413fac924afddb985dace23d0858b773523c | jijin-github/practice | /list_practice.py | 253 | 3.828125 | 4 | list_elements = [1, 2, 1, 3, 4, 3]
total_count = 0
for i in list_elements:
element_count = 0
for j in list_elements:
if i==j:
element_count += 1
if not element_count > 1:
total_count += i
print total_count,"IIII" |
6cdf2661ec50779f2d1d9826fe7e8b5af331394a | sravan-talishetti/FST-M1 | /python/activities/Activity1.py | 199 | 3.96875 | 4 | name = input("What's your name ?")
print("Hello, "+name)
age = int(input("What's your age?"))
year = str((2020 - age) + 100)
print("Hello, "+name+ " you will reach 100 years in the year - "+year) |
6a7dc6d243d78949d13fc9d7423bc774dd8960b2 | aayush2906/learning_curve | /prime.py | 295 | 4.0625 | 4 | def prime(n):
temp="off"
for i in range(2,n//2):
if n%i==0:
print("non-prime")
temp="on";
break;
if temp=="off":
print("prime")
n=int(input("number::"))
if n==0 or n==1:
print("neither prime nor composite")
else:
prime(n)
|
f2e3ddcbfedf9b3860590b28dbfd032e106e9390 | aayush2906/learning_curve | /for.py | 559 | 4.34375 | 4 | '''
You are given a number N, you need to print its multiplication table.
'''
{
#Initial Template for Python 3
//Position this line where user code will be pasted.
def main():
testcases=int(input()) #testcases
while(testcases>0):
numbah=int(input())
multiplicationTable(numbah)
print()
... |
4deb191a0ec010c083027f14104e13f7333021e2 | aayush2906/learning_curve | /pattern.py | 220 | 3.859375 | 4 | n=int(input("Enter number of rows::"))
for i in range(1,n):
for j in range(1,n):
if j<=i:
print(j,end="")
else:
print(" ",end="")
print()
'''
1
12
123
1234
12345
'''
|
179512c02c038c9339edda82cbf47460ec600bb5 | ssarup/covid19 | /data/Location.py | 2,231 | 3.5625 | 4 | class Location(object):
def __init__(self, country_ = None, state_ = None, county_ = None, city_ = None):
self._country = country_
self._state = state_
self._county = county_
self._city = city_
@property
def country(self):
return self._country
@property
def ... |
b2e4c76c658062a612946c974febfcdac4d6d2d4 | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/practice4-solution/binary_tree.py | 14,561 | 3.875 | 4 | class Node:
def __init__(self, data, parent=None):
self.data = data
self.parent = parent
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = root
def __str__(self):
"""
algorithm:
- get row for each nod... |
a4e7ded1eac764352cb65888ba36ef4289bd6c4b | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/lecture09/python/stack.py | 1,661 | 4.15625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.prev = None
class StackLinkedList:
"""
linked list implementation of stack
- similar to singly linked list
"""
def __init__(self):
self.top = None
def push(self, data):
"""
add element to ... |
fc93f7c07d5d82050334e0318dc5300528d67a3e | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/practice4-solution/question8.py | 844 | 3.78125 | 4 | """
write an algorithm that gets a binary tree, a number k
and returns all values in level k. what is the running time of your algorithm?
"""
from binary_tree import build_tree7
def get_level(bt, k):
"""
assume root is level 0
- O(N) solution (in worst case we look at entire tree)
"""
q = [(bt.roo... |
9a044231cb1d922651e6b3463e5f3696cf7b18af | nathanesau/data_structures_and_algorithms | /_courses/cmpt225/practice4-solution/question6.py | 892 | 4.1875 | 4 | """
write an algorithm that gets a tree and computes its
depth using iterative implementation.
"""
"""
write an algorithm that gets a tree and computes its size
using iterative implementation.
"""
from binary_tree import build_tree1, build_tree2, build_tree3
def get_depth(bt):
"""
use level-order iterative a... |
95ef723c79c98a134683407fa5096c99de3793d7 | kulukulu94/pythonrefresh | /pythonrefresh.py | 8,439 | 4.1875 | 4 | #intergers, floats
x = 15
price = 9.99
discount = 0.2
result = price * (1 - discount)
#print(result)
#strings
name = "Ali"
#print(name * 2 ) #this basicly means AliAli
#changing variable value
a = 25
b = a
#print(a)
#print(b)
b = 17
#print(a)
#print(b)
#String formating in python using f string
name = "Bob"
greeti... |
51b4418479638e867a6d0ad917ea641e75004bdb | Rejzor/Python_stuff | /Euler_1.py | 127 | 3.65625 | 4 | a=0
b=1
counter=0
for i in range(0,input("Podaj zakres fibo: ")):
a=a+b
a,b=b,a
counter+=a
print(a)
print("SUMA: ",counter) |
8d41f3cd9b13eab65efe91111f2e3c2bc0a37f72 | Rejzor/Python_stuff | /import_product.py | 170 | 3.5 | 4 | from itertools import *
tab1=map(int,input().split(" "))
tab2=map(int,input().split(" "))
tab = ([ i for i in product(tab1, tab2)])
for i in tab:
print (i, end=" ")
|
7272bad12702cd1d44c0d4a9064b75e1dbf893c9 | KieSun/StudyCode | /MIT 6.0001/week3.2.py | 1,937 | 3.765625 | 4 | # # x = (1, 2, (3, 'John', 4), 'Hi')
# # x[0] = 8
#
#
# def oddTuples(aTup):
# tup = ()
# for i in range(len(aTup)):
# if i % 2 == 0:
# tup += (aTup[i],)
# return tup
# print oddTuples(('I', 'am', 'a', 'test', 'tuple'))
#
# print range(10, 3)
#
# aList = range(1, 6)
# bList = aList
# aLi... |
00a7470d031936b91cc3d7f8500436bcd58395b0 | liggettla/programmingPython | /step1/b_step1UsingLists.py | 4,199 | 4.25 | 4 | #Uses python 3.x
import pprint
#using dictionaries is typically more convenient than using field labels
print('\nUsing a simple dictionary')
bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'}
sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'}
print(bob['name'], sue['pay'])
print(bob['na... |
7333177ce4f666b45d395305299bc640bd2a3e4d | liggettla/programmingPython | /step3/f_step3Classes.py | 1,111 | 3.671875 | 4 | '''
One advantage that classes provide over the use of dictionaries to store and process
data is that classes naturally associate reocrd data with processing logic, and
allows the logic to be changed once without redundancy.
'''
class Person:
#here pay=0 and job=None are used so that they will have default values i... |
76b059de7191f061009762dac4f21f7109741435 | UTEP-Parallel-Computing/parallel-computing-matrix-multiply-cjuare01 | /parallelmatrix.py | 4,064 | 3.734375 | 4 | # Charlie Juarez
# Restrictions: Integer matrices, defined matrices
import time
import random
import pymp
class Matrix(object):
row = 0
column = 0
matrix = []
def __init__(self, row, column, matrix):
self.row = row
self.column = column
self.matrix = matrix
def print_matrix... |
241f32aca011592cc5a6865b2288a5ce39fadb75 | uzet1976/python | /webscraper/ws.py | 890 | 3.59375 | 4 | from bs4 import BeautifulSoup
html_doc=""";
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div id="section1">
<h2>Test section1</h2>
<img src="http://www.walla.co.il/logo.png">
<p>Lorem Ipsom</p>
</div>
<div id="section1">
<h2>Test section2</h2>
<ul>
... |
3875d9590a0a90962b5680329c571b9e300d4540 | Pranav2507/My-caption-project | /project 2.py | 398 | 4.125 | 4 | filename=input('Enter a filename: ')
index=0
for i in range(len(filename)):
if filename[i]=='.':
index=i
print(filename[index+1: ])
filename = input("Input the Filename: ")
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
fn= input("Enter Filena... |
aba6611d825897b03b9d9c4a7adca8f2e6b66c69 | uniite/anagram_finder | /modules/util.py | 449 | 4.125 | 4 | import string
def remove_punctuation(word):
"""
Return the given word without any punctuation:
>>> remove_punctuation("that's cool")
'thatscool'
"""
return "".join([c for c in word if c in string.ascii_letters])
def save_anagram_sets(sets, output_file):
"""
Save the given list of a... |
c05d735fc66a5be2e49a837b75fe66eeb5f22fca | pchessah/learn-python-the-hardway | /ex19.py | 994 | 4 | 4 | #DEFINING A FUNCTION CHEESE AND CRACKERS THAT TAKES TWO ARGUMENTS
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers")
print(f"Man that is enough for a party")
print("Get a blanket. \n")
print("We c... |
5d8b5f6d8436b68596e79fd29672031d4e0fbd03 | kwstu/Algorithms-and-Data-Structures | /BubbleSort.py | 443 | 4.15625 | 4 | def bubble_sort(arr):
# Go over every element (arranged backwards)
for n in range(len(arr)-1,0,-1):
# For -1 each time beacuse each loop an elemnt will be set in position.
for k in range(n):
# Check with the rest of the unset elements if they are greater than one another if so, switch
... |
c608d17aeb079332cf51be22647352ce2abc5085 | titanlien/workshop | /task04/convert.py | 1,167 | 4.15625 | 4 | #!/usr/bin/env python3
import argparse
"""https://www.rapidtables.com/convert/number/how-number-to-roman-numerals.html"""
ROMAN_NUMERALS = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
... |
06b8339073dff3c0e3207154c9a1277f63202956 | davidygp/Project_Euler | /python/prob4.py | 893 | 4.34375 | 4 | """
Problem 4:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def find_max_palin_product() -> int:
"""
Find the largest palindrome made from the... |
dd37b3f9e28b6c26000a9c94f1883c647708b3ae | razvitesting/Automation-Testing | /mylist.py | 206 | 4.125 | 4 | mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# prints out 1,2,3
for x in mylist:
print(x) |
044be8776e8a959acbac43836290556e632b3e99 | milindukey/Python | /Beginners/control loop.py | 1,022 | 4.375 | 4 | largestNumber = -99999999
counter = 0
number = int(input("Enter a number or type -1 to end program: "))
while number != -1:
if number == -1:
continue
counter += 1
if number > largestNumber:
largestNumber = number
number = int(input("Enter a number or type -1 to end program: "))
if co... |
4b41f7f1a744e6820d77049da3443faadacaa9a6 | Abinaya3198/shivanya | /f4.py | 211 | 4.34375 | 4 | al = input("enter the character : ")
if((al >= 'a' and al <= 'z') or (al >= 'A' and al <= 'Z')):
print("The Given Character ", ch, "is an Alphabet")
elif(al == '?'):
print("no")
else:
print("not an alphabet")
|
5b654e1935198907e1ed7ea8cc09155ef7d73383 | marnyansky/matthes-python-cc-complex-solutions | /task0906_page186.py | 1,733 | 4.03125 | 4 | class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def print_served_visitors(business):
print("Current number of served visitors:", business.number_served)
def ... |
7a32f2447f6f788d3ed44dea04f605df50916ca5 | andreadistefano/RoboticsLab2016 | /ex1.py | 568 | 3.578125 | 4 | # -*- coding: utf-8 -*-
def sum(a, b):
return a + b
class Person():
def __init__(self, name, surname):
self._name = name
self._surname = surname
self._address = None
def __str__(self):
out = self._name + " " + self._surname
if not (self._address is None):
... |
5cae2f13f262c9018bd2617441b7103be73196c4 | Qingwen-Zhou/Projects | /Truck-simulator/part2Task2.py | 5,525 | 3.9375 | 4 | from queue import Queue
"""
Dijkstra's #Preet
"""
def dijkstra(map, office,target):
# make an empty dictionary for the answers
paths = {}
# make adjacency list dictionary
adj = {}
# make dictionary for distances
distances = {}
# make weights dictionary of dictionaries
weights = {}
... |
e6648804ad1ac3a032d1c2884a75136194af3985 | simzou/python-workshop | /workshop.py | 12,112 | 3.609375 | 4 |
# coding: utf-8
# # Intermediate Python Workshop
#
#
# ## Agenda
#
# - Introductions
# - Motivation
# - Warm-ups
# - sorted, slicing, sets
# - Fancy Python Shortcuts and Concepts and stuff
# - List comprehensions, ternary operator, iterables, generators
# - Functional Programming
# - map, filter
#... |
622ada44903d7e33a856257252f228a516dbd150 | bdugersuren/algorithmic-problems | /Others/medium/RemoveKthNodeFromTheEnd.py | 592 | 3.734375 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeKthNodeFromEnd(head, k):
if not head:
return
first_pointer = head
curr_pointer = head
while k >= 0 and first_pointer is not None:
firs... |
86e22c79ecbb1c8cbcb69fcda2cd2b986254a484 | bdugersuren/algorithmic-problems | /Others/medium/SumOfLinkedLists.py | 943 | 3.71875 | 4 | # This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def sumOfLinkedLists(linkedListOne, linkedListTwo):
result_list = None
head = None
carry = 0
while linkedListOne or linkedListTwo:
first = 0 if not linke... |
2423990dc132602d836245873c04190126297ab8 | bdugersuren/algorithmic-problems | /CodeForces/TheatreSquare/TheatreSquare.py | 200 | 3.515625 | 4 | def main():
n, m, a = (int(x) for x in input().split(' '))
length = n // a if n % a == 0 else n // a + 1
height = m // a if m % a == 0 else m // a + 1
print(length * height)
main()
|
9e92084bb0efc2ed1afb6ba2897437741674c8a6 | bdugersuren/algorithmic-problems | /Others/easy/ProductSum.py | 521 | 3.90625 | 4 | # Tip: You can use the type(element) function to check whether an item
# is a list or an integer.
def productSum(array):
# Write your code here.
return compute_product_sum(array, 1)
def compute_product_sum(expression, nested):
if not expression:
return 0
if type(expression[0]) == int:
... |
1d76c9e73fe6f3f3d4194a733d8ba67fd2b0da11 | bdugersuren/algorithmic-problems | /Others/easy/NodeDepths.py | 406 | 3.859375 | 4 | def node_depths(root, curr_depth):
if not root:
return 0
return curr_depth + node_depths(root.left, curr_depth + 1) + node_depths(root.right, curr_depth + 1)
def nodeDepths(root):
return node_depths(root, 0)
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, ... |
dd0ca1cb75f3340a5647ec5324331d4bfd73a45f | bdugersuren/algorithmic-problems | /Others/hard/SearchForRange.py | 971 | 3.734375 | 4 | def first_occurance(array, target):
left, right = 0, len(array) - 1
while left <= right:
mid = left + (right - left) // 2
if array[mid] == target:
if mid == 0 or array[mid - 1] != target:
return mid
right = mid - 1
elif array[mid] > target:
... |
5c25b02ecb40c82e49519980542ce46514f7eaed | bdugersuren/algorithmic-problems | /Others/medium/LongestPalindromicSUbstring.py | 1,425 | 3.71875 | 4 | def longestPalindromicSubstring(string):
if len(string) < 2:
return string
max_pal = ''
for i in range(1, len(string) - 1):
if string[i] == string[i - 1]:
pal = check_even_size_pal(i - 1, string)
if len(pal) > len(max_pal):
max_pal = pal
if ... |
5f12ff4b364897d99f9a9ac78243f1ad19907479 | jewellwk/sample-code | /Python/Cartesian Distance/Methods.py | 1,132 | 4.25 | 4 | #Compute the Cartesian distance between 2 points with coordinates (x1,y1) and (x2,y2) = sqrt((x2-x1)^2+(y2-y1)^2))
import math
def solveCart():
x1 = int(input("Enter a value for x1: "))
y1 = int(input("Enter a value for y1: "))
x2 = int(input("Enter a vlaue for x2: "))
y2 = int(input("Enter a value for y2: "))
ca... |
d2326636f04dece40fba57a7ca6299d46a6cd9e3 | HasseNasse/learning-ml | /simple-problem-set-solver/perceptron.py | 1,697 | 3.875 | 4 | import numpy as np
# Activation / Normalization function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Activation / Normalization function derivative
def sigmoid_derivative(x):
return x * (1 - x)
# Output calculation, used inside each neuron
def calculate_output(input, weights):
return sigmoid(np.dot(... |
4762247c81b3eca9eb59b5a15690a09b8d77d440 | shas-hank7/python | /Program_Flow_and_Control/guess.py | 1,562 | 4.03125 | 4 | import random
ul = 1000
answer = random.randint(1, ul)
#print(answer) #TODO: Remove after testing.
# guess = int(input("Enter a number"))
#
# if guess == answer:
# print("You guessed it")
# else:
# if guess < answer:
# print("Guess a higher number")
# else:
# print("Guess a lower num... |
9f300b19b9ebcab15e328c38af2d6dc26ee1eeef | shas-hank7/python | /Functions/fizz_buzz.py | 450 | 3.828125 | 4 | def fizz_buzz(n:int) -> str:
if n%3==0 or n%5==0:
if n%3==0 and n%5==0:
return "fizz buzz"
if n%3==0:
return "fizz"
else:
return "buzz"
else:
return str(n)
for i in range(1, 101, 2):
print(fizz_buzz(i))
userInput = i... |
763c3c177c9295c45a84a0031ce8871be247ed7a | shas-hank7/python | /01_Variables and Data Types/03_typecast.py | 190 | 3.65625 | 4 | a = "2434"
a=int(a)
print(type(a))
print(a+5)
""" b="Shashank"
b=int(b)
print(type(b)) """ #Compiler Error
c=32
c=str(c)
print(type(c))
a=float(a)
print(a)
d=12.34
d=int(d)
print(d)
|
1fc932f1990fdebc095860a8c1662acde51aa6c5 | shas-hank7/python | /Dictionaries and Sets/dict_intro.py | 531 | 3.765625 | 4 | vehicles = {
'dream': 'Honda 250T',
'roadster': 'BMW R1100',
'er5': 'Kawasaki ER5',
'can-am': 'Bombardier Can-Am 250',
'virago': 'Yamaha XV250',
'tenere': 'Yamaha XT650',
'jimny': 'Suzuki Jimny 1.5',
'fiesta': 'Ford Fiesta Ghia 1.4',
}
vehicles['starfighter'] = 'Lockheed F-104'
vehicles... |
30a2f99466b9be81f54aed3bb1e83e572f911c9e | shas-hank7/python | /Dictionaries and Sets/shallow_deep_copy.py | 368 | 3.734375 | 4 | from contents import recipes
def my_deepcopy(d: dict) -> dict:
newDict = {}
for food in recipes:
newDict[food] = recipes[food].copy()
return newDict
recipes_copy = my_deepcopy(recipes)
recipes_copy["Butter chicken"]["ginger"] = 300
print(recipes_copy["Butter chicken"]["ginger"])
print(recipes["B... |
7b293b29bac2cdafe7e6aedf0f248f6eb96883ac | Jian-Yin-Shine/python_learn | /algorithm/st_split.py | 222 | 4.0625 | 4 | # 将序列分解为单独的变量
p = (4, 5)
x, y = p
print(x,y)
data = ['ACME', 50, (2019, 4, 10)]
name, price, date = data
print(name, price, date)
# 经常使用_作为丢弃的值
_, _, date = data
print(_, date)
|
64f025687f71660d12e5a67a9bf0d102c864a5a2 | Jian-Yin-Shine/python_learn | /language/st_yield.py | 908 | 4.0625 | 4 | # 在函数中也可以返回迭代器,用yield代替return, 这个函数就是生成器函数
def generater(n):
for i in range(n):
yield i*3
a = generater(10)
a = iter(a)
for i in a:
print(i, end=' ')
# 自定义可迭代对象中__iter__()返回正向可迭代对象
# __reversed__()返回反向可迭代对象, 就可以使用内置函数reversed()函数
# tips: a = Countdown(10) 返回一个可迭代对象
# iter(a) 为迭代器对象
# iter(a).next()即... |
ad1f62985df4db4495e74257710c5830c3bf3aa5 | Jian-Yin-Shine/python_learn | /language/st_decorators.py | 942 | 3.890625 | 4 | # 装饰器
# https://www.cnblogs.com/lianyingteng/p/7743876.html#undefined
# 实质: 是一个函数
# 参数:是你要装饰的函数名(并非函数调用)
# 返回:是装饰完的函数名(也非函数调用)
# 作用:为已经存在的对象添加额外的功能
# 特点:不需要对对象做任何的代码上的变动
def foo(f):
def wrapper(*args, **kwargs):
print('调用函数: ', f.__name__)
return f(*args, **kwargs)
return wrapper
@foo
def bar... |
239451ac834f8064612718a790b4640354e5ad21 | jaw653/NIL_Interns | /URLParser_2.py | 2,612 | 3.515625 | 4 | import csv
import sys
#Author: Austin Rife
#Date: 1-23-2018
#Description:
# This program parses a csv file exported from wireshark
# to output all URLs in the file.
#Running the program:
#python URLParser.py (filename.csv)
#Create a dictionary with the value being a count and the key being a URL
url_Dictionary = {}... |
2243ad7b29eb17a023876e1123827be859f0ea98 | Leonardo220389/Deber | /Deber1/Diapositiva/1.py | 423 | 3.78125 | 4 | # Numericos
edad,_peso = 32, 70.5
#String
nombres = "Leonardo Altamirano"
dirDomiciliaria = "Valdez y Emilio"
Tipo_sexo = "M"
#Boolean
civil = True
#Colecciones
usuario = ("laltamiranor", "1234", "laltamiranor@unemi.edu.ec")
materias = ["Programación Web", "PHP", "POO"]
estudiante = {"nombre":"Leonardo", "edad":32, "fa... |
71d46478c5d66c433f3fd8eee6190e651711417a | fengye-lu/Leetcode_test | /6. Z 字形变换.py | 1,485 | 3.5 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/9 16:58
# @Author : Jackey-lu
# @File : 6. Z 字形变换.py
'''
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1: return s
a = [[] for i in range(numRows)]
l = 0
cow_index = 0
row_index = 0
# row... |
2f0d807ac27b16fc83b4121811754a6357849b79 | fengye-lu/Leetcode_test | /最长回文子串.py | 1,698 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/2/27 20:27
# @Author : Jackey-lu
# @File : 最长回文子串.py
# class Solution:
# def longestPalindrome(self, s: str) -> str:
# length = len(s)
# result = str()
# for i in range(length):
# sum1 = str()
# sum2 = str()
# ... |
856595a3067dbdb900abc1ec48f18e7f280b0d29 | dreamoir/challenges | /PythonProjects/basic.py | 333 | 4.03125 | 4 | # This is a basic program that wqill ask the user for a number(interger)
# and print sum
i=int(input("please enter an integer: "))
sum=0
if int(i)-i == 0:
num=str(i)
else:
error('please enter an integer!')
for x in range (0,len(num)):
digit=int(num[x])
sum=sum+digit
print("+",digit)
print("total sum of digits... |
41801fad4b3a2693ff4dbf696e7e5fa6e86c9dfc | ignaciomgy/python | /Tests/LambdaYmapYfilter.py | 774 | 4.21875 | 4 | #MAP mapea una funcion definida sobre un conjunto de objetos
#FILTER aplica en una funcion sobre un conjunto y los filtra por la funcion aplicada
#ej defino las funciones a mapear y filtrar
def cuadrado(a):
return a**2
def pares(a):
return a%2==0
numeros = [1,2,3,4,5,6]
#pongo dentro de una lista el resultad... |
d00d1de2b1547fbfe024e6f4e72a5fe685e471aa | djytwy/twy | /tkinter/class_tkinter.py | 468 | 3.5625 | 4 | #from tkinter import *
import tkinter as tk
class APP():
def __init__(self, master):
frame = tk.Frame(master)
frame.pack()
self.button1 = tk.Button(frame, text='exit', fg='blue', command=frame.quit)
self.button1.pack()
self.button2 = tk.Button(frame, text='hello tk', fg='re... |
b103c6ab2b7da7afa2d7a0eea54180d7499aa8c5 | djytwy/twy | /tkinter/change_tkinter.py | 235 | 3.59375 | 4 | from Tkinter import *
root = Tk()
label = Label(root, text='hello world')
label.config(cursor='gumby')
label.config(width='80', height='10', fg='red', bg='blue')
label.config(font=('times', 28, 'bold'))
label.pack()
label.mainloop()
|
2c909408aaca2f7f98658cb2a89084b25d29031f | djytwy/twy | /Python基础/obser_style.py | 924 | 3.53125 | 4 | #encoding=utf-8
#被观察的对象:邮局
class Postoffice():
def __init__(self):
self.observes=[]
self.kanwu=''
def attach(self,observe):
self.observes.append(observe)
def notify(self):
for observe in self.observes:
observe.update()
#观察对象:出版社
class Press():
def __init__(s... |
6dba316d4f557bad6d4e67497cc7d12fa11db562 | innoventurist/Improving-Deep-Neural-Networks | /Regularization.py | 20,153 | 4.15625 | 4 |
# coding: utf-8
### Regularization
#
# Deep Learning models have so much flexibility and capacity that overfitting can be a serious problem, if the training dataset is not big enough.
# It may do well on the training set, but the learned network doesn't generalize to new examples that it has never seen.
#
# Goal: U... |
2d4b50cd6fdc920ce7dcda0f2a423612ed27a66b | ahmcpsc/Python- | /Lessons/WorkingWithNumbers.py | 4,532 | 4.46875 | 4 | # python numbers:
# Variables of numeric types are created when you assign a value to them:
x = 1
y = 2.8
z = 1j
print(type(x))
print(type(y))
print(type(z))
# 1. Int
# Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
x = 1
y = 35656222554887711
z = -325... |
ee9808eb2be3d2ff8b34533bdd97a5314421c67f | ahmcpsc/Python- | /Lessons/Sets.py | 6,956 | 4.53125 | 5 | #Python Sets:
#Sets are used to store multiple items in a single variable.
#Set is one of 4 built-in data types in Python used to store collections of data,
# the other 3 are List,Tuple, and Dictionary, all with different qualities and usage.
#A set is a collection which is both unordered and not indexed.
#Sets ar... |
5825dc97e88969cd84b4357a65dcb8b1f4f58662 | mikhael-oo/Chocolate-Scraping-with-BeautifulSoup-Codecademy | /wbscrap.py | 1,688 | 3.578125 | 4 | from bs4 import BeautifulSoup
import requests
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
url = requests.get('https://s3.amazonaws.com/codecademy-content/courses/beautifulsoup/cacao/index.html')
soup = BeautifulSoup(url.content, 'html.parser')
#print(soup)
tags = soup.find_all(attrs... |
8a6fbf074e42644751e6a44e2a59ff39cd89fcdf | amirbigg/python-design-patterns | /proxy.py | 897 | 3.96875 | 4 | """
Proxy
- a structural design pattern that lets you provide a substitute or placeholder
for another object. A proxy controls access to the original object, allowing you
to perform something either before or after the request gets through to the original object.
"""
import abc
import time
import datetime
class Ab... |
37f0c595785c7ee0ce9acc28e0f1ced2a176afcd | amirbigg/python-design-patterns | /singleton.py | 369 | 3.875 | 4 | """
Singleton
- Ensure a class only has one instance, and provide a global point of access to it.
"""
class Singleton(type):
_instance = None
def __call__(self, *args, **kwargs):
if self._instance is None:
self._instance = super().__call__()
return self._instance
class A(metaclass=Singleton):
pass
on... |
2bd9a7b9f85108ce2867bedfe0cd4fa14c3bfe2f | amirbigg/python-design-patterns | /chain of responsibility.py | 1,422 | 3.9375 | 4 | """
Chain of Responsibility
- a behavioral design pattern that lets you pass requests along a chain of handlers.
Upon receiving a request, each handler decides either to process the request or to pass
it to the next handler in the chain.
"""
import abc
class AbstractHandler(abc.ABC):
@abc.abstractmethod
def set... |
8d1e406e1d186984fe7c49aa17de310783e67d4d | organizar/organizar | /utils/TimeUtils.py | 2,535 | 3.84375 | 4 |
import time as tm
class Watch:
count = 0
description = "Stopwatch class object (default description)"
name = "not defined"
instances = []
def __init__( self, name = "not defined" ):
self.name = name
self.elapsed = 0.
self.mode = 'init'
self.starttime = 0.
se... |
12c9cc69a9a3ea45386cf4e11980635391b7ef27 | CaptainAlexey/learnpython_homeworks | /3rd_a.py | 99 | 3.703125 | 4 | user_string = input("Введите строку: ")
for letter in user_string:
print(letter)
|
906504a1a4bc4dd8b3febeeabaec3ad44ba1b7eb | srikii/810HW | /HW03_srikanth.py | 7,915 | 3.828125 | 4 | '''python program to perform mathematical operations and compare the fractions
author : srikanth'''
import unittest
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
if (self.denominator < 0): #if loop to c... |
289e4d6052e8e4a36cb02b3c1fd4b84b25b55d52 | srikii/810HW | /HW02_srikanth.py | 2,832 | 3.546875 | 4 | '''python program to perform basic mathematical operations on fractions
author : srikanth'''
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
if self.denominator <= 0 : #check if divide by zero
ra... |
41e15ad7b305a2b3e0e11948b91b9f64ca163faf | zhuwenger/project_euler_solutions | /problem_23/problem_23.py | 629 | 3.515625 | 4 | #!/usr/bin/env python
border = 28123
def seq_sum(n):
return n * (n + 1) / 2
def get_divisors(n):
divisors = []
for i in range(1, n / 2 + 1):
if n % i == 0:
divisors.append(i)
return divisors
def is_abundant(n):
return sum(get_divisors(n)) > n
abundant_list = filter(is_abundant, [x for x in range(1, bor... |
fde02de917e90c680d456ad92088aede7c12f6bb | huebschwerlen/Python | /Python_Review/passing_funcs_lambdas.py | 794 | 4 | 4 | def methodception(another):
return another()
def add_two_numbers():
return 35 + 77
methodception(add_two_numbers)
###
methodception(lambda: 35 + 77)
my_list = [13, 56, 77, 484]
print(list(filter(lambda x: x != 13, my_list))) # A lambda function is just a short, one-lin... |
1f3df27ac8ef1f9d2f5e628f2917132301c28c96 | vidyavani/python-programs | /pattern.py | 164 | 3.59375 | 4 | n=int(input())
i=1
list=[]
while(i<n+1):
list.append(i)
list.append(-n)
i=i+1
n=n-1
list.pop()
for i in list:
print(i,end=" ")
|
c9603f42b945924fe72cdcf60349ebc0775518cf | ErdemOzgen/leetcode | /python/212-Word-Search-II.py | 1,729 | 3.59375 | 4 | class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
self.refs = 0
def addWord(self, word):
cur = self
cur.refs += 1
for c in word:
if c not in cur.children:
cur.children[c] = TrieNode()
cur = cur.chil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.