blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e77e5854a648a29d8780d866dab118cd99e9cb2d | cloud-abyss/pythonProject1 | /day02/practice01.py | 145 | 3.65625 | 4 | # 将华氏温度转换为摄氏温度
f=float(input('请输入华氏温度:'))
c=(f-32)/1.8
print('华氏温度%.1f==摄氏温度%.1f' %(f,c)) |
2dfabe76e6664805f92811f5cd634835354793f6 | renansald/Python | /cursos_em_video/Desafio35.py | 394 | 3.9375 | 4 | reta1 = float(input("Informe a primeira reta: "))
reta2 = float(input("Informe a segunda reta: "))
reta3 = float(input("Informe a terceira reta: "))
aux = (reta1 + reta2 + reta3)/2
if((reta1 <= 0) or (reta2 <= 0) or (reta3 <= 0) or (aux-reta1 <= 0) or (aux-reta2 <= 0) or (aux-reta3 <= 0)):
print("Não é possível cri... |
3d18a5e63ded60b21d38ce75b91b2504510b498f | OusmaneT/Projet3_GLO1901 | /quoridorx.py | 4,291 | 3.5 | 4 | """ Class Quoridorx - Phase 3
Écrit par :
Maxime Carpentier
Vincent Bergeron
Ousmane Touré
Le 16 décembre 2019
Ce programme contient la classe avec toutes
les méthodes pour jouer au jeu Quoridor en graphique
"""
import quoridor
import turtle
class Quoridorx(quoridor.Quoridor):
"""
Classe Quoridor, contient to... |
866bc556625dfa73cac7990cc1e2ef6b4148945b | 17mirinae/Python | /Python/DAYOUNG/3_for문/구구단.py | 81 | 3.5625 | 4 | n = int(input())
for x in range(1, 10):
print("%d * %d = %d" %(n, x, n*x))
|
efe4cde9e2bd6d76710393b3ab1fc582ccf5a26d | arpanrau/TextMining | /wikipedia_sentiment_revised.py | 3,400 | 3.78125 | 4 | #scrapes wikipedia and performs sentiment analysis to figure out what wikipedia thinks about
#congress democrats and republicans
from pattern.web import *
from pattern.en import *
def sentiment_finder(searchterm):
"""Finds sentiment of a given article on wikipedia.
accepts string searchterm where searcht... |
008130f93a8f1b0478b33d7e0a0d223a8e4f5217 | magdalena-natalia/PR3TimeMachine | /interactions.py | 521 | 3.53125 | 4 | import datetime
def ask_for_input(question):
""" Ask an user for input. """
response = ''
while not response:
response = input(question)
return response
def ask_for_date(question):
""" Ask an user for a date and return it as datetime object. """
response = ask_for_input(question)
... |
f5415708d6838f1cbbce45dd9728a9a396de05da | spencerzhang91/coconuts-on-fire | /find_friend_20150326.py | 485 | 3.546875 | 4 | def network(L, first = None, second = None):
connection = []
for item in L:
connection.append({item.split('-')[0], item.split('-')[1]})
print(connection)
l = [item for item in connection if item.issuperset({first})]
print(l)
if {first, second} in connection:
return True
else:... |
dd3c609f9a2f95c2669ac4c866a6ff9f4bfdac7a | kangmihee/EX_python | /py_hypo_tensor/pack/ten21mnist.py | 2,376 | 3.546875 | 4 | # MNIST 분류
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./data/", one_hot = True)
training_epochs = 25
batch_size = 100 # 데이터 처리를 100개 묶음으로 처리
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
... |
10503b426f388917032cb1415d7d001397a847f3 | MrAliTheGreat/Programming | /Python/Coding/Practice/MileStone2.py | 4,067 | 3.765625 | 4 | from random import shuffle
from random import randint
class Player():
def __init__(self,money=100):
self.money=money
self.player_cards=[]
def place_bet(self,bet):
flag_bet=False
if bet <= self.money:
print(f'You have bet {bet}$')
self.money-=bet
flag_bet=True
else:
print("You don't have eno... |
73c337e5a7b12151226fb6e3a3a55e95834dcade | zaetae/gomycode | /6th/Q5.py | 168 | 3.59375 | 4 | import numpy as np
array=np.array([[1,8,9,7],[4,8,3,1],[7,8,6,10]])
for i in range (array.shape[0]):
#to loop through rows in array
print(array[i].mean())
|
c5a987fe5ce6cffd53d216545aa62adedea1b8e1 | Jinx-Heniux/Python-2 | /maths/leap_year.py | 389 | 3.875 | 4 | """
https://en.wikipedia.org/wiki/Leap_year
"""
def is_leap_year(year: int) -> bool:
"""
>>> all(is_leap_year(year) for year in [1600, 2000, 24000])
True
>>> all(is_leap_year(year) for year in [1999, 2001, 2002])
False
"""
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
if __... |
0f8cc6df257e651db41eaa502a777f917193eaa5 | adelgar/python-for-everybody-book | /Chapter 03 (Conditional execution)/exercise2.py | 452 | 3.96875 | 4 | inp1 = input('Enter Hours: ')
try:
hours = float(inp1)
inp2 = input('Enter Rate: ')
try:
rate = float(inp2)
if hours > 40:
worked = hours - 40
extra = worked * 1.5
inp3 = (40 + extra) * rate
pay = str(round(inp3, 2))
print('Pay: ' + pay)
else:
inp3 = hours * rate
pay = str(round(inp3, 2))
... |
41b69d20aa147123113eb3835f729722a50125d8 | BruceWeng/Restaur-Predict | /Project3/binarify.py | 3,584 | 3.6875 | 4 | import csv, re, sys, string
from util import *
from os import path
from math import log
# Limit the number of features for testing
BCL_LIMIT = -1
def getColList(fname, clColIndex):
""" Return a list of values of the column in the CSV file
Parameters
----------
fname: str
The name of t... |
6220dffa7d908db306e8c55a56930ccdd2132b4e | srmishraqa/Python-For-Beginners-and-Selenium | /Comparison Operator/Example1.py | 177 | 4.21875 | 4 | temp = int(input("Enter the temperature : "))
if temp > 30 :
print("It is a hot day")
elif temp < 10:
print("It is a cold Day")
else:
print("It is a pleasant day")
|
cb72c6160d6e2d0358aeb64a7118b098f0c3aa37 | detcitty/100DaysOfCode | /python/2020/03-March/2020-03-22/intergerArray.py | 518 | 3.796875 | 4 | # https://www.codewars.com/kata/52a112d9488f506ae7000b95/train/python
import re
def is_int_array(arr):
# your code here
end_value = None
if not arr:
end_value = True
else:
for e in arr:
regex_exp = "(\.)(\d*$)"
test = re.search(regex_exp, str(e))
if... |
1a73a7cb6b6fbdc1ad35eb4befee3f04c0d0d5c8 | daniel-reich/ubiquitous-fiesta | /HaxQfQTEpo7BFE5rz_12.py | 257 | 3.53125 | 4 |
def alternate_pos_neg(lst):
i = 0
k = 0
if lst.count(0):
return False
while i < len(lst):
if lst[i] < 0:
k += 1
i += 1
if i == len(lst):
break
if lst[i] > 0:
k += 1
i += 1
return k == 0 or k == len(lst)
|
922434c86319eac24ca445fe1fb71082b5034c07 | vortep72/python2 | /05_circles.py | 1,085 | 3.96875 | 4 | class Circle:
def __init__(self, center_coords, radius):
self.center = center_coords
self.radius = radius
def intersect(self, other_circle):
"""
Проверяет пересекается ли текущая окружность с other_circle
:return: True/False
"""
distance_center_circle = (... |
e887297e5608e0d8736bc3fa9ebf7e6449b30e51 | GeekyMonk07/PythonProjects | /Project2/Project2.py | 716 | 3.90625 | 4 | import random
randNumber = random.randint(1,100)
# print (randNumber)
guesses = 0
userGuess = None
while(userGuess != randNumber):
userGuess = int(input("Enter your Guess : "))
guesses += 1
if(userGuess == randNumber):
print(f"Your Guess is Correct!")
else:
if(userGuess > randNumber):... |
83e2ebbe522303d992f2af4d0975d9a34b5c5ecf | tjkemp/gym-buy-high-sell-low | /gym_bhsl/math/average.py | 1,137 | 4.28125 | 4 | import itertools
from typing import List, Sequence, Union
import numpy as np
def moving_average(
values: Union[Sequence[float], Sequence[int]], window: int
) -> List[float]:
"""Calculate moving average.
Args:
values: a list of values for which to calculate average
window: the length of w... |
68f692eeeff3f8e3af93a9112b8e5538fa9e3e63 | Thomas-j1/IN1000 | /oblig1/beslutninger.py | 359 | 3.90625 | 4 | """
Spør om bruker vil ha brus og skriver ut svar basert på input
"""
jaEllerNei = input("Vil du ha brus, ja eller nei?: ") #ja eller nei input fra bruker
if jaEllerNei == "ja":
print("Her har du en brus!")
elif jaEllerNei == "nei":
print("Den er grei.")
else:
print("Det forstod jeg ikke helt") #skriver u... |
f229d2d2bcdb2762464e087fc7b5b1d3dd8ce094 | GitHubUPB/maicolrepositorio | /5.py | 226 | 3.96875 | 4 | n=int(input("ingrese el numero a estudio"))
if ((n>0 and n%7!=0) and (n%2==0 and n%9!=0)) or (n%2!=0 and (n>100 and n<5000)) and (n%7!=0 or n%5==0):
print("el numero es chevere")
else:
print("el numero no es chevere")
|
9fc43587c9b710b8f97688208904395e430962e0 | rk280392/hackerrank_python | /fizzbuzz.py | 343 | 3.640625 | 4 | num = int(input(""))
my_nums = [int(i) for i in input().split()]
for i in range(1, my_nums[-1]+1):
# if i%3 != 0 and i%5 !=0:
# print(i)
if i % 15 == 0:
print("FizzBuzz")
continue
elif i % 3 == 0:
print("Fizz")
continue
elif i % 5 == 0:
print("Buzz")
... |
9999f39402124771f4cc13fd377a7a724616126a | amanpanda/flex-your-sighs | /lexicon_generator.py | 11,043 | 3.59375 | 4 | from random import sample
from numpy.random import choice
from numpy.random import random
import math
from enum import Enum
import pandas as pd
import os
MAX_CHOICE_SIZE = 100000000
# Approaches for homophones
class HomophoneStrat(Enum):
# max probability between homophones
maxprob = 0
# add probabilitie... |
19d589356891d58c1ccc185f0a69ad4be5e78166 | Dmitry-White/HackerRank | /Python/Sets/captains_room.py | 983 | 3.546875 | 4 | """
Created on Wed Aug 09 23:34:11 2017
@author: Dmitry White
"""
# TODO: Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
# One fine day, a finite number of tourists come to stay at the hotel.
# The tourists consist of:
# A Captain.
# An unknown group of famil... |
a7ea2bf6fd5fc18c69cb3d8d756253f34960c474 | Lckythr33/CodingDojo | /src/python_stack/flask/flask_fundamentals/hello_flask/routing.py | 986 | 3.671875 | 4 | from flask import Flask # Import Flask to allow us to create our app
app = Flask(__name__) # Create a new instance of the Flask class called "app"
@app.route('/') # The URL FOR BROWSER AFTER LOCALHOST:5000/
def hello_world():
return 'Hello World!' # Return the string 'Hello World!' as a response
@app.... |
6c41f22826846d6259a987dd0f633ce3ce89b8ff | 19mateusz92/pythonPrograms | /lista3/palindrom.py | 369 | 3.84375 | 4 | #!/usr/bin/env python3
def function(word):
head=0
tail=len(word)-1
while(head < tail):
if word[head]==word[tail]:
head+=1
tail-=1
else:
return False
return True
word=(input("wpisz łańcuch znaków aby sprawdzić czy je... |
94f85d6d2404c97b8b55f74fb0ac810be2b8b389 | WilliamYi96/Machine-Learning | /DS-Python-Implementations/Basic/stack/divideBy2.py | 321 | 3.703125 | 4 | from pythonds.basic.stack import Stack
def divideBy2(decimal):
s = Stack()
while decimal > 0:
number = decimal % 2
s.push(number)
decimal = decimal // 2
final = ""
while not s.isEmpty():
final += str(s.pop())
return final
print(divideBy2(15))
print(divideBy2(8))... |
3ee3e1a26d4136b5913c8211a76e75f5beb021dc | Aminaba123/Solving-problems-in-python | /List Problems.py | 11,195 | 4.34375 | 4 |
# Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True ... |
c11337de191b01d582d9cefe66fd608bfe81ae9f | Siddhantham/pythonAssg | /seventeenTableInReverse.py | 151 | 3.515625 | 4 | lis = []
for i in range(1,21):
lis.append("17 * "+ str(i) + " = " + str(17*i) )
lis = lis[::-1]
for i in range(len(lis)):
print(lis[i]) |
eaa752f05c580d4796449482a0ea3698910940f3 | gauravssnl/python3-network-programming | /echo_server.py | 1,835 | 3.859375 | 4 | import socket
host = 'localhost'
data_payload = 2048
backlog = 5
# we need to define encode function for converting string to bytes string
# this will be use for sending/receiving data via socket
encode = lambda text: text.encode()
# we need to define deocde function for converting bytes string to string
# this will... |
c6ed7d9bc9ae3a9cd3272b029dea3a61792ade6d | priyankasomani9/basicpython | /Assignment12/basic12.1_findUniqeValue.py | 627 | 3.8125 | 4 | from itertools import chain
test_dict = {'gfg' : [5, 6, 7, 8],
'is' : [10, 11, 7, 5],
'best' : [6, 12, 10, 8],
'for' : [1, 2, 5]}
print("The original dictionary is : " + str(test_dict))
res = list(sorted({ele for val in test_dict.values() for ele in val}))
print("The unique values list is : " + str(res))
#wa... |
51a5058c4b9cd5cad24874c74727b864e9899675 | sfdye/leetcode | /all-possible-full-binary-trees.py | 734 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def allPossibleFBT(self, N):
"""
:type N: int
:rtype: List[TreeNode]
"""
def build(N):
... |
376db44884f242b57fae2f055ee34cbd8567daa1 | daisypandey/Assignment_05 | /CDInventory.py | 3,312 | 3.859375 | 4 | #------------------------------------------#
# Title: CDInventory.py
# Desc: Use dictionaries as the inner data type (list of dictionaries)
# Allows the user to load inventory from file, add CD data, view the current inventory,
# delete CD from inventory, save data to a text file, and exit the program.
... |
6b9520223f9866409c7bccf3c07bd13bf28c5104 | OneDayOneCode/1D1C_Agosto | /sumayproducto.py | 779 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Calcular e imprimir la suma de 1+2+3+4+5+6.......+50
# Asignamos a una variable el rango del 1 - 51, osea los primeros 50 números
r = range(1, 51)
# Con la función sum se suman los números de una lista
print sum(r), "Es el resultado de sumar del 1 al 50, uno a uno!"
... |
8a882bc3b46bae87fe0dae7835dddb7fd8ac8f9c | csufangyu/study_sklearn | /ch3/贝叶斯分类.py | 5,525 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 13 21:27:15 2017
@author: Thinkpad
主要是介绍贝叶斯分类器
1.高斯贝叶斯分类器
class sklearn.naive_bayes.GaussianNB
高斯贝叶斯分类器没有参数
2.多项式贝叶斯分类器
class sklearn.naive_bayes.MultinomialNB(alpha=1.0,fit_prior=True,class_prior=None)
参数含义如下:
alpha:一个浮点数,指定alpha的值
fit_prior:布尔值,如果为Ture,则不用去学习P(y=ck),以均... |
a716329fcd26f3b327e81ce6a0b94d5b4c00b0b7 | neelrshah/Infinity-Coders-YouTube---Python-Course | /04_Strings/04_Strings.py | 800 | 4.53125 | 5 | # String Basics
# Creating a String
# s = "Python"
# Printing a String
# print(s)
# String Concatenation
# s1 = "hello"
# s2 = "world"
# print(s1 + s2)
# Indexing and accessing elements of String
# s = "Python"
# print(s[0])
# print(s[-1])
# Slicing of String
# s = "hello world"
# # s[star... |
8031a6a131724ac3ad993a8b23e8541f97c2594b | BusgeethPravesh/Python-Files | /Question4.py | 323 | 3.6875 | 4 | """Write a Python program that will find the L.C.M. of two input number."""
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if(a > b):
min1= a
else:
min1= b
while True:
if(min1 % a==0 and min1 % b==0):
print("LCM is:",min1)
break
min1+=1
... |
a107d95779001e88f8f2944c502262ae6deea318 | afossey/codingame-solutions | /difficulty_average/aneo.py | 1,031 | 3.65625 | 4 | import sys
import math
# https://www.codingame.com/ide/puzzle/aneo
speed = int(input())
light_count = int(input())
distances = []
durations = []
for i in range(light_count):
distance, duration = [int(j) for j in input().split()]
distances.append(distance)
durations.append(duration)
# Write an answer... |
ddb9df0ab7147905f47eb3d40e925a2b62b3efde | bawejakunal/hackerrank | /ctci-connected-cell-in-a-grid.py | 1,466 | 3.5625 | 4 | """
https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid
"""
from collections import deque
def isValidCell(grid, r, c):
return not (r < 0 or r >= len(grid)
or c < 0 or c >= len(grid[r])
or grid[r][c] != 1)
def dfsGetSize(grid, r, c):
if not isValidCell(grid, r, ... |
2e3087ee441641dc9cb3b50ac52eb5df84211577 | miaomiao-chong/py | /py_admin/adminUser.py | 3,145 | 3.609375 | 4 | import search
import insert
import handleUserTable
import update
import delete
def adminUser():
while 1:
print('''
1.查询操作(单表查询、打印全表、复杂查询)
2.建立新表/删除新表(管理员用户/普通用户表)
3.插入学生数据/选课信息/管理员用户/普通用户
4.更改学生专业信息/成绩信息/用户密码
5.删除学生相关信息/管理员用户/普通用户
''... |
c732a4ed4ac2130b49873302f77aec52b514ec6e | FrancescoSRende/FrancescoSRende.github.io | /Python Contest Questions/iterativeBinarySearch.py | 1,942 | 4.0625 | 4 | # Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
# Check base case
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid, then it ca... |
26c65904c7f729e071633dffeb9e14f2da51ad99 | lmdiazangulo/hopfions | /anim.py | 562 | 3.609375 | 4 | #Este codigo abre "1D.h5", generado por "1Dh5.py" y muestra una animacion
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani
import h5py as h5
#Open h5 file
fin = h5.File('1D.h5','r')
N = fin.attrs['N']
iterations = fin.attrs['iterations']
L = 10
x = np.linspace(0,L,N+1)
Ex = fin['0... |
aebb309852dbeae693e2fe080d9726555e365e01 | Silberschleier/al-exercises | /sheet05/assignment38/plot.py | 593 | 3.71875 | 4 | import matplotlib.pyplot as plt
def run(x0, a, iterations):
results = [x0]
for _ in range(iterations):
x0 = a * x0 * (1 - x0)
results.append(x0)
return results
if __name__ == '__main__':
x0_1, x0_2 = 0.228734167, 0.228734168
a = 3.75
results_1 = run(x0_1, a, 1000)
results... |
ca7c6d592b32b27c332fbf61538f4b9548900605 | ncturoger/LeetCodePractice | /Linked_List/Reorder_List.py | 1,892 | 3.84375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
... |
4cf6757651d767beef9ce6ca40ec820cca7afbdb | ChikusMOC/Exercicios-Capitulo-5 | /cap5_ex29.py | 1,155 | 4.03125 | 4 | """
Exercicio 29 - Faça uma prova de matemática para crianças que estão aprendendo a somar números
inteiros menores do que 100. Escolha números aleatórios entra 1 e 100, e mostra na tela a pergunta:
qual é a soma de a + b, onde a e b são numeros aleatórios. Peça a resposta. Faça cinco perguntas ao aluno,
e mostre pra e... |
7fd265bda5808efec05f1cb125234f91ab1a6c1d | WillTheSun/interviewCake | /03_highest_product_of.py | 700 | 4.15625 | 4 | def my_function(list_of_ints):
highest = max(list_of_ints[0:3])
lowest = min(list_of_ints[0:3])
lowest_product_two = list_of_ints[0] * list_of_ints[1]
highest_product_two = lowest_product_two
highest_product_of_3 = lowest_product_two * list_of_ints[2]
for x in list_of_ints[2:]:
high... |
c65742c3924f2fa1c7d495c30f710f62c221df11 | BenTildark/sprockets-d | /DTEC501-Lab3-1/lab3-1_q4.py | 1,846 | 4.4375 | 4 | """
Write a program to ask the user to enter their first/given name.
Your program must display the following message:
Please enter your first name:
Then output the following:
Hi EnteredFirstName, please enter the first integer:
and once the user has entered the integer, display the following message:
Please ent... |
6d024c99512cf4dc7b1fd0118c49aa2fcc8809ce | huseyin1701/goruntu_isleme | /2. hafta - python devam/7_or.py | 67 | 3.609375 | 4 | a = 5
b = 8
if a == 5 or b == 10:
print("işler tıkırında")
|
31639b72107323d6cfbf3bd3b4497cf22df984f4 | Mustafalw02/MustafaPythonAssignment | /exercise_ii_a/sum_of_digits.py | 196 | 4.125 | 4 | # -*- coding: utf-8 -*-
x = int(input('Enter a five digit number: '))
sum = 0
sum += x%10
x //= 10
sum += x%10
x //= 10
sum += x%10
x //= 10
sum += x%10
x //= 10
sum += x%10
x //= 10
print(sum)
|
4dc7160cf47309833f027b1ebb7283f7e87ea674 | PyRPy/algorithms_books | /Others/gfg_dp_binomialCoeff.py | 1,910 | 3.671875 | 4 | # gfg_binomialCoeff
# https://www.geeksforgeeks.org/binomial-coefficient-dp-9/
def binomialCoeff(n, k):
if k > n:
return 0
if k == 0 or k == n:
return 1
# recursive call
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)
# test
n = 5
k = 2
print("the value of C(%d, ... |
b27a8253071c1b4f8756c7a80e1954ddf931e288 | Plasmoxy/MaturitaInformatika2019 | /python/strukturovane_typy/sifra.py | 312 | 3.640625 | 4 | v = input("text: ")
# funguje aj na desifrovanie
def sifra(s):
out = ""
l = len(s)
parne = l%2==0
for i in range(0, l if parne else l-1, 2):
out += s[i+1] + s[i]
if not parne:
out += s[-1] # pridaj posledny znak ak neparne
return out
print(sifra(sifra(v)))
|
2a691e19c25db8c1286386eed34d64bf7b5cd7a9 | AnyaKvon/coffee | /code.py | 2,892 | 4.3125 | 4 | class Coffee:
def __init__(self, water, milk, beans, cash):
self.water = water
self.milk = milk
self.beans = beans
self.cash = cash
class CoffeeMachine:
espresso = Coffee(250, 0, 16, 4)
latte = Coffee(350, 75, 20, 7)
cappuccino = Coffee(200, 100, 12, 6)
def __init_... |
194fc6361b2670ef1314e4b26ac7a28d2daf4b93 | wangwq1325/wangwq | /python/iteration/findMinMax.py | 209 | 3.9375 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
def findMinMax(*L):
for i in L:
minnum = min(L)
maxnum = max(L)
return (minnum,maxnum)
x = findMinMax(1,2,3,4,6)
print x
|
f4fd46b4fe8d3637253cdbbafef7a78096ef624d | b96705008/py-lintcode-exercise | /basic/ch5/word_break.py | 1,262 | 3.59375 | 4 | class Solution:
"""
@param: s: A string
@param: dict: A dictionary of words dict
@return: A boolean
"""
def wordBreak(self, s, dic):
# write your code here
if s is None or dic is None:
return False
if len(s) == 0:
return True
... |
951a02ddaab92ca7330ca2cfa329252cdd0eebb5 | jonycse/pythonSampleCode | /decoratonSample.py | 391 | 3.609375 | 4 | class MyDecorator(object):
def __init__(self, f):
self.doSomethingCopy=f
print "This line will call on decoration"
def __call__(self,p,q):
print "This line will work when we call the function 'doSomething' "
self.doSomethingCopy(p+1,q+1)
@MyDecorator
def doSomething(a,b):
p... |
4b18ab6102e5888fab73ff4382dedb7b02fa6a71 | neoBontia/cse210-student-jumper | /jumper/game/jumper.py | 1,604 | 4.03125 | 4 | class Jumper:
"""This class is responsible for handling the actions of the player.
It will facilitate the guessing and if the game is still playable.
Stereotype: Information Holder, Service Provider
Attr:
guess (character): the letter guessed by the jumper.
lives (number): how many liv... |
8735c75d6efbc3e5b0d62da00ee73b8a8fe07de5 | umbs/practice | /IK/Graphs/HW/AlienDictionary.py | 1,114 | 3.78125 | 4 | from collections import defaultdict
def topo(node, graph, visited, stack):
visited.add(node)
for neigh in graph[node]:
if neigh not in visited:
topo(neigh, graph, visited, stack)
stack.append(node)
def find_order(words):
'''
words: An array of strings
'''
graph = def... |
51051a9e056f6ba0294cf804d92ee6624932076e | jpslat1026/Mytest | /Section2/2.1/10.py | 366 | 3.9375 | 4 | # 10.py
#by John Slattery on December 13, 2018
#This will tell you the average amount of words you havre in a sentce
def main():
words = input("Enter a sentce: ")
words = words.split(" ")
k = len(words)
c = 0
for i in words:
v = len(i)
c = c + v
aw = c / k
print(aw, "is the ... |
d3ff3479f57745e660a55ddc01bc40e083751325 | snowhuand/python | /python_2/Programming1 Lecture/week10_revision.py | 682 | 4.03125 | 4 | """
Given:
subjects= {"CP1401": (60, 70, 80),
"CP1404": (70, 80, 90)}
print the above data with string formatting like the following:
CP1401 60% 70% 80.00%
"""
def print_marks(subjects={"dummy", (0, 0, 0)}):
for key, value in subjects.items():
print("{:^15}{:>10d}%{:>10d... |
16ac6be1c6ab112ac1857d2bb0291e8e92fdcdfb | Pyk017/Competetive-Programming | /Interview_Preparation_Questions/Interview_Questions(Coding_Club_PSIT)/Possible_Subsets.py | 622 | 3.953125 | 4 | """
Given a set of distinct integers, nums, return all possible subsets(the power set). Note: The Solution set must not
contain duplicate subsets.
Input : [1, 2, 3]
Output : [
[3], [2], [1],
[1, 2, 3], [1, 3],
[2, 3], [1, 2],
[]
]
"""
def subsets(array):
subset = [0]*len(array)
helper(array, s... |
ac24a9e4645c91ccd58fa0ac86ecc41f268a59d9 | Vishal45-coder/Day4 | /Assignment4_rangeofnum.py | 398 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 10:59:30 2020
@author: vishal
"""
X = 1000
Y = 7000
def checkRange(num):
# using comaparision operator
if (a>X and a<Y):
print(f"{a} is in between ({X} {Y})")
else:
print(f"The number {a} is not in range ({X}, {Y})")
# Test I... |
81fe2450e750d08612e2a653bcffda8c05aeaf37 | karolinanikolova/SoftUni-Software-Engineering | /3-Python-Advanced (May 2021)/workshop/lab/tic_tac_toe/main.py | 993 | 4.15625 | 4 | from workshop.lab.tic_tac_toe.core.logic import play
def print_initial_board_positions():
print("This is the numeration of the board:")
print("| 1 | 2 | 3 |")
print("| 4 | 5 | 6 |")
print("| 7 | 8 | 9 |")
def create_empty_board():
return [[" ", " ", " "] for _ in range(3)]
def setup():
pla... |
2989deb12897b53c056b3c58754e6b7a837bad94 | vaisaghvt/MistakeCorrectionScript | /extractPhrases.py | 1,820 | 4.15625 | 4 |
def extractPhrase(match, line):
"""Returns the phrase which was matched. Rather than just the matched pattern, it returns
the complete phrase in which the match occured """
startCount = 0
endCount = len(line)
for i in range(match.start() - 1, -1, -1):
if line[i] == ' ' or line[i] == '\n' o... |
7b4a63b2f0156ef0225c609006f347c36aaab872 | erkanuz/Python-Coursework | /application/languages.py | 184 | 3.546875 | 4 | class Language:
def __init__(self, main, second):
self.main = main
self.second = second
def print(self):
print(self.main + " " + self.second, end="")
|
05a09acae41f14da89124160326efe990ac3b3cd | D3nii/Random | /Python/dics.py | 244 | 3.78125 | 4 |
Hamza = {"name" : "Hamza", "age" : "18", "height" : "5.11"}
Bilal_Bhai = {"name" : "Bilal", "age" : "23", "height" : "6.1"}
people = [Hamza, Bilal_Bhai]
for ppl in people:
print("The name is", ppl["name"], "and his age is", ppl["age"])
|
2b2a0b093f345c503492512810f0b92fa740cac6 | eessm01/100-days-of-code | /real_python/testing_lambdas.py | 740 | 4.03125 | 4 | import unittest
"""Real Python. How to Use Python Lambda Functions
Python lambdas can be tested similary to regular functions. It's
possible to use both unittest and doctest.
"""
addtwo = lambda x: x + 2
addtwo.__doc__ = """Add 2 to a number.
>>> addtwo(2)
4
>>> addtwo(2.2)
4.2
>>> addtwo(3) # S... |
041acbc02b3094837c7643d1be710fa3134d1852 | harshVRastogi/python-examples | /src/exercise5-input/VariableArguments.py | 799 | 4.125 | 4 | # using import you include the feature you specify after import keyword
# every language has a vast pool of features or libraries or modules
# which are imported when the user requires to keep the program as small as possible
from sys import argv
# here python unpacks the variables you entered in the console
# enter e... |
bb7b46553c7d8774a5befd9ddaaa911a23731ae5 | Nithanaroy/PythonSnippets | /Intuit3.py | 533 | 3.890625 | 4 | """
Given a string, return the minimum number characters that should be added to that string to make it a palidrome
"""
def shortPalin(s):
e = len(s) - 1
i = 0
c = 0
while i < len(s) / 2:
if s[i] != s[e]:
s = insertAtIndex(s, i, s[e])
c += 1
e += 1
i ... |
a41b421cf088986543cefce0b521e6b7c97c5cb3 | LarissaMidori/curso_em_video | /exercicio037.py | 901 | 4.4375 | 4 | ''' Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão:
1 para binário, 2 para octal e 3 para hexadecimal. '''
print(f'{"=**=" * 15}')
print(f'CONVERSOR DE BASES NUMÉRICAS: ')
print(f'{"=**=" * 15}')
num = int(input(' Digite um número inteiro... |
d9169f3072c6dbc0f8adcf0ed3f2cd2fec6fc091 | SantiagoJSG/Trabajo_Final_30_Abril | /Ejercicio22.py | 299 | 3.953125 | 4 | # Ejercicio 22
print("El programa está orientado a determinar si el número ingresado es par o impar (solo se aceptan números enteros).")
numero = int(input("Digite un número entero: "))
if numero % 2 == 0:
print("Ingreso un número par")
else:
print("Ingreso un número impar")
|
b3b1e31a8a6480840f6f08c6f02d8beb6c2440b5 | hacmorgan/8-bit-cpu | /wirelen | 341 | 3.59375 | 4 | #!/usr/bin/env python
import sys
def wirelen( num_pins ):
print( "{}mm".format(float(num_pins)*2.54+14) )
def main():
while True:
try:
wirelen( eval(input("Number of pins: ")) )
except NameError:
print( "invalid input", file=sys.stderr )
if __name__ == '__main__':
... |
d63a47d4c938e61a6b3887ff9714df7fda3314bb | cacciatora/LintCode | /Rotate Array.py | 773 | 3.859375 | 4 | class Solution:
"""
@param nums: an array
@param k: an integer
@return: rotate the array to the right by k steps
"""
def rotate(self, nums, k):
# Write your code here
k = k % len(nums)
left = 0
p = len(nums) - k - 1
while left < p:
nums[left],... |
d348516646697897e7c2700ed4cc71cee9763f05 | DDDlyk/learningpython | /05_高级数据类型/ddd_10_字典基本使用.py | 358 | 4.1875 | 4 | xiaoming_dict = {"name": "小明"}
# 1、取值
print(xiaoming_dict["name"])
# 在取值的时候,如果指定的可以不存在,程序会报错。
# print(xiaoming_dict["123"])
# 2、增加/修改
xiaoming_dict["age"] = 18
xiaoming_dict["name"] = "小小明"
# 3、删除
# xiaoming_dict.pop("name")
xiaoming_dict.pop("name123")
print(xiaoming_dict)
|
2fceac6c317a831b868d88e9be9a539e07203f93 | ehpor/hcipy | /hcipy/optics/surface_profiles.py | 3,675 | 3.5 | 4 | import numpy as np
from ..field import Field
def spherical_surface_sag(radius_of_curvature):
'''Makes a Field generator for the surface sag of an even aspherical surface.
Parameters
----------
radius_of_curvature : scalar
The radius of curvature of the surface.
Returns
-------
Fie... |
cea41650826b1db80b942997354e467885ab830f | mizhi/project-euler | /python/problem-104.py | 1,510 | 4.03125 | 4 | #!/usr/bin/env python
# The Fibonacci sequence is defined by the recurrence relation:
#
# Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
#
# It turns out that F541, which contains 113 digits, is the first
# Fibonacci number for which the last nine digits are 1-9 pandigital
# (contain all the digits 1 to 9, but not nece... |
a196d7e2af36c66d756e4842367abbf018cb4ab5 | jdtayyub/HLC-Work-Python-Multi-Obstacle | /scene/scenes.py | 2,486 | 4.1875 | 4 |
class Scene2D:
"""Class defining the environment
Values of the abstract properties
* **_x,_y,_z,_width,_height,_depth** = "Dimensions of the scene"
* **_objects** = "a dictionary of objects of the 'physical object' class"
Members
* **_visualise** ():
"""
_x = 0
_y = 0
... |
9d8d646d8a80306ac9399076fe5686c22e25089a | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4414/codes/1635_2704.py | 168 | 3.828125 | 4 | nota=float(input("nota:"))
bonificacao=input("S ou N :")
if(bonificacao=="S"):
notafinal= nota + nota*0.10
print(notafinal)
else:
notafinal=nota
print(notafinal)
|
ae96f971595c8c348a91d39a7efa0acb7497daa9 | DRubioG/Traductor-a-braille | /diccionario.pyw | 12,024 | 3.5 | 4 | from tkinter import *
def ast():
return chr(9679)
def blc():
return chr(9675)
#str=""
def linea0(str):
return str+blc()+' '+blc()+' '
def linea1(str):
return str+blc()+' '+ ast()+' '
def linea2(str):
return str+ast()+' '+blc()+' '
def linea3(str):
return str+ast()+' '+... |
0a77d11e52c8b667af91b37aba4830e9bec208f7 | scj1420/Class-Projects-Research | /Class/ACME_Volume_1-Python/LinearSystems/linear_systems.py | 6,277 | 3.671875 | 4 | # linear_systems.py
"""Volume 1: Linear Systems.
<Name>
<Class>
<Date>
"""
import numpy as np
import scipy as sp
from scipy import linalg as la
# Problem 1
def ref(A):
"""Reduce the square matrix A to REF. You may assume that A is invertible
and that a 0 will never appear on the main diagonal. Avoid operating... |
2bf4964e746ed924390cb74b527417c79db38875 | JenZhen/LC | /lc_ladder/Adv_Algo/binary-search/Maximum_Average_Subarray_II.py | 2,163 | 4.0625 | 4 | #! /usr/local/bin/python3
# https://www.lintcode.com/problem/maximum-average-subarray-ii/description
# Given an array with positive and negative numbers, find the maximum average subarray which length should be greater or equal to given length k.
# It's guaranteed that the size of the array is greater or equal to k.
#... |
14f8b34e740dd3aca6b19cb4b9adea8f12baf3ae | kevinlichang/XiangQi | /main.py | 21,106 | 3.640625 | 4 | # Author: Kevin Chang
# Description: Creates a game call XiangQi. The game is played on a 9x10 board, with 7 different types of pieces
# that have their own individual behaviors and rulesets. The goal of the game is to capture the enemy's general piece.
# The game is over when a player's general piece has no spaces t... |
92f1711d53814d98d0e4aefa7dbcd4c2730edc79 | ka3254/test-xx | /python/demo.py | 2,110 | 4.125 | 4 | # print('你好'+"带我玩"*3,end="111")
# print(123)
# print(2.333)
"""
print((2+2-1*1/0.5)*2)
print(True,False)
print(1>3)
print(1<3)
print(1==2 or 1<3)
print(1==2 and 1<3)
print(None)
print(())
print([])
print({})"""
# name='张三'
# print(name)
# #运算输出
# res= (1+2+4+5*2/(4*2))%3
# print(res)
#获取内容并切换成小数进行运算
# a=input("输入:"... |
89d3d4ba267d9d859a62801ff845d676d0778e7e | omidcc/leetcode | /4. Median of Two Sorted Arrays/median.py | 351 | 3.515625 | 4 | def findMedianSortedArrays(nums1, nums2):
mergedArray = nums1 + nums2
i = 0
mergedArray.sort()
n = len(mergedArray)
median = 0.0
if n % 2:
median = mergedArray[int(n/2)]
else:
median = (mergedArray[(int(n/2))-1] + mergedArray[int(n/2)])/2.0
return median
print(findMedia... |
ba5eaaa5bd6c3dfa35db79f8a338969a28006806 | MMMinoz/p3.py | /Python.py | 6,605 | 3.828125 | 4 | #DrawPython蟒蛇
import turtle as tur
# #设置窗体大小 startx,starty非必需,默认在屏幕中间
# turtle.setup(width,height,startx,starty)
# #海龟到(x,y)坐标
# turtle.goto(x , y)
# #海龟向前移动d
# #当d值为正数时向前移动
# #当d为负数时向后移动
# turtle.fd(d)
# #画笔向后移动d
# turtle.bk(d)
# #r弧形半径
# #当radius值为正数时,圆心在当前位置/小海龟左侧
# #当radius值为负数时,圆心在当前位置/小海龟右侧
# #angle弧形角度 当无该参数或参数为... |
303ea276783a7ac30f8ac77789801cdb98b12df0 | silviagajdos/chatbot | /client_code-1.py | 3,845 | 3.671875 | 4 | import socket
from Printer import dictPrinter
mealDict = {1:"Breakfast", 2:"Lunch", 3:"Dinner"}
cuisineDict = {1:"African", 2:"British", 3:"Chinese", 4:"French", 5:"Fast Food", 6:"Indian", 7:"Italian", 8:"Japanese", 9:"Korean", 10:"Lebanese", 11:"Mexican", 12:"Turkish"}
def Main():
#connection to ChatBot
host ... |
03733307ed44e7db11d511e47c24f6193f90494b | imask22/Python-Assignment | /ask/module3/validation_negative.py | 303 | 3.921875 | 4 | print("enter exit to exit the loop")
while(1):
ask=input("Enter no of product = ")
whp=input("Enter wholesale price : ")
if(whp=="exit"):
break
elif("-" in whp):
continue
else:
whp=float(whp)
print("retail price = ",whp*0.5*float(ask))
|
2b0740af2a4c8083bdedb35a35afd7d3255f8277 | hauphanlvc/CS114 | /CodeGiup/Thoa_ChieuCaoCuaCay.py | 967 | 3.75 | 4 |
import collections
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.val=data
def insert_tree(root,data):
if root is None:
return Node(data)
else:
if root.val==data:
return root
elif root.val<data:
root.right=insert_tree(root.right,data)
... |
1c3a8b7e0f0ab924feda9535fe7d884dbf559930 | astrochialinko/StanCode | /SC201/Class_Demo/SC201_L4/titanic_survived.py | 5,263 | 3.75 | 4 | """
File: titanic_survived.py
Name: Chia-Lin Ko
----------------------------------
This file contains 3 of the most important steps
in machine learning:
1) Data pre-processing
2) Training
3) Predicting
"""
import math
TRAIN_DATA_PATH = 'titanic_data/train.csv'
NUM_EPOCHS = 1000
ALPHA = 0.01
def sigmoid(k):
"""
... |
abc7ebb9f9cbdcac540f54e0e65deeb1812f2f2f | zwwpaul/CISC481-681_Programming1 | /pancake.py | 1,932 | 3.53125 | 4 | class Pancake:
def __init__(self, o):
self.g = 0
self.h = 0
self.choice = o[4]
self.elements = o
self.maximum = int(self.elements[0] + self.elements[1] + self.elements[2] + self.elements[3])
self.length = len(o)
self.path_dic_dfs =[]
self.total_g = 0
self.path_dic_ucs = {}
self.root=None
self.pa... |
751835d654ea5f34d314204c2a854a8eb925a807 | jedzej/tietopythontraining-basic | /students/kojalowicz_piotr/lesson_02/While loop/The second maximum.py | 254 | 3.984375 | 4 | integer = int(input())
firstMax = 0
secendMax = 0
while integer != 0:
if firstMax < integer:
secendMax = firstMax
firstMax = integer
elif secendMax < integer:
secendMax = integer
integer = int(input())
print(secendMax) |
2f5e9926cf8f88a2e446dad5abf90c382d18946f | DirtNap/EulerSolutions | /p0010.py | 225 | 3.5625 | 4 | from util import prime_generator
def main():
result = 0
for pn in prime_generator(2000000):
result += pn
print(f'The sum of prime numbers below 2000000 is {result}')
if __name__ == '__main__':
main() |
98f8573110081a17ce7a41bbd31d2d04be6cd3a6 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/matrix/a83e05dd1d384c52a3364af6cafd9bd7.py | 525 | 3.578125 | 4 | class Matrix(object):
def __init__(self, matrix):
self.matrix = matrix
# generate rows as list of lists
self.rows = []
# first split on newline
for item in self.matrix.split('\n'):
# then split on space and convert string to int
self.rows.appe... |
2d5d7427742d7ac9911e49ae3ebef0b8d0ff1ea1 | yashshinde03/NLP | /NLP.py | 538 | 3.5 | 4 | import pandas as pd
data = pd.read_csv('amazon_alexa.tsv',delimiter='\t')#read dataset
# print(data.shape)#shape of dataset
# print(data.head()) Head of dataset
#If any missing value is their
# print(data.isnull().sum())
# print(data.describe()) checking description of data
# print(data.describe(include='object'... |
19ff245d7b1e41f95fbb23f78e29fa9d4b021c8c | xistadi/Python-practice | /PythonCourseYT-andrievskii/Урок 29 Тестирование/names.py | 376 | 3.78125 | 4 | from work import full_name
print("Для остановки теста введите 'Q' ")
while True:
first = input("\nВведите ваше имя: ")
if first == "Q":
break
last = input("\nВведите ваше фамилию: ")
if last == "Q":
break
format_name = full_name(first, last)
print("\tформатирование имени: " + format_name) |
ea51bd964de87f131ec8ba33ccf8c3b288ec631e | kaitoulee/python-learn | /pylearn1.py | 431 | 3.875 | 4 | # coding=utf-8
__author__ = 'kaitouLee'
#变量定义
'''
a = 10
b = 2
c = a + b
print (c)
'''
#判断定义
'''
判断成绩是否及格
score = 90
if score>=80 :
print("very Good")
elif score >= 50 :
print("good")
elif score<=30 :
print("no good")
else :
print("很差")
'''
#判断条件是否成立
x = 5
if x>0:
print 'x>0'
a = 2
b ... |
8654c0f5b5b7aeb59d2cef8fd96f83f896bc6a40 | pppssm/discretemathpython | /sort.py | 415 | 3.703125 | 4 | def bubblesort(L):
result = list(L)
for x in xrange(len(result)-1):
for y in xrange(len(result)-x-1):
if (result[y] > result[y+1]):
result[y], result[y+1] = result[y+1], result[y]
return result
def selectionsort(L):
temp = list(L)
result = []
while (len(temp)... |
a8fe0e0f8c9be134def2723493b24fd510ccb60d | gabriellaec/desoft-analise-exercicios | /backup/user_114/ch41_2019_04_05_02_06_05_447383.py | 157 | 4.03125 | 4 | palavra=input('tentativa senha: ')
if palavra!='desisto':
palavra=input('tentativa senha: ')
elif palavra=='desisto':
print('Você acertou a senha!') |
13cd261193732728dd907e963f342fe83e803e4d | mgmavely/turtle-racer | /main.py | 952 | 4.1875 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput("Place Your Bet!", "Which turtle will win the race?")
colors = ["red", "orange", "yellow", "green", "blue", "indigo"]
turtles = []
y_coord = -100
for turtle_index in range(0,6):
new_tur... |
52683cdee91397d40ea4ee81da32e8783bedf76b | xizhang77/CodingInterview | /Twitter-OA/get-set-go.py | 717 | 3.78125 | 4 | # -*- coding: utf-8 -*-
'''
Get set go
'''
class Solution(object):
def combinationSum(self, calories, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
calories.sort()
check = set( [0] )
for cal in calories:
... |
c55c1843a4d200a3bbaa29a9105b597179268a43 | samiulla7/learn_python | /file_handling/file.py | 2,102 | 3.78125 | 4 | # '''
# Method Description
# close() Close an open file. It has no effect if the file is already closed.
# detach() Separate the underlying binary buffer from the TextIOBase and return it.
# fileno() Return an integer number (file descriptor) of the file.
# flush() Flush the write buffer of the file stream.
# isatty() ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.