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
938acec65de13ca18263d10dbb295b1c9b8ec315
luhan93/leetcode
/BinarySearch.py
599
3.625
4
class Solution: def search(self, nums, target): left = 0 right = len(nums) - 1 return self.binary_search(nums, target, left, right) def binary_search(self, nums, target, left, right): if right < left: return -1 mid = (right + left) // 2 if target == n...
d6c7cd46e60e6aa74cdd28de4f94aa45a65eb861
GarrisonParrish/binary-calculator
/decimal_conversions.py
1,823
4.1875
4
"""Handle conversions from decimal (as integer/float) to other forms.""" # NOTE: A lot of this code is just plain bad def dec_to_bin(dec: int, N: int = 32): """Converts decimal integer to N-bit unsigned binary as a list. N defaults to 32 bits.""" # take dec, use algorithm to display as a string of 1's and 0...
2c6c321e6d3e2baefdf16a2287fdc52a605abcff
BonithanBiffutseder/python
/fibonatcci-numbers.py
260
3.75
4
#fibonatcci-numbers.py eingabe = int(input("Wähle eine Zahl:")) fz=0 letzteZahl=1 vorletzteZahl=1 for i in range(0, eingabe-1): fz=letzteZahl +vorletzteZahl print(vorletzteZahl, letzteZahl,"=>", fz) vorletzteZahl= letzteZahl letzteZahl=fz
8089b8196160c343d8ca5b2d314ac10f5e0a653c
Akamoha/Competitive-Coding-Solutions
/Codeforces/987/A.py
335
3.5625
4
n = input() seen = {} for i in xrange(n): seen[raw_input()] = 1 c2N = {} c2N["purple"] = "Power" c2N["green"] = "Time" c2N["blue"] = "Space" c2N["orange"] = "Soul" c2N["red"] = "Reality" c2N["yellow"] = "Mind" ans = 0 colors = [] for i in c2N: if i not in seen: ans += 1 colors.append(c2N[i]) print ans for c in c...
dedbff57cbcaa52e74cf7b49af275af47c9a76ed
Akamoha/Competitive-Coding-Solutions
/SPOJ/ONP.py
352
3.75
4
def convert(stringToConvert): return stringToConvert[2]+stringToConvert[0]+stringToConvert[1] t = int(raw_input()) for _ in range(t): s = raw_input() l = [] for i in range(len(s)): if s[i] != ')': l.append(s[i]) else: temp = [] while l[-1] != '(': temp.append(l.pop(-1)) l.pop(-1) l.append(co...
69ed89f19acf7867aee6d5f182d7aad247b358fa
Akamoha/Competitive-Coding-Solutions
/SPOJ/FAVDICE.py
113
3.75
4
for _ in range(input()): N = input() s = 0.00 for i in range(1, N+1): s += 1.0/i print "{:.2f}".format(s*N)
cfd78b5e2334d839bdcad00d335f1c99fba566a7
Akamoha/Competitive-Coding-Solutions
/SPOJ/ARITH2.py
436
3.890625
4
def compute(operand1, operand2, operator): x = int(operand1) y = int(operand2) if operator == '/': return x / y elif operator == '*': return x * y elif operator == '+': return x + y return x - y def solve(eqn): if len(eqn) == 3: return compute(eqn[0], eqn[2], eqn[1]) return compute(solve(eqn[:-2]), eqn...
88e2ddd284ad002fb36e02982d89412393f42aaa
Akamoha/Competitive-Coding-Solutions
/CodeChef/January Lunchtime 21/DREDIV.py
297
3.640625
4
def odd(k): if k%2: return k return odd(k//2) for _ in range(int(input())): n, k = list(map(int, input().split())) A = list(map(int, input().split())) ok = odd(k) for a in A: if a%ok: print("NO") break else: print("YES")
53b9149a7f5a947cbd3f1e7becaa37f3bdc3e83b
Akamoha/Competitive-Coding-Solutions
/SPOJ/CANTON.py
317
3.78125
4
T = int(raw_input()) for t in range(T): n = int(raw_input()) i = 1 while n > (i*(i+1)/2): i += 1 numerator = i - ((i*(i+1)/2) - n) denominator = i + 1 - numerator print ("TERM "+str(n)+" IS "+str(numerator)+"/"+str(denominator)) if (i % 2 == 1) else ("TERM "+str(n)+" IS "+str(denominator)+"/"+str(numerator))
a05f10b281d3314055318cd4b6d625e4d9467f3e
Akamoha/Competitive-Coding-Solutions
/SPOJ/HANGOVER.py
207
3.65625
4
while True: c = float(raw_input()) if c == 0.00: break else: totalOverhang = 0.00 den = 2.00 while totalOverhang < c: totalOverhang += 1.00/den den += 1.00 print str(int(den-2))+" card(s)"
67ec95eca527ef3afcc2d249790bdd47e0a175aa
Akamoha/Competitive-Coding-Solutions
/SPOJ/SMPCPH1.py
269
3.671875
4
n = input() HT = {} for letter in "abcdefghijklmnopqrstuvwxyz ": HT[letter] = letter code = raw_input() for i in xrange(n): HT[code[i]] = code[(i+1)%n] for _ in xrange(input()): plaintext = raw_input() ans = "" for letter in plaintext: ans+=HT[letter] print ans
5ba1e8e69f7c425bba22c7e990ac583edc313441
ieshaan12/Python-Programs
/cliter.py
613
3.96875
4
class Squares: def __init__(self, start, stop): # Save state when created self.value = start - 1 self.stop = stop def __iter__(self): # Get iterator object on iter, this is essential for iteration return self #Other wise object is non iterable def __next__(self): # Return a square on...
2efc926dcdec0121d729e64a538bcd2183ca13b9
ieshaan12/Python-Programs
/hr.py
363
3.875
4
def print_formatted(number): # your code goes here #Octal i=1 l=''; while i<=number: o=str(oct(i));h=str(hex(i));b=str(bin(i)); o1=str(o[2:]);h1=str(h[2:]);b1=str(b[2:]); l=l+str(i)+' '+o1+' '+h1+' '+b1+'\n' i+=1 print(l) return if __name__ == '__main__': ...
f6fa1ca914b1dabc4d0c9cf52606a628d83f36bb
ieshaan12/Python-Programs
/RegexStrip.py
499
3.9375
4
#! python # Regex Version of Strip() import re def RegexStrip(mainString,charsToBeRemoved=None): if(charsToBeRemoved!=None): regex=re.compile(r'[%s]'%charsToBeRemoved)#Interesting TO NOTE return regex.sub('',mainString) else: regex=re.compile(r'^\s+') regex1=re.compile(r'$\s+') ...
9661a468c664080866bd5ccd3e5668959b97b0f6
ieshaan12/Python-Programs
/firstturtleprog.py
438
3.71875
4
import turtle turtle.colormode(255); #turtle.color("blue"); for i in range(12): turtle.color(123,20*i,0); turtle.forward(50); turtle.left(72); turtle.penup(); turtle.forward(50); turtle.left(72); turtle.forward(50); turtle.left(72); turtle.pendown(); turtle.forward(50); turtle.left(72); turtle.penup(); tur...
f0d5e4afb2071cdcba9d49f6925a597a466ad245
EroshenkoD/BBP_Python_hillel
/lesson_12/task_2.py
624
4.21875
4
""" 2. Имеется строка вида: AABABBAABBBAB. Необходимо написать функцию которая заменит буквы A на B, а B, соответственно, на A. Замену можно производить ТОЛЬКО используя функцию replace(). В результате применения функции к исходной строке, функция должна вернуть строку: BBABAABBAAABA """ s = 'AABABBAABBBAB' def repl...
2545255134a606a5db026f0cf430aee7a62e75f7
EroshenkoD/BBP_Python_hillel
/lesson_3/home_work_les_3_TASK.py
751
3.953125
4
""" TASK*: Дано целое, положительное, трёхзначное число. Например: 123, 867, 374. Необходимо его перевернуть. Например, если ввели число 123, то должно получиться на выходе ЧИСЛО 321. ВАЖНО! Работать только с числами. Строки использовать НЕЛЬЗЯ! """ text_output = "Перевернутое число: {} " numb = int(input("Введите ...
dc73cf2be198140a7e5aa938eb6756a7cf1e21e8
EroshenkoD/BBP_Python_hillel
/lesson_5/task_3.py
780
4.03125
4
""" 3. Пользователь вводит, отдельно, строку `s` и один символ `ch`. Необходимо выполнить поиск в строке `s` всех символов `ch`.Для решения можно использовать только функцию `find`(rfind), операторы if и while. """ text_output = 'В строке "{s}", символ "{sm}", встречается с индексом: {count}' st = input('Введите стр...
61d14170e514309e51b765c3a25adfceaea82a51
anettepaula/todo
/todo04.py
200
4
4
#coding: utf-8 lista = [] num = int(input("Dime un numero: ")) while num != 0: num = int(input("Dime un numero: ")) lista += [num] lista.sort() print "La lista ordenada de menor a mayor es:",lista
0e004c6ed867e7f719fdd4c8e784fd6e2ed87530
aryabhatta-dey/n-body
/N-body.py
5,367
3.984375
4
''' doc: https://matplotlib.org/api/pyplot_api.html Mathplotlib has been used to make scatterplots to represent the point particles ''' import matplotlib.pyplot as plt ''' doc: https://numpy.org/doc/ Numpy has been used to make matrix claculations. All the arrays used are ndarrys supplied by Numpy and not the ususal p...
60d466d4c7f4ae90189956050a40f3108c0c7cb3
stefanm-git/Data-Science
/20-Machine-Learning-Supervised-Learning/logistic_regression_project.py
2,072
3.796875
4
import codecademylib3_seaborn import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler # Load the passenger data passengers = pd.read_csv('pas...
2726d03db151046c1091b93d14a5593c2d368e52
vrillusions/python-snippets
/ip2int/ip2int_py3.py
963
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Asks for an IPv4 address and convert to integer. In Python v3.3 the ipaddress module was added so this is much simpler """ import sys import ipaddress __version__ = '0.1.0-dev' def main(argv=None): """The main function. :param list argv: List of arguments ...
7e16042422411339b4636ae33f56673fef180e36
idaspahiuu/UrlAndStructureCrawler_Grupi11
/main.py
4,653
3.671875
4
from tkinter import * import tkinter as tk from tkinter import messagebox as ms from PIL import ImageTk, Image from bs4 import BeautifulSoup import validators import urllib.request def Scrape(arg=None): # Giving url url = url_entry.get() # Checking if given URL is valid if not validators.url(url): ...
4891261cf13ad1838f739a00785306ffd901f2f4
Gokul-raaj-5999/TCS_CPA_python_programing
/RESTAURANT MANAGEMENT, PRINTFOOD MATCHES WITH ID,DISCOUNT WITH PERSENTAGE GIVEN.py
1,272
3.53125
4
class FoodItem: def __init__(self,i,name,category,price): self.item_id = i self.item_name = name self.item_category = category self.item_price = price def provideDiscount(self,p): if p>0: self.item_price-=(self.item_price*p/100) class Restaurant: ...
30d6d86bbcdcfee563d26985ccfaae90c8480397
Splufic-Automation-Systems-Ltd/Python-Training-Online-Cohort-One
/Week Three/Day 2/temp.py
340
4.375
4
import math # a python program that converts temperature from Farenheit to Celcius # get the user input fahrenheit = input('Enter the temperature in degrees Fahrenheit: ') # calculate the result result = (5/9 * (int(fahrenheit) - 32)) result = math.trunc(result) # print the result print(f'The temperature in degrees C...
1256135da9e3090654e23d52145c2d2061e494a9
ledrui/Analyzing-Sentiment
/awesome_count.py
3,199
4.21875
4
def awesome_count(dicts): """" Count the number of occurence of the word on the dict""" #print dicts result = 0 word = 'for' for dict in dicts: print dict for words in dict: #print words if word in dict: result = dict[word] ...
d1d792d85b93fcb95cfc3183cf05541dd8579d84
rotus/the-python-bible
/tuple_examples.py
248
4.125
4
# Tuples, like lists, hold values - Except tuple data CANNOT be changed # Useful for storing data/values that never need updated or modified our_tuple = (1,2,3,"a","b") print(our_tuple) # Pull data out of individual elements print(our_tuple[3])
9cf228ee2b0cd2fa8899ce07b5ccc5738d729e92
rotus/the-python-bible
/dictionary_basics.py
394
4.5625
5
# Used to store values with "keys" and then can retreive values based on those keys students = {"Alice":25, "Bob":27, "Claire":17, "Dan":21, "Emma":25} print(students) # extract Dan's value from dict print(students["Dan"]) # Update Alice's age print(students["Alice"]) students["Alice"] = 26 print(students["Alice"])...
2662c446bc00416497a5e9071870763f79dc1509
mickaelthebox/owen-test
/exercice 3 open.py
435
3.546875
4
def list_of_txt(file) : #créer une liste dans lequel chaque élément est une ligne du texte en entrée #le but est de coder soi même readlines l = [] with open('{}'.format(file),'r') as f : text = f.read() line = '' for i in range(len(text)) : if text[i] != '\n' : ...
22afc903d5165e253d50a10862ba8f994f6b5081
johnnymcodes/cs131b_python_programming
/5_iteration/print_backwards.py
275
4.15625
4
string = input('enter a string ') print(string) print(type(string)) backwardsString = '' def print_backwards(string): n = len(string)-1 while n > -1: backwardsString += string[i] n = n-1 print(backwardsString) print_backwards(string)
ba5f177e8ed7dff0164f72206401d5dd35ab690a
johnnymcodes/cs131b_python_programming
/4_functions/w10exhand.py
1,504
4.21875
4
# Write a program that expects numeric command line arguments and calls # functions to print descriptive statistics such as the mean, median, # mode, and midpoint. # Week 9 : Severance 4 import sys #expects numeric command line arguments cmarg = sys.argv[1:] #returns a list of cmd arguments numlist = list(...
87f7b24055a392eb6a29a2a72b8b9395b4c083fe
johnnymcodes/cs131b_python_programming
/6_strings/sortuserinput.py
944
4.5625
5
#intro to python #sort user input #write a program that prints out the unique command line arguments #it receives, in alphabetical order import sys cmdarg = sys.argv[1:] cmdarg.sort() delimiter = ' ' if len(cmdarg) > 1: joinstring = delimiter.join(sys.argv[1:]) print('this is your command argument '...
14aacd6a28c36255d47cc5b8a589ea4083b9cfff
luka1199/csgo-case-helper
/utils.py
3,625
3.5625
4
import math from random import random STEAM_FEE = 0.05 CSGO_FEE = 0.10 def getPayoutFromPrice(price): """Returns the payout you get on the steam market for selling an item for the given price. Arguments: price {float} -- The price the buyer pays to buy your item. Returns: fl...
688b04e11acc4e5378e7d4b7082c9b8d635d7b66
rileyrisinger/Intro-to-Python
/bats.py
516
3.9375
4
speciesa1,speciesa2 = input("Enter 1st species: ").split() speciesb1,speciesb2 = input("Enter 2nd species: ").split() speciesc1,speciesc2 = input("Enter 3rd species: ").split() newspeciesa = (speciesa1[0:3].upper() + speciesa2[0:3].upper()) newspeciesb = (speciesb1[0:3].upper() + speciesb2[0:3].upper()) newspeciesc = (...
9669fb1b7942f879aa7c27be41bc2fc42e42d3a3
rileyrisinger/Intro-to-Python
/population.py
449
3.875
4
#Population #Calculate population number # Riley V. Risinger #February 4th, 2020 #import modules #Add any variables #Ask for input #Calculation of current population #Print results #birth time = 7 / 31536000 #death time = 13 / 31536000 #immigrant time = 35 / 31536000 #Inputs years_input = int(input ("how many years?...
aa47ff7f63c6a3d1c102f26361c540bd6872cffc
MaximChernyak98/LP_homework
/lesson2/marks_for.py
1,395
4.03125
4
''' Оценки Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] Посчитать и вывести средний балл по всей школе. Посчитать и вывести средний балл по каждому классу. ''' import statistics marks = [ {'school_class': '4a', 'scores': [3, 4, 4, 5,...
ff6e1c1d4887494c8ae8513f0f3b3e66dd895181
MaximChernyak98/LP_homework
/lesson2/compare_str_if.py
1,789
4.1875
4
''' Практика: Сравнение строк Написать функцию, которая принимает на вход две строки Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 Если строки одинаковые, вернуть 1 Если строки разные и первая длиннее, вернуть 2 Если строки разные и вторая строка 'learn', возвращает 3 Вызвать функцию н...
623df94dbc536e05c869944daf16b3c6a41c4090
yashdeepyds/python
/helloCalci.py
589
4.09375
4
print("Calculator") choice='y' while(choice=='y' or choice=='Y'): print("Enter the first number") x=int(input()) print("Enter the second number ") y=int(input()) print("Press 1-Addition \t 2-Subtraction \t 3-Multiplication \t 4-Division ") print("select the operation") ch=int((input())) ...
f6bfe019700f6a227d2f91e03268bf4a7ae82a36
RidleyLeisy/DS-Unit-3-Sprint-2-SQL-and-Databases
/sprint/northwind.py
2,352
4.09375
4
import sqlite3 conn = sqlite3.connect('northwind_small.sqlite3') curs = conn.cursor() def querydb(query): curs.execute(query) results = curs.fetchall() return results # Questions ''' What are the ten most expensive items (per unit price) in the database? What is the average age of an employee at the ti...
4600dba0ab1754ad3f7817df8ce71191033edd8d
Nabilabilalla/python_maison
/maison.py
3,822
3.90625
4
from turtle import * # Pour nommer la fenêtre de jeu title("Le jeu du Nabila !") def house(): begin_fill() color('black', 'pink') forward(141) left(90) forward(100) left(45) forward(100) left(90) forward(100) left(45) forward(100) left(90) goto(140, 100,) f...
58319d31330ca5b1889a58e8a91694bda3a17a72
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题26. 树的子结构.py
2,356
3.921875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): """ 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 给定的树 A:      3     / \    4   5   / \  1   2 给定的树 B:    ...
b6e96beb8923771c189b8b37df111069849288da
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题59 - II. 队列的最大值.py
6,507
3.53125
4
class MaxQueue(object): """ 请定义一个队列并实现函数 max_value 得到队列里的最大值, 要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。 若队列为空,pop_front 和 max_value 需要返回 -1 输入: ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] [[],[1],[2],[],[],[]] 输出: [null,null,null,2,1,2] 输入: ["MaxQueue","pop_front","max_value"]...
551b9bb2b713304002397c589dfb6c8d17532e91
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题06. 从尾到头打印链表.py
958
3.796875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): """ 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 输入:head = [1,3,2] 输出:[2,3,1] 限制: 0 <= 链表长度 <= 10000 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-...
41cd0de4011873128be614f2ac7f6a2e03abf18f
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题58 - I. 翻转单词顺序.py
1,776
3.71875
4
class Solution(object): """ 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。 为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ", 则输出"student. a am I"。 输入: "the sky is blue" 输出: "blue is sky the" 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 输入: "a good   example" 输出: "example good a" 解释: 如果两个单词间有多余的...
30e0dcb745515b489e5340a07ac61cb9b0a8db68
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题28. 对称的二叉树.py
1,825
3.96875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): """ 请实现一个函数,用来判断一棵二叉树是不是对称的。 如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。     1    / \   2   2  / \ / \ 3  4 4  3 但是下面这个 [...
38b91d3361eef7dd7469107771fd7eb48fe83efc
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题42. 连续子数组的最大和.py
1,175
3.515625
4
class Solution(object): """ 输入一个整型数组,数组里有正数也有负数。 数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 要求时间复杂度为O(n)。 输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 1 <= arr.length <= 10^5 -100 <= arr[i] <= 100 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/ 链接:https://leetcode-cn.com/proble...
3734ff6076983328b137a080f9e6360daa998163
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题27. 二叉树的镜像.py
1,531
3.96875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): """ 请完成一个函数,输入一个二叉树,该函数输出它的镜像。 例如输入:      4    /   \   2     7  / \   / \ 1   3 6   9 镜像输出:      4    /   \   7     2  / \   / \ 9...
1d2af39c99789aa1569e5da199c6ccb8629f7d87
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题20. 表示数值的字符串.py
998
3.625
4
import re class Solution(object): """ 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"0123"及"-1E-16"都表示数值, 但"12e"、"1a3.14"、"1.2.3"、"+-5"及"12e+5.4"都不是。 链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof """ def isNumber(self, s): """ :type s: str ...
d03d3f4dd377e27e95a71900594da2f18c2666ce
Jackyzzk/Coding-Interviews-2
/剑指offer-面试题41. 数据流中的中位数.py
2,579
3.734375
4
class MedianFinder(object): """ 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值, 那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值, 那么中位数就是所有数值排序之后中间两个数的平均值。 [2,3,4] 的中位数是 3 [2,3] 的中位数是 (2 + 3) / 2 = 2.5 设计一个支持以下两种操作的数据结构: void addNum(int num) - 从数据流中添加一个整数到数据结构中。 double findMedian() - 返回目前所有元素的中位数。 输入: ["MedianFinder","addNum","addNum","findMe...
a112ca66a8ca2e8c12f97d8a4e1a8c4d5efd5c66
JamesBrofos/Adaptive-Normalizing-Flow-Chains
/examples/stochastic/optimization.py
846
3.546875
4
import autograd.numpy as np def rmsprop(grad, x, avg_sq_grad, step_size, gamma=0.9, eps=10**-8): """Root mean squared prop. See Adagrad paper for details. Args: grad: The gradients of the loss function to use to update the parameters. x: The current value of the parameters. avg_sq_gra...
1c18f6b9652b5865257084184540e979ae1a1766
docjoel/youtubemissingvideonotify
/YT_model/checklinks.py
1,486
3.59375
4
import requests import csv # opens the video def countRows(filename): with open(filename, newline='') as f: reader = csv.reader(f) row_count = sum(1 for row in reader) return row_count def checkifavalible(youtubelink): q = requests.get("http://www.youtube.com/oembed?url=https://www.y...
1279aaf52fc0ba63405deaf110d776aa9f983ec8
Aldunate5/Diego_Aldunate
/Programacion_Avanzada/Contenidos/semana-00/semana00_strings.py
2,016
3.953125
4
cadena = "mi cadena de texto" print(cadena[0],cadena[-1]) #cadena[0]="M" error al no poder inmutar strings otra_cadena="" for caracter in cadena: otra_cadena+=caracter print(otra_cadena) #caracteres especiales \", \', \n, \t, \\ #dir(str): list of attributes s="esto programandoy" print("abn".isalpha()) print...
ae864361d1a391d885deef481b5e4311e5719366
Aldunate5/Diego_Aldunate
/Programacion_Avanzada/Contenidos/semana-02/semana02_polimorfismo.py
3,267
3.859375
4
#polimorfisimo: utilizar objetos de distinto tipo con la misma interfaz #overriding: sobereescribir metodo existente en subclase #overloading: metodo con mismo nombre, distinto argumentos y sus tipos import statistics class Variable: def __init__(self,data): self.data=data def representante(self): ...
4f82bea7b42f5f897ad0f95fc7584e371b4e5068
Aldunate5/Diego_Aldunate
/Dardos/darts.py
572
3.59375
4
import practica #import Puntaje import os import back_down def juego (): print("Bienvenido") print("Que desea jugar?") print("1. Modo chupar poto") print("2. Modo Focker") print("3. Practica") print("4. Puntaje") print("5. Salir") game=int(input()) if game==1: back_down.run(...
e65a8f9e682c03eeb41d4f3d285fcf3412089124
maxUser/minigames
/noname/Arena.py
2,389
3.53125
4
import json import sqlite3 from Player import Player def determine_players(): # essentially, logging in # search for each player in database # if player is found, add to arena # else ask if new player should be created print('determine_players') # p1 = input('Name of player: ') p1 = 'playe...
f181a4453d72a7f88408888a1356d349380a74a6
Qnouro/Gdelt-World-Events-Visualization
/scraper.py
3,390
3.5
4
#!/usr/bin/python3 import os import sys import requests import urllib import json import zipfile import pathlib from pathlib import Path def main(): """ Mainly for debugging purposes. """ last_url = "" config_file = read_config() while True: try: url = get_latest_url() ...
697c079b26a42a550cd80b63edd153897e394f7f
aliyakm/ICT_task1
/2.py
80
3.875
4
your_name = str(input()) print("Hello, "+your_name+"! Welcome to this page.")
8d88e73998d7d8bdfb3d323a963369c44aee27db
aliyakm/ICT_task1
/3.py
521
4.28125
4
print("Please, choose the appropriate unit: feet = 1, meter = 2.") unit = int(input()) print("Please, enter width and length of the room, respectively") width = float(input()) length = float(input()) if unit == 1: area = width*length result = "The area of the room is {0} feets" print(result.fo...
48c2d833b43246cdd94f46ed83e8d2c5b9729bad
aliyakm/ICT_task1
/6.py
166
3.90625
4
print("Enter the cost of the dish") cost = int(input()) tip = cost*0.18 tax = cost*0.15 final_cost = tip + tax + cost print("{0:.2f}".format(final_cost))
04b4ce4faa34e5b2d7aa9b02ce0357cb479d1baa
d391/UBB-Fundamentals-of-programming
/Gomoku/Square.py
420
3.6875
4
class Square: def __init__(self, line, col): self._line = line self._col = col @property def line(self): return self._line @property def column(self): return self._col def __str__(self): return str(self._line) + ", " + str(self._col) ...
2fb5cbc34f97537e84b9d9a7dc4b8088f513cb99
darbaga/simple_compiler
/virtual_machine.py
2,139
3.5
4
class VirtualMachine: def __init__(self, ram_size=512, executing=True): self.data = {i: None for i in range(ram_size)} self.stack = [] self.executing = executing self.pc = 0 self.devices_start = 256 def push(self, value): """Push something onto the stack.""" ...
043725bdbda46671fc1ca43ec741cd0ed32a48bb
mmondelli/swift-phylo
/bin/PA_Mafft.py
735
3.6875
4
#!/usr/bin/python def validateMafftFile(self, input): """ validateMafftFile - Method for mafft file format testing Responsible for the IsValid tag """ filename = input+".mafft" arq = open(filename, "r") output = "" conteudo = arq.readlines() seqcont = 0 out...
92827541e986f956574b4c50ae27ba757dc6a9a1
tarcisiocsn/4epy
/dictionaries02.py
1,774
4.25
4
#Counting Pattern #the general pattern to count the words in a line of the text is to split the line #into words, then loop through the words and use a dictionary to track the count of #each word independently counts=dict() print('Enter a line of text: ') line=input('') #se não colocar a definição de line essa porra d...
2f91d697437a7ae3ffb51c07443634f68505566b
androidgilbert/python-test
/ex33.py
514
4.1875
4
def test_while(a,b): numbers=[] i=0 while i<a: print "At the top is %d"%i numbers.append(i) i=i+b print "numbers now:",numbers print "at the bottom i is %d"%i return numbers def test_for(a): numbers=[] for i in range(0,a,3): print "at the top is %d"%i numbers.append(i) print "numbe...
00cf375c449164d643f12c421ffc3fbbde8a789e
androidgilbert/python-test
/ex30.py
410
4.15625
4
people=30 cars=40 buses=15 if cars>people: print "we should take the cars" elif cars<people: print "we should not take the cars" else: print "we can't decide" if buses>cars: print "that is too many buses" elif buses<cars: print "maybe we could take the buses" else: print "we still can not decide" if people>buse...
3391a8aed49e4335f75ad4b18ac26639b9752b6e
JenySadadia/MIT-assignments-Python
/Assignment2/list_comprehension(OPT.2).py
714
4.125
4
print 'Exercise OPT.2 : List comprehension Challenges(tricky!)' print '(1)' print 'find integer number from list:' def int_element(lists): return [element for element in lists if isinstance(element, int)] lists = [52,53.5,"grp4",65,42,35] print int_element(lists) print '(2)' print 'Here the y = x*x + ...
140790a0fe40f1cbacadeaf946c5b9d7cac637a0
JenySadadia/MIT-assignments-Python
/Assignment4/exercise4.6-overriding.py
566
3.9375
4
class Address: def __init__(self, street, num): self.street_name = street self.number = num class CampusAddress(Address): def __init__(self,office_num): office = office_num.split('-') new_offfice = office[0]+office[1][0]+'-'+office[1][1:] self.office_num = offic...
1ebba4633dee457b9cc6d9ef5da52658c67df17d
JenySadadia/MIT-assignments-Python
/Assignment3/OPT1palindromes.py
185
4.375
4
def is_palindrome(str): if(str==str[::-1]): print(str,"is pallindrome") else: print(str,"is not pallindrome") str=input("Enter String:") is_palindrome(str)
72595032f513b2d22b15bfe147b5ad8f921a597b
JenySadadia/MIT-assignments-Python
/Assignment2/Exercise2.2.2.py
389
4.0625
4
##Name : Krutika Shah ##date: 10 Aug ##Assignment 2.2.2 print ("------------------Exercise:2.2(.2)------------------") def not_equal(number1,number2): if number1 == number2: return False else: return True number1 = int(raw_input('Enter first number: ')) number2 = int(raw_input('Enter...
edfc365eed1537b5ae95d8effdf72af13e1a55f4
JenySadadia/MIT-assignments-Python
/Assignment4/tetrominoes.py
3,618
4.25
4
from graphics import * ''' class- block : it conveters the points into pixels and displays the block of pixel 30 it calls the super class ''' class Block(Rectangle): starting_num=0 def __init__(self,points,color): # to convert the points into pixels x = points.getX()*30 y...
67adff2a8096d2ca99e7ca7cb4b603be6ac37a94
sunilgoda/DataStructures_Alg_Python
/challenge/AllPairsGivenSum.py
1,710
3.875
4
''' Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. Input: The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains 3 lines . The first line contains...
8a78443920581225c0cf4df8f6765abaca9915dc
lic34/leetCoding
/leetcode/two_sum.py
453
3.59375
4
'''https://leetcode.com/problems/two-sum/''' class Solution: '''https://leetcode.com/problems/two-sum/''' def twoSum(self, nums: list(), target: int) -> list(): for index,num in enumerate(nums): next_num = target - num if next_num in nums[index+1:]: next_...
b387c1f07e7bfd2fd92ce661b0077e5185356275
lic34/leetCoding
/leetcode/longest_palidrome.py
3,013
3.828125
4
class Solution: ''' https://leetcode.com/problems/longest-palindromic-substring/''' def longestPalindrome(self, s: str) -> str: if not s: return s string_length = len(s) longest_palindrome = str() for pre_index in range(string_length): char_start_index = p...
eef8e004c063f73fa822b31d1d90dacc8c6602bf
timqsh/advent2020
/Day_18_Operation_Order/sol.py
5,543
3.9375
4
from pathlib import Path PLUS = "+" TIMES = "*" LPAREN = "(" RPAREN = ")" EOF = "EOF" class ArithmeticParser: """Parses a token list and returns a nested expression structure in prefix form using recursive descent method. Code based on this example: https://mail.python.org/pipermail/tutor/2003-Decem...
67dbb4c2137c76c7674549d33bf524a9373e538f
insixp/eulers_project
/Task30.py
489
3.84375
4
import time def main(): current_power = 5 max_num = 1 while((9**current_power)*len(str(max_num)) > max_num): max_num += 9**current_power total_sum = 0 i = 2 while(i <= max_num): print i if(check_if_sum_of_fifth_power_equal(i, current_power)): total_sum += i i += 1 print total_sum def check_if_sum...
12c53c723d3533e4c959653ef333add8de3990da
insixp/eulers_project
/Task29.py
252
3.53125
4
import time def main(): max_a = 100 max_b = 100 total_nums = set() for i in range(2, max_a + 1): for j in range(2, max_b + 1): print str(i) + "^" + str(j) total_nums.add(i**j) print len(total_nums) if __name__ == "__main__": main();
5e1e14bc8b2a04385f5d155e7097051310413678
insixp/eulers_project
/Task7.py
491
3.78125
4
def main(): list = [2] prime_num = 10001 check_range = 100000000 for i in range(3, check_range): print str(i) + " - " + str(len(list)) if(check_list_highest_divider(i, list)): list.append(i) if(len(list) == prime_num): print list print list[prime_num - 1] return True def check_list_highest_divi...
44c991c03adc43264913eaa325a1102eef8de93b
Tanner0397/LightUp
/src/population_member.py
8,901
3.8125
4
""" Tanner Wendland 9/7/18 CS5401 Missouri University of Science and Technology """ """ Object for population member. Each member has their own chromozome that determines their solution. This chromozome represents a list of bulb placement. A chromozome will be of variable length, this being the number of whit...
860251764c96cccf6db12d1695ae1774d9332dc4
Tanner0397/LightUp
/src/chromosome.py
2,288
4.125
4
""" Tanner Wendland 9/7/18 CS5401 Missouri University of Science and Technology """ from orderedset import OrderedSet """ This is the class defintion of a chromosome. A chromosome has genetic code that ddetermines the phenotype of the population member (the placement of the bulbs). The genetic code is a li...
1ff5200f0986ffce8e9cfbf05f795ccd56c90134
NathanNeff/hadoop-examples
/spark/dataframes/windowing.py
557
3.734375
4
# Spark SQL syntax for windowing # https://spark.apache.org/docs/latest/sql-ref-syntax-qry-select-window.html df = spark.range(10) df.createOrReplaceTempView("df") spark.sql(""" SELECT id, COUNT(id) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cum_count, SUM(id) OVER (ORDER BY id ROWS BETWEEN...
270d4d13611ee2f1f7191c0b27883750f5b94585
NathanNeff/hadoop-examples
/spark/dataframes/joins.py
1,785
3.6875
4
def printDataFrame(df, name): print("This is %s" % name) df.show() leftFile = "hadoop-examples-data/left.csv" rightFile = "hadoop-examples-data/right.csv" opts = { "inferSchema" : True, "header" : True } leftDF = spark.read.options(**opts).csv(leftFile) rightDF = spark.read.options(**opts).csv(righ...
1339505bfef78b891120feb3a67760d65095ea20
BrBritZ/DjangoMaster
/rango/bing_search.py
1,290
3.546875
4
import json import urllib, urllib2 # Py2.7.x from py_ms_cognitive import PyMsCognitiveWebSearch # Add your Microsoft Account Key to a file called bing.key def read_bing_key(): """ Reads the BING API key from a file called 'bing.key'. returns: a string which is either None, i.e. no key found, or with a key...
9ef689c757ce40d7d2f394ee6aeed2b4402205d9
rrigato/pyIntermediate
/regression.py
1,400
3.546875
4
import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from pybrain.structure import FeedForwardNetwork from pybrain.structure import LinearLayer, SigmoidLayer from sklearn.datasets import load_diabetes import pickle def loadData(): ''' Loads the data and prints some summa...
c962eccb4e729bfbb47964a68cd6a96a7fe3c0d7
antondelchev/Python-Basics
/Nested-Loops---More-Exercises/11. HappyCat Parking.py
521
3.796875
4
num_days = int(input()) num_hours = int(input()) price_total = 0 total_hours = 0 for i in range(1, num_days + 1): daily_price = 0 for j in range(1, num_hours + 1): if i % 2 == 0 and j % 2 != 0: daily_price += 2.5 elif i % 2 != 0 and j % 2 == 0: daily_price += 1.25 ...
0c629a1225af1897acdd0015c42b0dd452df683f
antondelchev/Python-Basics
/Conditional-Statements---More-Exercises/04. Transport Price.py
330
3.8125
4
distance_km = int(input()) day_or_night = input() price = 0 if 20 <= distance_km < 100: price = 0.09 * distance_km elif distance_km >= 100: price = 0.06 * distance_km elif day_or_night == "day": price = 0.7 + distance_km * 0.79 elif day_or_night == "night": price = 0.7 + distance_km * 0.9 print(f"{pri...
3a59ad61f105065973003d6b8751cc5b84520f17
antondelchev/Python-Basics
/Nested-Conditional-Statements---More-Exercises/06. Truck Driver.py
737
4
4
season = input() km_per_month = float(input()) income_per_km = 0 if km_per_month <= 5000: if season == "Spring" or season == "Autumn": income_per_km = 0.75 * km_per_month elif season == "Summer": income_per_km = 0.9 * km_per_month elif season == "Winter": income_per_km = 1.05 * km_...
f2b658c2ddaadeb03368607989aed88b9279d99d
antondelchev/Python-Basics
/Drawing-Figures-with-Loops---More-Exercises/05. Square Frame.py
430
4.0625
4
n = int(input()) for rows in range(1, n + 1): for columns in range(1, n + 1): if rows == 1 or rows == n: print("+", end=" ") for i in range(1, n - 1): print("-", end=" ") print("+") break else: print("|", end=" ") ...
f13297e99ff3632c7cf4c3d9a6cc28a5ccbc6296
antondelchev/Python-Basics
/Conditional-Statements-Advanced---Exercise/07. Hotel Room.py
829
3.890625
4
month = input() nights_number = int(input()) studio_price = 0 apartment_price = 0 if month == "May" or month == "October": studio_price = 50 * nights_number apartment_price = 65 * nights_number if 7 < nights_number <= 14: studio_price = studio_price * 0.95 elif nights_number > 14: stud...
3d66b0c6593a83435e0df5d2e132e8b504136e6c
antondelchev/Python-Basics
/Conditional-Statements-Advanced---Exercise/06. Operations Between Numbers.py
877
4.21875
4
number_one = int(input()) number_two = int(input()) action = input() result = 0 if action == "+" or action == "-" or action == "*": if action == "+": result = number_one + number_two elif action == "-": result = number_one - number_two elif action == "*": result = number_one * numbe...
ebbfa306172277f0d4762f04f755a26bcf0215f5
antondelchev/Python-Basics
/Drawing-Figures-with-Loops---More-Exercises/07. Christmas Tree.py
937
3.890625
4
n = int(input()) row_count = 0 done = False for rows in range(0, n + 2): for columns in range(1, 3 * n + 1): if row_count == 0: for i in range(1, n + 1): print(" ", end="") print(" | ") row_count += 1 break if 0 < row_count < n: ...
95ac6fa01a845c7a916f4ffaecbd99086902a247
antondelchev/Python-Basics
/Nested-Conditional-Statements---More-Exercises/02. Bike Race.py
1,356
3.859375
4
juniors_number = int(input()) seniors_number = int(input()) race_type = input() total_participants = juniors_number + seniors_number participation_fee_total_juniors = 0 participation_fee_total_seniors = 0 if juniors_number > 0: if race_type == "trail": participation_fee_total_juniors = 5.5 * juniors_numbe...
2fb03fcb40ce9720c021c68d55360ad7d81fad75
antondelchev/Python-Basics
/Conditional-Statements---Exercise/08. Scholarship.py
1,264
3.828125
4
import math income = float(input()) grade_score = float(input()) min_wage = float(input()) scholarship = 0 social_scholarship = 0 if grade_score <= 4.5: print("You cannot get a scholarship!") if income > min_wage and grade_score < 5.5: print("You cannot get a scholarship!") if income > min_wage and grade_sc...
36abc70372fdd83a075d24d6ee5019a032327b91
antondelchev/Python-Basics
/Conditional-Statements---More-Exercises/02. Sleepy Tom Cat.py
715
3.71875
4
holidays_per_year = int(input()) play_time_mins_yearly = 30000 work_days_play_mins = 63 holidays_play_mins = 127 total_playtime = holidays_per_year * holidays_play_mins + (365 - holidays_per_year)*work_days_play_mins if total_playtime > play_time_mins_yearly: difference = total_playtime - play_time_mins_yearly ...
158e61502f26b72fceb12201a851615f588fc35e
antondelchev/Python-Basics
/Nested-Conditional-Statements---More-Exercises/01. Match Tickets.py
829
3.875
4
budget = float(input()) category = input() men_in_group = int(input()) transport_cost = 0 tickets_cost = 0 if 1 <= men_in_group <= 4: transport_cost = 0.75 * budget elif 5 <= men_in_group <= 9: transport_cost = 0.6 * budget elif 10 <= men_in_group <= 24: transport_cost = 0.5 * budget elif 25 <= men_in_gro...
d4be4020b35ec1bc9066f20dce5a31a24ebd48c6
antondelchev/Python-Basics
/Nested-Loops---Exercise/05. Password Generator.py
664
3.703125
4
number_one = int(input()) number_two = int(input()) for first in range(1, number_one + 1): first_symbol = first for second in range(1, number_one + 1): second_symbol = second for third in range(97, 97 + number_two): third_symbol = chr(third) for fourth in range(97, 97 + ...
8f57617cf919dbe02d1f5c6a93d2eed4d143d585
antondelchev/Python-Basics
/While-Loop---Lab/09. Moving.py
569
4
4
space_width = int(input()) space_length = int(input()) space_height = int(input()) command = input() volume_of_room = space_width * space_length * space_height volume_of_box = 1 volume_taken = 0 while command != "Done": number_of_boxes = int(command) volume_taken += number_of_boxes if volume_taken >= vol...
73e4a96708628c9940c68cc51cc483ce76704bbf
SayoneeDassani/Python-for-everyone-coursera
/01.Programming for Everybody/week_5/assignment3_1.py
150
3.890625
4
hrs = input("Enter Hours:") h = float(hrs) rate = input("Enter Rate:") r = float(rate) if(h<=40): p=h*r else: p=((h-40)*1.5*r)+(40*r) print(p)
44ea0776a899365e662602923d481b1d5254d203
SayoneeDassani/Python-for-everyone-coursera
/01.Programming for Everybody/week_6/assignment4_6.py
213
3.734375
4
def computepay(h,r): if h>40: return(((h-40)*1.5*r)+(40*r)) else: return h*r hrs = input("Enter Hours:") h=float(hrs) rate= input("Enter Rate:") r=float(rate) p = computepay(h,r) print("Pay",p)
416f6a7d44338a086a0f0027004350ba6378dd6d
B3B3K/Calculator-4-v1.0
/4calc.py
509
3.75
4
print('{}\n{}\n{}\n{}'.format("1++toplama ", "2--çıkarma", "3**çarpma ", "4//bölme")) i = int(input(">-1-2-3-4-< sayılarından birini giriniz ")) s = int(input("1. sayıyı giriniz: ")) d = int(input("2. sayıyı giriniz: ")) if i > 4: print(">-1-2-3-4-< sayılarından birini giriniz", i) elif i == 1: print("to...
85d09d7da7622047269ca088a588d87e3baae6ba
roniphire/compVis
/basic_drawing.py
918
3.53125
4
""" Draw function basic. """ import numpy as np import cv2 as cv # Create a black image using np array operation IMG = np.zeros((512, 512, 3), np.uint8) # [base, start px, finish px, bgr color, thickness] cv.line(IMG, (0, 0), (511, 511), (255, 0, 0), 5) cv.rectangle(IMG, (384, 0), (510, 128), (0, 255, 0), 3) # [coo...