blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2a1a5b65f5ef8f270450832c2586b36e073dcfb9 | VICIWUOHA/Pycharm-Project | /Mapping.py | 387 | 3.765625 | 4 | import numpy as np
import pandas as pd
from pandas import Series, DataFrame
df = DataFrame({'Country': ['Afghanistan', 'Albania', 'Nigeria'],
'Code': ['89', '345', '213']
})
GDP_map = {'Afghanistan': '20', 'Albania': '12.8', 'Algeria': '215'}
print(GDP_map)
# Mapping values in df to va... |
7ee24e3c040a7624f1657e954ed35aeb8ed6e091 | nineties/prml-seminar | /prog/prog3-4-5.py | 1,337 | 3.796875 | 4 | # -*- coding: utf-8 -*-
from numpy import *
from scipy import stats
from matplotlib.pyplot import *
# 真の値(台形近似で. N=100だと4桁は合うはず.)
def answer():
N = 100
x = linspace(0, 2, N+1)
fx = stats.norm.pdf(x)
return 0.5 - (sum(2*fx)-fx[0]-fx[-1])*2/(2*N)
answer = answer()
def integrate1(n):
x = random.randn... |
7009549410254ccb70e5625b830963e5eef0495f | gitbrian/lpthw | /ex13.py | 399 | 3.59375 | 4 | from sys import argv
script, first, second, third, fourth, fifth = argv
print "The script is called:", script
print "Your first variable is", first
print "Your second variable is", second
print "Your third variable is", third
print "Your fourth variable is", fourth
print "Your fifth variable is", fifth
print ""
like... |
2b12c0ed7a5c2bc4ced81d12101a6e209cc58917 | garibaal/isat252 | /lab5.py | 868 | 3.9375 | 4 | """
lab 5
"""
# 3.1
alien_color = 'green'
if alien_color == 'green' :
print('you got 5 points')
# 3.2
alien_color = 'green'
if alien_color == 'green':
print('shot alien! you got 5 points')
else:
print('player earned 10 points')
# 3.3
favorite_fruits = ['apple','banana','strawberry']
if 'apple' in favo... |
84a3e699b22083c960d19dc2fbceaae76dbfd719 | Shishir-rmv/oreilly_math_fundamentals_data_science | /calculus_and_functions/15_log_function.py | 120 | 3.59375 | 4 | from math import log
# 2 raised to what exponent gives us 8?
exponent = log(8,2)
# The answer is 3.0
print(exponent)
|
4f70eadf87247e93252d7c70425215fb3e792353 | irasemarivera/Curso_python_cice | /Historial/strings.py | 3,722 | 4.375 | 4 | #strings
"""
mi_nombre = "Hola Irasema"
print(mi_nombre)
mi_nombre = "Hola Irasema, 'buenos dìas'!"
print(mi_nombre)
mi_nombre = "Hola Irasema, \"buenos dìas\"!"
print(mi_nombre)
mi_nombre = 'Hola Irasema, "buenos dìas"!'
print(mi_nombre)
mi_nombre = '''linea uno
otra màs
esta es la tercera linea!
ahora una cuart... |
9a38531ece8e74ff50ac885e28c44e94abf946f8 | hayleymathews/data_structures_and_algorithms | /Arrays/dynamic_array.py | 1,636 | 3.6875 | 4 | """python implementation of ADT Dynamic Array"""
import ctypes
from Arrays._array_abstract import Array
class DynamicArray(Array):
"""
implementing ADT Dynamic Array
"""
def __init__(self):
self.size = 0
self.capacity = 1
self.values = (self.capacity * ctypes.py_object)(*([None... |
85080444f8a6342deede9262a73bde8542a2541d | jczhangwei/leetcode_py | /121.买卖股票的最佳时机.py | 1,823 | 3.9375 | 4 | #
# @lc app=leetcode.cn id=121 lang=python3
#
# [121] 买卖股票的最佳时机
#
# https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/
#
# algorithms
# Easy (54.19%)
# Likes: 1027
# Dislikes: 0
# Total Accepted: 224.4K
# Total Submissions: 413.7K
# Testcase Example: '[7,1,5,3,6,4]'
#
# 给定一个数组,它的第 i 个元... |
8a1ff44f9c2f11a2c714f265850ff8e8d3bce970 | MiningXL/ggj2020 | /render.py | 7,415 | 3.671875 | 4 | from abc import ABCMeta, abstractmethod
import pygame
import math
from map import Grid
import os
SQRT3 = math.sqrt( 3 )
class Render( pygame.Surface ):
__metaclass__ = ABCMeta
def __init__( self, map, radius=24, *args, **keywords ):
self.map = map
self.radius = radius
# Colors for the map
self.GRID_CO... |
175d165d0d4ef780c7ae4c140950477f0bae4bc5 | THACT3001/PhamTienDung-c4t3 | /hahaha/filehw11.py | 983 | 3.875 | 4 | sizes = [5, 7, 300, 90, 24, 50, 75]
print("Hello my name is Dung and these are my ship sizes: ", *sizes, end = " ")
print()
print("Now my biggest sheep has size", max(sizes),"let's shear it")
print()
sizes[sizes.index(max(sizes))] = 8
print("After shearing, here is my flock:", *sizes, end = " ")
print()
sizes = [si... |
b5ddea7b34e379aecc176b8818cf191239b5e4e9 | ArtemDud10K/Homework | /TMSHomeWork-3/z15.py | 229 | 3.765625 | 4 | first_list = [1, 2, [5, 6, 7 , 8], 3, 4]
for i in first_list:
if isinstance(i, list):
second_list = i
index = first_list.index(second_list)
first_list.pop(index)
first_list.extend(second_list)
print(first_list)
|
3f20cce7eed0d738a57e5c198dfda17b2dbae3cf | Zzpecter/Coursera_AlgorithmicToolbox | /week2/7_last_digit_partial_sum_of_fib_numbers.py | 787 | 4.125 | 4 | # Created by: René Vilar S.
# Algorithmic Toolbox - Coursera 2021
def get_fibonacci_rene(n):
pisano_period = get_pisano_period(10)
remainder_n = n % pisano_period
if remainder_n == 0:
return 0
previous, current = 0, 1
for _ in range(remainder_n - 1):
previous, current = current, ... |
cb638e40fba6d5edeb377e2d9a67636c5e2ee2b7 | frostbooks/newbee-python | /二进制转化.py | 371 | 3.90625 | 4 | def trans(num):
temp = str(num)
if not temp.isdigit():
print('please enter a number!')
else:
list1 = []
result = ' '
while num :
a = num % 2
num = num //2
list1.append(a)
while list1:
result += str(list1.pop(... |
aa71fd3d1f05d7eaaef2bb87d66ac2cd38ad3004 | rcrick/python-designpattern | /Singleton/SingletonSimple.py | 902 | 3.625 | 4 | # -*- coding: utf-8 -*-
# 使用__new__
class Singleton(object):
_instance = None
def __new__(cls, *args, **kw):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
return cls._instance
def __init__(self, status_number):
self.status_numb... |
2c890715e3cfbc4dd62a65ed763a34e7e1883996 | sungjun-ever/algorithm | /chap6/bubble_sort3.py | 546 | 3.6875 | 4 | def bubble_sort(a) -> None:
n = len(a)
l = 0
while l < n - 1:
print('사이클')
last = n - 1
for j in range(n - 1, l, -1):
if a[j-1] > a[j]:
a[j-1], a[j] = a[j], a[j-1]
last = j
print(''.join(str(a)))
l = last
print('버블 ... |
33e5c5bd567f31cf822362aa6a599f0478e8c26e | torstenschenk/BeuthDevML | /Visual_n_Scientific_Comp/jupyter_files/vsc-05/k_nearest_neighbors.py | 2,373 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import glob
from collections import Counter
def distance(a, b):
"""calculates the distance between two vectors (or matrices)"""
# 2.1.1 Berechnen Sie die Distanz zwischen zwei Matritzen/Bildern
...
def knn(query, data, labels, k):
"""
Calculates... |
c2b4bb0915c7b542c581bf4ba2749844dcaa2925 | rcsolis/data_algs_python | /lambdafunc.py | 965 | 3.828125 | 4 | # Lamba function is a one line anonymous function (without name)
# Define unsing lambda keyword
square = lambda x: x ** 2
print(square(2))
mult = lambda x, y: x ** y
print(mult(2, 4))
# Sorted method
persons = [("Rafael", 35), ("Emi", 15), ("Sof", 8), ("Sam", 20)]
sort_people = sorted(persons)
print(sort_people)
age_... |
90461d044cb0578aff8546760cf37c15103bfc1d | an4p/python_learning | /homework_02/hw02_02.py | 202 | 3.65625 | 4 | userInput = str(input("Please input something: "))
userInput1 = userInput[0:(len(userInput)+1)//2]
userInput2 = userInput[(len(userInput)+1)//2:]
userInputNew = userInput2+userInput1
print(userInputNew) |
2154784bf89a91358401cd6b342e3fa976e78475 | sahiti0707/Python_Learning | /15.py | 178 | 3.5 | 4 | print("Enter your name:")
x = input()
print("Hello,", x)
print("How are you?")
y = input()
print("Good.")
print("Which school?:")
x = input()
print("Okay . It's a good school ")
|
1a23a66365875d08ea398f9125ff5d730d7fca4d | ghost9023/DeepLearningPythonStudy | /DeepLearning/DeepLearning/02_Deep_ChoTH/deep_learning_1.py | 969 | 3.703125 | 4 | # 넘파이
# 넘파이의 산술연산
import numpy as np
x = np.array([1.0, 2.0, 3.0])
y = np.array([2.0, 4.0, 6.0])
x + y
x - y
x * y
x / y
x = np.array([1.0, 2.0, 3.0])
x / 2.0
A = np.array([[1,2], [3,4]])
print(A)
A.shape
A.dtype
B = np.array([[3,0], [0,6]])
A + B
A * B # 배열연산
print(A)
A * 10
# 브로드캐스트
A = np.array([[1,2], [3,4]]... |
c4813b6ad6ca642f48c3c37a30b8dde0f0c14914 | carlos1500/Curso_Full-Stack_Blue | /Modulo 1/Exercícios de Aula/Aula 17/Exercício 1.py | 904 | 4.21875 | 4 | #1) Utilizando os conceitos de Orientação a Objetos (OO) vistos na aula anterior, crie um lançador de dados e moedas em que o usuário deve escolher o objeto a ser lançado. Não esqueça que os lançamentos são feitos de forma randômica.
import random
class Lançador():
def __init__(self, escolha):
self.escol... |
767e3ea49510fe817906249ca65083c5595641cf | annaymj/LeetCode | /RemoveDuplicateInOrder.py | 435 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 9 14:34:33 2019
@author: annameng
input = [4,4,3,6,6,7,7,7],output = [4,3,6,7]
"""
input1 = [4,4,3,6,6,7,7,7]
def removeDuplicate_inOrder(nums):
dict_n = {}
for num in nums:
if num not in dict_n.keys():
dict_n[num] = 1
... |
064544effad27ec442c7df4fe9b6ff282071a13c | aboubacardiawara/apprentissage | /c++/createFile.py | 1,349 | 3.53125 | 4 | #!/bin/python3
import re
if __name__ == '__main__':
import sys, re, os
def isValidArguments(args):
"""
CARACTERISTICS OF VALIDS ARGUMENTS:
- SIZE: 3
- ARGUMENT 1: ALPHANUMERIC CARACTERS.
- ARGUMENT 2: NUMERIC CARACTER.
- ARGUMEN... |
bcba750a8fafe1da684cc82f03154c5247d50cd3 | avvRobertoAlma/esercizi-introduzione-algoritmi | /esame_14_01_2019.py | 345 | 3.671875 | 4 | def massimo(lista):
max_val = 0
if len(lista) == 1:
return lista[0]
else:
tmp = lista[len(lista)-1]
max_val = massimo(lista[:-1])
if tmp > max_val:
return tmp
else:
return max_val
if __name__ == "__main__":
l = [12, 45, 23, 88, 1, 9, ... |
c49bce2c3d23370bceba6a49de2dd227c7cc2e4b | ScottSko/Python---Pearson---Third-Edition---Chapter-7 | /Chapter 7 - Programming Exercises - # 3 Rainfall Statistics.py | 507 | 3.890625 | 4 | def main():
index = 0
months = 12
total = 0
list = []
for x in range(months):
value = int(input("What was the total rainfall for the month? "))
list.append(value)
total += value
print("The total amount of rainfall was", total)
print("The average ... |
c0e50bacea3ac7b13b570a4157bd021d541d3f08 | abby501198/Programming-for-Bussiness-Computing | /hw1(1).py | 572 | 3.71875 | 4 | # abby chang
# input
# 有五行input,一行一個數字
adult_num = int(input()) # 全票數量
adult_price = int(input()) # 全票售價
student_num = int(input()) # 學生票數量
student_price = int(input()) # 學生票售價
money = int(input()) # 給付櫃台的金額
ttl_price = adult_num * adult_price + student_num * student_price # 總應付金額
remaining = money - ttl_price ... |
4206f808de54f1bedf62a684ce6e0636719851af | RxDx/playfair | /cifrador.py | 4,456 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
def constroiListaAlfabeto():
alfabeto = "abcdefghiklmnopqrstuvwxyz"
lista = []
for letra in alfabeto:
lista.append(letra)
return lista
def normalizaTextoOriginal(textoOriginal):
posicaoAtual = 0
novoTexto = ""
texto... |
33bdec1d542048fcd2468d74f217981fdf8c70e0 | Vladarbinyan/GeekPython | /Lesson04/func_tools.py | 328 | 3.5625 | 4 | import functools
user_balances = {'Vasya': 500, 'Petya': 300, 'Nina': 1000}
def my_balance(total, amount):
return total + amount
# users_total = functools.reduce(my_balance, user_balances.values())
users_total = functools.reduce(
lambda total, amount: total+amount,
user_balances.values())
print(users... |
944ec02f9589edac89d2c837e14938705fa6de71 | geunwooahn-dev/PythonAlgorithms | /Python_bj/etc/bj1181.py | 248 | 3.65625 | 4 | # 21.01.31 baekjoon 1181 단어정렬
n = int(input())
result = []
for i in range(n):
result.append(input())
result = list(set(result))
sorted_result = sorted(result, key = lambda x : (len(x), x))
for word in sorted_result:
print(word) |
4c35f0b024b36bed18a8e93996215e82285044f9 | jaresj/Python-Coding-Project | /Check Files Project/check_files_main.py | 2,213 | 3.703125 | 4 | # Python Ver: 3.8.2
#
# Author: Justice
#
# Purpose: Check Files
#
#
# Tested OS: This code was written and tested to work with windows 10.
from tkinter import *
import tkinter as tk
from tkinter import messagebox
# Be sure to import out other modules
# so we can have access to them
imp... |
c176a045c9fde53886e74233de87abc92dc02af5 | AravindVasudev/datastructures-and-algorithms | /problems/leetcode/prefix-and-suffix-search.py | 599 | 3.53125 | 4 | # https://leetcode.com/problems/prefix-and-suffix-search/
class WordFilter:
def __init__(self, words: List[str]):
self.mappings = {}
for weight, word in enumerate(words):
prefix = ""
for pre in [""] + list(word):
prefix += pre
... |
3137b8c7198220568d9584234085ffa0355a1d43 | matthewgiem/Socratica.py | /Python/class.py | 1,251 | 4 | 4 | import datetime
class User:
pass
user1 = User()
user1.first_name = 'Matt'
user1.last_name = 'Giem'
print(user1.last_name) # 'Giem'
first_name = 'Author'
last_name = 'Clarke'
print(user1.first_name, user1.last_name)
# "Matt Giem"
print(first_name, last_name)
# "Author Clarke"
user2 = User()
user2.first_name ... |
7eee90f2a36945713d64a7a04d2ae47fccd268b8 | ja-vu/pythonProjects | /dice_roll/dice_roll.py | 438 | 4.03125 | 4 | from random import randint
min_val = 1
max_val = 6
# Dice needs to return a random value between 1 and 6
def roll_dice(low, high):
print(randint(low, high))
def start():
""" ASK USER IF THEY WANT TO ROLL A DICE """
roll_again = True
while roll_again:
roll_dice(min_val, max_val)
prin... |
e96d915151e03c215ed230b825bb378c631af9e2 | gotoindex/python-course | /tasks/task7/method1.py | 925 | 4.375 | 4 | import argparse
import math
class Sequence:
"""Displays all natural numbers whose square is less than n.\n
Any negative inputs will be converted into positive ones.
### Params:
- n - a positive integer. The square of each number in
the result will be smaller than this number.
"""
def __i... |
1a8f43068200b80588545093501318fc9e9c8f7b | romulofff/SD_2018 | /aula_invertida_data/json_example.py | 801 | 3.796875 | 4 | '''
############ SISTEMAS DISTRIBUÍDOS ############
Aula Invertida - Representação de Dados
GRUPO: Rômulo Férrer Filho, Rhaniel Magalhães, Marcus Vinicius, Pablo Grisi
'''
# Inicialmente importamos o pacote 'json' do Python
import json
# Agora devemos criar objetos que serão transformados em JSON
contacts = [
{
... |
aa9cdcf475fd22e2e7e06f5bb640ffae2082090f | laukikk/Data-Structures | /Python/tree.py | 674 | 3.59375 | 4 | class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self .children.append(child)
def print_tree(self):
print
Tree = TreeNode('Pokemon')
Grass = TreeNode('G... |
c0fefb996aca5adcb1ebc13d717c4b2cff1993da | guprahul7/leetcode | /DesignTicTacToe.py | 2,102 | 3.765625 | 4 |
class TicTacToeGame(object):
def __init__(self,n,p1,p2):
self.size = n
self.board = [[None for i in range(n)] for i in range(n)]
self.p1 = p1
self.p2 = p2
def playGame(self):
r,c = 0,0
turn = self.p1
result = False
nTurns = 0
while not ... |
0a6506bfda63c39cc3bf90d778a09ce0fefdf830 | dukeqiu/practicePython | /createCsv/outputCsvFile.py | 458 | 3.75 | 4 | import csv
a = "What's you name?"
b = "What's your company?"
c = "How old are you?"
info1 = [a,b,c]
def create(x,y,z):
with open(x,y) as f:
w = csv.writer(f, delimiter=",")
w.writerow(z)
create("../Desktop/info.csv","w",info1)
for i in range(1,5):
a1= input("What's you name: ")
b... |
ee3bdbe0e58b210b33e43504e5d8b53907925e7d | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_04/day04_Assignment7.py | 552 | 4.40625 | 4 | '''
7)Identify the missing piece of code in below program and write the correct answer to remove the error which we get when print statements are called
'''
def decorator(func):
def wrapper():
print("I am the decorator")
func()
return wrapper
@decorator
def function():
print("I am the function")
function()
'''
... |
c57400522749fb76508c2ee5681f85eed6416bcb | tayloa/CSCI1100_Fall2015 | /Homeworks/hw3/hw3_util/hw3_part1.py | 1,560 | 3.625 | 4 | import hw3_util
teams = hw3_util.read_fifa()
team1 = int(raw_input("Team 1 id => "))
print team1
team2 = int(raw_input("Team 2 id => "))
print team2
points1 = teams[team1][2]*3 + teams[team1][3]
points2 = teams[team2][2]*3 + teams[team2][3]
gf1 = teams[team1][5]
gf2 = teams[team2][5]
diff1 = gf1 - teams[team1][6]
diff2... |
6a76a58abee6342a13270b3edaddf5c1e2519ee1 | toasty-toast/project-euler | /python/euler_005.py | 242 | 3.5 | 4 | #!/usr/bin/env python2.7
"""
Problem 5: Smallest multiple
"""
import sys
if __name__ == "__main__":
num = 2520
while True:
for i in xrange(1, 21):
if num % i != 0:
break
if i == 20:
print num
sys.exit(0)
num += 2520
|
992ea444ea6bdd249c052c814088be5a7df142df | xvrdm/pmpac | /pmp003_01.py | 170 | 3.875 | 4 | import re
word = input("Please enter a word: ")
#if word[0] in 'aeiou':
if re.match('[aeiou]', word):
print(word + 'way')
else:
print(word[1:] + word[0] + 'ay')
|
d931893327697584c7ef2b118df294b134864eaf | Lehcs-py/guppe | /Seção_07/parte_1/Exercício_26.py | 381 | 3.96875 | 4 | print("""
26. Faça um programa que calcule o desvio padrão de um matriz v contendo n = 10 números, onde m é A media do matriz.
Desvio Padrão = d= √[(v1-m)²+...(v10-m)²]/(10-1)
""")
v = [36, 70, 7, 73, 45, 19, 22, 25, 90, 92]
m = sum(v)/len(v) # media
mq = 0 # media dos quadrados da diferença
for num in v:
... |
a78ba91de86fb1c092dbebc9d509dbef59284c1a | qwert19981228/P4 | /课件/0218/tcp_s.py | 479 | 3.5625 | 4 | # 导包
import socket
# 创建套接字对象
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定ip和端口号
sock.bind(('',8090))
# 监听 队列
sock.listen()
# 接收 sock对象,客户端地址
s,addr = sock.accept()
data = s.recv(1024)
print(data.decode('utf-8'))
s.send('HTTP/1.1 200 OK\r\n'.encode('utf-8'))
s.send('Content-Type: text/html\r\n'.encode('u... |
ecd257cfba3fb2015533329abd4d39416c3be48a | apiccone/Euler-Problems | /Problem 3.py | 691 | 3.84375 | 4 | """
Ashley Piccone
Euler Problem 3: Largest Prime Factor
"""
import numpy as np
def prime_test(num):
# determines if a number is prime
arr = []
for k in range(2,num):
# for k from 2 until the user's entry num
# append the remainder of dividing num by k
arr.append(nu... |
ebbafc97e7086a80fd2cb183fe712f1e9856e3d9 | winstonfy/python_life | /base_py/5 object-oriented/8 metaclass.py | 17,117 | 4.34375 | 4 | #__author__ = 'Winston'
#date: 2020/4/2
# 元类
# 什么是元类呢?一切源自于一句话:python中一切皆为对象。让我们先定义一个类,然后逐步分析
class StanfordTeacher(object):
school='Stanford'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self):
print('%s says welcome to the Stanford to learn Python' %self.na... |
fcbacd6e4e24808e6f40d4fa26c6529c8842d170 | christophersousa/Primeiro-Periodo | /APE/ape/Terceira semana/questão 2.py | 510 | 3.78125 | 4 | m = int(input('Matrícula do operário: '))
p = int(input('Quantidades de peças fabricadas no mês : '))
peças = p - 30
bonus = peças * 10
sm = 1045
if p > 30:
salario = bonus + sm
print(f' O empregado de matrícula {m} \n classificado na classe B \n receberá um bônus salarial de R${bonus}')
print(f' Salario = ... |
9deee0f4effcbe6c525ad0393b97ae74d886dcfa | UserWangjn/JieYueProject | /Test/Demo/打印松树.py | 112 | 3.734375 | 4 | i = 0
while i < 5:
u = 0
while u < 5:
print("*"),
u = u +1
print("")
i = i + 1 |
4a6df3699b00e3a74f800db90439554db97d09f1 | mrinalmayank7/python-programming | /CLASSES & OBJECTS/M_Overloading.py | 467 | 3.6875 | 4 | class CSE8:
def __init__(self,o1,o2):
self.o1=o1
self.o2=o2
def arithmetic(self , a=None,b=None,c=None):
add,mul=0,0
if a!=None and b!=None and c!=None:
add = a+b+c
mul = a*b*c
elif a!=None and b!=None:
add = a+b
... |
cfd18aae6837149ce0b01136cdc5bf15bec2275c | phillib/P4E-Python- | /Loops/counting.py | 191 | 3.890625 | 4 | zork = 0
print 'Before', zork
for thing in [9, 41, 12, 3, 74, 15]:
zork = zork + 1
print zork, thing
print 'After', zork
# This loop will count the total number of objects in a list
|
9a7be3e60f7cf8c13ded8982a9aa60bdb2cb1685 | joycetan12/NLP_Fall2020 | /NLP_HW1/NLP_HW1.py | 13,143 | 3.59375 | 4 | # Author: Joyce Tan
# NLP Fall 2020 - HW1
import math
# this method pads each sentence and lowercase all words
# returns a processed sentence
def preprocess(text):
cleanText = '<s> '
text = text.lower()
cleanText += text
cleanText += ' </s>'
return cleanText
# this method pads and lowercase each s... |
8affa414845860649e7a97f93a87dff5a367e92e | jsadsad/aA_Python | /w1/d3/input_ex.py | 113 | 3.75 | 4 | print("hello world")
answer = input("how are you? ") # <== notice space before closing quote
print("I am fine")
|
85a719e6a32a3da63e0c355dd3980d644e2faa93 | abipriebe/CSE111 | /Week 2/week 2 notes.py | 773 | 4.03125 | 4 | #if statements
x = 5
y = 6
print(x < y)
favoriteNumbersList = [3,4,5,6,7,8]
if (4 in favoriteNumbersList):
print("this was true")
if (10 not in favoriteNumbersList):
print("this was true")
name = "Joey"
if("j" in name):
print("J is in the name")
else:
print("j is not in the name")
print(x < y and y... |
3aef37bb61835ad76fc8a88afbe6cda0b1c2bdab | abelvdavid/100DaysofCode | /day11/reverselinkedList.py | 960 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def printList(self):
curr = self.head
while(curr):
print(curr.data)
cur... |
5bf318be65dea2bcf86ed0f785e0e943a8981667 | Muhammad-Hammad-Ur-Rehman/MITx6.86x | /Projects/Digit Recognition (Project 2-3)/part1/svm.py | 2,003 | 3.578125 | 4 | import numpy as np
from sklearn.svm import LinearSVC
### Functions for you to fill in ###
def one_vs_rest_svm(train_x, train_y, test_x, C):
"""
Trains a linear SVM for binary classifciation
Args:
train_x - (n, d) NumPy array (n datapoints each with d features)
train_y - (n, ) NumPy array... |
66b3a58599b94c4a4f48e444496788782001d78d | NavigationLab/warehouse-teleporting | /data_collection/src/experiments.py | 2,580 | 3.5 | 4 | """
File: experiments.py
Descr: Represents a full study experiment and contains
all the participants run in that experiment
Developed 2/13/2019 by Alec Ostrander
"""
import os
from participants import Participant
class Experiment:
def __init__(self, name):
"""
:param name: string, a name ... |
70c99029b44c6898008b846ddfbe34be5107c653 | alvaroeletro/DimAmostra | /ListaGeradora.py | 1,571 | 3.84375 | 4 |
print("Bem vindo\n")
print("Calculo do Tamanho de uma amostra necessária\n")
print("V.0.01 versão inicial\n")
print(".....::: Admita as seguintes condições :::.....\n")
contador = 0
erro=float(input("Inserir erro pré-fixado "))
x=0
s=0
espacoamostral = []
somax=0
somaXi=0
n0=int(input("Insira a qntd. da Amostra Pilo... |
3b1a089c2a806b789e9ec31496e36ec0432a472d | PakhnovaMaria/Pakhnova1sem | /praktika_3/eleven.py | 252 | 3.734375 | 4 | import turtle
turtle.shape('turtle')
def cir():
for i in range(1,181):
turtle.forward(1)
turtle.right(1)
for b in range(1,10):
turtle.forward(1)
turtle.right(18)
turtle.left(90)
for a in range (10):
cir()
|
6ee768afc8f04d2a989874bf0c7903c46c73eb8a | shuai-z/LeetCode | /valid-sudoku.py | 594 | 3.546875 | 4 | class Solution(object):
def isValidSudoku(self, board):
s = [[], [], []]
for x in range(3):
s[x] = [[] for _ in range(9)]
for i in range(9):
s[x][i] = [False for _ in range(10)]
for i, r in enumerate(board):
for j, c in enumerate(r):
... |
f5d0d4cfbc994d6a27dd077121917a1465fb234c | thecoder-co/sorting | /bubble sort.py | 2,982 | 3.96875 | 4 | import tkinter as tk
import random
import time
def swap_two_pos(pos_0, pos_1):
"""This does the graphical swapping of the rectangles on the canvas
by moving one rectangle to the location of the other, and vice versa
"""
x1, _, _, _ = canvas.coords(pos_0)
x2, _, _, _ = canvas.coords(pos_1)
... |
9076b16442e9bbc174e43cf5b1656ba0efac9165 | AlexisAndresGarcia/Programacion-grupo-2 | /input.py | 218 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 12:19:08 2020
@author: Alexis Garcia
"""
nombre=input("Ingrese su nombre:")
print("Hola"+nombre+"!")
edad=input("Ingrese su edad:")
print("Usted es mayor de edad") |
20043033fea1034e1b88e251d6bf2486f519e0bc | GinnyGaga/PY-3 | /ex36-1.py | 1,307 | 4 | 4 | from sys import exit
def play():
print("so,how much money do you have?")
money=input(">")
if "0" in money or "1" in money:
how_much=int(money)
else:
quit("just type the money you have.")
if how_much < 100:
print("I'll go to Disney myself.")
exit(0)
else:
quit("you are the poor.")
def he():
prin... |
6eb4a1cc74fa0772b5450c5be0f025af07fe9e12 | ideologysec/practicepython | /exercise2.py | 742 | 4.0625 | 4 | # http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html
# modulo practice, mostly
incomingNumber = int(input(
"Please enter a number (and I'll tell you if it's even or odd: "))
if (not incomingNumber % 2):
if (not incomingNumber % 4):
print("Your number was a multiple of four (and ther... |
c94e12186f9ef8abaf3b3a9948acbd73cda904d6 | skilldisk/Python_Basics_Covid19 | /exercises/exercise9.py | 402 | 4.1875 | 4 | print("******* Fibonacci Sequences *******")
nterms = int(input("how many terms ? : "))
current = 0
previous = 1
count = 0
next_term = 0
if nterms <= 0:
print("Enter a positive number")
elif nterms == 1:
print('0')
else:
while count < nterms:
print(next_term)
current = next_term
nex... |
368f3f8228eb395325c092185523baa6ffe1cb82 | sritampatnaik/find-your-way | /distanceAngleCalculation.py | 831 | 3.75 | 4 | import math
# distance formula
def distance(x1, y1, x2, y2):
return math.sqrt((int(x2) - int(x1)) ** 2 + (int(y2) - int(y1)) ** 2)
# returns the angle between 2 points,
# with respect to magnetic north
def calcAngle(x1, y1, x2, y2, northAt):
angle = 0
xprime = x2 - x1
yprime = y2 - y1
if xprime... |
681d6327c4cbd8ee87311a828ce9bde0f9d484e0 | jcomicrelief/text_RPG | /main.py | 3,071 | 3.515625 | 4 | """TEXT RPG GAME - JCOMICRELIEF"""
from command import *
from variables import *
# help command (usage: help)
def aid():
lst = []
for command in commands:
lst.append(command)
lst.sort()
lst = ", ".join(lst)
print(lst)
# dictionary of commands
commands = {
"help": aid,
"check": che... |
14b125aca63cd0a93498d12891d3cd1f37470aa7 | Swathygsb/DataStructuresandAlgorithmsInPython | /DataStructuresandAlgorithmsInPython/com/kranthi/Algorithms/challenges/medium/permitationOfString.py | 780 | 4.15625 | 4 | """
Write a program to print all permutations of a given string
Last Updated: 03-12-2020
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an
ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http:... |
bd0bb990728589e47141afff2c6b709661cab470 | johnfwitt/rosalind | /subs.py | 829 | 4.125 | 4 | # http://rosalind.info/problems/subs/
sample = input("sample = ")
substring = input("substring = ")
start = 0
stop = len(substring) # create a search space the same size as the substring
results = []
def SubstringSearch(sample,substring,start,stop,results):
if sample[start:stop] == substring: # if the se... |
ad620a464f3632a5a24f1561118718ce87c06321 | taobupt/pycompete | /Trie.py | 1,106 | 4.09375 | 4 | class TrieNode:
def __init__(self):
self.isEnd=False
self.children=['*']*26 #we can judge wheather there is a children node
self.word='' # every node store string from root to this node
class Trie:
def __init__(self):
self.root=TrieNode()
def insert(self,word):
cur=... |
926d7abbbe6f063b2bc30eb3a2843d1f989722a1 | kokot300/python-core-and-advanced | /oddnumbers.py | 612 | 3.96875 | 4 | while True:
x=input("enter min number:\n")
y=input("enter max number:\n")
try:
xx=int(x)
try:
yy=int(y)
if xx%2!=0:
while xx<=yy:
print(xx)
xx+=2
#return 3
else:
xx+=1
... |
88c207be1647faf33d124172763aec3cc1fd015c | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/115/15210/submittedfiles/decimal2bin.py | 203 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=input('digite um número:')
b=n
d=0
while b>0:
b=b//10
d=d+1
s=0
for i in range(0,d,1):
c=n%10
s=s+c*(2)**i
n=n//10
print(s)
|
90e4175e7e08afe3014531e7d0c4f54e7c294946 | Silvernitro/DSaA | /search_trees.py | 18,618 | 3.609375 | 4 | class Tree():
class Position():
def element(self):
raise NotImplementedError('must be implemented by subclass')
def __eq__(self, other):
raise NotImplementedError('must be implemented by subclass')
def __ne__(self, other):
return not(self==other)
def ... |
9302ddfcb4609eeb1e80ed7185115c1a0dcad828 | katiewilkinson/pythonmultiply | /helloworld.py | 251 | 4.0625 | 4 | #Part 1 of code prints all the odd numbers from 1 to 1000
#Part 2 of code prints all the multiples of 5 from 5 to 1000000
for i in range (1,1001):
if(i % 2 == 1):
print i
for i in range(5, 1000001):
if(i % 5 == 0):
print i
|
d00a31d49e8bc5d0f58f517925bc84c619b2f0a5 | alisher0v/MeFirstPrograms | /if,else,elif.py | 229 | 4 | 4 | e = 6
f = 5
if e < f :
print('e меньше переменной f')
else :
if e == f :
print("переменная е равен с переменной f ")
else :
print("e больше f")
|
403a039276e60f8423041e4b42230c8212fdcf83 | dheerajdlalwani/PythonPracticals | /Experiment1/code/question1.py | 1,031 | 4.34375 | 4 | # Question: Write a python program to print the following lines in a specific format
# Using only one print function
# Twinkle Twinkle Little Star,
# "How I wonder what you are!"
# Up above the world so high
# Like a diamond in the sky.
# 'Twinkle Twinkle' Little star
# How I wonder what you ar... |
ba2a454866f5fa4b755383bad93dbeb3c175c96f | ravi4all/PythonWE_Morning_2020 | /Chat_3.py | 1,021 | 3.5625 | 4 | from datetime import datetime
import glob,os,random
print("Welcome",name := input("Enter your name : "))
helloIntent = ["hi","hello","hey","hi there","hello there","hey there"]
timeIntent = ["time","tell me time","what's the time","time please"]
dateIntent = ["date","tell me date","what's the date","date pleas... |
cc84ac426106b9f91008bc981037e6e8b5e26ab2 | the-potato-man/lc | /2019/go/127-word-ladder.py | 2,182 | 3.78125 | 4 | '''
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return ... |
2df91ab53f923726a1d6c25ddb952d0d231ff1f7 | jPUENTE23/ESTRUCTURA-DE-BASES-DE-DATOS-Y-SU-PROCESAMIENTO-3ER-SEMESTRE | /02 FEBRERO/03 DE FEB/02-modulo.datetime.py | 1,882 | 4.0625 | 4 |
# funciones con modulo datetime
import datetime
import time
# la funcion de datetime.time, lo que hace es ayudarnos a combertir un tipo de dato str
# a uno datetime, solo deaccuerdo a una hora espesificada (HH-MM-SS) dentro de los argumentos
hora = datetime.time(22,10,10)
print("El tipo de datos de la hora es {}".fo... |
af49a548f21f3e5590b799a4917451fc135cf60e | Sagbeh/Database-Manager | /DisplaySingleRecord.py | 1,792 | 4.21875 | 4 | __author__='Sam'
# Imports sqlite3 library for database use
import sqlite3
# Defines displaySingleRecord function
def displaySingleRecord():
while True:
try:
sqlite_file = 'NewDatabase.db' # name of the sqlite database file
# User enters product ID of the records they want to view... |
39096da1dc5d9abe8ff72cc4a077523aa3b8d445 | shui190/uband-python-s1 | /homeworks/B21413/Checkin-09/day13-homework1.py | 638 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def main():
week_overnight = [False, True, False, False, False] #包含判断的列表
for index,is_overnight in enumerate(week_overnight):
print '今天星期%d' % (index + 1)
try:
check(is_overnight)
except Exception,e: #若没有这一段,就会出现报错。
print '发生错误:%s' % (e)
print '老妈骂... |
a25bb6b92dcc945399675ff18999dd810223b75a | chandneepuri/comp110-21f-workspace | /exercises/ex01/numeric_operators.py | 434 | 3.84375 | 4 | """numeric_operators.py."""
__author__ = "730228106"
left: str = input("Left-hand side:")
right: str = input("Right-hand side:")
number1: int = int(left)
number2: int = int(right)
print(left + " ** " + right + " is " + str(number1 ** number2))
print(left + " / " + right + " is " + str(number1 / number2))
print(left ... |
972a5a73b77a64060cd4f317f815c4bb50318d22 | cmry/seqmod | /seqmod/misc/early_stopping.py | 4,119 | 3.546875 | 4 |
import heapq
class pqueue(object):
def __init__(self, maxsize, heapmax=False):
self.queue = []
self.maxsize = maxsize
self.heapmax = heapmax
def push(self, item, priority):
if self.heapmax:
priority = -priority
heapq.heappush(self.queue, (priority, item))
... |
76829bb3d375f31cfbd39dc7ba5216d24f9ae872 | chasegan/pixiepython | /pixiepython/utils.py | 3,391 | 4.4375 | 4 | import math
import datetime as dt
import numbers
def is_a_digit(char):
"""
Check if the provided character is a digit.
Returns a boolean result.
"""
if (char == '0' or char == '1'
or char == '2' or char == '3'
or char == '4' or char == '5'
or char == '6' or char == '7'
... |
7561bf29a034167ce7ac3f94c990bdf487b8bef9 | heartdance/learn-python | /src/basic/the_tuple.py | 447 | 4.1875 | 4 | animals = ("dog", "pig", "sheep")
print("type(animals) =", type(animals))
# 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符
numbers = (1)
print("type((1)) =", type(numbers))
numbers = (1,)
print("type((1,)) =", type(numbers))
animalsList = list(animals)
print("type(animalsList) = ", type(animalsList))
animalsTuple = tuple(animals... |
4ec016182b1b4314e2970c58480184f10b433f65 | zllion/ProjectEuler | /p035.py | 702 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 15:06:58 2020
@author: zhixia liu
"""
"""
Project Euler 35: Circular primes
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31... |
6a1bb3a5882d85b3a6a7c549f3ae4570be22d716 | vivekgsheth/Python_CodeBasics | /doubly_linkedList.py | 3,655 | 4.0625 | 4 | class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.prev = prev
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def print_forward(self):
print("LinkedList is empty")
if self.head is None:
... |
5f74215428e0884b9be1f1bf3d42f34e886f5a41 | ALLProject2/Project2 | /P2 V9.py | 22,488 | 3.875 | 4 | ###########financial position search#################
def financial_position_search(): #define code for financial statement as function
#menu
print "1. Search by business name" #display option 1
print "2. Search business from sector" #display option 2
print " " #print blank line
search_selecti... |
6723a1b4262244c04ba650d900a66fd267f7537b | Eugene-twj/python_train | /dictionary.py | 3,039 | 3.8125 | 4 | alien_0 = {'color': 'green', 'point': 5}
print(alien_0['color'])
print(alien_0['point'])
favorite_languages = {
'jen': 'python',
'sarah': 'C',
'edward': 'ruby',
'phil': 'python',
}
# 按字母顺序遍历字典键-值对
for name, language in sorted(favorite_languages.items()):
print(name.title() + "'s favorite lang... |
c4e8960c5c6bd1ea34ad9ab7f9616453c4e1208a | Ved005/project-euler-solutions | /code/ambiguous_numbers/sol_198.py | 1,067 | 3.625 | 4 |
# -*- coding: utf-8 -*-
'''
File name: code\ambiguous_numbers\sol_198.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #198 :: Ambiguous Numbers
#
# For more information see:
# https://projecteuler.net/problem=198
# Problem Statement
'''... |
351c3bb82700da890f0284405b8c6aff0f0bade2 | daniel-reich/turbo-robot | /Kk5Ku4CtipaFtATPT_14.py | 1,470 | 4.15625 | 4 | """
* "coconuts" has 8 letters.
* A byte in binary has 8 bits.
* A byte can represent a character.
We can use the word "coconuts" to communicate with each other in binary if we
use upper case letters as 1s and lower case letters as 0s.
**Create a function that translates a word in plain text, into Coconut.*... |
8b7a7d89b09ed8643b84fcca229df57910da6ee2 | nixeagle/euler | /utilities/euler.py | 748 | 3.765625 | 4 | # (C) 2010 zc00gii (zc00gii@gmail.com)
# Do not copy or modify without crediting
# MIT compatible
def prime_factors(n)
w = 2
a = []
while w < n+1:
if n%w == 0:
n = n / w
a.append[w]
else:
w = w + 1
def factors(n):
w = 2
a = []
while w < sqrt(n):
if n%w == 0 and w < sqrt(n):
a.append[w]
w = w ... |
44e919a0432ff687a4d01d57070b39d2188adf50 | AkashManiar/python-basics | /class.py | 439 | 3.625 | 4 | class Animal(object):
name = ""
def eat(self):
print("%s is eating.." % self.name)
def sleep(self):
print("%s is sleeping..." % self.name)
class Mammal(Animal):
hasBackBone = True
hasHair = True
def growHair(self):
print("%s is Growing Hair" % self.name)
cat = Ma... |
c4f3159fffe8df180fd208a6040f55997a367a74 | daniel-reich/ubiquitous-fiesta | /GaJkMnuHLuPmXZK7h_10.py | 275 | 3.5625 | 4 |
def letters(word1, word2):
w1 = set(list(word1))
w2 = set(list(word2))
intersect = sorted(w1.intersection(w2))
unique1 = sorted(w1.difference(intersect))
unique2 = sorted(w2.difference(intersect))
return ["".join(intersect), "".join(unique1), "".join(unique2)]
|
c236286e8fa828ba8f5fc0c6d1f473213908a298 | AvneetHD/little_projects | /encryptor.py | 693 | 3.84375 | 4 | import random
result = ""
message = ""
choice = ""
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while choice != '0':
number = random.choice(numbers)
choice = input('Do you want to encrypt or decrypt\nEnter 1 to encrypt, 2 to decrypt, and 0 to exit.')
if choice == '1':
message = input('Enter Message f... |
49b4ee5d4141665d212e01ca24e7f33228a62c24 | muhammadegaa/xzceb-flask_eng_fr | /final_project/machinetranslation/tests/tests.py | 882 | 3.625 | 4 | import unittest
from translator import english_to_french, french_to_english
class TestTranslateEnToFr(unittest.TestCase):
"""
Class to test the function english_to_french
"""
def test1(self):
"""
Function to test the function english_to_french
"""
self.assertIsNone(engli... |
8baef38728c2320d081ccc73f3623c9f5665cbaf | DSC-Sharda-University/Python | /data-structure/doublylinked.py | 1,608 | 4.3125 | 4 | """
To create doubly link list with the operation insert at the first location and
also insert at the last location.
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# creation of doulbly linked list
class doublylink:
def __init__(self):
... |
7262eabc34c7cf8de127e574b3af5cfac40a208b | faiderfl/algorithms | /recursion/CapitalizeFirst.py | 664 | 4 | 4 | def capitalize_first(arr):
len_arr=len(arr)
if len(arr)==1:
aux=''
aux=arr[len_arr-1][0].upper()
aux = aux+ arr[len_arr-1][1:]
arr[len_arr-1]=aux
return [arr[len_arr-1]]
else:
aux=''
aux=arr[0][0].upper()
aux= aux + arr[0][1:]
arr[0]=au... |
e13dc2562d9f6e8ce5dbf64adbbd50afc7205ede | sairabhur/Py-Me-Up-Charlie-python | /main.py | 2,115 | 3.6875 | 4 |
# coding: utf-8
# In[1]:
import os
import csv
import locale
locale.setlocale( locale.LC_ALL, '' )
months = []
revenue = []
revenue_change = []
# In[2]:
file_path = os.path.join("budget_data.csv")
with open(file_path,'r') as csvfile:
csvdata = csv.reader(csvfile, delimiter=",")
next... |
a54d08843545df7e6f9dcdc93ef975d3669359b1 | igortereshchenko/amis_python | /km73/Zeleniy_Dmytro/5/task1.py | 485 | 3.828125 | 4 | heights = []
n = int(input("Enter number of pupil: "))
for i in range(n):
new_height = int(input("Enter hight pupil less than previous: "))
heights.append(new_height)
height = int(input("Enter height of Petya: "))
heights.append(height)
if height < 200:
heights.sort()
heights = heights[::-1]
s... |
b91704b00a6d8f9a064f89d18a8fcc0d70afc6fb | lo1cgsan/rok202021 | /3A/konto.py | 783 | 3.515625 | 4 | class Konto:
def __init__(self, ile = 0):
self.bilans = ile
def wplata(self, ile):
self.bilans += ile
return self.bilans
def wyplata(self, ile):
self.bilans -= ile
return self.bilans
class KontoStart(Konto):
def __init__(self, ile = 0, debet = 0):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.