blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7fc5bd0332223545031c6953082e38de95d1f870
MirandaRemmer/HB-Intro-Final-Project
/budget_cashTRACKS.py
5,022
4.0625
4
#budget listing class class Month(object): def __init__(self, month, year): self.month = month self.year = year self.income = "" self.budget = { #monthly budget 'Rent' : 0.00, 'Utilities' : 0.00, 'Transportation' : 0.00, 'Food & Dining' : 0.00, 'Bars' : 0.00, 'Shopping' : 0...
5ec707533cdb32c88573ccb9e72c5d28793c8d7c
hawk-praxs/ud120-projects
/datasets_questions/explore_enron_data.py
2,568
3.734375
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that perso...
ea889b8b7a8222f703ac29487df21df363a84b66
santhu2210/tasks_utils
/eval_post_fix.py
2,507
3.5625
4
def tokenList(s): s = s.replace(" ","") tokens = [] i = 0 while i< len(s): if s[i] == "*" or s[i] == '/' or s[i] == '^' or s[i] == "(" or s[i] == ")": tokens.append(s[i]) i = i+1 elif s[i] == "+" or s[i] == "-": if i > 0 and (s[i-1] >= "0" and s[i-1]...
a8400a3a1579e8bc155cb10c2875399bc7eafeef
satofromjapan/DojoAssignments
/Python/Fundamentals/find_characters.py
209
3.71875
4
l = ['hello','world','my','name','is','Anna'] char = 'o' def findChar(l, char): new = [] for element in l: if char in element: new.append(element) print new findChar(l, char)
2e87648ac27d94472fa651019536e0cb5f11c292
kadertarlan/python
/if_else_while.py
476
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- kul_ad="kader" kul_soyad="tarlan" while True: ad=raw_input(" kullanıcı adı:") soyad=raw_input( "kullanıcı soyad:") if ad==" " and soyad==" ": continue if ad==kul_ad and soyad==kul_soyad: print " programa hosgeldınız." break else: pri...
021af6b6becde8ad53387a5f24d7d63062a59efd
sir106/sandbox-python
/text-adventure/testclass-character.py
337
3.734375
4
from character import Enemy dave = Enemy("Dave", "A smelly zombie") dave.describe() # Add some conversation for Dave when he is talked to dave.set_conversation("What's up, dude!") # Trigger a conversation with Dave dave.talk() dave.set_weakness("cheese") print("What will you fight with?") fight_with = input() dave....
c9db5bb6a6ad5fa87224655561a5985c0858bef9
hcheng761/CodeWars-Kata
/Python/petethebaker.py
254
3.515625
4
def cakes(recipe, available): # TODO: insert code match = [] for name in set(recipe).intersection(available): match.append(available.get(name)/recipe.get(name)) if len(match) != len(recipe): return 0 return min(match)
077256e4517dec720937fdab1a8f5331264a7431
wh-acmer/minixalpha-acm
/LeetCode/Python/spiral_matrix.py
1,448
3.578125
4
#!/usr/bin/env python #coding: utf-8 class Solution: def _getList(self, start, row, col, matrix): cs = [] for i in range(col): cs.append(matrix[start][start+i]) for i in range(1,row): cs.append(matrix[start+i][start+col-1]) if row > 1: f...
0f075c6f0584644688e99cbadbb731778899fbdc
SheaJanke/ProjectEuler
/Problems 1-50/Task41.py
833
3.796875
4
# -*- coding: utf-8 -*- primeList = [] largest = 0 def getPrimes(max): primes = [] for a in range(2,max+1): primes.append(True) for a in range(0,int(max/2)): if primes[a] == True: for b in range (2*a + 2, max-1,a+2): primes[b] = False for a in range...
c8e016c763e84c5aa7031fe4329de15af178842e
wolf132132/data
/lecture_8.py
263
3.59375
4
import numpy as np #make a 2-d array arr1 = np.array([[1, 2, 3, 4], [8, 9, 10, 11]]) #two arrays multiplication arr2 = arr1 * arr1 #two array substraction arr3 = arr1 - arr1 #make a reciporcal arr4 = 1 / arr1 #assign an opponent to the array arr5 = arr1 ** 3
ec30c375efd16665e374f785a3ee60627b756adc
LuValhala/beginner_scripts
/6. regex ip&mail.py
585
3.796875
4
# -*- coding: utf-8 -*- """ Sipmle regional expression search and match excercise. Matching the IP and searching for mail. Ľuboš Valčo, april 2016 """ import re #optionaly: ip=input("Zadajte IP adresu:") ip = "78.99.245.194" findip=re.match(r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][...
2cbf107309f90428b05a5cf48fde2c032b48405c
jackspicer1229/CSCI4622-NLP
/data_exploration.py
1,592
3.5625
4
#You will need to install these packages to see the data import pandas as pd import numpy as np music_review_dataframe = pd.read_json("Digital_Music_5.json", lines=True) #Look at the columns in our dataset print(music_review_dataframe.columns) print() #How many reviews do we have? print("total # of reviews:") prin...
85368f0f52c3752a31f7ffbf83bd012cfa1a35b2
LuccaBiasoli/python-cola
/python_colas/set_unicos.py
248
3.59375
4
lista = [1 ,1 ,1 ,4 ,78 ,78 ,4,'foda','mcdonalds','foda','mcdonalds'] print(lista) print(set(lista)) #/// #set transforma tudo dentro unico vor = set('Mississipi') print(vor) #/// print(set('3 , 4 ,3 ,4')) print(f'sabia q ia dar isso {set(lista)}')
a1da7eaba857ccc96ca680854a8820c949e56a1c
lidxhaha/suisui
/evaluate_keras_augmentation.py
825
3.65625
4
# дһչʾ Data Augmentation Чij # ڴģCNN磬ҪһӺ Data Augmentation from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing.image import ImageDataGenerator from keras.models import Model import matplotlib.pyplot as plt from PIL import Image import numpy as np img1 = Image.open('3.jpg') img2 ...
887e26fd0226691737c146db71d9194f4e2edcc6
calebwebster/task-tracker
/version1/patch0/task.py
1,112
4.28125
4
"""Task - This class represents a task with a name, subject, priority, and a boolean for whether or not the task has been competed.""" class Task: """This class stores information about a task.""" def __init__(self, name="", subject="", priority=0, is_completed=False): """Initialize Task class, setti...
9aaa481c8829d4028dc444c009b8d22399446d9e
geordie-quiroa/AC
/Labs/Lab-3/quicksort.py
921
3.6875
4
from math import floor as f unsorted_array = [5,10,15,32,55,21,40,2,3,76,89,28,9,7] n = len(unsorted_array)-1 def quicksort(A, p, r): i = p j = r q = f((A[i] + A[j])/2) #print(A[i], A[j], q) while i < j: while A[i] < q: i+=1 while A[j] > q: j-=1 ...
0083a1185f08c07549e160accd40cf44ce2ec707
whitefly/leetcode_python
/二分/33_search_in_rotated_sorted_array.py
1,409
3.5625
4
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int 思入: 由于数组的形式有2种(正序和2个正序).所以需要写2种二分.普通二分和特殊2分 """ l, r = 0, len(nums) - 1 while r - l + 1 >= 1: mid = (l + r) // 2 if nums[mid...
50aeb142f08374f6833e759b339d6bbc489d9b60
AKozhemyako/chapter04_tasks
/temperature.py
1,258
4.4375
4
# Эта программа помогает лаборанту в процессу # котроля температуры вещества # Именованная константа, которая представляет максимальную # температуру MAX_TEMP = 102.5 # Получить температуру вещества temperature = float(input('Введите температуру вещества в градусах Цельсия: ')) # пока есть необходимость, инструктир...
c810c5291891d41bcc145c8d3c33d3887c1dbc2d
Chimmahh/partner
/util.py
771
4.25
4
""" Utitility methods """ import csv def load_choices(path, reversed=False): """ Load choices from a CSV file. The choices are expected to be a list of CSV pairs `v,k` where `k` is the short symbol value of the choice, and `v` is the human-readable value of choice. :param path: Path of the CSV fil...
707116be5bb4bec02e7a2c1f913dcd089594d935
saadbinmanjur/CodingBat-Codes
/Logic-1/cigar_party.py
478
4
4
# When squirrels get together for a party, they like to have cigars. A # squirrel party is successful when the number of cigars is between 40 and 60, # inclusive. Unless it is the weekend, in which case there is no upper bound # on the number of cigars. Return True if the party with the given values is # successful...
2bf97e8ec0570f269bae3e5aa70bc1b7906628e7
AnhquanNguyenn/PythonPracticeScripts
/Edit Distance Between Two Strings/distance.py
1,982
3.734375
4
def distance(s1, s2, lengths1, lengths2): # When s1's length is zero then the number of changes necessary to equal s2 is # the length of s2 if lengths1 == 0: return lengths2 # When s2's length is zero then the number of changes necessary to equal s2 is # the length of s1 if lengths2 == ...
4f71b08997a4618582201745405f7c27493d17c3
AugustLONG/Code
/CC150Python/challenges-masterCC50-Python-good/two-dimensional-array-number-exist.py
844
3.9375
4
''' Question: Given a two dimensional matrix where rows and columns are sorted in increasing order. Design an efficient algorithm that decides whether a number X appears in A. ''' rows = 5 cols = 5 count = 0 #Initialize matrix with increasing values def init(): global count count += 1 return count def S...
38531cc59bff253237282b49cf7026ae2c254057
anthonynguyen/aoc
/2016/17/solution.py
852
3.921875
4
#!/usr/bin/env python3 import collections import hashlib # up down left right def walls(path): inp = "udskfozm" d = hashlib.md5((inp + path).encode("utf-8")).hexdigest() return (d[0] in "bcdef", d[1] in "bcdef", d[2] in "bcdef", d[3] in "bcdef") # bfs without remembering visited nodes q = collections.deque([(0, 0...
ce4ece82ff03551de2934ea0bce12574f1b9834f
guillemontecinos/sfpc
/poetry/class_2/class1_4.py
336
3.8125
4
#http://www.gutenberg.org/cache/epub/61/pg61.txt with open('manifesto.txt') as infile: #text = infile.read() lines = infile.readlines() find = "capital" replacer = "Mark Zuckerberg" #text = text.replace(find,replacer) #print text for line in lines: if find in line: line = line.replace(find, repl...
7b6570674400f6a90aed61ea972f5c84edae7ee1
albertotb/solar
/src/utils/df_to_roll.py
3,195
4.0625
4
''' Functions to build df_roll (Each time step in a different index) and to transform it into numpy arrays ''' import numpy as np import pandas as pd def window_stack_forward(a, stepsize=1, width=3): """https://stackoverflow.com/questions/15722324/sliding-window-in-numpy""" return np.hstack(a[i:1 + i - width...
181d88d35953e153207d96adc74d76dc52f96107
Areid0093/PythonMiniProjects
/PythonMini/final.py
4,663
4.125
4
import math ## Find PI to the Nth Digit ## # def find_pi(): # while True: # try: # num = int(input('How many decimals would you like?: ')) # except ValueError: # print('Integers only!') # else: # if num > 25 or num < 0: # print('You cann...
eb5d5cc571e78a5177c09dcb5d7c600134680c1b
WangYangLau/learnpython
/Practice_12.py
573
4.03125
4
# -*- coding: utf-8 -*- #功能:使含有整数的List中的字符变小写 print(u"功能:使含有整数的List中的字符变小写") L = ['Hello','World',18,'Apple',None] L2 = [l.lower() for l in L if isinstance(l,str)] print(L2) if L2 == ['hello','world','apple']: print(u'测试通过!') else: print(u'测试失败!') #注意:列表生成式中,如果,有if判断,列表中不符合判断内容的都不会生成在列表当中 print(u'列表生成式中,如果,有if判断,...
02406ce8e911d557f70d283de4bbc34cb50b0807
haiyogi/Hackerearth
/factorial1.py
175
3.875
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 8 16:40:54 2020 @author: K Yogesh """ a=int(input()) fact=1 for i in range(1,a+1): fact = fact * i print(fact)
b7e5a0cd5a285fb401788dc836fa56c65ddca0c7
ArdaCemBilecan/PythonProjects
/Sympy Plot/week2_lesson1_part1_sympy_examples.py
1,325
3.6875
4
import sympy as sp sp.init_printing() x = sp.Symbol('x') y,z = sp.symbols('y,z') f = sp.Function('f') g = x**2+y**2+z**2 display(g) # sp.pprint(g) --> Bize çıktıyı sembolleştirirler # Kucuk bir örnek: x**2 +2x-5 i yazdıralım h = x**2 +2*x -5 display(h) # h.subs(x,2) dersem x yerine 2 yazar ve bize sonucu verir...
f29eac0db0115ddb259968c49d7acf61647d9489
SS4G/AlgorithmTraining
/exercise/leetcode/python_src/by2017_Sep/Leet148_2.py
5,190
3.9375
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class LinkedListUtil: @staticmethod def merge2Ascendinglist(l1, l2): """ 合并两个升序的链表 合并后仍然是一个升序的链表 :param l1: :param l2: :return: """ t1 = l1 t...
29729852f71060b0fe0afe0879daea743f1326e6
miikanissi/python_course_summer_2020
/week3_nissi_miika/week3_ass6_nissi_miika.py
750
4.28125
4
def myMax(l): number = l[0] # Goes through the list and compares it to the previous largest number, # If the number is higher than previous largest number, # It becomes the new largest number. for x in l: if x > number: number = x return number print("Find the biggest num...
66e71447a3e4dcb263d05ab34169891b055c3862
kupeliaysekubra/bootcamp-code-institue
/Stream 2/Week 1/Day 2/uppercasecool.py
961
4.0625
4
# def count_upper_case(message): # count = 0 # for c in message: # if c.isupper(): # count += 1 # return count # Also works def count_upper_case(message): return sum([1 for c in message if c.isupper()]) assert count_upper_case("") == 0, "Empty String" assert count...
66df08e69ad0020e42a8a3f150931520b522e6fb
810Teams/pre-programming-2018-solutions
/Onsite/1130-Matrix Multiplication 3x3.py
678
4.03125
4
""" Pre-Programming 61 Solution By Teerapat Kraisrisirikul """ def main(): """ Main function """ matrix_a = [[int(input()) for _ in range(3)] for _ in range(3)] matrix_b = [[int(input()) for _ in range(3)] for _ in range(3)] matrix_r = [[multiply(matrix_a, matrix_b, i, j) for j in range(3)] for i in ra...
0661afe77d03dc3b3160717b3a93ed7bbc99db6d
Nandagopan-Gopi/Python_Mini-Projects
/5. rock-paper-scissors.py
1,693
4.21875
4
import random print("_______________WELCOME TO ROCK-PAPER-SCISSORS_______________") print(".\n.\n.") print("______________________STARTING THE GAME_____________________") print(".\n.\n.") user_score = 0 computer_score = 0 options = ["ROCK", "PAPER", "SCISSORS"] username = input("ENTER THE PLAYER NAME:- ") ...
1a143c2f9eef660fb9435f36f478341aab5888f7
C-TAM-TC1028-003-2113/tarea-1-marianaaglz
/assignments/21LevaduraParaPizza/src/exercise.py
568
3.875
4
def main(): # escribe tu código abajo de esta línea """ Se requieren 50 gramos de levadura para 1 kg. de harina si se utiliza para la base de una pizza. Realiza el cálculo de la levadura necesitada a partir de los gramos de harina que indique el usuario. Dame la harina en gramos: 1500 Necesitas estos gramos de le...
f2f031fa6f3e81b33159907552ea04eadf9806e2
NateScheidler/ProjectEuler
/euler20.py
287
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 04 16:04:31 2014 @author: nscheidler """ def factorial(n): ret = 1 for i in xrange(1,n+1): ret = ret*i return ret largeNumber = factorial(100) k = 0 for digit in str(largeNumber): k += int(digit) print k
f0718cee4354b9a6ad425b47950fe416c26eda9b
anantkaushik/Competitive_Programming
/Python/Interviewbit/Arrays/add-one-to-number.py
1,474
3.875
4
""" Problem Link: https://www.interviewbit.com/problems/add-one-to-number/ Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is at the head of the list. Example: If the vecto...
6ce36de4718295530679d46c81449e64a95d55a2
arun1167/my-project
/ex31.py
1,148
3.765625
4
print "You enter a dark room with two doors. Do you go through door #1 or door #2 ?" door=raw_input("> ") if door=="1": print "There's a giant beer eating here chesse cake. What do you do ?" print "1. Take the cake." print "2. Scream the bear." ########################### bear=raw_input("> ") #########...
7f48c3e361f1e6cda5e25eaa4bdedb8f5be5edd9
xiaoandx/learningCode
/Python_Code/experimentFour/experimentFour_test2.py
270
3.703125
4
# 输入一个列表 listOne = eval(input("请输入一个列表用逗号(,)区分:")); # 将输入的列表进行降序重新赋值 listTwo = sorted(listOne, reverse=True); # 输出排序后的新列表 print("将输入的列表降序后如下:"); print(listTwo);
2f9463f54a81dc7d2752becc1aca6352331e62fc
diegoasanch/Fundamentos-de-Progra-2019
/TP2 Estructura secuencial/TP2.9 Cajero automatico.py
2,245
3.859375
4
#Un banco necesita para sus cajeros automáticos un programa que lea #una cantidad de dinero e imprima a cuántos billetes equivale, considerando #que existen billetes de $100, $50, $10, $5 y $1. Desarrollar dicho programa #de tal forma que se minimice la cantidad de billetes entregados por el cajero. print('Cajero Autom...
dd0d1291b0bf4783bfae7ae9d452c6deadc51d76
johanwahyudi/Cryptography
/Classic/Transposition-Cipher/Decrypt.py
2,361
3.953125
4
#!/usr/bin/env python import math from string import ascii_lowercase, ascii_uppercase def caesar_dec(ciphertext, key_dec): hasil = [] for d in ciphertext: if d in ascii_lowercase: dekripsi = ascii_lowercase.index(d) dekripsi = (dekripsi - key_dec) % 26 hasil.append(as...
886d822839daa9ae46f371fab7dedcc3f32f5c01
BondarchukGleb/Python
/task3-2.py
1,082
4.03125
4
# Paying debt off int a year using bisection search to make it more faster balance = float(input('Balance = ')) annualInterestRate = float(input('Annual interest rate = ')) months = 12 monthlyInterestRate = annualInterestRate / months monthlyPaymentLowerBound = balance / months monthlyPaymentUpperBound = bala...
503d1a78ee81c4a7c97ee34f5367dfc335714a03
sadpotatoes/G6capstone-AI_Education
/utilities/FeatureSelection.py
1,068
3.5
4
import os import sys import pandas as pd import numpy as np from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.ensemble import ExtraTreesClassifier import matplotlib.pyplot as plt """@package FeatureSelection # ExtraTreesClassifier is an ensemble learning method ...
77f13c90f307031ffe2b28df83680145ad8dca9b
nchong128/fit2099
/Week 2/DuckTyping.py
438
3.890625
4
class Duck: def fly(self): print("Duck flying") class Butterfly: def fly(self): print("Butterfly flying") class Whale: def swim(self): print("Whale swimming") def lift_off(entity): entity.fly() animals = [Duck(), Butterfly(), Whale()] while 1: choice = input("Enter 1, 2, o...
c0d7ed68b13180939424b5dba625c1911ab0c21c
luluxing3/LeetCode
/lulu/singleNumberII.py
505
3.609375
4
class Solution(object): def singleNumber(self, nums): t1 = 0 t2 = 0 t3 = 0 for x in nums: t2 = t2 | (t1 & x) #occur twice t1 = t1 ^ x #occur once t3 = t1 & t2 #occur three times t1 = t1 & (~t3) #turn to zero if occur three times ...
b714bd650c5feb8ffd55477b8bc1745318069d7c
itsparth20/Data-structure-and-Algorithms
/LeetCode/ValidParenthese/Valid_Parentheses.py
331
3.671875
4
def isValid(s): lst = list(s) dic = {'}': '{',')' : '(',']' : '['} stk = [] for i in range(len(s)): if s[i] in dic.keys(): if len(stk) == 0 or stk.pop() != dic[s[i]]: return False else: stk.append(s[i]) return True if len(stk) == 0 else False print is...
1ecd661de5e547576f81d6917e0afcbf469924c0
realdingke/undergraduate-projects-showcase
/python machine learning Michigun university Coursera/course1 numpy and pandas/c1week1_numpy0.py
1,079
3.5
4
import numpy as np #a1=np.array([1,2,3]*2) #a2=a1.reshape(3,2) ##a2=a1.resize(3,2) This will return none, as resize only changes a1, does not create a2 #print(a1,'\n') #print(a2) #print(a1*2) #a3=np.repeat([3,4,5,6],2) #print(a3**2) #a4=np.arange(10)**2 #print(a4) #print(a4[-3::-1]) #slice from -3 position ...
c56e7c6e59e58696828a228aa52d12768bb8a301
NikoTaga/Python-algorithms-and-data-structures
/lesson_1/less1_task_7.py
991
4.3125
4
# # По длинам трех отрезков, введенных пользователем, определить возможность существования # треугольника, составленного из этих отрезков. # Если такой треугольник существует, то определить, является ли он разносторонним, # равнобедренным или равносторонним. a = int(input('длина отрезка 1 :')) b = int(input('длина отр...
2fb5c073efd8088f820d18448a2ae32f02d12835
cucumber-ltd/cyber-dojo-start-points-custom
/shouty-python/CoordinateTest.py
820
3.734375
4
import unittest from Coordinate import Coordinate class CoordinateTest(unittest.TestCase): def test_itCalculatesTheDistanceFromItself(self): a = Coordinate(0, 0) self.assertEqual(0, a.distance_from(a)) def test_itCalculatesTheDistanceFromAnotherCoordinateAlongXAxis(self): a = Coordin...
4bc51853e4b7d1bfac61d4b09175229ada5534eb
RRCHcc/python_net
/Data/day02/day02_linklist.py
3,250
3.921875
4
""" 链式结构代码实现 **重点程序** 链式线性思路 1.结点如何表示? 自定义对象:对象即数据,对象属性即数据元素 数据元素:包含有用数据和记录下一个对象地址的数据 2.如何建立关联? a = Node(1) a.val = 1 a.next = b b = Node(2) b.val = 2 b.next = None 3.实现什么样的链表操作? 链表初始化 链表的遍历 """ #创建结点类 class Node: def __init__(self,val,next = None): self.val = val sel...
9ce6526a74beb90f1248cf749c4392bf1d72257e
SergioB-dev/UDD_Training
/which_are_in.py
495
3.96875
4
""" Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2. Example 1: a1 = ["arp", "live", "strong"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] returns ["arp", "live", "strong"] Example 2: a1 = ["tarp", "mice"...
64985d0199b39eb13936636f70ffef8baeca1911
kariane/projectsPython
/project2.py
306
4.03125
4
from random import randint def rand(): return randint(1,10) rep = True while rep: x=input("enter a random number between 1 and 10: ") print("came out the number",rand()) if x==rand(): print("the numbers are equal") else: print("the numbers are not equal") break
290a29cd40f6178a2538186d46bb8758adffad68
mtnzorro/digita_crafts_week2_python_practice_exercises
/loop_ex8.py
160
3.734375
4
start = int(raw_input("Height: ")) space = range(1,start+1) x=1 y=1 for num in space: v = start - y print (v * " ") + (x * "*") x += 2 y += 1
74be97e775ba1a188623d59e8189dd126a3158aa
luizgallas/uri_iniciante
/1118.py
504
3.65625
4
x = 0 while(x != 2): soma = 0 qntd = 0 while(qntd < 2): nota = float(input()) if (0 <= nota <= 10.0): qntd += 1 soma += nota else: print("nota invalida") print("media = {:.2f}".format(soma/2)) print("novo calculo (1-sim 2-nao)") ...
8b686cce7038d0cd5b567b61a06dd06f261f5c37
qichangc/python_code
/3rd/1.py
612
3.5
4
#!/usr/bin/python #coding:utf-8 """ 写一个函数实现以下功能 找出一个列表的中位数,列表的元素都是浮点数。 列表中的元素个数为奇数:比喻L =[15.0, 5.3, 18.2], returns 15.0. 返回中位数 列表中的元素个数为偶数:比喻L =[1.0, 2.0, 3.0, 4.0], returns 2.5. 返回中间2位数之和/2 """ mylist = [2.4,1.2,3.5,0.1] mylist2 = [2.4,1.2,3.5,0.1,3.2] def myfun(clist): clist = sorted(clist) clen = len(cli...
2d014931cbfde1707550ce4f23fedfe4f636e875
KayDebrah/Lab_Python_02
/usingControlStructures.py
991
3.984375
4
#Question 5 theinput=raw_input("Enter an Integer: ") varx=int(theinput) if varx%2==0: print "Even" else: print "Odd" primaryschoolage=4 votingage=18 min_presidentage=50 retirement_age=60 PersonAge=input("Enter your age: ") Age=int(PersonAge) if Age<primaryschoolage: print "Too Young to be schooling" ...
7c757608ca70b79fbd09ac4686fbc1dfc0ff263d
evyatare92/tufin
/docker/zip_job.py
682
3.8125
4
import os import os.path import zipfile from pathlib import Path def validate_file(file_path): if not os.path.isfile(file_path): #raise FileNotFoundError(f"File {file_path} does not exists") print("File " + file_path + " does not exists") def create_zip_file(source_file_path): zip_file_name = ...
bc4092b4dbd7a8e9374a44f18452c0bdcbebba71
egurra/thermostate
/thermostate/abbreviations.py
1,123
3.734375
4
""" This module contains classes with attributes representing the common property units """ class EnglishEngineering(object): """String representations of common units. The attributes of this class are strings that represent the common units for thermodynamics calculations. Attributes ----------...
d2d3e42397e754a1a790c17b28c1bcccb7fcbe67
aaminu/BlackJack
/Blackjack.py
6,469
3.6875
4
import random from time import sleep SUITS = ('Diamonds', 'Hearts', 'Spades', 'Clubs') ORDERS = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') VALUES = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 1...
a8412d33b7e2c5e628d8fb136276a51f87fbbbf5
mpettersson/PythonReview
/questions/data_structure/tree/tree_from_inorder_and_preorder_traversal.py
11,329
4
4
r""" TREE FROM INORDER AND PREORDER TRAVERSAL (EPI 10.12: RECONSTRUCT A BINARY TREE FROM TRAVERSAL DATA) Write a function that can build and return a binary tree when given the inorder and preorder traversal values of the binary tree. Assume that there are no duplicate values in the binary tree. Con...
48fc9819df0e53db026d6c3d4032a114c52eba0c
xyp8023/LeetCode_Python
/786_Repeated_String_Match.py
915
3.53125
4
import math class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if B in A: return 1 x = (len(B) // len(A)) x = math.ceil(len(B) / len(A)) A_new = A * x if B in A_new: return x else: if B in A_new + A: ...
2aa5bb20215b549f761bedbf22be76fae081a0a9
SuperShinyEyes/Only_Numpy_Basic
/1_artificial_neural_networks_basic/2_step_decay_learning_rate.py
1,606
3.546875
4
import numpy as np # ----- ASSUME ------- # 1. pyhon - comfortable # 2. NN - understanding # ------ NETWORK ARCH ---- # 1. Epoch 100 # 2. LR = 1 # 3. SGD - BATCH # 4. Loss - MSE with added 1/2 # Generate Same Random Numbers Every Time np.random.seed(1) def sigmoid(x): return 1 / (1 + np.exp( -1 * x)) def d_...
bc26416188a76ae20f16cec240e21a5821697940
liazylee/python
/my_py_notes_万物皆对象/迭代器与生成器/迭代器/迭代器2.py
1,478
4.09375
4
# coding = utf-8 ''' @author = super_fazai @File : 迭代器2.py @Time : 2017/8/3 13:58 @connect : superonesfazai@gmail.com ''' # 一体化迭代器 class MyList(object): '''自定义一个容器, 保存多个数据, 做成可迭代对象''' def __init__(self): self.container = [] # container中文意思为容器 self.index = 0 def add(self, item): ...
d26161caf55999dd250bc6d91896d5ba2425d3d6
elastest/elastest-device-emulator-service
/eds/FrontEnd/server/openmtc-ngsi/lib/futile/string/__init__.py
414
3.796875
4
import string letters_digits_underscore = string.letters + string.digits + "_" class InvalidIdentifier(ValueError): pass def is_identifier(s): if not s or s[0] not in string.letters: return False for c in s: if c not in letters_digits_underscore: return False return Tr...
eafa7714b93f226e344f8556df1528c314590911
alejorods/fibonacci-stuff
/fibonacci-sequence.py
584
4
4
# Programa que genera la secuencia # de Fibonacci hasta el término # solicitado por el usuario. try: element = int(input("¿Cuántos elementos de la secuencia quieres?: ")) fibo_list = [0, 1] if element <= 0: print("¡Debes ingresar un número entero mayor que cero") elif element == 1: pr...
028181c9b14f164092adb4ef83eb5c79244cc7f8
AdamZhouSE/pythonHomework
/Code/CodeRecords/2311/60799/306081.py
1,564
3.625
4
class Tree(object): def __init__(self, preOrderList, inOrderList): self.left, self.right = None, None self.value = preOrderList[0] ptr = list(inOrderList).index(self.value) left1 = preOrderList[1:ptr + 1] left2 = inOrderList[0:ptr] right1 = preOrderList[ptr + 1:] ...
d0c66c4850e84adb2e2c9c1742030aac9f0d39b1
jason3189/Mr.zuo
/Mr.左/mothon02/代码/mysql/read_db.py
886
3.65625
4
""" 数据库读操作 select """ import pymysql # 连接数据库 db = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', database='stu', charset='utf8') # 创建游标 cur = db.cursor() sql = "select * from class_1 wh...
35b55362a04cc2d516c5b873ffad1cb65354ce05
abdul1380/UC6
/learn/decorater_learn.py
1,320
4.1875
4
""" https://realpython.com/primer-on-python-decorators/ """ def be_awesome(name): return f"Yo {name}, together we are the awesomest!" def greet_bob(greeter_func): return greeter_func("Bob") def parent(num): def first_child(): return "Hi, I am Emma" def second_child(): return "Call m...
41c69679ea6580265b2027f430ec39d17620dc1e
akifkartal03/CSE321-Introduction-to-Algorithm-Design
/Take Home Final/source/171044098_Akif_Kartal_Q2.py
1,812
3.640625
4
# 171044098 # Akif Kartal # Final Exam-Q2 Real Code import random def main(): print("---------------------------------------------------------") arr = [-1, 6, 4, 2, 3, -7, -5] print("Test List:", arr) getAllMinValues(arr, len(arr)) print("---------------------------------------------------------") ...
426eb4fe8fe42079e9220f5ff85bd1aa56b0e5f8
Vignettes/PythonBootcamp
/Section_23_Making_HTTP_Requests/http_introduction_and_crash_course.py
2,960
4.28125
4
### HTTP Introduction ### Our goals # A. Describe what happens when you type a URL into URL bar # B. Describe the request/response cycle # C. Explain what a request or response header is, and give examples # D. Explain the different categories of response codes # E. Compare GET and POST requests # When you go to goo...
ca4aa05ee28c71950a72c7d22a77d7c4f9fe6ff7
EOKruglov/Bioinformatics
/How_Do_We_Assemble_Genomes/String_Composition_Problem.py
175
3.53125
4
def main(): k = int(input()) input_str = input() for i in range(len(input_str) - k + 1): print(input_str[i:k + i]) if __name__ == '__main__': main()
f3e5786735114cd93aed8bdcba1510dbcc01a389
Polyhistor/Algorithms
/Arrays/Findmaximum.py
224
4.09375
4
# Find Maximum def findmaximum(arr): maximum = arr[0] for i in range(len(arr)): if arr[i] > maximum: maximum = arr[i] return maximum arr = [3,4,1,6,2,9] ans = findmaximum(arr) print(ans)
59ae27f4ce3bcd361d25cb33b6e79dea4f968534
zhaochenjin/zpython-0426
/day03/list_test.py
1,262
4.46875
4
names = ['Tom', 'Jerry'] print(names) print(names[0]) print(names[-1]) # last element 输出最后一个 print(names[-2]) # 输出倒数第二个 print(len(names)) # 输出个数 names.append('spike') # 添加 print(names) names.insert(2, 'Tyke') # 在2的位置添加Tyke,后面的给后面推移 print(names) names[3] = 'Spike' # 把3的位置上的内容改为 print(names) names.pop() # 删...
3795bb1bbb67f1d7add097ed885028fe92da908f
sachin0186/python_programs
/table while.py
93
3.765625
4
a=1 x=int(input("enetr the number")) while a<11: b=x*a print(x,"*",a,"=",b) a=a+1
816094c44ae491da22b86206a76df9ef55e192ae
lucasrcz/Python-Exercises
/Python-01/Exercicio 14.py
213
3.90625
4
C= float(input('Digite a temperatua atual para que seja feita a conversão em Fahrenheit: ')) F= float(C * 1.8 + 32) FC=float((F-32.0))/ 1.8 print('A temperatura atual {:.2f}Cº é igual a {:.2f}Fº'.format(C,F))
648a71ad2cf0fab5cf92ac84d6f1df7684f330c2
apantiuk/Polygons
/main.py
5,359
3.9375
4
import tkinter import CustomPolygon import Polygon import pickle WIDTH = 800 HEIGHT = 600 MAX_AREA_WIDTH = 2.5 canvas = None def main(): main_window = tkinter.Tk() set_window(main_window) main_window.mainloop() ##### # Setting window and drawing functions ##### def set_window(main_window): global...
d6c2c178555c33aa902149fe388fffcd1efa670f
manish1822510059/Python-1000-Programs
/List/7_length.py
132
3.640625
4
mylist = ['mi','oppo',"oneplus",'Micromax','Lava','Nokia'] print("List contant: ",mylist) print("Length of list >>",len(mylist))
c124f8fa524f06ec28302526b4889e36908bdc0f
codekansas/gandlf
/gandlf/layers/attention.py
15,800
3.53125
4
import keras import keras.backend as K class RecurrentAttention1D(keras.layers.Wrapper): """Makes a recurrent layer pay attention to an attention tensor. This implementation takes an attention tensor with shape (batch_size, num_features). On each recurrent step, the hidden state is weighted by the a ...
5155e9f43b2cb2d0de23b7b7d17ad389d19c19bb
stuckswimmer/image-compression-prototype
/zigzag.py
2,990
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 11:39:16 2019 @author: micha """ def zigzag(array): #converts a matrix into 1D array in order of energy frequency values n = len(array) if n != len(array[0]): print("Matrix is not square") return # 1D array cont...
ffd4473ece470015f7e1004ba5594c16abb39967
Gauravkochhar/100-days-of-code
/100 Days Work/Python/NINTH DAY WORK/3. SelectionSort.py
552
3.859375
4
n=int(input("Enter the Number of Element to be Sorted:")) a=[] for i in range(n): print("Enter ",i+1,"th Element:") val=int(input()) a.append(val) print("Old Values are:") print(a) lengthArr=len(a) for i in range(lengthArr-1): min=a[i] loc=i for j in range(i+1,lengthArr): if(a[j]<min): ...
40317f340bd0f3e816a8fb899b28265b11a4aef0
RobsonFulaneti/python-learning
/cursoemvideo/cursoemvideo/Listaex008.py
286
3.984375
4
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for lin in range(0, 3): for col in range(0, 3): matriz[col][lin] = int(input(f"Digite a posicão [{col}, {lin}]: ")) for lin in range(0, 3): for col in range(0, 3): print(f'[{matriz[lin][col]:^5}]', end='') print()
f3fd04c0923e88e0e9916056a529b03351fb4640
Rafael-Fonseca/Airport-Radar
/src/pixel.py
1,735
3.96875
4
''' PROJETO DESENVOLVIDO POR: FELIPE OLIVEIRA MAIA RA: 21801679 RAFAEL ABREU FONSECA RA: 21700439 ''' class Pixel: ''' Esta classe define um pixel. Ela mantém a posição no plano cartesiano de duas dimensões e a cor do pixel. ''' def __init_...
c617fdadd04b14bab641f1e46736599842b1c163
Aman123at/Machine-Learning-price-predictor
/mlpriceprediction.py
4,878
3.53125
4
''' This is the Machine Learning Project of Home Price Prediction it contain 13 labels and 1 feature that decides the predicted output For users go to the end of the programme and make changes in Using the model labels and get the predicted price by own .I attached housing.names and housing.data in files and by anal...
b6e2b7f06a23cd2ef0bda6df9f44d50e56d2aa16
AndyJZhao/MAGDataExtraction
/src/utils/util_funcs.py
1,343
3.640625
4
import os import pickle def save_pickle(var, f_name): mkdir_list([f_name]) pickle.dump(var, open(f_name, 'wb')) print(f'File {f_name} successfully saved!') def load_pickle(f_name): return pickle.load(open(f_name, 'rb')) def mkdir_p(path, log=True): """Create a directory for the specified path. ...
f49ab01381059bf9ea7b3124406790c2b656d723
lilhamad/py-desktop
/simpleFunctionToLayout.py
184
3.78125
4
from tkinter import * window = Tk() def printMyText(): print("We are good") myButton = Button(window, text="Click me", command=printMyText) myButton.pack() window.mainloop()
548b62f0e24cc7c3b5baa51abb12463ad8f06d84
david8388/Python-100-Days
/Day01-15/Day02/circle.py
244
3.953125
4
import math radius = float(input('請輸入半徑: ')) perimeter = radius * 2 * math.pi area = radius* radius * math.pi print('半徑為:%.2f' % ( radius )) print('圓周長為:%.2f' % ( perimeter )) print('面積為:%.2f' % ( area ))
970ba282244cdd124a0cb9a51127401a5c279fba
benjmerales/Python-Dump
/Frailty Deck.py
1,810
3.796875
4
import random import math Player = 20 Enemy = 20 AttackPlayers = math.floor(random.randrange(1,13)) AttackEnemy = math.floor(random.randrange(1,13)) print("Available Frailty Deck:") print("1. Overcharge") print("2. Melancholy") print("3. Break") print("4. Hack") frail_deck = [] for i in range(3): f...
a28973600617fcacc5859073032113c28484434d
Cours-a-Ynov/Cours-Python
/Pyhton/annexe.py
3,112
3.609375
4
import json # Lire un fichier: with open("words.txt", "r") as file: lines = file.read().splitlines() print(lines) # Ecrire dans un fichier: with open("words.txt", "w") as file: newWords = ["Chocolat", "Vanille", "Fraise"] file.write('\n'.join(newWords)) # Comment ajouter un nouveau mot/une nouvelle l...
d1ba0361d27047cff4e9f07f601e77a1353b554b
sarahxiao01/CS-UY-1114
/Dictionaries.py
1,105
3.8125
4
## Sarah Xiao ## CS 1114 ## 18 April 2019 ## Homework 8 ##Problem 1 def respell(str): respellings = {"teh": "the", "relevent": "relevant", "lite": "light", "lol": "haha"} lst= str.split() new_lst=[] for i in range(len(lst)): if lst[i] in respellings: new_lst.append(respellings[lst[i...
61256afe1436fc53bcf971c5c5a70e36b96d4250
Billoncho/RainbowSpiralSeven
/RainbowSpiralSeven.py
858
4.40625
4
# RainbowSpiralSeven # Billy Ridgeway # Creates a seven sided rainbow spiral drawn by a turtle. import turtle # Imports the turtle library. t = turtle.Turtle() # Creats a new pen called t. t.shape("turtle") # Makes the pen look like a turtle. turtle.bgcolor("black") # Sets the background color to b...
9e3ee25c85136cbd29259869938fe613febb675a
CPT413/Bioinformatics-Suite
/GUI/dnaFuncs.py
4,841
4.28125
4
def dnaSeqCheck(sequence): """ This function will be used to proofread the entered sequence before processing. The function qill return a sequence in lower-case format """ baseList = ['a', 't', 'g', 'c'] #list to compare each character to sequence = sequence.lower() #converts sequence to lower...
874532391edbb16d943e895e9f00bf75e37535bb
Hoeiriis/SameShitDifferentHyperParameter-Mirror-
/src/parameter_config/rescalers.py
3,485
3.890625
4
import numpy as np def create_min_max_rescaler(original_min_max, target_min_max): """ Min max rescaler creator. Creates a rescaler that rescales from target range into original range. :param original_min_max: tuple of floats, the range of values that is rescaled to :param target_min_max: tuple of floa...
29fca9d4dfc14ded0e91c90665f9c9355faad079
alexandraback/datacollection
/solutions_5695413893988352_0/Python/Static/B.py
1,783
3.59375
4
# -*- coding: utf-8 -*- # input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. import copy from sys import argv def load_file(filename): in_file = open(filename, encoding='utf-8') content = in_file.readlines() ...
c03e3f9f1cd74d09d97986cf775230c31d8d7d4f
VincentZ174/Cracking-the-Coding-Interview
/Section 3/3.5SortStack.py
508
4.03125
4
from Stack import Stack def sort_stack(unsorted, sorted): size = len(unsorted) while len(sorted) != size: curr = unsorted.pop() if len(sorted) == 0: sorted.push(curr) else: while sorted.peek() > curr: temp = sorted.pop() unsor...
4c39a7015ce995c31238c0b78757c692dc10635c
instaboy007/SEM-4
/Python Programming Lab/Practice_WS1/WS1_10.py
446
3.890625
4
def has22(arr): for i in range(len(arr)-1): if arr[i]==2 and arr[i+1]==2: return True return False has_22=[] n=int(input("ENTER THE NUMBER OF ELEMENTS IN THE ARRAY :")) for i in range(n): has_22.append(int(input("ENTER THE {}'st ELEMENT :".format(i+1)))) if(has22(has_22)): ...
9413471b47337ccda6bd607ad94296f049ba6d1d
Zhuoyue-Xing/IOT---INTELLIG-CONNECTED-SYS
/Lab/Lab2/lab2_group12_check2.py
2,351
3.90625
4
# Created by Chenye Yang, Haokai Zhao, Zhuoyue Xing on 2019/9/18. # Copyright © 2019 Chenye Yang, Haokai Zhao, Zhuoyue Xing . All rights reserved. from machine import Pin import time switch = Pin(15, Pin.IN) # With the inner pulldown register in Pin 15, we can get a stable 0V when the switch is not pressed. redLED ...
9428526566538da5a31c5042c24ec5e81d4912bd
GLAU-TND/python-programming-assignment2-ayush-saxena19
/problem_2.py
375
4
4
from functools import cmp_to_key list=[] elements=int(input()) for i in range(elements): elements=int(input("enter the elements")) list.append(elements) print("The original list is : " + str(list)) res = sorted(list, key=cmp_to_key(lambda i, j: -1 if str(j) + str(i) < str(i) + str(j) else 1)) print("Th...
fcffc38ec3a2f90c85413ddde9ad5ac81ba4a2a2
stefandurlesteanu/Codecool
/4th_SI_week/Game_inventory/game_inventory.py
1,201
3.921875
4
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def display_inventory(inventory): for i in inventory: print(i.rjust(11), '|', (str(inventory[i])).rjust(3)) def add_to_inventory(inventory, added_items): f...
6d4d0504503baa26224a17254dc625fa7311d88c
mikehung/leetcode
/342.Power_of_Four.py
268
3.78125
4
#!/usr/bin/env python class Solution(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ return not num&num-1 and bool(num&0x55555555) for i in range(20): print(4**i,Solution().isPowerOfFour(4**i))
91606c7d0e05b79abf8f1bb45c90a45b1e1a5d27
Clebom/exercicios-livro-introd-prog-python-3ed
/capitulo-09/ex05.py
836
3.78125
4
# Crie um programa que inverta a ordem das linhas do arquivo pares.txt # A primeira linha deve conter o maior número; e a última, o menor # Solução inicial # # pairs = open('pares.txt', 'r') # pairsReverse = open('pares-invertido.txt', 'w') # # contentPairs = pairs.readlines() # contentPairs.reverse() # # for line in ...