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
6200eeede1e4b44712623d7536c88c3f4e3a7ec5
davro76/python_challenge
/PyPoll/Script/main2.py
2,963
3.5625
4
# Import dependencies import os import csv from collections import Counter # Define PyPoll's variables candidates_list = [] votes_per_candidate = [] total_voters = [] # file location pypoll_csv = os.path.join("/Users/rodneydavermann/Desktop/python_challenge/PyPoll/Ressources_1/pypoll.csv") # Open and read the csv f...
e1a9d197e6c056d02cdc481598e0d39d06f0f918
aliwo/ComputerNetwork
/homework3/webserver.py
3,990
3.515625
4
from socket import * class Webserver: def __init__(self, port, connection): self.port = port serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('', port)) serverSocket.listen(connection) self.serverSocket = serverSocket def run_forever(self): wh...
5cbe7b44640c6d2c81d1d791e9c5f057b59c03fc
huytranvan2010/Python-Tutotial
/OOP/inheritance.py
1,497
4.21875
4
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) # Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() """ Tạo c...
4b6365fbfbd13e9de05ce46149eb5be65347938f
uds5501/Story-Snatch
/errors.py
190
3.65625
4
def success(): print "DONE" while True: try: x=int(raw_input("Enter a number ")) success() except ValueError: print "Nopes"
6bf40d036388a3f1236d0f637ae7dcbfa7e28d26
aixpact/NLP
/Michigan - Text Mining/Text Mining Assignment+2.py
6,708
4.59375
5
# coding: utf-8 # --- # # _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._ # # ...
ce4d10cf9f66aacc8d37cc1caad42324b509bd2e
KocUniversity/comp100-2021f-ps0-Omajidov21
/main.py
99
3.65625
4
x = int(input("input x:")) y = int(input("input y:")) print(x ** y ) print(x**0.5) print("0080559")
7c3bf6d4e34bed66651ad22278f7124be1410ece
roduquen/42-AI_Bootcamp-Machine-Learning
/day00/ex03/count.py
816
4.0625
4
import string def text_analyzer(*parameter): text = "" if len(parameter) > 1: print("There is too much parameters.") return if parameter: text = parameter[0] while not text: print("What is the text to analyze ?") text = input(">> ") if len(text) == 1: char = " character:" else: char = " characters...
87763757b4832353bf360fd03131d24b64f6a71c
aav789/study-notes
/notes/reference/moocs/udacity/ud359-intro-to-data-science/final_project/gradient_descent.py
2,223
3.5
4
import numpy as np import pandas def normalize_features(array): mu = array.mean() array_normalized = (array-mu)/array.std() sigma = array.std() return array_normalized, mu, sigma def compute_cost(features, values, theta): m = len(values) sum_of_square_errors = np.square(np.dot(features, theta...
1c48d3d9796e5fddef72d94f7d908808b5eb173f
theoziyu/crawler_turbosquid
/utils.py
3,971
3.734375
4
import urllib.request import os class Utils: """Utils is a class for utility functions to change and get names of urls. It also has a function to check if a directory exists and create one if it does not exist. """ def __init__(self): try: print("Started creation of object type...
5bd63b007c1d016d87dcd4fc0e1be0e6b3376d4d
ohseoyoung1114/python
/p200808/varEx01.py
253
3.59375
4
from copy import copy data = [2,4,6] #copyData = data[:] copyData = copy(data) #id는 address를 찾는다. print(data) print(id(data)) print(id(copyData)) data[0] = 10 print(data) print(copyData) num1 = 10 num2 = 10 print(id(num1)) print(id(num2))
577d055da626e858cdce8cf3a65d06e926d1fb9f
Dangcn/python_learn
/regex_test/test01.py
1,067
3.984375
4
def deduplication(array): i = 0 if array.__class__ != list: print("it is not list") elif sorted(array) == array or sorted(array,reverse=True)==array: if len(array) == 1: return len(array) else: while i<len(array): j = i+1 while...
40917733d3f5c754297756d8e440bdb2c96d5607
calvinwalterheintzelman/Computer-Security-Algorithms
/Finding Primes/Fields.py
1,307
4.125
4
# Calvin Walter Heintzelman # ECE 404 # Homework 3 # Python 3.7.2 import os import sys print("Please enter a small digit: ") number = input() while(number.isdigit() is False or int(number) < 1): print("Error! Please only input a single small positive integer!") number = input() if(int(number)...
6d83abf938d8bf9513e9faabedbc9812d1737761
Frank-Junran-Yang/CS-2021-Summer
/Homework/NewBlackJack/new/main.py
1,823
3.5625
4
from blackjack import Card, Deck, Player, Game import csv class Hello: def __init__(self,deck,name): self.deck=deck self.name=name def __str__(self): return self.deck + self.name def __repr__(self): return self.deck + self.name def main(): user=Player('Fra...
464ae5156de0aa05ac852fd2f8a10322d44a5937
stainedhat/crypto
/ciphers/caesar.py
4,328
3.734375
4
from ciphers.utils import word_check, DEFAULT_MIN_PROBABILITY DEFAULT_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]\{}|;\':\",./<>?`~" def setup_charset(charset=None): """ Common functionality between the caesar functions so better to abstract it out :param cha...
8bbd7cf629e55bf5ed6f9ea1752f19baaebbd25d
harshmalik9423/SeleniumPractice
/Data driven testing/readExcel.py
486
3.5
4
import openpyxl path = r"C:\Users\harsh\Desktop\test.xlsx" # r for reading as raw string workbook = openpyxl.load_workbook(path) # sheet = workbook.get_sheet_by_name("Sheet1") # Extracts by name sheet = workbook.active # extracts active sheet print("Rows = ", sheet.max_row) print("Columns = ", shee...
c20b5ce6105620b80c6f3b9eee2c41208cf07e96
trux66/location_clock
/location_gui.py
3,237
4.125
4
#!/usr/bin/env python """ Name: location_gui.py Description: setup location GUI for testing History: """ import Tkinter as tk class locations_tk(tk.Tk): """ doc string to be defined """ def __init__(self, parent): tk.Tk.__init__(self, parent) # initiazlie the Tkinter GUI self.parent = pa...
42efd486938984bf55bb1699472c9abca16e3106
Pratik180198/Every-Python-Code-Ever
/factorial.py
480
4.375
4
num1=input("Enter number: ") try: num=int(num1) fact=1 for i in range(1,num+1): #Using For Loop fact=fact*i print("Factorial of {} is {}".format(num,fact)) #For Loop Answer def factorial(num): #Using Recursive Method if num == 0 or num ==1: return 1 else: ...
2fc7d0e8da23df889d164fb89d64482d59fcec92
ssmi4th98/python_test_class
/test_suite_add.py
823
3.65625
4
import unittest class TestMultiplication(unittest.TestCase): def runTest(self): #runTest is an attribute for the object and must be there. self.assertEqual((3*5), 15) class TestAddition(unittest.TestCase): def runTest(self): self.assertEqual((3+5), 8) class TestDivision(unittest.TestCas...
85b0ef7228314b2e62a51eb5a62958d9cf191a68
scottpdo/physcomp
/controller.py
2,684
3.515625
4
""" This program sends 10 random values between 0.0 and 1.0 to the /filter address, waiting for 1 seconds between each value. Example edited on 9-20-16 by Joseph Paetz for use in Intro to Physical Computing (60-223) at Carnegie Mellon University MODIFIED by eholthau and sdonalds for 60-223 F16. This version send...
2da714a6c9ae716bc364496d5a542d28d20846c7
aaychen/introPython
/logreader.py
2,799
3.84375
4
#Anna Chen #June 2, 2019 #zyLab 12.8 Security Threat Analysis #Reads passed file and stores information into a nested dictionary that holds IP addresses as keys and a sub-dictionary (of username lists and time lists) as values. ''' def extract_attacks(fname): #Extracts all the attackers and attacks from log # Indexe...
4deb8ccb8105fd9d2ada9458ca65f1332414b316
ramon-aprigio/tabela.campeonatoBR
/tabela.campeonatoBR.py
722
4.0625
4
times = ('Flamengo' , 'Vasco' , 'Botafogo', 'Santos' , 'Atlético - MG' , 'Atlético - PR' , 'São Paulo' , 'Palmeiras' , 'Grêmio' , 'Sport' , 'Fortaleza' , 'Coritiba' , 'Bahia' ,'Internacional' , 'Fluminense' , 'Cortinthians' , 'Bragantino' , 'Ceará' , 'Goiás' , 'Atlético - GO' , ) print('---- CLASS...
7e2a66e5587437205a88b90b6cfa07a56daa8008
uuljan/Part_2
/p2_task_3/p2_task_3.py
197
3.875
4
n = int(input("Введите число: ")) print('Следущее число ' + str(n) + ' это ' + str(n + 1)) print('Предыдущее число ' + str(n) + ' это ' + str(n - 1))
944aa125ff85c6e973e38f612b15faefbe4d885c
uuljan/Part_2
/p2_task_11/p2_task_11.py
137
4.09375
4
string = "Python is awesome, isn't it?" for i in string: count = string.count(" ") + 1 # print count print("The count is:", count)
74faf2e88599d608990ce1b79b3227d597502846
ldaniil32l/Numerical_method
/КРexp.py
887
3.609375
4
import matplotlib.pyplot as plt from math import exp # n - порядок разности n = 3 x = [-1, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1] # h - величина шага h = (x[-1] - x[0]) / (len(x) - 1) # В списки h и ans записаны значения функции ans = [] f = [] for i in x: ans.append(exp(i)) f += ans ...
72091d74c0555595d232f2cb84ff2d16f8007453
z21mwKYq/Python
/Lesson1/Algoritm/Tasks/task2_resheto.py
871
3.53125
4
import cProfile def fun_sieve (num): n = 1 while True: sieve = [i for i in range(n+1)] sieve[1] = 0 for i in range(2,n+1): if sieve[i] !=0: j = i*2 while j < n+1: sieve[j] = 0 j += i result = [i f...
e37e9102d0cf0c191ee4b78bee54a22920f510c4
z21mwKYq/Python
/Lesson1/les1_task5.py
376
4.1875
4
# Пользователь вводит номер буквы в алфавите. Определить, какая это буква. num = int(input("Ввдеите порядковый номер буквы")) if (num > 26 or num < 1): print("Нет буквы с таким порядковым номером") exit(0) print(f"Эта буква - {chr(num+96)}")
94735ece62d713325e31697856a1337050474cc7
z21mwKYq/Python
/Lesson1/Arrays/les3_tasks/les3_task3.py
874
3.6875
4
# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random size = int(input(f'Введите размер массива ')) a = [random.randint(-5, size+15) for _ in range(size)] print(f'Сгенерированный массив {a}') Maxind = 0 Minind = 0 smax = a[0] smin = a[0] for ind, i in enumerate(a): ...
017aaeb4d9240deb2d0bf790778dca6738d90dc9
Sunilsai1066/Hackerrank
/codEnigma7/SuperReducedString.py
256
3.609375
4
def superReducedString(s): Stack = [] for i in s: if(Stack and i==Stack[-1]): Stack.pop() else: Stack.append(i) Str = "".join(Stack) if Str: return Str else: return "Empty String"
c166cd8e7e0b62aec727fe086a5894a79ac9715e
peitruthxxx/learning_log_python
/w11_CoinClass.py
673
3.90625
4
import random class Coin: #大寫開頭 def __init__(self): #對物件作初始化,self像是C++裡的this self.side_up = "Head" def toss_coin(self): if self.side_up == "Head": self.side_up = "Tail" else: self.side_up = "Head" def random_toss(self): rand = random.randint(0,1) ...
25bd71ab62050ef3c965f97d91a6b640f812396b
peitruthxxx/learning_log_python
/order3.py
241
3.71875
4
count = 0 for i in range(1,5): for j in range(1,5): if i!=j: for k in range(1,5): if (j!=k) and (i!=k): print("i,j,k:",i,j,k) count+=1 print("總數:",count)
68f710e132605c543b0172a2047a888972896267
peitruthxxx/learning_log_python
/estimate.py
867
4.03125
4
import math def cal(x ,a): y = (x + a/x) / 2 return y def main(): a = float(input("Enter a value to find square root: ")) x = 3.0 prev = 0 curr = cal(x, a) while abs(prev - curr) > 0.0000001: print(curr) prev = curr curr = cal(prev, a) print(curr) ...
1dc6065bbe249c01dd7d86ff7b28a9da65921372
n3z0xx/tp_labs1-3
/14.py
263
3.78125
4
# 14. создать рандомн список из 20 целых (1,12) и срезами скопировать # его в другой с конца через один import random a = [random.randint(1, 12) for _ in range(20)] b = a[::-2] int(a) print(b)
709149ec888a0e68b31c9c78f93e214d34aa76a9
n3z0xx/tp_labs1-3
/33.py
384
3.640625
4
# 33. Заполните массив целыми числами начиная с нуля по строчкам, слева # направо, строчки обходятся сверху вниз. # 0 1 2 3 4 5 # 6 7 8 9 10 11 # 12 13 14 15 16 17 # 18 19 20 21 22 23 # 24 25 26 27 28 29 import pprint a = [[int(i) for i in range(j*6-6,j*6)] for j in range(1, 6)] pprint.pprint(a)
3b63c61174bd9183655baf55bb997aa6d53a7892
n3z0xx/tp_labs1-3
/31.py
350
3.984375
4
# 31. Заполните массив, записав в каждом элементе номер столбца, в котором он находится # Пример для n = 5, m = 6. # 0 1 2 3 4 5 # 0 1 2 3 4 5 # 0 1 2 3 4 5 # 0 1 2 3 4 5 # 0 1 2 3 4 5 import pprint n = 5 m = 6 pprint.pprint([[int(j) for _ in range(n)] for j in range(m)])
6a2554123a1ab931a59c1b3613abe60af8090d77
n3z0xx/tp_labs1-3
/42.py
619
3.9375
4
# 42. Создать множество сеткомпом из 10 букв русского, а фильтровать # так, чтобы было 5 гласных 5 согласных, всяких, конечно. import random rus = [chr(i) for i in range(ord("а"), ord("е") + 1)] + ["ё"] + [chr(i) for i in range(ord("ж"), ord("я") + 1)] a = ['а', 'е', 'ё', 'и', 'й', 'о', 'у', 'ы', 'э', 'ю', 'я'] # ...
55c96cfdd31b9f54f0cb21ec131aa948ee037526
n3z0xx/tp_labs1-3
/32.py
348
3.984375
4
# 32. Заполните массив, записав в каждом элементе номер строки, в которой он находится. # Пример для n = 5, m = 6. # 0 0 0 0 0 0 # 1 1 1 1 1 1 # 2 2 2 2 2 2 # 3 3 3 3 3 3 # 4 4 4 4 4 4 import pprint n = 5 m = 6 pprint.pprint([[int(j) for _ in range(m)] for j in range(n)])
1af7bd227c2e2a919baeda39d55c27d631b93908
maimumatsumoto/prac04
/list_exercises.py
2,474
4.28125
4
#//1. Basic list operations//# numbers=[] for i in range(5): value= int(input("Number: ")) numbers.append(value) print("The first number is {}".format(numbers[0])) print("The last number is {}".format(numbers[-1])) print("The smallest number is {}".format(min(numbers))) print("The largest number is {}".format...
347e9bec6171321968d9c32d3b8b86595805c809
Sandy4321/Scikit-image-book
/_build/jupyter_execute/Edge_operators.py
2,746
3.78125
4
# Edge operators ### Dr. Tirthajyoti Sarkar, Fremont CA 94536 Edge operators are used in image processing within edge detection algorithms. They are discrete differentiation operators, computing an approximation of the gradient of the image intensity function. import numpy as np import matplotlib.pyplot as plt from s...
078d86dd543094730650b6456c36c6857f7b8425
MichaelENGs/Falcons_Income_Estimator
/src/CSE578Project_JitengXu_Visuals.py
3,276
3.5625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np from collections import Counter import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') df = pd.read_csv("readonly/adult.txt", header=None, sep=", ") df.columns = ["age", "workclass", "fnlwgt", "educat...
16519cd7a5ca337c139da4a9adeab8c6cc5bf70b
BrianNguyen214/PathPlanningPractice
/RRT/modules/RewireTest2.py
4,749
3.75
4
import pygame as pg import time # perf_counter returns a float that represents the time in seconds # we'll use it to record the run time of the algorithm from time import perf_counter # this allows you to generate a random number from a specified range from random import randrange as rand # turns out there's a math f...
baf5d69ea97a527e765fcfbd0ce8dfa9bb1a8da2
wbecher/rosalind.info
/008_computing_gc_content.py
1,569
3.734375
4
def load_fasta(filename): """ Open a fasta txt file and returns a formatted dict. Parameters ---------- filename Returns ------- A Formatted dict where the keys are the labels, and the values are the DNA strings. """ # open file with open(filename, "r") as arquivo: ...
7eb89d2127cf0ed14c4d844ef590564dc07ce2c6
regevino/NAND_EX6
/HackWriter.py
747
3.703125
4
class HackWriter: """ Writes HACK machine language code into a .hack file with a given name. """ def __init__(self, code, filename): """ Create a HackWriter object for some byte code. :param code: A 16-bit byte array containing Hack machine language code. :param filename...
8505415b05ed15e01410897e2a4d390515e616a1
mifiamigahna/ANN
/01.py
1,185
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 18 16:30:39 2019 @author: mifiamigahna """ import numpy as np import matplotlib.pyplot as plt #1 x = np.arange(-50, 51) plt.subplot(121) plt.plot(x, np.square(x)) plt.subplot(122) plt.plot(x, np.sqrt(x)) plt.plot(x, -np.sqrt(x)) #2 x = np.arange(-10, 11) def F...
00800d116906ee17de56403b971748d27a1d4e7c
c334706598/MIT-6.006-Introduction-to-algorithms
/merge sort.py
901
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu May 17 22:52:49 2018 @author: XIN """ import random def gen_1D(n): return [random.uniform(0,10) for _ in range(n)] def merge(A, B): lA = len(A) lB = len(B) if lA == 0: return B if lB == 0: return A res = [] iA =...
32aa4728228b484ee7688709d0afccabcda6b64e
Andrest07/26th-27th_Nov_2019
/Practice_Assorted_Problem/Num_14.py
1,026
4.15625
4
def makeForming(verb): if verb.endswith("ie"): verb = verb[0:len(verb)-2] + "ying" elif verb.endswith("e") and not verb == "be" and not verb == "see" and not verb == "flee" and not verb == "knee": verb = verb[0:len(verb)-1] + "ing" elif (verb.endswith("a") or verb.endswith("o") or verb....
8dcd674321458f81521b58d73c43f9cd786e71af
Andrest07/26th-27th_Nov_2019
/Practice_Assorted_Problem/Num_3.py
144
4.1875
4
import calendar def formatmonth(year, month): print(calendar.month(year, month)) formatmonth(int(input("Year: ")), int(input("Month: ")))
b490019d350ca9345f6b7ec09320369ce11be4e6
GustavoPT/interviewexercises
/codeforces/TooLong.py
397
3.640625
4
def wordConverter(longString): returnString = "" if(len(longString) > 10): firstChar = longString[0] lastChar = longString[len(longString) - 1] stringLength = len(longString) returnString += firstChar returnString += str(stringLength) returnString += lastChar ...
32423ae92b1b7d7ef3b5f16fd46ed0d0e6a53f34
LucasZapata/Misc
/calc_raices.py
2,278
4
4
num_list = list() def main(): while True: print("choose option: \n", "1: get root \n", "2: enter list \n", "3: get list root \n", "4: split list and get roots \n", "0: quit \n") textInput = str(input()) if textInput == '0': exi...
fc0efc7d395977cf7bb1334c0419a592a5ab18de
shantanu6201/Instagram-bot
/Instabot.py
3,294
3.546875
4
from selenium import webdriver #selenium module is used for web automation , webdriver is used for automation in Google Chrome import time from secrets import username from secrets import password #secrets.py file contains username and password of the user class Instabot: def __init__(self ,username,pa...
6914291dd367d497c870c1ad279053aa494621ed
misrab/homework
/tonyktan/python lab files/02_files_and_weather_lab.py
7,908
4.09375
4
''' Lab: Reading and Writing Files in Python ''' import csv ''' PART 1: Read in drinks.csv Store the header in a list called 'header' Store the data in a list of lists called 'data' Hint: you've already seen this code! ''' header = None data = [] <<<<<<< HEAD with open('data/drinks.csv', 'rb') as csvfile: ======= w...
b47ff9336d87e5e091ed5ac025deae8dea9ded95
kamalgirdher/MachineLearningAlgorithms
/pandas_input_tools/read_csv/read_csv.py
397
3.59375
4
#Code to read csv file using Pandasa import pandas as pd df=pd.read_csv('inp.csv') #df=pd.read_csv('inp.csv',error_bad_lines=False) #df=pd.read_csv('inp.csv', usecols=['Age','Name']) #df=pd.read_csv('https://ed-public-download.app.cloud.gov/downloads/Most-Recent-Cohorts-Scorecard-Elements.csv') #df...
8e22a1d209caa3ba766626656cdf3aa822b4a2a5
luisfcolg/FinancieraBonos
/models/User.py
1,196
3.5
4
import logging import traceback logging.basicConfig(level=logging.DEBUG, filename='events.log') class User: def __init__(self, id, role, username, password): self.id = id self.role = role self.username = username self.password = password def getId(self): return self.i...
4fc8aceaed09696b35673561d7d52b638418a8f2
ACEinfinity7/Fractions-PS
/gcd.py
617
3.546875
4
num_1 = 997 num_2 = 1 def find_gcd(a,b): a,b = abs(a),abs(b) if a == 0 and b == 0: return a if a == 0: return b if b == 0: return a while a != b: if b > a: b -= a else: a,b = b,a b -=a return a def recur_gcd(a,b): ...
ed8ab04ef3846c633b3cba5c6b02a54eb314f222
cassandrelepercque/TP1_Jeu-de-la-vie
/utils.py
949
3.578125
4
import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation def afficher_iterations(function, matrix): """Affiche les étapes du je de la vie sur 10 itérations.""" plt.figure(figsize=(11,5)) #affichage des figures des itérations plus lisible. plt.subplot(2, 5, 1) matrice_...
6345ea093f6a674e8b993f169b5d0a96107fa152
hman523/brutecipher
/brutecipher.py
724
3.828125
4
#Brutecipher: a program to test all rotations to decrypt a cipher #Author: Hunter Barbella (hman523) #Date: 1/17/19 import argparse def rot(code, num): newString = "" for i in range(0, len(code)): if code[i] is " ": newLetter = " " else: newLetter = "" + chr((ord(code[i])-97 + num)%26 + 97) newString = n...
d0e05ebcea5cba2da768a15ef8bf15ea0c65e97d
Wag2323/ThinkPython
/wordplay.py
3,130
4.09375
4
def count_letters(word, n): """Takes a word and counts if it has at least n number of characters""" if len(word) > n-1: return True else: return False def word_w_length(object, n): """takes an object holding one text word per line and returns a list of words that are at least n ch...
fe8333d3d7a00a12dbcc0130d00ecd2772dd79a0
peter-steiner/adventofcode-2017
/d-2.py
1,082
3.8125
4
#!/user/bin/env python3 -tt """ https://adventofcode.com/2017/day/2 """ import sys import os task="d-2" infile=task + ".input" def readInput(): with open('input\\' + infile) as file: data = file.read() file.close() return data def solve_a(): rows = readInput().split("\n") sum = 0 ...
e7da7c6882194f7b206b2ce5f69b67699fb1ed11
cyopse/codigos
/questao 9 cap 3.py
854
3.59375
4
import random import math def high(array): print('array criado: ', end = '') print (array) media = sum(array)/len(array) power = [] for num in array: power.append(num**2) desvio = (sum(power)/len(array)) - media**2 array.sort() print('array ordenado: ', end = '') print(array...
6e3eb22d742bfc94435b49109cfe88ad6ee772b1
Elenanikiforov/my_python
/random_letter1.py
374
3.515625
4
import random s = ["самовар","весна","лето"] p = random.choice(s) k = p.index(random.choice(p)) p1 = list(p) p1[k] = "?" p1 = "".join(p1) print(p1) l = input("Введите букву:\n") if l == p[k]: print("Победа!\nСлово:\n",p) else: print("Увы! Попробуй в другой раз.\nСлово:\n",p)
3233df03679d4c81333f0375da5f065e721b1c75
Elenanikiforov/my_python
/if_random_game.py
293
3.625
4
import random x=random.randint(1,4) y=int(input("Введите число от 1 до 4:\n")) if x==y: print("Победа!\n") elif x>y: print("Рез-т больше введенного числа\n") elif x<y: print("Рез-т меньше введенного числа\n")
7cea4c823ccc79e5eb8967767c58b0856a6e93d6
roblburris/derivatives-pricing
/scripts/black_scholes.py
1,390
3.65625
4
import numpy as np import scipy.integrate as integrate def black_scholes(spot, strike, interest_rate, volatility, time_mature): """ Uses Black-Scholes pricing model to determine the value of an option :param spot: current price of stock in question :param strike: given strike/exercise price fo...
0806acba3e3093ee23b5ebca67d64f4662d54a91
devyueightfive/Templates
/Singleton/Python/by_singleton_class.py
2,255
3.53125
4
class BadSingleton: # static variable value = 0 class ClassicSingleton(object): def __new__(cls): if not hasattr(cls, 'value'): cls.value = super().__new__(cls) return cls.value def singleton(cls): instances = {} def get_instance(): if cls not in instances: ...
ab4979856481185c0820d450fe33e147ab67b208
trm84/AI-Checkers
/main.py
2,870
3.59375
4
import pygame from pygame.locals import * #Tyler Matthews #4/18/19 #Global Variables (WIDTH, HEIGHT) = (480, 480) WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) xArr = [] oArr = [] lastIndex = '' #main function def main(): drawBool = False drawOBool = False (posX , posY) = (0, 0) pygame.init() # Prep...
96f1072460031e38a7f4577a94108c66735d1bdc
gagnongr/Gregory-Gagnon
/Program 2/Program_Two - edits.py
5,441
3.5
4
# CS101 # Program 2 # Gregory Gagnon # gmg634@mail.umkc.edu # # PROBLEM: Play "Lucky Sevens" until the player loses all money in the pot. Then give user # a mathematical report detailing the futility in playing a game of chance such # as "Lucky Sevens" at a casino. # # ALGORITHM: # 1. Impor...
d7a241d07e554b6b0b56913e51aa3a853ee5c6b9
gagnongr/Gregory-Gagnon
/Exercises/sum up odd ints.py
718
4.40625
4
# Sum up a series of even numbers # Make sure user input is only even numbers # Variable names without types are integers print("Allow the user to enter a series of even integers. Sum them.") print("Ignore non-even input. End input with a '.'") # Initialize input number and the sum number_str = input("Number: ") the_...
f2f7d2cf276dd84736e9163ace75e9e9c54cd2b2
gagnongr/Gregory-Gagnon
/Exercises/list.py
134
3.71875
4
numbers = [1,2,9] x = numbers numbers.sort() if x == numbers: is_ascending = True else: is_ascending = False print(len(numbers)
157415f4175114671ada7f20ed40154c531d9665
gagnongr/Gregory-Gagnon
/Exercises/Check Yourself.py
216
3.703125
4
a_float = 2.5 a_int = 7 b_int = 6 print(a_int / b_int) # Line 1 print(a_int // a_float) # Line 2 print(a_int % b_int) # Line 3 print(int(a_float)) # Line 4 print(float(a_int)) # Line 5
aae5e7b47a9b24b6f3e646f81fd28cfed4e26428
KhoaMinhLe/Unit_5_01
/Unit_5_01.py
704
3.875
4
# Created by: Khoa Le # Created on November 13 2017 # Created for ICS3U # This program picks 10 random numbers and calculates average. import ui def calculate_button_touch_up_inside(sender): # When user presses the button, picks 10 random and calculates average. from numpy import random random_number = []...
31d07aafbddb275691aa91ca2317ab2ea9dedb45
rhs369/dog_food_calculator
/food_calculator.py
1,632
3.625
4
NORMAL_FOOD_PERCENT = 0.95 TREAT_PERCENT = (1 - NORMAL_FOOD_PERCENT) LBS_TO_KG_FACTOR = 0.45359237 # Resting energy requirement factor based on life stage. life_stage_RER_factor_dict = { "Puppy: 0 to 4 months": 3, "Puppy: 4 months to Adult": 2, "Intact Adult": 1.8, "Neutered/Spayed Adult": 1.6...
a46568507e0cec211f9a4fc6542fc378b847e7ae
KolodkinPA/Labs-
/Python/Laba3.py
5,089
4.03125
4
# coding: utf8 import math import matplotlib.pyplot as plt #Спрашиваем пользователя хочет ли он запустить код print ("Вы хотите начать программу? Если да нажмите 1. Если нет нажмите 0") z=int(input()) xv= [] if z==1: #Задаем все переменные имеющиеся в коде print("Введите переменную a") a=float(input()) ...
9fc52b2e6a2a43c2aa277e491f72319e29ba6a68
CodecoolBP20161/python-pair-programming-exercises-2nd-tw-toti_aron
/listoverlap/listoverlap_module.py
469
4.1875
4
def listoverlap(list1, list2): common_elements = [] for i in list1: for j in list2: if i == j and j not in common_elements: common_elements.append(j) return common_elements def main(): list1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] list2 = [1, 2, 3, 4, 5, 6, 7,...
8eb1a225acb3b20cfc62f720ee60f66dd49c0417
wafflestudio/waffle-algorithm
/algorithm-interview/ch8/14/noaarhk_merge_two_sorted_lists.py
870
3.984375
4
from typing import List class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if (not l1) or (l2 and l1.val > l2.val): l1, l2 = l2, l1 if l1: l1.next = ...
a6d63cc18af45cb6b2afc32da1d907ccc5883065
wafflestudio/waffle-algorithm
/algorithm-interview/ch10/27/keepRainy_merge_k_sorted_lists.py
1,342
3.828125
4
# # LeetCode # ver.Python # # Created by GGlifer # # Open Source """ 641. Design Circular Deque """ from typing import List from heapq import heappush, heappop # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solut...
c78fb1e9fa5f2c4a9c53271ffd10a4b5e58177d4
wafflestudio/waffle-algorithm
/algorithm-interview/ch7/12/keepRainy_best_time_to_buy_and_sell_stock.py
567
3.765625
4
# # LeetCode # ver.Python # # Created by GGlifer # # Open Source """ 121. Best Time to Buy and Sell Stock """ from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: curr_max = prices[-1] max_profit = 0 for price in reversed(prices[:-1]): curr_m...
2730b2a1016f306936dcac3c3b44a3fd7194bac6
wafflestudio/waffle-algorithm
/algorithm-interview/ch8/14/keepRainy_merge_two_sorted_lists.py
1,299
3.78125
4
# # LeetCode # ver.Python # # Created by GGlifer # # Open Source """ 21. Merge Two Sorted Lists """ from typing import List import sys # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoList...
cefeb0dbe91e6489487b2c5b80c61e3a997c70d7
wafflestudio/waffle-algorithm
/algorithm-interview/ch10/27/guzus_merge_k_sorted_lists.py
773
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: pq = [] res = ListNode() head = res for i in range(len(list...
24851dd9d45c3b0ba2f516d65b65395d42449c67
wafflestudio/waffle-algorithm
/algorithm-interview/ch9/23/keepRainy_implement_stack_using_queues.py
1,203
4.0625
4
# # LeetCode # ver.Python # # Created by GGlifer # # Open Source """ 225. Implement Stack using Queues """ class MyStack: def __init__(self): """ Initialize your data structure here. """ self.que = [] self.tmp = [] def push(self, x: int) -> None: """ ...
65acd108dfe8efd2db816be15be69344c159ae14
DYasser/RandomNums_Python
/Random Number.py
4,447
3.78125
4
#Nabil Yasser #Python3~ #COLORS# import sys try: color = sys.stdout.shell except AttributeError: raise RuntimeError("Use IDLE") try: shell = sys.stdout.shell except AttributeError: raise RuntimeError("you must run this program in IDLE") import random def RESTART(): print("") shell.wri...
f12c754ab630f45dfab63003ac170323036f77a9
Ninjam06/Com-Sci-1-Pre-AP
/Lab Solutions/PS3/Finished/JhanjiI_Recommendation.py
1,716
3.703125
4
# Ishaan Jhanji # Recommendation.py ''' Begin Required variables section: ================================= Do not change the names of these variables at all. You may change the values on the right side of the equals (=) sign if you would like. For instance if you would like to have raw_input to be able to test differ...
b8f1f7cb80e9a9b4c08798e67ff6cc65c2dd109e
Ninjam06/Com-Sci-1-Pre-AP
/Lab Solutions/PS4/JhanjiI_Checkerboard.py
819
3.546875
4
# Ishaan Jhanji # Checkerboard.py import turtle turtle.speed(.5) def blackSquare(): turtle.color("black") turtle.fill(True) for i in range(4): turtle.forward(20) turtle.right(90) turtle.fill(False) turtle.forward(20) def redSquare(): turtle.color("red") turtle.fill(True)...
d384530c200d486f5be5f33bf93403e137a691bf
Kshitij-s/Alexa-Skill-Python-Quiz
/Lambda.py
29,360
3.625
4
# -*- coding: utf-8 -*- from __future__ import print_function import math import string import random GAME_STATE_QUERY = "QUERY" GAME_STATE_START = "START" GAME_STATE_HELP = "HELP" GAME_QUESTIONS_KEY = "gameQuestions" ANSWERTEXT_KEY = "correctAnswerText" SCORE = 'score' CORRECTANSWERINDEX = "correc...
bb1a5113a69d17e09e5caf040f14555bfe143e7a
seanigami/Artificial-Intelligence-Labs
/lab2/TabuSearch.py
2,305
3.5
4
from lab2.Functions import * import time def tabuSearch(problem, args): startTime = time.time() best = initGreedySol(problem.size, problem) bestFitness, _ = problem.calcPathCost(best) bestCandidate = best globalBest = best globalFitness = bestFitness tabuDict = {str(best): True} tabu =...
263bf82e012bf39a84847e34861f3bde3e327a14
zac11/python-code-snippets
/Basics/add_nos.py
149
3.9375
4
## Get two integers print("Enter the first integer") a = int(input()) print("Enter second number") b= int(input()) print('Sum of a and b is',(a+b))
cbd6742367ceb7a1521789bdab1712519c7de750
benskee/codewars
/highest_scoring_word.py
407
3.515625
4
def high(x): w_list = x.split(" ") num = 0 ans = "" for w in w_list: x = 0 for l in w: x += ord(l)-96 if x > num: ans = w num = x return ans print(high('man i need a taxi up to ubud')) # 'taxi') print(high('what time are we cl...
9e94a5d2d064757ce8a793108ed2cc7e5bb21720
benskee/codewars
/hashtag.py
710
3.6875
4
def generate_hashtag(s): if not s: return False j = '#' + s.replace(" ", '') if len(j) > 139: return False else: return j print(generate_hashtag('')) print(generate_hashtag('Do We have A Hashtag')) print(generate_hashtag('Codewars')) print(generate_hashtag('Codewars ')) print(gene...
4980cf47f76ad1e56ba4026ff95274394e135336
benskee/codewars
/most_frequent_weekdays.py
939
4.0625
4
import datetime def most_frequent_days(year): day_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] start = datetime.date(year,1,1).weekday() start_list = day_list[start:] end = datetime.date(year,12,25).weekday() end_list = day_list[:end] ans...
f55ae7e36f0430c48633e5b032f0adf57c57c9b0
cserajeevdas/Python-Coding
/decorator.py
701
4.5625
5
#assigned a method to a variable and called the method # def f1(): # print("in f1") # x = f1 # x() #calling f2 from the rturn value of f1 # def f1(): # def f2(): # print("in f2") # return f2 # x = f1() # x() #calling the nested method through passed method # def f1(f): # def f...
8e893b4dfd81e2709a7e4a58a89c21aadf2d1916
cserajeevdas/Python-Coding
/calendar.py
165
3.5
4
import calendar # initializing the year # printing the calendar def main(): year = 2020 print(calendar.calendar(year)) if __name__=="__main__": main()
474102fdf57458bbeb37705d88a66af083db5377
mezga-alex/Laboratory-work-SFedU
/Computer Graphics/triangle_reflection/ui.py
4,139
3.78125
4
from tkinter import * from tkinter import messagebox # Check if triangle is not degenerate def is_triangle_check(x_a, y_a, x_b, y_b, x_c, y_c): is_triangle = False side_a = ((x_b - x_a) * (x_b - x_a) + (y_b - y_a) * (y_b - y_a)) ** (1 / 2) side_b = ((x_c - x_b) * (x_c - x_b) + (y_c - y_b) * (y_c - y_b)) ...
e952043dd1df951ec23fd055979671bf7d00e554
mezga-alex/Laboratory-work-SFedU
/Computer Graphics/polygon_processing/ui.py
2,381
3.515625
4
from tkinter import * import tkinter as tk from tkinter import messagebox import numpy as np import polygon as pln class MyDialog: def __init__(self): root = tk.Tk() top = self.top = Toplevel(root) top.geometry("400x200+400+300") Label(top, text="Enter vertices coordinates").pack()...
1ca439047d56d81e1b0d6ee1a7ff0ecbf43df4db
LucasEvo/Estudos-Python
/ex037.py
514
4.03125
4
# Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: # binário, octal ou hexadecimal. n = int(input('Escreva um número: ')) escolha = int(input('1 = Binário\n2 = Octal\n3 = Hexadecimal\nEscolha: ')) if escolha == 1: print('O número {} em bi...
0b090ffa1933333f2f91aa482af2dc5d98e1bdf6
LucasEvo/Estudos-Python
/ex024.py
307
3.9375
4
# Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "Santo". cidade = str(input('Qual cidade você mora: ')).strip().title() print('Se sua cidade começa com a palavra "Santo" vai aparecer "True" e se não começa vai aparecer "False".') print('Santo' in cidade)
fcdd687866bc08111a796b3f9650b6317c665049
LucasEvo/Estudos-Python
/ex022.py
690
4.3125
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: # 1- O nome com todas a letras minúsculas # 2- O nome com todas a letras maiúsculas # 3- Quantas letras ao todo (sem considerar espaços). # 4- Quantas letras tem o primeiro nome. nome = str(input('Qual seu nome completo? R: ')).strip() print('S...
6b5b9bcd8f937304043afb2012e9955b1ea34e90
LucasEvo/Estudos-Python
/ex044.py
844
3.875
4
# Elabore um programa que calcule o valor a ser pago por um produto, considerando o preço normal e condição de pagamento: # À vista dinheiro/cheque: 10% de desconto; # À vista no cartão: 5% de desconto; # Em até 2x no cartão: preço normal; # 3x ou mais no cartão: 20% de juros. valor = float(input('Valor do produ...
b15831b709e487f5fc2063bf8e9daf6336813419
LucasEvo/Estudos-Python
/ex031.py
497
4
4
# Desenvolva um programa que pergunte a distância de uma viagem em KM. Calcule a passagem, cobrando R$0,50 por KM para # viagens de até 200 KM e R$0,45 para viagens mais longas. distancia = int(input('Qual é a distância da sua viagem em KM? ')) if distancia <= 200: valor = distancia * 0.50 print('Você te...
ef9125e95cbccc44e74801d3370716e753f814a5
EmanoelFraguas/GitProject
/Python/InsertAndReadV2.py
661
3.703125
4
from itertools import chain def insert_file(filename): with open(filename, "w") as file: matrix = [] for i in range(2): row = [] for j in range(2): row.append(raw_input()) matrix.append(row) file.write("\n".join(chain(*matrix))) d...
d0f2195d42cd0c36b44d1fab022773f208faf99e
BaiMoHan/LearningPython_ING_202002
/Part5/local_function_test.py
944
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/14 15:50 # @Author : Baimohan/PH # @Site : https://github.com/BaiMoHan # @File : local_function_test.py # @Software: PyCharm def get_math_func(types, n): # python支持在函数内定义函数为局部函数,局部函数对外隐藏 # 定义一个计算平方的局部函数 def square(n): return n **...
1089725bb18a94128e2bf06a80ac8bd7ee1074db
BaiMoHan/LearningPython_ING_202002
/Part4/gobang.py
1,495
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/13 14:45 # @Author : Baimohan/PH # @Site : https://github.com/BaiMoHan # @File : gobang.py # @Software: PyCharm # def Count(radium): # from math import pi as p # C = 2 * p * radium # A = p * radium ** 2 # return C, A # # # if __na...
fc7be54cf3e16f683efdd14a28c3ad415ddcf19e
BaiMoHan/LearningPython_ING_202002
/Part5/multi_return.py
602
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/2/13 16:25 # @Author : Baimohan/PH # @Site : https://github.com/BaiMoHan # @File : multi_return.py # @Software: PyCharm def sum_and_avg(list): sum = 0 count = 0 for e in list: # 如果元素e是数值 if isinstance(e,int) or isinstan...
1f8af7b3a724de1a0744d57405c084945a52a940
pearvx/idea-portrait
/analysis/poll.py
5,105
3.609375
4
# libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.animation as animation # %matplotlib inline def replace_line(line_num, text): lines = open('feelings.txt', 'r').readlines() lines[line_num] = text out = open('feelings.txt', 'w') out.writelines(li...