blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7700b49d52da43608f9bdeed2eb74f85474b3eee | MarcosAndre5/SocketPython | /ServidorTCP.py | 3,588 | 3.515625 | 4 | # -*- coding: utf-8 -*-
'''
ALUNO: Marcos André Azevedo de Assis
DISCIPLINA: Redes de Computadores
TRABALHO: Chat Cliente/Servidor com Socket usando modeldo TCP.
DATA: 03/10/2018
Python versão 3.7
'''
from socket import *
from _thread import *
import time
import sys
def endereco(): # P... |
4285950bd3c0c2a33e226a5338f18240d83fee4f | kubac65/adventofcode2020 | /day3/part_1.py | 655 | 3.65625 | 4 | with open("day3/input.txt") as file:
lines = [l.strip() for l in file.readlines()]
line_len = len(lines[0])
line_count = len(lines)
def calculate_trees(slope):
left, down = slope
x = 0
y = 0
trees_hit = 0
while True:
x += left
y += down
if y >= line_count:
... |
51250174b93af1b4c2f7e14bd99a7bbe1c1e3330 | TheConstructRIT/Machine-Swipe-System | /tests/Model/LockableBufferTest.py | 1,964 | 3.515625 | 4 | """
Zachary Cook
Unit tests for the LockableBuffer module.
"""
import unittest
from Model import LockableBuffer
"""
Test the LockableBuffer class.
"""
class TestLockableBufferClass(unittest.TestCase):
"""
Tests the constructor.
"""
def test_constructor(self):
CuT = LockableBuffer.LockableBuffer(3)
self.ass... |
74558a09badf460ca602ed948df174abc4ba3bce | bozicschucky/DATA-STRUCTURES | /arraystack.py | 3,603 | 3.953125 | 4 | class Empty(Exception):
"""
Error attempting to access an element from an empty container
"""
pass
class ArrayStack:
"""
LIFO stack implementation using a python list as underlying storage.
"""
def __init__(self):
"""
Create an empty stack
"""
self... |
d6cb4031763856cc3e47b1e1f438a3c9aab6ff2c | gabriellaec/desoft-analise-exercicios | /backup/user_111/ch150_2020_04_13_19_10_46_671123.py | 116 | 3.71875 | 4 | def calcula_pi(n):
i=0
x=0
while i<n+1:
x+=6/((n-1)**2)
i+=1
y=x**(1/2)
return y |
5607f146f5ecc55c696088a85b658cbbb74b0289 | chenmingio/LMPTHW | /ex21/bsearch.py | 1,307 | 4.125 | 4 | def search_list(data, target):
print(">>> data is ", data)
print(">>> target is ", target)
rc = search_recursive(data, target, 0, len(data) -1)
if rc is not None:
return target, rc
else:
return None, -1
def search_recursive(data, target, low, high):
"""the core recursiv... |
7d6e905c8fce4fc5cbe97dbbbdc3da9101069537 | chandramohank/Logical-Programes | /Python/checkgivenbracketsbalanced.py | 444 | 3.71875 | 4 |
def isBalanced(input):
isTrue=False
tempStack=[]
for i in range(0,len(input)):
if input[i]=="(":
tempStack.append(input[i])
else:
if not tempStack:
isTrue=False
return isTrue ... |
1676792917bef6cc61979dcd8154fd17e32d4029 | hyuk02006/Jusung | /Python 20210624/a_datatype_class/Ex06_dictionary.py | 1,756 | 3.84375 | 4 | """
[ dictionary 형 ]
1- 키와 값으로 구성 ( 자바의 map 와 유사 )
2- 저장된 자료의 순서는 의미 없음
3- 중괄호 {} 사용
4- 변경가능
` 사전.keys() : key만 추출 (임의의 순서)
` 사전.values() : value만 추출 (임의의 순서)
` 사전.items() : key와 value를 튜플로 추출 (임의의 순서)
"""
print('--------- 1. 딕셔너리 요소 --------------- ')
dt = {1:'one', 2:'two', '3':'thr... |
475ce999a6ce6afaee5c4036e00bb457c768a5b0 | ptycast/cspfloresportfolio | /images/Lyric_Title_Artist.py | 2,656 | 4.3125 | 4 | #Lyrics,Artist, Title Quiz
#Can you name the Songs which first words of the lyrics are the Song's Title"
#By Patricia Flores
#This is the first fuction that will explain the directions.
def intro():
print "Can you name the the song titles which the first words of the lyrics are the song's title?"
p... |
3e9842343d745abb17177ac7e13c12b623ae6b5a | IoC-Sunderland/Intro-to-Python-DTS-L7 | /main.py | 886 | 3.703125 | 4 | """
REPL:
Read
Evaluate
Print
Loop
"""
'''
CTRL-L to clear REPL
'''
# Variable decleration
num = 1
print(num)
# Get input from user
# name = input("Please enter your name: ")
# Type function to check var type
# print(type(name))
print(type(num))
# Functions
def name_of_function():
return "Hi from name_of_fu... |
4bde12105d98163a02492f9d386cc6a926607e74 | jitendra93/DSA | /code/search/search_ternary.py | 725 | 4 | 4 | a = [1,4,6,7,8,23,56,344,444,552,634,764,866,879,999,3645,4567,6587,7890,9996,999999]
def ternary_search(a,left,right,key):
if(left <= right):
mid1 = left + int((right - left)/3)
mid2 = right - int((right - left)/3)
if(a[mid1] == key):
return mid1
elif a[mid2] == key:... |
001a740c73924019188ff61a65138eeb0bfe9eee | zavon25/Intro-to-scripting | /assignments/assn2.py | 2,912 | 4.34375 | 4 | #!/usr/bin/env python
"""
ITS 3210 Introduction to Scripting Languages
Governor's State University
Adam Balauskas
Assignment 2
This program should receive input from the user from both the command line arguments
used when launching the script and by use of prompts while the script is running. The
comments in this ass... |
69727e8ae267b4d34b342f8d6d8453d03df88c4b | zqy1/pythonCookbook | /8.10.py | 1,246 | 3.546875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
8.10.py
~~~~~~~
让属性具有惰性求值的能力
"""
# 描述符和@property装饰器让属性具有惰性求值的能力,惰性求值-希望将
# 一个只读的属性定义为property方法,并只有在访问时才参与计算,一旦
# 访问了该属性,我们希望把值缓存起来,不必每次都重新计算
class lazyproperty:
"""惰性属性装饰器"""
def __init__(self, func):
self.func = func
def __get__(self,... |
c8095ae3178fbecac07afc8f79ce666cf5986c7d | SherazKhan/DS-rep | /Sandbox/Avishai/clinicians/clinic_find_tasks.py | 4,884 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 15:34:56 2017
@author: awagner
"""
def chunk_it(seq, n, shuffle=False):
"""
Accept an array and return a list of the array broken into chunks.
Input:
seq (array or list): The input array
n (int): Number of chunks to break the array into
... |
ddc477e7d0a59d7acec363f3ae72cb8900767c0f | bavneetsingh16/Python | /Anagram.py | 456 | 3.546875 | 4 | import sys
def anagram(s):
s1=len(s)
n1=int(s1/2)
if(s1%2 != 0):
return -1
else:
j=s[0:n1]
k=s[n1:]
c=0
for l in j:
if l not in k:
c=c+1
else:
k=k.replace(l,"",1)
return c ... |
d86553fa56914d1dab9c22d428cde83ee270750b | Toranian/CR-Hackathon-Youth-Events | /test.py | 459 | 3.5 | 4 | # def block_text(text, length=7):
# final_text = ""
# while len(text) >= length:
# final_text += text[0:length] + "\n"
# text = text[length:]
# print(final_text, text)
# print(final_text)
# # print(final_text, text)
# block_text("Come to Steves house for an absolute rager! I... |
733d85431c636911ba8ef353f5fc4ba490efaa69 | Nradionenko/DQE_Python_Homework | /Classes_Homework_5/modules/dates.py | 892 | 4.125 | 4 | from datetime import datetime
class Dates:
@staticmethod
def get_current_date():
"""Returns current date in date-time format"""
current_date = datetime.today()
return current_date
def str_to_date(self, string_date, date_format):
"""Format string to date (for dates passed f... |
aea96494442547362405e7a7f97d495f70faee1f | bineeshpc/problemsolving | /datastructures/recursion_and_backtracking/towers_of_hanoi1.py | 785 | 4 | 4 | def move_disk(source, destination, n):
print 'Moving disk {n} from {source} to {destination} '.format(n=n, source=source, destination=destination)
def towers_of_hanoi(source, destination, temp, n):
"""
Towers of hanoi problem
1
2
3
4
5
6
"""
# base case
# only 1 disk... |
8b965da89024cfbd8679c946b0d5ada64ae5c334 | mushfiqulIslam/tkinterbasic | /window.py | 548 | 3.84375 | 4 | import tkinter
def mushfiq():
# add label
label = tkinter.Label(root, text="Mushfiqul Islam Chowdhury \n Passionate and Enthusiastic", fg='white', bg='black')
label.pack(expand=tkinter.TRUE) #for middle
#label.pack()
if __name__ == "__main__":
root = tkinter.Tk()
root.title("Hello This is Wind... |
25d08fbee7c8144f129d3820b80ba7911ea2816f | mvmap/mvptest | /Python/mp/test_mp.py | 560 | 3.515625 | 4 | #!/usr/bin/env python
#coding=utf-8
#CPU密集型程序会充分利用服务器的CPU资源
from multiprocessing import Process
import time,os,sys,math
def f(name):
print 'hello ',name
print os.getppid() #取得父进程ID
print os.getpid() #取得进程ID
sys.stdout.flush()
for i in xrange(10000000):
math.sqrt(i**2)
print name,'ok'
sys.stdout.flush()
def... |
ef245464a075b8663a1c86ebbee4c443ec400f63 | Jacopo6/tic_tac_toe | /tic_tac_toe.py | 1,946 | 4.25 | 4 | """
File: tic_tac_toe.py
---------------
Insert comment...
Jacopo Mascitelli
"""
def commit_move(board, sign, pos):
board[pos] = sign
def check_free(board, pos):
return board[pos] == " "
def winner(board, sign):
return (board[7])
def make_board():
board = []
for y in range(3):
row = ... |
b928e7e6cc9f05ede56130dc1ab1801658724f6c | Booyah1898/scrape | /scrape.py | 880 | 3.625 | 4 | #import libraries
import urllib.request
from bs4 import BeautifulSoup
import csv
from datetime import datetime
#specify the url
quote_page='http://www.bloomberg.com/quote/SPX:IND'
#query the website and return the html to the variable 'page'
page=urllib.request.urlopen(quote_page)
#parse the page into beautiful so... |
6a041abf95daaa5ddb5bd49995687c36bc4efcf2 | Ezi4Zy/leetcode | /384.打乱数组.py | 795 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=384 lang=python
#
# [384] 打乱数组
#
# @lc code=start
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
... |
8e92db766b39cec174253197089693033c8baedc | dooley444/Experiments | /Hamlet1.py | 2,498 | 4.1875 | 4 | from sys import exit
print("""Hello, Hamlet. I've been expecting you. """)
reaction0 = input("Ask who this is. " )
print(f"""{reaction0}? I am your father's ghost, speaking from the beyond.\n""")
reaction1 = input("Do you believe your father's ghost? Write 'Yes' or 'No'")
if reaction1 == "No":
print("No??? Ham... |
9bc2765f7c04ffe452dad636701043a836bcc8b6 | AidenMarko/CP1404Practicals | /prac_05/emails.py | 939 | 4.21875 | 4 | """
CP1404/CP5632 Practical
Do-from-scratch - Emails
"""
NAME_TO_EMAIL = {}
def main():
email = input("Email: ")
while email != "":
name = get_name(email)
confirm_name(email, name)
email = input("Email: ")
print()
for name, email in NAME_TO_EMAIL.items():
print("{} ({})... |
5a72daa95822077845247861311d39fbcd21d244 | lydiolectal/snippets | /graph_cuts.py | 2,360 | 3.8125 | 4 | # Implementation of minimum cut graph algorithm
# written by Lydia Ding
# 02/23/18
import networkx as nx
import random
# calculates the minimum cut of a connected graph G.
# input: a networkx multiGraph.
# output: graph of 2 nodes that represents the 2 clusters of the minimum cut.
def minCut(g):
# contract two n... |
b01d2ce193c93451ad9793a3f479fcca90cdb131 | Vandor13/Tic-Tac-Toe | /Problems/What day is it/main.py | 151 | 3.75 | 4 | offset = int(input())
time = 10
if time + offset >= 24:
print("Wednesday")
elif time + offset < 0:
print("Monday")
else:
print("Tuesday")
|
af103dd6c850923e3db4232fc6f2ce32333bbcb4 | felipesilvadv/felipesilvadv-iic2233-2017-1 | /Tareas/T04/Alumno.py | 435 | 3.625 | 4 | from matplotlib import pyplot as plt
import numpy as np
from functools import reduce
class Alumno:
pass
def factorial(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return reduce(lambda w, z: w * z, range(1, n + 1))
if __name__ == "__main__":
print(factorial(4))
x ... |
1c7a9575e2d54518f8755cb168404dc7d78716e2 | yesdino/review_before_interview | /算法与数据结构/数据结构与算法进阶/03_02_RecursionII/code/01_Subset.py | 1,623 | 3.953125 | 4 | '''
题目:
给你一个不含重复元素的集合 nums,要求返回所有可能的子集。
'''
# -------------------
# 迭代解法
def subsets(nums):
result = [[]]
for item in nums:
for sub_lis in result[:]: # 1. 注意这里为什么要用切片 切片其实是复制了一个copy
result.append(sub_lis+[item]) # 2. 注意每一轮的 item, result 都发生了改变
return result
# -------------------
# 递... |
18dbe18eadf8dc42b288b3136c0a99c5cb3d4c74 | jordanhanson1/Game-of-NIN | /Stick Game.py | 11,827 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 12:27:58 2020
@author: matt hanson
"""
import random
def printboard(board):
stringboard=[0,0,0,0]
strin=[]
index=0
total=0
for num in board:
total+=num
if total==0:
print("")
return
for nums in board:
strin.a... |
03d556f7a956b148bf17d15d0522b779499ce0ba | mivargas/ejercicios-de-python | /funciones.py | 357 | 3.8125 | 4 | #!/usr/bin/python3
def mensaje():
print("aprender")
print("aprender mas")
print("aprender aun mas")
#mensaje()
def suma():
num1=5
num2=7
print (num1+num2)
#suma()
def suma_dinamica(a, b):
print(a+b)
#suma_dinamica(56,8)
#suma_dinamica(89,6)
#suma_dinamica(4,81)
def sumica(a, b):
resultado=a+b
r... |
1d99af1b16c7ceb0daba0f7de4aecb1a13b36cbd | Nick-WangRunzhou/2017A2CS | /Ch23/ordered_linked_list.py | 353 | 3.71875 | 4 | #Free list
#Wang Runzhou Opt 3
NP = -1
class Myclass:
def __init__(self):
self.Value = ""
self.Next = NP
def InitializeList():
List = [Myclass() for i in range(10)]
SP = NP
FP = 0
for i in range(9):
List[i].Next = i + 1
List[9].Next = NP
print(List)
print(SP,FP)... |
3f4497d4cefd4f4c1c6825d87be87d447bf4b436 | Milkhail-S/python | /lesson_4/t6_my_iterators.py | 458 | 3.546875 | 4 | from itertools import count
from itertools import cycle
# итератор 10 значений от точки отсчёта
start = int(input('Введите точку отсчёта в виде целого числа: '))
for i in count(start):
if i > start + 10:
break
print(i)
# итератор перебора
lst = ['start', 1, 2, 3, 'end']
sch = 0
for i in cycle(lst):
... |
51ed557a7aa11c185b9d014e6fcdccde87b72f46 | ashushekar/python-advance-samples | /linkedin/25.sparsematrixmultiply.py | 949 | 3.84375 | 4 | """
Given two sparse matrices A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
Example:
Input:
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]
Output:
| 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = |... |
8507cee32a92b1d19214e08ac731be5a10bc8bb4 | daviddwlee84/LeetCode | /Python3/LinkedList/MergeTwoSortedLists/Better021.py | 892 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from ..ListNodeModule import ListNode
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
... |
d3ea2dd35a460d24650b0b7cb45d76bd1d822d51 | rafaelrbnet/curso-completo-de-python | /Aulas/03-Criando Funções/lamb.py | 544 | 4.125 | 4 | """
O uso do lambda é excelente para
calcular operações matemáticas.
Um típico exemplo é o uso na
black friday, onde os preços
são diminuidos.
Modificado em 09 de março de 2017
por Vitor Mazuco (vitor.mazuco@gmail.com)
Editado em 27 Setembro 2018
por Rafael Baena Neto (rafael.baena@gmail.com)
... |
3ff11c3eeae32ad1e3655442f2ac256ce86f568e | MonRes/bonus_exercises | /back_list.py | 145 | 3.828125 | 4 | """Napisać program wypisujący elementy danej listy od tyłu"""
list = [0, 1, 7, 3, 4]
for i in range(len(list)-1, -1, -1):
print(list[i]) |
62441869e8311ea5db508f4c41359c4e14bdc6af | bridgeQiao/Course_Object-Oriented | /test2_1/tools/record.py | 1,765 | 3.546875 | 4 | import re
class Record(object):
"""one line of the data of the File
Include a label and concrete data
Attributes:
_label : main attribute value
record_data : one record's data
"""
def __init__(self):
self._label = ''
self.record_data = []
def read_line(... |
5229f0bede4df8fd5b67feaf44ebe4537c7e15a7 | matthewkhle/stock-predictor | /archive/misc/matt_test.py | 993 | 3.578125 | 4 | import yfinance as yf
import pandas as pd
tickers = pd.read_csv('historical_data/A.csv', sep=',', header=None, skiprows=[0]) #reading the data by using Pandas library
print(tickers)
# BERT
# Ticker: A
# pass in the article to BERT for context analysis
# gives some sort of numerical representation of connotati... |
0aaf9db7dc25bb8ca87e9c613a3782c4be218421 | Xnsam/assignments | /fibonacci.py | 277 | 4.1875 | 4 | """Python to execute python fibonacci."""
def fibo(x):
"""Function to calculate the fibonacci series."""
if x < 2:
return 1
else:
return fibo(x - 1) + fibo(x - 2)
num = int(input('Enter the number : \t'))
for i in range(num):
print(fibo(i))
|
3f517bc1e3f891d5d2987cc7d47dd7feac220b8d | dougcirqueira/sentiment-analysis-social-br | /implementation/facebook-fanpage-retrieval/retrieve_fanpage.py | 16,771 | 3.5625 | 4 | """
This code retrieves data from a Facebook FanPage. This data includes posts and
comments of those retrieved posts.
It is possible to limit the number of posts to be retrieved or comments per posts.
Moreover, it is possible to set the 'since' and 'until' paramenters for retrieving posts.
Always remember to set a v... |
c664e15a75d0991dcd4f763d9f6058bbbccdda3d | iwuch/python_examples | /powerxn.py | 556 | 4.09375 | 4 | # def pow(x,n):
# if n == 0:
# return 1
# if n >= 0:
# if n%2==1:
# return pow(x,n//2)**2*x
# else:
# return pow(x,n/2)**2
# else:
# return 1/pow(x,-n)
def pow(x,n):
if not isinstance(n,int):
return 'N is not an interger.'
def cal(i):
if i == 0:
return 1
root = cal(i//2)
return root*root ... |
5c23a4f53cd7c3bda3bfca593d656648495dfb18 | hideraldus13/mini_jogos_python | /pedra_papel_tesoura.py | 669 | 3.625 | 4 | import random
def jogar():
jogador = input("Eu já escolhi. O que você escolhe? 'p' para pedra, 'a' para papel, 't' para tessoura\n").lower()
maquina = random.choice(['p', 'a', 't'])
if jogador == maquina:
return 'Empatou!'
# r > s, s > p, p > r
if vitoria(jogador, maquina):
return... |
bde7adccdcc3c90051511b4fe58febe0d284900a | taeheechoi/coding-practice | /FB/????4-maximumSubarray.py | 475 | 4.21875 | 4 | # Example 1:
# Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Example 2:
# Input: nums = [1]
# Output: 1
# Example 3:
# Input: nums = [5,4,-1,7,8]
# Output: 23
def maxSubarray(nums):
maxSub = nums[0]
curSum = 0
for num in nums:
if curSum <... |
92839ec4d2faf3285b1f29290f49e6e2035fb07a | Aasthaengg/IBMdataset | /Python_codes/p03273/s575793537.py | 220 | 3.578125 | 4 | h, w = map(int, input().split())
grid = [list(input()) for i in range(h)]
for i in range(2):
grid = [col for col in grid if '#' in col ]
grid = list(map(list, (zip(*grid))))
for g in grid:
print(''.join(g)) |
a7791ee848d82eb9b58087960979ff5eb752d101 | wildenali/Python3_Basics | /24_Pengenalan_Class/class.py | 579 | 3.890625 | 4 | # class
# class harus di atas, karena python itu interpreted language, makanya harus berurutan
class mahasiswa():
nama = 'nama' # atribut, nilai yang nempel di dalam kelas
# membuat sebuah method
def belajar(self, kondisi):
print(self.nama, 'sedang belajar', kondisi)
def tidur(self):
... |
8c708a0deb8eacf86e2cff8497b49c0119459386 | ceden95/self.py | /countletters_dict.py | 863 | 4.15625 | 4 | #the program prints a dict of letters as a keys and number
#of times the letter is in the sentance as a value. sentance given by user.
def main():
my_str = input("type a sentance: ")
countDict = count_chars(my_str)
print(countDict)
def count_chars(my_str):
"""the functoin returns a dict of le... |
d06101bcbfb89d0e87143930d538c0d9349c849a | hankroark/advent_of_code_2019 | /src/day02/day02.py | 2,671 | 3.90625 | 4 | from typing import List
Program = List[int]
"""
Here are the initial and final states of a few more small programs:
1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.
"""
def run... |
e908e1ea78a360180dc1ca56786fd5abdaf2195e | ChristianFusco/homework_ai | /assignment1/shop.py | 3,522 | 3.546875 | 4 | """Author: Christian Fusco
Class: CSI-480-01/02
Assignment: Python Practice
Date Assigned: 9/11/2017
Due Date: 9/11/2017
Description:
A short python intro assignment.
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others... |
5b0bc9ece9244c928d8f72a4242ea6262548ebbe | Joao-Aguiar-Moreira-Gomes/PS-Navi | /Questão2.py | 403 | 3.6875 | 4 | import math
import statistics
list = []
for number in range(0, 10):
if number % 2 == 0:
x = pow(3, number) + 7 * math.factorial(number)
else:
x = pow(2, number) + 4 * math.log(number)
list.append(x)
print("Valor Máximo: " + str(max(list)) + "\n" + "Posição do Valor Máximo: " + str(l... |
80246a6df84510b218fe84eacf6ef62116de594f | antonpols/Hinton-Coursera-Python | /Quiz/Lecture7_Q3.py | 338 | 3.515625 | 4 | import math
def sigmoid(z):
return 1/(1+math.exp(-z))
x0 = 9
x1 = 4
x2 = -2
Wxh = 0.5
Whh = -1
Why = -0.7
hbias = -1
ybias = 0
z0 = Wxh*x0 + hbias
h0 = sigmoid(z0)
y0 = Why*h0 + ybias
z1 = Wxh*x1 + Whh*h0 + hbias
h1 = sigmoid(z1)
y1 = Why*h1 + ybias
z2 = Wxh*x2 + Whh*h1 + hbias
h2 = sigmoid(z2)
y2 = Why*h2 ... |
91aee05617b394c89412cb5d96c733194a2ec4c3 | kanbei7/IR-Project | /src/nltk_examples.py | 177 | 3.65625 | 4 | import nltk
NN = ['NN', 'NNS', 'NNP', 'NNPS', 'NP', 'NPS']
text = nltk.word_tokenize("Do you know information retrieval?")
print([t for t in nltk.pos_tag(text) if t[1] in NN])
|
bbfa3a1b321485a538c26f7143a8401d0f253b4a | sfujiwara/ProjectEuler | /Python/problem077.py | 821 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import math
## エラトステネスの篩でn以下の素数列を返す関数
def sieve(n):
## 0-nが素数か否かのフラグ
flag = [True]*(n+1)
## 0, 1 は素数ではない
flag[0], flag[1] = False, False
for i in xrange(2, int(math.sqrt(n))+1):
if flag[i]:
for j in xrange(i*2, n+1, i): flag[j] = False
return [i for ... |
417a79f6d754bca6821786c067765d2d30135ea5 | golyakova27/PolynomialClassPython | /PolynomialWork.py | 6,601 | 3.984375 | 4 | class Polynomial(object):
#constructor
def __init__ (self, coeffs):
if isinstance(coeffs, list):
if len(coeffs) != 0:
for c in coeffs:
if isinstance(c, (int, float)):
while coef... |
efa08c2e81ce5c7b51aee56435f617557051eb63 | KynanBertulli/HackerRank | /PythonChallenges/Swap_Cases/__init__.py | 284 | 4.0625 | 4 | def swap_case(s):
a1 = list(s)
for i in range(len(a1)):
if(a1[i].isupper()):
a1[i] = a1[i].lower()
else:
a1[i]= a1[i].upper()
return a1
if __name__ == '__main__':
s = input()
result = swap_case(s)
print("".join(result)) |
31942ae0cc2423e993bfa79748a56b00aa886473 | crberry/week3 | /divvy.py | 821 | 3.796875 | 4 | # Divvy Bikes
#
# Here's an example of how to retrieve the list of Divvy bike stations:
import json
from urllib.request import urlopen
webservice_url = "http://www.divvybikes.com/stations/json"
data = urlopen(webservice_url).read().decode("utf8")
result = json.loads(data)
stations = result['stationBeanList']
print(st... |
6e2d4d2b98f077155cc446a41af50a5b251975b8 | SergeiSd/nix-course-beginner | /strings_upper.py | 1,323 | 4.09375 | 4 | """This modelu provides the function to converts all sentences to uppercase."""
import argparse
import codecs
import os
import sys
import nltk
# nltk.download('punkt')
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--path_file', default='strings.txt',
help='The location of file.')
ar... |
2934d774d26aa27767e51495866a3d642f9ca4a7 | mukeshprasad/30-Day-LeetCoding-Challenge | /July-LeetCoding-Challenge/Week-4/single_number.py | 1,246 | 3.796875 | 4 | '''
# Single Number III
# Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice.
Find the two elements that appear only once.
# Example:
Input: [1,2,1,3,2,5]
Output: [3,5]
# Note:
1. The order of the result is not important. So in th... |
079606656b8aa6db14423ff1436f874afa9eb684 | Olexiy-repin/python-course | /lesson05/hw.py | 624 | 3.796875 | 4 | import re
CYRILLIC_SYMBOLS = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяєіїґ'
TRANSLATION = ("a", "b", "v", "g", "d", "e", "e", "j", "z", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h", "ts", "ch", "sh", "sch", "", "y", "e", "u", "ja")
TRANS = {}
for c, l in zip(CYRILLIC_SYMBOLS, TRANSLATION):
TRANS[... |
0812086984ba1215a908d4f9590b27b5067da734 | clckwrkbdgr/dotfiles | /lib/clckwrkbdgr/math/geometry.py | 9,221 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import re, math
try:
math.gcd
except AttributeError: # pragma: no cover -- py2
import fractions
math.gcd = fractions.gcd
import clckwrkbdgr.math
import clckwrkbdgr.utils
class Line(object):
""" 2D segment between two points on plane. """
def __init__(self, a, b):
self.a = clckwrkbdgr.mat... |
9aefc6bd86eab73ca5473cca6907b98660179a96 | aquatir/code-samples | /code-sample-python/python_first_project/05_oop_hiding_and_inheritance.py | 3,032 | 4.03125 | 4 | class Rectangle:
def __init__(self, length, width):
self.__length = length
self.__width = width
def area(self):
return self.__length * self.__width
def perimeter(self):
return 2 * (self.__length + self.__width)
class Student:
__name = None
__roll_number = None
... |
09366a8e7132fdda0c04548f0dfcf867bf44f19a | mmatrix05/cs50_Python | /Mario.py | 886 | 4.25 | 4 | while True: #pokreni beskonačnu petlju za upis
try:
visina = int(input("Enter height (1-8):")) #upis broja 1 do 8
if visina<0 or visina>8:
print("Enter whole number between 1 and 8!")
continue #pogrešan upis pravog tipa, vrati se na upis
else:
break... |
21a753f7618ea727e86ec00876de2eaefafe04ad | mrgrit/ml_from_scratch | /1_86_nn_basic.py | 2,749 | 3.609375 | 4 | import numpy as np
def sigmoid(x):
# np.exp : just used for matrix input
return 1/(1+np.exp(-x))
def relu(x):
return np.maximum(0,x)
def identity_function(x):
return x
def test(test_no):
if test_no == 1:
# implement neural network
x = np.array([1.0,0.5])
w1 = np.array([... |
4aca9606c4b03506d12387d76d061a6c5b15b265 | cdrn/Algorithms | /quick_sort.py | 849 | 4.28125 | 4 | """
1) Pick an element, called a pivot, from the array.
2) Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final... |
61c8b92910370bd4fac370c6f9f405c059270296 | ivanromanv/manuales | /Python/Edx_Course/Introduction to Programming Using Python/Excercises/W5_Function_lista_numeros_impares_desc.py | 884 | 4.3125 | 4 | # Write a function that accepts two positive integers a and b (a is smaller than b)and returns a list that contains all the odd numbers between a and b (including a and including b if applicable) in descending order.
#
def funcion_lista_numeros_impares_desc(number_one, number_two):
my_index=int(0)
contador=int(0)... |
a33bae2f0db2ce239b30b1d84b18c2468cf182af | VamsiMohanRamineedi/Algorithms | /206.Reverse_Linked_List.py | 947 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#Recursive solution. Time and space - O(n)
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr... |
324cd5cae0341ba99169a383bfffd2d8f1e02891 | HDB-1/Tamagotchi | /tamagotchi.py | 2,603 | 3.828125 | 4 | class pet:
def __init__(self, name, happiness = 0, hunger = 0):
self.name = name
self.happiness = happiness
self.hunger = hunger
def __repr__(self):
return 'Your pet: \n Pet name is ' + self.name + '\n and they are ' + str(self.happiness) + ' out of 10 happy,\n and ' + str(self.... |
f07d947e249cbebd691b647028e5196bb0c004a3 | razyesh/razyesh.github.io | /iw/python-assignment-ques/multiply_list-q17.py | 566 | 4.21875 | 4 | """
Write a Python program to multiplies all the items in a list.
"""
from functions_ex.utils import get_integer
def multiply_item(input1):
"""function to multiply all the item in a list"""
total = 1
for i in input1:
total = total * i
return total
if __name__ == "__main__":
list_length... |
2e08f8e519cca4acb4a13afa5a84fbbd88f2c8d9 | Code-Institute-Submissions/Tic-Tac-Toe-5 | /run.py | 4,268 | 4.09375 | 4 |
class Board:
"""
Creates the game board.
"""
def __init__(self, from_board=None):
"""
Define the amount of cells in the board.
"""
self.board = (from_board or list('012345678')).copy()
def to_string(self):
"""
Create the actual board as it appears on... |
3688c587241abfa8abb14457d41cc4bfd1cee5d9 | dunton-zz/coderbyte | /DistinctList.py | 584 | 4.21875 | 4 | # Have the function DistinctList(arr) take the array of numbers
# stored in arr and determine the total number of duplicate entries.
# For example if the input is [1, 2, 2, 2, 3] then your program
# should output 2 because there are two duplicates of one of the elements.
def DistinctList(arr):
# code goes here ... |
7c95145ca75ebdae2ea55b6d56acbac73aa5ace9 | ssillva/Sleepmon | /conexaoBD.py | 1,224 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Sandro
import sqlite3
class ConexaoBD(object):
#inicializando o Banco de dados
def __init__( self, bdName ):
try:
#dfefinindo atributo conexao
self.conexao = sqlite3.connect(bdName)
#definindo atributo direcionador
... |
f6862989e122574bd1f311c75b57fcd1254148d7 | Kartikey1999/Python-Programs | /If-Else/matrix.py | 905 | 3.96875 | 4 | # num1=int(input("enter a number: "))
# num2=int(input("enter a number: "))
# num3=int(input("enter a number: "))
# num4=int(input("enter a number: "))
# num5=int(input("enter a number: "))
# num6=int(input("enter a number: "))
# num7=int(input("enter a number: "))
# if num1==1:
# print("Sunday")
# if num2==2:
# ... |
19ea1ba909c36625169cdb0c3947b4a71a0749f8 | bionic790/ML-LAB | /ID3 ALGO/code.py | 4,917 | 3.6875 | 4 | import pandas as pd
df = pd.read_csv('PlayTennis.csv')
print("\n Input Data Set is:\n", df)
t = df.keys()[-1]
print('Target Attribute is: ', t)
# Get the attribute names from input dataset
attribute_names = list(df.keys())
#Remove the target attribute from the attribute names list
attribute_names.remove(t)
print('Pred... |
79f182cbeb2fc5e82bd02e28dc217d1dba66f7a5 | californianseabass/devtools | /generators/utils.py | 1,516 | 3.625 | 4 |
# turns any single argument function into a generator
def generate(f):
''' example:
gen_sqrt = generate(math.sqrt)
for x in gen_sqrt(xrange(100)):
print x
'''
def gen_func(s):
for item in s:
print('item: ', item)
yield f(item)
return ... |
0bd86a71ab5470e160c43a163680f463ad4f613a | jtrinklein/advent-of-code | /2020/18/main.py | 2,602 | 3.71875 | 4 | #!/usr/bin/env python3
data = []
with open('./data.txt') as f:
data = [line.strip() for line in f.readlines()]
def eval_expr(ex):
# a is always a literal
# op is one of +,*,)
# b is either a literal or (
# evaluate a op b for s = n*m or s = n+m and return [s] + expressionlist
# ex: 1+2+3
... |
61344262b885b11b3da83410361a4619c6774e0f | GongchunDing/python100 | /day01-15/day9.py | 6,244 | 3.890625 | 4 | '''
单下划线_作为模块内的函数/类名:
在别的文件中import module import * 时,这些下划线变量不会被引用到文件内
python内的私有都是“伪私有”
使用property修饰符相当于java中的private变量使用get set方法访问,但是在python中仍可直接访问带_的“私有”属性
双下划线开头的类内变量与函数
表示私有成员,不能直接访问,必须以“_类名__变量名”的方式访问
双下划线开头、双下划线结尾的变量或函数(魔法方法和魔法属性)
在python解释器中有特定的处理方式和机理
'''
from abc import ABCMeta, abstractmethod
... |
c89b17e3b5fcd36b658bf4dce21c22ebcd6caf6b | KADEEJASAFEER/pythonnew | /object_oriented_programming/inheritance/bank.py | 1,023 | 3.890625 | 4 |
class Person:
def setPerson(self,name,age,address):
self.name=name
self.age=age
self.address=address
class Bank(Person):
bankname = "SBI"
def Account_create(self,account_no,account_type):
self.account_no=account_no
self.accoount_type=account_type
self.balan... |
c13b75a216885a3a8d7978d8be953ed7c4aeb30e | srenegado/pycrashcourse | /ch8/messages.py | 214 | 3.703125 | 4 | # Ex 8-9
def show_messages(messages):
"""Print a series of text messages."""
for message in messages:
print(message)
texts = ['Hey', 'You coming tonight?', "At John's place?"]
show_messages(texts) |
d1dd72b1a8654091390d529dfa416c82d03c3b1a | muthuvel26/self-study- | /Python _syntax/Sting_Edit.py | 106 | 3.65625 | 4 | b=[]
a="Muthu,in,chennai"
a = a.split(',')
print(a[2])
for i in a:
b.append(i)
print(b[0])
|
20a9a40c3944e62903957a733edde1fd2dff7a76 | Kirushanr/Python | /Python Crash Course/Ty8-6.py | 366 | 3.90625 | 4 | def city_country(city, country):
""" Return a formated string """
string = city + ", " + country
return string.title()
formatted_string = city_country('sydney', 'australia')
print(formatted_string)
formatted_string = city_country('delhi', 'India')
print(formatted_string)
formatted_string = city_country('c... |
2024164b98d4f69210c8648549e3cb25b5e9caaf | kpessa/CodeSignal | /py/meanGroups.py | 973 | 4.0625 | 4 | """
You are given an array of arrays a. Your task is to group the arrays a[i] by their mean values, so that arrays with equal mean values are in the same group, and arrays with different mean values are in different groups.
Each group should contain a set of indices (i, j, etc), such that the corresponding arrays (a[i... |
5b2bede8033e1817af136eef94c12d9f4a2a3673 | PramodJana/Python_horler | /list.py | 522 | 4.25 | 4 |
"""created a list"""
lst=[10,20,"pramod",-10,30.5]
print(lst)
print(lst[3])
print(lst[3:5])
print(lst*4)
"""append function"""
lst.append(69)
print(lst)
"""remove function"""
lst.remove("pramod")
print(lst)
"""clear function
lst.clear()
print(lst)
"""
"""max function"""
print(max(lst))
"""min function"""
print(m... |
3ced5c83f5cdda99a971e5a612b3bb8286b6952b | ericcheng09/LeetCodeSolution_Python | /Scripts/1028.py | 2,261 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import re
class Solution(object):
def recoverFromPreorder(self, S):
"""
:type S: str
:rtype: TreeNode
"""
... |
6c43567b33a63bf5c3f04cc9420a34b8a7acfc90 | sczhan/wode | /类(class)/import练习.py | 9,591 | 3.515625 | 4 | import random
# x = random.randint(100, 999)
# n = 10
# while n:
# # 输入函数
# num = input("请输入一个三位数")
# # 检测输入是否是纯数字
# if num.isdigit():
# # 输入函数的是字符类型,不强制会报错
# num = int(num)
# if 100 <= num <= 999: # if 100<= int(num) <= 999:
# """判断输入的数与系统随机数比较大小
# """
#... |
2e9939965f2faeef193a4daa83afa4749881d021 | maxpel10/PythonLab | /MostrarTabla.py | 2,106 | 3.515625 | 4 | from tkinter import *
from tkinter.ttk import Separator
class MostrarTabla:
def __init__(self, bd, curso):
listaAlumnos = bd.getRegistroXCurso(curso)
pantalla = Toplevel()
pantalla.grab_set()
pantalla.resizable(0, 0)
w = 440
h = 700
ws = pantalla... |
f546106f7c505a6ab5487efce22b4a00cb6afce7 | kajmaj87/tankbr | /slowmath.py | 1,629 | 3.875 | 4 | def square(a):
return a * a
def circlesCollide(x0, y0, r0, x1, y1, r1):
a = (x0 - x1) ** 2
b = (y0 - y1) ** 2
r_low = (r0 - r1) ** 2
r_high = (r0 + r1) ** 2
pointDifference = a + b
return r_low <= pointDifference and pointDifference <= r_high
def dist_square(x1, y1, x2, y2):
dx, dy =... |
2e68b367afc36f62746767aad50cada22a04da6b | niufenjujuexianhua/Leetcode | /[491]Increasing Subsequences.py | 1,329 | 3.75 | 4 | # Given an integer array, your task is to find all the different possible increa
# sing subsequences of the given array, and the length of an increasing subsequenc
# e should be at least 2.
#
#
#
# Example:
#
#
# Input: [4, 6, 7, 7]
# Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7],... |
8a2817014df4451b4870fe34d8d4cf701d882d2b | tangzichengcc/python-study | /算法/leetcode/easy/9.py | 914 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Autor:tangzicheng
class Solution(object):
def isPalindrome(self, x ):
"""
:type x: int
:rtype: bool
"""
if x < 0 :
return False #这个会不会提升效率?
num = 0
a = abs(x)
while (a != 0):
temp... |
19518b4c4859c6b044a7f4145b103a58f8f7c719 | tlops/Pythoncode | /string1.py | 358 | 3.84375 | 4 | # This code process a string and extract some
# predefined characters from it.
text = "X-DSPAM-Confidence: 0.8475"
textlen = len(text)
print textlen, "\n"
zeropos = text.find('0') # finds the first letter becos its a string
print zeropos
num = text[zeropos:] # we slice off from this position till the end
num = flo... |
3fe465135ad28da1753c2676fbdcabf8e9f91ca2 | TianyaoHua/LeetCodeSolutions | /House Robber.py | 377 | 3.5625 | 4 | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
table = [0]*(n+1)
table[1] = nums[0]
for i in range(2, n+1):
table[i] = max(table[i-1], table[i-2] + nums[i-1])
return table[-1]
s... |
42ff8c9cf9b1b293fd95ed8e610b6b228bbaa5a0 | iocbio/iocbio | /iocbio/io/cacher.py | 6,996 | 4.03125 | 4 | """Provides Cacher that implements computational model with caching results.
Example
-------
::
>>> \
class System(Cacher):
def compute (self, a=1, t=0):
'''Integrate dx/dt=a till t with x(0)=1.
'''
if self.previous_results is not None:
last_t = self.previous_par... |
7ae4c9f5a8bf39abc852a6db558803a4b7cde0b4 | shadow923540/Python_small_project | /Calculator/assaigning_events.py | 476 | 3.828125 | 4 | from tkinter import *
def doOK():
print("OK button clicked")
def doCancel():
print("Cancel button clicked")
window = Tk()
btnOK = Button(window, text="OK", fg='blue',
command=doOK)
btnCancel = Button(window, text="Cancel", bg='blue',
command=doCancel)
btnOK.grid(row=1, column... |
80135045c8b48986842d9c29e1b52c57b2df72ef | iriagzz/Exercises | /PYTHON/Dictionary/Budega.py | 2,711 | 3.9375 | 4 | class Clientes():
def __init__(self, nome, divida):
self.nome = nome
self.divida = divida
class Budega():
def __init__(self):
self.clientes = {}
def cadastrar_clientes(self,):
print('****** Cadastrar Cliente ******')
nome = input('Nome: ').upper()
if nome ... |
df8d4c1a14613e4ca93b26d51ca9e8fc8ba43399 | marciomazza/codesummary | /tests/examples/chains/b.py | 205 | 3.71875 | 4 | # f | a
def f(x):
return a
# g | a
def g(y):
yield a, b
a = 1
c = " "
a += 1
b = None
b = a + 2
c = f(b)
____________________
# f | a
def f(x):
return a
a = 1
a += 1
b = a + 2
c = f(b)
|
04b7eeda5ad7df885258deda129b3db0d18708fc | somasekharreddy1119/DS-Algo-with-python | /Algorithms/bit_manipulation/check_kth_bit_is_set.py | 532 | 3.5 | 4 | # RBR Interview Prep
# Check kth bit is set or not
'''
we assume that index of LSB is 0 here k = 3
ex: 1001010
and 0001000 (to get this: 1 << k)
-------------
ans 0001000 ----> if set then sol > 0; else sol = 0
-------------
TIME: O(logn)
'''
def check_kth_bit(num, k):
'''
:param num: integer, number to test... |
f14390ee5d4a5bb5077c59898779edb750c0fe5c | Anoopcb/Map_function1 | /Map_function1.py | 302 | 3.96875 | 4 | ## map() function
numbers = [1, 2, 3, 4]
#def square(a):
#return a**2
squares = list(map(lambda a: a**2, numbers))
print(squares)
## by list comprehension
squares1 = [i**2 for i in numbers]
print(squares1)
name =["abc", "abcd", "abcde"]
length = map(len, name)
for i in length:
print(i) |
c492cb08a8bcc7c5411fc65eaa9128da9ada8b01 | adityad30/Backtracking-2 | /70Subsets.py | 1,590 | 3.59375 | 4 | """
// Time Complexity :O(n*2^n) Visiting each node ones.
// Space Complexity :O(2^n)
// Did this code successfully run on Leetcode : YES
// Any problem you faced while coding this : NA
//Explanation:
Take pivot from the input nums list. and follow-
action -> add nums[0] in temp list.
recursion -> recurse on nums[0+1]... |
95f2c0e2901d2fdbe0a26dbf117a696ca3621963 | poonamangne/Programming-Exercises-1 | /Chapter06_02.py | 465 | 4.3125 | 4 | # 6.2 Write a function that computes the sum of the digits in an integer
# Compute sum of the digits
def sumDigits(n):
sumOfDigits = 0
while n > 0:
digit = n % 10
n = n // 10
sumOfDigits += digit
return sumOfDigits
def main():
number = eval(input("Enter an integer: ")) # Prompt... |
b779a7d13eb212aacda033e627db56e21f4d58e0 | YSabarad/monopyly | /monopyly/cards/get_out_of_jail_free.py | 689 | 3.640625 | 4 | from .card import Card
class GetOutOfJailFree(Card):
'''
Get Out Of Jail Free.
'''
def __init__(self, deck=None):
'''
The constructor.
'''
# The deck that the card belongs to.
# We hold this so that we can put the card back in the deck
# after it has bee... |
43c6761d9dc7a81af83d0404b1ddaf5170116f43 | SeBol17/Education | /017_zero_in_one.py | 357 | 3.875 | 4 | a = int(input())
print(a*0)**1
# водится число 0 или 1, необходимо вывести 1 или 0 соответственно.
# Формат ввода
# Число 0 или 1.
# Формат вывода
# Число 0 или 1.
# Примеры
# Тест 1
# Входные данные:
# 0
# Вывод программы:
# 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.