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 |
|---|---|---|---|---|---|---|
33ba04c4c59b0e51ef8f8e5acd62f2cffb9e05bb | AricA05/Python_OOP | /encapsulation.py | 1,480 | 4.34375 | 4 | #4.Encapsulation
'''It is the concept of wrapping data such that the outer world has access only to exposed properties.
Some properties can be hidden to reduce vulnerability.
This is an implementation of data hiding.
For example, you want buy a pair of trousers from an online site.
The data that you want is its cos... |
6e41079607878e8ec7250a195945c19d1550d89b | NhutNguyen236/Code-challenges | /hackerEarth/Monk and Rotation/monk_and_rotation.py | 1,068 | 3.640625 | 4 | # Link: https://www.hackerearth.com/practice/codemonk/
# Input: T - Number of testcases(also the number of input array), N - number of input integers, K - number of times to rotate
# Output: an rotated array
# The problem here is that 10 test cases will be repeated by the exact input of N, K and the array
from time ... |
bf74c26130119120dfc2f6c97a78882d81c19f90 | dansackett/learning-playground | /python/pythonchallenge-solutions/3.py | 231 | 3.8125 | 4 | import re
with open('3.txt') as file:
string = file.read()
with open('/usr/share/dict/words') as file:
dict = set(file.read())
matches = re.findall('[^A-Z]+[A-Z]{3}([a-z])[A-Z]{3}[^A-Z]+', string)
print ''.join(matches)
|
f7c22e308aa4f6903129e8b7d76842ff5c830e14 | dansackett/learning-playground | /project-euler/problem_1.py | 321 | 4.25 | 4 | #!/usr/bin/python
"""
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
limit = 1000
print sum(x for x in xrange(limit) if not x % 3 or not x % 5)... |
6aa2cfcfcad24d4ddcaee43b996456025c157924 | dansackett/learning-playground | /python/python-cookbook/chapter_3/code/numbers_example.py | 1,371 | 3.96875 | 4 | """
Rounding
"""
print(round(1.23, 1))
print(round(1.27, 1))
print(round(-1.27, 1))
print(round(-1.25432, 3))
a = 1627731
print(round(a, -1))
print(round(a, -2))
print(round(a, -3))
"""
Decimals
"""
from decimal import Decimal, localcontext
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b)
print((a + b) == Decimal('... |
410cce6e0377a4f1dca9ef25749f462aead8c5a6 | adichills/Northeastern_Projects | /Hacker_Rank/Detect_Cycle_In_Linked_List.py | 1,158 | 4.09375 | 4 | '''\
A linked list is said to contain a cycle if any node is visited more than once while traversing the list.
Complete the function provided in the editor below.
It has one parameter: a pointer to a Node object named that points to the head of a linked list.
Your function must return a boolean denoting whether or not... |
365c76d8d2550262e86f8371d84aa14b70b74018 | adichills/Northeastern_Projects | /Hacker_Rank/Anagrams.py | 1,343 | 3.828125 | 4 | '''
Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacd... |
97c981af26a950a02568b8e8b10d2288354e70fc | fireinjunstudent/Data-Structures | /linked_list/linked_list.py | 2,575 | 3.828125 | 4 | """
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
### Linked Lists
# ? Should have the methods:
# * add_to_tail
# * remove_head
# * contains
# * get_max
# add_to_tail replaces the tail with a new value that is passed in.
# remove_head removes... |
9772635be6884b6cc98ff8ca3af8cc8f5bbf35a3 | Number1788/Python | /tutorial/cycle/while.py | 1,876 | 3.953125 | 4 | # Симулятор трехлетнего ребенка
# Демонстрирует работу цикла while
print("\tДoбpo пожаловать в программу 'Симулятор трехлетнего ребенка'\n")
print("Имитируется разговор с маленьким ребенком.")
print("Попробуйте остановить этот кошмар.\n")
response = ''
while response != "Потому что":
response = input("Почему?\n")
p... |
0354a62971df05b02b9c30824b5e29ce2f967c70 | Number1788/Python | /tutorial/lists/1.py | 3,934 | 3.96875 | 4 | L=[123,'123',1.23]
print(len(L)) #Длина строки
print(L[0]) #Возвращаем элемент по индексу
print(L[:1]) # делаем срез до второго элемента
print(L + [4,5,6]) # контатация сторк
print(L)
print(len([1,2,3])) ... |
d493dab665c1ec85de31eef74ffd114ecbfb7244 | sumanthp/Tensorflow-PredictHousePrices-Regression-Gradient-Descent | /Tensorflow-Demo.py | 6,339 | 3.609375 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math
# from tensorflow.examples.tutorials.mnist import input_data
# mnist=input_data.read_data_sets('MNIST_data',one_hot=true)
# def Train_size(num):
# print('Total Training images in dataset... |
e7977a734f29dca3121ea9a5a2a4c8d1294ce3bf | jose-brenis-lanegra/T10_Brenis.Niquen | /Menu08.py | 1,020 | 3.59375 | 4 | # mostrar algunos instrumentos musicales segun su clasificacion
import libreria
def Mostrar_Viento():
a=libreria.pedir_listas("viento.txt")
print("Los instrumentos de viento son:", a)
def Mostrar_Cuerda():
b=libreria.pedir_listas("cuerda.txt")
print("Los instrumentos de cuerda son:", b)
def Mostrar_... |
c7280fee28d40ec39da63e6107867d5c631d4ba8 | charlie83cl/funciones_basicas_i | /bucles.py | 578 | 3.59375 | 4 | #EN ESTE EPISODIO USAERMOS BUCLES
# UN BUCLE ES UN ESTRUCTURA DE CODIGO QUE ME PERMITE REPETIR
# UN BLOQUE DE CODIGO EN LA N CANTIDA DE VECES RECORRER UNA LISTA
#while
respuesta = 's'
contador = 0
while contador <= 2:
try:
edad = int(input(f"Ingrese su Edad en Numeros. Intento Nro.{contador}: "))
... |
f907640b0bc293d1d3fea7fc88489fa7ac2a7713 | charlie83cl/funciones_basicas_i | /primos.py | 548 | 3.59375 | 4 |
def sumar (a,b):
r = a + b
return r
def primos(a,b):
primos =[]
for num in range(a, (b + 1)):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
primos.append(num)
return primos
num1 = int(input("... |
7449ccb219229cfe5a956c1ef7ceaa5da2422b7d | Liz04/progres | /exercice1/server.py | 1,190 | 3.65625 | 4 | import socket
import sys
import utils
def server(server_port=1235):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('', server_port))
server_socket.listen(1)
print("Server ready...!")
connection_socket, address = server_socket.accept()
while True:
... |
d01b142a983b9c682f5412d7c504b642fd847cd3 | adimukh1234/python_projects | /hangman1.py | 871 | 4.125 | 4 | import random
name = input("What is your name?\n")
print("Hello ", name)
print("Welcome to the Hangman Game \nBest of luck")
words = ["balloon", "hook", "octopus", "communication", "piano", "honey", "playstation"]
guesses = ''
word = random.choice(words)
print("Guess the characters!")
turns = 6
# main ... |
ca8a612e654795d55625e199997945549b713a1c | untalinfo/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 296 | 4.34375 | 4 | #!/usr/bin/env python3
"""
Basic annotations - to string
"""
def to_str(n: float) -> str:
"""takes a float n as argument and returns the string representation
of the float
Args:
n (float): number
Returns:
str: convert float to string
"""
return str(n)
|
d20a07ad9e1e311b21a9a52c0011657850fc4da6 | portypy/Rock_Paper_Scissors | /app/modules/game.py | 688 | 3.71875 | 4 | import random
import pdb
class Game():
def game(self,player1_choice,player2_choice):
if player1_choice == player2_choice:
return "Draw"
elif player1_choice == "rock" and player2_choice == "paper":
return "Paper wins over rock"
elif player2_choice == "rock" and ... |
a16d910dad34c229805ed9875e638a077216b788 | StarTux/DailyCodingProblem | /003-2019-03-07-TreeSerialize.py | 1,154 | 4.125 | 4 | #!/usr/bin/python3
# Problem #3 [Medium]
# Given the root to a binary tree, implement serialize(root),
# which serializes the tree into a string, and deserialize(s),
# which deserializes the string back into the tree.
#
# For example, given the following Node class
class Node:
def __init__(self, val, left=None,... |
48b627584ab02e091132fb31ee9e963b9caa4572 | StarTux/DailyCodingProblem | /020-2019-03-24-LinkedListIntersection.py | 1,949 | 3.875 | 4 | #!/usr/bin/python3
# Problem #20 [Easy]
# This problem was asked by Google.
# Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
# For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
# In this example, assum... |
0aebab530dfa54a10e1d98bd2ba6ad0458f85b2b | jp117/codesignal | /Arcade/Intro/010 - commonCharacterCount.py | 804 | 4.125 | 4 | '''
https://app.codesignal.com/arcade/intro/level-3/JKKuHJknZNj4YGL32
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
Input/Output
[execution... |
1edbcf09655272d63213d4722b568964a9dde0b0 | jp117/codesignal | /Arcade/Intro/006 - makeArrayConsecutive2.py | 1,296 | 3.859375 | 4 | '''
https://app.codesignal.com/arcade/intro/level-2/bq2XnSr5kbHqpHGJC
Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will ... |
c3a961ca9ca84e7b2e4cd713b740cfa51b946056 | jenyu7/09_sqlite | /db_builder.py | 1,591 | 3.53125 | 4 | '''
Jen Yu
HW #09: No Treble
Software Development Pd7
2017-10-15
'''
import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
f="discobandit.db"
db = sqlite3.connect(f) #open if f exists, otherwise create
c = db.cursor() #facilitate db ops
#====================================... |
a024b6ba4b21ce74464f5ba07689d0cf7a319c2f | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/12-learning_rate_decay.py | 1,229 | 4.03125 | 4 | #!/usr/bin/env python3
"""
Learning rate decay operation in tensorflow
"""
import tensorflow as tf
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""
Updates the learning rate using inverse time decay in numpy
Args:
alpha: is the original learning rate
decay_rate: is... |
66ed4319b4f0728429430c657c9e381c5ee57e95 | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x02-tensorflow/2-forward_prop.py | 883 | 3.953125 | 4 | #!/usr/bin/env python3
"""
Contains a function to create the forward propagation graph for the neural
network
"""
import tensorflow as tf
create_layer = __import__('1-create_layer').create_layer
def forward_prop(x, layer_sizes=[], activations=[]):
"""
Creates the forward propagation graph for the neural ne... |
f135ed7ee98274de5b48923f9677e11344c630bc | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/9-Adam.py | 1,196 | 3.765625 | 4 | #!/usr/bin/env python3
"""
Adam optimization Algorithm
"""
import numpy as np
def update_variables_Adam(alpha, beta1, beta2, epsilon, var, grad, v, s, t):
"""
Updates a variable in place using the Adam optimization algorithm:
Args:
alpha: is the learning rate
beta1: is the momentum we... |
14c11a27484edf19581bca75d54f84ad101b16c0 | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x04-error_analysis/1-sensitivity.py | 736 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Calculates sensitivity in a confusion matrix
"""
import numpy as np
def sensitivity(confusion):
"""
Calculates the sensitivity for each class in a confusion matrix
Args:
- confusion: is a confusion numpy.ndarray of shape (classes, classes)
where row indices... |
40af5eb5fdff198ec67908ea65efc14a5740e2e6 | emmanavarro/holbertonschool-machine_learning | /supervised_learning/0x06-keras/1-input.py | 1,469 | 3.765625 | 4 | #!/usr/bin/env python3
"""
Input
"""
import tensorflow.keras as keras
def build_model(nx, layers, activations, lambtha, keep_prob):
"""
Builds a neural network with the Keras library
Args:
- nx: is the number of input features to the network
- layers: is a list containing the number of no... |
4f729792f482ec11beaa209697c8f3dac2b913d6 | emmanavarro/holbertonschool-machine_learning | /math/0x04-convolutions_and_pooling/1-convolve_grayscale_same.py | 1,752 | 3.78125 | 4 | #!/usr/bin/env python3
"""
Same convolution
"""
import numpy as np
def convolve_grayscale_same(images, kernel):
"""
Performs a valid convolution on grayscale images
Args:
- images is a numpy.ndarray with shape (m, h, w) containing multiple
grayscale images:
:m: is the number... |
2abb33f2ee8e358de39d18afe1f7688aa6330bdf | deepika-13-alt/Python-Assignment | /test/pattern1.py | 455 | 4.03125 | 4 | '''
print the following
0
1 0
0 1 0
1 0 1 0
'''
def patt_print():
n=int(input("please enter range to print pattern"))
for row in range(1,n+1):
for col in range(1,row+1):
if(row+col)%2==0:
print(0,end=" ")
elif(row+col)%2!=0
print(i,ends" ")
else:
print(" ... |
47343978488c706d01d9aae0759a6db216e6be11 | deepika-13-alt/Python-Assignment | /assignment1/si.py | 481 | 4 | 4 | '''
Q.Write a program to calculate simple interest for a given principal, rate of interest,and time. [Formula: I=P*t*i].
'''
principal = float(input("Enter the principal amount: "))
time = float(input("Enter the tenure in years: "))
rate = float(input("Enter the rate of interest % per annum: "))
si = principal*time... |
03061b2fc0160e3978a9dc462b912fcffc558642 | deepika-13-alt/Python-Assignment | /assignment4/perfect_no.py | 766 | 4.03125 | 4 | '''
Program: Write a program using function to determine whether a number is a perfect number. A natural number is said to be
a perfect number if it is the sum of its divisors. [6=1+2+3]
'''
def checkPerfect(num):
list_divisor = []
sum = 0
for i in range(1, num):
if num % i == 0:
list_d... |
a1e5f6b0404ae16c57c5c5261fca9a9ed962d14c | deepika-13-alt/Python-Assignment | /assignment3/pattern1.py | 757 | 4.09375 | 4 | '''
wap to print the following using loop.
* AAA AAAAA
** AA AAAA
*** A AAA
**** AA
A
'''
# Pattern 1
def pattern1():
num = int(input("Enter a number: "))
for row in range(1, num+1):
for col in range(1, row+1):
print('*', e... |
30f5b94defb435a4bb6d98c51b865b46446ef48c | deepika-13-alt/Python-Assignment | /assignment2/second_smallest.py | 1,087 | 4.34375 | 4 | '''
Program: WAP to input 3 numbers and find the second smallest.
'''
import re
# Declarations
regex_float = '[+-]?[0-9]+\.[0-9]+'
regex_int = "[-+]?[0-9]+$"
small_list = []
small_1 = 0
small_2 = 0
# Taking input from users
print("Enter 3 numbers for finding smallest among them")
for i in range(3):
inp = input("... |
248b398e2d84d812ab7dea2614e296faeeae20cd | deepika-13-alt/Python-Assignment | /assignment5/two_list.py | 305 | 4.125 | 4 |
'''
Concatenate two lists in the following order
Input: L1=[1,2]L2=[4,5]
Output: L3=[(1,4),(1,5),(2,4),(2,5)]
'''
l1 = [1,2]
l2 = [4,5]
print("Original list 1: ", l1)
print("Original list 2: ", l2)
l3 = []
for i in l1:
for j in l2:
tup = (i,j)
l3.append(tup)
print("Output: ", l3) |
0ab310466fc993fc1c68a99c0b7969c110670a0c | schinhsu/cupoy11001 | /day2.py | 309 | 3.6875 | 4 | import numpy
# 題目:
# 1.將下列陣列(array1),轉成維度為(5X6)的array,順序按列填充。(hint:order="F")
array1 = numpy.array(range(30))
array = array1.reshape((5, 6), order='F')
print(array)
# 2.呈上題的array,找出被6除餘1的數的索引
b = numpy.where(array % 6 == 1)
print(b)
|
538792c0ac5f4e0073d02367931e0aa1394ebecd | mightykim91/algorithm_and_data_structure | /quicksort.py | 635 | 3.90625 | 4 | def quickSort(array, left, right):
if left >= right:
return
pivot = array[(left+right)//2]
index = partition(array, left, right, pivot)
quickSort(array, left, index-1)
quickSort(array, index, right)
def partition(array, left, right, pivot):
while (left <= right):
while (array[l... |
a1886c1da210be82c9f7662e8bb7b3e65fa898d0 | SomeClown/Jackanapes | /app/stuff.py | 1,244 | 3.5625 | 4 | #!/usr/bin/env python3
__author__ = 'SomeClown'
__license__ = "MIT"
__maintainer__ = "Teren Bryson"
__email__ = "teren@packetqueue.net"
class myFile(object):
def __init__(self, myfilename: object, myflag: object, mycontents: object) -> object:
self.myfilename = myfilename
self.myflag = myflag
... |
de75908b25e0af3fb5662612188b63e73428a6d9 | dbrizan/MSAN-NLP | /test-person.py | 795 | 3.734375 | 4 | '''
I use the "person" class... and print using that.
'''
from person import person
#
# Main
#
if __name__ == '__main__':
# Create a person named "Guido".
guido_name = {'f': 'Guido', 'last': 'van Rossum'}
guido = person(guido_name)
# Add to Guido's bio.
guido.add_to_bio('1956: Born in the Netherla... |
de54527ff137b208270c335b4a00775f439a3092 | ErvinCs/FP | /Lab05-09-Library/src/domain/IterableModule.py | 4,169 | 3.671875 | 4 | from copy import deepcopy
class IterableEx:
def __init__(self, start, end):
self.start = start - 1
self.end = end - 1
def __iter__(self):
#Called at the start of loops
return self
def __next__(self):
#Called at each loop increment
if self.start > self.end:
... |
d7a3829ee80b6eb449cdb006bf26d4add0cc4c82 | ErvinCs/FP | /Lab05-09-Library/src/domain/Book.py | 1,845 | 3.609375 | 4 | class Book:
bookIterator = 0 #bookId generator
def __init__(self, title, description, author):
'''
Sets bookId using the bookIterator
:param title, description, author: strings
'''
self.__bookId = Book.bookIterator
Book.bookIterator += 1
self.__title = ti... |
3854b35adf018c60540c42f62c9b34972151a815 | Sipa91/Streamlit_dashboard | /Home.py | 2,330 | 3.734375 | 4 | #Underpage1
import streamlit as st
from PIL import Image
def page():
st.title('Apply or not to apply')
st.subheader('A machine learning approach to predict the appealingness of job ads for female applicants*')
image = Image.open('Images/Intro.jpg')
st.image(image, use_column_width=True)
st.write("... |
846aa33d9b9f27164d386266161e575a8c705405 | gqxjones/hogwartsThree | /pythonGame.py | 1,207 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
一个回合制游戏,每个角色都有hp 和power,
hp代表血量,power代表攻击力,hp的初始值为1000,
power的初始值为200。打斗多个回合
定义一个fight方法:
my_hp = hp - enemy_power
enemy_final_hp = enemy_hp - my_power
谁的hp先为0,那么谁就输了
"""
from random import randint
from time import sleep
def fight():
my_hp = 1000
my_power = r... |
fa94b2127ee33769ebf6710c62e76b75bb89a48d | dbms-ops/hello-Python | /1-PythonLearning/9-多任务/3-生产者与消费者模型/1-生产者-消费者.py | 1,053 | 3.796875 | 4 | # -*-coding:utf-8-*-
# !/data1/Python2.7/bin/python2.7
# 生产者与消费者模型:
# 通过队列来实现消费者和生产者模型
#
import Queue
import random
import threading
import time
def producer(i, q):
for I in range(10):
num = random.randint(0, 1000)
q.put(num)
print "producer: {} product {} put in queue".format(i, num)
... |
41d3941aa20d24dd298d89bd0d0578cac6f0bc36 | dbms-ops/hello-Python | /1-PythonLearning/3-Python-基础知识/3-字符串.py | 1,465 | 3.65625 | 4 | # !/data1/Python2.7/bin/python2.7
# -*-coding:utf-8-*-
# date: 2020/1/16 16:57
# user: Administrator
# description: 常见数据类型:字符串介绍
#
#
# 字符串
# 字符串是单引号或者双引号引用的任意文本
# 引号本身并不属于字符串内容
#
def Create_string():
# 字符串创建
proverb1 = "see it all"
proverb2 = "Love is a carefully designed lie"
print proverb1, prover... |
992aeac8134a8ba27f8bed97c85a473a6760978f | dbms-ops/hello-Python | /1-PythonLearning/1-Python学习/5-字符串函数.py | 891 | 3.953125 | 4 | #!/data1/Python2.7/bin/python27
# -*-coding:utf-8-*-
# time: 2020-01-24 10:21
# user: linux
# description: 字符串函数
#
#
from __future__ import print_function
print('你好')
print('112')
string = "hello,world"
# isspace():用于判断是否是空白字符
name = 'hello, are tom'
i = 0
while i < len(name):
if name[i].isspace():
print... |
15125946987e4d6c06ce9c30982b15f5342ef7f8 | dbms-ops/hello-Python | /1-PythonLearning/9-多任务/4-协程/3-生产者与消费者.py | 733 | 3.640625 | 4 | #
# -*-coding:utf-8-*-
# !/data1/Python2.7/bin/python27
# time: 2020-01-18 14:35
# user: linux
# description: 利用协程来实现生产者与消费者模型
#
def producer(c):
c.send(None)
n = 0
for i in range(5):
print "Producer produces data: {}".format(i)
# send 需要发送的是一个字符串,而不是一个整数类型
r = c.send(str(i))
... |
2a1bf9fcc9abb1631922937e7eb7e5f2b96e3ca2 | dbms-ops/hello-Python | /1-PythonLearning/7-面向对象/11-运算符重载.py | 454 | 4.0625 | 4 | # coding=utf-8
#
#
# !/data1/Python2.7/bin/python27
#
# 运算符重载
#
#
print 1 + 2
print "1" + "2"
class Person(object):
def __init__(self,num):
self.num = num
# 运算符重载
# 对象相加,默认执行__add__运算
def __add__(self, other):
return Person(self.num + other.num)
def __str__(self):
retu... |
726db70c7cca49422f9edeefc1edf51d3b09cc1d | dbms-ops/hello-Python | /1-PythonLearning/3-Python-基础知识/10-数据结构-集合.py | 2,009 | 4.125 | 4 | # !/data1/Python2.7/bin/python2.7
# -*-coding:utf-8-*-
# date: 2020-1-16 16:57
# user: Administrator
# description: set 的常见操作
#
# set:
# 无序和无重复的list
# 1、set的对象不能够是可变对象,字典、列表是不能够添加的,但是元组是可以的
def create_set():
# 创建set
# 创建set 通过list或者tuple或者dict作为输入集合
# set 可以用于 list tuple,dict元素的去重操作
num = set([1,... |
973d55a382f5a2c127655e4f672f6b7c2743ee1c | dbms-ops/hello-Python | /1-PythonLearning/7-面向对象/7-多继承.py | 1,104 | 4.40625 | 4 | # coding=utf-8
#
#
# !/data1/Python2.7/bin/python27
#
#
# 多继承:表示子类继承自多个父类
# Father <<<------- Child
# Mother <<<------- Child
# 声明 Fahter
class Father(object):
def __init__(self, pocket):
self.pocket = pocket
def play(self):
print "play son"
def func(self):
print "func"
# ... |
ff5d1e1e6d8a69ec7f01c90b8873a7cd8f4573d7 | allchanzi/TspGa | /Parser.py | 466 | 3.5 | 4 | import csv
class Parser():
def __init__(self, file):
self.coords=[]
coords = []
with open(file) as csv_file:
reader = csv.reader(csv_file, delimiter=',')
coords = list(reader)
print(coords)
for i in coords:
self.coords.app... |
f46a7d811e6d3f8044ad4e9b425b0bd4166c9b67 | dhurng/LeetCode | /Sorts.py | 2,737 | 3.96875 | 4 | """
Popular Sorting Algorithms
"""
import time
def main():
sorter = Sorter()
start = time.time()
list = [3, 2, 5, 1, 4, 0]
class Sorter(object):
def __init__(self):
pass
def merge_sort(self, nums):
# basic merge sort
self.merge_sort_helper(nums, 0, len(nums) - 1)
de... |
7a78dab8963bf919849939d4d6364a1662bb881e | jedrzejd/PO-semestr-2 | /lesson_11/main.py | 741 | 3.5625 | 4 | class Stos:
def __init__(self, maxsize):
self.arr = []
self.maxsize = maxsize
def pop(self):
try:
self.arr.pop()
except Exception as e:
print(e)
def push(self, item):
try:
assert (len(self.arr) < self.maxsize)
self.arr... |
31bdfa043482f2dc10dc2adb24c92e1fdc10c206 | jerrywu64/morsetrainer | /modules/listen.py | 4,155 | 3.5 | 4 | import random
import utils
import time
import quiz
import threading
def printStartText():
print "Welcome to Listen Mode!"
print "Listen Mode is like Quiz Mode except you will only translate"
print "from Morse to English, and you will hear beeps instead of"
print "seeing a visual representation of the M... |
d4d9080118052f588f983eda5905295b9234f902 | diegochav/Herramientas | /holapython.py | 1,580 | 4.0625 | 4 | import math
def cal():
print("\n\nCALCULADORA\n 1:Suma\n 2:Resta\n 3:Multiplicacion\n 4:Division\n 5:Exponencial\n 6:Funcion Coseno\n 7:De grados a radianes\n 10:Salir\n")
valor = int( input("escriba una opcion: "))
if(valor == 1):
numero1 = int(input("Escriba un numero: "))
numero2 = int(input("Escriba otro n... |
b72613da1ea7477258c44a11299bcdb8f3a4ff88 | yuan201/Algorithms | /heapsort.py | 1,717 | 3.75 | 4 | import sys
def max_heapify(heap, i):
l=left(i)
r=right(i)
heapsize = len(heap)
if l < heapsize and heap[l] > heap[i]:
largest = l
else:
largest = i
if r < heapsize and heap[r] > heap[largest]:
largest = r
if largest != i:
heap[i], heap[largest] = heap[largest... |
88357992358b120b9427fa663c75fe92faa010aa | nmh-dee/Python-for-everybody-coursera | /Using Python to Access Web Data/Extracting Data from JSON.py | 809 | 3.921875 | 4 | # The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and
# extract the comment counts from the JSON data, compute the sum of the numbers in the file
'''
Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553)
Actual data: http://py4e-data.dr-chuck.net/comment... |
f35b008351ae5a60a306fa986028003df3b1a859 | apeete/RPProjects | /exponent.py | 389 | 4.03125 | 4 | first = raw_input("Enter a base:")
second = raw_input("Enter an exponent:")
solution = int(first) ** int(second)
print "{} to the power of {} = {}".format(first, second, solution)
def square(number):
"""Return the result of input number to
the power of 2."""
sqr_num = number ** 2
return sqr_n... |
3f4041a095ebbfb7e4881a5a703294c1530bc0a0 | AtulCoder01/Programming-Notes | /Python/hello.py | 344 | 3.9375 | 4 | #Default argument
def add(a, b=5):#b is default value of zero
return a+b
print (add(2))
#####################################################################################################
def foo(i, a=[0]):
a.append(i)
return a
'''
z=[]
print (foo(1,z))
print (foo(2,z))
print (foo(3,z))'''
print (foo(1))
print ... |
a8eb94b4b57a9893fdb0e265a32081101072a78e | AtulCoder01/Programming-Notes | /Python/raw_input.py | 132 | 3.921875 | 4 | #raw Input
#python 2: raw_input
#python 3: input
#r=raw_input('Enter Your Name:')
s=input('Enter Your Name:')
print ('Good Morninig:\n',s)
|
9c9583973533a1e23377a6bea33c3c66d89b0689 | AtulCoder01/Programming-Notes | /Python/readFile.py | 131 | 3.515625 | 4 | #reading file
#open(filename,mode)
f = open("atul.txt", "r")
#file is asequnce of line
for i in f:
print (i,end='')
f.close()
|
2be7758469498d80c2c2d865c7e7dceae1f2a922 | AtulCoder01/Programming-Notes | /Python/regularSearch.py | 121 | 3.640625 | 4 | import re
s='abc.xyz@d.com'
p=re.search('\w+\.*\w*@\w+\.\w+',s)
if p:
print 'found email:',p.group()
else:
print 'not found'
|
216e04cf7cea8146ba56d418232ebf903732eacc | ZamoraAlexey/hillel_lessons | /lesson11.3.py | 623 | 4.03125 | 4 | import re
entered_password = input("Enter your password")
password = True
while password:
if len(entered_password) <= 8 or len(entered_password) > 16:
break
elif not re.search('[a-z]', entered_password):
break
elif not re.search("[0-9]", entered_password):
break
elif not re.sea... |
e0bca1e1bf571a39dad643ccd0485b6be44fa473 | ZamoraAlexey/hillel_lessons | /lesson7.py | 1,123 | 4.1875 | 4 | def calculate_of_numbers():
first_number = int(input('Enter your first number: '))
second_number = int(input('Enter your second number: '))
choice_function = input('Choice your function (+, -, /, //, *, **, %): ')
if choice_function == '+':
print(f'{first_number} + {second_number} =', first_nu... |
ee5c36be93c0d19303731f99c64e5bc5d21e7c91 | junhaideng/tkinter | /main.py | 7,105 | 3.578125 | 4 | # coding:utf-8
"""
Author: Edgar
"""
from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
import json
# 创建主窗口
window = Tk()
window.title("Welcome")
window.geometry("500x400")
window.resizable(width=False, height=False)
# 首页的图片
image = Image.open("./welcome.jpg")
img = I... |
debb6045891c28d4d5764c282d02b92f7ff5b251 | EricHoo1998/PythonStudy | /Unit5/OnLineWorks/p2.py | 1,473 | 4.09375 | 4 | '''
连续质数计算
描述
补充编程模板中代码,完成如下功能:
获得用户输入数字N,计算并输出从N开始的5个质数,单行输出,质数间用逗号,分割。
注意:用户输入的数字N可能是浮点数,都是正数;最后一个输出后不用逗号。
'''
def prime(m)... |
c265226d8ab472866038dd6d5c75352108492118 | EricHoo1998/PythonStudy | /Unit1/HomeWorks/P2.py | 4,319 | 3.859375 | 4 | '''
温度转换 II
描述
温度的刻画有两个不同体系:摄氏度(Celsius)和华氏度(Fahrenheit)。
请编写程序将用户输入华氏度转换为摄氏度,或将输入的摄氏度转换为华氏度。... |
3213979c6bced8add2f33075f9860e77564601ad | EricHoo1998/PythonStudy | /Unit5/OnLineWorks/p1.py | 1,097 | 3.5 | 4 | #key
'''
随机密码生成
描述
补充编程模板中代码,完成如下功能:
以整数17为随机数种子,获取用户输入整数N为长度,产生3个长度为N位的密码,密码的每位是一个数字。每个密码单独一行输出。
产生密码采用random.randint()函数。
... |
890ac255c3b3f644e01d8ccefd0702a60d5a75be | caoxm-me/.PythonChallenge | /06/061.py | 849 | 3.890625 | 4 | #! /usr/bin/python
import re
import zipfile as z
zf=z.ZipFile('channel.zip','r')#打开zip文件包channel.zip, ZipFile是一个python类型,这里相当于构造了一个ZipFile对象
zipnames=zf.namelist()#ZipFile对象有方法,getinfo(),namelist(),open()
#print(zipnames) #会看到这个zip压缩文件里面有很多xx.txt的文件
filename=zipnames[0]#第一个文件名
# print(i) #i is the element of... |
ac8c8e99d248797dcbd4dd9611225c3092fff17b | mkcbe/python | /vrc.py | 344 | 4.03125 | 4 | a=input()
ascii=ord(a)
if (65<=ascii)and(ascii<=90):
if(a=='A')or(a=='E')or(a=='I')or(a=='O')or(a=='U'):
print("Vowel")
else:
print("Consonant")
elif(97<=ascii)and(ascii<=122):
if(a=='a')or(a=='e')or(a=='i')or(a=='o')or(a=='u'):
print("Vowel")
else:
print("Consonant")
els... |
de1224f6d8992b4893fe29f63388629c3cec28b9 | michaelstiefel/Project_DataWarehouse | /.ipynb_checkpoints/create_tables-checkpoint.py | 1,588 | 3.578125 | 4 | import configparser
import psycopg2
from sql_queries import create_table_queries, drop_table_queries
def drop_tables(cur, conn):
"""
This function executes sql queries in order to
delete tables that might exist from an earlier call to create tables.
Input:
- cursor object which interacts with... |
9ea111f75ba5c9ceb956b78c3ac9f70fdf69540d | tachyonlabs/raspberry_pi_pyladies_presentation | /hello_world_blink.py | 1,566 | 4.28125 | 4 | # See https://github.com/tachyonlabs/raspberry_pi_pyladies_presentation
# for information on the wiring and the presentation in general
# The Rpi.GPIO library makes it easy for your programs to read from and write to
# the Raspberry Pi's GPIO (General Purpose Input/Output) pins
import RPi.GPIO as GPIO
import time
# G... |
45ef0152b3ec8e1c4871e2d339c49fc89637022e | christopherward/week2 | /solution_10.py | 1,501 | 4.03125 | 4 | #Christopher Ward
#MPCS 50101, Winter 2015
#Homework 2, Solution 10
def main():
#ask user for location of mileage data
try:
filename = input("\nIn which file are the travel data located? ")
infile = open(filename,'r')
#initialize variables to hold MPG data
miles = []
g... |
7af07053a6c7e2da6b4f37fa9d0c308d933d1b02 | sureshyhap/Introduction-to-Computer-Science-and-Programming-Using-Python-6.00.1x | /Week 1/Problem Set 1/1/1.py | 172 | 3.921875 | 4 | # s = 'azcbobobegghakl'
VOWELS = ('a', 'e', 'i', 'o', 'u')
num_vowels = 0
for c in s:
if c in VOWELS:
num_vowels += 1
print("Number of vowels:", num_vowels)
|
caac5290530594af0055a0c3330ca6376eb1d48a | puneetchopra16/advanced-topics | /adv.topics.py | 914 | 3.78125 | 4 | from math import *
#question1
li=[1,2,3,4,5]
m=[i**3 for i in li]
print(m)
#question2
list=[x for x in range(2, 20)
if all(x % y != 0 for y in range(2, x))]
print(list)
#question3
'''
In terms of syntax, the only difference is that you use parenthesis instead of square brackets.
The type of data returned ... |
36b96ede8bb19efe620df180e8ce6cff509a6812 | agSant01/operating-systems-course | /lecture-7-deadlocks/bankers-algorithm.py | 3,566 | 3.890625 | 4 | """
Bankers Algorithm is a deadlock avoidance algorithm used to allocate resources in a system
where multiple instances of a resource type exists.
This algorithm is not very efficient, but it accomplished the goal of ensure that the system can satisfy the
request of multiple processes without deadlocks, as long as ... |
9b6630a266362864a4ca927cf38eadf455147b34 | Michael-png/olympiad-python-lvl-3 | /Test Question Three.py | 168 | 3.75 | 4 |
def printMessage(message, name = "Anonymous"):
for x in message:
print("<" + name + "> : " + "<" + message + ">")
printMessage(message = "I love chicken")
|
bc7e5ab60e4bc53aef04f7394bb7fed171ab9c9b | Michael-png/olympiad-python-lvl-3 | /Python Homework/Homework 5 d).py | 519 | 4.09375 | 4 | print("Enter the hours of someone working to repair a device or more that you own, and the cost of the parts used after and I shall tell you the charge of your order.")
HoursWorked = int(input("Enter the work hours of the technician working for you"))
PartsCost = int(input("Enter the cost of the parts used to fix your ... |
1dba1be9e1d73add881b416f7d0b571e2ba1b734 | prasanth50/Python_spring | /Homework4/Program1.py | 143 | 3.703125 | 4 | def temp_converter(Tf):
Tc = (5/9)*(Tf-32)
return Tc
Tf = float(input('Enter temperature in Fahrenheit :'))
print(temp_converter(Tf)) |
a23ce773aa80b9a59349b8428c38373c11fe502a | prasanth50/Python_spring | /Homework4/Program2.py | 310 | 3.921875 | 4 | def count_frequency(mylist):
frequent = {}
for i in mylist:
if(i in frequent):
frequent[i] += 1
else:
frequent[i] = 1
return frequent
mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"]
print(count_frequency(mylist))
|
633d3ff808ffec5924cfb578a429b6dbb7df6f2f | EY-X/day18_reinforcement_python | /word_counter.py | 293 | 3.84375 | 4 |
def word_counter(string):
words_list = []
for words in string:
string_x = string.split()
if words == None:
return 0
else:
for word in string_x:
words_list.append(word)
return len(words_list) |
e7a0b5a07eed5f41b9b218413c021817569708fa | mdeakyne/IT150 | /Completed Activities/0220Deakyne.py | 5,266 | 4.03125 | 4 | __author__ = 'Matthew'
print "Problem 1 : --------------iteration---------------------------------------"
lost = [2,4,8,15,16,32,42]
banana = "My spoon is too big."
rankings = {"Deakyne":"The best", "Hughes":"No comment","Philpot":"Hard","King":"Pretty Great"}
for item in lost:
print item
for char in banana:
... |
f4a1d0b9f4725cbb845088e97bf460d1931dc301 | mdeakyne/IT150 | /Blank Class Activities/0119Blank.py | 2,694 | 4.90625 | 5 | """
This assignment is worth 10 points and you should be able to answer the following questions after completing it:
What is the difference between a variable and a literal?
How do you assign variables in python?
How do you deal with errors in python?
What are different types of python variables?
How do you make a mult... |
f52d6fd295841a0e99f744f5a63b08e580ab49a8 | abdelazizrashed/Time-Manager-API | /app/shared/db_man/service.py | 7,779 | 3.59375 | 4 | import sqlite3
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from typing import Iterable
db = SQLAlchemy()
class DBMan:
@staticmethod
def execute_sql_query(app: Flask, query: str, params: Iterable = ()):
"""
This method takes an SQLite query and execute it and returns the ro... |
5108d71e4a691970e833836e65983895f2325fb5 | shubhangisiddhapure/DSA_hypervergeq | /step 5/interunion.py | 777 | 4.25 | 4 | # Find the union and intersection of two sorted arrays.
def union(list1,list2,len1,len2):
union1=[]
for i in range(len1):
if list1[i] not in union1:
union1.append(list1[i])
for j in range(len2):
if list2[j] not in union1:
union1.append(list2[j])
print(union1)
def... |
48054c3d30d80f2e273961d157ae254acfbc48e2 | shubhangisiddhapure/DSA_hypervergeq | /interviewbit/numberof1.py | 540 | 3.890625 | 4 | # Write a function that takes an unsigned integer and returns the number of 1 bits it has
def numSetBits(A):
s=[]
j=1
while j<=32:
z=A%2
s.append(z)
A=A//2
j+=1
s.reverse()
print(s)
i=0
counter=0
counter1=0
... |
7852b600e0d6e1c398112c061444e03bb8d6b335 | shubhangisiddhapure/DSA_hypervergeq | /step7/dupalicate.py | 196 | 3.640625 | 4 | name=input("enter the name")
c=""
i=0
j=1
while i <len(name):
if name[i]==name[j]:
c+=name[i]
i+=1
j+=1
if j==len(name):
break
print("duplicate letter in string",c) |
802515a3d9d4ed203c8ff67d2105fe7fcdaf58ba | shubhangisiddhapure/DSA_hypervergeq | /step9/stack2_queue.py | 601 | 4.03125 | 4 | class Queue:
def __init__(self):
self.s1 = []
self.s2 = []
def enQueue(self, x):
while len(self.s1) != 0:
self.s2.append(self.s1[-1])
self.s1.pop()
self.s1.append(x)
while len(self.s2) != 0:
self.s1.append(self.s2[-1])
... |
f5e89265b44ab3fc30230ea0a692a23fd91d30b9 | shubhangisiddhapure/DSA_hypervergeq | /step 5/leftshift.py | 598 | 4.125 | 4 | def leftshift(arr1,m,n):
dictionary={}
for i in range(m):
key=m+i-n
if key < m:
dictionary[key]=arr1[i]
elif key>=m:
dictionary[key-m]=arr1[i]
len2=len(dictionary)
for j in range(m):
arr1[j]=dictionary[j]
return print("left shift ",arr1)
... |
8c8de5ecf83cb442bb175788d6b99f20e8250960 | simon-ha/codecademy-python | /supermarket.py | 494 | 4.03125 | 4 | #codecademy python - a day at the supermarket - 9. something of value
#challenge - how to do a sumproduct
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
total = 0
for x in prices:
total = ... |
68064f95a463f5d09ad79d5f6057f2ac40b43156 | hzw1996123/lianxi | /比较不同文件.py | 681 | 3.5 | 4 | def file_compare(file1,file2):
f1 = open(file1)
f2 = open(file2)
count = 0 #统计行数
differ = [] #统计不一样的数量
for line1 in f1:
line1 = f2.readline()
count += 1
if line1 != line2:
differ.append(count)
f1.close()
f2.close()
return differ
file... |
2f22e90473597a15a2216077484fa6fe82fb0b86 | hzw1996123/lianxi | /未完成,比较单词长短.py | 742 | 3.875 | 4 | class Word(str):
'''存储单词的类,定义比较单词的几种方法'''
def __new__(cls,word):
#必须用到__new__方法,因为str是不可变类型
#所以在创建时将其初始化
if " " in word:
print ("Value contains spaces,Truncating to first space.")
word = word[:word.index(' ')] #单词是第一个空格之前所有字符
return str.__n... |
eb442a3e77a1eb3592f3d662aaeb78ab25bb94c0 | hzw1996123/lianxi | /4.2.py | 250 | 3.875 | 4 | temp = input("输入一个整数:")
number=int(temp)
while number:
i = number-1
while i:
print(' ',end='')
i=i-1
j=number
while j:
print('s',end='')
j=j-1
print()
number=number-1
|
83785fccf8afad83db4b5e6d20af65a63889fada | omgimanerd/rmt-python-cryptography | /06_encryption_decryption/substitutioncipher.py | 403 | 3.546875 | 4 | #!/usr/bin/python
import sys
fromChar = "abcdefghijklmnopqrstuvwxyz"
toChar = "qpwoeirutyalskdjfhgzmxncbv"
def encode(filename):
f = open(filename)
data = f.read().lower()
f.close()
print data
out = ""
for i in data:
if i in fromChar:
out += toChar[fromChar.index(i)]
else:
out += i
... |
de855108cea2130a2d560623abd8620e012d50c9 | alexcolombari/Python-Scripts | /calculadora.py | 1,413 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Alex Colombari (http://github.com/alexcolombari)
Date: 2019-08-20
Available functions:
+ : addition
- : subtraction
* : multiplication
/ : division
% : percentage
"""
import sys
def calculator(input_term):
"""
This is the man function
output --... |
a71c2228398c79bc0078171b6b85bf7b63744ce3 | pavankoduru/Freshworks-Assignment | /kvdatastore.py | 1,816 | 3.703125 | 4 | from threading import *
import time
dictionary={}#used to store in key:value format
def create(key,val,timeout=None):
if key in dictionary:
print("Error!-key already exists")
else:
if key.isalpha():
if len(key)<=32:
if len(dictionary)<(1024**3) and val<=(16*1... |
ad65e302b0b943b71947551523f7f644c1c4d715 | DanJimm/AlgorithmStudy | /[62]不同路径.py | 1,712 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/8/5
@Author : jim
@File : [62]不同路径
@Description :
"""
# 思路1、递归,转换为子问题,自顶向下
def uniquePaths_recur1(self, m: int, n: int) -> int:
def helper(x, y):
if (x, y) == (m - 2, n - 1) or (x, y) == (m - 1, n - 2):
return 1
elif x < m - 1... |
40aa8b88cad57515f5b94320e85d67ceab318d42 | DanJimm/AlgorithmStudy | /[547]朋友圈.py | 2,535 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/8/13
@Author : jim
@File : [547]朋友圈
@Description :
"""
# 思路1:DFS
def findCircleNum_DFS(self, M: List[List[int]]) -> int:
def dfs(x, y):
if M0[x][y] == 1:
M0[x][y] = '#'
for y1 in range(col):
if M0[x][y1] !... |
7416e1a5aafac156837db5da69fe18dcc821e474 | DanJimm/AlgorithmStudy | /各位相加.py | 315 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/7/24
@Author : jim
@File : 各位相加
@Description :
"""
# 自己只能想到循环和迭代,纯数学解法这么简洁美观,膜拜大佬
def addDigits(self, num: int) -> int:
if num % 9 == 0 and num != 0:
return 9
return num % 9 |
b703bf7f8c7a4e768b8b7584fed5d8f54c111c71 | DanJimm/AlgorithmStudy | /[242]有效的字母异位词.py | 1,127 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/8/23
@Author : jim
@File : [242]有效的字母异位词
@Description :
"""
# 1.第一眼看觉得可以用计数排序解决
def isAnagram(self, s: str, t: str) -> bool:
letter = [chr(i) for i in range(97, 126)]
def countNum(str):
tmp = [0] * 26
for i in str:
for j ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.