blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
70cf93d84df84c789b9b0fa36eb44a1ca03c6417 | lalaheihaihei/THCat_kMC | /SF/count_reaction.py | 16,238 | 3.65625 | 4 | # -*- coding:utf-8 -*-
"""
@author: Jin-Cheng Liu
@file: count_reaction.py
@time: 12/26/2016 11:49 AM
A module to find all avail_sites for every elementary reactions.
"""
def count_of_forwards_reactions(kmc, n_avail, lat, i, j, k):
"""
this def append '4': [['4', [3, 3], [3, 2]], ['4', [3, 3], [3, 4]]] valu... |
3f7beced4923849b4d2981ef84d7023bf7a04121 | pratikshas8080/PYTHON_Daily_Code_2021 | /Tuple.py | 177 | 4.09375 | 4 | #Tuple
Tuple1=("Patiksha", "Sudarshan", "Darsh", "Shree")
var=Tuple1
var=type(Tuple1)
print(Tuple1)
#Tuple are Unmutable that time you convert into List and Then add Elements
|
70e08ce057ee11ce2680cdf3b6486cfebd2b6c7f | maidougit/python-test | /com/maimai/python/爬虫/weather.py | 1,686 | 3.546875 | 4 | #coding:utf8
#!/usr/bin/env python
# 解释器路径
from html.parser import HTMLParser
import sys, urllib.request, string, re
# 导入使用方法模块
class HtmlParser(HTMLParser):
style = "font-family: Arial, Verdana, sans-serif;"
def __init__(self):
self.data = ''
self.readingdata = 0
HTMLParser.__init__(self)
def ... |
74e38c11fb3b5aac6b73e89ef7db7872b5b933da | rasky0607/CursoPython3 | /clases/LecturaFicheros/LecFicherosCSV.py | 2,044 | 3.9375 | 4 | #Modulo de lectura de python para ficheros CSV
#Importamos el modulo de csv
import csv
#Nota1: podemos usar el meotod seek() de los ficheros para mover el puntero a una posicion concreta
#En primer lugar abrimos el fichero de "prueba.csv"como un fichero normal de texto en modo lectura
f=open("./FicherosDePrueba/prueba... |
1b95c5839318e21449ca5ace8b86a54df170a998 | xoyolucas/My-solutions-for-Leetcode | /581.最短无序连续子数组.py | 1,479 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=581 lang=python3
#
# [581] 最短无序连续子数组
#
# https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/description/
#
# algorithms
# Easy (34.84%)
# Likes: 366
# Dislikes: 0
# Total Accepted: 34.3K
# Total Submissions: 98.4K
# Testcase Example: '[2,6,4,8,10,9,15]'
#
# 给定一个整数数组... |
e05427682ca8424ef9d69170e59d0bea57088e9f | CouchNut/Python3 | /inlinemodule/use_datetime.py | 3,045 | 3.53125 | 4 | #!/usr/local/bin python3
# -*- coding: utf-8 -*-
# 获取当前日期和时间
print('----- 获取当前日期和时间 -----')
from datetime import datetime
now = datetime.now() # 获取当前datetime
print(now)
print(type(now))
# 获取指定日期和时间
print('----- 获取指定日期和时间 -----')
dt = datetime(2015, 4, 19, 12,20) # 用指定日期时间创建datetime
print(dt)
# datetime转换为timestam... |
da664baaa182fc905149fc3c94b7c429d9f36cb7 | DelbyPicnic/swan_gordon_set09103_coursework1 | /data_access.py | 5,853 | 3.671875 | 4 | # Python DataObject System - Read, Write, Append, Search
# Gordon Swan - Edinburgh Napier University
import json, sys
# Method to retrieve all the data from the JSON file in one go
def getData():
try:
openFile = open("static/data/fileData.JSON","r")
fileData = openFile.read()
allData = json.loads(fileData)
... |
a64c885a07bfbf52a87c0fa39f4c5a7294690efa | Vyom20798/Vyom20798 | /Series.py | 642 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
#Fibonacci series
Number = int(input("How many Number? "))
# in fibonacci 1st term is 0 and 2nd term is 1 hence:
n1, n2 = 0, 1
count = 0
if Number == 1:
print("Fibonacci sequence upto",Number,":")
print(n1)
else:
print("Fibonacci sequence: ", end=" ")
... |
593d97256ece7ab64ce395696ce54e8aec9c18ea | leeehh/cs231n | /assignment1/cs231n/classifiers/softmax.py | 3,608 | 3.875 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X:... |
b237ad72acae8d1de4bdd634bffd7ecdb5039f82 | manfrina87/WordLab | /palindromes.py | 285 | 3.578125 | 4 | from collections import deque
def palyndromer(pword):
d = deque(pword)
while len(d) >1:
if d[0] == d[-1]:
d.popleft()
d.pop()
ck="Char IS palindrome"
else:
ck="NOT palindrome"
break
return ck |
4f4274d47569060c335a26333a6ba89a5608c1cd | Tha-Ohis/demo_virtual | /If and Elif Examples.py | 1,001 | 4.15625 | 4 | #If and Elif(Else) example
#Elif is also known s the chain condition
# gen=input("Enter your gender: ")
# if gen.lower()=="m" or gen.lower()=="male":
# print("Male!!")
# elif gen.lower()=="f" or gen.lower()=="female":
# print("Female!!")
# elif gen.lower()=="t" or gen.lower()=="transgender":
# print("Trans... |
f1d6f397baf9ca1fd745d92ed83adc5be0e74f36 | hongm32/2020design | /第1学期/【第12课】二分算法/猜数游戏(2.0破解版).py | 886 | 3.765625 | 4 | import random
print('这是一个猜数游戏,数字范围1-50')
set_number = random.randint(1, 50) # 随机设定正确的数
print("当前随机生成的正确的数是:", set_number)
number_min = 1
number_max = 50
step = 1
guess_number = number_min + (number_max - number_min) // 2 # 取中间数
while guess_number != set_number:
step += 1
if guess_number > set_number: # 比较猜的数... |
91a87d2427f694038cce36fb90252152233e877d | NRishab17/code | /DEqueue.py | 1,532 | 4 | 4 | #code for DoubleEndedqueue
class DEqueue:
def __init__(self):
self.items=[]
def isempty(self):
return self.items==[]
def addrear(self,data):
self.items.append(data)
def addfront(self,data):
self.items.insert(0,data)
def removefront(self):
return se... |
09ec9d5dcd7c3b4dd6a922b41f8d5c4437fcd14c | SinaSarparast/CPFSO | /JupyterNotebook/bagOfWords.py | 1,151 | 3.796875 | 4 | from sklearn.feature_extraction.text import CountVectorizer
def get_word_bag_vector(list_of_string, stop_words=None, max_features=None):
"""
returns a vectorizer object
To get vocabulary list: vectorizer.get_feature_names()
To get vocabulary dict: vectorizer.vocabulary_
To convert a list... |
86a5b0d1d6685bff265f1d73e44267bd0f3c79fa | poplock1/Lightweight_ERP | /store/store.py | 7,549 | 3.5625 | 4 | """ Store module
Data table structure:
* id (string): Unique and random generated identifier
at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters)
* title (string): Title of the game
* manufacturer (string)
* price (number): Price in dollars
* in_stock (nu... |
6a6097e35d74aa99e2e025796c4ea34065103057 | DmitryGlyuz/german_numbers | /german_numbers.py | 362 | 3.8125 | 4 | import core
# Simple interface where we can check how our function works
# Enter any non-Int to exit
print('Enter any integer number to get it in German.\nEnter any non-integer to exit.')
while True:
try:
n = int(input('\nNumber: '))
print(f'German: {core.GermanNumeral(n)}')
except ValueError:
... |
c1a8c786783a8b97ce5760fa9d3426c239853c7e | ZahraaSaied/AI | /Algorithms learning/regression/Multiple LR/multiple_Linear_regression.py | 882 | 3.5 | 4 | #import liberaries
import pandas as pd
import numpy as np
import matplotlib as plt
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
#import dataset
dataset = pd.read_csv("50_Startups.csv")
X = dataset.i... |
98d0a5887ba44934c3c69af2be2a42520b72d934 | way0utwest/projecteuler | /euler9.py | 1,060 | 4.21875 | 4 | '''
Euler 9
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a*2 + b*2 = c*2
For example, 3^2 + 4*2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import sys
import time
def Solution(end):
x, counter, ans... |
7643f39ae2116ef42a77d2de08a5d6398101367b | Debolina136208/python | /Day1Assignments/fibonacci.py | 138 | 3.96875 | 4 | val=20
num1=0
num2=1
count=0
while count < val:
print(num1,end=',')
nth=num1+num2
num1=num2
num2=nth
count+=1 |
ef5882975688b6bbf6426627c48d12702935d6b5 | Yeslie22/PythonFinalDemo | /PC4_Yeslie Aguilar/Módulo 2/mario.py | 344 | 3.65625 | 4 | intentos = 0
while intentos < 1000:
entrada= input('Ingrese un dato, por favor: ')
intentos+= 1
if entrada in ('1','2','8'):
for i in range(1,int(entrada)+1):
print(" " * (int(entrada) - i) + '#' * int(i))
break
else:
print('Dato inválido, inténtalo de nue... |
5052d66c3df6ba350ed6fde5bca44d5f1e6b4cb6 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/edlada002/util.py | 1,885 | 3.75 | 4 | """push
Adam Edelberg
2014/04/29"""
def create_grid(grid):
"""create a 4x4 grid"""
blank_array = [0,0,0,0]
for i in range (4):
grid.append (blank_array[:])
def print_grid (grid):
"""print out a 4x4 grid in 5-width columns within a box"""
print("+------------------... |
8b44c196c798f4dc66ee3bea70823c7010f82f63 | jackzkdavies/foobar- | /University/Python/Maze Solver/dada.py | 1,457 | 3.734375 | 4 | neighbours = [1,2,3,4]
count = 0
while count != 3:
hold = neighbours[0]
hold2 = neighbours[1]
neighbours[1] = hold
neighbours[0] = hold2
print neighbours
hold = neighbours[2]
hold2 = neighbours[3]
neighbours[3] = hold
neighbours[2] = hold2
print neighbours
hold... |
38e9b9381fbf25230ccb7ebb9b1ff6bc7919af3e | sindredl/code_vault | /exercises/trivia.py | 21,820 | 4.1875 | 4 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
# Ask a simple question without multicolumns
# Show multichoice window and return selected item
class AskForChoice(Frame):
# question is a simple string
# answers - is a dictionary object like
# { 'a' => 'Choice 1', 'b' => 'C... |
53e9cb27afe1543b369ff8f51aa5ea644b6ace66 | AlexWilliam/PythonUdemy | /excript/app-comerciais-kivy/aulas/aula25.py | 153 | 3.546875 | 4 | num_int = 1
num_dec = 7.5
val_str = "qualquer texto"
print("O valor é:", num_int)
print("O valor é: %i" %num_int)
print("O valor é: " + str(num_int)) |
cc151f93e4c3b59142c4367ba25dfcd4cc367522 | GuhanSGCIT/SGCIT | /replacerightside.py | 965 | 4 | 4 | def nextGreatest(arr):
size = len(arr)
# Initialize the next greatest element
max_from_right = arr[size-1]
# The next greatest element for the rightmost element
# is always 0
arr[size-1] = 0
# Replace all other elements with the next greatest
for i in range... |
e312ceae926fd9ace8e6915305c6743b4878583c | ammarjussa/Cs50Projects | /Lecture0_Search/tictactoe/tictactoe.py | 3,784 | 3.9375 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
turn = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a ... |
e94581b7628aa0b70227dac0a7daed36d67c20e7 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2499/60738/313601.py | 203 | 3.765625 | 4 | n=int(input())
if n==3:
print(0)
elif n==2:
print(0)
elif n==9:
print('''1
1
0
0''')
elif n==11:
print(2)
print(2)
print(2)
print(1)
elif n==6:
print(2)
else:
print(n) |
222336bbd7d48702f641127ecdfa8fa20b8db034 | ModestTheKnight/PythonLessons | /board_test.py | 373 | 3.828125 | 4 | def is_valid_board(board, column):
row = len(board)
r = 0
for c in board:
if column == c or abs(row-r) == abs(column-c):
return False
else:
r += 1
return True
alist = [int(x) for x in input('board>>').split()]
pos = int(input('column>>'))
if is_valid_board(alist... |
1a5c0c809eb4be3305bd5e0e773448f2a9a22b24 | carlos-andrey/programacao-orientada-a-objetos | /listas/lista-de-exercicio-07/questao10/questao02.py | 312 | 3.6875 | 4 | '''Questão 2. Modele uma paixonite, sendo que essa possua ao menos o atributo nome,
e ao menos um metodo que utilize o atributo nome. '''
class Crush:
def __init__(self, nome):
self.nome = nome
def iludir(self):
print(f'{self.nome} só ilude.')
crush1 = Crush('Pedro')
crush1.iludir() |
1e50b05ff12b7a148ec70c9adf2ec447752986ea | projective-splitting/just-continuity | /robustFusedLasso.py | 10,266 | 3.546875 | 4 | '''
#references:
#[1]: "Projective Splitting with Forward Steps only Requires Continuity", Patrick R. Johnstone, Jonathan Eckstein, https://arxiv.org/pdf/1809.07180.pdf
# Functions defined in this file:
1. ps() - projective splitting applied to the robust fused lasso problem
2.
'''
import numpy as np
from mat... |
562fc5da1d34291a12e1e32ca7b179166b10c2c4 | javierunix/ca_computerscience | /CS101/functions/challenges.py | 2,576 | 4.21875 | 4 | # Create a function named divisible_by_ten() that takes a list of numbers named nums as a parameter.
# Return the count of how many numbers in the list are divisible by 10.
def divisible_by_ten(nums):
counter = 0 # define and initialize counter
for num in nums: # iterate over list
if num % 10 == 0: # i... |
c8e8cd2348f5b6fbd5ce91bae1c4e8042d5f2fc8 | LialinMaxim/Toweya | /name_handler.py | 1,745 | 4.0625 | 4 | """
Implement the unique_names method.
When passed two lists of names, it will return a list containing the names that appear in either or both lists.
The returned list should have no duplicates.
For example, calling unique_names(['Ava', 'Emma', 'Olivia'], ['Olivia', 'Sophia', 'Emma'])
should return a list containin... |
291760734a3fa653ac77be254c5ba93844f9537d | kseniiacode/STC | /lab1/main.py | 9,345 | 3.890625 | 4 | import func
import pickle
def main():
func.createPassFile()
while True:
print("1 - SignIn")
print("2 - SignIn as ADMIN")
print("3 - Info")
print("4 - Exit")
answ = 0
answ = int(input())
if answ == 1:
flag = 1
login ... |
149f6fb64768683c862e326fe018aa759fd97ae1 | shduttacheezit/Interview-Cake | /flight_movie_feature.py | 1,350 | 4.34375 | 4 | # You've built an inflight entertainment system with on-demand movie streaming.
# Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runtimes... |
a09d3b39d04c4bcdb68052939ed9fb8e947297d2 | arcstarusa/prime | /StartOutPy4/CH5 Functions/commission_rate/main.py | 600 | 3.796875 | 4 | # This program calculates a salesperson's pay
# at Make Your Own Music. 5-23
def main():
# Get the amount of sales.
sales = get_sales()
# Get the amount of advanced pay.
advanced_pay = get_advanced_pay()
# Determine the commission rate.
comm_rate = determine_comm_rate(sales)
# Calculate t... |
c61d5981ed567760cad039cf9886e1aa67c764fd | qs12/tomato | /function.py | 222 | 3.90625 | 4 | # function
def example():
print('My function in action, yo!')
example()
def SymonAdd(a, b):
# a = input('Enter first number: ')
# b = input('Enter second number: ')
c = a+b
print('the sum is: ', c)
SymonAdd(2,3) |
e8965c3b971782be3233a41fc3df53e36c3e9d81 | jb255/dslr | /caca/feature_scaling.py | 571 | 3.90625 | 4 | def mean_normalization(x, mean=False, std=False):
mean = mean if mean is not False else x.mean()
std = std if std is not False else x.std()
return (x - mean) / std
def rescaling(x, min_x=False, max_x=False):
min_x = min_x if min_x is not False else x.min()
max_x = max_x if max_x is not False else x... |
eac31d42d601a4726313908224fd8687c5e763e9 | TheNotChosenOne/ash | /Ash/Pool.py | 894 | 3.609375 | 4 | class BasePool(object):
"""A base pool for providing objects."""
def __init__(self, factory):
"""Set up the pool itself, and the factory."""
self.pool = []
self.factory = factory
self.factory.variablePool = self.pool
def Get(self):
"""Return a new object, fro... |
3fd8f8dd74104e71b68a7a3df84556dd2f5383c9 | timhannifan/ml-toolkit | /lib/classifier.py | 1,928 | 3.59375 | 4 | '''
Class for generating/training classification models
'''
import pandas as pd
import utils
from sklearn import tree
class Classifier:
'''
Class for representing classifier
'''
def __init__(self):
self.input = None
self.config = {}
self.output = None
self.model = None... |
47dba66704e616524b453b44ff87b7669594b503 | suhassrivats/Data-Structures-And-Algorithms-Implementation | /Grokking-the-Coding-Interview-Patterns-for-Coding-Questions/1. Pattern Sliding Window/Problem Challenge 4 - Words Concatenation (hard) .py | 2,805 | 3.984375 | 4 | '''
Problem Challenge 4
Words Concatenation (hard)
Given a string and a list of words, find all the starting indices of substrings in the given string that are a concatenation of all the given words exactly once without any overlapping of words. It is given that all words are of the same length.
Example 1:
Input: S... |
f2c97ad607586e53f5b74269d2c4ea8a692dd297 | edu-athensoft/cdes1201dataanalysis | /session03/numpy_basic/ndarray_01_creation/ndarray_creation.py | 708 | 3.890625 | 4 | # important attributes of an ndarray object
import numpy as np
# create an array from Python list
# 1-d array
a = np.array([1,2,3,4]) # RIGHT
# a = np.array(1,2,3,4) # WRONG
print(a,"\n",type(a), "the datatype is ", a.dtype)
print()
# 1-d array
a = np.array([1.4,2.5,3.6,4.7]) # RIGHT
# a... |
50fa4f9445aff319e3239a296ee11cec4d14fde7 | mutex1/A-star-Search | /ASS.py | 5,545 | 3.53125 | 4 | import sys
from heapq import heappush, heappop
class ASS():
N = int()
M = int()
maze = list()
start = list()
end = list()
# init variables
def __init__(self):
# read input file
with open(sys.argv[1], 'r') as f:
inputStrings = f.readlines()
... |
6652aab2d73d8727c848bc4d6d98733ef8ef0eff | GowriKrishnamurthy/Python-HackerRankSolutions | /AVeryBigSum.py | 1,028 | 4.09375 | 4 | import math
import os
import random
import re
import sys
# Complete the aVeryBigSum function below.
def aVeryBigSum(ar):
return sum(ar)
if __name__ == '__main__':
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = aVeryBigSum(ar)
print(str(result) + '\n')
"""
In ... |
d589dde7d48c2e0e2a8eff72e58452905e3366b2 | wengellen/cs36 | /additionalWithoutCarrying.py | 480 | 4.09375 | 4 | def additionWithoutCarrying(param1, param2):
# transform param1 and param2 into lists of digits
# transform the ints into strings
# pad the shorter list of digits with 0s at the front
# until both lists are of equal length
# for i in range(len(param1))
# add digits at i for both params together
# check if the resultin... |
d407cae432ebce648a2f23a95fdb1384e973d9b9 | Aasthaengg/IBMdataset | /Python_codes/p03631/s419596935.py | 170 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
N = list(input())
print('Yes'if N[::1] == N[::-1] else 'No')
if __name__ == "__main__":
main()
|
bb4af6d403fc9eae709a4e6c036395e6f5873754 | JoalisonMatheuss/ExercicioRevisaoPython | /Questao 2.py | 139 | 4 | 4 | a = int(input("Digite um nmero: "))
if (a%2 == 0):
print("O nmero %d Par"%(a))
else:
print("O nmero %d mpar"%(a))
|
f134334d0d96110fa674c6c9f0e8eae8bff9c02a | ryandancy/project-euler | /problem40.py | 820 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler Problem 40:
An irrational decimal fraction is created by concatenating the positive integers:
0.12345678910(1)112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If d(n) represents the nth digit of the fractional p... |
e30886a02507059e374bd9c3e2204dc9db7a0461 | AutomaticcData/Web-Mission-To-Mars-App | /appy.py | 1,642 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 16:51:34 2018
@author: antho
"""
# import necessary libraries
from flask import Flask, render_template, jsonify
import pymongo
import scrape
# create instance of Flask app
app = Flask(__name__)
# create mongo connection
client = pymongo.MongoClient()... |
d2085824a2eb04cee6fb01c572137f514248d1a8 | jmbaker94/graph-generator | /graph-generator.py | 3,491 | 3.71875 | 4 | import random
from Graph import Graph, Vertex
## UNTESTED ##
class GraphGenerator:
def __init__(self):
self.__method_list = ["random"]
self.__n = None
self.__m = None
self.__connected = None
self.__method = None
def generate_erdos_renyi_graph(self, n=None, p=None, c... |
37d8261227f8a22b1145ab222ed20069ec913dd2 | kishore163/TechnicalInterviewCodeSnippets | /countingIslandsProblem/countingInversions.py | 922 | 3.71875 | 4 | def solution(arr):
return countInversions(arr)
def countInversions(arr):
if len(arr) == 0 or len(arr) == 1:
return 0
# recursive case
middle = len(arr) // 2
left = arr[0:middle]
right = arr[middle:]
total = countInversions(left) + countInversions(right)
i = 0
pLeft = 0
... |
b46cd924151a15661dd5b1324acdc82910f3c11a | Ben-Rapha/Python-HWS | /HM for volume of a box.py | 1,062 | 4.34375 | 4 | # CSI 31 KINGSLEY OTTO CONVERTION.PY
# THIS PROGRAM CALCULATE THE VOLUME OF A BOX
# Pragram task
# 1. print introduction to the user.
# 2. get lenght, width and height values from the user at the console.
# 3. computes the volume of the bocx by multiplying lenght*width*height
# 4. prints the volume on the s... |
0bfff912e7e7708340b3eec74d76c58d8902848f | gabriellaec/desoft-analise-exercicios | /backup/user_160/ch25_2019_09_30_23_48_59_665654.py | 157 | 3.546875 | 4 | distancia = "Qual a distancia em km?"
if distancia <=200:
preco = 200*0.5
print (preco)
else:
preco = 200*0.50 + (distancia-200) * 0.45
print (preco) |
0a60eb5f59e6ceffc4cf8ae2f94e043a793a3282 | gauravnv/snake-starter | /app/board.py | 2,075 | 3.984375 | 4 | from .snake import Snake
class Board:
"""Represents board including food, opponent snakes, and board metadata."""
# Constants for board spaces.
# Positive integers are reserved for representing snakes.
FOOD = -1
def __init__(self, width, height, food, snakes, player):
self.width = width
self.height = height... |
eccbdabb23ebe9eebf0d1830a9906f477692058f | cravo123/LeetCode | /Algorithms/0234 palindrome Linked List.py | 794 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Solution 1,
# Split linked list to two equal parts, and iterate to check
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
fast = slow = head
... |
e69cb297d53d88140ddcfd25013cd369e04b7d30 | FranHuzon/ASIR | /Marcas/Python/Ejercicios/Repetitivas/Ejercicio 4.py | 2,476 | 4.15625 | 4 | numero_minimo_intervalo = int(input('Indica el comienzo del intervalo: '))
numero_maximo_intervalo = int(input('Indica el final del intervalo: '))
cantidad_numeros_dentro_intervalo = 0
maximo_fuera_intervalo = []
cantidad_numeros_fuera_intervalo = []
igual_numeros_extremos = False
#-------------------- CORRECION INTE... |
f59b05a31dcc3ced08a8b700241052bb3bd23c67 | craciunescu/algo | /U3/test/test_e2.py | 1,462 | 3.9375 | 4 | """
@author: David E. Craciunescu
@date: 2021/03/10 (yyyy/mm/dd)
2. We are given a vector of unordered positive integers that we cannot alter
or copy in any way, shape, or form. Yet, we'd like to obtain information from
this vector as if it were ordered.
=> Modify the standard MergeSort alg... |
ed5c6bc1e896107f10406308f72e3447cffdd51f | echosatyam/interviewbit-solutions | /binary-search/square_root_of_integer.py | 357 | 3.71875 | 4 | def sqrt(A):
if(A == 0 or A == 1):
return A
low = 2
high = int(A/2)+1
while(low <= high):
mid = int((low+high)/2)
if(mid*mid <= A and (mid+1)*(mid+1) > A):
return mid
elif mid*mid > A:
high = mid-1
else:
low = mid+1
return -... |
7b3b37aee8b4f1e2b6ec5df4337bbc9e59c9043a | JordonZ90/ListPracticePython | /CatsList.py | 552 | 3.984375 | 4 | cats = []
while True:
name = input(f"Enter the name of the cat {str(len(cats) + 1)} or nothing to stop ")
if name == '':
break
cats += [name]
print("The cat names are:")
for name in cats:
print(f"{name}")
# for i in range(len(cats)):
# print(f"Index {i} in cats is {cats[... |
cac18ad80778080b5d8a258b19f50dec4b0c4e5f | olyasorokina/InterviewBit | /week2_after/hashing/anagrams.py | 358 | 3.53125 | 4 | def anagrams(self, A):
solutions = {}
for i in range(len(A)):
word = A[i]
sorted_word = "".join(sorted(word))
if solutions.get(sorted_word, []) == []:
solutions[sorted_word] = []
solutions[sorted_word] += [i + 1]
else:
solutions[sorted_word] +=... |
391cea4dac24f80ed6ffae11df2a76a9ada578bd | Heez27/AI_Edu | /Day11-class2/practice02.py | 218 | 3.8125 | 4 | #키보드로 정수 수치를 입력 받아 짝수인지 홀수 인지 판별하는 코드를 작성하세요.
a = int(input('수를 입력하세요: '))
if a%2==0:
print('짝수')
else:
print('홀수') |
086d9d32e451b30330e9d65eccd4e65d61d839c5 | ToshineeBhasin/space_invaders | /game_practice/enemy_attack.py | 1,892 | 3.609375 | 4 | '''
Created on 19-Jun-2020
@author: Toshinee Bhasin
'''
import random
import pygame
from builtins import *
#initialize the pygame
pygame.init()
#create the screen
screen = pygame.display.set_mode((800, 600))
#uploading player image
playerImg = pygame.image.load("spaceship.png")
playerx = 370
play... |
a6046264a4497f14cebf410f1efd6138dcfd7faf | hperezv/100DaysofCode-Python | /Day-095/assertion-1.py | 727 | 4.5 | 4 | #!/usr/bin/env python3
"""
Write an assert statement that triggers an AssertionError
if the variables `eggs` and `bacon` contain strings that are the same as each other,
even if their cases are different.
(that is, 'hello' and 'hello' are considered the same,
and 'goodbye' and 'GOODbye' are also considered the same).
... |
00c2405863724f7181b2efc16e355630d053d118 | UltraMarine107/Data-Clustering | /Clustering/Data.py | 1,532 | 3.515625 | 4 | '''
Get data for all analysis practice
MBT: March total bill, which represents the amount of service
that customers purchase
emp: Employee number, the size of customer companies
'''
import csv
import codecs
from matplotlib import pyplot
import math
def get_data():
# Read csv file
csvFile = codecs.open... |
1d5ebb9e976d058fb691b1e19e4aed44be1c203c | RobinROAR/CommonAlgorithm | /leetcode-python/sort/170_LargestNumbers.py | 1,385 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###### 179. Largest Number
#Given a list of non negative integers, arrange them such that they form the largest number.
#Input: [10,2]
#Output: "210"
#
#Input: [3,30,34,5,9]
#Output: "9534330"
#Note: The result may be very large, so you need to return a string instead of ... |
a44c747df368838302b441aff694f779b0d0d53f | thinthinzarsoe/BootCamp2 | /Variable.py | 1,314 | 3.921875 | 4 | Variable.py
>>> 2 + 2
4
>>> 50 - 5 * 6
20
>>> (50 - 5 * 6) / 4
5.0
>>> round(5.0)
5
>>> 5.123456
5.123456
>>> round(5.123456,2)
5.12
>>> 17 / 3
5.666666666666667
>>> 17 // 3
5
>>> 18 // 4
4
>>> 20 // 5
4
>>> 17 % 3
2
>>> 17 * 4 % 3
2
addition = 75 + 25
subtraction = 204 - 204
multiplication = 100 * 0.5
division = 9... |
d70c3b3377948fc2cb19463b1057d1b85ffcb7f7 | vivekanandabhat/PYTHON-LEARNING | /S01Q03_mult_table_user_input.py | 814 | 4.5625 | 5 | """ To Print multiplication table of a number which the user provides.
"""
def get_number():
""" This function fetches the number from user
This function also fetches the number upto which the table has to be printed
"""
number=raw_input("Enter the number for which multiplication table needs... |
1048bed1cdbf7bb84ac858035fd335719595608b | alifa-ara-heya/My-Journey-With-Python | /day_15/forloop.py | 1,477 | 4.5 | 4 | # Day_15: August/11/2020
# In the name 0f Allah..
# Me: Alifa
# From: Book : Python for everybody
# Chapter:5 (Iterations)
friends = ['joseph', 'glenn', 'sally']
for friend in friends:
print("Happy new year:", friend.title())
print("Done!")
# Counting and summing loops:
# to count the number of items in a list,
c... |
8e20099eda7783a8896319f42acf48789abecf7d | PBarde/ASAF-playground | /examples/simple_ffa_run.py | 2,070 | 3.6875 | 4 |
'''An example to show how to set up an pommerman game programmatically'''
import pommerman
from pommerman import agents
def print_state(state):
for key in state:
print(f'{key} : {state[key]}\n')
def main():
'''Simple function to bootstrap a game.
Use this as an example to s... |
026e12ed5a2d5de8b333b338f633653df400ced1 | makkaba/training | /quiz/dynamic.py | 736 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
나누기2
나누기3
빼기1
이 세가지의 연산만 가능할 때 n을 1로 만드는 최소경우의 수를 리턴하라.
ex) 10인 경우 1을 먼저 빼는 것이 최소경우임.
'''
d = [0]*100
def shortestNum(n):
temp = 0
if n == 1:
return 0
if d[n] > 0:
return d[n]
d[n] = shortestNum(n-1) + 1
if n%3 == 0:
temp = shortestNum(n/3)... |
6967d87d1452848ebcc0d2b22d821aa769212076 | DayGitH/Python-Challenges | /DailyProgrammer/DP20170811C.py | 1,760 | 3.890625 | 4 | """
[2017-08-11] Challenge #326 [Hard] Multifaceted alphabet blocks
https://www.reddit.com/r/dailyprogrammer/comments/6t0zua/20170811_challenge_326_hard_multifaceted_alphabet/
# Description
You are constructing a set of N alphabet blocks. The first block has 1 face. The second block has 2 faces, and so on up
to the N... |
fc8246339d950931d80cb07a0612ea1f7ba6e8ea | almeidaalijessica/meus-arquivos-pessoais- | /ex014.py | 120 | 3.734375 | 4 | c=float(input("informe a tempretura em c"))
f=((19*c)/5)+32
print("a tempretura de {}*c correspode a {}'f'".format(c,f)) |
d4557ad07fd97d43b319ba32b1cfd9bd6e4fc395 | murongziying/python | /WeekStudyPython/countchar.py | 271 | 3.9375 | 4 | # /usr/bin/env python3
# coding=utf-8
import test
mystr = "hello world linux and ubuntu and chrome"
a = mystr.find("linux") # 第一次出现linux的索引号
print(a)
mylist = mystr.split(" ")
print(mylist)
for key in mylist:
print(key)
test.printname("hello")
|
88e72452dd4ecb2848ef7c13edd17c09c6e373af | gregsol/home | /py_course_2/1_Basics/1.6.7_Classes_Emulation.py | 940 | 3.5625 | 4 | # https://stepik.org/lesson/24462/step/7?unit=6768
mas = []
def depth(parent,child,all_classes):
global mas
mas+=all_classes[child]
for element_of_child in all_classes[child]:
depth(parent, element_of_child, all_classes)
#print(mas)
dict= {}
n = int(input())
for i in range(n):
classes =... |
6a4b4aecbdaee5ee8756ac866f77c7891166ffcb | DVNLO/learn_tensorflow | /basic_classification/basic_classification/basic_classification.py | 3,352 | 3.90625 | 4 | # The following is an exploration of tensorflow keras api using the fashion
# MINST data set. The tutorial is available:
# https://www.tensorflow.org/tutorials/keras/basic_classification
# TensorFlow and tf.keras
import tensorflow as tf
import matplotlib
from tensorflow import keras
# Helper libraries
import numpy as... |
18243b0742353ee3ee0dc28e3e4149d66e69b608 | angelaregine/Angela-Regine-M-I0320009-Abyan-Tugas4 | /I0320009_soal1_tugas4.py | 1,709 | 4.09375 | 4 | # Exercise 4.1
x = 15
y = 4
# Output: x + y = 19
print('x + y =', x+y)
# Output: x - y = 11
print('x - y =', x-y)
# Output: x * y = 60
print('x * y =', x*y)
# Output: x / y = 3.75
print('x / y =', x/y)
# Output: x // y = 3
print('x // y =', x//y)
# Ouput: x ** y = 50625
print('x ** y =', x**y)
# Exercise 4.2
x ... |
38f90ecb13d1a2c71873433079f66954a69cbc14 | KashifNiaz59/image_processing | /2_rotate_image.py | 709 | 3.875 | 4 | import cv2
img=cv2.imread("imageProcessing.jpg")
height,widht=img.shape[0:2]
# ****** ROTATION OF THE IMAGE ******
# to get the rotation matrix, we use getRotationMatrix2D() ----> cv2
# cv2.getRotationMatrix2D(center,angle,scale)
# center = center of the image
# angle = how much degree you want to rotate the image
... |
79bcc754f77a51cc8a20b13a0787f2a4de85f741 | Alexander-Igonin/Study | /Lesson2/Task3.py | 1,436 | 4.25 | 4 | """
В школе решили набрать три новых математических класса.
Так как занятия по математике у них проходят в одно и то же время,
было решено выделить кабинет для каждого класса и купить в них новые парты.
За каждой партой может сидеть не больше двух учеников.
Известно количество учащихся в каждом из трёх классов.
С... |
6d5355c1c3553544cd0b11962023dc292783860b | LiveSlowSkateFast/dev-tools | /dev_tools/json.py | 680 | 3.515625 | 4 | #!/usr/bin/env python3
"""Simple functions for working with JSON objects in Python"""
from __future__ import print_function
import json
def jdump(obj):
"""Convert a data object in pretty JSON format"""
obj = json.dumps(obj, indent=4, sort_keys=True)
return obj
def pprint(obj):
"""Print a data objec... |
0416f2a71a84f25b1a43338dd5811f1e68bbc891 | harihavwas/pythonProgram | /Fundamenta_programming/datatypes.py | 217 | 3.859375 | 4 | #____Python Datatypes____
#__1. str...string
a="hello"
print(a)
print(type(a))
#__2. boolean
b=True
print(b)
print(type(b))
#__3. Numeric
c=10
print(c)
print(type(c))
#__4. float
d=10.8
print(d)
print(type(d)) |
08630d7806a61e5ffa145a12578c0e01c8f27865 | vikasdongare/Number-Guessing-Game | /Number Guessing Game tkinter.py | 10,885 | 3.984375 | 4 | # NUMBER GUESSING GAME
#
# Devloped By:- Vikas Laxman Dongare
# Versin:- 1.0
import tkinter as tk
import tkinter.font as font
import random
#set number of guesses to particular number
no_of_guesses = 10
#set hovers effects to the buttons
def playButtonHoverOn(e):
play_button['bg'] = '#c2ffdf'
... |
c0f03792ca212120407d43654159a9a8eaebc011 | lyqtiffany/learngit | /leetCodeLearning/findMaxTimeElement.py | 855 | 3.984375 | 4 | # 找出列表中出现次数最多的元素三种方式
from collections import Counter
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
collection_words = Counter(words)
print(collection_words)
#还可以输出频率最大的n个元素,类型为list
most_counterNum = collection_words.most_common(3)
... |
0aba1816d2bde4e3f5bbcd589d8ed702fd608769 | gitktlee88/MPS-project | /tests_mytest/primes.py | 1,083 | 4.28125 | 4 | """
A prime number is a whole number greater than 1 whose only factors are 1 and itself.
If a number n is not a prime, it can be factored into two factors a and b: n = a * b
If both a and b were greater than the square root of n, then a * b would be greater than n.
So at least one of those factors must be less th... |
cbb3fa72ca819303a142414dc1786068c6f1a2c3 | wmaxlloyd/CodingQuestions | /Recursion/strobogrammatic.py | 844 | 4.1875 | 4 | # A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
# Write a function to determine if a number is strobogrammatic. The number is represented as a string.
# For example, the numbers "69", "88", and "818" are all strobogrammatic.
# Find all strobogrammatic of l... |
2583b07ca74425d66e09eaf5fc2edc252c4dec39 | viswan29/Leetcode | /Greedy/distribute_candies.py | 1,546 | 4.03125 | 4 | '''
https://leetcode.com/problems/candy/
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What i... |
77bdaedf9479c0d781a48ba230a75fd254952b1a | johnny-cy/FLASK | /flask_demo/app2.py | 1,821 | 3.859375 | 4 | """
說明:
使用Flask_API套件,無發現其與原生Flask使用區別,看點是request的使用方式,可獲取headers、post body、query params。
這範例是models放在db.py,使用前先引用進來。包括app跟db及User表
安裝:
Flask==1.1.2
Flask-API==2.0
"""
from flask import request, url_for, jsonify
from db import db, app, User
@app.route('/api/<name>/<location>', methods=['GET'])
def create_user(name, l... |
a3c458a74e7b0b62ab2ad61a0c4e56a644238d3b | ankitrana1256/LeetcodeSolutions | /MaximumNoOfBalloons[56ms].py | 981 | 3.671875 | 4 | class Solution(object):
def maxNumberOfBalloons(text):
flag = True
counter = True
count = 0
a = {}
for i in text:
if i not in a:
a[i] = text.count(i)
word = "balloon"
word2 = "".join(list(set(word)))
while f... |
1ef43ce1db7a963a629c5be4ad16fd22dd45e195 | Carolinas-dsantos/LP1-praticas | /NPC1/QUESTAO13.py | 387 | 3.625 | 4 | #Faça um programa para escrever a contagem regressiva do lançamento de um foguete.
#O programa deve imprimir 10, 9, 8..., 1, 0 e "Fogo!". Detalhe, o cronômetro está quebrado e pula os números pares..
from time import sleep
import os
x = 10-1
while x > 0:
for contagem in range(2):
sleep(1)
print(... |
868d69c8952d4b89249f5863c55783c806e15245 | managorny/python_basic | /homework/les03/task_1.py | 937 | 4.375 | 4 | """
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
"""
def my_func(x, y):
return x / y
try:
print("Укажите числа для операции деления")
first_num = float(input("Введите пе... |
2cf389cc76f117a8a9c9e66f9d8399779f636c92 | Djheffeson/Python3-Curso-em-Video | /Exercícios/ex074.py | 297 | 3.71875 | 4 | from random import randint
tup = (randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9))
print('O os números sorteados foram: ', end='')
for n in tup:
print(f'{n}', end=' ')
print(f'\nO maior valor sorteado foi {max(tup)}')
print(f'O menor valor sorteado foi {min(tup)}')
|
1acd6196b95f9ef03739ff82f05475f5f9d29159 | JaneShi99/interview-problems | /python-interview-book/Q16-1-p.py | 593 | 3.75 | 4 | def climb_stairs(n,k):
"""
construct an array of size n, called dp,
where dp(i) records the number of ways to reach there
if i = 1 then return 0
if i <= k return :
1 + loop through dp[1]+...+dp[i-1]
if i > k return:
loop through dp[k-n]+....+dp[k-1]
"""
... |
dd105c45222472909f4e9a424bef6a1d0c7278fe | andsus/python | /raindrops/raindrops.py | 442 | 3.53125 | 4 | rain = { 3: 'Pling', 5: 'Plang', 7: 'Plong'}
def convert(number):
# Using list comprehension
# result = [ rain[factor] for factor in [3,5,7] if number % factor == 0 ]
# Using python 3.8, that support ordered dictionary
result = [ v for k,v in rain.items() if number % k == 0 ]
# for factor in [... |
76d01469ce2974c5ca5a80e6f6d76502145087b6 | dan-sf/leetcode | /univalued_binary_tree.py | 687 | 3.625 | 4 | """ Problem statement: https://leetcode.com/problems/univalued-binary-tree/ """
import lib.tree_util as tu
class Solution:
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def _is_unival(node, val):
if node is not None:
if ... |
aba329a33b1ef3a55473c45a2381e94c0f60d9dd | haandol/algorithm_in_python | /search/binsearch.py | 621 | 4.125 | 4 | # https://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html#analysis-of-binary-search
def binsearch(L, target, start, end):
while start <= end:
mid = 1 + (start + end - 1) // 2
if L[mid] == target:
return mid
elif L[mid] < target:
start... |
9076163295e749791313d8a3ea12d23da057f8a4 | Priscila601/CEC-PYTHON | /funcion.py | 205 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 18:35:58 2020
@author: CEC
"""
def message():
print("Enter a value: ")
message()
a=int(input())
message()
b=int(input())
message()
|
2b15686160a49b920ebb603909c060eb752633f2 | agb2k/Scanner-Compiler-Design | /scanner2.py | 2,449 | 4.34375 | 4 | # Scanner/Lexer built with NLTK library
from nltk.tokenize import word_tokenize
# Allows the user to select the filename they would like to scan
print("Enter Filename: ")
file = input()
# Opens the file selected by the user
f = open(file, "r", encoding='utf-8')
code = f.read()
tokens = word_tokenize(code)
# Deals w... |
59fdbbb7052812672e5d896c808b1e01e32f4515 | mastermind2001/Problem-Solving-Python- | /string_compression.py | 760 | 4.375 | 4 | # Date : 02-06-2018
# String Compression
import re
# main function for string compression
def string_compression(string):
"""
:param string: a string
:return: compressed string
"""
# compressed string
new_string = ''
while len(string) != 0:
new_string += string[0] + str(string.co... |
0c4dfa1a4bb3df7e3cb897522051ab3a83b67eba | unknownboyy/GUVI | /program18.py | 251 | 3.828125 | 4 | import time
while True:
_seconds=int(time.time())+5*3600+30*60
seconds=_seconds%86400
hour=seconds//3600
seconds=seconds%3600
minute=seconds//60
seconds=seconds%60
print(hour,'H ',minute,'M ',seconds,'S ')
time.sleep(1) |
5b2448882d128e8d4287eedcb6f745a26e6f0b1f | vicety/LeetCode | /python/interview/2023-fulltime/huawei/1.py | 1,412 | 3.8125 | 4 | # If you need to import additional packages or classes, please import here.
# 听说都是 100 多分
# 多字段排序
import sys
def func():
nArea = list(map(lambda x: int(x), sys.stdin.readline().strip().split()))[0]
msgIdToUser = dict()
usersDi = dict()
for _ in range(nArea):
mid, _ = list(map(lambda x: int(... |
129461a1eba61b441400e3f19a7c35e8d1ea4d0f | baishuhuaGitHub/DeepLearning.ai | /Coursera-deeplearning.ai1-4/dnn_model.py | 1,699 | 4.09375 | 4 | # Function: model_training -- training L-layer neural network parameters: [LINEAR->RELU]*(L-1) -> [LINEAR->SIGMOID]
import numpy as np
import matplotlib.pyplot as plt
from initialize import *
from forward import *
from compute_cost import *
from backward import *
from update_parameters import *
def dnn_model(train_x,... |
d86481d3d0ceec4667f7c00b48ca2f0ff68f9e35 | JapoDeveloper/think-python | /exercises/chapter7/exercise_7_2.py | 979 | 4.4375 | 4 | """
Think Python, 2nd Edition
Chapter 7
Exercise 7.2
Description:
The built-in function eval takes a string and evaluates it using the Python
interpreter. For example:
>>> eval('1 + 2 * 3')
7
>>> import math
>>> eval('math.sqrt(5)')
2.2360679774997898
>>> eval('type(math.pi)')
<class 'f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.