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 |
|---|---|---|---|---|---|---|
9f5407be41c1f4cb4921675a6af320a866cdc8ad | Swift-2016/Python | /python35-tutorial-MOOC/week1-2/homework1-2/01 string_contact.py | 292 | 3.5625 | 4 | # coding: utf8
__author__ = 'xray'
str1 = input(" 请输入一个人的名字:")
str2 = input(" 请输入一个国家名字:")
print(" 世界这么大,{} 想去{} 看看.".format(str1, str2))
'''
(1 )字符串拼接。
用户输入两个字符串,将它们组合后输出。
''' |
577265e1554051680fcadadb8fa981999354b1dc | Swift-2016/Python | /python35-tutorial-MOOC/week1-2/homework1-2/09 spiral_line.py | 268 | 3.53125 | 4 | # coding: utf8
__author__ = 'xray'
'''
(9)螺旋线绘制。
绘制一个螺旋线的图形,如图所示。
'''
import turtle
import time
turtle.speed("fastest")
turtle.pensize(2)
for x in range(100):
turtle.forward(2*x)
turtle.left(90)
time.sleep(3)
|
47954e932e370ab8205788a587ec78c6bde28ac1 | Kheya28/Machine-Learning | /matplotlib/subgraph.py | 1,337 | 3.890625 | 4 | import numpy as np
import matplotlib as pylab
import matplotlib.pyplot as plt
#drawing a subgraph
x=np.linspace(0,10,12) # 0 theke 10 ke 12 vag kora
y=x*x+2
plt.subplot(1,2,1) #the contents are rows,columns & indexes
plt.plot(x,y,'r--') # third parameter defines color & line style,,,,r-- means red colo... |
b6c43d8e05c2c06879abe86a53a1d919a75b5fa9 | KellyOllos/STRUCTURES | /STRUCTURE.py | 416 | 4.1875 | 4 | #BRIANNE KELLY R. OLLOS
#STRUCTURES
letters = ['s','l','l','o','s','s','o','l',
's','o','o','l','o','l','s','s',
'o','s','s','o','l','l','l',
's','l','s','l','l','o','o','s',
'l','l','s','o','s','s','o']
from collections import Counter
letter... |
96ef9aed043bd0816417e91e02ea00d33c7823c7 | AlexisEspinosaGayosso/ArrayCapture_PY | /CylindricalVelocities/strings_AEG.py | 783 | 3.75 | 4 | #AEG: This module is intended to keep all the functions used for manipulating or processing strings
################################################################
#is_number(s)
#----------
#2017.04.11
#Function to evaluate if a string is a number.
#Copied-Pasted from website: http://pythoncentral.io/how-to-check... |
282e226545895ba0f8ca60f85c79aee937445c9a | cwang0129/algos | /ctci/chapter_02/problem_02_01_remove_dup.py | 417 | 3.90625 | 4 | from linkedlist import linkedlist
def remove_dup(unsort_ll):
if unsort_ll.head is None:
return
cur = unsort_ll.head
while(cur):
runner = cur
while(runner.next):
if cur.value == runner.next.value:
runner.next = runner.next.next
else:
runner = runner.next
cur = cur.next
ll = linkedlist()
ll... |
48339888816a5b7cd95fdee5fc61ad01b48f6a7d | cwang0129/algos | /ctci/chapter_02/problem_02_06_detectCycle.py | 188 | 3.78125 | 4 | from linkedlist import linkedlist
def detectCycle(ll):
slow = fast = ll.head
while()
ll = linkedlist()
ll.append(1)
ll.append(8)
ll.append(2)
ll.append(3)
ll.append(2)
ll.printll() |
1b42a46a34c60dace2d426b8557cff4b3e0975f4 | amyfranz/Problem-4-smallest-number | /main.py | 422 | 4.03125 | 4 | def checkMultiple(num, multiple):
return num % multiple == 0
def checkMultiples(num, biggestMultiple):
for i in range(3, biggestMultiple):
if checkMultiple(num, i) == False:
return False
return True
def getMultiples(multiple):
i = 1
multiply = multiple * (multiple -1 ) * (multiple -2 )
while not... |
8a4506d28b8dfcaa41a8eac3953d2000cdc2141b | lc00/grokking-deep-learning | /hot-cold-learning.py | 451 | 3.796875 | 4 | weight = 0.0
goal_pred = 0.8
input = 10
alpha = 0.001
for iteration in range(20):
error = (input * weight - goal_pred) ** 2
derivative = (input * weight - goal_pred) * input
print('Iteration:' + str(iteration))
print("Error:" + str(error) + " Weight:" + str(weight) + " Derivative:" + str(derivative))
t... |
dcb5272e38f4e8aa10ddf9f3329e2ec9a35f7079 | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_6/2_16.py | 398 | 3.6875 | 4 | import sys
lst111 = sys.argv[1:]
def count(lst):
str1 = ''.join(lst)
str1 = str1.lower()
lst1 = [elem for elem in str1]
dict1 = dict.fromkeys(lst1)
for key in dict1.keys():
dict1[key] = lst1.count(key)
returnstr = ''
for k, v in dict1.items():
returnstr += (str(k) + ' - ... |
dc887bb54690949bbf6da1673981c5132a49993f | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_13/calculator.py | 1,602 | 3.828125 | 4 | from tkinter import *
def result(z1, z2):
res = z1 + z2
lblresult.delete(0, END)
lblresult.insert(0, res)
def result1(z1, z2):
res1 = z1 * z2
lblresult.delete(0, END)
lblresult.insert(0, res1)
def result2(z1, z2):
res2 = z1 / z2
lblresult.delete(0, END)
lblresult.insert(0, res2... |
498970fdb182ffb833d5b5f6b9f843ae82847b94 | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_1/average.py | 186 | 4.0625 | 4 | list1 = [1,2,3,4,5,6,7,8,9,10]
summa = 0
count = 0
for num in list1:
summa = summa + num
count = count + 1
average = summa / count
print('Average number of list is : ', average) |
36f4f16e4fbcb7582f599b2a9467d237ebce25e0 | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_9/2_22_human_class.py | 661 | 3.515625 | 4 | class Human:
def __init__(self, gender, age, nationality, height):
self.gender = gender
self.age = age
self.nationality = nationality
self.height = height
def get_gender(self):
return self.gender
def get_age(self):
return self.age
def get_nationality(se... |
06690f49c83dbc767cdbd71990639ee5759d4679 | tigransargsyan1994/Tigran_Sargsyan_My_projects | /BST_001/avl.py | 4,610 | 3.78125 | 4 | # Python code to insert a node in AVL tree
# Generic tree node class
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
def count_level(self):
if self.val == None:
return 0
if (self.left !=... |
9906795d86eaa7d028f2c7635fe701af96f16d8c | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_1/sum_of_1_to_10.py | 133 | 3.9375 | 4 | summa = 0
list1 = [1,2,3,4,5,6,7,8,9,10]
for x in list1:
summa = summa + x
print('Sum of numbers between 1 and 10 is : ', summa)
|
6c2cda9f02706f0b4a63ebaec74c0957e55f2386 | tigransargsyan1994/Tigran_Sargsyan_My_projects | /Homework_12/upper_or_lower.py | 240 | 3.875 | 4 | def make_upper(s):
new = s.upper()
return new
print(make_upper(input('input lowcase to make them capital')))
def make_lower(s):
new1 = s.lower()
return new1
print(make_lower(input('input capital to make them lowcase'))) |
1708d66404362fb9a0e18008e6e500453235a49e | chandnipatel881/201 | /chap3.py | 407 | 4.25 | 4 | print "This program illustrates average of numbers"
# total_num = input ("How many numbers you want to average : ")
# sum = 0.0
#
# for i in xrange(total_num):
# sum = sum + input("Enter: " )
# average = sum/total_num
# print average
avg = 0.0
count = 0
while True:
total = avg * count
num = input("Enter ... |
d917f727a549ea557428d218dc930f343fe2b98c | chandnipatel881/201 | /topDownLab.py | 3,406 | 3.984375 | 4 | import calendar
# some constants
MIN_YEAR = 1900
MAX_YEAR = 2500
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
weekdayFor1990 = 0
def printGreeting():
print "This program will print the calender for the year you enter"
def getValidInt(question, min, max):
# use a bad... |
d12aeb406b14ac6da003d4e593ae7af47a5c6d88 | LairdCP/wtf | /wtf/node/__init__.py | 2,460 | 3.84375 | 4 | class UninitializedError(Exception):
"""
Exception raised when routines are called prior to initialization.
"""
pass
class InsufficientConfigurationError(Exception):
"""
Exception raised when sufficient configuration information is not available.
"""
pass
class UnsupportedConfigurationError(Except... |
1d174d9c7a783642bb28e862b830b7d511bafc7c | vamerico/Programacao | /Python/EX15.py | 276 | 3.75 | 4 | alt = float(input('Digite a sua altura em (m): '))
peso = float(input('Digite o seu peso (em Kg): '))
imc = peso / (alt * alt)
if(imc<20):
print('Abaixo do Peso')
elif(imc>=25):
print('Acima do Peso')
else:
print('Peso Ideal')
|
bb5ef03d3d8ee1b51a9e766b51799e7e55d66d36 | vamerico/Programacao | /Python/EX26.py | 281 | 4.0625 | 4 | numero = int(input('digite um numero positivo: '))
while(numero<=0):
print("Digite somente numeros positivos")
numero = int(input('digite um numero positivo: '))
print("Tabuada do ",numero)
for i in range( 1, 11 , 1) :
tab = numero*i
print(numero," x",i," = " , tab) |
73aaf7187529c9857a7d21ac60be9ec1006a13dc | vamerico/Programacao | /Python/EX29.py | 116 | 3.5625 | 4 | soma=0
for x in range( 0 , 101 , 1):
soma=soma+x
print("A soma dos numeros positivos de 1 a 100 e: ",soma) |
6f3ac4d9e2576fe149a71935b65d5e03071af050 | vamerico/Programacao | /Python/EX36.py | 395 | 3.75 | 4 | num = []
segvet = []
print('insira 20 numeros:')
for i in range(0, 20, 1):
x = int(input())
num.append(x)
b = int(input('insira uma constante multiplicativa:'))
for i in range(0, 20, 1):
y=num[i]*b
segvet.append(y)
print('Os numeros inseridos e multiplciados pela constante... |
abd5ab05ed62594269cdda8e461509b35dd5abd7 | codingSIM/CardGames | /General.py | 4,299 | 3.84375 | 4 | from time import sleep
class Card:
suits = ["Diamonds", "Clubs", "Hearts", "Spades"]
numbers = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
suitsSymbol = ["♦", "♣", "♥", "♠"]
def __init__(self, suit, number):
self.__suit = suit # We don't want to change the ... |
638e237ed30897d1d51dcad84eb74c21f8b82efe | jingr1/python_learn | /hello.py | 3,520 | 3.859375 | 4 | #!C:\python35\python.exe
#!/usr/bin/env python3 #linux system
# -*- coding:utf-8 -*- # for chinese character
'''
name = input('please enter your name: ' )
print("hello",name)
'''
#景日
#string and encoding
print ('牧云轩')
ascii_A = ord('A')
str_B = chr(66)
bytes_abc = 'abc'.encode('ascii')
utf_jr = '景日'.encode('utf-8')... |
36a43f5e0feff303d89919ee9b379d977f5751c6 | jingr1/python_learn | /exercise/sudoku.py | 2,307 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-10-14 09:17:06
# @Author : jingray (lionel_jing@163.com)
# @Link : http://www.jianshu.com/u/01fb0364467d
# @Version : $Id$
import os
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9... |
a03ba243f37e4b53a63e527914bc323c80899031 | jingr1/python_learn | /threads.py | 2,386 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time, threading, multiprocessing
# 新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep... |
d8d84e4893a62c93de5b27553434d06f605dd7ff | h-asano/nlp100knock | /chapter2/q16.py | 802 | 3.671875 | 4 | import argparse
import sys
def main():
parser = argparse.ArgumentParser(
description='Output pieces of FILE to FILE1, FILE2, ...;')
parser.add_argument('file')
parser.add_argument('-n', '--number', type=int,
help='split FILE into n pieces')
args = parser.parse_args()
... |
08197c4f418d8742631cc813c178056f2209dfe4 | LaxminarayanaViSEEC/DailyTasks | /DT#22062020/util.py | 811 | 3.515625 | 4 |
def inside_justifier(bbox_1:dict, bbox_2:dict):
"""
Returns True if bbox_2 is inside bbox_1
bbox_1 input format is dictionary
bbox_1 = {'Left':0,
'Top':0,
'Width':10,
'Height':10}
bbox_2 is same as bbox_1
"""
bbox_1_left = bbox_1['Left']
bbox_1_top ... |
8115775c9a79aa2e8f66ecc4bf4223b99fa526df | songwonie/TIL | /Python-basic/basic-starcraft/pr10_function.py | 4,191 | 3.515625 | 4 | # 함수
def open_account():
print("새로운 계좌가 생성되었습니다.")
open_account()
# 전달값과 반환값
def deposit(balance, money): # 입금
print("입금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance + money))
return balance + money
def withdraw(balance, money): # 출금
if balance >= money: # 잔액이 출금보다 많으면
print("출금이 완료되었습니다. 잔액은 {0} ... |
faa39cc453310743c2ff03bc8672478748e9dc68 | songwonie/TIL | /Python-basic/basic-starcraft/pr14_methodOveriding.py | 2,987 | 3.609375 | 4 | # 메서드 오버라이딩
# pr13의 스타크래프트 이어서...
class Unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
def move(self, location):
print("[지상 유닛 이동]")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"\
.format(self.name, location, self.speed))
... |
7da3db61afacf88dcf426c92c0d5c5b4c54d0602 | songwonie/TIL | /Python-basic/num.py | 406 | 3.65625 | 4 | '''짝수/홀수 구분하기'''
# 1) str형 구분
num_str = input("숫자를 입력하시오:")
last_str = num_str[-1]
print(type(last_str))
if last_str in '02468':
print("짝수")
elif last_str in '13579':
print("홀수)
# 2) int형 구분
str = input("숫자를 입력하시오:")
num = int(str) # int형 변환
print(type(num))
if num % 2 == 0:
print("짝수")
if num % 2 == 1:
print("... |
58a2059860d5717db8e738b9991c590775c3f884 | HiskelKelemework/DSP_LAB | /lab_1/sec_1/occurence_counter.py | 912 | 3.59375 | 4 | from threading import Thread, Lock
total_count = 0
def count_word(filepath, search_word, l):
global total_count
counter = 0
with open(filepath) as f:
for line in f.readlines():
for word in line.split():
if word.lower() == search_word:
counter += 1
... |
360a3b520b4dab42ac3cd4ef78e10ff985640b2f | loyeloye/Assignment-2 | /Numpy and pandas/array_index1.py | 406 | 3.859375 | 4 | import numpy as np
array = np.arange(0,12,)
print (array)
#print(array [0:5]) #shows array of (0,1,2,3,4)
#print(array[2:6]) #shows array (2,3,4,5)
array [0:5] = 30 #numbers 0-4 get assigned the value of 30
print(array)
# intresting thing and important
array2= array [0:6]
array2[:] = 29 #all elements... |
d4b2cdb089e531181f30b6130d915878bd5744ef | Aiswarya333/Python_programs | /const5.py | 1,595 | 4.1875 | 4 | '''CELL PHONE BILL - A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs
$0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the enti... |
e0c092d943f38f9fe3367f38de20304706ad7974 | ar-shestopal/algorigthms | /calc.py | 1,532 | 3.671875 | 4 | # class Solution(object):
# def __eval_helper(self, expression, index):
# op = '+'
# result = 0
# while index < len(expression):
# char = expression[index]
# if char in ('+', '-'):
# op = char
# else:
# value = 0
# if char.isdigit():
# value = int(char)
... |
41eca5f7b6eb7078d226452949782295dc3b5601 | CrislyGonzalez/monjesYcanibales--Paradigma-Funcional | /ProyectoLenguajes.py | 4,951 | 3.78125 | 4 | """
Creado por Crisly Gonzalez S
Carne 2013389846
Fecha finalizacion 19/04/2016
"""
def removeIf(funcion, lista):
if len(lista) == 0:
return []
elif funcion(lista[0]):
return removeIf(funcion,lista[1:])
else:
return [lista[0]] + removeIf(funcion,lista[1:])
#movimientos
def unCan... |
38f3243733f0a36e5c2ca109f986f9fdc94cd9f0 | ed4m4s/learn_python_the_hard_way | /Exercise18.py | 569 | 4.1875 | 4 | #!/usr/bin/python
# Exercise on Names, Variables, Code, Functions
# this one is like the scripts we did with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Take out the *args as you do not need it
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg... |
42cff654eaa388a09a859f3fcc2c1c90eb557413 | ed4m4s/learn_python_the_hard_way | /Exercise19.py | 1,017 | 3.984375 | 4 | #!/usr/bin/python
# Exericse on Functions and Variables
# Defining a Variable named cheese_and_crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
... |
72383af3e252445b9b702ab4c4e9df517f1442d4 | ed4m4s/learn_python_the_hard_way | /Exercise11.py | 390 | 3.984375 | 4 | #!/usr/bin/python
# Exercise on prmpting a user to give output
print "How old are you?"
age = int(raw_input())
print "How tall are you?"
height = float(raw_input())
print "How much do you weight?"
weight = int(raw_input())
print "Which is your favourite team"
team = raw_input()
print "You are %d old, %d in height, %... |
aa485648439f686e0e658d3ac64e21fad30a4803 | tuna-f1sh/aoc-2020 | /python/day1.py | 838 | 3.8125 | 4 | from inputs import get_ints
INPUT = get_ints(2020, 1)
def find_sum_multiple(values, part = 1):
found = False
z = 1
for i, v in enumerate(values):
for j, x in enumerate(values):
if i == j:
continue
if part == 2:
for k, z in enumerate(values):... |
8b22d29fe68d630751114148481d8b6b83111bb0 | tuna-f1sh/aoc-2020 | /python/day3.py | 2,633 | 3.59375 | 4 | import math
from inputs import get_input
"""
You start on the open square (.) in the top-left corner and need to reach the bottom (below the bottom-most row on your map).
The toboggan can only follow a few specific slopes (you opted for a cheaper model that prefers rational numbers); start by counting all the trees y... |
4e1b3aefb34d57069cf41c6b75d071a58d2a24f4 | yyht/BERT | /t2t_bert/utils/dsmm/utils/np_utils.py | 148 | 3.71875 | 4 |
import numpy as np
def _try_divide(x, y, val=0.0):
"""try to divide two numbers"""
if y != 0.0:
val = float(x) / y
return val
|
8714fc3a90c9d4796b8adf41fdca19bd21c0692f | yyht/BERT | /bert_language_understanding-master/bert_language_understanding-master/model/poistion_wise_feed_forward.py | 5,281 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import tensorflow as tf
import time
"""
Position-wise Feed-Forward Networks
In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully
connected feed-forward network, which is applied to each position separately and identically. This
consists of two linea... |
b3a33028c25c932e2e3fa6e7b9b312fbf2c4bd5a | syedrizvi03/python--programming | /beginner level/odd or eve.py | 125 | 3.859375 | 4 | a=input("enter the nos:")
if(isinstance(a,(int,float))):
if(a%2==0):
print("even")
else:
print("odd")
else:
print("invalid")
|
c8f190fa82909e484947c8ff89ef2cbaa99dfa50 | katiachaparro/Proy2-IA | /jugador_libre.py | 458 | 3.59375 | 4 | #
# Universidad Nacional de Itapua
# Inteligencia Artificial
# 7mo Semestre
#
# Proyecto#2: Torneo Ta-te-ti 3d
#
# Autor: Amin Mansuri, modificado por Wildo Monges
#
# NO ES NECESARIO MODIFICAR ESTE ARCHIVO
#
import random
def jugar(tablero, tiempo) :
for z in range(len(tablero)) :
for x in range(len... |
26855dfdd69c47f86926a78d02fbeaf0b6667df5 | Amogh-Bharadwaj/Elliptic-Curve-Cryptography | /Scalar_Multiplication.py | 870 | 3.890625 | 4 | from Cryptodome.Util.number import inverse
# You may also use sympy's inverse function
from collections import namedtuple
Origin = 'O'
Point = namedtuple('Point', ('x','y'))
# a = ?
# b = ?
# p = ?
def point_addition(P, Q):
if P == Origin:
return Q
elif Q == Origin:
return P
elif P.x == Q... |
ab6ae906a8a1489395462f81be70f39965b40de1 | xuanthuong/golfgame | /rule.py | 2,524 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# Description: Define some rules of golf game
# By Thuong.Tran
# Date: 21 Aug 2017
import random
import json
RULE_DATA = "./data/rule_data.json"
LEVEL_PROB = "./data/level_prob.json"
class rule:
def __init__(self, hole, game_type):
self.hole = hole
self.game_type = game_type
sel... |
beb7fb85aa10f1a352e48b991ba639923804bf29 | edianibarrola/master-python-programming-exercises | /exercises/17-Century/app.py | 220 | 3.71875 | 4 | #Complete the function to return the respective number of the century
#HINT: You may need to import the math module.
def century(year):
return None
#Invoke the function with any given year.
print(century()) |
c6f0fefbaeb3888257f971267ed3b88dac5005ae | edianibarrola/master-python-programming-exercises | /exercises/18-Total_cost/app.py | 590 | 4.09375 | 4 | #Complete the function to return the total cost in dollars and cents of N cupcakes.
#Remember you can return multiple parameters => return a, b
def total_cost(d,c,n):
dollars = int(d)
cents = int(c)
cupcakes = int(n)
total_amount_dollars = 0
total_amount_cents = 0
total_amount_dollars = int((d... |
bc545e38dada84d7f7621b6574ff152c61f7a662 | acatesby/Gatton-Computer-Science-Club | /lostcow/where my cows at lol.py | 417 | 3.828125 | 4 | x = int(input("Where is John starting out?"))
cowPos = int(input("Where is the cow?"))
cowPos -= x
x = 0
farmerPos = 0
distanceTraveled = 0
newPos = 1
turn = 1
while (farmerPos - cowPos) * (cowPos / abs(cowPos)) < 0:
distanceTraveled += abs(newPos) + abs(farmerPos)
farmerPos = newPos
newPos = (-2)**turn
turn += ... |
44d82e18384cb8c9b769bd05284afbb75ba8b622 | pavelbraginskiy/appleseed | /parsing.py | 5,879 | 4.03125 | 4 |
import cfg
def scan(code):
"""Take a string and yield a series of tokens."""
# Add a newline to the end to allow peeking at the next character
# without requiring a check for end-of-string
code += "\n"
i = 0
while i < len(code):
char = code[i]
if char in cfg.WHITESPACE:
... |
d326db41baaedaab1a768edd3d117f48824decd0 | AnanthKumarVasamsetti/design_patterns | /chain of responsibility/chain_of_responsibility.py | 1,899 | 3.984375 | 4 | """
Chain of responsibility: In this structural pattern the processing of any given request is handled through a chain of handlers.
Request is passed across the chain of handlers until it is fulfilled.
Example : In following example there will be display of processors which would to take the re... |
6047b085643033e6cfaca53a0bca66bfa9aa872b | kyunghee28/pythonTest | /day0402/numpyTest05.py | 238 | 3.515625 | 4 | import numpy as np
# 파이썬 배열을 numpy배열로
a = [1,2,3,4,5,6]
# a를 numpy배열로
c = np.array(a)
print(type(c))
# numpoy배열을 파이썬 배열로
b = np.arange(6)
# b를 python 배열로
d = list(b)
print(type(d))
|
0813cda333a1466af043aff4282b0670eae0d940 | kyunghee28/pythonTest | /day0403/ex02.py | 2,100 | 3.921875 | 4 | import numpy as np
# 예제 10. numpy 배열의 연산
# broadCasting : 어떤 값 하나가 배열의 요소만큼 연산을 수행
# ex. 1 + [1,2,3,4,5]
# vector Operation(vectorization) : 두개의 배열의 인덱스가 같은 요소끼리 연산을 수행
# ex. [1,2,3] + [4,5,6] => 열의 크기가 같아야 한다.
# broadCasting
a = np.array([1,2,3,4,5])
b = a + 1
print(b) # 배열의 요소에 각각 1을 더해 준다. -... |
d3a89292ff555bfc9824d630330a632c317bb003 | kyunghee28/pythonTest | /day0409/ex06.py | 664 | 3.5625 | 4 | from sklearn import preprocessing
import numpy as np
# 때에 따라 존재하지 않는 임의의 특징값(feature)를 만들어야 하는 경우가 있을 수 있는데
# sklearn 의 preprocessing 을 이용하여 임의의 특징값을 생성해 봅시다,
x = [[0,1],[3,5]]
x2 = preprocessing.add_dummy_feature(x)
# add_dummy_feature ==> value를 생략하면 1을 각 행마다 추가해 준다.
print(x2)
'''
[[1. 0. 1.]
[1. 3. 5.]]
... |
183caf95ddc793b7232f77148263f01905c2153b | kyunghee28/pythonTest | /day0402/numpyTest07.py | 274 | 3.5 | 4 | import numpy as np
a = ['160.7','180.9','145.2','175.7','160.7','165.8']
# 연습 ) 파이썬 배열의 numpy 배열로 만든 후 170이상 데이터 뽑아
# 새로운 numpy배열로 만드세요
b = np.array(a, dtype='float64')
c = b[b > 170]
print(c)
print(type(c))
|
bd25ed1fc8e82584fa0b3849f1eef9700bb0a229 | kyunghee28/pythonTest | /day0405/ex03.py | 876 | 3.625 | 4 | # 합치고자 하는 두개의 파일에 데이터 수가 일치하지 않아요
# dan 학생의 점수정보는 없다.
import numpy as np
import pandas as pd
df1 = pd.read_csv('../data/stu01', sep="::", engine='python')
df2 = pd.read_csv('../data/stu02', sep="::", engine='python')
df = pd.merge(df1,df2)
print(df) # dan은 나오지 않음
'''
name kor eng mat bio class age
0 ... |
4f6055b3f73e62ca48c359b623c5d878df5ba103 | KrishnanandBiradar/python_click | /lib/4-commands-groups.py | 546 | 3.75 | 4 | import click
@click.group()
def main():
'''use click.group for grouping commands to function'''
pass
@main.command()
@click.argument('text')
def reverse(text):
'''reverse a text'''
click.echo(text[::-1])
@main.command()
@click.argument('text')
def getovels(text):
'''extract ovels'''
ovels = [... |
25852be6673399b024193f1956d0aad2840b4325 | goodlucky1215/artificial-intelligence | /1.딥러닝과러닝머신/1기본/2.스크레이이핑(원하는 데이터 추출).py | 530 | 3.5625 | 4 | #라이브러리 읽어 들이기
from bs4 import BeautifulSoup
#분석하고 싶은 HTML
html="""
<html><body>
<h1>스크레이핑이란?</h1>
<p>웹 페이지를 분석하는 것</p>
<p>원하는 부분을 추출하는 것</p>
</body></html>
"""
# HTML 분석하기
soup = BeautifulSoup(html,'html.parser')
#원하는 부분 추출하기
h1=soup.html.body.h1
p1=soup.html.body.p
p2=p1.next_sibling.next_sibling
#요소의 글자 출력하... |
c36df596298272dbb0b00f576c9f2b00b4cc3df1 | goodlucky1215/artificial-intelligence | /1.딥러닝과러닝머신/6/5.N-gram/N-gram.py | 2,577 | 3.5 | 4 | #레벤슈타인 거리 구하기
def calc_distance(a,b):
'''레벤슈타인 거리 계산하기'''
if a == b: return 0
a_len = len(a)
b_len = len(b)
if a == "":return b_len # a 가 비어있다면, b_len의 길이만큼 채워지니깐 그 횟수가 됨.
if b == "":return a_len # b 가 비어있다면, a_len의 길이만큼 채워지니깐 그 횟수가 됨.
# 2차원 표 (a_len+1, b_len+1) 준비하기
matrix = [[] for i i... |
2aa40e17f5a7b75075462bf5d2b546a7776b1620 | liushuailong/python_2_work | /017-列表当实参传递到线程中.py | 650 | 3.6875 | 4 | # 导入 threading 模块
import threading
# 导入 time 模块实现延时功能
import time
g_nums = [11, 22, 33]
def work1(nums):
nums.append(44)
print("___in work1:{}".format(nums))
def work2(nums):
time.sleep(1)
print("___in work2:{}".format(nums))
def main():
# 创建一个线程,去修改g_num的值
t1 = threading.Thread(target... |
81190be06991bf9d7d942ccc7962d7a0b1881c61 | deepak7514/Venturesity-Need_For_Hack | /need25.py | 1,225 | 4.1875 | 4 | import datetime
while True:
date=raw_input("Enter date in format dd-mm-yyyy: ")
if not date:
print 'Please provide input'
continue
date=date.strip().split('-')
if len(date)!=3:
print 'Day, Month and Year should be separated by \'-\'.'
continue
d,m,y=date
if y.isdi... |
9075f8baff1862e391820b915fb941c695d2d554 | ksea-cal/first-repo | /first_repo/utils.py | 470 | 3.875 | 4 | def change_player(player):
return 1 - player
def number_to_coord(number):
if number > 9:
print("Invalid number")
return
horizontal = (number - 1) % 3
vertical = (number - 1) // 3
return (horizontal, vertical)
def play(board, player):
if player == 0:
player_piece = 'X'
... |
1f024b3de44ee95d07ab6b44a2c3fcf22079ba09 | pioziela/programming-learning | /Hacker_Rank_Exceptions.py | 965 | 4.25 | 4 | import sys
def divide_exceptions():
"""
divide_exceptions function trying to divide two values.
The user provides data in the following format:
- in the first line the number of divisions to be carried out,
- in the following lines, the user provides two values to divide, the values should be sepa... |
b4b144bde2eeb3377ec7c17ad9a0a09efd781021 | InfiniteDisorder/Numerical-Methods | /lab_3_numerical_integration/numerical_integration.py | 672 | 3.78125 | 4 | # numerical_integration.py
# describes:
# 1) middle rectangle method
# 2) trapezium method
# 3) simpson method
def mid_rectangle_method(a, b, f, n):
step = (b - a) / n
s = 0
for i in range(0, n):
s += step * f(a + (i + 0.5) * step)
return s
def trapezium_method(a, b, f, n):
step = (b - a... |
e760956adaad129a03ccc103938b87790651c5ba | bhavya1803/one_shot_learning- | /roman_to_int.py | 685 | 3.59375 | 4 | class Solution:
def romanToInt(self, s):
arr={'I' : 1,'V' : 5,'X' : 10,'L' : 50,'C' : 100,'D' : 500,'M' : 1000}
arr2={'IV' : 4, 'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
li=list(s)
count=0
if s in arr2:
for j in arr2:
if(s==j):
... |
a8ccbb64d4ebd2c79d1da634d6c69b47793de507 | GOFIRST-Robotics/NASA-RMC-2018 | /testCode/Sensors/LIDAR/mollyV2/filetoimage3dpyplot.py | 1,479 | 3.5 | 4 | import pygame
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax=Axes3D(fig)
#ax=plt.axes(projection='3d')
swidth=1000
sheight=1000
screen=10
#screen=pygame.display.set_mode((swidth,sheight))
#pygame.display.flip()
color=[240,240,240]
def heightcolor(z):
color... |
d5a00f615405f587bafeaa8865067d151497f6cb | anselb/Core-Data-Structures | /routing/scenario_2_and_3.py | 2,533 | 3.9375 | 4 | """You have a carrier route list with 100,000 (100K) entries (in arbitrary
order) and a list of 1000 phone numbers. How can you operationalize the route
cost lookup problem?"""
import sys
sys.path.append('../source/')
# from hashtable import HashTable
# I realized it is faster to use the built in dictionary
def rea... |
a1b191446e960f38e7e6621275d85ac7629d0368 | geetha10/GeeksForGeeks | /basic/factorial.py | 317 | 4.25 | 4 | def factorial(num):
result = 1
for x in range(1, num+1):
result = result*x
return result
num = input("Enter a number for finding factorial")
if num.isdigit():
num = int(num)
fact = factorial(num)
print(f"Factorial of {num} is {fact}")
else:
print("Please enter a valid Integer")
|
2afb1fe312b9226f32cf6608a59c2f3a0d59ee18 | tg1625/Leetcode-Practice | /Container-With-Most-Water.py | 1,269 | 3.703125 | 4 | """
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
https://l... |
87107ac51d964a02ae07991f35b039752d21aaab | Yagomfh/sudoku_hacker | /solve_it.py | 3,066 | 3.6875 | 4 | #!/usr/bin/python3
import sys
from pynput.mouse import Controller as ctr
from pynput.mouse import Button
from pynput.keyboard import Key, Controller
import time
def get_todo_list(grid):
res = []
for x in range(0, 9):
for y in range(0, 9):
if grid[x][y] == 0:
res.append({'x' ... |
69fecfadc2c92d4e20ae4ee3fe8c0e4cb9080bb9 | tpoljak/BERT_RESSEL | /bert_model/modeling_utils.py | 7,324 | 3.65625 | 4 | import collections
import six
import re
import math
import tensorflow as tf
def gelu(input_tensor):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
input_tensor: float Tensor to perform activation.
Returns:
`input_tensor... |
99489f3e209bebc5a20b15b327e0545c1cd3dafb | tutfakulunto/codingDojo | /PythonFlask/multiply.py | 116 | 3.75 | 4 | def multiply(list, multiple):
list = [x * multiple for x in list]
return list
b = multiply(a, 5)
print(b)
|
3a3f8d499bd79ef279dffd230c677b88e0ceb13a | tutfakulunto/codingDojo | /PythonFlask/draw_stars.py | 604 | 3.734375 | 4 | # Part 1
x = [4, 6, 1, 3, 5, 7, 25]
def draw_stars(num_list):
for num in num_list:
stars = ''
for i in range(num):
stars += '*'
print(stars)
draw_stars1(x)
# Part 2
y = [4,'Tom',1,'Michael',5,7,'Jimmy Smith']
def draw_stars2(name_list):
for item in name_list:
output... |
c8746ef7b8712c0c28bd3d0aeb7eeeb2811af652 | yanjj199609017239230/D-python-gy-1908A-demo | /demo/day02/list_demo.py | 931 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#__title__ = ''
#__author__ = 'xuepl'
#__mtime__ = '2019/9/5'
l = [1,2,3,4,5,6,7,8,9,0]
# 截取某一段内容git
print(l[1:7])
print(l[:6])
print(l[2:])
print(l[:-1])
# 步长
print(l[::2])
print(l[1::2])
# 倒叙
print(l[::-1])
# 拼接 +
#
# # 成员判断 in
# 新增数据
# 在列表最后新增单个数据
l.append(11)
print(... |
cc8d3b1b5d12299494d897fc24e6173b0a407aca | ricamos/study_code | /Programming _Foundations_with_Python/aula3_Use_classes_Draw_Turtles/a3c5_mindstorms_v2.py | 1,009 | 4.625 | 5 | """
Versão otimizada: Uso de funções em codigos repetido.
Estudo do uso de classes. No caso a classe turtle.
Usamos varias instancias da classe turtle. instancia como brad e angie.
Podemos pensar em uma classe como uma planta de um edificio. E em seus objetos (Edificios criado a partir da planta)
como exemplos ou ins... |
d7739e3eb6a10b172b7777d54c14c7b73e701c85 | ricamos/study_code | /Programming _Foundations_with_Python/aula3_Use_classes_Draw_Turtles/Secret_Message.py | 771 | 3.828125 | 4 | import os
files_address = r"C:\Users\rcoelho\Downloads\prank\prank"
def rename_files():
# 1 Get file names from folder
file_list = os.listdir(files_address)
print(file_list)
saved_path = os.getcwd() # In the end go back to saved_path
print("Current directory " + saved_path)
os.chdir(files_ad... |
15404b8fc706ee063c958850d57d44f7086b3f54 | Harpreet1214/python-challenge | /PyPoll/main.py | 2,762 | 3.890625 | 4 | #import library
import os
import csv
# CSV file to be read from Resources
csv_election_data = os.path.join(".","Resources","election_data.csv")
#List of variables
Total_votes = 0
Khan_vote = 0
Correy_vote = 0
Li_vote = 0
Otooley_vote = 0
# Read the CSV file
with open(csv_election_data,"r") as csvfile:
csvreader ... |
abaf862778380496482c4134999789ef331eaf73 | necroant/PY100_Oct2020_Prac | /exam.py | 7,288 | 4.25 | 4 | def int_input(prompt_string="Введите число "):
"""
:return: Integer from keyboard input
"""
n = input(prompt_string)
while not n.lstrip("-").isnumeric():
n = input("Это не число.\n" + prompt_string)
return int(n)
if __name__ == '__main__':
# 1.4 Записать логическое выражение, ко... |
5d3458477603cf4efcc142ee898e321cf1bf81d3 | gauravndabhade/MyCart | /product/cli.py | 963 | 3.546875 | 4 | import click
from product.controller import ProductController
from category.controller import CategoryController
product_controller = ProductController()
category_controller = CategoryController()
@click.group()
def product():
"""Manage products"""
pass
@ product.command()
def create():
"""Create new pr... |
b47def14c4611c48df0fb0669ab014cc8dfc811f | bigeast/PE | /PE199.py | 991 | 4.03125 | 4 | #/********************************
# * Author: bigeast
# * Time: 2015-05-02
# * Description: AC.
# * http://en.wikipedia.org/wiki/Descartes%27_theorem
# ********************************/
from mpmath import mp
def dcurve(a, b, c):
return a + b + c + 2 * mp.sqrt(a * b + b * c + c * a)
... |
d98d83c9bc83d6e376a9fd113ededa3aa73bd0e3 | davidyeon-finance/letuin-tutorial | /selfnumber.py | 174 | 3.78125 | 4 | def myfunction(num : int):
N = len(str(num))
print(N)
sum = 0
for n in range(N):
sum += int(str(num)[n])
return sum + num
print(myfunction(123)) |
9dab9798b01fadc7ae4eb889304c66f905093617 | yiyisf/SKLearn | /com/yiyi/learn/argParse.py | 818 | 3.828125 | 4 | import argparse, sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=float, default=1.0, help='What is the first number?')
parser.add_argument('--y', type=float, default=1.0, help='What is the second number?')
parser.add_argument('--operation', type=str, default='add', h... |
c0cee7e4da8f65223209c9463e6cad4b4b4b5a95 | tingjuch/algo-notes | /codes/largest_even_sum.py | 685 | 3.546875 | 4 | # A: array of N positive numbers
# K: positive integer
# Find largest even sum when selecting K numbers in A with distinct positions
def solution(A, K):
odds = []
evens = []
for n in sorted(A, reverse=True):
if n % 2 != 0:
odds.append(n)
else:
evens.append(n)
... |
6913c66eb5172c1884e3722f7b4abc86679fa06b | Andreeapripa/-Instruc-iunea-FOR | /problema_12_IF.py | 374 | 3.6875 | 4 | #12)“Mă iubeşte un pic, mult, cu pasiune, la nebunie, de loc, un pic,…”. Rupând petalele unei margarete cu x petale, el (ea) mă
#iubeşte ….
x=int(input('Introduceti numarul='))
if x%5==1:
print('... un piv')
elif x%5==2:
print('mult')
elif x%5==3:
print('cu pasiune')
elif x%5==4:
print('la neb... |
e70e9eb9065981b65a038fe0e383a91dd1167765 | Andreeapripa/-Instruc-iunea-FOR | /problema_10_IF.py | 706 | 3.5625 | 4 | #10)La ferma de găini Copanul este democraţie. Fiecare găină primeşte exact acelaşi număr de boabe de porumb. Cele care nu pot
#fi împărţite vor fi primite de curcanul Clapon. Să se spună cine a primit mai multe boabe şi cu cât. În caz de egalitate, se va
#afişa numărul de boabe primite şi cuvântul "egalitate". Datel... |
721b2651ffb8c02d09a2130810f3baf3294c48ec | jayantpranjal0/ITW1-Lab | /python-assignments/3/4.py | 219 | 4.375 | 4 | '''
Python program to read last n lines of a file.
'''
with open("test.txt", "r") as f:
n = int(input("Enter number of lines from last to read: "))
for i in f.readlines()[-n:]:
print(i, end = "") |
79d5853ce0f7dd8175bc012bb511c79ab86cbcec | jayantpranjal0/ITW1-Lab | /python-assignments/2/8.py | 156 | 4.25 | 4 | '''
Python program to find maximum and the minimum value in a set
'''
s = set(map(int, input("Enter the set: ").split()))
print(max(s))
print(min(s)) |
4bc1c71828f44dda49523303fa15adc3ba9ed9d3 | jayantpranjal0/ITW1-Lab | /python-assignments/1/14.py | 213 | 4.21875 | 4 | '''
Python program to get the number of occurrences of a specified element in an array.
'''
l = input("Enter the array: ").split()
e = input("Enter the element: ")
print("No of occurence: "+str(l.count(e))) |
ef5a5ef91aa89a32839640b4ae1b3210ea9faec5 | jayantpranjal0/ITW1-Lab | /python-assignments/1/18.py | 329 | 4 | 4 | '''
Python program to find the list in a list of lists whose sum of elements is the highest
'''
def max_sum(l):
ans = l[0]
s_max = sum(ans)
for i in l:
if sum(i) > s_max:
s_max = sum(i)
ans = i
return ans
l = [[1,2,3],[4,5,6],[10,11,12],[7,8,9]]
print(max_... |
eecf3b4c3635d6de005320cc22de378334d64723 | jayantpranjal0/ITW1-Lab | /python-assignments/2/15.py | 342 | 4.1875 | 4 | '''
Python program to sort a list of elements using the selection sort algorithm
'''
a = list(map(int, input("Enter the list: ").split()))
n = len(a)
for i in range(0,n-1):
m = a[i]
pos = i
for j in range(i+1,n):
if m > a[j]:
m = a[j]
pos = j
a[i], a[pos] = ... |
4f3308ec3c3a1373db2c8657e800c8de4d942d99 | jayantpranjal0/ITW1-Lab | /python-assignments/4/python5.py | 24,726 | 3.9375 | 4 | #Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays.
#It is the fundamental package for scientific computing with Python.
#It save coding time. Example: No for loop for many vector and matrix operations.
#Faster Exe... |
9f08f225b4d19ab56c1d751b1978ce358f1de397 | jayantpranjal0/ITW1-Lab | /python-assignments/4/13.py | 186 | 3.609375 | 4 | import numpy as np
arr = np.array([1,2,3,4,5])
print("No. of elements:", arr.size)
print("Length of one array element:", arr.itemsize)
print("Total bytes:", arr.size*arr.itemsize) |
a52b7fd40ca9a9bb9ef968748f00b276321cef08 | jayantpranjal0/ITW1-Lab | /python-assignments/3/9.py | 178 | 4.03125 | 4 | '''
Python program to write a list content to a file.
'''
l = input("Enter the list: ").split()
with open("test.txt", "a") as f:
for i in l:
f.write(i+"\n") |
7ed95fb7e1c2de78f179109a293250c5b0b65d83 | mr6r4y/re-test | /python/byte-reverse.py | 389 | 3.5625 | 4 | #!/usr/bin/env python3
def byte_rev(x):
x = (x & 0x55) << 1 | (x & 0xAA) >> 1
x = (x & 0x33) << 2 | (x & 0xCC) >> 2
x = (x & 0x0F) << 4 | (x & 0xF0) >> 4
return x
def bin(x):
return "{0:08b}".format(x)
def main():
xx = 0x32
print(hex(xx))
print(bin(xx))
y = byte_rev(xx)
pri... |
46a5b705cc56953719e939eb7845bebccfb4991c | Sviatoslav-Lobanov/Python_learning | /X and O.py | 2,103 | 3.96875 | 4 |
def print_step (table): # Печать игрового поля
print (' | 1 | 2 | 3 |')
print ('---------------')
for i in range(len(table)):
print(f'{i+1} | {table[i][0]} | {table[i][1]} | {table[i][2]} |')
print('---------------')
def check (a): # Проверка введенных координат
point = input(f'Введит... |
b4cb98c16619a4e07f7b0714c7ed97e3acfb68fb | krystal-llose/lps_compsci | /problem_sets/ps7/teamManagerDeluxe.py | 3,600 | 3.78125 | 4 | # teamManagerDeluxe.py
class Player(object):
def __init__(self, name, age, goals, jersey, position):
self.name = name
self.age = age
self.goals = goals
self.jersey = jersey
self.position = position
def getStats(self):
print("Player: " + self.name)
print("A... |
e10256e7abb86ebdaec50238045e8138b975154b | gglluukk/YandexAlgorithms | /Lesson8_Trees.py | 3,371 | 3.59375 | 4 | """Memory manager code"""
def initmemory(maxn):
memory = []
for i in range(maxn):
memory.append([0, i+1, 0])
return [memory, 0]
def newnode(memstruct):
memory, firstfree = memstruct
memstruct[1] = memory[firstfree][1]
return firstfree
def delnode(memstruct, index):
memory, firstfr... |
d0ce9d317158014d927d7672de30c767d97eb9ef | Mechanio/student_perfomance_journal | /windows_for_users.py | 23,003 | 3.75 | 4 | from tkinter import *
from tkinter.ttk import Notebook
import sqlite3
import tkinter.messagebox
import re
import os
conn = sqlite3.connect('data.sqlite')
cur = conn.cursor()
def adding_date(title_of_class_entry, title_of_subject_entry, add_root, teacher_id, date_entry):
cur.execute('SELECT id FROM Su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.