blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
017be8cc7d7f5363b54fa59e8a81a3e31177bb58 | Schikoti/Deep-learning-basics | /Assignments/svm.py | 4,099 | 3.578125 | 4 | import numpy as np
class SVM(object):
def __init__(self, n_epochs=10, lr=0.1, l2_reg=1):
"""
"""
self.b = None
self.w = None
self.n_epochs = n_epochs
self.lr = lr
self.l2_reg = l2_reg
def forward(self, x):
"""
Compute "forward" computati... |
0d43b24c41a3a1f06efae16a590d77b3670a7b10 | niemitee/mooc-ohjelmointi-21 | /osa03-05b_pidempi_jono/src/pidempi_jono.py | 257 | 3.875 | 4 | # Kirjoita ratkaisu tähän
jono1 = input("Anna jono 1: ")
jono2 = input("Anna jono 2: ")
if len(jono1) > len(jono2):
print(f"{jono1} on pidempi")
elif len(jono2) > len(jono1):
print(f"{jono2} on pidempi")
else:
print("Jonot ovat yhtä pitkät")
|
97ccfa048133005feb0906676b95103fa08c9128 | ryotakano77/atcoder | /ABC/217/b.py | 115 | 3.59375 | 4 | s = set(["ABC", "ARC", "AGC", "AHC"])
for _ in range(3):
i = input()
s.discard(i)
for e in s:
print(e) |
92cb0f419f4cb0db04003d31048e816a1a39bc88 | Vimal06Pal/opencv | /opencv_item/thresholding_open_cv_example.py | 1,515 | 3.96875 | 4 | '''thresholding is a very important segment technique
used to seperate the object from its backgroung
it require to compare the each pixel from the predefined
threshold value]
it divide the imge into two part
1. pixel contain value less than threshold value
2. pixel contain value more than threshold value
'''
... |
49d63bb255115cc6673dc84672d1c8a357053f53 | javier-m/The-Algorithm-Design-Manual---Skiena | /skiena/sorting/heapsort.py | 400 | 3.5 | 4 | from typing import Sequence, List
from datastructures import KeyedItem, Heap
def heapsort(items: Sequence[KeyedItem], order=None) -> List[KeyedItem]:
"""O(n*log n)"""
heap = Heap(heaptype=order)
heap.heapify(items)
sorted_items = []
while True:
item = heap.extract_root()
if not it... |
68f37de8548ec7645fc6fcd1e8085cea4294bbb2 | Aequivinius/uibk-python | /exercise-6/bad_importee.py | 146 | 3.734375 | 4 | def tokenize(input):
return [token.lower().strip(".,!") for token in input.split()]
print(tokenize("Wenn es nur einmal so ganz stille wäre!")) |
905d7a100ce416ffc759a31c8d582732243e28bb | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/1fae892354e44ddb8b572d5cae5dce97.py | 440 | 3.9375 | 4 | def difference(number):
square_of_the_sum = square_of_sum(number)
sum_of_the_squares = sum_of_squares(number)
return square_of_the_sum - sum_of_the_squares
def square_of_sum(number):
numbers = range(1,number+1)
numbers_sum = sum(numbers)
return numbers_sum**2
def sum_of_squares(number):
numbers = squ... |
73b3f29a6959aaadf7dab9d840f35abba052310f | undersonrs1/PYTHON_Projetos | /mediaProvas.py | 375 | 3.90625 | 4 |
n1 = eval(input('Digite a sua primeira nota : '))
n2 = eval(input('Digite a sua segunda nota : '))
n3 = eval(input('Digite a sua segunda nota : '))
media = (3/(1/(1/n1+1/n2+1/n3+4)))-4
if media >= 5:
print('Parabéns! Você foi aprovado ')
else:
print('Infelizmente você foi reprovado ')
print('A... |
c1723caeffd8cddac88ce09c5293d03eedfb7223 | khushboo011/python-programs | /tests/array/array_left_rotation_tests.py | 1,786 | 3.578125 | 4 |
import unittest
from array.array_left_rotation import rotate_using_temp_array, rotate_using_reversing_array
class TestArrayLeftRotation(unittest.TestCase):
def test_dummy(self):
self.assertEqual("test", "test")
def test_empty_array(self):
input, expected, rotate_by = [], [], 2
resul... |
5dc1a85cb6008f66590d40487ec539f029c373a7 | SeanMitchell1994/cryptography | /src/caesar/caesar.py | 633 | 3.859375 | 4 | from file_utils import *
from ascii_utils import *
def Encrypt(plaintext, shift):
temp_string = ""
for c in plaintext:
if c.lower == "z":
c = "a"
temp = (ord(c) + shift)
if Is_Special_Character(c):
temp_string += c
else:
c = chr(temp)
... |
63cf64b18e69ecfee2ee07e52c16c97712480037 | BU-Computing/6502PicturePainter | /PicturePainter.py | 2,494 | 3.625 | 4 | import csv
import tkinter as tk
from tkinter import filedialog
import tkMessageBox
# Start of Colour Constants
B = "#$00"
W = "#$01"
R = "#$02"
C = "#$03"
P = "#$04"
G = "#$05"
BL= "#$06"
Y = "#$07"
O = "#$08"
BR = "#$09"
LR = "#$0A"
DG = "#$B"
GR = "#$0C"
LG = "#$0D"
LB = "#$0E"
# End of Colour Constants
def getPict... |
b5e5a6fa8cdfd0b488d5e043eda32d7fb429c31d | ShuyaoLim/Test2 | /python1.2/1_格式化输出.py | 1,016 | 3.890625 | 4 | # name=input("请输入名字:")
# age=input("请输入年龄:")
# job=input("请输入工作:")
# hobby=input("请输入爱好:")
#
# # print("-----------info of "+name+"-----------")
# # print("Name :"+name)
# # print("Age :"+age)
# # print("job :"+job)
# # print("hobby :"+hobby)
# # print("----------end------------")
# #字符串格式化
# s="""
# -----------info of... |
45e3657bb54cb05ef14aed983a436c41e462045a | EduardoArgenti/Python | /CursoEmVideo/aula20.py | 426 | 3.65625 | 4 | # Funções
def linha(msg):
print('=' * 30)
print(f'\t\t{msg}\t\t')
print('=' * 30)
def soma(a, b, res):
res = a + b
return(res)
def contador(* num):
tam = len(num)
print(f'Recebi {tam} valores')
def dobra(lista):
for i in range(0, len(lista)):
lista[i] *= 2
# Programa principa... |
23f3baa82eb62fd0b1df661c5946058c92cfd8bb | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4131/codes/1637_2445.py | 178 | 3.546875 | 4 | gg= input("se C ou F (C/F) ")
valor= float(input("temp:"))
if(gg.upper() == "C"):
ce = (valor*9/5)+ 32
print(round(ce, 2))
else:
f= (5/9)*(valor - 32)
print(round(f, 2))
|
25b377b2bc607feb400bf5a0f750a9cab01e4a76 | matdoz/Sorting-algorithms | /src/Merge_Sort.py | 887 | 3.90625 | 4 | '''
Inspiration from this source: https://www.geeksforgeeks.org/merge-sort/
'''
def mergeSort(list, length):
if len(list) > 1:
left = list[:len(list)//2]
mergeSort(left, len(left))
right = list[len(list)//2:]
mergeSort(right, len(right))
i = j = k = 0
while i < leng... |
b06e3debd9c122d11d203e0649687fa5031fd08c | YellowWaitt/old-python-stuff | /partonia/partonia.py | 8,315 | 3.640625 | 4 | # -*- coding: utf-8 -*-
class Partonia ():
"""Classe en charge de définir toute les règles et mécanismes du jeu"""
def __init__ (self):
# La meilleure initialisation jamais vue
pass
def initialiser_partie (self):
"""Création de la grille de jeu avec les pions à leur position de
... |
e67a38216c50e66f8cfa73551dcb2e725755af31 | Denis-Oyaro/Data-structures-and-algorithms-with-Python | /searching.py | 1,111 | 4.15625 | 4 | """You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and
element... |
799eef036cc75ead3f3525a368fc0fb6ac97d3f7 | C-GDA-TC1028-009-2113/tarea1-JaimeCarrillo22 | /assignments/10Videojuego/src/exercise.py | 383 | 3.671875 | 4 | def main():
#escribe tu código abajo de esta línea
JuegosN= int(input("Dame la cantidad de juegos nuevos: "))
JuegosU= int(input("Dame la cantidad de juegos usados: "))
multiplicacion= JuegosN*1000
multiplicacion2= JuegosU*350
suma= multiplicacion+multiplicacion2
print("El total de la compra... |
5e5066de32e3b08d501d2ed543b4697854ddb3c2 | MRlaura/Python | /CondSent1.py | 750 | 4.25 | 4 | age1 = 18
age2 = 15
age3 = 21
m_age = 18
if age1 >= m_age:
print ("You have the majority age required")
if True:
print ("This is executed, every time it has the majority age required")
else:
print ("You don’t have the majority age required")
print ("Hello! This will always be execute... |
2d157098f1f22a0940dd413d5459cd8e6027fc0b | mikaylakonst/ExampleCode | /loops.py | 1,222 | 4.375 | 4 | # This is a for loop.
# x takes on the values 0, 1, 2, 3, and 4.
# The left end of the range is inclusive.
# The right end of the range is exclusive.
# In other words, the range is [0, 5).
for x in range(0, 5):
print(x)
# This is another for loop.
# x takes on the values 0, 1, 2, 3, and 4. In other words,
# x tak... |
87a9d84709422ce4ff9e5db9fa315316a981be26 | Nideayu/codeing | /section1/1.3格式化输出.py | 844 | 3.9375 | 4 | '''
例子:
age = 18
name = "xiaohua"
print("我的姓名是%s,年龄是%d"%(name,age))
%c 字符
%s 通过str() 字符串转换来格式化
%i 有符号十进制整数
%d 有符号十进制整数
%u 无符号十进制整数
%o 八进制整数
%x 十六进制整数(小写字母)
%X 十六进制整数(大写字母)
%e 索引符号(小写'e')
%E 索引符号(大写“E”)
%f 浮点实数
%g %f和%e 的简写
%G %f和%E的简写
'''
'''
\n代表换行
''... |
682e97cd85096dcc2dce402e07c19a807f4b8515 | ThePlesner/presidentialSpeeches | /readability.py | 2,677 | 3.875 | 4 | import re # Importing regular expression-library
from pathlib import Path # Used to generate OS specific file paths
# Speeches (.txt) are named by the year in which they were spoken
# Returns a string containing the whole transcription of the speech
def readSpeech(year):
filePath = Path('speeches', f'{year}.txt')
... |
26927717239f6b5f036e1215b8596858883ee596 | ishres19/tic-tac-toe | /Desktop/tic_tac_toe/tic_tac_toe.py | 7,180 | 3.859375 | 4 | from tkinter import *
from tkinter import messagebox
def click_button(button):
""" writes 'x' or 'o' in the boxes"""
global clicked, num_clicks
if button["text"] == " " and clicked == True:
button["text"] = 'X' #writes x on the button if the player has clicked on it
clicked = False ... |
dcb00d4469d34f645e47fc3c05a32b65e1edc3a2 | simplynaive/LeetCode | /171. Excel Sheet Column Number.py | 349 | 3.5 | 4 | class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
res = 0
for a in s:
res = 26 * res + (ord(a) - ord('A') + 1)
return res
if __name__ == "__main__":
s = 'AB'
print(... |
8648adfc13ee9ba73775b13e0fd2ddf870427815 | souvenir13/Leetcode | /LongestSubstring.py | 1,777 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 22 16:48:20 2017
@author: bowen
Problem:
寻找最长无重复子串
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without
repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given... |
2fcf5a1abf49fc22b15e9f24a2b6b50a6a8ae179 | Nadia-N/Portfolio | /FruitMachineGame.py | 4,503 | 4.40625 | 4 | #The random library needs to be imported in order to randomise what symbols come up.
import random
#This list are the possible symbols that can be used by the program
symbols = ["Cherry","Bell", "Lemon", "Orange", "Star", "Skull"]
#This condition is necessary for the while loop.
valid = False
#Credit starts at £1
credi... |
903c0cec7d26bd07717637cb2ae9933663e41c3d | Dreamingson/python-learning | /Digital_Tube.py | 1,622 | 3.78125 | 4 | import turtle
import time
def drawLine(draw): # 绘制单段数码管
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
turtle.right(90)
def drawDigit(digit): # 根据数字绘制七段数码管
drawLine(True) if digit in [2,3,4,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,1, 3, 4, 5, 6, 7, 8, 9] else drawL... |
3a37372bcee1df479590b8b53ba717969e3311bb | ishikashendge/python | /10 - Greatest.py | 185 | 3.734375 | 4 | a,b,c=map(int,input("Enter 3 No. - ").split())
if(a>=b and b>=c):
print(a," is greatest.")
elif(b>=c and b>=a):
print(b," is greatest.")
else:
print(c," is greatest.") |
4cb6883f8a8db0c2d1d676fd6e7fabda0a2c7cca | friendbear/AutomateWithPython | /map/ticTacToe.py | 637 | 3.71875 | 4 |
# Input Key and Display Char
the_board = {
'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '
}
def print_board(board):
print(board)
# Game Logic
turn = 'X'
while True:
print_board(the_board)
print('Next turn: ' + turn... |
488c0ed98879ab647bc63bed5ba8b0a9072ee556 | arya200/Arya-s-Coding-Projects | /week 3 - lab3b/vectors.py | 1,664 | 4.46875 | 4 | import math
from math import *
print("This program will calculate the angle between two points, as seen by an observer")
print("")
print("Enter the 3D position of the observer below")
x_obs = float(input("Enter the x value: "))
y_obs = float(input("Enter the y value: "))
z_obs = float(input("Enter the z ... |
cfcfd105f7c9d9609542c773c9c698e8718f30e9 | Andres2902/ParcialHerramientasComputacionales | /ParcialHerramientas.py | 825 | 3.5 | 4 | docente=1
estudiante=2
Productos=[]
doc=eval(input("ingrese su número de documento: "))
rol=eval(input("ingrese si es docente o estudiante: "))
CantProd=eval(input("ingrese cuantos productos va a llevar: "))
CompraTotal=0
for x in range(CantProd):
cod=str((input("ingrese el codigo del producto: ")))
... |
127fff42b203802ac86c91794512dda61fbeffed | ManonLescaut/10_homework | /Vectors.py | 4,707 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Vector():
def __init__(self, x = 0, y = 0, z=0):
self.x = x
self.y = y
self.z = z
def set_vector(self, x, y, z):
self.x = x
self.y = y
self.z = z
return Vector(self.x, self.y, self.z)
... |
fefccbab7d726aae8a41e3ac79945960816b1741 | JorgeCeja/mini-transformer | /data/char_dataset.py | 2,934 | 3.71875 | 4 | import math
import torch
from torch.utils.data import Dataset
class CharDataset(Dataset):
def __init__(self, data, block_size):
chars = sorted(list(set(data)))
data_size, vocab_size = len(data), len(chars)
print('data has %d characters, %d unique.' % (data_size, vocab_size))
... |
3c02fd896b98b1fae2a8b7dd32de0af1592102c5 | Kazzuki/study_python | /53_function_2.py | 757 | 4.0625 | 4 | def menu(entree='beef', drink='wine'):
print(entree,drink)
menu(entree='beef',drink='coffee')
# キーワード引数の辞書化
def menu1(**kwargs):
# {'entree': 'beef', 'drink': 'coffee'}の辞書型で表示される
print(kwargs)
# 辞書型を展開して表示
for k, v in kwargs.items():
print(k,v)
menu1(entree='beef',drink='coffee')
# 以下の様... |
27cfc5f3a46a9d4a23f166af6b5da63a3fb5b658 | riya-21/SITHS-JuniorYrPython | /Magic 8 Ball Challenge.py | 522 | 3.859375 | 4 | from random import choice
responses = ["As I see it, yes", "Ask again later", "It is certain", "Don't count on it", "My sources say no",
"Better not tell you now", "Signs point to yes", "Reply hazy try again", "Very doubtful"]
question = input("What is your question?").strip()
next_question = ""
... |
015be153c029c673767d6b65715c1cd2e678cd56 | alexbarsan944/Python | /Lab9/ex2/ex2.py | 784 | 3.65625 | 4 | # 2) Write a function get_file_info that has one parameter representing a file path. The function will return a
# dictionary with the following fields:
# - full_path - the absolute path of the file
# - file_size - the size of the file
# - file_extension - the file's extension
# - can_read/can_write - True or False, if ... |
9bfe75c39f475af7a7dc921f872039266f32edfe | tylerharter/caraza-harter-com | /tyler/cs301/spring19/materials/code/lec-11/battleship.py | 1,240 | 4.0625 | 4 | def is_ship1(x, y):
ship_x1 = 1
ship_y1 = 2
ship_x2 = 5
ship_y2 = 2
if ship_x1 <= x <= ship_x2:
if ship_y1 <= y <= ship_y2:
return True
return False
def is_ship2(x, y):
ship_x1 = 10
ship_y1 = 5
ship_x2 = 10
ship_y2 = 7
if ship_x1 <= x <= ship_x2:
... |
f305219718db740560614e7a4994a2a65bc7de06 | carlocostacc/fractal | /branch.py | 333 | 3.71875 | 4 | astring = 'F+F+F+F'
actuallvl = 0
def fractal(serie, level, actuallvl):
if actuallvl >= level:
return serie
else:
actuallvl = actuallvl + 1
serie = serie.replace('F', 'F+F-F-FF+F+F-F')
return fractal(serie, level, actuallvl)
astring =(fractal(astring, 2, actuallvl))
p... |
26628e755d39e6349df21d458ad678dfd5fe0c33 | salvadorraymund/Python | /Generators/data_pipeline.py | 953 | 3.5625 | 4 | import csv
file_name = "techcrunch.csv"
lines = (line for line in open(file_name))
list_line = (s.rstrip().split(",") for s in lines)
cols = next(list_line)
company_dicts = (dict(zip(cols, data)) for data in list_line)
funding = (
int(company_dict["raisedAmt"])
for company_dict in company_dicts
if company_... |
e385de0f958a31499461033b1624d3928e40e66c | GabrielMMelo/compilers | /lexical/file_manager.py | 2,607 | 3.703125 | 4 | class GerenciarArquivo:
def __init__(self, arquivo):
self.arquivo = open(arquivo, "r")
self.linha = 1
self.coluna = 0
self.indice = 0
self.linha_entrada = self.arquivo.readline()
self.tamanho_linha = len(self.linha_entrada)
def __ler_caracter_aux(self)... |
a7f872bdca89f5487949651e5431c4a47ed9b72e | NeoMindStd/CodingLife | /baekjoon/10997py/a.py | 770 | 3.609375 | 4 | n = int(input())
space = [[' ']*(4*n-3) for _ in range((4*n-1) if n > 1 else 1)]
def create_universe(idx):
char = '*' if idx %2 == 0 else ' '
# ┌
for i in range(idx, 4*n-3 - idx):
space[idx][i] = char
for i in range(idx, ((4*n-1) if n > 1 else 1)-idx):
space[i][idx] = char
... |
199e4f2f023d92840f00e0b30b3aece0d1bc7ac0 | hu279318344/Python-work | /PycharmProjects/Task/购物车.py | 1,866 | 4.09375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: Python 2.7
@author: Admin
@license: Apache Licence
@contact: yang.hu@live.com
@software: PyCharm
@file: 购物车.py
@time: 2017/2/9 14:26
"""
import sys
products = ['Car', 'Iphone', 'Coffee', 'Mac', 'Cloths', 'Bicyle']
pices = [250000, 4999, 35, 9688, 438, 1500]
shop... |
f9ecb601d9e9f19b37578b3213074ac53f675065 | fenghuoxiguozu/guaziershouche | /guaziershouche/analysis/knn.py | 1,062 | 3.609375 | 4 | from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
df=pd.read_csv(r'F:\guaziershouche\cleaned_data.csv')
df=df.round(0)
# def get_brand_num(brand):
# return np.argwhere(df['car_brand'].unique()==brand)[0][0]
# df['car_bran... |
400b1908e9d1a7d6c480a90fe9653a549d1f8224 | chenboshuo/learn_algorithm | /introduction/union_find.py | 2,386 | 3.8125 | 4 | import unittest
import logging
from typing import *
logging.root.setLevel(level=logging.INFO)
class UnionFind():
def __init__(self, n: int, text: str):
""" Initialize nodes with integer names(0-n-1)
@param n the number of nodes
@param text the user input
"""
self.id = l... |
6ae674f3dd7933e3a8d33ca9ce5ae89adf7d7cd4 | shyam81295/CODING | /leetcode-python/MEDIUM_394-decode_string.py | 1,185 | 3.734375 | 4 | # O(N) time and O(N) space complexity
# implementation problem of stack
# why stack?
# because we need to process on some level as 'last in first order' on the current elements of stack
# when you get ']', pop all alphabets in a string
# then after you get '[', pop all numbers in a string
# append in same stack
cla... |
ab1ae89b29b7e47e543e9cdd703f1a6971974d4b | riopes/MP_Prob3-Python- | /Problem3.py | 676 | 3.875 | 4 | import numpy as np
print(' ')
# Can read nx2 matrix form
xi = int(input("Enter number of rows: "))
yi = 2
print("Enter values in the matrix: ")
# Must be exact values (e.g. twice number of row values)
R = list(map(int, input().split()))
e = np.array(R).reshape(xi, yi)
print(e)
print(' ')
def Python3(e):
... |
f83eba3cf42326790db15420c3cbef7b9d6ee6b2 | kmbabu/guvi | /sss.py | 282 | 4.03125 | 4 | ch=raw_input("enter the charecter")
if(ch=="a"):
print("ch is a vowel")
elif(ch=="e"):
print("ch is a vowel")
elif(ch=="i"):
print("ch is a vowel")
elif(ch=="o"):
print("ch is a vowel")
elif(ch=="u"):
print("ch is an vowel")
else:
print("ch is a consonent")
|
c8f499f58ae0cba99a03193352953e7ab48d026e | sweetherb100/python | /interviewBit/BinarySearch/00_binary_search.py | 737 | 4.34375 | 4 | '''
*binary search
1) should be "sorted in advance"
2) start, end, middle should be the index
3) while should be start <= end
4) middle should have int(): should not be float!
'''
# Use a binary search to find the index of a given value within an array of integers.
def binary_search(list, target):
start=0
end... |
4049fc9ba24bb8a6810f22d92add74e5925a04f4 | antonylu/leetcode2 | /Python/836_rectangle-overlap.py | 1,672 | 3.921875 | 4 | """
https://leetcode.com/problems/rectangle-overlap/description/
A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner.
Two rectangles overlap if the area of their intersection is positive. To be c... |
63d137145712daa958a2b83311d950320fb0d9fa | jadamowi/PAT_interview | /stringBackward.py | 577 | 4.5 | 4 | # text to be entered by user
text = input('Enter text:')
def backward(string):
"""
This function backwards words longer
than 3 signs in a string
:param string: string entered by user
:return: string with reversed words unless
shorter then 3 signs
"""
string = string.split()
words =... |
d400780c96cd5d1e476cc115783e5017d5360924 | beijuy/2study | /pythonwork/0327.py | 305 | 3.96875 | 4 | """def add(*a):
sum=0
m=1
for value in a:
sum+=value
m*=value
return sum,m
def main():
print(add(5,6,7,8,9,10))
if __name__ == "__main__":
main()
num1 = 666
num2 = 888
name = 'zhaona'
print (num1)
"""
def ps():
print(num1)
num1=3
print(num1)
ps()
print(num1) |
49d92f188408a952f8f570b6a11ce8c2e496d39c | priscillashort/priscillashort.github.io | /COCCCourses/CS260/11.8.18/btree_class.py | 403 | 3.609375 | 4 | import node
class BTree:
def __init__(self):
self.root = None
self.data
def insert(self,data):
if self.root == None:
self.root = Node(data)
elif data < self.root.data():
insert(self, data, )
def __str__(self):
return "[]"
... |
cd69304bd1ca7ad904d4a1f03ad837f51cb8c017 | MuskanShrivastava15/Python-programs | /to check if palindrome.py | 286 | 3.890625 | 4 |
def check(str):
for i in range(0,len(str)//2):
if str[i]!=str[len(str)-i-1]:
return False
return True
str="1111111122222222333333333335666677889944"
if(check(str))==True:
print("its a palandrome")
else:
print("it is not a palindrome")
|
dc71708c5038c317cc93f758b23b5c54c0ab653b | Serap08/Unit_Testing_Example | /test_FizzBuzz.py | 1,474 | 3.71875 | 4 | import FizzBuzz
import unittest
class test_fizzbuzz(unittest.TestCase):
#tests for multiples of 3 that should return Fizz
def test_3_returns_Fizz(self):
self.assertEqual(FizzBuzz.fizzbuzz(3), 'Fizz')
def test_6_returns_Fizz(self):
self.assertEqual(FizzBuzz.fizzbuzz(6), 'Fizz')
def test_9_return... |
6dd786878f2684c02b2e3d264f73ea44bfb21227 | jmstudyacc/python_practice | /POP1-Exam_Revision/repl_problems/session_1/min_3_numbers.py | 178 | 3.96875 | 4 | def min_of_three(a, b, c):
list1 = [a, b, c]
list1.sort()
return list1[0]
int1, int2, int3 = [int(input()) for x in range(3)]
print(min_of_three(int1, int2, int3))
|
d8453b83dcd82ed512279890128bac363fa4ef68 | andylamp/NQueens-Solver | /src/chessBoard.py | 3,533 | 3.84375 | 4 | '''
Created on Apr 12, 2013
@author: agrammenos
'''
from __future__ import print_function
from random import randint
class chessBoard(object):
global qCols
global totalCols
global verbose
def __init__(self,nsize, verbose):
'''
Constructor
'''
global bsize
... |
0ed47d25917877635bac63dff9269f7181d5552f | alessandrosp/reptile | /reptile/forms/abstract.py | 4,819 | 3.890625 | 4 | import abc
import collections
import prompt_toolkit.key_binding as ptk_key_binding
class AbstractForm(abc.ABC):
"""Abstract class for all the other Reptile forms.
Args:
kwargs: A dictionary containg all the information necessary to
instantie the form. Specifically:
- Name: Th... |
c98745b573cee7694e314e6a0c4b6247d11bf342 | serdarayalp/my-python | /wissenschaftliches_rechnen/pca4.py | 547 | 3.828125 | 4 | import pandas as pd
import numpy as np
# Let's take this dataset
a = [[0,2],[1,-1],[-1,-1]]
b = ['X','Y']
dat = pd.DataFrame(a,columns = b)
print(dat)
#Let's create the covariance matrix here.
# An intuitive reason as to why we're doing this is to capture the variance of the entire dataset
C = np.cov(dat.T)
eigenval... |
6aadf4309e2bca8912aea35d600ce8e159065726 | jiaoxiaoyou/study | /01-Python/10-100 plan/2020-04-23.py | 968 | 3.546875 | 4 | """
@Author : JJ
@Time : 2020/4/23 21:05
@Desc :
"""
"""
1.0423-列表的增加、删除、更新
2.0423-字典的增加、删除、更新
"""
print("---------------------第一题---------------------")
# 列表的增加、删除、更新
list1 = ['aa', 'bb', 'cc', 'dd']
list1.append(11)
list1.append(22)
list1.append(33)
print('append新增后的列表:',list1)
list1.pop()
print('pop删除后的列表:',lis... |
bc55990fdc3ade7d319444e01f87c607bea25519 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/f6f4342a68d746169a4ba8ead26321c1.py | 363 | 4.1875 | 4 | # Return difference of square_of_sum and sum_of_squares
def difference(x):
return square_of_sum(x) - sum_of_squares(x)
# Use mathematical induction to get sum then return the square of the result
def square_of_sum(x):
return (x*(x+1)/2)**2
# Use sum of squares formula and return the result
def sum_of_... |
33642a4afc2398a7c28ab249d81bc0c5e80cb47e | onehouse/python | /ex68.py | 587 | 3.6875 | 4 | '''
有 n 个整数,使其前面各数顺序向后移 m 个位置,最后 m 个数变成最前面的 m 个数。
'''
initial_l = list(range(1, 20))
for m in range(20):
print("当m = %d 时:" % m)
# 第一种方法:使用切片
final_l1 = initial_l[19-m:] + initial_l[:19-m]
print(final_l1)
# 第二种方法:按照要求,逐元素进入空列表
final_l2 = []
for i in range(19-m, 19):
fi... |
7e9cb57f388dfbc87d6e700a58c1592eb3d2bbc7 | laolee010126/algorithm-with-python | /problems_solving/algospot/strjoin.py | 622 | 3.53125 | 4 | """Get minimum cost of concatenating files
:input:
3
3
2 2 4
5
3 1 3 4 1
8
1 1 1 1 1 1 1 2
:return:
12
26
27
url: https://algospot.com/judge/problem/read/STRJOIN
ID : STRJOIN
"""
def strjoin(lens):
ret = 0
lens.sort()
while len(lens) > 1:
a = lens.pop(0)
b = lens.pop(0)
ret += a ... |
e8dd9dd4c0e32cfc3cbf527849bf809ca6504f5e | ydxt25/trade_matching_engine | /OrderQueue.py | 2,291 | 3.609375 | 4 | """
Alternetive Order Queue
which is Meant to be container of (Order)s
"""
from bintrees import FastRBTree # An implementation of c/cython which is really fast
class OrderQueue(object):
"""
"""
def __init__(self):
self.Orders = FastRBTree()
self.totalAmount = 0.0
def app... |
19becd4075ee0fc2176f19bce12e27f7f1a12ac9 | Rafael-doctom/CC33Z | /Cursos/Introdução à Ciência da Computação/Scripts/decimalfraction_to_binary.py | 1,206 | 4.125 | 4 | """
Função para converter decimal para binário
Até uma precisão-k após o ponto decimal
"""
def decimalfraction_to_binary(num, k) :
binary = ""
# Obter a parte integrante do número decimal
integral = int(num)
# Obter a parte fracional do número decimal
fractional = num - integral
# Converter a... |
ea591f328541c1534a776e319dc961798736d24e | ZhilaAghajari/Distributed-Replicated-Hash-Table | /old_app.py | 4,214 | 3.640625 | 4 | # client side
import socket
import sys
import random
from random import randint
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect_server( message):
#connect the socket to the port where the server is listening to
server_address = ('localhost', 10000)
print('client is now connecting to t... |
81f44f385af4bcfdaf8a7dcb83adb7e1b307565c | MahrezBH/Python_snippets | /Search_StackOverFlow.py | 712 | 3.515625 | 4 | # for install requests : pip install requests or the origin site
# for install beautifulSoup : pip install bs4 or the origin site
import requests, sys, webbrowser, bs4
print('-----------------| Here we go! |---------------------')
req = requests.get('https://www.google.com/search?q=site: stackoverflow '+''.... |
d3c5d59bf7893eec3cdec8e0d573e54734085de0 | akhilmiryala/Basketball-Stats-Tool | /main.py | 3,105 | 3.90625 | 4 | import app
import constants
def main():
print("\nBASKETBALL TEAM STATS TOOL")
dashes = '----'
print('{} MENU {}\n'.format(dashes,dashes))
print('Here are your choices:')
print('1) Display Team Stats')
print('2) Quit')
while True:
try:
stats_choice = input('Enter an ... |
3dffc770e3065fc937a915e51c19495a9b262ded | naldeco98/TaTeTI | /tateti.py | 2,091 | 3.515625 | 4 | class TaTeTi():
def __init__(self, board=None):
if board is None:
self.board = [' ' for _ in range(9)]
else:
self.board = board
def full(self):
full = True
for value in self.board:
if value == ' ':
full = False
return f... |
23922f1a0275bd6286f9f4f3a44421bf9b47bd84 | Lihong062/CS101 | /APTs/APT-4 (optional)/CerealSnack.py | 983 | 4.09375 | 4 | import math
def computeCups(calplan, eaten, calperserv, servsize):
'''
Here are the parameters for the function computeCups.
calplan is an integer representing the number of
calories you want to eat each day.
eaten is an integer representing the number of
calories you have eaten s... |
1365de315a43b0772bcda1c4cb68ce5cc274cadb | lilitam/problems_from_exercismio | /isogram/isogram.py | 156 | 3.734375 | 4 | import re
def is_isogram(string):
filtered_string = re.sub("[^a-z]", "", string.lower())
return len(set(filtered_string)) == len(filtered_string)
|
2183151d3042abd4a1bdcfc9fe11cc374e6ca7eb | rpreardon/Bike-Share-Project-DAND | /bs.py | 9,693 | 4.15625 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = {'Chicago': 'chicago.csv',
'New York': 'new_york_city.csv',
'Washington': 'washington.csv'}
months = ['January', 'February', 'March',
'April', 'May','June','All']
day_of_week = ['Sunday', 'Monday', ... |
e49a30d8af4541ad7be10c28c08a9c819226ed32 | cliffwhitworth/algokit | /algokit.py | 6,973 | 4 | 4 | import math
import numpy as np
import re
def string_reversal(s: str) -> str:
"""
Enter a string
Returns reversed string
"""
return "".join(reversed(s))
s = "Hello World!"
# print("Reverse of \"{}\" is \"{}\"".format(s, string_reversal(s)))
def char_mapper(s: str) -> str:
"""
Enter a strin... |
7f24bc138f9b76220de148ff0b7b1ac7ce4fa481 | mbaseman1918/testrep | /hammertime.py | 514 | 4.21875 | 4 | time = input("When are you eating your meal? ")
hour = int(time[:-2])
meridian = time[-2:].lower()
if hour in [7,8,9] and meridian == "am":
print("You are eating breakfast.")
elif hour in [12,1,2] and meridian == "pm":
print("You are eating lunch.")
elif hour in [7,8,9] and meridian == "pm":
print("You are ... |
5c3e63d049666701401550db8ca82bf765a7eae1 | LarisaOvchinnikova/Python | /1 - Python-2/3 - strings/1. Print n-th character of a word.py | 202 | 4.03125 | 4 | # Print n-th character of a word
word = input("Enter word: ")
n = int(input("Enter number: "))
if n < len(word):
print(f"{n}-th character of a word {word} is {word[n]}")
else:
print("Too much!") |
680bc44a13537d2ed44e809f94fc672ddc107678 | colinmcnicholl/first-project | /sec_15.6_python_move_rectangle4_think_python.py | 1,655 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 29 15:19:13 2017
@author: Colin
"""
"""
Exercise section 15.6 think python.
write a version of move_rectangle that creates and returns a new Rectangle
instead of modifying the old one.
"""
"""
create a type called Point that represents
a point in two-dime... |
2f6ee141cf7c478ac06ef899b2fc742b3934bb04 | abyingh/Machine-Learning-Implementations | /Movie Recommendation with KNN/dataset & code.py | 1,210 | 3.59375 | 4 | '''
The IMDB data can be accessed at:
https://www.kaggle.com/orgesleka/imdbmovies
query: the movie you need to received recommendations based on
k: number of recommendations with respect to euclidean distances between query and movies
'''
def knn(data, query, k):
distances_and... |
4aab1260e7e94d8595b0ba72bdfbf8f505b03c76 | Amruta-Pendse/Python_Exercises | /PrimeNumber.py | 785 | 4.15625 | 4 | #Program to check if a number is prime number
while True:
InputNumber=int(input("Enter any number to check if it is prime or not:"))
if InputNumber==1:
print("Enter value greater than 1.")
continue
elif InputNumber==0:
print("Not a valid number to check")
break
el... |
85400bc31fb93fce2ff0bd1934c3bfbbed6ff615 | YorkFish/git_study | /FishCDailyQuestion/ex021-030/Python3_030/030_05.py | 758 | 3.890625 | 4 | #!/usr/bin/env python3
# coding:utf-8
from random import choice
def rock_paper_scissors():
rps_d = {0:["石头", 5], 2:["剪刀", 0], 5:["布", 2]} # 代号a:[名称, 克制a的代号b]
rps_l = [0, 2, 5]
robot = choice(rps_l)
human = int(input("请输入手势代号(0 石头,2 剪刀,5 布):"))
while human not in rps_l:
human = int(input(... |
6549fd0ae48162825c48aa58a2b29bd95bfe0be8 | DesAbdWis/cw-python-temelleri | /prime-number.py | 490 | 4.15625 | 4 | number = int(input("Please enter a positive number whether to find out prime number or not : "))
if number == 0:
print("Zero is not prime number")
elif number == 1:
print("One is not prime number")
elif number == 2:
print("Two is prime number")
else:
for i in range (2,number):
if number %i == 0 ... |
c0ed97dbc8945be66492c0beb3601361ca8ea321 | qiu997018209/TensorFlow | /13.命名实体识别第一版(集成crf++和深度学习crf两种方法)/crf++/result/data.py | 256 | 3.59375 | 4 | right=0
wrong=0
with open('out.txt','r',encoding='utf-8') as f:
for l in f.readlines():
line=l.strip().split('\t')
if len(line) != 3:
continue
if line[1] == line[2]:
right+=1
else:
wrong+=1
print('准确率:%f'%(right/wrong)) |
9607a430fee65f8247f295f093942f8cc8148a51 | eszon/python-exercises | /Cursos/Curso de Python 3 - Canal Curso em Vídeo/challenges - mundo1/challenge-018.py | 430 | 3.953125 | 4 | #!/usr/bin/python
from math import cos, sin, tan, radians
ang = float(input('Digite o Ângulo: '))
c = cos(radians(ang))
s = sin(radians(ang))
t = tan(radians(ang))
print('O ângulo de {} tem o COSSENO {}{:.2f}{}'.format(ang, '\033[1;32m', c, '\033[m'))
print('O ângulo de {} tem o SENO {}{:.2f}{}'.format(ang, '\033[1;32m... |
c8b37c482bf19ccbd79baebc50d0d046b3278c59 | NguyenHiep/python_coban | /buoi3/vd1.py | 128 | 3.890625 | 4 | """
Dung else voi cau truc lap
"""
count = 1
while count <=5:
print(count, "<=5")
count +=1
else:
print(count, ">5") |
94767f83f4a4b0f24e01b1a0af554fbf5433972f | waffle-iron/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /week2/lecture4/polysum.py | 313 | 3.75 | 4 | from math import *
def polysum(n, s):
"""
:param n: number of sides
:param s: length of each side
:return: sum of : - the area and the square of the perimeter
"""
perimeter_squared = (n * s) ** 2
area = (0.25 * n * s ** 2) / tan(pi / n)
return round(perimeter_squared + area, 4)
|
f769877db57b83f8b138af43886029ab3faeaa4b | Ved005/project-euler-solutions | /code/tribonacci_nondivisors/sol_225.py | 711 | 3.734375 | 4 |
# -*- coding: utf-8 -*-
'''
File name: code\tribonacci_nondivisors\sol_225.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #225 :: Tribonacci non-divisors
#
# For more information see:
# https://projecteuler.net/problem=225
# Problem Sta... |
dc4a0102d750a2b353b15ef9505b1d5125ecd91b | anantkaushik/algoexpert | /BST-Traversal.py | 1,450 | 4.15625 | 4 | """
Problem Link: https://www.algoexpert.io/questions/BST%20Traversal
You are given a BST data structure consisting of BST nodes. Each BST node has an integer value stored in a property called "value" and two children nodes
stored in properties called "left" and "right," respectively. A node is said to be a BST node ... |
081da09b1eb88a293410a0afc10e5ded1c43a90d | manudubinsky/bigdata-2016-2c | /practicas/practica6/resolucion/Punto 5) a).py | 1,192 | 3.515625 | 4 | import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.test
"""cursor = db.restaurants.find()
for document in cursor:
print(document)
cursor = db.restaurants.find({"borough": "Manhattan"})
cursor = db.restaurants.find({"grades.score": {"$gt": 30}})
cursor = db.res... |
74a714a82552d0cc9e0d17f04e47c7b2f66764b8 | MM12583/line-bot | /rule_base.py | 1,038 | 3.609375 | 4 | trigger = input('指定句: ')
reply = input('回應句: ')
class Rule :
def __init__(self) :
self.answer = {}
self.read_data('add_reply.csv')
def read_data(self, file = 'add_reply.csv') :
with open ('add_reply.csv' , 'r', encoding = 'utf-8') as f :
for line in f :
if '... |
cd78f73b632ee4cc615c9d8dcb07d72f89922286 | jaganrajagopalme/Python | /TranslatterifLoop.py | 363 | 3.984375 | 4 | #While and If loop :Start
def TranslatorPhrase(phrase):
translator=""
print(phrase)
for myletter in phrase:
if myletter.lower() in "aeiou":
translator=translator+ "g"
else:
translator=translator+ myletter
return translator
#while and If the loop:Ends
print(Tran... |
85c5cab5f38b8796ef461370108da7d5019040c9 | Aasthaengg/IBMdataset | /Python_codes/p02730/s399259114.py | 137 | 3.71875 | 4 | S=input()
S2=S[:(len(S)-1)//2]
S3=S[(len(S)+3)//2-1:]
if S==S[::-1] and S2==S2[::-1] and S3==S3[::-1]:
print("Yes")
else:
print("No") |
e0443fb3f4b1de24bfac442c8a37af2160d20573 | parwell/Project-Euler | /Solved/004.py | 572 | 3.734375 | 4 | # Largest Palindrome Product
# Runtime 0.513 seconds
import time
start = time.time()
def findProducts():
products = []
for x in range(100,1000):
for y in range(x,1000):
products.append(x*y)
return products
def isPalindrome(number):
return str(number) == str(number)[::-1]
def getP... |
7e09c841ef991b6b146c1b392947c4ff67bd8b01 | sametarat/pythonx | /Week1/hw1.py | 702 | 3.828125 | 4 | import math
t = int(input("Program kac defa calısacak : "))
if t <=0:
print("Döngü sıfırdan küçük olamaz")
for i in range(0,t):
sayi1 = int(input("Birinci Sayıyı Giriniz: "))
sayi2 = int(input("İkinci Sayıyı Giriniz: "))
islem = input("Yapılmasını İstediğiniz İşlemi Giriniz: ")
if islem == "+":
... |
3c81472f7062116f901552b88917725fe7840c3a | Kristof95/GoodLuckHaveFun | /donation_location_unit_test.py | 6,683 | 3.625 | 4 | import unittest
from donation_location import Donation_class
class DonationLocation(unittest.TestCase):
global test
test=Donation_class("","","","","","","","","","")
############
##zip_code##
############
def test_zip_code_one(self):
test.zip_code = "3530"
self.assertTrue(tes... |
fe28bd88ba40979c4caa1f900d0bcde79304536f | WNjihia/bootcamp_codelab_17 | /bootcamp_day_3/Andelabs/max_and_min/max_and_min.py | 434 | 4.0625 | 4 | def find_max_min(list_value):
"""
Function that returns the maximum and minimum values in a list_value
"""
if len(set(list_value)) > 1:
return [min(list_value), max(list_value)]
else:
return [list_value[0]]
print(find_max_min([1, 2, 3, 4]))
print(find_max_min([6, 4]))
print(f... |
675fb6dca3b0e6259d9be10a1fd12f0a9cbe8478 | unsortedtosorted/Medium | /String/validIPAddress.py | 1,758 | 3.640625 | 4 | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def check4(ip):
l=ip.split(".")
if len(l)==4:
for x in l:
try:
if 0<=int(x)<=255:
... |
bee194ccfd90ce1ba3d4511be2421eb65c9b2153 | ehudt/euler | /sieve.py | 810 | 3.5 | 4 | from collections import defaultdict
class Sieve(object):
"""Generate a sieve of selected size"""
def __init__(self, size):
super(Sieve, self).__init__()
if size <= 0:
raise ValueError("Sieve size must be at least 1")
self.size = size
d = defaultdict(lambda : True)
d[0] = d[1] = False
for i in xrange(2... |
e3973732deccf80faa5a4e9e0148c05146e19a7c | craftyeve/GWC | /python/June24.py | 1,541 | 4.21875 | 4 | start = "I'm lonely and I need friends. Let's go find some!"
print(start)
keepplaying = "yes"
while keepplaying == "yes":
location = input("Should I look for friends in the woods or in the river? ")
if location == "woods":
print("There are no friends here.")
keepplaying = input("Try again? ")... |
badfc64c8ea0d99d222783368122c1583fa1c710 | CodeLeom/Web-Programing-with-python-and-Javascript | /python/hello.py | 400 | 4.03125 | 4 | name = input("enter your name: ")
print("hello, " + name)
#conditonal statements
n = int(input(f"{name}, kindly enter a number: "))
if n > 0:
print(f"{n} is a positive number")
elif n < 0:
print(f"{n} is a negative number")
else:
print ("your input is zero")
#lists
stores = ["Mabruur", "Zallacks", "... |
604dc58d6e3e9c4bb98b61421af09492414071cb | 19133/Te-Reo-Maaori-Quiz-Final | /quiz_component2.py | 835 | 3.9375 | 4 | def quiz_question(question):
valid=False
while not valid:
user_response = input (question) .lower()
if user_response == "whero":
user_response = "whero"
return user_response
else:
print("Incorrect, try again")
def quiz_question2(question):
valid=False
while not valid:
... |
966d873047552b8371ca22754f22b7c4a6bf62eb | timsergor/StillPython | /384.py | 855 | 3.96875 | 4 | # 100. Same Tree. Easy. 51.1%.
# Given two binary trees, write a function to check if they are the same or not.
# Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# ... |
c0769990d9cf2bcb351069ca5055224caeb08270 | aventador2018/Principle-Programming-Language-504-51 | /Assignment_5/fill_arrays_loop.py | 264 | 3.578125 | 4 | import numpy as np
from matplotlib.pyplot import plot, show, xlabel, ylabel
def h(x):
return (1/np.sqrt(2*np.pi))*np.exp(-0.5*x**2)
n = 41
dx = 8. / (n - 1)
x = [-4 + i * dx for i in range(n)]
y = [h(i) for i in x]
plot(x, y)
xlabel('x')
ylabel('y')
show() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.