blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
fdd1cec8b3dea5572cb57eb5bf417a11d815156c | tjhlp/personal_exe | /ex_/ex_2.py | 3,349 | 3.890625 | 4 | """
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
... |
30f6bebe6709f7e1fbe68e21e99cf77a39dc1f5e | qianzach/math-164-optimization | /qian_zachary_hw_2.py | 3,732 | 3.640625 | 4 | # Script for Homework 2 Algorithms
#importing libraries
import math
import matplotlib
#6a:
#NOTE: My plot was done on matlab, and the script is as commented:
#x = linspace(0,10,200);
#y = 8*exp(1-x) + 7*log(x);
#plot(x,y)
#xlim([1 2])
#ylim([7.5 8])
#6b and 6c:
#define f(x)
def f(x):
# function f(x) definitio... |
20f4c2974e5516f24ffbe7096e3fcfb00fb802cc | Prashanith/DSA-CP | /DSA/Searching/linear_search.py | 385 | 3.90625 | 4 | # Linear Search
# Time Complexity
# Worst Case Time Complexity - O(n)
# Average Case Time Complexity - O(n)
# Best Case Time Complexity - O(1)
arr = [1,5,6,7,8,9,10,11]
target = 10
def linear_search(arr,target):
if(len(arr)==0):
return -1
for i in range(0,len(arr)):
if(arr[i] == target):
... |
982054663a885ecdbcfec15fc1b4e00b5bb4ca48 | TSTCCloud/ITSE-1329-Python | /CC5/CC5-Ex07/code.py | 106 | 3.578125 | 4 | def sum_three(nums):
total = 0
for _____ in _____:
_____ = _____ + _____
return total
|
4d175fb615c36070be6f12c27cd8a0653401751d | chiahan/movie_trailer_website | /imdb.py | 1,511 | 3.828125 | 4 | import urllib
import json
"""
This module provides methods to get the imdb information for movies.
"""
def get_rating(movie_title, movie_year):
"""
Get the imdb rating for the movie
Parameters
----------
movie_title : string
The title of the movie
movie_year : string
The year... |
a4170ad073ce91333da568ad066ed694d98b4170 | farroyo-ucr/ci0117 | /practicas/Semana-06/DiningPhilo/Python/DinningPh.py | 3,060 | 3.796875 | 4 | import threading
import sys
import time
"""
States represent the philosopher state in any moment
"""
class States:
Thinking, Hungry, Eating = range( 0, 3 )
"""
Represents the Silberschatz solution using a monitor
We use a lock to allow only one thead running in all 'public' (PickUp, and PutDown) metho... |
570238d89940867eae69aa1661992e30a7390760 | Parkash067/Python | /practiceCode/Lecture-9-4-2017.py | 1,929 | 3.625 | 4 | #print numbers which are divisble by 7 and 13
# for num in range(1,100):
# if num%7==0 and num%13==0:
# print(num)
# sentence = "The brown fox jumps quickly over the lazy dog"
# words = sentence.lower().split(' ')
# count = {}
# for w in words:
# if w in count:
# count[w] += 1
# else:
# ... |
8b0a24438ff1310343cf8e365bfd4f96a1dbfaf8 | Parkash067/Python | /practiceCode/session#2_dictionaries.py | 2,333 | 4.09375 | 4 | #Step#1
# carDetails = {"name":"Civic","model":2016,"color":"Black"}
# print (carDetails)
# print (carDetails["name"])
# print (carDetails.keys())
# print (carDetails.values())
# print (carDetails.items())
#Step#2
# personInfo = {"Name":"Parkash Kumar","age":25,"city":"Karachi"}
# print (personInfo["Name"]+"\n"+str(p... |
9fec3121a3af588884bf38bc77cafe6d41a22513 | Israel1Nicolau/Python | /opArit002.py | 421 | 3.953125 | 4 | n1 = int(input('Primeira nota: '))
n2 = int(input('Segunda nota: '))
m = (n1+n2)/2
print('A nota 1 do aluno foi: {}\nA nota 2 foi: {}\ne a média é: {:.0f}'.format(n1, n2, m))
print('======================================')
metro = float(input('Quantos metros para conversão? '))
centi = metro*100;
mili = me... |
032c6c754294eb94941d5d9464343283a6324c38 | Israel1Nicolau/Python | /opArit001.py | 268 | 3.953125 | 4 | n = int(input('Digite um número: '))
n1 = n-1
n2 = n+1
print('O número digitado: {}\nseu antecessor: {}, seu sucessor: {}'.format(n, n1, n2))
n3 = n*2
n4 = n*3
n5 = n**(1/2)
print('O dobro do número: {}, O triplo {}, a raiz: {:.0f}'.format(n3, n4, n5)) |
f257c04116334c1a701cc28aa5b6b15485eea10a | Israel1Nicolau/Python | /condAninhadas000.py | 356 | 4.25 | 4 | nome = str(input('Digite seu nome: ')).strip().capitalize()
if nome == 'Israel':
print('Que nome bonito!')
elif nome == 'Pedro' or nome == 'Maria' or nome == 'Paulo':
print('Nome bastante comum')
elif nome in 'Ana Juliana Elisabeth Joana':
print('Belo nome feminino')
'''else:
print('Nome norma... |
844a8dfc101140dd522d2d59aee50ed6ddcbb028 | Israel1Nicolau/Python | /manipulaStrings000.py | 992 | 4.0625 | 4 | frase = ' Rafa é um lixo, de fato ele é '
print(frase[0:4])
print(frase[0:8:2])
print(frase[:10])
print(frase[15:])
print(frase[10::2])
print(len(frase)) #tamanho da frase
print(frase.count('e'), frase.count('é')) #quantas vezes aparece
print(frase.count('0', 0, 14))
print(frase.find('fat')) #indica a PR... |
cfdebb80a07830867cb49177b200d40949dffec3 | Israel1Nicolau/Python | /modulos003.py | 301 | 3.828125 | 4 | from math import hypot
co = float(input('O comprimento do cateto oposto: '))
ca = float(input('O comprimento do cateto adjacente: '))
'''hi = (co**2+ca**2)**(1/2)
print('A hipotenusa vai medir {:.2f}'.format(hi))'''
hi = hypot(co, ca)
print('O valor da hipotenusa {:.2f}'.format(hi))
|
cc99fdc147a479b929cbd0f35a577d8a82a40c33 | MoCuishle28/fisher-FlaskPractice | /app/libs/helper.py | 584 | 3.859375 | 4 |
def is_isbn_or_key(word):
"""
判断是isbn还是关键字
"""
# isbn: isbn13 13个0-9的数字组成
# isbn10 10个0-9的数字组成 含有一些'-'
# 默认传过来的参数是关键字
isbn_or_key = 'key'
# q.isdigit()判断q是否全是数字
if len(word) == 13 and word.isdigit():
isbn_or_key = 'isbn'
# 先判断是否有'-' 然后去掉'-'(q.replace('-',''))再判断是否全长度为10且剩下的是数字
short_word = word.repla... |
7a95542a602e3df30e3b16aa15b0ada47e0cdb5d | Mitul-Joby/Unknown-Variable-Calculator | /main.py | 8,129 | 3.84375 | 4 | '''
This is a python program of a graphical Calculator made using Tkinter.
It operates with the help of MyMath.py module to calculate areas, volumes, csa, tsa of different shapes.
'''
import MyMath
from os import path
from tkinter import Tk,Text,BOTH,END,Menu,StringVar,Label,W,E,N,S,Entry,Button,ttk
def note... |
8a99a85a0cb95bb61619ccdb7ed022b29c36aef1 | jizwang/pythonOOP | /OOP/魔法函数.py | 1,197 | 4.125 | 4 | # # __call__举例
# class A():
# # def __init__(self):
# # print("哈哈")
# def __call__(self):#对象当函数使用的时候触发
# print("我被调用了")
# # def __str__(self):#当对象被当做字符串使用的时候可以触发这个函数
# # return "图灵学院"
# def __repr__(self):
# return "图灵"
# a = A()
# a
# # print(a)
#__getattr__
# class A()... |
2ad077c4c9e4f8b34c2d7feba449e92b9a03bc10 | georgelzh/Text-Spell-Checker | /spell_checker.py | 3,355 | 4.03125 | 4 | #!Python 3
# Spelling Checker
# It receives the letters of a word and automatically corrects it.
# Zhihong Li
# 5/26/2019
#
import sys, re
inFile = sys.argv[1] # dictionary path
textFile = sys.argv[2] # textFile path
outputFile = sys.argv[3] # output path
class Node(object): # create a node... |
6f99b9509fa696853a8fbc5e674e72c0f072e73e | edumaximo2007/Mundo1 | /Desafio19.py | 655 | 3.546875 | 4 | from random import choice
print('-=-'*10)
print('''\033[7m DESAFIO 19 \033[m''')
print('-=-'*10)
print('\033[1mUm professor quer sorte um dos seus quatro alunos para apagar o quadro.\033[m')
print('\033[1mFaça um programa que a ajude ele, lendo o nome deles e escrevendo o nome escolhido.\033[m')
... |
4427b69fc934931e42e472abcf6a2cae6fac135e | edumaximo2007/Mundo1 | /Desafio17.py | 521 | 3.875 | 4 | from math import hypot
print('-=-'*10)
print('''\033[7m DESAFIO 17 \033[m''')
print('-=-'*10)
print('')
print('\033[1mFaça um programa que leia o comprimento oposto e do cateto adjacente de um triangulo \nretângulo, calcule e mostre o comprimento da hipotenusa\033[m')
print('')
co = float(input... |
1d8564875ea5fd1586409783b1d0183dd384dec3 | edumaximo2007/Mundo1 | /Desafio30.py | 397 | 3.9375 | 4 | print('-=-'*10)
print('''\033[7m DESAFIO 30 \033[m''')
print('-=-'*10)
print('''\033[1mCrie um programa que leia um número inteiro e
mostre na tela se ela é PAR ou ímpar.\033[m''')
print('-=-'*20)
print('')
n = int(input('Digite um número: '))
n1 = n % 2
if n1 == 0:
print('O número {} e... |
01a24ae55c6319c043829e890631432e04c0acec | edumaximo2007/Mundo1 | /Desafio23.py | 840 | 4.0625 | 4 | print('-=-'*10)
print('''\033[7m DESAFIO 23 \033[m''')
print('-=-'*10)
print('')
print('''\033[1mFaça um programa que leia um número de 0 a 9999 e mostre na tela cada um digitos separados.
EX:
Digite um número: 1834
Unidade: 4
Dezena: 3
Centena: 8
Milhar: 1\033[m''')
print('')
p1 = str(inp... |
ae75d3454e3cb5f8bba0f4c01c40fd0afbcdb50b | TaeCV/Chess | /ChessMain.py | 12,838 | 3.6875 | 4 | """
This file will be responsiple for user's input and displaying the board
"""
import os
import pygame as pg
import ChessEngine
Width = Height = 512
FPS = 15
Dimention = 8 # the chess board is 8x8
SQ_size = Height//Dimention
Images = {}
# Initialize a global dictionary images.
def LoadImages():
pieces = ["bR... |
bc28f59260ef3170c6a58ae2a2c4d4282835c3f4 | Itapirema/python-practice | /ex017.py | 279 | 3.859375 | 4 | import math
co = float(input('Digite o comprimento do cateto oposto: '))
ca = float(input('Digite o comprimento do cateto adjacente: '))
hi = (co ** 2 + ca ** 2) ** (1/2)
print('A hipotetuna vai medir {}'.format(hi))
print('A hipotetuna vai medir {}'.format(math.hypot(co, ca)))
|
03b0bbb1c60d50e76976e40dc1fd97e4e427a928 | Itapirema/python-practice | /ex025.py | 131 | 3.890625 | 4 | nome = str(input('Digite um nome: ')).strip()
# print(nome.upper().count('SILVA') > 0)
print('{}'.format('silva' in nome.lower()))
|
30bde3b2c463325b2340fa4dadb8d1d6fe462454 | quinneerste/B8IT105 | /CA3/Calc_Def.py | 1,893 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 8 13:40:47 2020
@author: quinn
"""
from functools import reduce
class function_calculator():
def __init__(self):
self.x = []
self.y = []
def set_x(self,x):
self.x =x
def set_y(self,y):
self.y =y
... |
01ded1e364228bee542d4d4fe2d71a5993c7b1ae | sunstat/icml-workshop | /lime_tabular_8_features/decision_tree_label.py | 2,223 | 3.609375 | 4 | class Node:
def __init__(self, index, value, left = None, right = None, label = None):
self.index = index
self.value = value
self.left = left
self.right = right
self.label = label
class DecisionTree(object):
def __init__(self, decision_rules):
... |
cd78b4c7f66dc4be1ea2b1f84e523cb07453ce96 | shruti-sureshan/Python-course-projects | /sum of digits.py | 139 | 3.859375 | 4 | n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
|
e775477b22538a9af3291711c2731d3035129af4 | shruti-sureshan/Python-course-projects | /armstrong.py | 248 | 3.9375 | 4 | num =int(input('enter a no\n'))
sum = 0
temp = num
while (temp > 0):
digit = temp % 10
sum += digit ** 3
temp=temp//10
if (num == sum):
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
|
f76d2035e06031ed1bdf2be5a1ee438c6628a3fc | hepteract/misc | /Chef/ironchef-read-only/trunk/resources/tense.py | 653 | 3.78125 | 4 | def get_past_tense(s):
class detensor:
def __init__(self):
print "hey"
def _t_y(self, word):
return word[:-1] + "ies"
def _t_e(self, word):
return word + "d"
def _t_n(self, word):
return word + "ned"
def _t_ch(self, word):
return word + "ed"
def _t_x(self, word):
return word +... |
2c1d0b344d25d4d2d93924933935fa147d61d0e3 | wycg1984/TensorFlowStudy | /class2/p5_RandomState.py | 324 | 3.609375 | 4 | import numpy as np
# np.random.RandomState。rand() 返回一个【0,1)之间的随机数
# np.random.RandomState。rand(维度) 维度为空 返回标量
rdm = np.random.RandomState(seed=1)
a = rdm.rand() #返回一个随机标量
b = rdm.rand(2, 3) #返回维度为2行3列随机数矩阵
print("a:", a)
print("b:", b)
|
b2e3ffc28ce862b81494771468fd489f43d583e8 | niharvaidya0212/Movie-Tickets-booking | /main.py | 4,096 | 3.796875 | 4 | class BookTicket:
def __init__(self):
print("Enter the number of rows:")
self.rows=int(input())
print("Enter the number of seats in each row:")
self.seats=int(input())
self.l=[]
self.userlist=[]
self.currentincome=0
self.noticketpurchased=0
... |
df48c554b84ea63a10cf9a7615b7d73d1a39f57c | reyanshsurabhi/pythonassignment | /Revers Number_ans1.py | 182 | 3.9375 | 4 | num = input("Enter number:")
print(num)
reverse_number = 0
length = len(num)-1
for i in range(len(num)):
reverse_number = reverse_number*10+int(num[length-i])
print(reverse_number) |
0e946e0525483d49f393f655efbb3d71411c34f4 | prajwollamichhane11/CDAYS | /CODES/makingAnagrams.py | 425 | 3.640625 | 4 | def intersection(set1, set2, la, lb):
st1 = {}
st2 = {}
for i in range(la):
st1[i] = set1[i]
for i in range(lb):
st2[i] = set2[i]
return (st1 & st2)
if __name__ == '__main__':
a = input()
b = input()
la = len(a)
lb = len(b)
L = intersection(list(a), list(b)... |
b58e388a11a73b88499b4926202895334c9bf241 | vighnesh153/ds-algo | /src/arrays/combination-sum.py | 580 | 3.59375 | 4 | def recursion(arr, target, index, solutions, current):
if target == 0:
solutions.append(current[:])
return
if target < 0 or index >= len(arr):
return
recursion(arr, target - arr[index], index, solutions, current + [arr[index]])
recursion(arr, target, index + 1, solutions, curre... |
a01cc60cb309b530bbf2f185f13117706c2494f5 | vighnesh153/ds-algo | /src/arrays/word-search.py | 1,089 | 3.734375 | 4 | def recursion(board, i, j, word, index, indices):
if index >= len(word):
return True
if not (0 <= i < len(board)) or not (0 <= j < len(board[0])):
return False
if (i, j) in indices:
return False
if board[i][j] == word[index]:
indices.add((i, j))
if recursion(b... |
d6075723f56660e6cf4a7c5cfe6915d8ab86ae1d | vighnesh153/ds-algo | /src/arrays/unique-paths-2.py | 574 | 3.53125 | 4 | def solve(matrix):
rows = len(matrix)
cols = len(matrix[0])
if rows == 0 or matrix[0][0] == 1:
return 0
result = [[0 for _ in range(cols)] for __ in range(rows)]
result[0][0] = 1
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 1:
cont... |
849b4cf1853d0d8a3d0bcdb24c46a7671798949d | vighnesh153/ds-algo | /src/arrays/non-decreasing-array.py | 417 | 3.765625 | 4 | def is_sorted(_array):
for i in range(len(_array) - 1):
if _array[i] > _array[i + 1]:
return False
return True
def solve(arr):
arr1, arr2 = arr[:], arr[:]
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
arr1[i] = arr[i + 1]
arr2[i + 1] = arr[i]... |
921a731040c63950672c7fa6d1bfb4e5db725b5f | vighnesh153/ds-algo | /src/arrays/find-the duplicate number.py | 525 | 3.828125 | 4 | # it is like finding a cycle in a linked list
def solve(arr):
slow = arr[0]
fast = arr[arr[0]]
while slow != fast:
slow = arr[slow]
fast = arr[arr[fast]]
length_of_cycle = 1
slow = arr[slow]
while slow != fast:
length_of_cycle += 1
slow = arr[slow]
slow = f... |
2b667d96df5424c1e4da6fc11740079827c0628e | vighnesh153/ds-algo | /src/arrays/set-matrix-zeroes.py | 1,046 | 3.65625 | 4 | def solve(matrix):
r_count = len(matrix)
c_count = len(matrix[0])
is_first_row_zero = False
for elem in matrix[0]:
if elem == 0:
is_first_row_zero = True
is_first_col_zero = False
for i in range(r_count):
if matrix[i][0] == 0:
is_first_col_zero = True
... |
e551d61657a05b87b0ed1e57566d8207dc646779 | vighnesh153/ds-algo | /src/arrays/next-permutation.py | 716 | 3.640625 | 4 | def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
def solve(arr):
last_index = len(arr) - 1
while last_index >= 1 and arr[last_index] <= arr[last_index - 1]:
last_index -= 1
if last_index == ... |
16f92900d4f3c03613d6501cdbd229d17060a7da | Mauc1201/Python | /data_structures/7_tuplas.py | 725 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# ------------- Tuplas -------------
# Declaración de una tupla
diasDelMes = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
#diasDelMes = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 #Otra forma de declarar una tupla
print (diasDelMes)
print ("Enero: " + str(diasDelMes[0]))
print ("Junio: ... |
538e82a8b0645c471baa1e3712da0222c0476789 | Mauc1201/Python | /basics/01_expresiones.py | 426 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# --------------- Uso de expresiones matemáticas ---------------
# La funcion print sirve para imprimir valores en la pantalla
# NOTA: La funcion print en python 3 debe utilizar paréntesis,
# en python 2 se usa sin paréntesis.
print (1 + 5)
print (6 * 3)
print (10 - 4)
print (100 / 50)
print ... |
fe1469b0a5e4c70f8d84cd90b0be4ba080b36c59 | Mauc1201/Python | /graphing/11_bar_3D.py | 511 | 3.609375 | 4 | # -*- coding=utf8 -*-
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
# The coordinates of the anchor point of the bars.
x = np.arange(1,11)
y = np.arange(1,11)
z = np.zeros(10)
print(z)
# The width, depth, an... |
e696456b8972555a2f81797b8cc2b621f17c640c | Mauc1201/Python | /basics/08_comparaciones.py | 346 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# ------------- Comparaciones -------------
print (7 < 5) # Falso
print (7 > 5) # Verdadero
print ((11 * 3) + 2 == 36 - 1) # Verdadero
print ((11 * 3) + 2 >= 36) # Falso
print ("curso" != "CuRsO") # Verdadero
print (5 and 4) #Operacion en binario
print (5 or 4)
print (not(4 > 3))
p... |
4cebb2aedddc8fbff32ec458168557f1c7d41362 | Mauc1201/Python | /functional_programming/1_imperativo.py | 150 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# Área de un círculo
pi = 3.14159
radio = 8
area_circulo = pi*(radio**2)
print("El área del círculo es ", area_circulo)
|
99dae88c68d64b67d1f29de82469af41bec6c687 | Mauc1201/Python | /data_structures/4_funciones_listas2.py | 604 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# ------------- Funciones en listas -------------
lista_alfa = [0, 1, 10, 15, [3, 4, 10, 20, 5]]
# Uso de index en listas
print (lista_alfa.index(15))
print (lista_alfa[4].index(20))
#print (lista_alfa[3].index(1)) #Error por indice
if 15 in lista_alfa:
print ("Find")
else:
print ("Not... |
010dea262665adb0bff2d1eb64ea8ab8516d2271 | TOLAStudios/Text-RPG | /RPG.py | 3,039 | 4 | 4 |
def info ():
print("To play this game, you will need to know some things.")
input()
print("1. Every time you see a blank press the 'Enter' key")
input()
print("2. To leave the game you have to type 'stopgame'")
input()
print("3. When you start the game the text will have obvious thi... |
9df944c1d4925534562ae42f184e37aa16a02839 | asarlashmit/EDUYEAR-PYTHON---20 | /DAY 3.py | 461 | 4.0625 | 4 | # AGE CALCULATOR
x = int(2021)
y = int(input("Enter your Birth of year: "))
age = x-y
print('Your age is ', age ,'.')
# Simple Calculator:
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("a + b = {}".format(a + b))
print("a - b = {}".format(a - b))
print("a * b = {}".format(a * b))... |
729eb9381c611cc11b36aedd70f96e6be7696efd | thiagohenriquef/python3-learning | /oo/date.py | 284 | 3.984375 | 4 | class Date:
def __init__(self, day, month, year):
self.day = day
self.month = month
self.year = year
print('new Python Object')
def __str__(self):
return f'{self.day} - {self.month} - {self.year}'
date = Date(1, 1, 2018)
print(date)
|
6a535e03313d9ee831ddc26322a11165368ed719 | thiagohenriquef/python3-learning | /oo/car.py | 579 | 3.59375 | 4 | class Car:
def __init__(self, max_speed):
self.speed = 0
self.max_speed = max_speed
def speed_up(self, velocity=5):
self.speed = self.speed + velocity if self.speed + \
velocity <= self.max_speed else self.max_speed
return self.speed
def brake(self, delta=5):
... |
8cbbc400a009ef82f0f70fa2c995a541ef34ebe0 | fishhead2567/MazeGeneratorApp | /RandomizationTools.py | 2,248 | 4.0625 | 4 |
# https://stackoverflow.com/questions/2140787/select-k-random-elements-from-a-list-whose-elements-have-weights
# testing out roulette wheel algorithm
from random import randint, choice, shuffle
import numpy as np
def TestRouletteWheeel():
# generate elements
NUM_ELEMENTS = 100
ELEMENTS = [
"STE... |
c39a9687a0d2616dabe086106e46bf4a15ace12b | 317196591/eda1_p10 | /numero.py | 315 | 4.03125 | 4 | print("Ingresa un numero del 1 al 5")
numero=int(input())
if numero==1:
print("El numero es 1")
elif numero==2:
print("El numero es 2")
elif numero==3:
print("El numero es 3")
elif numero==4:
print("El numero es 4")
elif numero==5:
print("El numero es 5")
else:
print("Error")
|
8cdf1143bbf1aa90dededff44d9900f6b17e77ef | hamzatahir007/if-else-Score-Grade-programms | /Assignment_2.py | 190 | 3.828125 | 4 | hrs = input("Enter Hours:")
istrg= float(hrs)
rate= input("Enter Rate:")
astrg= float(rate)
pay = (istrg * astrg)
if pay < 500 :
print(pay)
else :
print('not a number')
|
d43c1f9b963a1f495ecd9cf8b744d4ec98ca4fe4 | krystiankkk/codewars | /phonenumber.py | 261 | 3.640625 | 4 | def create_phone_number(n):
prefix=''
mid=''
intern=''
for i in range(0, 3):
prefix+=str(n[i])
for i in range(3,6):
mid+=str(n[i])
for i in range(6, 10):
intern+=str(n[i])
return f"({prefix}) {mid}-{intern}" |
4c9ff6ba2fd41295325e470089a1311b85c47269 | karollsadowski/Python | /test1.py | 127 | 3.796875 | 4 | print('Hello World')
print('What is your name?')
myName = input()
print('It is food to meet you ' + myName)
print(len(myName))
|
85ff2141af0f8606dacdd75760f4d3d23b21dd9b | xNewz/gitignore_3 | /ใบงานที่1/2.py | 138 | 4.0625 | 4 | num = int(input("ป้อนตัวเลข : "))
for l in range(1,13):
Result = num*l
print("{}*{}={}".format(num,l,Result))
|
12e4244cbb963d6fc86951deaff658243611a035 | xNewz/gitignore_3 | /ใบงานที่6/electro.py | 1,864 | 3.6875 | 4 | import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.geometry('500x120')
window.title("คำนวณค่าค่าไฟฟ้า")
lbl1 = tk.Label(window,text="ป้อนหน่วยค่าไฟ",font=(12))
lbl1.pack(pady=5)
txt1 = tk.Entry(window,width=15)
txt1.pack(pady=5)
def electro():
unit = txt1.get()
if unit == '':
... |
ab09f15a8af7a072057298b008604ec5fde10a79 | iamharsh1312/Python-Code | /image classification using Random forest.py | 1,899 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
## Image classification using RandomForest: An example in Python using CIFAR10 Dataset
def Snippet_349():
print()
print(format('Image classification using RandomForest: An example in Python using CIFAR10 Dataset','*^88'))
# In[2]:
import warnings
warnings... |
84c1f728aab94f541d27d7265aa207bf1dce831b | Jo-bot86/Hacker-Rank-Practice | /4/Division.py | 217 | 3.765625 | 4 | '''
Created on 13.12.2020
@author: Joe
'''
if __name__ == '__main__':
a = int(input('Please enter the first integer '))
b = int(input('Please enter the second integer '))
print( a//b)
print(a/b) |
c93449ff507b3f66ab5a60bcea70e51f469c8f2a | Raimundor/aulaspythons | /PythonExercicios/ex042.py | 473 | 4.0625 | 4 | n1 = float(input('Primeiro segmento: '))
n2 = float(input('Segundo segmento: '))
n3 = float(input('Terceiro segmento: '))
if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n2 + n1:
print('Os segmentos acima PODEM FORMAR um triângulo ', end='')
if n1 == n2 == n3:
print('EQUILÁTERO.')
elif n1 == n2 or n2 == n... |
8e3598b6b8724e4522200dac62c06dbd879244e8 | Raimundor/aulaspythons | /PythonExercicios/ex034.py | 252 | 3.515625 | 4 | sal = float(input('Qual é o salário do funcionário? R$ '))
if sal <= 1250:
novo = (sal * 0.15) + sal
else:
novo = (sal * 0.10) + sal
print('Quem ganhava \033[33mR${:.2f}\033[m passa a ganhar \033[31mR${:.2f}\033[m agora.'.format(sal, novo))
|
78fc7dfcaca81c65e74ccc5df8fa854c555fa41e | Raimundor/aulaspythons | /PythonExercicios/ex043.py | 510 | 3.84375 | 4 | peso = float(input('Qual é o seu peso? (Kg) '))
alt = float(input('Qual é o sua altura? (m) '))
imc = peso / alt**2
print('O IMC dessa pessoa é de {:.1f}'.format(imc))
if imc < 18.5:
print('Você está ABAIXO DO PESO normal')
elif 18.5 <= imc < 25:
print('PARABÉNS, você está na faixa de PESO NORMAL')
elif 25 <= i... |
7dcfec4b5510f56bcd69a73b3dc6f29ec8643662 | piecesofreg09/DSA | /Course_1/W3/2_maximum_value_of_the_loot/fractional_knapsack.py | 859 | 3.703125 | 4 | # Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
ratio = [(values[i] / weights[i], values[i], weights[i]) for i in range(len(weights))]
ratio.sort(key=lambda x:x[0])
while capacity > 0 and len(ratio) > 0:
# get the largest density item
pair = ratio.... |
746864faa1908bcb08d1bc879482cdb00bc65326 | piecesofreg09/DSA | /Course_1/W2/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py | 1,049 | 3.890625 | 4 | # Uses python3
import sys
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
def fibonacci_partial_sum(from_, to):
m = 10
period... |
8b09052ddd28000e43d930967ed84b8215097d2b | minxiii/TIL_python | /day4/whileLab4.py | 654 | 3.875 | 4 | #사용자로부터 월에 해당하는 숫자를 입력받는다
#입력된 숫자가 1~12면: 각 월에 맞는 계절을 'x월은 xx'이렇게 출력
#입력된 숫자가 1~12아니면 : '1~12사이의 입력하세요'출력
while True:
month = int(input('월을 입력하세요'))
if 3<= month <= 5 :
print(month,'월은 봄', sep='')
elif 6<= month <= 8 :
print(month,'월은 여름', sep='')
elif 9<= month <=11:
print(mont... |
60e8f95734a56b06159f523ece965e9d8d1c3fd6 | dado3212/advent-of-code | /2020/dec2/p1.py | 370 | 3.71875 | 4 | import math, re
def is_valid(password):
a = re.search(r"(\d+)-(\d+) (.): (.*)", password)
char = a.group(3)
password = a.group(4)
num_times = password.count(char)
return num_times >= int(a.group(1)) and num_times <= int(a.group(2))
valid = 0
with open("./input.txt", "r") as f:
for x in f.readl... |
d2a2c0102c6d339b7c5567a51ba9b8f25b0663ea | GovindMalhotra/Project-Euler | /ques3.py | 743 | 3.921875 | 4 | """
Project Euler question 3
Author : Govind Malhotra
Date : 8th July 2016
Objective : Largest prime factor of a number
"""
#First drive the prime numbers function
def number_generator(x):
n=5
while n < x:
yield n
n = n+2
def prime_func(x):
l=[2,3]
for i in number_gen... |
44e3112841cedc41105659ea1fde0d74660e55aa | GovindMalhotra/Project-Euler | /ques3.2.py | 419 | 3.515625 | 4 |
"""
Project Euler question 3
Author : Govind Malhotra
Date : 8th July 2016
Objective : Largest prime factor of a number
"""
import time
l=[]
def div_check1(x):
i=2
while i <= x:
if x%i ==0:
l.append(i)
x = x/i
div_check1(x)
break
i=i+1
return ... |
a73ec7acec6bba511734074fcb463fde0522db94 | ryhamz/researcher-social | /db.py | 3,543 | 3.90625 | 4 | """
This module contains example code for basic SQLite usage.
Feel free to modify this file in any way.
"""
import sqlite3
# on import create or connect to an existing db
# and turn on foreign key constraints
conn = sqlite3.connect("globus_challenge.db", check_same_thread=False)
conn.row_factory = sqlite3.Row
c = conn... |
fc00d2e865a2a429de10c17b74d2d90ed57a6a21 | lion963/SoftUni-Python-Fundamentals- | /EXERCISE_DATA TYPES AND VARIABLES/Prime Number Checker.py | 207 | 3.78125 | 4 | num = input()
num = int(num)
cond = True
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print('False')
cond = False
break
if cond:
print('True')
|
3535790b070bc2f1867546ed77cebb82beca9c82 | lion963/SoftUni-Python-Fundamentals- | /Basic Syntax Conditional Statements and Loops/Number Definer.py | 328 | 4.0625 | 4 | number=float(input())
if number==0:
print('zero')
elif 0<number<1:
print('small positive')
elif 1<=number<=1000000:
print('positive')
elif number>1000000:
print('large positive')
elif -1<number<0:
print('small negative')
elif -1000000 <= number <= -1:
print('negative')
else:
print('large ne... |
58f9ed33398601973ba0755f4440de98086b89e6 | lion963/SoftUni-Python-Fundamentals- | /Exercise Lists Basics/Zeros to Back.py | 192 | 3.515625 | 4 | list1=input().split(', ')
count=0
list2=[]
for el in list1:
if el=='0':
count+=1
else:
list2.append(int(el))
for i in range(count):
list2.append(0)
print(list2) |
6a053f7dfbda90bf296646f4c4a45f5075243c84 | lion963/SoftUni-Python-Fundamentals- | /Functions/Calculations.py | 378 | 4.1875 | 4 | def simple_calculator(operator, num1, num2):
if operator=='multiply':
return int(num1*num2)
elif operator=='divide':
return int(num1/num2)
elif operator=='add':
return int(num1+num2)
elif operator=='subtract':
return int(num1-num2)
oper=input()
num_1=float(input())
num_2... |
880a862d6b1d7dea7b44e64ec5965c64ba963fd6 | lion963/SoftUni-Python-Fundamentals- | /EXERCISE_DATA TYPES AND VARIABLES/Gladiator Expenses.py | 456 | 3.53125 | 4 | lost_fight = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
amount = 0
for lost in range(1, lost_fight + 1):
if lost % 2 == 0:
amount += helmet_price
if lost % 3 == 0:
amount += sword_price
if lost % 6 == 0... |
9e10251f252dbd7bd582cc4d8468241da9d82b00 | lion963/SoftUni-Python-Fundamentals- | /Exercise Lists Basics/Bread Factory.py | 1,050 | 3.71875 | 4 | list1=input().split('|')
current_energy=100
coins=100
condit=True
for el in list1:
command, value=el.split('-')
value=int(value)
if command=='rest':
if value+current_energy<=100:
current_energy+=value
print(f'You gained {value} energy.')
print(f'Current energy:... |
4df84862ce197d9b673349f52b70fc30847f4347 | lion963/SoftUni-Python-Fundamentals- | /Exercise Dictionaries/Ranking.py | 1,252 | 3.53125 | 4 | contests = {}
line = input()
while not line == 'end of contests':
contest, password = line.split(':')
if contest not in contests:
contests[contest] = password
else:
contests[contest] = password
line = input()
users = {}
line = input()
while not line == 'end of submissions':
contes... |
29901ca839a437f88d4013b5247f322bf9d81f1c | lion963/SoftUni-Python-Fundamentals- | /Exercise_Basic_Syntax_Conditional_Statements_and_Loops/Jenny's Secret Message.py | 90 | 3.90625 | 4 | name=input()
if name=='Johnny':
print(f'Hello, my love!')
else:
print(f'Hello, {name}!') |
a357a9fb7602066f1b0802ab521dd1d6a6644736 | lion963/SoftUni-Python-Fundamentals- | /FinalExam Preparation/Secret Chat.py | 844 | 3.796875 | 4 | message = input()
line = input()
while not line == 'Reveal':
command_list = line.split(':|:')
if command_list[0] == 'InsertSpace':
index1 = int(command_list[1])
message = message[:index1] + ' ' + message[index1:]
print(message)
elif command_list[0] == 'Reverse':
substring =... |
3c6840ca538e25c17337d835a6d5e73cb548d4d4 | lion963/SoftUni-Python-Fundamentals- | /Lists Basics/Courses.py | 101 | 3.734375 | 4 | n=int(input())
list1=[]
for i in range(1,n+1):
line=input()
list1.append(line)
print(list1) |
80d4fa3b605c41ead3a00e0385738e8565391e1e | lion963/SoftUni-Python-Fundamentals- | /Exercise Functions/Center Point.py | 450 | 3.765625 | 4 | list1=[int(input()),int(input())]
list2=[int(input()),int(input())]
import math
list_point1=list(map(lambda x: abs(x**2),list1))
distance1=math.sqrt(sum(list_point1))
list_point2=list(map(lambda x: abs(x**2),list2))
distance2=math.sqrt(sum(list_point2))
if distance1>distance2:
print(f'({list2[0]}, {list2[1]})')
... |
5ee9b4e07c6167dbd99d1903e6cea411450ae1ee | lion963/SoftUni-Python-Fundamentals- | /Regular Expressions/Match Full Name.py | 130 | 3.9375 | 4 | import re
line = input()
pattern = '\\b[A-Z][a-z]+ [A-Z][a-z]+\\b'
result = re.findall(pattern, line)
print(' '.join(result))
|
d57140520690ea09f60a3f25c4bc697e2060c603 | lion963/SoftUni-Python-Fundamentals- | /Exercise Lists Advanced/Take Skip Rope.py | 399 | 3.5625 | 4 | list1=list(input())
result=[]
index=0
numbers=[int(el) for el in list1 if el.isdigit()]
non_numbers=[el for el in list1 if not el.isdigit()]
take=[numbers[i] for i in range(len(numbers)) if i%2==0]
skip=[numbers[i] for i in range(len(numbers)) if not i%2==0]
for i in range(len(take)):
result+=non_numbers[index:i... |
f4a1b5b9b4580ba0df146dd410f1582bc631f3c6 | lion963/SoftUni-Python-Fundamentals- | /Exercise Lists Advanced/Which Are In.py | 251 | 3.734375 | 4 | list1 = input().split(', ')
list2 = input().split(', ')
list3 = []
list4=[]
for el in list1:
for ele in list2:
if ele.find(el) >= 0:
list3.append(el)
for el in list1:
if el in list3:
list4.append(el)
print(list4) |
36174c7532cc308c15b318340b0cced28c6c75be | lion963/SoftUni-Python-Fundamentals- | /Exercise_Basic_Syntax_Conditional_Statements_and_Loops/Find The Capitals.py | 256 | 3.671875 | 4 | str = input()
list2=[]
def new_list(string):
li = []
li[:0] = string
return li
list1 = new_list(str)
for char in range(len(list1)):
for i in range(65, 91):
if ord(list1[char]) == i:
list2.append(char)
print(list2) |
0f2cf16de36eb9c366d24f0e811929b0e04e4692 | lion963/SoftUni-Python-Fundamentals- | /Exercise Functions/Tribonacci Sequence.py | 442 | 3.734375 | 4 | n=int(input())
list1=[0,0,1]
for i in range (1,n):
tribonacci=list1[-1]+list1[-2]+list1[-3]
list1.append(tribonacci)
list1.pop(0)
list1.pop(0)
list1=list(map(str,list1))
print(' '.join(list1))
# n=int(input())
#
# list1=[1]
# list2=[0,0,1]
#
# for i in range (1,n):
# tribonacci=sum(list2)
# list1.ap... |
8d83e1ab473d9b87da5d370ac9ccf5aa62f24360 | lion963/SoftUni-Python-Fundamentals- | /Exercise Dictionaries/Orders.py | 407 | 3.5625 | 4 | items_dict = {}
command = input()
while not command == 'buy':
name, price, quantity = command.split()
price = float(price)
quantity = int(quantity)
if name not in items_dict:
items_dict[name] = [0, 0]
items_dict[name][0] = price
items_dict[name][1] += quantity
command = input()
fo... |
fac6e82bdd8248496c05a19cda03dc00b38b1d19 | JackyCafe/basicProject | /example1.py | 139 | 3.609375 | 4 | #靠窗 靠走道
seat = 28
if seat % 4 ==0 :
print('靠走道')
elif seat % 4 <= 2:
print ('靠窗' )
else:
print('靠走道') |
63505b0898a1923164d77fa9bed3693f7afcfde9 | Rajas2323/snake_game | /snake.py | 3,381 | 3.5625 | 4 | import pygame
import random
pygame.init()
def game_over():
blue = (0, 0, 255)
X = 800
Y = 700
RUN = False
while not RUN:
window1 = pygame.display.set_mode((X, Y))
pygame.display.set_caption("Game Over!")
font = pygame.font.Font("freesansbold.ttf", 40)
text = font... |
9d5c1fc35239f5a244510ca5cda71b51f37a31a6 | deepakmali/Assignment | /getTrendingProducts.py | 523 | 3.53125 | 4 | import csv
import sys
exf = open("ProductDetails.csv")
exr = csv.reader(exf)
# date = raw_input("Enter date: ")
date = sys.argv[1]
topNum = int(sys.argv[2])
total_items = dict()
for data in exr:
if date in data:
if data[1] in total_items.keys():
total_items[data[1]] += int(data[2])
else:
total_... |
363f6e0f4577f14944dcc5c7bb767626f11ff120 | cvalentim/ToolKit | /python/re/quick_tutorial.py | 1,975 | 3.9375 | 4 | # BASIC SIMBOLS
# . (the dot character) matches one of any characters
# * (the start character) matches zero or more of the previous character or group
# [0-9] any digit between 0 and 9. [ab] matches either a or b. [0-9a-zA-Z] matches any letter or number
# {number} will repeat the previous element the specified number... |
7d8ddea16300242e98a3bfec748d46103dddecaf | Eden-YifeiXu/Amortization | /Amortization.py | 3,626 | 3.984375 | 4 | import prettytable as ptb
# Get User Input
while True:
principal = float(input("Please input a principal: "))
if principal < 0:
print("Principal must be a float and no less than 0. Please try again.")
else:
break
while True:
interest_rate = float(input("Please input an inter... |
f9465c33f806b1887c493d94c896d16975b7012a | AlexNedyalkov/ScienceProjectsPython | /entropy_written_english/entropy_written_english.py | 1,683 | 3.578125 | 4 | import string
import numpy as np
import matplotlib.pyplot as plt
import re
import requests
# get the text from the internet
book = requests.get('http://www.gutenberg.org/files/35/35-0.txt')
text = book.text
# character strings to replace with space
strings2replace = [
'\r\n\r\nâ\x80\x9c', # new parag... |
babdcd29d06ba66ff7613062938ce35f61c5ba79 | swedakonsult/algorithmic-toolbox | /week2/fibonacci/fibonacci.py | 477 | 3.5 | 4 | # Uses python3
def calc_fib(n):
if n <= 1:
return n
return calc_fib(n - 1) + calc_fib(n - 2)
def calc_fibFast(n, lst):
if n <= 1:
return n
if lst[n] > 0:
#print('hit:', n)
return lst[n]
r = calc_fibFast(n - 1, lst) + calc_fibFast(n - 2, lst)
lst[n] = r
re... |
7a87e88b7d69e35e8cfe9d29e808c33e47366e75 | joaorobertomartins/Projeto-PL1 | /real_python_example.py | 3,346 | 3.609375 | 4 | """
Real Python Linear Programming example
https://realpython.com/linear-programming-python/
"""
import numpy as np
from scipy.optimize import linprog
from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable
from pulp import GLPK
def main_scipy():
"""
linprog() solves only minimization (not maxim... |
f6f02170a57bcfa2268164ab4007063b44eef7cf | GerryMijarry/dino_vs_robots_project | /Battlefield.py | 2,631 | 3.671875 | 4 | from fleet import Fleet
from herd import Herd
import random
class Battlefield:
def __init__(self):
self.fleet = Fleet()
self.herd = Herd()
def run_game(self):
self.display_welcome()
self.battle()
self.display_winners()
def display_welcome(self):
print("Welc... |
80a56ff5956febc329e45879c1cb4206dddd2a9b | jimilythomas/classwork | /listins.py | 154 | 3.859375 | 4 | months=['jan','feb','mar']
months.append ('april')
months.append('may')
months.insert(5,'june')
print months
print 'the index of may',months.index('may')
|
bade340aa00a0fecd8c304a9b9b48b1d74404d51 | tasyrkin/web-crawler | /webcrawler/crawler_utils.py | 664 | 3.6875 | 4 |
class HopsCounter:
INFINITE = 0
def __init__(self, hops_limit):
assert hops_limit >= HopsCounter.INFINITE, 'Expected non negative value, but was [{}]'.format(hops_limit)
self.__hops_limit = hops_limit
self.__is_infinite = self.__hops_limit == HopsCounter.INFINITE
self.__hops_done = 0
def can_hop(self):
... |
fa7f23805b96903988a4aacf449f3089b1783b58 | leiwang758/Texas-Holdem | /texas_holdem.py | 3,946 | 3.65625 | 4 | import functools
from community_cards import CommunityCard
from player import Player
from tie_breaker import TieBreaker
from description_printer import DescriptionPrinter
# validate the input card
def validate_input_card(input_card):
if len(input_card) != 2:
return False
if input_card[0] not in ["2", ... |
7b5237b1f220745d60284ac9d45bec4beca81f2f | mtbulut/python-challenge | /PyPoll/main_p.py | 1,490 | 3.59375 | 4 | import os
import csv
import pprint
import math
import decimal
with open(os.path.join("Resources","election_data.csv"), "r") as in_file:
in_csv = csv.reader(in_file)
header = next(in_csv) # activating this will exculede the firs line.
data = list(in_csv)
# print(data)
################################... |
e9556ca094d1d1ee9895a390a4fcf1379dbf1baf | dddooo9/CodeUp | /1041/1048.py | 107 | 3.5625 | 4 | # a, b = input().split()
# print(int(a) << int(b))
a, b = input().split(' ')
print(int(a) * (2 ** int(b))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.