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 |
|---|---|---|---|---|---|---|
6e444f3fed6cf74c4c814cae3654613fa718f554 | claudiodornelles/CursoEmVideo-Python | /Exercicios/ex091 - Jogo de Dados em Python.py | 1,540 | 3.671875 | 4 | """
Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionário. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado.
"""
from random import randint
from time import sleep
jogadores = {'Jogador 1':randint(1,6),
... |
cbf7ff3e7d8ee7dcf6f5d7832e707f425c2482f7 | zacharyk88/ZachG | /Python/a2.py | 814 | 3.875 | 4 | #Author: Zachary Goss
#Purpose: Copies any .txt file lines as list elements to be printed off with error checking
def main():
count = 0
while True:
fName = input("enter the input file name please: ")
try:
inputFile = open(fName, 'r')
except:
print("I cannot open t... |
2c16aa82e920054180917da613bdca916d377e0c | wangyeon-Lee/Yeon | /keras17_minmax.py | 1,791 | 3.59375 | 4 | from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
#1 데이터
x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7],
[6,7,8], [7,8,9], [8,9,10], [9,10,11], [10,11,12],
[20000,30000,40000], [30000,40000,50000], [40000,50000,60000], [100,200,300]])... |
25ab32b13d8567b042e3b72888f4c75f6f2a77f4 | dyt1993/Python-Staly | /初始练习/app09.py | 206 | 3.921875 | 4 | #字符串显示输出和替换
course = 'python for beginners'
#print(len(course))
#print(course.upper())
#print(course.lower())
#print(course)
#print(course.replace('p','ab'))
#print('python' in course)
|
8842748ca429fbf865743d9cfb2d6b29214d64a0 | Tahmid2000/war-card-game | /war-card-game.py | 4,223 | 3.59375 | 4 | from random import shuffle
import time
SUITE = 'H D S C'.split()
RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
class Deck:
def __init__(self):
self.deck = []
for x in SUITE:
for y in RANKS:
card = (x, y)
self.deck.append(card)
def split(self):
... |
c743c3761bbc1c098f805d93fd584da247eb5215 | juebrauer/teaching_multimodal_sensor_systems | /Particle Filter Demo in Python/particle_filter.py | 9,825 | 3.921875 | 4 | # file: particle_filter.py
#
# Simple particle filter demo in Python (Python 2.7.x)
#
# Originally written by Martin J. Laubach in 2011.
# Source: https://github.com/mjl/particle_filter_demo
#
# Slightly adapted by Prof. Dr. Jürgen Brauer, www.juergenbrauer.org
#
# coding=utf-8
#
# Original description by Martin J. La... |
3ad0c9cb1ffbe5e18d4a1fa0659b1455bda00988 | mandrakean/Estudo | /Python_Guan/ex039.py | 331 | 3.78125 | 4 | print('-=-'*20)
print('Preciso me alistar?')
print('-=-'*20)
print('')
from datetime import date
ano1 = int(input('quando você nasceu? '))
data = date.today()
ano2 = '{}'.format(data.year)
idade = int(ano2) - ano1
print('')
if idade > 18:
print('Hora de se alistar!')
else:
print('você ainda não precisa se al... |
8d90b848a27d6f6745a9f434f5c6fc4355e72c32 | SeriwanIS/Python | /TPAlgorithmique/exercice 2 parti 1.py | 207 | 3.9375 | 4 | phrase= input ("Entrer une phrase : ")
saisie= input ("Entrer une lettre: ")
nombre=0
for lettre in phrase:
if lettre == saisie:
nombre +=1
print (" la phrase saisie comporte ", nombre ,saisie)
|
a8b536bfd57355994d566e70e41e59b8345eacc6 | darthsuogles/phissenschaft | /algo/leetcode_628.py | 346 | 4.1875 | 4 | """ Maximum product of three
"""
def maximumProduct(nums):
if len(nums) < 3: return 0
nums = sorted(nums)
a, b = nums[:2]
c, d, e = nums[-3:]
post_max = c * d * e
if b < 0:
return max(a * b * e, post_max)
else:
return post_max
def TEST(nums):
print(maximumProduct(nums)... |
9c4b51190bc53a004f8660c3445f84e55c7ca140 | alejandrac06/Programacion4 | /Quiz2.py | 196 | 3.953125 | 4 |
def letters_generator():
current = 'a'
while current <= 'm' :
yield current
current = chr(ord(current)+1)
for letter in letters_generator():
print(letter) |
4b8cc20be6de87ba7fe8f230245987d79ce8f07d | connortomi/1_1 | /linear_graphing_calculator_g8(SAVED VERS).py | 1,880 | 4 | 4 | #group members: Zach, Connor, Anvit
import turtle as t
#asks the user for equation
s = int(input("Enter an equation in the form y=mx+b: "))
s.split()
t.print(s[6])
t.hideturtle()
#t.setup(1000,500 )
t.title('Rounded Rectangle - Pythont.Academy')
t.speed(0)
t.up()
t.hideturtle()
#creates calculator... |
b791497f05e22202a4dd11607fe634b6bdb7b724 | iamrishap/PythonBits | /InterviewBits/backtracking/permutations.py | 1,168 | 4.09375 | 4 | """
Given a collection of numbers, return all possible permutations.
Example:
[1,2,3] will have the following permutations:
[1,2,3]
[1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
[3,2,1]
NOTE
No two entries in the permutation sequence should be the same.
For the purpose of this problem, assume that all the numbers in the collection a... |
ed0f1635c98ceaa8d594025fe9c8e809a1a80803 | pro-pedropaulo/estudo_python | /executaveis/51_tuplas_tabela_preço.py | 365 | 3.640625 | 4 | listagem = ('Borracha', 2.00,
'Caderno', 7.55,
'Caneta', 1.99,
'Lapiz', 1.10,
'Corretivo', 2.15,)
print('-' *30)
print(f'{"LISTAGEM DE PREÇO":^30}')
print('-' *30)
for c in range(0, len(listagem)):
if c % 2 == 0:
print(f'{listagem[c]:.<30}', end='')
else... |
c3bd8911aada775f6341aeb70f263626bbdb92c3 | Veganveins/LSTM | /rnn.py | 1,952 | 3.8125 | 4 | #Recurrent
# Part 1 Data Pre Processing
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import the training set (only numpy arrays can be the input)
dataset_train = pd.read_csv("Google_Stock_Price_Train.csv")
training_set = dataset_train.iloc[:,1:2]... |
3c418f88218e1b04eb5ed0b89424709f8f068a96 | fdirri/Simbot | /robot.py | 3,257 | 3.59375 | 4 | import numpy as np
salida=[10,10]
derecha=[0.1]
izquierda=[0,-1]
arriba=[1,0]
abajo=[-1,0]
class Laberinto(object):
def __init__(self,largo,alto):
self.largo= largo
self.ancho= ancho
class Obstaculo(object):
def __init__(self,posicion,tipo):
self.posicion=posicion
... |
567a5e84f29fb3d6fcc334a9f9e895a9c967daa2 | ANU197/CodeChef-Beginner | /1.py | 372 | 3.703125 | 4 | # for i in range(int(input("Enter No. Test Cases"))):
# a=input("Enter Year")
# if(a=="2010" ):
# print("HOSTED")
# elif(a=="2015"):
# print("HOSTED")
# elif(a=="2016"):
# print("HOSTED")
# elif(a=="2017"):
# print("HOSTED")
# elif(a=="2019"):
# print("HOS... |
7aeb6a5ae930128fd305ade1f41271a6d5d58b25 | EdwaRen/Competitve-Programming | /Leetcode/75.sort-colors.py | 1,056 | 3.78125 | 4 | class Solution:
def sortColors(self, nums):
"""
Used the Dutch partition solution
Assume everything is a 1 and then swap from there
"""
red = 0
white = 0
blue = len(nums)-1
# Stop when the 1 and 2 meet
while white <= blue:
# swap... |
cb025ebe9656286a7dad9ee21e16551e7c2fe8f7 | minhle2505/WIS_Test | /WIS_Test/8th_question.py | 640 | 4 | 4 | def convert_number(n, b):
if (n < 0 or b < 2 or b > 32):
return "";
sb = "";
m = 0;
remainder = n;
while (remainder > 0):
if (b > 10):
m = remainder % b;
if (m >= 10):
sb = sb + str(chr(55 + m));
else:
... |
a24d6ce65eeee1a62e798dda17fcac22acb72c8f | reema-eilouti/python-problems | /CA12/probelm3.py | 456 | 3.5625 | 4 | # Probelm3
# Write a program that reads the contents of sentences.txt and writes exactly
# the same contents to the file sentences.tmp.
# Then open the file sentences.tmp and display the contents.
filename = "c:/Users/Reema Eilouti/Documents/Python/CA12/sentences.txt"
filename2 = "c:/Users/Reema Eilouti/Documents/... |
a1f6f1e3594a12253a24879804bdf4b90ca9ad20 | EsWees/MA-docs | /utest.py | 624 | 3.59375 | 4 | #!/usr/bin/env python
import unittest
def not_true():
return not True
class NotTrueTest(unittest.TestCase):
""" Test not True and UnitTest """
@classmethod
def setUpClass(cls) -> None:
print("======setUpClass======")
@classmethod
def tearDownClass(cls) -> None:
print("=====... |
dadcdf3c1da0a4b62dfdd80a137bc2b99c73bb7e | nfoppiani/Top-Mass-Measurement-FCC-ee | /utils/CovarianceMatrixFunctions.py | 3,006 | 3.65625 | 4 | import numpy as np
def CombineCovarianceMatrices(covariance_matrix_list):
"""Combine two covariance matrices.
The combination is done assuming that the fit parameters and the covariance
matrices are obtained with a maximum likelihood fit, in the approximation of
a gaussian likelihood (limit of big da... |
6ff77cafe1ca8982878e39f91b7ad1ae70eab79e | dbychkar/python_lessons | /python_coursera/8_week/98_XOR.py | 1,337 | 3.96875 | 4 | """
Булева функция XOR (сложение по модулю два) задаётся следующей таблицей истинности:
xor(0,0)=0
xor(0,1)=1
xor(1,0)=1
xor(1,1)=0
На вход подаются две последовательности (a₁,…,an) и (b₁,…,bn) из 0 и 1.
Вычислите последовательность из (c₁,…,cn), где каждая cᵢ=xor(aᵢ,bᵢ).
Формат ввода
На вход подаются две строки из 0 и... |
c8fc7b3b70be1deac055c8b9f0361054543162f0 | vsego/advent-of-code | /2020/day01.py | 1,525 | 3.703125 | 4 | #!/usr/bin/env python3
"""
Solution for
[Day 1 of Advent of Code 2020](https://adventofcode.com/2020/day/1).
"""
from common import AoCSolution, main
class Day01(AoCSolution):
"""
Solution for
[Day 1 of Advent of Code 2020](https://adventofcode.com/2020/day/1).
"""
tests = [
{
... |
76d75bd8ad6503502edb876c445a16e6e32c6b83 | liaosilzu2007/python-learn | /day01/Generator.py | 698 | 3.5625 | 4 | L = [x * x for x in range(5)]
print(L)
g = (x * x for x in range(5))
print(g)
for i in g:
print(i)
print('====================')
def fib(max):
m, a, b = 0, 0, 1
while m < max:
print(b)
a, b = b, a + b
m = m + 1
return 'done'
print(fib(6))
def fibGenerator(max):
j, a... |
45bbb57f555076a2cfcef65120c2c860ae47f83e | pokhym/guidb | /sqlite3DB.py | 13,849 | 3.703125 | 4 | import sqlite3
import os
DEFAULT_NAME_COLUMN_TYPE = [("staffnumber", "INTEGER PRIMARY KEY", "integer"),\
("fname", "VARCHAR(20)", "text"),\
("lname", "VARCHAR(30)", "text"),\
("gender", "CHAR(1)", "text"),\
("joining", "DATE", "text")
]
class sqlite3DB:
# TODO: The input of columnListType ... |
6848446302419550a6ddda99e20f589b8fb04e6c | hckhilliam/programming | /LeetCode/30DayChallengeApril/30isValidSequence.py | 595 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
return self.walk(root, arr, 0)
... |
b157973618776a822877f2a58b89b94c0a750dd1 | ydv-sahitya/leetcode-python- | /tkinter_learn/第一次.py | 813 | 3.5 | 4 | #-*- coding:utf8 -*-
#author : Lenovo
#date: 2018/10/7
import tkinter as tk
from PIL import Image,ImageTk
class App(object):
def __init__(self,master):
frame=tk.Frame(master) #容器里可以存放tk,TK()对象
frame.pack(side=tk.LEFT,padx=10,pady=10)
self.button=tk.Button(frame,text='你好',bg='white',fg='bl... |
aedcb473286e251253584ad59e0293c0088bb521 | amogchandrashekar/Leetcode | /Medium/Display Table of Food Orders in a Restaurant.py | 2,335 | 4.5 | 4 | """
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically
orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the
table customer sit at, and foodItemi is the item customer orders.
Return the restauran... |
5971476994c44aef19bb9d550187afda409eb223 | santosemax/ROSALIND-Stuff | /Problems/complementingDNA.py | 425 | 4.09375 | 4 | from sys import exit
# Get DNA Strand
dnaStrand = input('Please input your DNA strand here: ')
reversedStrand = dnaStrand[::-1] # Increment throught the string backwards to reverse it (slicing)
for alpha in reversedStrand:
if alpha == 'A':
print('T', end="")
if alpha == 'T':
print('A', end="")... |
72de5baa2580cbc269e471b999f08d3ab04728b4 | LiuXi0314/MPython | /function/BaseFun.py | 2,040 | 4.1875 | 4 | print(abs(1))
print(abs(-2))
print(abs(3.33))
print(abs(False))
# print(abs('str')) error
print(max(1, 2, 3, -2, True))
print(bool("23"))
print(int("23"))
# 定义函数
def myFirstFun():
print("Hello %s" % 'My First Function')
def getMulResults(x=1, y=1):
return x * y
def getDivResults(x=1, y=2):
return in... |
9f26fd7bb6714346e6be1473f2adfa18d78a93cb | RodionLe/homework | /10/10.30/10.30/_10.30.py | 530 | 3.640625 | 4 | def sentence(a):
length = len(a)
x = 0
for i in range(length):
if a[i] == "б" or a[i] == "Б":
x += 1
return (x * 100 ) // (length)
a = input("Введите предложение ")
X = sentence(a)
a = input("Введите предложение ")
Y = sentence(a)
print(X, Y);
if Y < X:
... |
6bf178e3e5902af8106e10375748ad85c392cb4f | kr-Raviraj/Py-Assignments | /OTP.py | 1,194 | 3.65625 | 4 | import random
def opt_match():
fname = input("\nPlease Enter Your First Name:\n")
lname = input("\nPlease Enter Your Last Name:\n")
ran = random.randint(1,5)
# print("Your Otp For Transaction Is = ",ran)
attempts = 4
while True:
try:
x = int(input("\nPlease Enter the number Here:\n")... |
2c6e83613923e4112d34cf678fa74aa8305a0639 | yinkz1990/100daysofcode | /turn_right.py | 470 | 3.96875 | 4 | num = []
n = int(input("Enter the num of item on the list-:"))
for i in range(n):
number = int(input("Enter the number-:"))
num.append(number)
print(num)
d = int(input("Enter the number of rotation-:"))
def rotate(num):
if n >= 1 and n <= 10*5:
if d >= 1 and d <= n:
if len(num) >= 1 and... |
02ae2d25842932a6789d8f546453f1d02497f390 | yamilafuentes/Ejercicios-Python | /claseUno/1.py | 357 | 3.609375 | 4 | # Calcular el sueldo de una persona, conociendo la cantidad de horas que trabaja en el mes y el valor de la hora
horas_trabajo = int(input("Ingrese la cantidad de horas de trabajo en el mes: "))
valor_hora = int(input("Ingrese el valor de 1 hora de trabajo: "))
Sueldo = horas_trabajo * valor_hora
print... |
e266a39f785d16ed4801983d1b34720a681c34c8 | venessaliu1031/Data-structure-and-algorithm | /1. algorithm toolbox/assignments/week2_algorithmic_warmup/my answers/last digit of sum of Fibonacci number.py | 373 | 3.796875 | 4 |
# coding: utf-8
# In[10]:
#last digit of sum of Fibonacci number
a = int(input())
def Fn3(a):
f0 = 0
f1 = 1
if a <= 1: return a
else:
rem = a % 60
if(rem == 0): return 0
for i in range(2, rem + 3):
f =(f0 + f1)% 60
f0 = f1
f1 = f
... |
0f09c23092474d61a535cc702edb60512e3ae683 | yukihuang09/C109156111 | /25.py | 203 | 3.75 | 4 | while True:
a=list(input("輸入字串(end結束):"))
if a[0]=="e"and a[1]=="n" and a[2]=="d":
print("檢測結束")
break
else:b=input("檢測字元:")
print(a.count(b))
|
4ac53695974de7032ffd8604d5aa2a2d74da2b7a | hadeelhhawajreh/data-structures-and-algorithms-c401 | /data_structures_and_algorithms/data_structures/Tree/binary_tree/binary_search_tree.py | 6,263 | 4.125 | 4 | # from stacks_and_queues.stack_queue import Queue
from collections import deque
class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
# op=[]
# breadth=Queue()
# breadth.enqueue(root)
# while breadth.peek():
# self.front=self... |
d9670b2df81a0352acd00b37229fbce41573e688 | JJong-Min/Baekjoon-Online-Judge-Algorithm | /소수판별.py | 280 | 3.671875 | 4 | def is_prime_number(x):
# 2부터 x의 제곱근까지의 모든 수를 확인하며
for i in range(2, int(x**(1/2)) + 1):
# x가 해당 수로 나누어떨어진다면
if x % i == 0:
return False # 소수가 아님
return True # 소수임
|
65df1235c19cf3c402ae19818537530db9c25631 | nkawaller/design_pattern_practice | /observer_pattern/weather_station.py | 2,018 | 3.5625 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from random import randrange
from typing import List
class Subject(ABC):
@abstractmethod
def attach(self, observer: Observer) -> None:
pass
@abstractmethod
def detach(self, observer: Observer) -> None:
pass
@a... |
cae8ce99913fb280b2a9f6fe7f4d7877384b48dd | WondrousSquirrel/Design-patterns | /strategy/strategy.py | 924 | 4.0625 | 4 | '''
Паттерн "Стратегия" позволяет использовать функиональность
в любом классе. Таким образом избегается повторения кода, в параллельных ветках
и сохраняется разное поведение объектов
'''
import abc
class INoiseStrategy(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def noise(self):
'''... |
9a1bd51a21659aae3c9b88f17eb7cd1b3bbe2f76 | kalebm1/Random-Number-Generator-Study | /test.py | 2,122 | 3.734375 | 4 | '''This File is used for testing Randomness in the algorithms
and for plotting the findings of those tests.'''
from Algorithms.RandomMarsenne import Random
from Algorithms.RandomWells import WellsRandom
from Algorithms.RandomBBS import RandomBBS
from Algorithms.RandomBMAlgo import RandomBM
import matplotlib.... |
19d2e987d42249d9d9481a03406e40804c4fb9dd | PC-coding/Exercises | /algorithms/greedy_and_divide_and_conquer/2_binary_search/solution/solution.py | 432 | 3.78125 | 4 | def binary_search_helper(lst, x, low, high):
if high >= low:
mid = (high + low) // 2
if lst[mid] == x:
return mid
elif lst[mid] > x:
return binary_search_helper(lst, x, low, mid - 1)
else:
return binary_search_helper(lst, x, mid + 1, high)
... |
2053e92834bc811822e010c8cab2e090e0ae6b09 | daniel-reich/ubiquitous-fiesta | /aW8mz7Tky3gGiuQsX_0.py | 353 | 3.703125 | 4 |
def is_powerful(n):
def isPrime(n:int) -> bool:
#returns true if input is prime number, false otherwise
#horribly ineffective
return not any([c for c in range(2,n) if n%c==0])
p=[]
mp=[]
for i in range(2,n):
if n%i==0 and isPrime(i):
p.append(i)
if n%(i*i)==0:
#print(i)
... |
e677fedd5320f3354482b120a91af6cdff32ab10 | pengzhefu/Algorithms-in-Python | /binary_search.py | 1,212 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 21:21:11 2019
@author: UPenn-BU-01
"""
######Binary Search######
def binarySearch(alist, item):
first = 0
final = len(alist) -1
found = False
while not found and first <= final: ##这个中止条件一定要记牢!
mid = int((first+final)/2)
if alist[mid] =... |
f89a161e9aee16bac6f7cc900660724433e3df82 | psuong/haiku-generator-ibm | /haiku_generator.py | 946 | 3.515625 | 4 | from sample_database import words
from random import randint
def generate_line(syllable_count):
# TODO: Generate the logic which defines the line in a haiku
pass
def generate_random_lines():
# TODO: Generate the line by randomly selecting words, this should be relatively
# easy to do
haiku = []
... |
7ac3e5a7b1e83cc08430af880dd1c901ea379f66 | crbrodie/dice_rolling | /dice.py | 125 | 3.671875 | 4 | from random import randint as r
dice_size = int(input('pick a dice size: '))
random_num = r(1, dice_size)
print(random_num) |
540d7ab15d71e09084eb51036aafc73800893822 | SsomyaSaxena/PythonCodes | /sumMul.py | 424 | 4.125 | 4 | a=[]
n = int(input("Enter the list size : "))
for i in range(0, n):
print("Enter number at location", i, ":")
item = int(input())
a.append(item)
tot = 1
for x in range(0,n):
tot *= a[x]
print("The multiplied value is:",tot)
#OUTPUT:
#Enter the list size : 3
#Enter number at location 0 :
... |
dbaccb8c48902d4615ec8ab7f681142bc8e142e3 | BrianWaldron97/graph-theory-project | /main.py | 2,403 | 3.734375 | 4 | # Brian Waldron
# G00350150
# Code adapted from Lab exercises
import shunting
import thompson
# os allows for file path manipulation (os.path)
import os
# sys allows for runtime manipulation
#import sys
# User enters directory of txt file
userPath = input("Please enter the directory path: ")
directory = os.listdir(... |
6553b40ab4675ae089fc73a5d1910373312fe0a6 | tnakaicode/jburkardt-python | /combo/pruefer_to_tree.py | 2,917 | 3.640625 | 4 | #! /usr/bin/env python
#
def pruefer_to_tree ( n, p ):
#*****************************************************************************80
#
## PRUEFER_TO_TREE converts a Pruefer code to a tree.
#
# Discussion:
#
# The original code attempts to tack on an extra entry to P.
#
# Licensing:
#
# This code is distribu... |
f48aea974ea79950e4d7acda44a4a435dfa5ddbf | tanpf5/LeetCode_Python | /Merge Sorted Array/Solution.py | 583 | 3.71875 | 4 | __author__ = 'Vigery'
class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
i, j, k = m - 1, n - 1, m + n - 1
while i >= 0 and j >= 0:
... |
cf498ec23ec512642779d916956e2c3daa13ed5a | Sabinu/6.00x | /_final_01/final_04.py | 980 | 4.09375 | 4 | __author__ = 'Sabinu'
def is_it(num, secret):
if num < secret:
return -1
elif num == secret:
return 0
else:
return 1
def is_it_min_5(num):
return is_it(num, -5)
def is_it_pl__1(num):
return is_it(num, 1)
def is_it_pl_10(num):
return is_it(num, 10)
def jumpAndBackp... |
c1a6ccda24ed62d2b4c10c868d10130df5558f5b | yangzongwu/leetcode | /20200215Python-China/0504. Base 7.py | 570 | 4 | 4 | '''
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
'''
class Solution:
def convertToBase7(self, num: int) -> str:
if num==0:
return '0'
flag=... |
8723c9cf2f39a3f2ab25e0cae4053be0e7b06103 | haraGADygyl/SoloLearn | /01. Easy/10. Popsicles.py | 471 | 4.03125 | 4 | """
Determine whether you can give each of your siblings equal number of popsicles.
If not, eat them yourself.
"""
while True:
try:
siblings = int(input("How many siblings do you have? "))
popsicles = int(input("How many popsicles do you have? "))
if siblings % popsicles:
print... |
58a05ad164b1aa3fae5b4dd690a9fda412700ab3 | Guilt-tech/PythonExercices | /Exercices/Secao04/exercicio22.py | 174 | 3.71875 | 4 | print('Digite um comprimento em jardas, que será convertido em metros')
J = float(input('Comprimento: '))
M = 0.91 * J
print(f'O valor em metros é: {M} e em jardas é {J}') |
9889a944f445fa7ed8fe9ab5a4438862d7525dd7 | lmboullosa/morty | /find_tickets.py | 2,623 | 3.65625 | 4 | #!/usr/bin/python2.7
# Please don't just copy the code, lmao.
def find_numbers(string_list):
lottery_numbers = []
for ticket_number in string_list:
if len(ticket_number) >= 7 and len(ticket_number) <= 14:
temp_result = {}
final_result = []
n_double = len(ticket_num... |
7573dbb69a8aedbd81c16a26dfd46fe84322c1fa | xCiaraG/Kattis | /mjehuric.py | 372 | 3.53125 | 4 | numbers = list(map(int, input().strip().split()))
while numbers != sorted(numbers):
i = 0
while i < len(numbers) - 1:
if numbers[i] > numbers[i+1]:
numbers[i], numbers[i+1] = numbers[i+1], numbers[i]
numbers = list(map(str, numbers))
print(" ".join(numbers))
... |
cee4f7910d460808e79da178c672ee6a94d37b37 | mpencegithub/python | /pyds/8_5.py | 358 | 3.71875 | 4 | fhandle=open('mbox-short.txt')
words=list()
count=0
for line in fhandle :
line = line.rstrip()
if line.startswith('From:') : continue
if line.startswith('From') :
words=line.split()
address=words[1]
print(address)
count=count+1
print('There were',count,'lines in th... |
e96b86d3908dd8a07e959aae91bbd4f9c648b9fd | FuongHoa/hoalephuong-fundamentals-C4E22 | /session3/update.py | 265 | 3.640625 | 4 | items = ["Com", "Pho", "Chao"]
print(items[1])
items[1] = "Pho xao"
print(items[1])
print(items)
# x = "Com rang"
# print(x)
# print(items[2])
# print(items)
# x = items[2]
# items[2] = "Com nhao"
# x = "Com trang"
# print(x)
# print(items[2])
# print(items)
|
ade693c700bc31623148805168017994a3d3fbbf | shireeny1/eng-48-naan-factory | /naan_factory_tests.py | 1,431 | 3.84375 | 4 | from naan_factory_functions import *
# Tests go here (for separation of concerns)
# Make test for make_dough
print("testing make_dough with 'water' and 'flour'. Expected --> 'dough'")
print(make_dough('water', 'flour') == 'dough')
print('got:', make_dough('water', 'flour'))
# When I pass in cement and water, or anyt... |
595285d7967efa245ad046058bde3c2bb8f3f9fe | 9618712234/2 | /2.py | 117 | 4.09375 | 4 | num=int(input())
if(num%2==0):
print(" even")
elif(num<=0):
print("invalid")
else:
print("num is odd")
|
c636170d858c912f5aa04786db115e1941bf9079 | YeasinArafatFahad/Python-code | /coursera problem 3.2.py | 174 | 4.09375 | 4 | hours = input("Enter Hours:")
h = float(hours)
Rate = input("Enter the Rate:")
x = float(Rate)
if h <= 40:
print( h * x)
elif h > 40:
print(40* x + (h-40)*1.5*x)
|
088788817a7317cb9701b826cc0970b66949d0ea | NikiDimov/SoftUni-Python-Fundamentals | /exam_preparation_08_21/need_for_speed_III.py | 1,684 | 3.609375 | 4 | n = int(input())
my_cars = {}
TANK_CAPACITY = 75
for _ in range(n):
car_data = input().split("|")
car, mileage, fuel = car_data[0], int(car_data[1]), int(car_data[2])
my_cars[car] = [mileage, fuel]
command = input()
while not command == "Stop":
data = command.split(" : ")
if data[0] == "Drive":
... |
f277adc061a30de951644b81fbf28a112972fc09 | bigdata202005/PythonProject | /Turtle/Ex027.py | 670 | 3.890625 | 4 | import turtle
import math
def make_window(colr, ttle):
w = turtle.Screen()
w.bgcolor(colr)
w.title(ttle)
return w
def make_turtle(colr, sz):
t = turtle.Turtle()
t.color(colr)
t.pensize(sz)
return t
def draw_rectangle(t, w, h):
for i in range(2):
t.forward(w)
t.left... |
800e922a5bed1715b13fe7b42fa9f64da13e221a | tema-art/python-base | /lesson_1/task1.py | 941 | 4.0625 | 4 | # ЗАДАНИЕ 1
# Человеко-ориентированное представление интервала времени
# Спросить у пользователя размер интервала (в секундах). Вывести на экран строку в зависимости от размера интервала:
# 1) до минуты: <s> сек;
# 2) до часа: <m> мин <s> сек;
# 3) до суток: <h> час <m> мин <s> сек;
# 4) сутки или больше: <d> дн <h> ... |
d0949f20b85283ed7e4132b26eb1780034e79a29 | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/LC543.py | 1,055 | 3.703125 | 4 | # O(n)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution(object):
def diameterOfBinaryTree(self, root):
depth... |
7a0929990ba27d6906d7082fe71aae2fabd5b4c9 | theGreenJedi/Path | /Python Books/Athena/training/exercises/exercises/scipy/stats_functions/stats_functions_solution.py | 3,092 | 3.890625 | 4 | from __future__ import print_function
"""
1. Import stats from scipy, and look at its docstring to see
what is available in the stats module::
In [1]: from scipy import stats
In [2]: stats?
2. Look at the docstring for the normal distribution::
In [3]: stats.norm?
You'll notice it has th... |
0b9b70c39bf8a8f0218f77917f9a4a06b74bd14f | tinagoetschi/DiceRollCode | /dice roll william.py | 476 | 3.9375 | 4 | import random
def roll (sides=6):
numberrolled = random.randint (1,sides)
return numberrolled
def main():
faces = 6
rolling = true
while rolling:
rolldiceagain = input('roll dice again? ENTER = roll. Q=Quit?')
if rolldiceagain.lower() != 'q':
numberrolled = ... |
9fc8a8c25e06042000a860081f2ef4df920e5a82 | yufeialex/all_python | /mofan/numpy&pandas/11_pandas_intro.py | 1,137 | 3.515625 | 4 | # View more python tutorials on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.... |
768e78c8e4704fd001e72ece91750ac2b1fd9c78 | ukrduino/PythonElementary | /Lesson02/Exercise2_5.py | 3,414 | 4 | 4 | # -*- coding: utf-8 -*-
# Write a function that computes a large factorial using multiple threads
import threading
from Queue import Queue
from operator import mul
from Lesson02.Exercise2_4 import factorial_l
from Lesson02.Exercise2_4 import wrapped_with_timer
# @wrapped_with_timer
def multiply_numbers_in_chunk(chun... |
0e6660f48e6ecb55262e6333d203d645c768696f | JakobLybarger/Weather-App | /Weather.py | 4,376 | 3.5 | 4 | # Python program to find current weather
import requests
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import Screen
def get_weather(find_city):
# get nam... |
c088ba853bda409eccdff1425609460613186059 | Titchy15/HackerRankPython | /PhthonIfElse.py | 177 | 3.90625 | 4 | n = int(input())
if n % 2 == 1 or (n % 2 == 0 and 6 <= n <= 20):
print("Weird")
elif (n % 2 == 0 and 2 <= n <= 5) or (n % 2 == 0 and n >= 20):
print("Not Weird")
|
1aeb96c6e0f1d2ef511c8bcb5b98bb3e4ae825b9 | Werifun/leetcode | /array/56. 合并区间.py | 1,603 | 3.96875 | 4 | '''
给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[i... |
03942554c70af838da6b615478103e861d0b4a93 | DenisWilsonDev/Courses | /Data_Structures_and_Algorithms_in_Python/05_03_BST_Practice.py | 1,478 | 4.03125 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
cur_node = self.root
while True:
if new_val < cur_... |
09a0a0bbc6384e590264b86826e53f8f7b68a6b3 | Elizaveta239/AdventOfCode2020 | /day8.py | 2,096 | 3.640625 | 4 | from typing import Tuple, List
def read_data(filename: str):
with open(f"input/{filename}") as f:
lines = f.readlines()
commands = list()
for com in lines:
items = com.split(" ")
commands.append((items[0], int(items[1])))
return commands
def acc_before_loo... |
b0d68c1adbcddc3ab563cc32eae38f98bb370046 | cuixd/PythonStudy | /6.函数.装饰器.偏函数.异常与文件读取/function.py | 104 | 3.59375 | 4 | def getMax(a, b):
if a > b:
return a
else:
return b
a = getMax(4,7)
print(a)
|
a0f6aecbec63e159e084297cb0bd68f02de0065a | Keitling/algorithms | /python/Nim/Nim21/Nim21.py | 5,540 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Nim 21 game and machine players.
"""
import random
# ===============
# The Game Class
# ===============
class Nim21:
"""
Nim 21 game.
"""
def __init__(self, player1, player2, heaps=21):
self._heaps = heaps
self._player1 = player1
self._player2 = pl... |
d9639c7931d1aeb18f26f9312ee6dfd9d3f29dcd | efeu1133/Python | /calendar.py | 273 | 3.625 | 4 | def leapyear(year):
def AmountDaysPerMonth(month, year):
def nextDate(date):
# initialization
starting_date = (1,15,2012)
end_date = (4,16,2015)
# process
# print
print("starting date:", starting_date)
print("end date:", end_date)
print("amount of days:", amount_days)
|
1ae95669844ae70dd1d49a2c6c28ee0fc0e5d27d | akpinar/Pyhton-Algorithm-Practices | /ornek79.py | 238 | 3.65625 | 4 |
#1’den 10’a kadar olan tamsayılar için bir çarpım tablosu hazırlayan bir program yazınız.
carpim = int()
for i in range(1,11):
for j in range(1,11):
#carpim = i * j
print("{} x {} = {}".format(i,j,(i*j))) |
2115c2e33906ae8758a6d7813d32a29664eb3100 | RaghuA06/ChatBox-Application | /client.py | 730 | 3.53125 | 4 | #Raghu Alluri
#May 2021
import socket
import sys
import time
socket_server = socket.socket()
server_host = socket.gethostname()
ip = socket.gethostbyname(server_host)
sport = 8000
print("This is your IP address:{}".format(ip))
server_host = input("Enter server's IP address:")
name = input("Enter your ... |
a264cab76692bd07038d031b3b1855ff18e35f4c | younglilyhe/pythonBase | /hl_01_base/hl_06_string.py | 138 | 3.5625 | 4 | num_str = "0123456789"
print(num_str[2:6])
print(num_str[2:])
print(num_str[:6])
print(num_str[:])
print(len(num_str))
print(max(num_str)) |
64f813d1f574ab516c4951b8a476145df73b38c8 | v-cardona/CompeticionProgramacion | /Carmichael/eratostenes.py | 261 | 3.5 | 4 | primos = [-1]*20
def eratosthenes(n):
multiples = []
for i in range(2, n+1):
if i not in multiples:
primos[i] = i
for j in range(i*i, n+1, i):
multiples.append(j)
return primos
print(eratosthenes(20)) |
1dcffcec4794af97da881543f56e859c9f1ed25c | clivejan/python_object_oriented | /basic/object_attributes.py | 271 | 3.640625 | 4 | # Define a class
class Point:
pass
# Instantiate objects from the defined class
p1 = Point()
p2 = Point()
# setting arbitrary attributes on instantiated objects
p1.x = 5
p1.y = 4
p2.y = 3
p2.y = 6
# accseeing the attribute values
print(p1.x, p1.y)
print(p2.y, p2.y)
|
50bcb61c949430771521264a538cd95794a1ae9c | balaji-senthil/program1_part1 | /project1_funs.py | 3,301 | 3.671875 | 4 | '''
Programming Assignment 1 - Part1
Submitted by Balaji Senthilkumar
'''
#The funtion to load the board (.txt to 2Dlist/array)
def loadBoard(board):
inputFile = open(board, 'r')
myBoard = []
for row in inputFile:
myBoard.append(row.split())
return myBoard
#THE FUNCTION TO PRINT 'myBoa... |
db5896ecf8b678202021c781bf2a7561c5af9215 | ShellySrivastava/Machine-Learning | /ML_CW1/assgn_1_part_1/3_regularized_linear_regression/gradient_descent.py | 3,931 | 3.9375 | 4 | import numpy as np
from compute_cost import *
from compute_cost_regularised import *
from plot_hypothesis import *
from plot_sampled_points import *
from plot_cost import *
from calculate_hypothesis import *
def gradient_descent(X, y, theta, alpha, iterations, l, do_plot):
"""
:param X : 2D arra... |
7fccfb6cae960f00dcd29dd06f73aede8c373c37 | lybtt/python_notes | /itertools_note/permutations_notes.py | 239 | 3.53125 | 4 | # coding:utf-8
# author: 'lyb'
# Date:2018/8/24 20:38
from itertools import permutations
# 获得列表所有的排列方式
colors = ['red', 'blue', 'black']
for random_colors in permutations(colors):
print(random_colors)
|
670db95c212774abb8923da93f20290c75b49aa6 | nischalshrestha/automatic_wat_discovery | /Notebooks/py/mrblond89/titanic-eda-data-cleaning-and-initial-modelling/titanic-eda-data-cleaning-and-initial-modelling.py | 22,696 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Titanic Dataset
# A classification task, predict whether or not passengers in the test set survived. I started learning to code about 12 months ago in my spare time and thanks to some friends have become interested in data science, this is my first data science project
# ## I... |
03a4febf7fa754104c55afd0319a00bf1a623174 | naffi192123/Python_Programming_CDAC | /Day1/16-evenodd.py | 132 | 4.25 | 4 | #check the number is even or odd
n = int(input("Enter number of natural numbers: "))
if n%2 == 0:
print("Even")
else:
print("Odd") |
3f62e3333c20a40413ad1a166357c2686a8da89c | Hyperdraw/FridayClub | /games/spacetrails.py | 23,106 | 3.5 | 4 | from time import sleep
import random
from os import system, name
import urllib.request
import json
item = []
money = 0
print('''
_____ ____ ____ __ ___ ______ ____ ____ ____ _
/ ___/| \ / | / ] / _] | || \ / || || |
( \_ | o ) o | / / / [_ | ... |
7da5b4322a7d6d42a151d5c5ec225158da4f5a6c | anne75/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 395 | 3.703125 | 4 | #!/usr/bin/python3
import json
"""
This is module 8-load_from_json.
This module contains one function.
"""
def load_from_json_file(filename):
"""
Creates a python object from a text file
Arguments:
filename: path to file
Returns:
a python object - no error checking
"""
with op... |
71a97453efc231c269573debd2e9beddb9e54f0a | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/bdhsan003/question2.py | 456 | 4.25 | 4 | #Sandisha Budhal
#BDHSAN003
# a function to count the number of pairs
def pairs (strngs):
if len(strngs)==1:
return 0
elif len(strngs)==2:
if strngs[0]==strngs[1]:
return 1
else:
return 0
elif strngs[0] == strngs[1]:
return 1 +pairs(strngs[2:])
el... |
49e93d655ab54cdd24aaab2322a81e50bb4dedf3 | aniket435/pythonprog | /fact.py | 116 | 4.0625 | 4 | num=input('enter the number')
factorial=1
for i in range(1,num + 1):
factorial = factorial*i
print(factorial) |
152dfbb289ab2d9d2420e8dc29402d6cb08e3949 | OShine/Examples | /TestQa/intOrNot.py | 516 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# python 3.5
while True:
try:
x = int(input("Enter the number for check: "))
except ValueError:
print('The entered value should be an integer. Please, try again.')
else:
if x < 0:
x = 0
print('The negative one, val... |
7261ac7450fd50e680def587c5f6476dda77c05c | nidhisd/learn_python_with_nidhi | /tests/test_function_annotations.py | 1,460 | 4.1875 | 4 | """ Function Annotations.
see: @https://www.python.org/dev/peps/pep-3107/#fundamentals-of-function-annotations
Function annotations are arbitrary python expressions that are associated
with various part of functions. These expressions are evaluated at compile
time and have no life in python’s runtime ... |
83bc43e8dadad6c5a16e10675d1c982c07576b12 | subsetpark/posical | /posical.py | 19,607 | 3.890625 | 4 | #! usr/bin/env python #
# -*- coding: utf-8 -*-
"""
Posical is a Python 3 module that models a generalized calendar reform with regularly-sized weeks and months and an intercalary period, based on August Comte's Positivist Calendar.
"""
import datetime,operator
from calendar import isleap as std_isleap
from nonzero i... |
116c5e2fc6f41a47917324626f7e0bee9194d7f7 | yanglan201766/learning_python2 | /Week3/Week3_课后练习.py | 1,273 | 3.984375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[72]:
#生成并打印2020年的日历
month = ['January','February','March','April','May','June','July','August','September','October','November','December']
big_month = [1,3,5,7,8,10,12]
small_month = [4,6,9,11]
def curse(m):
if m in [1,4,7]:
return 3
elif m in [2,8]:
... |
5b6f0da8dd3c1bb0a37700e7e1a408fb0762f834 | stephaniesmith/python-playground | /CollectionModules/counter.py | 365 | 3.515625 | 4 | from collections import Counter
l = [1, 1, 1, 1, 12, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
count_l = Counter(l)
print(count_l)
s = 'lskdjfasdlfksj'
count_s = Counter(s)
print(count_s)
w = 'Hello how are you? you?'.split()
count_w = Counter(w)
print(count_w)
common_w = count_w.most_common()
print(common_w)
comm... |
a2ea2b0e67fb63a47b17e8868c3ad5c9c9e09c2d | tree330/algorithm-practice | /8393.py | 82 | 3.625 | 4 | # a=input()
# add=0
# for i in range(1,int(a)+1):
# add=add+i
# print(add) |
9bb99aa4aff5f0f80fff4f76471062c7fed776c4 | thuongnht/Python3 | /exercises/e12.py | 472 | 3.5 | 4 | from sys import argv
from os.path import exists
script, fromFile = argv
def printAll(f):
print(f.read())
def rewind(f):
f.seek(0)
def printLine(l, f):
print('Line %r' %l, f.readline())
current = open(fromFile)
while (True):
what = input('like \(all=a, rewind=r, line=l\) >')
if (what == 'e'):
break
elif ... |
96373074edd6f2fa5e823acce95210246067da72 | ncturoger/LeetCodePractice | /Dynamic_Programming/Climbing_Stairs.py | 508 | 3.59375 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
step = 0
for i in range(0, n+1):
if (n-i) % 2 == 0:
y = int((n-i) / 2)
step += int(self.stage(i+y) / (self.stage(i) * self.stage(y)))
... |
735a7c00270bc661b398655ed58e13b0892166ca | Sarkar-Physics/Python | /air_drag_2.py | 1,334 | 3.75 | 4 | # freefall when drag force is proportional to v^2 with initial velocity 0 #
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
import math
plot_t=[]
plot_v=[]
def euler(f,v0,t0,tf,h):
t,v=t0,v0
while t<=tf:
plot_t.append(t)
plot_v.append(v)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.