blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
9401128be979ec64051bdd28229d602c91e28420
MCLACS/Python-Public
/Module3/3F-Nested.py
147
3.78125
4
for i in range(0,5): print("Outer loop: %d" % i) for j in range(0,3): print("\tInner loop: %d" % j)
2841f13de676c095b9e02490d15206ce4cdbae26
MCLACS/Python-Public
/Module6/6A-ReadWriteFile.py
642
4.0625
4
def main(): # opens a file for reading only... file = open('colors.txt', 'r') # a list to hold the colors... colors = [] # read each line and add it to the list... for line in file: colors.append(line) # don't forget to close the file... file.close() # opens a file for wr...
cb272af3f0738405ed50ecef7782ed403f8a81fd
MCLACS/Python-Public
/Module5/5D-ListAndStrings.py
798
3.78125
4
from Module5 import populateListFromUser def main(): s = "ABC123" myList = [] populateListFromUser(myList) print("Printing string has %d characters." % len(s)) print("Printing list has %d characters." % len(myList)) print("Printing string using range and index:") for i in range...
aa04fd2789623c8233df405aeb760541fde236fe
ruffyleaf/scrape_roar_reviews
/scrape.py
528
3.578125
4
import requests from bs4 import BeautifulSoup def scrapeURL(url, element, class_): """Takes in a URL, HTML element, and HTML class for scraping. Returns a beautiful soup element result set. """ #get the page r = requests.get(url) #take out the meat doc = r.text #prepare the soup ...
2cbb0cd96e3508eb90057e2d4be67395b56c5e69
fvilchez/Python_for_DataScience
/Series Temporales/Analizando estructura temporal/Analizando Estacionalidad/code.py
2,719
3.71875
4
########################## Analizando la Estacionalidad ######################## ################ Eliminando estacionaliad por diferenciación ################### # #Si somos capaces de detectar la estacionalidad, esta puede ser eliminada #simplemente mediante diferenciación. Es decir, si tenemos una estacionalidad #s...
6ffa9e58676b1f6471c34d935594e1e7e506b321
kawasaki2254/Python_100problem_practice_problem
/文字型/No.22.py
395
3.90625
4
''' 問題22.2つの文字列を入力して、重複する部分だけ 出力するプログラムを作成してください。 ''' word1 = input('1つ目の文字列を入力してください > ') word2 = input('2つ目の文字列を入力してください > ') r = '' for i in word1: if i in word2 and not i in r: r += i print(f'重複する文字列 : {r}')
48710ae1908c86542e4c7a6baac83f07bf90d7e3
kawasaki2254/Python_100problem_practice_problem
/リスト型/No.34.py
259
3.5625
4
''' 問題34.偶数のインデックス番号に絞り込んだリストを 出力するプログラムを作成してください。 ''' l = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] print(f'偶数のインデックス番号 : {l[1:: 2]}')
5a46bf9cfd02662f30fcb917c3b2fc6fcac41c5f
kawasaki2254/Python_100problem_practice_problem
/基本文法/No.3.py
329
3.546875
4
''' 問題3.好きな整数を入力して、以下のように 二乗値を出力するプログラムを作成しましょう。 例:3が入力された場合→9(3×3)を出力 ''' input_int = int(input('好きな整数を入力してください > ')) print(f'{input_int}の二乗値 : {input_int ** 2}')
00d25dbf8e4eb83bc96b95785f92ca4f5ff86461
kawasaki2254/Python_100problem_practice_problem
/リスト型/No.36.py
268
3.53125
4
''' 問題36.以下のように、2つのリストが格納されたリストを 出力するプログラムを「2行以下」で作成してください。 ''' l = [[5 * i + j for j in range(1, 6)] for i in range(2)] print(f'作成したリスト : {l}')
1ac82eb883120d44ee21d88145e489e71811572c
nishnareddy1/Trees-4
/k-smallest-bst.py
1,241
3.90625
4
# 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 # follow-up- if it were a binary tree use prioirty # queue for sorting and searching whose time complexity will be de...
b8235c4057ca747adb40f371b1db14b5d1d80e87
hat/leetcode
/april2020_challenge/productOfArrayExceptSelf.py
1,105
3.75
4
# Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. # Example: # Input: [1,2,3,4] # Output: [24,12,8,6] # Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (in...
e52e8cb4e02bc92e55099d80c4ddfcf2d015cd80
hat/leetcode
/april2020_challenge/contiguousArray.py
1,239
3.9375
4
# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. # Example 1: # Input: [0,1] # Output: 2 # Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. # Example 2: # Input: [0,1,0] # Output: 2 # Explanation: [0, 1] (or [1, 0]) is a longe...
2e1bc9f4f1cf875efcadb7ee3cc4d00a5d5d72f6
hat/leetcode
/may2020_challenge/findAllAnagramsInAString.py
1,131
3.765625
4
""" Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. """ class Solution: def __isAnagram__(self, s, p_map): ...
a234f96ed83a9bef64d003e4b90ee99dd5c7dcc9
HanhHongBui/CS50-Pset6-Sentiments
/sentiments/tweets
1,322
3.578125
4
#!/usr/bin/env python3 import os import sys import helpers from analyzer import Analyzer from termcolor import colored def main(): #accepts one and only one command-line argument, the screen name for a user on Twitter, if len(sys.argv) != 2: sys.exit("Usage: ./tweets screenname") else: name = s...
1a54906048c12d3133b1f6f8f8808837070a9cec
yangzhichang/program
/5.10-2.py
332
3.78125
4
i=1 while 1: n = input("Enter a number:") if n == 'done': break try: m = int(n) if i==1: min = max = m if max<m: max=m if min>m: min=m i=0 except: print("Invalid input") print("maximum:",max,"mini...
dfed06b4bbf51b8d57511753a08f09e26e3605d0
MuhammetEser/Class4-PythonModule-Week4
/4- Mis Calculator.py
2,631
4.28125
4
# As a user, I want to use a program which can calculate basic mathematical operations. So that I can add, subtract, multiply or divide my inputs. # Acceptance Criteria: # The calculator must support the Addition, Subtraction, Multiplication and Division operations. # Define four functions in four files ...
460d3cbf1d47f8e930872e25eefea74575536306
BrittanyRoll/PythonProject
/namegenerator.py
671
3.796875
4
import random def nameGen(): name1 = ["Chris' ", "Brittany's ", "Brandon's ", "Maddi's ", "Jen's ", "Matt's ", "Anna's ", "Courtney's ", "Hannah's ", "Falou's " ] adj = ["awesome ", "amazing ", "crazy ", "luxurious ", "wild "] place = ["restaurant", "office", "bistro", "cafe", "spot"] print(random.choi...
25950fd5d37b447e3534420878ca5419b39a901d
kkoocheki/sciann
/examples/example-fitting-1d-lstm.py
1,904
3.890625
4
''' # Curve fitting in 1D Here, a 1D curve fitting example is explored. Imagine, a synthetic data generated from \\\( \sin(x) \\\) over the range of \\\( [0, 2\pi] \\\). To train a neural network model on this curve, you should first define a `Variable`. A neural network with three layers, each containing 10 neurons...
be8d416b98c1befb472cd2af0496aa04c523e367
tanuj208/CipherForces
/challenges/RSA-4/encrypt.py
652
3.546875
4
from helper import * from padding import * import json import sys def get_keys(): """Extracts key from json file.""" with open('keys.json') as f: keys = json.load(f) return keys # Asymmetric encryption def encrypt(msg, public_key): n = public_key["n"] e = public_key["e"] msg = msg.encode() hlen = 20 # S...
0ff05f138b0d910a816a6d6ab4102983eb54d0a3
tanuj208/CipherForces
/encryption_codes/rsa_encoded/generate_large_prime.py
2,431
3.65625
4
# Large Prime Generation for RSA import random # Pre generated primes first_primes_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, ...
307de488259980632947dadc1804e7c0b9c92c3a
tanuj208/CipherForces
/challenges/RSA-1/encrypt.py
618
3.84375
4
from helper import * import json def get_keys(): """Extracts key from json file.""" with open('keys.json') as f: keys = json.load(f) return keys # Asymmetric encryption def encrypt(msg, public_key): n = public_key["n"] e = public_key["e"] en_msg = [] for i in range(0, len(msg)): en_msg.append(msg[i]) ...
b0dd182919235bc858adc107d5dccbc5acf22c43
mag389/AirBnB_clone
/tests/test_models/test_city.py
883
3.53125
4
#!/usr/bin/python3 """ unit testing file for States """ import unittest from models.base_model import BaseModel from models.city import City import uuid import json from datetime import datetime as dt class TestCity(unittest.TestCase): """class for unit testing Cities""" def test_bm1(self): """basi...
444256bdb2ae5b3aa29aec5acf93bfbb5875a8c7
ivanakonatar/MidtermExample
/task4.py
985
4.21875
4
""" =================== TASK 4 ==================== * Name: Convert To Upper * * Write a function `convert_2_upper` that will take * a string as an argument. The function should * convert all lowercase letter to uppercase without * usage of built-in function `upper()`. * Note: Please describe in details possible ...
86b14047bd1e0f705af2c6ce2548b528654fa59b
eomioo/hellogit
/alarm_clock.py
1,529
4.03125
4
#!/usr/bin/python3 # Filename: alarm_clock.py # make a alarm clock from tkinter import * import datetime import time import winsound def alarm(set_alarm_timer): while True: time.sleep(1) current_time = datetime.datetime.now() now = current_time.strftime("%H:%M:%S") date = current_time.strftime("%Y:%d:%m") ...
5cae2691b29e74917c55007405b67e7fcf1a60de
KennethNielsen/presentations
/python_and_beer_lesser_known_gems/ex6_namedtuple.py
2,143
4.21875
4
"""namedtuple example""" from __future__ import print_function from collections import namedtuple def arange(start, end, step): """Arange dummy function""" print('arange', start, end, step) def get_data_from_db(data_id): """Get data from db dummy function""" print('get_data_from_db', data_id) def ...
60d38f244c499b7ce44aecf92e9a90cfcae2b1c8
joku9100/RandomGameChooser
/start.py
1,290
3.703125
4
import random import os import pickle def randomizegame(): # print (list_games) amount_games = len(list_games) print (list_games[random.randrange(0,amount_games,1)]) if not os.path.isfile('gamedata.txt'): open('gamedata.txt','w') print("what's up") list_games = [] f = open('gamedata.txt','rb') while 1...
a3a3f3d4f105a421db7e4cfd07c8748b96ba0726
rash805115/bookeeping.frontend
/Python/pybookeeping/plugins/storage/interface/storage.py
459
3.578125
4
import abc class Storage(metaclass = abc.ABCMeta): @abc.abstractmethod def inhale(self, localpath, remotepath): """Copy file at localpath from local machine to remotepath at storage.""" return @abc.abstractmethod def exhale(self, remotepath, localpath): """Copy file from remotepath at storage to localpath ...
e4393132c4f2f5e68e9c82c468838017633fb42f
tejasten5/leetcode_practise
/Implement_strStr.py
230
3.65625
4
class Solution: def strStr(self, haystack:str,needle:str) -> int: if needle in haystack: return haystack.index(needle) else: return -1 s = Solution() print(s.strStr("hello","ll"))
19349cef03ee97555d420022fe42461717238902
tejasten5/leetcode_practise
/third_maximum.py
230
3.6875
4
class Solution: def thirdMax(self, nums: list[int]) -> int: nums = list(set(nums)) nums.sort() return max(nums) if len(nums) <= 2 else nums[-3] s = Solution() print(s.thirdMax([3,2,1]))
6f45844e85302bd24b018241aba0bcb75ee2ad8f
MrGreen1995/TPL_SMALL_PROJECT
/Product.py
1,325
3.546875
4
## Product Class ## class Product(object): def __init__(self, productCode, name, description, price, points): self.__productCode = productCode self.__name = name self.__description = description self.__price = price self.__points = points @property def pr...
604ab08cc6f2613dfab2764ac1ad7991bb5a0f2d
Bilalbc/CIMPL.py
/T098_image_filters.py
12,092
3.765625
4
# T098 P6 Task 2 Submission - Image Filters - 26/03/20 from Cimpl import * # Red Channel Filter - Author: Pietro Alvarez, 10115082 def red_channel(image: Image) -> Image: """Returns a new picture with a filter applying a colour of red on every pixel in the image, and removing the green and blue components of...
58ef041cd45d155935f4d30f46ec26e09c6b0c36
rarmand/project_graphs
/project2/DijkstraUpgraded.py
673
3.5625
4
edgeWeights = {'e1': 1, 'e2': 2, 'e3': 3} print(edgeWeights) def Neighbours(ver1, ver2): return 1 def Weight(ver1, ver2): return 2 def DijkstraUpgraded(StartVertexes, Tab): for v in StartVertexes: for w in Tab.v: if Neighbours(v,w) and (Tab[v].w + Weight(v,w)) < Tab[w].w : ...
de31bc761ac04f9c15ac4a74328d74b907fbd822
oliviamillard/CS141
/coinAdder.py
1,690
4.28125
4
#Olivia Millard - Lab 3a #This program will add up a user's coins based off of their input. #Short welcome message. print("Hello. This program will add up all of your change!\nCool! Let's get started.\n") """ This function, first, take input from the user asking how many coins they have. Next, it takes input for what...
e287eb63af5781999f148ef1aecf4dc2752e2ed1
a-ruzin/python-base2
/lesson_11/homework/task5.py
2,064
4.15625
4
""" 5. Продолжить работу над первым заданием. Разработайте методы, которые отвечают за приём оргтехники на склад и передачу в определённое подразделение компании. Для хранения данных о наименовании и количестве единиц оргтехники, а также других данных, можно использовать любую подходящую структуру (например, словарь). ...
ecfa094bfdd8d94b9f8fa23c01229bfe690b060e
a-ruzin/python-base2
/lesson_2/homework/task3.py
1,148
3.9375
4
""" Задание 3 *(вместо задачи 2) Решить задачу 2 не создавая новый список (как говорят, in place). Эта задача намного серьёзнее, чем может сначала показаться. """ source_list = ['в', '5', 'часов', '17', 'минут', 'температура', 'воздуха', 'была', '+5', 'градусов'] source_list_index = 0 while source_list_index < len(so...
026ab33806d41d40ca774ecdea2286e04730bf91
a-ruzin/python-base2
/lesson_5/homework/task2.py
1,354
4.0625
4
""" 2. * Задание 2. Выражение-генератор Создайте объект-генератор, выбирающий из функции-генератора rand_nums, написанного в предыдущем задании, только нечетные числа. Проитерируйтесь по этому объекту-генератору и выведите на экран для каждого значения на отдельной строке: порядковый номер (начиная с 1-го) и соответств...
62822586c745ae9ccea05554d297f5cddcf67586
a-ruzin/python-base2
/lesson_11/homework/task2.py
974
4.0625
4
""" 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль. Проверьте его работу на данных, вводимых пользователем. При вводе нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. """ class MyDivisionByZero(Exception): pass def my_div(...
52c44bc5f786ab5c741fce402acf47ee901c5818
a-ruzin/python-base2
/lesson_3/homework/task3.py
1,367
4.15625
4
""" 3. Написать функцию thesaurus(), принимающую в качестве аргументов имена сотрудников и возвращающую словарь, в котором ключи — первые буквы имен, а значения — списки, содержащие имена, начинающиеся с соответствующей буквы. Например: >>> thesaurus("Иван", "Мария", "Петр", "Илья") { "И": ["Иван", "Илья"], "М"...
4660fcbd2bc5df305214bffd4b4bc073abe6c1f5
samwata/Python-Is-Easy
/Dictionaries-And-Sets/dictionary-assignment.py
531
4.1875
4
#Songs dictionary Songs = {"Laugh Now, Cry Later":"Drake","Dark Lane Demo Tapes":"Drake", "Sounds from the Other Side":"Wizkid","Joro":"Wizkid","jeje":"Diamond Platnumz","A Boy from Tandale":"Diamond Platnumz", "Tambarare":"Eunice Njeri"} #Function to check if the Song exists in Songs dictionary while (True): Song...
c3f3d5d3fe2848324e9ef560b99bf6dc44bd4759
samwata/Python-Is-Easy
/If-Statements/If-statement-assignment.py
316
3.890625
4
#Create three variables Users, Issues and workers Users = "5" Issues = 3 WorkersNeeded = True #Comparing Users and issues by first converting the strings into integers if int(Users) >= 2 and Issues >2: WorkersNeeded = True print(WorkersNeeded)
cfc944dcbdd8b2d609ef6da2cb560d4869d807f1
rajk1344/I2G-Application
/app/Team.py
398
3.890625
4
class Team(object): def __init__(self, project, students, team_number): self.project = project self.students = students self.team_number = team_number #This function prints the team array def print_team_info(self): print('-----') print(self.project.project_title) ...
f62eb20f319326fdb3bbd8436c070c66b3e1cd1c
devilsec/resume-maker
/app/dict_tools.py
1,173
3.578125
4
from itertools import filterfalse from json import loads from typing import Dict, Tuple, List, Text KEYS = { "name": Text, "profession": Text, "phone": Text, "email": Text, "address": Text, "portfolio": str, "education": List, "experience": List, "skills": List, "languages": Lis...
2cc09f2ced03865a2715ac98b63cc131dbfae4f2
RaminParker/automatization_with_pyautogui
/draw.py
581
3.78125
4
import pyautogui pyautogui.click() # click to put drawing program in focus distance=200 while distance > 0: print(distance, 0) pyautogui.dragRel(distance, 0, duration=0.1) # move right distance=distance-25 print(0,distance) pyautogui.dragRel(0,distance,duration=0.1) # move down print(...
ea3418acdaee2b7c54bfc4ea1ebe71124072decc
YashKrSaini/basic-algorithms
/python/simple_calculator.py
825
4
4
def calculator(): print " List of the fuctions : " print " 1. Add " print " 2. Sub " print " 3. Mul " print " 4. Div " opt=input(" Enter your number => ") if opt==01: a=input(" Enter your first number : ") b=input(" Enter your second number: ") c=a+b print c ...
6cfe689695caa46288fa2eab66e90cacd8bf6a3a
angga30/Kejartarget
/python/2.variable.py
471
3.84375
4
#varible int nomer = 123 #varible string text = "power ranger" text2 = 'power tangert' text3 = ''' sepatula jambrong peraks ''' print("variable nomer "+str(nomer)) print("variable text "+text) print("variable text2 "+text2) print("variable text3 "+str(type(text1))) #di python memungkinkan untuk merubah tipe data var...
ac836d4891ffd5b7178e0c9ee1c992693feec932
Jattwood90/Python_Scripts
/viewDNS.py
1,053
3.5
4
import pandas as pd import json import csv import requests """Script written to automate searching of IP to domain pairings, using ViewDNS's paid API Results are processed through a Pandas df, before exported to a spreadsheet""" def main(file, url, apikey): with open('file') as csvfile: reader=csv.reade...
256f1cde0cb921c1ccc1d70cd224c23a35449bf7
yqu212/Projects
/Text/reverse_string.py
91
3.828125
4
string = raw_input('What is your string?') print('The reverst string is: ' + string[::-1])
fc0b45737c25f22552bdb5d588e25922a44fd6d9
JBAnderson5/kaggle
/titanic/IOData.py
2,851
3.625
4
#file loads data from the csv files import pandas as pd from sklearn.model_selection import train_test_split from sklearn import preprocessing verbose = True #determines whether we should practice by only using the training data or produce real results practice = True def practiceTraining(): global practice ...
12cab9369f50ba2a99af8f0b9184586cdeb1f3b9
teodorklaus/PyStudy
/additional/day2.Additional.8.py
280
3.9375
4
sum = float(input('Enter purchase amount: ')) if sum >= 1000: discount = (sum * 0.1) sum = sum - discount print ('You need to pay: ' + str(sum) + 'And your discount is: ' + str(discount)) else: print ('You need to pay: ' + str(sum) + 'Your didnot have discount!')
dbd8e8ab148840f8e8d45eec18d4c1d883643a33
teodorklaus/PyStudy
/additional/day2.Additional.4.py
227
4.09375
4
speed1 = float(input('Enter speed in KM/H: ')) speed2 = float(input('Enter speed in M/S: ')) print ('Speed KM/H more, then speed M/S.' if float(speed1 * 0.2777777777778) > float(speed2) else 'Speed M/S more, then speed KM/H.')
6c735d329b226153474d53de5730a5dc039b4df2
teodorklaus/PyStudy
/additional/day2.Additional.3.py
455
4.03125
4
num = int(input('Enter 3 numeral: ')) list1 = list (str(num)) if list1[0] == list1[1] and list1[1] == list1[2]: print ('Entered number has 3 the same numeral: ' + list1[1]) elif list1[0] == list1[1] or list1[1] == list1[2] or list1[0] == list1[2]: print ('Entered number has 2 the same numeral!') elif list1[0] ...
1565c55ec5fb3e17adb280790dc6237751b082c2
monci07/AI
/Primer bloque/1249134_primerEje.py
578
4.09375
4
#funcion que invierte la lista def rev(lista): reversa = [] #el ciclo empieza en el ultimo elemento de la lista, para ir decrementando mientras sea mayor a -1 for i in range(len(lista)-1, -1, -1): reversa.append(lista[i]) return reversa lista1=[] listaR=[] bandera = 's' #se empiezan a tomar dat...
dcb64944d7e25e53b62e2ee0de6ef2131aa14d49
monci07/AI
/Ejercicio2.py
342
3.796875
4
import numpy as np import matplotlib.pyplot as plt lx = np.arange(-10,10.1,0.1) a=int(input("Ingrese a:")) b=int(input("Ingrese b:")) c=int(input("Ingrese c:")) ly=a*np.power(lx,2)+b*lx+c plt.plot(lx,ly) plt.title("Las raices son: " + str(np.roots([a,b,c]))) print("Los valores fueron los siguientes: \n" + str(ly)) plt...
173ecefb3bd3070bff1b3cd83e91dab2dd2eb4bd
renan-suetsugu/WorkshopPythonOnAWS
/Labs/Loops/lab_6_step_1_Simple_Loops.py
545
4.125
4
#fruit = ['apples','oranges','bananas'] #for item in fruit: # print(f'The best fruit now is {item}') #numbers = [0,1,2,3,4,5,6,7,8,9,10] #for number in numbers: # print(f'The next number is {number}') #for number in range(10): # print(f'The next number is{number}') #for number in range(10): #...
11e733b184ab6c6fbecd8dff9c0f05d2153fb269
dongupak/Advanced-Python
/src/fibon_generator.py
242
3.59375
4
import time # generator version def fibon(n): a = b = 1 for i in range(n): yield a a, b = b, a + b start_t = time.time() for x in fibon(1000000): pass end_t = time.time() print('total time = ',end_t - start_t)
ff2b3ffb98400cd7fe746342318622dd09070f3c
jc566/SchoolProjects
/Python/DictionaryNotesPython/dictionary notes.py
2,004
3.90625
4
""" Dictionaries """ """ What data types exist? Strings Floats Integers Doubles Characters Boolean List - encased in brackets [ ] Tuple - ( ) encased in parenthesis dict aka Dictionary - encased in { } """ #Dictionary is key:value """ 2 items in dictionary definition """ #create empty dictionary print("create empty d...
33b209f2d18b16c659e8178c322205f5bd57a6b5
Gadiel09/Projetos_POO
/Sistema_Lanchonete.py
2,810
4.0625
4
import math class Pizza: def sabores_pizza(self): print(""" SABORES DE PIZZAS DISPONÍVEIS [ 1 ] - Havaiana [ 2 ] - Carne-de-Sol [ 3 ] - Queijo [ 4 ] - Frango """) def dados_pizza(self, nome, preco, validade, peso): self.nome = nome self.preco = prec...
2e9cd41fe4bfdea59b06da9f2bf84c6daea467a6
elinapiispanen/lajittelualgoritmit
/src/quicksort.py
1,054
3.578125
4
from datetime import datetime startTime = datetime.now() def partition(numeroarray, low, high): pivot = numeroarray[(low+high) // 2] print("Uusi pivot-luku on", pivot) i = low - 1 j = high + 1 while True: i += 1 while numeroarray[i] < pivot: i = i+1 j -= 1 ...
df4855ff04bb8631ba453360d5a25d2e17f5e65c
blackicetee/Python
/python_games/simple_games/TicTacToeGame.py
6,485
3.96875
4
# This program will implement a "Tic Tac Toe" game with the pygame import pygame from python_games.simple_games.TicTacToe import TicTacToe display_width = 400 display_height = 500 # RGB defined variables RED GREEN BLUE(RGB) # (0, 0, 0) means there is no red no green and no blue black = (0, 0, 0) # (255, 255, 255) mea...
2eb7b0407b50b50897d6c2b86626998069d8d882
blackicetee/Python
/python_games/simple_games/Reversi.py
42,530
3.640625
4
import numpy # TODO make this class a library of procedures - one procedure should return a random game situation # TODO Implements this file a production system for Reversi game situations? class Reversi: """Contains rules and logic of the board game Reversi. Winning condition of Reversi is to have the most t...
2a4dd3b8574142a991f73761bd43d6e2688c83a0
blackicetee/Python
/python_games/simple_games/MyValidator.py
451
4.125
4
"""This self written python module will handle different kinds of user input and validate it""" # This is a module for regular expressions see python documentation "Regular expression operations" import re class MyValidator: @staticmethod def is_valid_from_zero_to_three(user_input): regex_pattern = r...
33fb9923407ec0ef9358114711893f2085a87648
s6521990/python
/密碼鎖字典版.py
1,090
3.59375
4
from machine import Pin import time ans = (1,2,3) b = 0 input_num={'first_num':0, 'second_num':0, 'third_num':0} botton = {'button1':Pin(16,Pin.IN), 'button2':Pin(14,Pin.IN), 'button3':Pin(12,Pin.IN), 'button4':Pin(13,Pin.IN), 'button5':Pin(15,Pin.IN), ...
38b8fdbc9690816a5c3f275c9d643f52cd1386f0
theimgclist/100CodingProblems
/InterviewCake/challenge31_matchingparens/matchingparens.py
579
3.84375
4
def get_closing_paren(sentence, opening_paren_index): open_nested_parens = 0 position = opening_paren_index + 1 for position in range(opening_paren_index + 1, len(sentence)): char = sentence[position] if char == '(': open_nested_parens += 1 elif char == ')': if open_nested_parens == 0: return positio...
6bd65010e04d61311ccff521ad5aacfa15672ec3
theimgclist/100CodingProblems
/firecode/challenge33_reverseastring/stringreverse.py
138
3.671875
4
def reverse_string(a_string): return a_string[::-1] if __name__ == "__main__": result = reverse_string("hello") print(result)
89bbce3484168bc929adab65667e5f7e12e23781
theimgclist/100CodingProblems
/geeksgforgeeks/challenge15_palindromepartition/palindrimepartition.py
1,011
3.703125
4
# Created by Avinash on 16th Dec, 2017 import sys def process() : data = input("Enter the data") n = len(data) isPal = [[False for i in range(n)]for j in range(n)] isPal = palCheck(data) minSplits = palPartition(data,isPal) print("The minimum number of cuts required for palindrome partitioning is %d"%minSplits) ...
5e22f100609c2d56c4ee66b6799d5c6b61356220
theimgclist/100CodingProblems
/geeksgforgeeks/challenge11_cuttingarod/cuttingrod.py
842
3.984375
4
# Created by Avinash on 13th Nov, 2017 import sys def process(): n = int(input("Enter the length of the rod : ")) price = [ 0 for i in range(n)] print("Enter the price of different lengths of rod : ") for i in range(n): price[i] = int(input()) maxPrice = findMaxPriceDP(price,n) print("The maximum price that can...
30ecdccae18a9b4abd12e8e24c635bfa767d52bc
theimgclist/100CodingProblems
/firecode/challenge32_findrepeatednos/findrepeatednos.py
396
4
4
""" Created by Avinash on 8th Dec, 2018 """ def duplicate_items(list_numbers): list_numbers.sort() repeatlist = [] for i in range(1,len(list_numbers)): if list_numbers[i] == list_numbers[i-1]: repeatlist.append(list_numbers[i]) return repeatlist if __name__ == "__main__": re...
8190dd1f19c1c918cd16997aae5a2c0b77c60607
CoitThomas/Milestone_7
/7.1/test_string.py
480
4.3125
4
"""Verify the correct returned string value of a list of chars given to the funtion string(). """ from reverse_string import string def test_string(): """Assert the correct returned string values for various lists of chars given to the string() function. """ # Anticipated input. assert string(['H',...
8769486af9a9f7064cfe98f3c84e4e9197d788cf
bahulkark/CVND_P1_facial_keypoint_detection
/models.py
2,756
3.609375
4
## TODO: define the convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def ...
30fbd83798b20c1cd984799546bac6313d1c0ffa
Ursyyy/TestProjectForPlayRIX
/RaitingList.py
2,089
3.625
4
class RaitingList: def __init__(self): self.__averange = 0 #Среднее значение self.__items = [] #Список словарей def addItem(self, item): #Словарь в Python выглядит как {key: value} и при добавлении другого вида # Нужно преобразование в словарь # Следующая провер...
669c2f80647c3c51bb4e2b215d3765d58780cdc3
SimonCW/classic-cs-problems
/src/maze.py
2,349
3.609375
4
from dataclasses import dataclass from typing import List from enum import Enum import random class Cell(str, Enum): EMPTY = " " BLOCKED = "X" START = "S" GOAL = "G" PATH = "*" @dataclass class MazeLocation: row: int col: int class Maze: def __init__( self, rows: in...
939063da319468a799a1256d07a062e5f0ff1209
taisei-s/nlp100
/swings/swing02.py
434
3.703125
4
# coding:utf-8 """ 02. 「パトカー」+「タクシー」=「パタトクカシーー」 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ. """ def swing02(str1, str2): return ''.join(c1 + c2 for c1, c2 in zip(str1, str2)) if __name__ == "__main__": str1 = u'パトカー' str2 = u'タクシー' print(swing02(str1, str2))
f4ad480c6b9e7d8754506f060649b77b99049268
taisei-s/nlp100
/swings/swing09.py
1,051
4.15625
4
# coding:utf-8 """ 09. Typoglycemia スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.ただし,長さが4以下の単語は並び替えないこととする.適当な英語の文(例えば"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .")を与え,その実行結果を確認せよ. """ import random def shuffle_inside(word): ...
c7c16f1aafc45a7b1dc3b9328785dcf86ab01846
Amena-pu/Python-Basics
/ListAverage.py
128
3.71875
4
numbers = [1, 2, 3, 4, 5, 1, 4, 5, 6, 7, 98, 56] Sum = sum(numbers) average = Sum / len(numbers) print ("Average %i"%average)
430a851a1cd5628c34504762fa78ec72ab15f3e1
VN-LuisOrtiz/NewRoutingProgram
/Delivery.py
12,326
3.59375
4
# Luis Ortiz #000855626 import csv import datetime from ReadCSV import get_truck1, get_truck2, get_truck3, get_hash_table # Open Addresses File, read contents from it and store the data in a Addresses list. # O(1) with open("Addresses.csv", newline='', encoding='utf-8-sig') as addressesFile: addressesReader = csv...
81edf516ab7d5cce021b727504a49654c7afe479
Puk258/Fake-Nukes
/Buttons.py
4,965
3.734375
4
import pygame from pygame import * pygame.init() screen = pygame.display.set_mode((1366,705)) menuButtonFont = pygame.font.SysFont("calibri", 25) spawnButtonFont = pygame.font.SysFont("calibri",15) white = (255,255,255) grey = (150,150,150) lightgrey = (50,50,50) black = (0,0,0) red = (255,0,0) green = (...
2a5221fd6e832a2f4d842191fcae1a2ab4759a31
KevinGarciaR/proyectoIA
/VersionesPasadas/prueba.py
6,589
3.828125
4
"""Con la finalidad de aclarar mejor los conceptos cubiertos previamente, presentaremos ahora una sencilla aplicación del algoritmo genético a un problema de optimización: Un grupo de financieros mexicanos ha resuelto invertir 10 millones de pesos en la nueva marca de vino "Carta Nueva". Así pues, en 4 ciudades de las ...
980b85f1bb7a41772e562c3a4224b4bc5586ad47
RichardEmilMiklos/Permutationcalculator
/talents.py
1,081
3.703125
4
char_name = 'Kirez' talentrowlength = 3 talents = [1,1,1,1,1,1,1] text = '' def add_list_to_text(lst): global text talentstring = '' for i in range(0,len(lst)): talentstring += str(lst[i]) text += 'copy=' + char_name + '-' + talentstring + '\n' + 'talents=' + talentstring + '\n\n' de...
313947b60813bec8b6956a808f7c5ee1efed7618
scottwedge/code_hilfen
/ONLINE-KURSE/Become a Python Developer/5 - Learning the Python 3 Standard Library/code-training/3 - Python Input_Output/input_output.py
2,875
4.1875
4
#1 - Command line arguments #python3 input_output.py 0 1 2 #in CLI ist alles immer ein String import sys #um auf die CLI-Param zugreifen zu können sys.argv print("Number of arguments: " + str(len(sys.argv))) print("Arguments: ", sys.argv) #<- erstes Argument ist Name (bzw. Pfad der Datei) sys.argv.remove(sys.argv[...
b9fef56fb7e42afa69e1b71859d5a132b11b7660
scottwedge/code_hilfen
/ONLINE-KURSE/Become a Python Developer/5 - Learning the Python 3 Standard Library/code-training/2 - Pyhton Math/math1.py
3,151
3.71875
4
#1 - Trigonomentry, Ceiling, Floor and Constants import math # module muss man importieren math.ceil(10.10) #Methhoden und Variablen des Moduls benutzen mit math. #Konstanten print(math.pi) print(math.e) print(math.nan) # Non a number print(math.inf) #unendlich print(-math.inf) #-unendlich #trigonometrische Met...
52e700eccf6b8b453f6680c9a991b150774033e4
scottwedge/code_hilfen
/ONLINE-KURSE/Become a Python Developer/4 - Python Essential Training/code-training/11 - String Objects/string_objects.py
1,442
4.28125
4
# 1 - Overview of string objects #String sind Objekte # Strin-Methoden, print("TestString".upper()) print("TestString".swapcase()) print("TestString {}".format(4)) print('''Test Str ing {}'''.format(4)) s = "Test String {}" print(s.format(4)) class myString(str): def __str__(self): return self[::-1] s =...
0d1c20c06df04db38816871c02d442090d94ece0
scottwedge/code_hilfen
/ONLINE-KURSE/Become a Python Developer/1 - Programming Foundations Algorithmus/code-training/Beispiele/valuecounter_start_6-2.py
452
3.71875
4
items=["apple", "pear", "orange", "banana", "apple", "orange", "pear", "banana", "orange", "apple", "pear", "banana", "orange", "apple", "kiwi", "pear", "apple", "orange"] #TODO hach-Tabelle erstellen um Array-Elemente zu halten und sie zu zählen: counter=dict() #TODO über Elemente iterriereen und counter inkrementie...
c6f2e5fd3d86a2b4fc319b6d636ee80d2f0d6753
thomas-legrand/advent-of-code-python
/2016/day05/door_hash.py
2,048
3.53125
4
import hashlib PASSWORD_LENGTH = 8 def is_good_hash(s): return s.startswith("00000") def get_hash(s): return hashlib.md5(s).hexdigest() def compute_password(input_door_id): password = "" counter = 0 while len(password) < 8: h = get_hash(input_door_id + str(counter)) if is_goo...
c1e17a2816a9fcfeb9bbed909a497c8cbe1588f0
thomas-legrand/advent-of-code-python
/2016/day22/day22.py
740
3.640625
4
from collections import namedtuple NodeUsage = namedtuple('NodeUsage', ['name', 'used', 'avail']) def get_input(input_path): directions = open(input_path) rows = directions.readlines() nodes = [r.strip("\n").split() for r in rows[2:]] return {node[0]: NodeUsage(name=node[0], used=int(node[2][:-1]), ...
49e7d79cad13573d737e89ce71fc6d3bbd167314
thanosa/cs50-harvard-edu
/pset6_python_readability/readability.py
7,928
4
4
from cs50 import get_string import re SENTENCE_CHARS = [".", "!", "?"] WORD_CHARS = [".", "!", "?", ",", ";", ":", "\""] def main(): # Runs all the test test_all() # Gets the input text from the user. text = get_string("Text: ") # Calculates the grade and outputs it. grade ...
d14ba5df3da5e75c023c8d1f6dfabb95462747c2
devcodus/Python_Fundamentals
/lists.py
477
3.859375
4
'''x = [3, 0.4, "3", "hello", "world"] x.sort() print x''' # x = [99,4,2,5,-3]; # print x[:] # #the output would be [99,4,2,5,-3] # print x[1:] # #the output would be [4,2,5,-3]; # print x[:4] # #the output would be [99,4,2,5] # print x[2:4] # #the output would be [2,5]; # my_list = [0] # print any(my_list) # print...
cfa37b31ba41696ef5000fe24fe7b691e4c554f5
xpx31/codebase_python
/Data_structure/LinkedList_Double.py
1,152
3.5
4
""" Script Description:. Doubled linked list Created by Pengxiang Xu Date: Oct/14/2019 Time: 10:22 """ from Data_structure.ListNode import ListNode class LinkedList_Double: def __init__(self, node: ListNode): self.__length = 0 self.__head = node self.__tail = node def __iter__(self): node = self.head()...
c8b48cf793fac77fd158794c5cc1d41a064d8df9
rachemelendres/FTW3-Day3
/Exer3.py
377
3.859375
4
## Euler Exercise 3 - Largest Prime Factor def largest_prime_fac(number): n = number x = 2 prime_factors = [] while x <= n: if n % x == 0: prime_factors.append(x) n /=x else: x += 1 return "The largest prime factor of {} is {}.".format(number, ma...
ded278a456e224b49cb4eae50c8fa77390a5fadc
sakshigupta06/Python-Loops-and-Statements
/coins.py
200
3.609375
4
# true or false import turtle t = turtle.Turtle() t.width(100) coins = 1000 # This is the line we changed. rich = coins >= 1000 if rich: t.color("gold") else: t.color("silver") t.forward(0)
257a10e33e0df88debb4b7955f1cc072452a5639
maximizo/Stock-And-Election-Analysis
/election_analysis/main.py
2,110
3.734375
4
#import os module import os #import module for reading csv file import csv #set path for csv file csvpath = os.path.join('..', 'resources', 'PyPoll.csv') #set variables votes = 0 votecount = [] candidates = [] percentages = [] #open csv file with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimi...
9aa3769e8d1b00de684ac973a25c80d2cc6db24d
llduyll10/backup
/Backup/BigOGreen/big-o-on-tap/chuong-7/bai-2.py
88
3.734375
4
str = input() count = 0 for s in str: if '0'<=s<='9': count +=1 print(count)
bc58fb8b971f9a907786caac451b8d603a7ec1c0
llduyll10/backup
/Backup/BigOGreen/classPython.py
1,960
4.34375
4
#Create Class class MyClass: x=5 print(MyClass) #Create object p1 = MyClass() print(p1.x) #__innit__() function class Person: def __init__(self,name,age): self.name = name self.age = age p1 = Person("DuyNND",22) print(p1.name) print(p1.age) #Object METHOD #Object can also cotain method clas...
b1a30834dc10c8113cadbdcf1807a1b83ea8856e
llduyll10/backup
/Backup/BigOGreen/big-o/in-hang-rao.py
323
3.765625
4
#in hang rao n = int(input()) # in hang dau tien for i in range(1, n + 1) : print('*', end = '') print() #in 2 bien hang rao for i in range(2, n) : print('*', end = '') for j in range(2, n) : print(' ', end = '') print('*') #in hang cuoi cung for i in range(1, n + 1) : print('*', end = '') ...
8df1aad4a38f0fd69f4b3fe608a981b3ce0fd922
llduyll10/backup
/Backup/BigOGreen/demo.py
3,035
4.1875
4
print("Hello world!!"); #Dem so ky tu trong chuoi a = "Hello Duy"; print(len(a)); #Xoa khoang trang dau va cuoi b=" Hello, World "; print(b.strip()); #Chuyen thanh chu thuong print(a.lower()) #Chuyen thanh chu hoa print(b.upper()); #Replace ky tu print(a.replace('H','111')) #Cat chuoi ky tu print(b.split(','...
d82455f0fcc627170f37e448dc48b24c053ffe96
llduyll10/backup
/Backup/BigOGreen/big-o-on-tap/chuong-5/bai-5.py
278
3.6875
4
def isPrime(n): if n<2: return False for i in range(2,int(n**0.5)+1): if n%i==0: return False return True n = int(input()) a = list(map(int,input().split())) count = 0 for i in range(n): if isPrime(a[i]): count+=1 print(count)
7c4cd0979039b7a6c932480ed16e4b7396cf5851
llduyll10/backup
/Backup/BigOGreen/big-o/chuong-12/so-nho-nhat-linked-list.py
1,026
3.828125
4
class Node: def __init__(self, data=None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def insertTail(self, data): #Ky thuat them x vao cuoi linked list p = Node(data) #Khoi tao node p if self...
c8b9325556640a1427b485c8389f4991f9e9b98a
llduyll10/backup
/Backup/BigOGreen/big-o/chuong-12/chen-so-thu-tu.py
1,116
3.984375
4
class Node: def __init__(self,data=None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def insertTail(self,data): p = Node(data) if self.head == None: self.head = self.tail = p el...
a4758e539bc32445a30febc209d51f7d66c89926
llduyll10/backup
/Backup/BigOGreen/big-o-on-tap/chuong-4/bai-4.py
145
3.546875
4
def DemSoLuongChuSo(n): count = 0 while n>0: count+=1 n //=10 return count n = int(input()) print(DemSoLuongChuSo(n))
b08e836594c083fb7ce73c7cc4c48ea651975ed8
camilocs89/inventar-con-python
/código/tresenlínea.py
6,364
3.984375
4
# Tres en línea import random def dibujarTablero(tablero): # Esta función dibuja el tablero recibido como argumento. # "tablero" es una lista de 10 cadenas representando el tablero (ignora índice 0) print(tablero[7] + '|' + tablero[8] + '|' + tablero[9]) print('-+-+-') print(tablero[4] + '|' + ta...
45ecf4ff1ce77a3544f3260d7b9aaae534f4a281
cathuan/LeetCode-Questions
/python/q53.py
546
3.75
4
import numpy as np class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ min_value = 0 current_value = 0 current_max = -np.inf for num in nums: current_value += num current_max = max(...